@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.cjs CHANGED
@@ -23,192 +23,576 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  //#endregion
24
24
  let __codemation_core = require("@codemation/core");
25
25
  __codemation_core = __toESM(__codemation_core);
26
- let __langchain_openai = require("@langchain/openai");
27
- __langchain_openai = __toESM(__langchain_openai);
28
- let __langchain_core_messages = require("@langchain/core/messages");
29
- __langchain_core_messages = __toESM(__langchain_core_messages);
30
- let __langchain_core_utils_types = require("@langchain/core/utils/types");
31
- __langchain_core_utils_types = __toESM(__langchain_core_utils_types);
32
- let __langchain_core_utils_json_schema = require("@langchain/core/utils/json_schema");
33
- __langchain_core_utils_json_schema = __toESM(__langchain_core_utils_json_schema);
34
- let __langchain_core_tools = require("@langchain/core/tools");
35
- __langchain_core_tools = __toESM(__langchain_core_tools);
26
+ let __ai_sdk_openai = require("@ai-sdk/openai");
27
+ __ai_sdk_openai = __toESM(__ai_sdk_openai);
36
28
  let __codemation_core_bootstrap = require("@codemation/core/bootstrap");
37
29
  __codemation_core_bootstrap = __toESM(__codemation_core_bootstrap);
30
+ let ai = require("ai");
31
+ ai = __toESM(ai);
32
+ let croner = require("croner");
33
+ croner = __toESM(croner);
38
34
 
39
- //#region \0@oxc-project+runtime@0.95.0/helpers/decorate.js
40
- function __decorate(decorators, target, key, desc) {
41
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
42
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
43
- 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;
44
- return c > 3 && r && Object.defineProperty(target, key, r), r;
45
- }
35
+ //#region src/credentials/ApiKeyCredentialType.ts
36
+ /**
37
+ * API key credential that injects a key either as an HTTP header or a query parameter.
38
+ */
39
+ const apiKeyCredentialType = (0, __codemation_core.defineCredential)({
40
+ key: "core-nodes.api-key",
41
+ label: "API Key",
42
+ description: "Authenticates requests by injecting an API key into a header or query parameter.",
43
+ public: {
44
+ placement: {
45
+ label: "Placement",
46
+ type: "string",
47
+ helpText: "Where to send the key: \"header\" (default) or \"query\".",
48
+ placeholder: "header"
49
+ },
50
+ name: {
51
+ label: "Parameter name",
52
+ type: "string",
53
+ helpText: "Header or query param name. Defaults to \"X-API-Key\" for headers, \"api_key\" for query.",
54
+ placeholder: "X-API-Key"
55
+ }
56
+ },
57
+ secret: { apiKey: {
58
+ label: "API Key",
59
+ type: "password",
60
+ required: true,
61
+ helpText: "The secret API key value."
62
+ } },
63
+ async createSession(args) {
64
+ const apiKey = String(args.material.apiKey ?? "");
65
+ if (!apiKey) throw new Error("API key credential material is incomplete: apiKey is required.");
66
+ const isQuery = String(args.publicConfig.placement ?? "header").toLowerCase() === "query";
67
+ const defaultName = isQuery ? "api_key" : "X-API-Key";
68
+ const paramName = String(args.publicConfig.name ?? "").trim() || defaultName;
69
+ return { applyToRequest: (_spec) => {
70
+ if (isQuery) return { query: { [paramName]: apiKey } };
71
+ return { headers: { [paramName]: apiKey } };
72
+ } };
73
+ },
74
+ async test(args) {
75
+ const apiKey = String(args.material.apiKey ?? "");
76
+ return {
77
+ status: apiKey.length > 0 ? "healthy" : "failing",
78
+ message: apiKey.length > 0 ? "API key is configured." : "API key is missing.",
79
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
80
+ };
81
+ }
82
+ });
46
83
 
47
84
  //#endregion
48
- //#region src/chatModels/OpenAIChatModelFactory.ts
49
- let OpenAIChatModelFactory = class OpenAIChatModelFactory$1 {
85
+ //#region src/credentials/BasicAuthCredentialType.ts
86
+ /**
87
+ * HTTP Basic authentication credential.
88
+ * Session sets `Authorization: Basic <base64(username:password)>`.
89
+ */
90
+ const basicAuthCredentialType = (0, __codemation_core.defineCredential)({
91
+ key: "core-nodes.basic-auth",
92
+ label: "Basic Auth",
93
+ description: "Authenticates requests using HTTP Basic Authentication (username + password).",
94
+ public: { username: {
95
+ label: "Username",
96
+ type: "string",
97
+ required: true,
98
+ helpText: "The username for HTTP Basic Authentication."
99
+ } },
100
+ secret: { password: {
101
+ label: "Password",
102
+ type: "password",
103
+ required: true,
104
+ helpText: "The password for HTTP Basic Authentication."
105
+ } },
106
+ async createSession(args) {
107
+ const username = String(args.publicConfig.username ?? "");
108
+ const password = String(args.material.password ?? "");
109
+ if (!username) throw new Error("Basic Auth credential is incomplete: username is required.");
110
+ const encoded = Buffer.from(`${username}:${password}`).toString("base64");
111
+ return { applyToRequest: (_spec) => ({ headers: { authorization: `Basic ${encoded}` } }) };
112
+ },
113
+ async test(args) {
114
+ const username = String(args.publicConfig.username ?? "");
115
+ const password = String(args.material.password ?? "");
116
+ const ok = username.length > 0 && password.length > 0;
117
+ return {
118
+ status: ok ? "healthy" : "failing",
119
+ message: ok ? "Basic Auth credentials are configured." : "Username or password is missing.",
120
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
121
+ };
122
+ }
123
+ });
124
+
125
+ //#endregion
126
+ //#region src/credentials/BearerTokenCredentialType.ts
127
+ /**
128
+ * Simple Bearer token credential.
129
+ * Session sets `Authorization: Bearer <token>` on every request.
130
+ */
131
+ const bearerTokenCredentialType = (0, __codemation_core.defineCredential)({
132
+ key: "core-nodes.bearer-token",
133
+ label: "Bearer Token",
134
+ description: "Authenticates requests using a static Bearer token in the Authorization header.",
135
+ public: {},
136
+ secret: { token: {
137
+ label: "Token",
138
+ type: "password",
139
+ required: true,
140
+ helpText: "The Bearer token to include in the Authorization header."
141
+ } },
142
+ async createSession(args) {
143
+ const token = String(args.material.token ?? "");
144
+ if (!token) throw new Error("Bearer token credential material is incomplete: token is required.");
145
+ return { applyToRequest: (_spec) => ({ headers: { authorization: `Bearer ${token}` } }) };
146
+ },
147
+ async test(args) {
148
+ const token = String(args.material.token ?? "");
149
+ return {
150
+ status: token.length > 0 ? "healthy" : "failing",
151
+ message: token.length > 0 ? "Bearer token is configured." : "Token is missing.",
152
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
153
+ };
154
+ }
155
+ });
156
+
157
+ //#endregion
158
+ //#region src/credentials/OAuth2TokenExchangeFactory.ts
159
+ var OAuth2TokenExchangeFactory = class {
50
160
  async create(args) {
51
- const session = await args.ctx.getCredential(args.config.credentialSlotKey);
52
- return new __langchain_openai.ChatOpenAI({
53
- apiKey: session.apiKey,
54
- model: args.config.model,
55
- temperature: args.config.options?.temperature,
56
- maxTokens: args.config.options?.maxTokens,
57
- configuration: session.baseUrl ? { baseURL: session.baseUrl } : void 0
161
+ const body = new URLSearchParams({
162
+ grant_type: "client_credentials",
163
+ client_id: args.clientId
58
164
  });
165
+ if (args.scopes) body.set("scope", args.scopes);
166
+ if (args.audience) body.set("audience", args.audience);
167
+ const encoded = Buffer.from(`${args.clientId}:${args.clientSecret}`).toString("base64");
168
+ const response = await globalThis.fetch(args.tokenUrl, {
169
+ method: "POST",
170
+ headers: {
171
+ "content-type": "application/x-www-form-urlencoded",
172
+ authorization: `Basic ${encoded}`
173
+ },
174
+ body: body.toString()
175
+ });
176
+ if (!response.ok) {
177
+ const text = await response.text().catch(() => "");
178
+ throw new Error(`Token exchange failed (${response.status} ${response.statusText}): ${text}`);
179
+ }
180
+ const json = await response.json();
181
+ const token = String(json["access_token"] ?? "");
182
+ if (!token) throw new Error("Token exchange response did not include an access_token.");
183
+ return token;
59
184
  }
60
185
  };
61
- OpenAIChatModelFactory = __decorate([(0, __codemation_core.chatModel)({ packageName: "@codemation/core-nodes" })], OpenAIChatModelFactory);
62
186
 
63
187
  //#endregion
64
- //#region src/chatModels/OpenAIStructuredOutputMethodFactory.ts
65
- var _OpenAIStructuredOutputMethodFactory;
66
- let OpenAIStructuredOutputMethodFactory = class OpenAIStructuredOutputMethodFactory$1 {
67
- static {
68
- _OpenAIStructuredOutputMethodFactory = this;
188
+ //#region src/credentials/OAuth2ClientCredentialsTypeFactory.ts
189
+ /**
190
+ * OAuth2 client-credentials flow credential.
191
+ *
192
+ * This is a machine-to-machine flow: no user redirect occurs. The session
193
+ * POSTs to the configured `tokenUrl` with `client_credentials` grant, caches
194
+ * the resulting access token for the duration of the session, and injects it
195
+ * as `Authorization: Bearer <token>` on each request.
196
+ *
197
+ * Token caching is per-session only (one createSession call = one token fetch
198
+ * at most). Cross-session caching would require host-level state and is out of
199
+ * scope here. Because the engine creates a fresh session per execution, a new
200
+ * token is fetched once per node activation.
201
+ *
202
+ * NOTE: `auth` is intentionally omitted from the definition. The OAuth2
203
+ * `auth: { kind: "oauth2" }` shape signals an authorization-code / user-redirect
204
+ * flow; using it here would cause the host UI to render an OAuth consent button
205
+ * that goes nowhere. Client-credentials is a purely server-side flow.
206
+ */
207
+ const oauth2ClientCredentialsType = (0, __codemation_core.defineCredential)({
208
+ key: "core-nodes.oauth2-client-credentials",
209
+ label: "OAuth2 Client Credentials",
210
+ description: "Machine-to-machine OAuth2 using the client_credentials grant. Exchanges client ID and secret for a bearer token before each workflow execution.",
211
+ public: {
212
+ tokenUrl: {
213
+ label: "Token URL",
214
+ type: "string",
215
+ required: true,
216
+ helpText: "The token endpoint URL, e.g. https://auth.example.com/oauth/token."
217
+ },
218
+ scopes: {
219
+ label: "Scopes",
220
+ type: "string",
221
+ helpText: "Space-separated list of OAuth2 scopes to request (optional)."
222
+ },
223
+ audience: {
224
+ label: "Audience",
225
+ type: "string",
226
+ helpText: "Optional audience parameter sent to the token endpoint.",
227
+ visibility: "advanced"
228
+ }
229
+ },
230
+ secret: {
231
+ clientId: {
232
+ label: "Client ID",
233
+ type: "string",
234
+ required: true
235
+ },
236
+ clientSecret: {
237
+ label: "Client Secret",
238
+ type: "password",
239
+ required: true
240
+ }
241
+ },
242
+ async createSession(args) {
243
+ const tokenUrl = String(args.publicConfig.tokenUrl ?? "");
244
+ const clientId = String(args.material.clientId ?? "");
245
+ const clientSecret = String(args.material.clientSecret ?? "");
246
+ if (!tokenUrl || !clientId || !clientSecret) throw new Error("OAuth2 client credentials are incomplete: tokenUrl, clientId, and clientSecret are required.");
247
+ const accessToken = await new OAuth2TokenExchangeFactory().create({
248
+ tokenUrl,
249
+ clientId,
250
+ clientSecret,
251
+ scopes: String(args.publicConfig.scopes ?? ""),
252
+ audience: String(args.publicConfig.audience ?? "")
253
+ });
254
+ return { applyToRequest: (_spec) => ({ headers: { authorization: `Bearer ${accessToken}` } }) };
255
+ },
256
+ async test(args) {
257
+ const tokenUrl = String(args.publicConfig.tokenUrl ?? "");
258
+ const clientId = String(args.material.clientId ?? "");
259
+ const clientSecret = String(args.material.clientSecret ?? "");
260
+ if (!tokenUrl || !clientId || !clientSecret) return {
261
+ status: "failing",
262
+ message: "tokenUrl, clientId, and clientSecret are all required.",
263
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
264
+ };
265
+ try {
266
+ await new OAuth2TokenExchangeFactory().create({
267
+ tokenUrl,
268
+ clientId,
269
+ clientSecret,
270
+ scopes: String(args.publicConfig.scopes ?? ""),
271
+ audience: String(args.publicConfig.audience ?? "")
272
+ });
273
+ return {
274
+ status: "healthy",
275
+ message: "Token exchange succeeded.",
276
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
277
+ };
278
+ } catch (error) {
279
+ return {
280
+ status: "failing",
281
+ message: error instanceof Error ? error.message : String(error),
282
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
283
+ };
284
+ }
69
285
  }
70
- static isoDatePattern = /^\d{4}-\d{2}-\d{2}$/;
71
- create(chatModelConfig) {
72
- if (chatModelConfig.type !== OpenAIChatModelFactory) return;
73
- const model = this.readModelName(chatModelConfig);
74
- if (!model) return {
75
- method: "functionCalling",
76
- strict: true
286
+ });
287
+
288
+ //#endregion
289
+ //#region src/http/HttpRequestExecutor.ts
290
+ /**
291
+ * Executes a single HTTP request described by {@link HttpRequestSpec}.
292
+ *
293
+ * - Credential sessions provide header/query deltas via `applyToRequest`.
294
+ * - Body encoding is delegated to {@link HttpBodyBuilder}.
295
+ * - URL query merging is delegated to {@link HttpUrlBuilder}.
296
+ * - Binary response bodies: when `download.mode` triggers binary attach, the
297
+ * `bodyBinaryName` field is set in the result but the body is NOT read here.
298
+ * Callers that need binary attachment should use `buildRequest` to get the
299
+ * resolved URL + init and make the fetch + binary attach themselves.
300
+ *
301
+ * Collaborators (`fetch`, body builder, url builder) are injected so callers
302
+ * own construction at composition roots and tests can supply deterministic stubs.
303
+ */
304
+ var HttpRequestExecutor = class {
305
+ constructor(fetchFn, bodyBuilder, urlBuilder) {
306
+ this.fetchFn = fetchFn;
307
+ this.bodyBuilder = bodyBuilder;
308
+ this.urlBuilder = urlBuilder;
309
+ }
310
+ /**
311
+ * Builds the fetch init (headers, query, body) from the spec + credential delta,
312
+ * returning both the resolved URL and the RequestInit so callers can make the
313
+ * actual fetch call themselves (useful for streaming / binary attach).
314
+ */
315
+ async buildRequest(spec, item) {
316
+ const credentialDelta = spec.credential?.applyToRequest(spec) ?? {};
317
+ const mergedHeaders = {
318
+ ...spec.headers ?? {},
319
+ ...credentialDelta.headers ?? {}
320
+ };
321
+ const mergedQuery = {
322
+ ...spec.query ?? {},
323
+ ...credentialDelta.query ?? {}
77
324
  };
325
+ const encodedBody = await this.bodyBuilder.build(spec.body, item, spec.ctx);
326
+ const hasExplicitContentType = Object.keys(mergedHeaders).some((k) => k.toLowerCase() === "content-type");
327
+ if (encodedBody && encodedBody.contentType && !hasExplicitContentType) mergedHeaders["content-type"] = encodedBody.contentType;
328
+ return {
329
+ url: this.urlBuilder.build(spec.url, mergedQuery),
330
+ init: {
331
+ method: spec.method,
332
+ headers: mergedHeaders,
333
+ ...encodedBody ? { body: encodedBody.body } : {}
334
+ }
335
+ };
336
+ }
337
+ /**
338
+ * Executes an HTTP request and returns parsed result.
339
+ * For binary downloads (when `shouldAttachBody` is true), the body is NOT consumed
340
+ * and callers must call `ctx.binary.attach` directly using the resolved URL + init
341
+ * (available via `buildRequest`).
342
+ */
343
+ async execute(spec, item) {
344
+ const { url: resolvedUrl, init } = await this.buildRequest(spec, item);
345
+ const response = await this.fetchFn(resolvedUrl, init);
346
+ const responseHeaders = this.readHeaders(response.headers);
347
+ const mimeType = this.resolveMimeType(responseHeaders);
348
+ const downloadMode = spec.download?.mode ?? "auto";
349
+ const binaryName = spec.download?.binaryName ?? "body";
350
+ const shouldDownload = this.shouldAttachBody(downloadMode, mimeType);
351
+ const isJson = this.isJsonMimeType(mimeType);
352
+ let json;
353
+ let text;
354
+ let bodyBinaryName;
355
+ if (shouldDownload) bodyBinaryName = binaryName;
356
+ else if (isJson) try {
357
+ json = await response.json();
358
+ } catch {
359
+ text = await response.text();
360
+ }
361
+ else text = await response.text();
78
362
  return {
79
- method: this.supportsJsonSchema(model) ? "jsonSchema" : "functionCalling",
80
- strict: true
363
+ url: resolvedUrl,
364
+ method: spec.method.toUpperCase(),
365
+ status: response.status,
366
+ ok: response.ok,
367
+ statusText: response.statusText,
368
+ mimeType,
369
+ headers: responseHeaders,
370
+ ...json !== void 0 ? { json } : {},
371
+ ...text !== void 0 ? { text } : {},
372
+ ...bodyBinaryName !== void 0 ? { bodyBinaryName } : {}
81
373
  };
82
374
  }
83
- readModelName(chatModelConfig) {
84
- const candidate = chatModelConfig;
85
- return typeof candidate.model === "string" ? candidate.model : void 0;
375
+ readHeaders(headers) {
376
+ const values = {};
377
+ headers.forEach((value, key) => {
378
+ values[key] = value;
379
+ });
380
+ return values;
381
+ }
382
+ resolveMimeType(headers) {
383
+ const contentType = headers["content-type"];
384
+ if (!contentType) return "application/octet-stream";
385
+ return contentType.split(";")[0]?.trim() || "application/octet-stream";
86
386
  }
87
- supportsJsonSchema(model) {
88
- if (model === "gpt-4o" || model === "gpt-4o-mini") return true;
89
- return this.supportsSnapshotAtOrAfter(model, "gpt-4o-", "2024-08-06") || this.supportsSnapshotAtOrAfter(model, "gpt-4o-mini-", "2024-07-18");
387
+ isJsonMimeType(mimeType) {
388
+ return mimeType === "application/json" || mimeType.endsWith("+json");
90
389
  }
91
- supportsSnapshotAtOrAfter(model, prefix, minimumSnapshotDate) {
92
- if (!model.startsWith(prefix)) return false;
93
- const snapshotDate = model.slice(prefix.length);
94
- return _OpenAIStructuredOutputMethodFactory.isoDatePattern.test(snapshotDate) && snapshotDate >= minimumSnapshotDate;
390
+ shouldAttachBody(mode, mimeType) {
391
+ if (mode === "always") return true;
392
+ if (mode === "never") return false;
393
+ return mimeType.startsWith("image/") || mimeType.startsWith("audio/") || mimeType.startsWith("video/") || mimeType === "application/pdf";
95
394
  }
96
395
  };
97
- OpenAIStructuredOutputMethodFactory = _OpenAIStructuredOutputMethodFactory = __decorate([(0, __codemation_core.injectable)()], OpenAIStructuredOutputMethodFactory);
98
396
 
99
397
  //#endregion
100
- //#region src/chatModels/openAiChatModelConfig.ts
101
- var OpenAIChatModelConfig = class {
102
- type = OpenAIChatModelFactory;
103
- presentation;
104
- provider = "openai";
105
- modelName;
106
- constructor(name, model, credentialSlotKey = "openai", presentationIn, options) {
107
- this.name = name;
108
- this.model = model;
109
- this.credentialSlotKey = credentialSlotKey;
110
- this.options = options;
111
- this.modelName = model;
112
- this.presentation = presentationIn ?? {
113
- icon: "builtin:openai",
114
- label: name
398
+ //#region src/http/HttpBodyBuilder.ts
399
+ /**
400
+ * Builds a fetch-compatible `BodyInit` + Content-Type pair from an {@link HttpBodySpec}.
401
+ * Multipart binaries are read from `item.binary` via `ctx.binary.openReadStream`.
402
+ */
403
+ var HttpBodyBuilder = class {
404
+ async build(spec, item, ctx) {
405
+ if (!spec || spec.kind === "none") return;
406
+ if (spec.kind === "json") return {
407
+ body: JSON.stringify(spec.data),
408
+ contentType: "application/json"
115
409
  };
410
+ if (spec.kind === "form") {
411
+ const params = new URLSearchParams();
412
+ for (const [key, value] of Object.entries(spec.data)) params.append(key, value);
413
+ return {
414
+ body: params.toString(),
415
+ contentType: "application/x-www-form-urlencoded"
416
+ };
417
+ }
418
+ if (spec.kind === "multipart") {
419
+ const formData = new FormData();
420
+ for (const [key, value] of Object.entries(spec.fields)) formData.append(key, value);
421
+ if (spec.binaries) for (const [fieldName, binaryRef] of Object.entries(spec.binaries)) {
422
+ const attachment = item.binary?.[binaryRef];
423
+ if (attachment) {
424
+ const readResult = await ctx.binary.openReadStream(attachment);
425
+ if (readResult) {
426
+ const merged = await this.readStreamToBuffer(readResult.body);
427
+ const blob = new Blob([merged], { type: attachment.mimeType });
428
+ formData.append(fieldName, blob, attachment.filename ?? binaryRef);
429
+ }
430
+ }
431
+ }
432
+ return {
433
+ body: formData,
434
+ contentType: ""
435
+ };
436
+ }
437
+ if (spec.kind === "binary") {
438
+ const attachment = item.binary?.[spec.slot];
439
+ 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.`);
440
+ const readResult = await ctx.binary.openReadStream(attachment);
441
+ if (!readResult) throw new Error(`HttpRequest bodyFormat "binary": could not open read stream for slot "${spec.slot}".`);
442
+ return {
443
+ body: readResult.body,
444
+ contentType: attachment.mimeType
445
+ };
446
+ }
116
447
  }
117
- getCredentialRequirements() {
118
- return [{
119
- slotKey: this.credentialSlotKey,
120
- label: "OpenAI API key",
121
- acceptedTypes: ["openai.apiKey"]
122
- }];
448
+ async readStreamToBuffer(stream) {
449
+ const reader = stream.getReader();
450
+ const chunks = [];
451
+ let done = false;
452
+ while (!done) {
453
+ const result = await reader.read();
454
+ done = result.done;
455
+ if (result.value) chunks.push(result.value);
456
+ }
457
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
458
+ const merged = new Uint8Array(new ArrayBuffer(totalLength));
459
+ let offset = 0;
460
+ for (const chunk of chunks) {
461
+ merged.set(chunk, offset);
462
+ offset += chunk.length;
463
+ }
464
+ return merged;
123
465
  }
124
466
  };
125
467
 
126
468
  //#endregion
127
- //#region src/chatModels/OpenAiChatModelPresetsFactory.ts
469
+ //#region src/http/HttpUrlBuilder.ts
128
470
  /**
129
- * Default OpenAI chat model configs for scaffolds and demos (icon + label match {@link OpenAIChatModelConfig} defaults).
130
- * Prefer importing {@link openAiChatModelPresets} from here or from the consumer template re-export
131
- * instead of repeating {@link OpenAIChatModelConfig} construction in app workflows.
471
+ * Merges query parameters into a base URL.
472
+ * Handles both scalar and array values, and preserves any existing params.
132
473
  */
133
- var OpenAiChatModelPresets = class {
134
- demoGpt4oMini = new OpenAIChatModelConfig("OpenAI", "gpt-4o-mini");
135
- demoGpt41 = new OpenAIChatModelConfig("OpenAI", "gpt-4.1");
474
+ var HttpUrlBuilder = class {
475
+ build(baseUrl, query) {
476
+ if (!query || Object.keys(query).length === 0) return baseUrl;
477
+ const parsed = new URL(baseUrl);
478
+ for (const [key, value] of Object.entries(query)) if (Array.isArray(value)) for (const entry of value) parsed.searchParams.append(key, entry);
479
+ else parsed.searchParams.append(key, value);
480
+ return parsed.toString();
481
+ }
136
482
  };
137
- const openAiChatModelPresets = new OpenAiChatModelPresets();
138
483
 
139
484
  //#endregion
140
- //#region src/nodes/AgentMessageFactory.ts
141
- var AgentMessageFactory = class {
142
- static createPromptMessages(messages) {
143
- return messages.map((message) => this.createPromptMessage(message));
144
- }
145
- static createSystemPrompt(systemMessage) {
146
- return new __langchain_core_messages.SystemMessage(systemMessage);
147
- }
148
- static createUserPrompt(prompt) {
149
- return new __langchain_core_messages.HumanMessage(prompt);
150
- }
151
- static createAssistantPrompt(prompt) {
152
- return new __langchain_core_messages.AIMessage(prompt);
153
- }
154
- static createToolMessage(toolCallId, content) {
155
- return new __langchain_core_messages.ToolMessage({
156
- tool_call_id: toolCallId,
157
- content
158
- });
159
- }
160
- static extractContent(message) {
161
- if (typeof message === "string") return message;
162
- if (!this.isRecord(message)) return String(message);
163
- const content = message.content;
164
- if (typeof content === "string") return content;
165
- if (Array.isArray(content)) return content.map((part) => {
166
- if (typeof part === "string") return part;
167
- if (this.isRecord(part) && typeof part.text === "string") return part.text;
168
- return JSON.stringify(part);
169
- }).join("\n");
170
- return JSON.stringify(content);
171
- }
172
- static extractToolCalls(message) {
173
- if (!this.isRecord(message)) return [];
174
- const toolCalls = message.tool_calls;
175
- if (!Array.isArray(toolCalls)) return [];
176
- return toolCalls.filter((toolCall) => this.isRecord(toolCall) && typeof toolCall.name === "string").map((toolCall) => ({
177
- id: typeof toolCall.id === "string" ? toolCall.id : void 0,
178
- name: toolCall.name,
179
- input: this.isRecord(toolCall) && "args" in toolCall ? toolCall.args : void 0
180
- }));
181
- }
182
- static isRecord(value) {
183
- return typeof value === "object" && value !== null;
184
- }
185
- static createPromptMessage(message) {
186
- if (message.role === "system") return this.createSystemPrompt(message.content);
187
- if (message.role === "assistant") return this.createAssistantPrompt(message.content);
188
- return this.createUserPrompt(message.content);
189
- }
190
- };
485
+ //#region src/authoring/defineRestNode.types.ts
486
+ /**
487
+ * Substitutes `{name}` placeholders in a path template using values from `params`.
488
+ */
489
+ function substitutePath(template, params) {
490
+ return template.replace(/\{([^}]+)}/g, (_match, key) => {
491
+ const value = params[key];
492
+ return value !== void 0 ? String(value) : `{${key}}`;
493
+ });
494
+ }
495
+ /**
496
+ * Declarative helper for creating thin API-wrapper nodes.
497
+ *
498
+ * Usage:
499
+ * ```ts
500
+ * export const postMessage = defineRestNode({
501
+ * key: "slack.post-message",
502
+ * title: "Send Slack message",
503
+ * icon: "si:slack",
504
+ * api: { baseUrl: "https://slack.com/api", path: "/chat.postMessage", method: "POST" },
505
+ * credentials: { auth: bearerTokenCredentialType },
506
+ * inputSchema: z.object({ channel: z.string(), text: z.string() }),
507
+ * request: ({ input }) => ({
508
+ * body: { kind: "json", data: { channel: input.channel, text: input.text } },
509
+ * }),
510
+ * response: ({ json }) => ({ messageTs: (json as any).ts }),
511
+ * });
512
+ * ```
513
+ *
514
+ * - `defineRestNode` is a thin wrapper over `defineNode`; it does not introduce a new runtime kind.
515
+ * - Credential sessions are resolved via the `credentials` binding map (same as `defineNode`).
516
+ * - Path `{placeholder}` substitution is applied from `input` keys before the request is made.
517
+ * - Non-2xx responses throw an `Error` by default (`errorPolicy: "throw"`).
518
+ */
519
+ function defineRestNode(options) {
520
+ const errorPolicy = options.errorPolicy ?? "throw";
521
+ return (0, __codemation_core.defineNode)({
522
+ key: options.key,
523
+ title: options.title,
524
+ description: options.description,
525
+ icon: options.icon,
526
+ credentials: options.credentials,
527
+ inputSchema: options.inputSchema,
528
+ async execute({ input, item, ctx }, { credentials }) {
529
+ const credentialSlot = options.credentials ? Object.keys(options.credentials)[0] : void 0;
530
+ const credential = credentialSlot ? await credentials[credentialSlot]?.() : void 0;
531
+ const inputRecord = input ?? {};
532
+ const requestShape = options.request ? await options.request({ input }) : {};
533
+ const pathParams = {
534
+ ...inputRecord,
535
+ ...requestShape.pathParams ?? {}
536
+ };
537
+ const resolvedPath = substitutePath(options.api.path, pathParams);
538
+ const resolvedUrl = `${options.api.baseUrl}${resolvedPath}`;
539
+ const result = await new HttpRequestExecutor(globalThis.fetch, new HttpBodyBuilder(), new HttpUrlBuilder()).execute({
540
+ url: resolvedUrl,
541
+ method: (options.api.method ?? "GET").toUpperCase(),
542
+ headers: requestShape.headers,
543
+ query: requestShape.query,
544
+ body: requestShape.body,
545
+ credential,
546
+ ctx
547
+ }, item);
548
+ if (errorPolicy === "throw" && !result.ok) throw new Error(`HTTP ${result.status} ${result.statusText} for ${result.method} ${result.url}`);
549
+ const responseCtx = {
550
+ status: result.status,
551
+ ok: result.ok,
552
+ statusText: result.statusText,
553
+ mimeType: result.mimeType,
554
+ headers: result.headers,
555
+ ...result.json !== void 0 ? { json: result.json } : {},
556
+ ...result.text !== void 0 ? { text: result.text } : {}
557
+ };
558
+ if (options.response) return await options.response({
559
+ ...responseCtx,
560
+ input
561
+ });
562
+ return { json: responseCtx };
563
+ }
564
+ });
565
+ }
191
566
 
192
567
  //#endregion
193
- //#region src/nodes/AgentOutputFactory.ts
194
- var AgentOutputFactory = class {
195
- static fromUnknown(value) {
196
- return { main: [{ json: value }] };
197
- }
198
- static replaceJson(item, value) {
568
+ //#region \0@oxc-project+runtime@0.95.0/helpers/decorate.js
569
+ function __decorate(decorators, target, key, desc) {
570
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
571
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
572
+ 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;
573
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
574
+ }
575
+
576
+ //#endregion
577
+ //#region src/chatModels/OpenAIChatModelFactory.ts
578
+ let OpenAIChatModelFactory = class OpenAIChatModelFactory$1 {
579
+ async create(args) {
580
+ const session = await args.ctx.getCredential(args.config.credentialSlotKey);
199
581
  return {
200
- ...item,
201
- json: value
582
+ languageModel: (0, __ai_sdk_openai.createOpenAI)({
583
+ apiKey: session.apiKey,
584
+ baseURL: session.baseUrl
585
+ }).chat(args.config.model),
586
+ modelName: args.config.model,
587
+ provider: "openai",
588
+ defaultCallOptions: {
589
+ maxOutputTokens: args.config.options?.maxTokens,
590
+ temperature: args.config.options?.temperature
591
+ }
202
592
  };
203
593
  }
204
- static fromAgentContent(content) {
205
- try {
206
- return JSON.parse(content);
207
- } catch {
208
- return { output: content };
209
- }
210
- }
211
594
  };
595
+ OpenAIChatModelFactory = __decorate([(0, __codemation_core.chatModel)({ packageName: "@codemation/core-nodes" })], OpenAIChatModelFactory);
212
596
 
213
597
  //#endregion
214
598
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js
@@ -299,10 +683,21 @@ function cleanRegex(source) {
299
683
  const end = source.endsWith("$") ? source.length - 1 : source.length;
300
684
  return source.slice(start, end);
301
685
  }
686
+ function floatSafeRemainder(val, step) {
687
+ const valDecCount = (val.toString().split(".")[1] || "").length;
688
+ const stepString = step.toString();
689
+ let stepDecCount = (stepString.split(".")[1] || "").length;
690
+ if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
691
+ const match = stepString.match(/\d?e-(\d?)/);
692
+ if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
693
+ }
694
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
695
+ return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
696
+ }
302
697
  const EVALUATING = Symbol("evaluating");
303
- function defineLazy(object, key, getter) {
698
+ function defineLazy(object$1, key, getter) {
304
699
  let value = void 0;
305
- Object.defineProperty(object, key, {
700
+ Object.defineProperty(object$1, key, {
306
701
  get() {
307
702
  if (value === EVALUATING) return;
308
703
  if (value === void 0) {
@@ -312,11 +707,19 @@ function defineLazy(object, key, getter) {
312
707
  return value;
313
708
  },
314
709
  set(v) {
315
- Object.defineProperty(object, key, { value: v });
710
+ Object.defineProperty(object$1, key, { value: v });
316
711
  },
317
712
  configurable: true
318
713
  });
319
714
  }
715
+ function assignProp(target, prop, value) {
716
+ Object.defineProperty(target, prop, {
717
+ value,
718
+ writable: true,
719
+ enumerable: true,
720
+ configurable: true
721
+ });
722
+ }
320
723
  function mergeDefs(...defs) {
321
724
  const mergedDescriptors = {};
322
725
  for (const def of defs) {
@@ -325,6 +728,12 @@ function mergeDefs(...defs) {
325
728
  }
326
729
  return Object.defineProperties({}, mergedDescriptors);
327
730
  }
731
+ function esc(str) {
732
+ return JSON.stringify(str);
733
+ }
734
+ function slugify(input) {
735
+ return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
736
+ }
328
737
  const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
329
738
  function isObject(data) {
330
739
  return typeof data === "object" && data !== null && !Array.isArray(data);
@@ -353,6 +762,14 @@ function shallowClone(o) {
353
762
  if (Array.isArray(o)) return [...o];
354
763
  return o;
355
764
  }
765
+ const propertyKeyTypes = new Set([
766
+ "string",
767
+ "number",
768
+ "symbol"
769
+ ]);
770
+ function escapeRegex(str) {
771
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
772
+ }
356
773
  function clone(inst, def, params) {
357
774
  const cl = new inst._zod.constr(def ?? inst._zod.def);
358
775
  if (!def || params?.parent) cl._zod.parent = inst;
@@ -373,6 +790,11 @@ function normalizeParams(_params) {
373
790
  };
374
791
  return params;
375
792
  }
793
+ function optionalKeys(shape) {
794
+ return Object.keys(shape).filter((k) => {
795
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
796
+ });
797
+ }
376
798
  const NUMBER_FORMAT_RANGES = {
377
799
  safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
378
800
  int32: [-2147483648, 2147483647],
@@ -380,6 +802,130 @@ const NUMBER_FORMAT_RANGES = {
380
802
  float32: [-34028234663852886e22, 34028234663852886e22],
381
803
  float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
382
804
  };
805
+ function pick(schema, mask) {
806
+ const currDef = schema._zod.def;
807
+ const checks = currDef.checks;
808
+ if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
809
+ return clone(schema, mergeDefs(schema._zod.def, {
810
+ get shape() {
811
+ const newShape = {};
812
+ for (const key in mask) {
813
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
814
+ if (!mask[key]) continue;
815
+ newShape[key] = currDef.shape[key];
816
+ }
817
+ assignProp(this, "shape", newShape);
818
+ return newShape;
819
+ },
820
+ checks: []
821
+ }));
822
+ }
823
+ function omit(schema, mask) {
824
+ const currDef = schema._zod.def;
825
+ const checks = currDef.checks;
826
+ if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
827
+ return clone(schema, mergeDefs(schema._zod.def, {
828
+ get shape() {
829
+ const newShape = { ...schema._zod.def.shape };
830
+ for (const key in mask) {
831
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
832
+ if (!mask[key]) continue;
833
+ delete newShape[key];
834
+ }
835
+ assignProp(this, "shape", newShape);
836
+ return newShape;
837
+ },
838
+ checks: []
839
+ }));
840
+ }
841
+ function extend(schema, shape) {
842
+ if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
843
+ const checks = schema._zod.def.checks;
844
+ if (checks && checks.length > 0) {
845
+ const existingShape = schema._zod.def.shape;
846
+ 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.");
847
+ }
848
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
849
+ const _shape = {
850
+ ...schema._zod.def.shape,
851
+ ...shape
852
+ };
853
+ assignProp(this, "shape", _shape);
854
+ return _shape;
855
+ } }));
856
+ }
857
+ function safeExtend(schema, shape) {
858
+ if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
859
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
860
+ const _shape = {
861
+ ...schema._zod.def.shape,
862
+ ...shape
863
+ };
864
+ assignProp(this, "shape", _shape);
865
+ return _shape;
866
+ } }));
867
+ }
868
+ function merge(a, b) {
869
+ return clone(a, mergeDefs(a._zod.def, {
870
+ get shape() {
871
+ const _shape = {
872
+ ...a._zod.def.shape,
873
+ ...b._zod.def.shape
874
+ };
875
+ assignProp(this, "shape", _shape);
876
+ return _shape;
877
+ },
878
+ get catchall() {
879
+ return b._zod.def.catchall;
880
+ },
881
+ checks: []
882
+ }));
883
+ }
884
+ function partial(Class, schema, mask) {
885
+ const checks = schema._zod.def.checks;
886
+ if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
887
+ return clone(schema, mergeDefs(schema._zod.def, {
888
+ get shape() {
889
+ const oldShape = schema._zod.def.shape;
890
+ const shape = { ...oldShape };
891
+ if (mask) for (const key in mask) {
892
+ if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
893
+ if (!mask[key]) continue;
894
+ shape[key] = Class ? new Class({
895
+ type: "optional",
896
+ innerType: oldShape[key]
897
+ }) : oldShape[key];
898
+ }
899
+ else for (const key in oldShape) shape[key] = Class ? new Class({
900
+ type: "optional",
901
+ innerType: oldShape[key]
902
+ }) : oldShape[key];
903
+ assignProp(this, "shape", shape);
904
+ return shape;
905
+ },
906
+ checks: []
907
+ }));
908
+ }
909
+ function required(Class, schema, mask) {
910
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
911
+ const oldShape = schema._zod.def.shape;
912
+ const shape = { ...oldShape };
913
+ if (mask) for (const key in mask) {
914
+ if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
915
+ if (!mask[key]) continue;
916
+ shape[key] = new Class({
917
+ type: "nonoptional",
918
+ innerType: oldShape[key]
919
+ });
920
+ }
921
+ else for (const key in oldShape) shape[key] = new Class({
922
+ type: "nonoptional",
923
+ innerType: oldShape[key]
924
+ });
925
+ assignProp(this, "shape", shape);
926
+ return shape;
927
+ } }));
928
+ }
383
929
  function aborted(x, startIndex = 0) {
384
930
  if (x.aborted === true) return true;
385
931
  for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
@@ -585,6 +1131,64 @@ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
585
1131
  };
586
1132
  const safeDecodeAsync$1 = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);
587
1133
 
1134
+ //#endregion
1135
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js
1136
+ const cuid = /^[cC][^\s-]{8,}$/;
1137
+ const cuid2 = /^[0-9a-z]+$/;
1138
+ const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
1139
+ const xid = /^[0-9a-vA-V]{20}$/;
1140
+ const ksuid = /^[A-Za-z0-9]{27}$/;
1141
+ const nanoid = /^[a-zA-Z0-9_-]{21}$/;
1142
+ /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
1143
+ 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)?)?)$/;
1144
+ /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
1145
+ 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})$/;
1146
+ /** Returns a regex for validating an RFC 9562/4122 UUID.
1147
+ *
1148
+ * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
1149
+ const uuid = (version$1) => {
1150
+ 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)$/;
1151
+ 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})$`);
1152
+ };
1153
+ /** Practical email validation */
1154
+ const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
1155
+ const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1156
+ function emoji() {
1157
+ return new RegExp(_emoji$1, "u");
1158
+ }
1159
+ 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])$/;
1160
+ 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}|:))$/;
1161
+ 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])$/;
1162
+ 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])$/;
1163
+ const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
1164
+ const base64url = /^[A-Za-z0-9_-]*$/;
1165
+ const e164 = /^\+[1-9]\d{6,14}$/;
1166
+ 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])))`;
1167
+ const date$1 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
1168
+ function timeSource(args) {
1169
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
1170
+ 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+)?)?`;
1171
+ }
1172
+ function time$1(args) {
1173
+ return /* @__PURE__ */ new RegExp(`^${timeSource(args)}$`);
1174
+ }
1175
+ function datetime$1(args) {
1176
+ const time$2 = timeSource({ precision: args.precision });
1177
+ const opts = ["Z"];
1178
+ if (args.local) opts.push("");
1179
+ if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
1180
+ const timeRegex = `${time$2}(?:${opts.join("|")})`;
1181
+ return /* @__PURE__ */ new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1182
+ }
1183
+ const string$1 = (params) => {
1184
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
1185
+ return /* @__PURE__ */ new RegExp(`^${regex}$`);
1186
+ };
1187
+ const integer = /^-?\d+$/;
1188
+ const number$1 = /^-?\d+(?:\.\d+)?$/;
1189
+ const lowercase = /^[^A-Z]*$/;
1190
+ const uppercase = /^[^a-z]*$/;
1191
+
588
1192
  //#endregion
589
1193
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js
590
1194
  const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
@@ -593,25 +1197,164 @@ const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
593
1197
  inst._zod.def = def;
594
1198
  (_a$1 = inst._zod).onattach ?? (_a$1.onattach = []);
595
1199
  });
596
- const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
597
- var _a$1;
1200
+ const numericOriginMap = {
1201
+ number: "number",
1202
+ bigint: "bigint",
1203
+ object: "date"
1204
+ };
1205
+ const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
598
1206
  $ZodCheck.init(inst, def);
599
- (_a$1 = inst._zod.def).when ?? (_a$1.when = (payload) => {
600
- const val = payload.value;
601
- return !nullish(val) && val.length !== void 0;
602
- });
1207
+ const origin = numericOriginMap[typeof def.value];
603
1208
  inst._zod.onattach.push((inst$1) => {
604
- const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
605
- if (def.maximum < curr) inst$1._zod.bag.maximum = def.maximum;
1209
+ const bag = inst$1._zod.bag;
1210
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
1211
+ if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
1212
+ else bag.exclusiveMaximum = def.value;
606
1213
  });
607
1214
  inst._zod.check = (payload) => {
608
- const input = payload.value;
609
- if (input.length <= def.maximum) return;
610
- const origin = getLengthableOrigin(input);
1215
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
611
1216
  payload.issues.push({
612
1217
  origin,
613
1218
  code: "too_big",
614
- maximum: def.maximum,
1219
+ maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
1220
+ input: payload.value,
1221
+ inclusive: def.inclusive,
1222
+ inst,
1223
+ continue: !def.abort
1224
+ });
1225
+ };
1226
+ });
1227
+ const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
1228
+ $ZodCheck.init(inst, def);
1229
+ const origin = numericOriginMap[typeof def.value];
1230
+ inst._zod.onattach.push((inst$1) => {
1231
+ const bag = inst$1._zod.bag;
1232
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
1233
+ if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
1234
+ else bag.exclusiveMinimum = def.value;
1235
+ });
1236
+ inst._zod.check = (payload) => {
1237
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
1238
+ payload.issues.push({
1239
+ origin,
1240
+ code: "too_small",
1241
+ minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
1242
+ input: payload.value,
1243
+ inclusive: def.inclusive,
1244
+ inst,
1245
+ continue: !def.abort
1246
+ });
1247
+ };
1248
+ });
1249
+ const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
1250
+ $ZodCheck.init(inst, def);
1251
+ inst._zod.onattach.push((inst$1) => {
1252
+ var _a$1;
1253
+ (_a$1 = inst$1._zod.bag).multipleOf ?? (_a$1.multipleOf = def.value);
1254
+ });
1255
+ inst._zod.check = (payload) => {
1256
+ if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
1257
+ if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
1258
+ payload.issues.push({
1259
+ origin: typeof payload.value,
1260
+ code: "not_multiple_of",
1261
+ divisor: def.value,
1262
+ input: payload.value,
1263
+ inst,
1264
+ continue: !def.abort
1265
+ });
1266
+ };
1267
+ });
1268
+ const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
1269
+ $ZodCheck.init(inst, def);
1270
+ def.format = def.format || "float64";
1271
+ const isInt = def.format?.includes("int");
1272
+ const origin = isInt ? "int" : "number";
1273
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
1274
+ inst._zod.onattach.push((inst$1) => {
1275
+ const bag = inst$1._zod.bag;
1276
+ bag.format = def.format;
1277
+ bag.minimum = minimum;
1278
+ bag.maximum = maximum;
1279
+ if (isInt) bag.pattern = integer;
1280
+ });
1281
+ inst._zod.check = (payload) => {
1282
+ const input = payload.value;
1283
+ if (isInt) {
1284
+ if (!Number.isInteger(input)) {
1285
+ payload.issues.push({
1286
+ expected: origin,
1287
+ format: def.format,
1288
+ code: "invalid_type",
1289
+ continue: false,
1290
+ input,
1291
+ inst
1292
+ });
1293
+ return;
1294
+ }
1295
+ if (!Number.isSafeInteger(input)) {
1296
+ if (input > 0) payload.issues.push({
1297
+ input,
1298
+ code: "too_big",
1299
+ maximum: Number.MAX_SAFE_INTEGER,
1300
+ note: "Integers must be within the safe integer range.",
1301
+ inst,
1302
+ origin,
1303
+ inclusive: true,
1304
+ continue: !def.abort
1305
+ });
1306
+ else payload.issues.push({
1307
+ input,
1308
+ code: "too_small",
1309
+ minimum: Number.MIN_SAFE_INTEGER,
1310
+ note: "Integers must be within the safe integer range.",
1311
+ inst,
1312
+ origin,
1313
+ inclusive: true,
1314
+ continue: !def.abort
1315
+ });
1316
+ return;
1317
+ }
1318
+ }
1319
+ if (input < minimum) payload.issues.push({
1320
+ origin: "number",
1321
+ input,
1322
+ code: "too_small",
1323
+ minimum,
1324
+ inclusive: true,
1325
+ inst,
1326
+ continue: !def.abort
1327
+ });
1328
+ if (input > maximum) payload.issues.push({
1329
+ origin: "number",
1330
+ input,
1331
+ code: "too_big",
1332
+ maximum,
1333
+ inclusive: true,
1334
+ inst,
1335
+ continue: !def.abort
1336
+ });
1337
+ };
1338
+ });
1339
+ const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
1340
+ var _a$1;
1341
+ $ZodCheck.init(inst, def);
1342
+ (_a$1 = inst._zod.def).when ?? (_a$1.when = (payload) => {
1343
+ const val = payload.value;
1344
+ return !nullish(val) && val.length !== void 0;
1345
+ });
1346
+ inst._zod.onattach.push((inst$1) => {
1347
+ const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
1348
+ if (def.maximum < curr) inst$1._zod.bag.maximum = def.maximum;
1349
+ });
1350
+ inst._zod.check = (payload) => {
1351
+ const input = payload.value;
1352
+ if (input.length <= def.maximum) return;
1353
+ const origin = getLengthableOrigin(input);
1354
+ payload.issues.push({
1355
+ origin,
1356
+ code: "too_big",
1357
+ maximum: def.maximum,
615
1358
  inclusive: true,
616
1359
  input,
617
1360
  inst,
@@ -681,6 +1424,123 @@ const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEqual
681
1424
  });
682
1425
  };
683
1426
  });
1427
+ const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
1428
+ var _a$1, _b;
1429
+ $ZodCheck.init(inst, def);
1430
+ inst._zod.onattach.push((inst$1) => {
1431
+ const bag = inst$1._zod.bag;
1432
+ bag.format = def.format;
1433
+ if (def.pattern) {
1434
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1435
+ bag.patterns.add(def.pattern);
1436
+ }
1437
+ });
1438
+ if (def.pattern) (_a$1 = inst._zod).check ?? (_a$1.check = (payload) => {
1439
+ def.pattern.lastIndex = 0;
1440
+ if (def.pattern.test(payload.value)) return;
1441
+ payload.issues.push({
1442
+ origin: "string",
1443
+ code: "invalid_format",
1444
+ format: def.format,
1445
+ input: payload.value,
1446
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
1447
+ inst,
1448
+ continue: !def.abort
1449
+ });
1450
+ });
1451
+ else (_b = inst._zod).check ?? (_b.check = () => {});
1452
+ });
1453
+ const $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
1454
+ $ZodCheckStringFormat.init(inst, def);
1455
+ inst._zod.check = (payload) => {
1456
+ def.pattern.lastIndex = 0;
1457
+ if (def.pattern.test(payload.value)) return;
1458
+ payload.issues.push({
1459
+ origin: "string",
1460
+ code: "invalid_format",
1461
+ format: "regex",
1462
+ input: payload.value,
1463
+ pattern: def.pattern.toString(),
1464
+ inst,
1465
+ continue: !def.abort
1466
+ });
1467
+ };
1468
+ });
1469
+ const $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
1470
+ def.pattern ?? (def.pattern = lowercase);
1471
+ $ZodCheckStringFormat.init(inst, def);
1472
+ });
1473
+ const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
1474
+ def.pattern ?? (def.pattern = uppercase);
1475
+ $ZodCheckStringFormat.init(inst, def);
1476
+ });
1477
+ const $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
1478
+ $ZodCheck.init(inst, def);
1479
+ const escapedRegex = escapeRegex(def.includes);
1480
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
1481
+ def.pattern = pattern;
1482
+ inst._zod.onattach.push((inst$1) => {
1483
+ const bag = inst$1._zod.bag;
1484
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1485
+ bag.patterns.add(pattern);
1486
+ });
1487
+ inst._zod.check = (payload) => {
1488
+ if (payload.value.includes(def.includes, def.position)) return;
1489
+ payload.issues.push({
1490
+ origin: "string",
1491
+ code: "invalid_format",
1492
+ format: "includes",
1493
+ includes: def.includes,
1494
+ input: payload.value,
1495
+ inst,
1496
+ continue: !def.abort
1497
+ });
1498
+ };
1499
+ });
1500
+ const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
1501
+ $ZodCheck.init(inst, def);
1502
+ const pattern = /* @__PURE__ */ new RegExp(`^${escapeRegex(def.prefix)}.*`);
1503
+ def.pattern ?? (def.pattern = pattern);
1504
+ inst._zod.onattach.push((inst$1) => {
1505
+ const bag = inst$1._zod.bag;
1506
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1507
+ bag.patterns.add(pattern);
1508
+ });
1509
+ inst._zod.check = (payload) => {
1510
+ if (payload.value.startsWith(def.prefix)) return;
1511
+ payload.issues.push({
1512
+ origin: "string",
1513
+ code: "invalid_format",
1514
+ format: "starts_with",
1515
+ prefix: def.prefix,
1516
+ input: payload.value,
1517
+ inst,
1518
+ continue: !def.abort
1519
+ });
1520
+ };
1521
+ });
1522
+ const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
1523
+ $ZodCheck.init(inst, def);
1524
+ const pattern = /* @__PURE__ */ new RegExp(`.*${escapeRegex(def.suffix)}$`);
1525
+ def.pattern ?? (def.pattern = pattern);
1526
+ inst._zod.onattach.push((inst$1) => {
1527
+ const bag = inst$1._zod.bag;
1528
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1529
+ bag.patterns.add(pattern);
1530
+ });
1531
+ inst._zod.check = (payload) => {
1532
+ if (payload.value.endsWith(def.suffix)) return;
1533
+ payload.issues.push({
1534
+ origin: "string",
1535
+ code: "invalid_format",
1536
+ format: "ends_with",
1537
+ suffix: def.suffix,
1538
+ input: payload.value,
1539
+ inst,
1540
+ continue: !def.abort
1541
+ });
1542
+ };
1543
+ });
684
1544
  const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
685
1545
  $ZodCheck.init(inst, def);
686
1546
  inst._zod.check = (payload) => {
@@ -688,6 +1548,38 @@ const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (i
688
1548
  };
689
1549
  });
690
1550
 
1551
+ //#endregion
1552
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js
1553
+ var Doc = class {
1554
+ constructor(args = []) {
1555
+ this.content = [];
1556
+ this.indent = 0;
1557
+ if (this) this.args = args;
1558
+ }
1559
+ indented(fn) {
1560
+ this.indent += 1;
1561
+ fn(this);
1562
+ this.indent -= 1;
1563
+ }
1564
+ write(arg) {
1565
+ if (typeof arg === "function") {
1566
+ arg(this, { execution: "sync" });
1567
+ arg(this, { execution: "async" });
1568
+ return;
1569
+ }
1570
+ const lines = arg.split("\n").filter((x) => x);
1571
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
1572
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
1573
+ for (const line of dedented) this.content.push(line);
1574
+ }
1575
+ compile() {
1576
+ const F = Function;
1577
+ const args = this?.args;
1578
+ const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
1579
+ return new F(...args, lines.join("\n"));
1580
+ }
1581
+ };
1582
+
691
1583
  //#endregion
692
1584
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js
693
1585
  const version = {
@@ -786,10 +1678,308 @@ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
786
1678
  version: 1
787
1679
  }));
788
1680
  });
1681
+ const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
1682
+ $ZodType.init(inst, def);
1683
+ inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
1684
+ inst._zod.parse = (payload, _) => {
1685
+ if (def.coerce) try {
1686
+ payload.value = String(payload.value);
1687
+ } catch (_$1) {}
1688
+ if (typeof payload.value === "string") return payload;
1689
+ payload.issues.push({
1690
+ expected: "string",
1691
+ code: "invalid_type",
1692
+ input: payload.value,
1693
+ inst
1694
+ });
1695
+ return payload;
1696
+ };
1697
+ });
1698
+ const $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
1699
+ $ZodCheckStringFormat.init(inst, def);
1700
+ $ZodString.init(inst, def);
1701
+ });
1702
+ const $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
1703
+ def.pattern ?? (def.pattern = guid);
1704
+ $ZodStringFormat.init(inst, def);
1705
+ });
1706
+ const $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
1707
+ if (def.version) {
1708
+ const v = {
1709
+ v1: 1,
1710
+ v2: 2,
1711
+ v3: 3,
1712
+ v4: 4,
1713
+ v5: 5,
1714
+ v6: 6,
1715
+ v7: 7,
1716
+ v8: 8
1717
+ }[def.version];
1718
+ if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
1719
+ def.pattern ?? (def.pattern = uuid(v));
1720
+ } else def.pattern ?? (def.pattern = uuid());
1721
+ $ZodStringFormat.init(inst, def);
1722
+ });
1723
+ const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
1724
+ def.pattern ?? (def.pattern = email);
1725
+ $ZodStringFormat.init(inst, def);
1726
+ });
1727
+ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1728
+ $ZodStringFormat.init(inst, def);
1729
+ inst._zod.check = (payload) => {
1730
+ try {
1731
+ const trimmed = payload.value.trim();
1732
+ const url = new URL(trimmed);
1733
+ if (def.hostname) {
1734
+ def.hostname.lastIndex = 0;
1735
+ if (!def.hostname.test(url.hostname)) payload.issues.push({
1736
+ code: "invalid_format",
1737
+ format: "url",
1738
+ note: "Invalid hostname",
1739
+ pattern: def.hostname.source,
1740
+ input: payload.value,
1741
+ inst,
1742
+ continue: !def.abort
1743
+ });
1744
+ }
1745
+ if (def.protocol) {
1746
+ def.protocol.lastIndex = 0;
1747
+ if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
1748
+ code: "invalid_format",
1749
+ format: "url",
1750
+ note: "Invalid protocol",
1751
+ pattern: def.protocol.source,
1752
+ input: payload.value,
1753
+ inst,
1754
+ continue: !def.abort
1755
+ });
1756
+ }
1757
+ if (def.normalize) payload.value = url.href;
1758
+ else payload.value = trimmed;
1759
+ return;
1760
+ } catch (_) {
1761
+ payload.issues.push({
1762
+ code: "invalid_format",
1763
+ format: "url",
1764
+ input: payload.value,
1765
+ inst,
1766
+ continue: !def.abort
1767
+ });
1768
+ }
1769
+ };
1770
+ });
1771
+ const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
1772
+ def.pattern ?? (def.pattern = emoji());
1773
+ $ZodStringFormat.init(inst, def);
1774
+ });
1775
+ const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
1776
+ def.pattern ?? (def.pattern = nanoid);
1777
+ $ZodStringFormat.init(inst, def);
1778
+ });
1779
+ const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
1780
+ def.pattern ?? (def.pattern = cuid);
1781
+ $ZodStringFormat.init(inst, def);
1782
+ });
1783
+ const $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
1784
+ def.pattern ?? (def.pattern = cuid2);
1785
+ $ZodStringFormat.init(inst, def);
1786
+ });
1787
+ const $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
1788
+ def.pattern ?? (def.pattern = ulid);
1789
+ $ZodStringFormat.init(inst, def);
1790
+ });
1791
+ const $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
1792
+ def.pattern ?? (def.pattern = xid);
1793
+ $ZodStringFormat.init(inst, def);
1794
+ });
1795
+ const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
1796
+ def.pattern ?? (def.pattern = ksuid);
1797
+ $ZodStringFormat.init(inst, def);
1798
+ });
1799
+ const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
1800
+ def.pattern ?? (def.pattern = datetime$1(def));
1801
+ $ZodStringFormat.init(inst, def);
1802
+ });
1803
+ const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
1804
+ def.pattern ?? (def.pattern = date$1);
1805
+ $ZodStringFormat.init(inst, def);
1806
+ });
1807
+ const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
1808
+ def.pattern ?? (def.pattern = time$1(def));
1809
+ $ZodStringFormat.init(inst, def);
1810
+ });
1811
+ const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
1812
+ def.pattern ?? (def.pattern = duration$1);
1813
+ $ZodStringFormat.init(inst, def);
1814
+ });
1815
+ const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
1816
+ def.pattern ?? (def.pattern = ipv4);
1817
+ $ZodStringFormat.init(inst, def);
1818
+ inst._zod.bag.format = `ipv4`;
1819
+ });
1820
+ const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
1821
+ def.pattern ?? (def.pattern = ipv6);
1822
+ $ZodStringFormat.init(inst, def);
1823
+ inst._zod.bag.format = `ipv6`;
1824
+ inst._zod.check = (payload) => {
1825
+ try {
1826
+ new URL(`http://[${payload.value}]`);
1827
+ } catch {
1828
+ payload.issues.push({
1829
+ code: "invalid_format",
1830
+ format: "ipv6",
1831
+ input: payload.value,
1832
+ inst,
1833
+ continue: !def.abort
1834
+ });
1835
+ }
1836
+ };
1837
+ });
1838
+ const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
1839
+ def.pattern ?? (def.pattern = cidrv4);
1840
+ $ZodStringFormat.init(inst, def);
1841
+ });
1842
+ const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
1843
+ def.pattern ?? (def.pattern = cidrv6);
1844
+ $ZodStringFormat.init(inst, def);
1845
+ inst._zod.check = (payload) => {
1846
+ const parts = payload.value.split("/");
1847
+ try {
1848
+ if (parts.length !== 2) throw new Error();
1849
+ const [address, prefix] = parts;
1850
+ if (!prefix) throw new Error();
1851
+ const prefixNum = Number(prefix);
1852
+ if (`${prefixNum}` !== prefix) throw new Error();
1853
+ if (prefixNum < 0 || prefixNum > 128) throw new Error();
1854
+ new URL(`http://[${address}]`);
1855
+ } catch {
1856
+ payload.issues.push({
1857
+ code: "invalid_format",
1858
+ format: "cidrv6",
1859
+ input: payload.value,
1860
+ inst,
1861
+ continue: !def.abort
1862
+ });
1863
+ }
1864
+ };
1865
+ });
1866
+ function isValidBase64(data) {
1867
+ if (data === "") return true;
1868
+ if (data.length % 4 !== 0) return false;
1869
+ try {
1870
+ atob(data);
1871
+ return true;
1872
+ } catch {
1873
+ return false;
1874
+ }
1875
+ }
1876
+ const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
1877
+ def.pattern ?? (def.pattern = base64);
1878
+ $ZodStringFormat.init(inst, def);
1879
+ inst._zod.bag.contentEncoding = "base64";
1880
+ inst._zod.check = (payload) => {
1881
+ if (isValidBase64(payload.value)) return;
1882
+ payload.issues.push({
1883
+ code: "invalid_format",
1884
+ format: "base64",
1885
+ input: payload.value,
1886
+ inst,
1887
+ continue: !def.abort
1888
+ });
1889
+ };
1890
+ });
1891
+ function isValidBase64URL(data) {
1892
+ if (!base64url.test(data)) return false;
1893
+ const base64$1 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
1894
+ return isValidBase64(base64$1.padEnd(Math.ceil(base64$1.length / 4) * 4, "="));
1895
+ }
1896
+ const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
1897
+ def.pattern ?? (def.pattern = base64url);
1898
+ $ZodStringFormat.init(inst, def);
1899
+ inst._zod.bag.contentEncoding = "base64url";
1900
+ inst._zod.check = (payload) => {
1901
+ if (isValidBase64URL(payload.value)) return;
1902
+ payload.issues.push({
1903
+ code: "invalid_format",
1904
+ format: "base64url",
1905
+ input: payload.value,
1906
+ inst,
1907
+ continue: !def.abort
1908
+ });
1909
+ };
1910
+ });
1911
+ const $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
1912
+ def.pattern ?? (def.pattern = e164);
1913
+ $ZodStringFormat.init(inst, def);
1914
+ });
1915
+ function isValidJWT(token, algorithm = null) {
1916
+ try {
1917
+ const tokensParts = token.split(".");
1918
+ if (tokensParts.length !== 3) return false;
1919
+ const [header] = tokensParts;
1920
+ if (!header) return false;
1921
+ const parsedHeader = JSON.parse(atob(header));
1922
+ if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
1923
+ if (!parsedHeader.alg) return false;
1924
+ if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
1925
+ return true;
1926
+ } catch {
1927
+ return false;
1928
+ }
1929
+ }
1930
+ const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
1931
+ $ZodStringFormat.init(inst, def);
1932
+ inst._zod.check = (payload) => {
1933
+ if (isValidJWT(payload.value, def.alg)) return;
1934
+ payload.issues.push({
1935
+ code: "invalid_format",
1936
+ format: "jwt",
1937
+ input: payload.value,
1938
+ inst,
1939
+ continue: !def.abort
1940
+ });
1941
+ };
1942
+ });
1943
+ const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
1944
+ $ZodType.init(inst, def);
1945
+ inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
1946
+ inst._zod.parse = (payload, _ctx) => {
1947
+ if (def.coerce) try {
1948
+ payload.value = Number(payload.value);
1949
+ } catch (_) {}
1950
+ const input = payload.value;
1951
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
1952
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
1953
+ payload.issues.push({
1954
+ expected: "number",
1955
+ code: "invalid_type",
1956
+ input,
1957
+ inst,
1958
+ ...received ? { received } : {}
1959
+ });
1960
+ return payload;
1961
+ };
1962
+ });
1963
+ const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
1964
+ $ZodCheckNumberFormat.init(inst, def);
1965
+ $ZodNumber.init(inst, def);
1966
+ });
789
1967
  const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
790
1968
  $ZodType.init(inst, def);
791
1969
  inst._zod.parse = (payload) => payload;
792
1970
  });
1971
+ const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
1972
+ $ZodType.init(inst, def);
1973
+ inst._zod.parse = (payload, _ctx) => {
1974
+ payload.issues.push({
1975
+ expected: "never",
1976
+ code: "invalid_type",
1977
+ input: payload.value,
1978
+ inst
1979
+ });
1980
+ return payload;
1981
+ };
1982
+ });
793
1983
  function handleArrayResult(result, final, index) {
794
1984
  if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
795
1985
  final.value[index] = result.value;
@@ -798,28 +1988,229 @@ const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
798
1988
  $ZodType.init(inst, def);
799
1989
  inst._zod.parse = (payload, ctx) => {
800
1990
  const input = payload.value;
801
- if (!Array.isArray(input)) {
1991
+ if (!Array.isArray(input)) {
1992
+ payload.issues.push({
1993
+ expected: "array",
1994
+ code: "invalid_type",
1995
+ input,
1996
+ inst
1997
+ });
1998
+ return payload;
1999
+ }
2000
+ payload.value = Array(input.length);
2001
+ const proms = [];
2002
+ for (let i = 0; i < input.length; i++) {
2003
+ const item = input[i];
2004
+ const result = def.element._zod.run({
2005
+ value: item,
2006
+ issues: []
2007
+ }, ctx);
2008
+ if (result instanceof Promise) proms.push(result.then((result$1) => handleArrayResult(result$1, payload, i)));
2009
+ else handleArrayResult(result, payload, i);
2010
+ }
2011
+ if (proms.length) return Promise.all(proms).then(() => payload);
2012
+ return payload;
2013
+ };
2014
+ });
2015
+ function handlePropertyResult(result, final, key, input, isOptionalOut) {
2016
+ if (result.issues.length) {
2017
+ if (isOptionalOut && !(key in input)) return;
2018
+ final.issues.push(...prefixIssues(key, result.issues));
2019
+ }
2020
+ if (result.value === void 0) {
2021
+ if (key in input) final.value[key] = void 0;
2022
+ } else final.value[key] = result.value;
2023
+ }
2024
+ function normalizeDef(def) {
2025
+ const keys = Object.keys(def.shape);
2026
+ 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`);
2027
+ const okeys = optionalKeys(def.shape);
2028
+ return {
2029
+ ...def,
2030
+ keys,
2031
+ keySet: new Set(keys),
2032
+ numKeys: keys.length,
2033
+ optionalKeys: new Set(okeys)
2034
+ };
2035
+ }
2036
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
2037
+ const unrecognized = [];
2038
+ const keySet = def.keySet;
2039
+ const _catchall = def.catchall._zod;
2040
+ const t = _catchall.def.type;
2041
+ const isOptionalOut = _catchall.optout === "optional";
2042
+ for (const key in input) {
2043
+ if (keySet.has(key)) continue;
2044
+ if (t === "never") {
2045
+ unrecognized.push(key);
2046
+ continue;
2047
+ }
2048
+ const r = _catchall.run({
2049
+ value: input[key],
2050
+ issues: []
2051
+ }, ctx);
2052
+ if (r instanceof Promise) proms.push(r.then((r$1) => handlePropertyResult(r$1, payload, key, input, isOptionalOut)));
2053
+ else handlePropertyResult(r, payload, key, input, isOptionalOut);
2054
+ }
2055
+ if (unrecognized.length) payload.issues.push({
2056
+ code: "unrecognized_keys",
2057
+ keys: unrecognized,
2058
+ input,
2059
+ inst
2060
+ });
2061
+ if (!proms.length) return payload;
2062
+ return Promise.all(proms).then(() => {
2063
+ return payload;
2064
+ });
2065
+ }
2066
+ const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
2067
+ $ZodType.init(inst, def);
2068
+ if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) {
2069
+ const sh = def.shape;
2070
+ Object.defineProperty(def, "shape", { get: () => {
2071
+ const newSh = { ...sh };
2072
+ Object.defineProperty(def, "shape", { value: newSh });
2073
+ return newSh;
2074
+ } });
2075
+ }
2076
+ const _normalized = cached(() => normalizeDef(def));
2077
+ defineLazy(inst._zod, "propValues", () => {
2078
+ const shape = def.shape;
2079
+ const propValues = {};
2080
+ for (const key in shape) {
2081
+ const field = shape[key]._zod;
2082
+ if (field.values) {
2083
+ propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
2084
+ for (const v of field.values) propValues[key].add(v);
2085
+ }
2086
+ }
2087
+ return propValues;
2088
+ });
2089
+ const isObject$1 = isObject;
2090
+ const catchall = def.catchall;
2091
+ let value;
2092
+ inst._zod.parse = (payload, ctx) => {
2093
+ value ?? (value = _normalized.value);
2094
+ const input = payload.value;
2095
+ if (!isObject$1(input)) {
2096
+ payload.issues.push({
2097
+ expected: "object",
2098
+ code: "invalid_type",
2099
+ input,
2100
+ inst
2101
+ });
2102
+ return payload;
2103
+ }
2104
+ payload.value = {};
2105
+ const proms = [];
2106
+ const shape = value.shape;
2107
+ for (const key of value.keys) {
2108
+ const el = shape[key];
2109
+ const isOptionalOut = el._zod.optout === "optional";
2110
+ const r = el._zod.run({
2111
+ value: input[key],
2112
+ issues: []
2113
+ }, ctx);
2114
+ if (r instanceof Promise) proms.push(r.then((r$1) => handlePropertyResult(r$1, payload, key, input, isOptionalOut)));
2115
+ else handlePropertyResult(r, payload, key, input, isOptionalOut);
2116
+ }
2117
+ if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
2118
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
2119
+ };
2120
+ });
2121
+ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
2122
+ $ZodObject.init(inst, def);
2123
+ const superParse = inst._zod.parse;
2124
+ const _normalized = cached(() => normalizeDef(def));
2125
+ const generateFastpass = (shape) => {
2126
+ const doc = new Doc([
2127
+ "shape",
2128
+ "payload",
2129
+ "ctx"
2130
+ ]);
2131
+ const normalized = _normalized.value;
2132
+ const parseStr = (key) => {
2133
+ const k = esc(key);
2134
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
2135
+ };
2136
+ doc.write(`const input = payload.value;`);
2137
+ const ids = Object.create(null);
2138
+ let counter = 0;
2139
+ for (const key of normalized.keys) ids[key] = `key_${counter++}`;
2140
+ doc.write(`const newResult = {};`);
2141
+ for (const key of normalized.keys) {
2142
+ const id = ids[key];
2143
+ const k = esc(key);
2144
+ const isOptionalOut = shape[key]?._zod?.optout === "optional";
2145
+ doc.write(`const ${id} = ${parseStr(key)};`);
2146
+ if (isOptionalOut) doc.write(`
2147
+ if (${id}.issues.length) {
2148
+ if (${k} in input) {
2149
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
2150
+ ...iss,
2151
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
2152
+ })));
2153
+ }
2154
+ }
2155
+
2156
+ if (${id}.value === undefined) {
2157
+ if (${k} in input) {
2158
+ newResult[${k}] = undefined;
2159
+ }
2160
+ } else {
2161
+ newResult[${k}] = ${id}.value;
2162
+ }
2163
+
2164
+ `);
2165
+ else doc.write(`
2166
+ if (${id}.issues.length) {
2167
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
2168
+ ...iss,
2169
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
2170
+ })));
2171
+ }
2172
+
2173
+ if (${id}.value === undefined) {
2174
+ if (${k} in input) {
2175
+ newResult[${k}] = undefined;
2176
+ }
2177
+ } else {
2178
+ newResult[${k}] = ${id}.value;
2179
+ }
2180
+
2181
+ `);
2182
+ }
2183
+ doc.write(`payload.value = newResult;`);
2184
+ doc.write(`return payload;`);
2185
+ const fn = doc.compile();
2186
+ return (payload, ctx) => fn(shape, payload, ctx);
2187
+ };
2188
+ let fastpass;
2189
+ const isObject$1 = isObject;
2190
+ const jit = !globalConfig.jitless;
2191
+ const allowsEval$1 = allowsEval;
2192
+ const fastEnabled = jit && allowsEval$1.value;
2193
+ const catchall = def.catchall;
2194
+ let value;
2195
+ inst._zod.parse = (payload, ctx) => {
2196
+ value ?? (value = _normalized.value);
2197
+ const input = payload.value;
2198
+ if (!isObject$1(input)) {
802
2199
  payload.issues.push({
803
- expected: "array",
2200
+ expected: "object",
804
2201
  code: "invalid_type",
805
2202
  input,
806
2203
  inst
807
2204
  });
808
2205
  return payload;
809
2206
  }
810
- payload.value = Array(input.length);
811
- const proms = [];
812
- for (let i = 0; i < input.length; i++) {
813
- const item = input[i];
814
- const result = def.element._zod.run({
815
- value: item,
816
- issues: []
817
- }, ctx);
818
- if (result instanceof Promise) proms.push(result.then((result$1) => handleArrayResult(result$1, payload, i)));
819
- else handleArrayResult(result, payload, i);
2207
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
2208
+ if (!fastpass) fastpass = generateFastpass(def.shape);
2209
+ payload = fastpass(payload, ctx);
2210
+ if (!catchall) return payload;
2211
+ return handleCatchall([], input, payload, ctx, value, inst);
820
2212
  }
821
- if (proms.length) return Promise.all(proms).then(() => payload);
822
- return payload;
2213
+ return superParse(payload, ctx);
823
2214
  };
824
2215
  });
825
2216
  function handleUnionResults(results, final, inst, ctx) {
@@ -977,6 +2368,115 @@ function handleIntersectionResults(result, left, right) {
977
2368
  result.value = merged.data;
978
2369
  return result;
979
2370
  }
2371
+ const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
2372
+ $ZodType.init(inst, def);
2373
+ inst._zod.parse = (payload, ctx) => {
2374
+ const input = payload.value;
2375
+ if (!isPlainObject(input)) {
2376
+ payload.issues.push({
2377
+ expected: "record",
2378
+ code: "invalid_type",
2379
+ input,
2380
+ inst
2381
+ });
2382
+ return payload;
2383
+ }
2384
+ const proms = [];
2385
+ const values = def.keyType._zod.values;
2386
+ if (values) {
2387
+ payload.value = {};
2388
+ const recordKeys = /* @__PURE__ */ new Set();
2389
+ for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
2390
+ recordKeys.add(typeof key === "number" ? key.toString() : key);
2391
+ const result = def.valueType._zod.run({
2392
+ value: input[key],
2393
+ issues: []
2394
+ }, ctx);
2395
+ if (result instanceof Promise) proms.push(result.then((result$1) => {
2396
+ if (result$1.issues.length) payload.issues.push(...prefixIssues(key, result$1.issues));
2397
+ payload.value[key] = result$1.value;
2398
+ }));
2399
+ else {
2400
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
2401
+ payload.value[key] = result.value;
2402
+ }
2403
+ }
2404
+ let unrecognized;
2405
+ for (const key in input) if (!recordKeys.has(key)) {
2406
+ unrecognized = unrecognized ?? [];
2407
+ unrecognized.push(key);
2408
+ }
2409
+ if (unrecognized && unrecognized.length > 0) payload.issues.push({
2410
+ code: "unrecognized_keys",
2411
+ input,
2412
+ inst,
2413
+ keys: unrecognized
2414
+ });
2415
+ } else {
2416
+ payload.value = {};
2417
+ for (const key of Reflect.ownKeys(input)) {
2418
+ if (key === "__proto__") continue;
2419
+ let keyResult = def.keyType._zod.run({
2420
+ value: key,
2421
+ issues: []
2422
+ }, ctx);
2423
+ if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
2424
+ if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) {
2425
+ const retryResult = def.keyType._zod.run({
2426
+ value: Number(key),
2427
+ issues: []
2428
+ }, ctx);
2429
+ if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
2430
+ if (retryResult.issues.length === 0) keyResult = retryResult;
2431
+ }
2432
+ if (keyResult.issues.length) {
2433
+ if (def.mode === "loose") payload.value[key] = input[key];
2434
+ else payload.issues.push({
2435
+ code: "invalid_key",
2436
+ origin: "record",
2437
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
2438
+ input: key,
2439
+ path: [key],
2440
+ inst
2441
+ });
2442
+ continue;
2443
+ }
2444
+ const result = def.valueType._zod.run({
2445
+ value: input[key],
2446
+ issues: []
2447
+ }, ctx);
2448
+ if (result instanceof Promise) proms.push(result.then((result$1) => {
2449
+ if (result$1.issues.length) payload.issues.push(...prefixIssues(key, result$1.issues));
2450
+ payload.value[keyResult.value] = result$1.value;
2451
+ }));
2452
+ else {
2453
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
2454
+ payload.value[keyResult.value] = result.value;
2455
+ }
2456
+ }
2457
+ }
2458
+ if (proms.length) return Promise.all(proms).then(() => payload);
2459
+ return payload;
2460
+ };
2461
+ });
2462
+ const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
2463
+ $ZodType.init(inst, def);
2464
+ const values = getEnumValues(def.entries);
2465
+ const valuesSet = new Set(values);
2466
+ inst._zod.values = valuesSet;
2467
+ inst._zod.pattern = /* @__PURE__ */ new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
2468
+ inst._zod.parse = (payload, _ctx) => {
2469
+ const input = payload.value;
2470
+ if (valuesSet.has(input)) return payload;
2471
+ payload.issues.push({
2472
+ code: "invalid_value",
2473
+ values,
2474
+ input,
2475
+ inst
2476
+ });
2477
+ return payload;
2478
+ };
2479
+ });
980
2480
  const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
981
2481
  $ZodType.init(inst, def);
982
2482
  inst._zod.parse = (payload, ctx) => {
@@ -1252,10 +2752,349 @@ const globalRegistry = globalThis.__zod_globalRegistry;
1252
2752
  //#endregion
1253
2753
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js
1254
2754
  /* @__NO_SIDE_EFFECTS__ */
2755
+ function _string(Class, params) {
2756
+ return new Class({
2757
+ type: "string",
2758
+ ...normalizeParams(params)
2759
+ });
2760
+ }
2761
+ /* @__NO_SIDE_EFFECTS__ */
2762
+ function _email(Class, params) {
2763
+ return new Class({
2764
+ type: "string",
2765
+ format: "email",
2766
+ check: "string_format",
2767
+ abort: false,
2768
+ ...normalizeParams(params)
2769
+ });
2770
+ }
2771
+ /* @__NO_SIDE_EFFECTS__ */
2772
+ function _guid(Class, params) {
2773
+ return new Class({
2774
+ type: "string",
2775
+ format: "guid",
2776
+ check: "string_format",
2777
+ abort: false,
2778
+ ...normalizeParams(params)
2779
+ });
2780
+ }
2781
+ /* @__NO_SIDE_EFFECTS__ */
2782
+ function _uuid(Class, params) {
2783
+ return new Class({
2784
+ type: "string",
2785
+ format: "uuid",
2786
+ check: "string_format",
2787
+ abort: false,
2788
+ ...normalizeParams(params)
2789
+ });
2790
+ }
2791
+ /* @__NO_SIDE_EFFECTS__ */
2792
+ function _uuidv4(Class, params) {
2793
+ return new Class({
2794
+ type: "string",
2795
+ format: "uuid",
2796
+ check: "string_format",
2797
+ abort: false,
2798
+ version: "v4",
2799
+ ...normalizeParams(params)
2800
+ });
2801
+ }
2802
+ /* @__NO_SIDE_EFFECTS__ */
2803
+ function _uuidv6(Class, params) {
2804
+ return new Class({
2805
+ type: "string",
2806
+ format: "uuid",
2807
+ check: "string_format",
2808
+ abort: false,
2809
+ version: "v6",
2810
+ ...normalizeParams(params)
2811
+ });
2812
+ }
2813
+ /* @__NO_SIDE_EFFECTS__ */
2814
+ function _uuidv7(Class, params) {
2815
+ return new Class({
2816
+ type: "string",
2817
+ format: "uuid",
2818
+ check: "string_format",
2819
+ abort: false,
2820
+ version: "v7",
2821
+ ...normalizeParams(params)
2822
+ });
2823
+ }
2824
+ /* @__NO_SIDE_EFFECTS__ */
2825
+ function _url(Class, params) {
2826
+ return new Class({
2827
+ type: "string",
2828
+ format: "url",
2829
+ check: "string_format",
2830
+ abort: false,
2831
+ ...normalizeParams(params)
2832
+ });
2833
+ }
2834
+ /* @__NO_SIDE_EFFECTS__ */
2835
+ function _emoji(Class, params) {
2836
+ return new Class({
2837
+ type: "string",
2838
+ format: "emoji",
2839
+ check: "string_format",
2840
+ abort: false,
2841
+ ...normalizeParams(params)
2842
+ });
2843
+ }
2844
+ /* @__NO_SIDE_EFFECTS__ */
2845
+ function _nanoid(Class, params) {
2846
+ return new Class({
2847
+ type: "string",
2848
+ format: "nanoid",
2849
+ check: "string_format",
2850
+ abort: false,
2851
+ ...normalizeParams(params)
2852
+ });
2853
+ }
2854
+ /* @__NO_SIDE_EFFECTS__ */
2855
+ function _cuid(Class, params) {
2856
+ return new Class({
2857
+ type: "string",
2858
+ format: "cuid",
2859
+ check: "string_format",
2860
+ abort: false,
2861
+ ...normalizeParams(params)
2862
+ });
2863
+ }
2864
+ /* @__NO_SIDE_EFFECTS__ */
2865
+ function _cuid2(Class, params) {
2866
+ return new Class({
2867
+ type: "string",
2868
+ format: "cuid2",
2869
+ check: "string_format",
2870
+ abort: false,
2871
+ ...normalizeParams(params)
2872
+ });
2873
+ }
2874
+ /* @__NO_SIDE_EFFECTS__ */
2875
+ function _ulid(Class, params) {
2876
+ return new Class({
2877
+ type: "string",
2878
+ format: "ulid",
2879
+ check: "string_format",
2880
+ abort: false,
2881
+ ...normalizeParams(params)
2882
+ });
2883
+ }
2884
+ /* @__NO_SIDE_EFFECTS__ */
2885
+ function _xid(Class, params) {
2886
+ return new Class({
2887
+ type: "string",
2888
+ format: "xid",
2889
+ check: "string_format",
2890
+ abort: false,
2891
+ ...normalizeParams(params)
2892
+ });
2893
+ }
2894
+ /* @__NO_SIDE_EFFECTS__ */
2895
+ function _ksuid(Class, params) {
2896
+ return new Class({
2897
+ type: "string",
2898
+ format: "ksuid",
2899
+ check: "string_format",
2900
+ abort: false,
2901
+ ...normalizeParams(params)
2902
+ });
2903
+ }
2904
+ /* @__NO_SIDE_EFFECTS__ */
2905
+ function _ipv4(Class, params) {
2906
+ return new Class({
2907
+ type: "string",
2908
+ format: "ipv4",
2909
+ check: "string_format",
2910
+ abort: false,
2911
+ ...normalizeParams(params)
2912
+ });
2913
+ }
2914
+ /* @__NO_SIDE_EFFECTS__ */
2915
+ function _ipv6(Class, params) {
2916
+ return new Class({
2917
+ type: "string",
2918
+ format: "ipv6",
2919
+ check: "string_format",
2920
+ abort: false,
2921
+ ...normalizeParams(params)
2922
+ });
2923
+ }
2924
+ /* @__NO_SIDE_EFFECTS__ */
2925
+ function _cidrv4(Class, params) {
2926
+ return new Class({
2927
+ type: "string",
2928
+ format: "cidrv4",
2929
+ check: "string_format",
2930
+ abort: false,
2931
+ ...normalizeParams(params)
2932
+ });
2933
+ }
2934
+ /* @__NO_SIDE_EFFECTS__ */
2935
+ function _cidrv6(Class, params) {
2936
+ return new Class({
2937
+ type: "string",
2938
+ format: "cidrv6",
2939
+ check: "string_format",
2940
+ abort: false,
2941
+ ...normalizeParams(params)
2942
+ });
2943
+ }
2944
+ /* @__NO_SIDE_EFFECTS__ */
2945
+ function _base64(Class, params) {
2946
+ return new Class({
2947
+ type: "string",
2948
+ format: "base64",
2949
+ check: "string_format",
2950
+ abort: false,
2951
+ ...normalizeParams(params)
2952
+ });
2953
+ }
2954
+ /* @__NO_SIDE_EFFECTS__ */
2955
+ function _base64url(Class, params) {
2956
+ return new Class({
2957
+ type: "string",
2958
+ format: "base64url",
2959
+ check: "string_format",
2960
+ abort: false,
2961
+ ...normalizeParams(params)
2962
+ });
2963
+ }
2964
+ /* @__NO_SIDE_EFFECTS__ */
2965
+ function _e164(Class, params) {
2966
+ return new Class({
2967
+ type: "string",
2968
+ format: "e164",
2969
+ check: "string_format",
2970
+ abort: false,
2971
+ ...normalizeParams(params)
2972
+ });
2973
+ }
2974
+ /* @__NO_SIDE_EFFECTS__ */
2975
+ function _jwt(Class, params) {
2976
+ return new Class({
2977
+ type: "string",
2978
+ format: "jwt",
2979
+ check: "string_format",
2980
+ abort: false,
2981
+ ...normalizeParams(params)
2982
+ });
2983
+ }
2984
+ /* @__NO_SIDE_EFFECTS__ */
2985
+ function _isoDateTime(Class, params) {
2986
+ return new Class({
2987
+ type: "string",
2988
+ format: "datetime",
2989
+ check: "string_format",
2990
+ offset: false,
2991
+ local: false,
2992
+ precision: null,
2993
+ ...normalizeParams(params)
2994
+ });
2995
+ }
2996
+ /* @__NO_SIDE_EFFECTS__ */
2997
+ function _isoDate(Class, params) {
2998
+ return new Class({
2999
+ type: "string",
3000
+ format: "date",
3001
+ check: "string_format",
3002
+ ...normalizeParams(params)
3003
+ });
3004
+ }
3005
+ /* @__NO_SIDE_EFFECTS__ */
3006
+ function _isoTime(Class, params) {
3007
+ return new Class({
3008
+ type: "string",
3009
+ format: "time",
3010
+ check: "string_format",
3011
+ precision: null,
3012
+ ...normalizeParams(params)
3013
+ });
3014
+ }
3015
+ /* @__NO_SIDE_EFFECTS__ */
3016
+ function _isoDuration(Class, params) {
3017
+ return new Class({
3018
+ type: "string",
3019
+ format: "duration",
3020
+ check: "string_format",
3021
+ ...normalizeParams(params)
3022
+ });
3023
+ }
3024
+ /* @__NO_SIDE_EFFECTS__ */
3025
+ function _number(Class, params) {
3026
+ return new Class({
3027
+ type: "number",
3028
+ checks: [],
3029
+ ...normalizeParams(params)
3030
+ });
3031
+ }
3032
+ /* @__NO_SIDE_EFFECTS__ */
3033
+ function _int(Class, params) {
3034
+ return new Class({
3035
+ type: "number",
3036
+ check: "number_format",
3037
+ abort: false,
3038
+ format: "safeint",
3039
+ ...normalizeParams(params)
3040
+ });
3041
+ }
3042
+ /* @__NO_SIDE_EFFECTS__ */
1255
3043
  function _unknown(Class) {
1256
3044
  return new Class({ type: "unknown" });
1257
3045
  }
1258
3046
  /* @__NO_SIDE_EFFECTS__ */
3047
+ function _never(Class, params) {
3048
+ return new Class({
3049
+ type: "never",
3050
+ ...normalizeParams(params)
3051
+ });
3052
+ }
3053
+ /* @__NO_SIDE_EFFECTS__ */
3054
+ function _lt(value, params) {
3055
+ return new $ZodCheckLessThan({
3056
+ check: "less_than",
3057
+ ...normalizeParams(params),
3058
+ value,
3059
+ inclusive: false
3060
+ });
3061
+ }
3062
+ /* @__NO_SIDE_EFFECTS__ */
3063
+ function _lte(value, params) {
3064
+ return new $ZodCheckLessThan({
3065
+ check: "less_than",
3066
+ ...normalizeParams(params),
3067
+ value,
3068
+ inclusive: true
3069
+ });
3070
+ }
3071
+ /* @__NO_SIDE_EFFECTS__ */
3072
+ function _gt(value, params) {
3073
+ return new $ZodCheckGreaterThan({
3074
+ check: "greater_than",
3075
+ ...normalizeParams(params),
3076
+ value,
3077
+ inclusive: false
3078
+ });
3079
+ }
3080
+ /* @__NO_SIDE_EFFECTS__ */
3081
+ function _gte(value, params) {
3082
+ return new $ZodCheckGreaterThan({
3083
+ check: "greater_than",
3084
+ ...normalizeParams(params),
3085
+ value,
3086
+ inclusive: true
3087
+ });
3088
+ }
3089
+ /* @__NO_SIDE_EFFECTS__ */
3090
+ function _multipleOf(value, params) {
3091
+ return new $ZodCheckMultipleOf({
3092
+ check: "multiple_of",
3093
+ ...normalizeParams(params),
3094
+ value
3095
+ });
3096
+ }
3097
+ /* @__NO_SIDE_EFFECTS__ */
1259
3098
  function _maxLength(maximum, params) {
1260
3099
  return new $ZodCheckMaxLength({
1261
3100
  check: "max_length",
@@ -1280,6 +3119,58 @@ function _length(length, params) {
1280
3119
  });
1281
3120
  }
1282
3121
  /* @__NO_SIDE_EFFECTS__ */
3122
+ function _regex(pattern, params) {
3123
+ return new $ZodCheckRegex({
3124
+ check: "string_format",
3125
+ format: "regex",
3126
+ ...normalizeParams(params),
3127
+ pattern
3128
+ });
3129
+ }
3130
+ /* @__NO_SIDE_EFFECTS__ */
3131
+ function _lowercase(params) {
3132
+ return new $ZodCheckLowerCase({
3133
+ check: "string_format",
3134
+ format: "lowercase",
3135
+ ...normalizeParams(params)
3136
+ });
3137
+ }
3138
+ /* @__NO_SIDE_EFFECTS__ */
3139
+ function _uppercase(params) {
3140
+ return new $ZodCheckUpperCase({
3141
+ check: "string_format",
3142
+ format: "uppercase",
3143
+ ...normalizeParams(params)
3144
+ });
3145
+ }
3146
+ /* @__NO_SIDE_EFFECTS__ */
3147
+ function _includes(includes, params) {
3148
+ return new $ZodCheckIncludes({
3149
+ check: "string_format",
3150
+ format: "includes",
3151
+ ...normalizeParams(params),
3152
+ includes
3153
+ });
3154
+ }
3155
+ /* @__NO_SIDE_EFFECTS__ */
3156
+ function _startsWith(prefix, params) {
3157
+ return new $ZodCheckStartsWith({
3158
+ check: "string_format",
3159
+ format: "starts_with",
3160
+ ...normalizeParams(params),
3161
+ prefix
3162
+ });
3163
+ }
3164
+ /* @__NO_SIDE_EFFECTS__ */
3165
+ function _endsWith(suffix, params) {
3166
+ return new $ZodCheckEndsWith({
3167
+ check: "string_format",
3168
+ format: "ends_with",
3169
+ ...normalizeParams(params),
3170
+ suffix
3171
+ });
3172
+ }
3173
+ /* @__NO_SIDE_EFFECTS__ */
1283
3174
  function _overwrite(tx) {
1284
3175
  return new $ZodCheckOverwrite({
1285
3176
  check: "overwrite",
@@ -1287,6 +3178,26 @@ function _overwrite(tx) {
1287
3178
  });
1288
3179
  }
1289
3180
  /* @__NO_SIDE_EFFECTS__ */
3181
+ function _normalize(form) {
3182
+ return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
3183
+ }
3184
+ /* @__NO_SIDE_EFFECTS__ */
3185
+ function _trim() {
3186
+ return /* @__PURE__ */ _overwrite((input) => input.trim());
3187
+ }
3188
+ /* @__NO_SIDE_EFFECTS__ */
3189
+ function _toLowerCase() {
3190
+ return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
3191
+ }
3192
+ /* @__NO_SIDE_EFFECTS__ */
3193
+ function _toUpperCase() {
3194
+ return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
3195
+ }
3196
+ /* @__NO_SIDE_EFFECTS__ */
3197
+ function _slugify() {
3198
+ return /* @__PURE__ */ _overwrite((input) => slugify(input));
3199
+ }
3200
+ /* @__NO_SIDE_EFFECTS__ */
1290
3201
  function _array(Class, element, params) {
1291
3202
  return new Class({
1292
3203
  type: "array",
@@ -2130,58 +4041,40 @@ let AIAgentExecutionHelpersFactory = class AIAgentExecutionHelpersFactory$1 {
2130
4041
  createConnectionCredentialExecutionContextFactory(credentialSessions) {
2131
4042
  return new ConnectionCredentialExecutionContextFactory(credentialSessions);
2132
4043
  }
2133
- createDynamicStructuredTool(entry, toolCredentialContext, item, itemIndex, items) {
2134
- if (entry.runtime.inputSchema == null) throw new Error(`Cannot create LangChain tool "${entry.config.name}": missing inputSchema (broken tool runtime resolution).`);
2135
- const schemaForOpenAi = this.createJsonSchemaRecord(entry.runtime.inputSchema, {
2136
- schemaName: entry.config.name,
2137
- requireObjectRoot: true
2138
- });
2139
- return new __langchain_core_tools.DynamicStructuredTool({
2140
- name: entry.config.name,
2141
- description: entry.config.description ?? entry.runtime.defaultDescription,
2142
- schema: schemaForOpenAi,
2143
- func: async (input) => {
2144
- const result = await entry.runtime.execute({
2145
- config: entry.config,
2146
- input,
2147
- ctx: toolCredentialContext,
2148
- item,
2149
- itemIndex,
2150
- items
2151
- });
2152
- return JSON.stringify(result);
2153
- }
2154
- });
2155
- }
2156
4044
  /**
2157
- * Produces a plain JSON Schema object for OpenAI tool parameters and LangChain tool invocation:
2158
- * - **Zod** `toJSONSchema(..., { target: "draft-07" })` so shapes match what `@cfworker/json-schema`
2159
- * expects (`required` must be an array; draft 2020-12 output can break validation).
2160
- * - Otherwise LangChain `toJsonSchema` (Standard Schema + JSON passthrough); if the result is still Zod
2161
- * (duplicate `zod` copies), fall back to Zod `toJSONSchema` with draft-07.
2162
- * - Strip root `$schema` for OpenAI; normalize invalid `required` keywords for cfworker; ensure `properties`.
4045
+ * Produces a plain JSON Schema object (`draft-07`) from a Zod schema, as needed by
4046
+ * OpenAI tool-parameter schemas and the structured-output repair prompt.
4047
+ * - Prefers the schema's **instance** `toJSONSchema(...)` method so we stay inside the Zod
4048
+ * instance that created the schema (works across consumer/framework tsx namespaces see
4049
+ * {@link ZodInstanceToJsonSchema}). Falls back to the framework-imported module function.
4050
+ * - Strips root `$schema` (OpenAI ignores it).
4051
+ * - Sanitizes `required` for cfworker json-schema compatibility (must be a string array or absent).
2163
4052
  */
2164
4053
  createJsonSchemaRecord(inputSchema, options) {
2165
- const draft07Params = { target: "draft-07" };
2166
- let converted;
2167
- if ((0, __langchain_core_utils_types.isInteropZodSchema)(inputSchema)) converted = toJSONSchema(inputSchema, draft07Params);
2168
- else {
2169
- converted = (0, __langchain_core_utils_json_schema.toJsonSchema)(inputSchema);
2170
- if ((0, __langchain_core_utils_types.isInteropZodSchema)(converted)) converted = toJSONSchema(inputSchema, draft07Params);
2171
- }
2172
- const { $schema: _draftSchemaOmitted,...rest } = converted;
2173
- 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)}).`);
2174
- 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)}).`);
4054
+ const { $schema: _draftSchemaOmitted,...rest } = this.convertZodSchemaToJsonSchema(inputSchema, { target: "draft-07" });
4055
+ 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)}).`);
4056
+ 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)}).`);
2175
4057
  if (options.requireObjectRoot && rest.properties === void 0) rest.properties = {};
2176
4058
  this.sanitizeJsonSchemaRequiredKeywordsForCfworker(rest);
2177
4059
  return rest;
2178
4060
  }
2179
4061
  /**
4062
+ * Runs Zod's `toJSONSchema` via the schema's own instance method when available, so consumer
4063
+ * schemas loaded under a different tsx namespace still convert correctly. If the caller handed us
4064
+ * a payload that lacks that method (e.g. a plain JSON Schema record or a Zod instance whose
4065
+ * prototype was stripped), we fall back to the framework-bundled module function.
4066
+ */
4067
+ convertZodSchemaToJsonSchema(inputSchema, params) {
4068
+ const candidate = inputSchema.toJSONSchema;
4069
+ if (typeof candidate === "function") return candidate.call(inputSchema, params);
4070
+ return toJSONSchema(inputSchema, params);
4071
+ }
4072
+ /**
2180
4073
  * `@cfworker/json-schema` iterates `schema.required` with `for...of`; it must be a string array or absent.
2181
4074
  */
2182
- sanitizeJsonSchemaRequiredKeywordsForCfworker(node$16) {
2183
- if (!node$16 || typeof node$16 !== "object" || Array.isArray(node$16)) return;
2184
- const o = node$16;
4075
+ sanitizeJsonSchemaRequiredKeywordsForCfworker(node$20) {
4076
+ if (!node$20 || typeof node$20 !== "object" || Array.isArray(node$20)) return;
4077
+ const o = node$20;
2185
4078
  const req = o.required;
2186
4079
  if (req !== void 0 && !Array.isArray(req)) delete o.required;
2187
4080
  else if (Array.isArray(req)) {
@@ -2223,6 +4116,214 @@ function __decorateParam(paramIndex, decorator) {
2223
4116
  };
2224
4117
  }
2225
4118
 
4119
+ //#endregion
4120
+ //#region src/chatModels/OpenAiStrictJsonSchemaFactory.ts
4121
+ var _ref$5;
4122
+ let OpenAiStrictJsonSchemaFactory = class OpenAiStrictJsonSchemaFactory$1 {
4123
+ constructor(executionHelpers) {
4124
+ this.executionHelpers = executionHelpers;
4125
+ }
4126
+ createStructuredOutputRecord(schema, options) {
4127
+ const record$1 = this.executionHelpers.createJsonSchemaRecord(schema, {
4128
+ schemaName: options.schemaName,
4129
+ requireObjectRoot: false
4130
+ });
4131
+ this.strictifyRecursive(record$1);
4132
+ if (options.title !== void 0) record$1.title = options.title;
4133
+ return record$1;
4134
+ }
4135
+ strictifyRecursive(node$20) {
4136
+ if (!node$20 || typeof node$20 !== "object" || Array.isArray(node$20)) return;
4137
+ const o = node$20;
4138
+ this.stripOpenAiRejectedKeywords(o);
4139
+ if (this.isObjectNode(o)) {
4140
+ const props = this.readPropertiesObject(o);
4141
+ o.properties = props;
4142
+ o.additionalProperties = false;
4143
+ o.required = Object.keys(props);
4144
+ for (const value of Object.values(props)) this.strictifyRecursive(value);
4145
+ }
4146
+ this.recurseIntoComposites(o);
4147
+ }
4148
+ stripOpenAiRejectedKeywords(o) {
4149
+ delete o["$schema"];
4150
+ delete o["unevaluatedProperties"];
4151
+ delete o["default"];
4152
+ }
4153
+ isObjectNode(o) {
4154
+ const typeIsObject = o.type === "object" || Array.isArray(o.type) && o.type.includes("object");
4155
+ const hasObjectProperties = o.properties !== void 0 && typeof o.properties === "object" && !Array.isArray(o.properties);
4156
+ return typeIsObject || hasObjectProperties;
4157
+ }
4158
+ readPropertiesObject(o) {
4159
+ if (o.properties && typeof o.properties === "object" && !Array.isArray(o.properties)) return o.properties;
4160
+ return {};
4161
+ }
4162
+ recurseIntoComposites(o) {
4163
+ for (const key of [
4164
+ "allOf",
4165
+ "anyOf",
4166
+ "oneOf",
4167
+ "prefixItems"
4168
+ ]) {
4169
+ const branch = o[key];
4170
+ if (Array.isArray(branch)) for (const sub of branch) this.strictifyRecursive(sub);
4171
+ }
4172
+ if (o.not) this.strictifyRecursive(o.not);
4173
+ if (o.items) if (Array.isArray(o.items)) for (const sub of o.items) this.strictifyRecursive(sub);
4174
+ else this.strictifyRecursive(o.items);
4175
+ for (const key of [
4176
+ "if",
4177
+ "then",
4178
+ "else"
4179
+ ]) if (o[key]) this.strictifyRecursive(o[key]);
4180
+ for (const key of ["$defs", "definitions"]) {
4181
+ const defs = o[key];
4182
+ if (defs && typeof defs === "object" && !Array.isArray(defs)) for (const sub of Object.values(defs)) this.strictifyRecursive(sub);
4183
+ }
4184
+ }
4185
+ };
4186
+ OpenAiStrictJsonSchemaFactory = __decorate([
4187
+ (0, __codemation_core.injectable)(),
4188
+ __decorateParam(0, (0, __codemation_core.inject)(AIAgentExecutionHelpersFactory)),
4189
+ __decorateMetadata("design:paramtypes", [typeof (_ref$5 = typeof AIAgentExecutionHelpersFactory !== "undefined" && AIAgentExecutionHelpersFactory) === "function" ? _ref$5 : Object])
4190
+ ], OpenAiStrictJsonSchemaFactory);
4191
+
4192
+ //#endregion
4193
+ //#region src/chatModels/openAiChatModelConfig.ts
4194
+ var OpenAIChatModelConfig = class {
4195
+ type = OpenAIChatModelFactory;
4196
+ presentation;
4197
+ provider = "openai";
4198
+ modelName;
4199
+ constructor(name, model, credentialSlotKey = "openai", presentationIn, options) {
4200
+ this.name = name;
4201
+ this.model = model;
4202
+ this.credentialSlotKey = credentialSlotKey;
4203
+ this.options = options;
4204
+ this.modelName = model;
4205
+ this.presentation = presentationIn ?? {
4206
+ icon: "builtin:openai",
4207
+ label: name
4208
+ };
4209
+ }
4210
+ getCredentialRequirements() {
4211
+ return [{
4212
+ slotKey: this.credentialSlotKey,
4213
+ label: "OpenAI API key",
4214
+ acceptedTypes: ["openai.apiKey"]
4215
+ }];
4216
+ }
4217
+ };
4218
+
4219
+ //#endregion
4220
+ //#region src/chatModels/OpenAiChatModelPresetsFactory.ts
4221
+ /**
4222
+ * Default OpenAI chat model configs for scaffolds and demos (icon + label match {@link OpenAIChatModelConfig} defaults).
4223
+ * Prefer importing {@link openAiChatModelPresets} from here or from the consumer template re-export
4224
+ * instead of repeating {@link OpenAIChatModelConfig} construction in app workflows.
4225
+ */
4226
+ var OpenAiChatModelPresets = class {
4227
+ demoGpt4oMini = new OpenAIChatModelConfig("OpenAI", "gpt-4o-mini");
4228
+ demoGpt41 = new OpenAIChatModelConfig("OpenAI", "gpt-4.1");
4229
+ };
4230
+ const openAiChatModelPresets = new OpenAiChatModelPresets();
4231
+
4232
+ //#endregion
4233
+ //#region src/nodes/AgentMessageFactory.ts
4234
+ /**
4235
+ * AI-SDK-shaped message construction for the AIAgent stack. Emits plain `ModelMessage[]`
4236
+ * ( `{ role: 'system' | 'user' | 'assistant' | 'tool', content: ... }` ) as consumed by
4237
+ * `generateText({ messages })` from the `ai` package.
4238
+ */
4239
+ var AgentMessageFactory = class AgentMessageFactory {
4240
+ static createPromptMessages(messages) {
4241
+ return messages.map((message) => this.createPromptMessage(message));
4242
+ }
4243
+ /**
4244
+ * Builds the assistant message that contains optional text plus one or more tool-call parts,
4245
+ * matching the shape AI SDK emits between steps.
4246
+ */
4247
+ static createAssistantWithToolCalls(text, toolCalls) {
4248
+ const content = [];
4249
+ if (text && text.length > 0) content.push({
4250
+ type: "text",
4251
+ text
4252
+ });
4253
+ for (const toolCall of toolCalls) content.push({
4254
+ type: "tool-call",
4255
+ toolCallId: toolCall.id ?? toolCall.name,
4256
+ toolName: toolCall.name,
4257
+ input: toolCall.input ?? {}
4258
+ });
4259
+ return {
4260
+ role: "assistant",
4261
+ content
4262
+ };
4263
+ }
4264
+ /**
4265
+ * Builds the `{ role: "tool", content: [{ type: "tool-result", ... }, ...] }` message returned
4266
+ * to the model after each tool round.
4267
+ */
4268
+ static createToolResultsMessage(executedToolCalls) {
4269
+ return {
4270
+ role: "tool",
4271
+ content: executedToolCalls.map((executed) => ({
4272
+ type: "tool-result",
4273
+ toolCallId: executed.toolCallId,
4274
+ toolName: executed.toolName,
4275
+ output: {
4276
+ type: "json",
4277
+ value: AgentMessageFactory.toToolResultJson(executed.result)
4278
+ }
4279
+ }))
4280
+ };
4281
+ }
4282
+ static toToolResultJson(value) {
4283
+ if (value === void 0) return null;
4284
+ try {
4285
+ return JSON.parse(JSON.stringify(value));
4286
+ } catch {
4287
+ return String(value);
4288
+ }
4289
+ }
4290
+ static createPromptMessage(message) {
4291
+ if (message.role === "system") return {
4292
+ role: "system",
4293
+ content: message.content
4294
+ };
4295
+ if (message.role === "assistant") return {
4296
+ role: "assistant",
4297
+ content: message.content
4298
+ };
4299
+ return {
4300
+ role: "user",
4301
+ content: message.content
4302
+ };
4303
+ }
4304
+ };
4305
+
4306
+ //#endregion
4307
+ //#region src/nodes/AgentOutputFactory.ts
4308
+ var AgentOutputFactory = class {
4309
+ static fromUnknown(value) {
4310
+ return { main: [{ json: value }] };
4311
+ }
4312
+ static replaceJson(item, value) {
4313
+ return {
4314
+ ...item,
4315
+ json: value
4316
+ };
4317
+ }
4318
+ static fromAgentContent(content) {
4319
+ try {
4320
+ return JSON.parse(content);
4321
+ } catch {
4322
+ return { output: content };
4323
+ }
4324
+ }
4325
+ };
4326
+
2226
4327
  //#endregion
2227
4328
  //#region src/nodes/AgentStructuredOutputRepairPromptFactory.ts
2228
4329
  var _ref$4, _AgentStructuredOutputRepairPromptFactory;
@@ -2263,6 +4364,37 @@ AgentStructuredOutputRepairPromptFactory = _AgentStructuredOutputRepairPromptFac
2263
4364
  __decorateMetadata("design:paramtypes", [typeof (_ref$4 = typeof AIAgentExecutionHelpersFactory !== "undefined" && AIAgentExecutionHelpersFactory) === "function" ? _ref$4 : Object])
2264
4365
  ], AgentStructuredOutputRepairPromptFactory);
2265
4366
 
4367
+ //#endregion
4368
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js
4369
+ const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
4370
+ $ZodISODateTime.init(inst, def);
4371
+ ZodStringFormat.init(inst, def);
4372
+ });
4373
+ function datetime(params) {
4374
+ return _isoDateTime(ZodISODateTime, params);
4375
+ }
4376
+ const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
4377
+ $ZodISODate.init(inst, def);
4378
+ ZodStringFormat.init(inst, def);
4379
+ });
4380
+ function date(params) {
4381
+ return _isoDate(ZodISODate, params);
4382
+ }
4383
+ const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
4384
+ $ZodISOTime.init(inst, def);
4385
+ ZodStringFormat.init(inst, def);
4386
+ });
4387
+ function time(params) {
4388
+ return _isoTime(ZodISOTime, params);
4389
+ }
4390
+ const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
4391
+ $ZodISODuration.init(inst, def);
4392
+ ZodStringFormat.init(inst, def);
4393
+ });
4394
+ function duration(params) {
4395
+ return _isoDuration(ZodISODuration, params);
4396
+ }
4397
+
2266
4398
  //#endregion
2267
4399
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js
2268
4400
  const initializer = (inst, issues) => {
@@ -2380,6 +4512,181 @@ const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
2380
4512
  inst.apply = (fn) => fn(inst);
2381
4513
  return inst;
2382
4514
  });
4515
+ /** @internal */
4516
+ const _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
4517
+ $ZodString.init(inst, def);
4518
+ ZodType.init(inst, def);
4519
+ inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
4520
+ const bag = inst._zod.bag;
4521
+ inst.format = bag.format ?? null;
4522
+ inst.minLength = bag.minimum ?? null;
4523
+ inst.maxLength = bag.maximum ?? null;
4524
+ inst.regex = (...args) => inst.check(_regex(...args));
4525
+ inst.includes = (...args) => inst.check(_includes(...args));
4526
+ inst.startsWith = (...args) => inst.check(_startsWith(...args));
4527
+ inst.endsWith = (...args) => inst.check(_endsWith(...args));
4528
+ inst.min = (...args) => inst.check(_minLength(...args));
4529
+ inst.max = (...args) => inst.check(_maxLength(...args));
4530
+ inst.length = (...args) => inst.check(_length(...args));
4531
+ inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
4532
+ inst.lowercase = (params) => inst.check(_lowercase(params));
4533
+ inst.uppercase = (params) => inst.check(_uppercase(params));
4534
+ inst.trim = () => inst.check(_trim());
4535
+ inst.normalize = (...args) => inst.check(_normalize(...args));
4536
+ inst.toLowerCase = () => inst.check(_toLowerCase());
4537
+ inst.toUpperCase = () => inst.check(_toUpperCase());
4538
+ inst.slugify = () => inst.check(_slugify());
4539
+ });
4540
+ const ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
4541
+ $ZodString.init(inst, def);
4542
+ _ZodString.init(inst, def);
4543
+ inst.email = (params) => inst.check(_email(ZodEmail, params));
4544
+ inst.url = (params) => inst.check(_url(ZodURL, params));
4545
+ inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
4546
+ inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
4547
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
4548
+ inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
4549
+ inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
4550
+ inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
4551
+ inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
4552
+ inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
4553
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
4554
+ inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
4555
+ inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
4556
+ inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
4557
+ inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
4558
+ inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
4559
+ inst.xid = (params) => inst.check(_xid(ZodXID, params));
4560
+ inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
4561
+ inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
4562
+ inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
4563
+ inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
4564
+ inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
4565
+ inst.e164 = (params) => inst.check(_e164(ZodE164, params));
4566
+ inst.datetime = (params) => inst.check(datetime(params));
4567
+ inst.date = (params) => inst.check(date(params));
4568
+ inst.time = (params) => inst.check(time(params));
4569
+ inst.duration = (params) => inst.check(duration(params));
4570
+ });
4571
+ function string(params) {
4572
+ return _string(ZodString, params);
4573
+ }
4574
+ const ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
4575
+ $ZodStringFormat.init(inst, def);
4576
+ _ZodString.init(inst, def);
4577
+ });
4578
+ const ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
4579
+ $ZodEmail.init(inst, def);
4580
+ ZodStringFormat.init(inst, def);
4581
+ });
4582
+ const ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
4583
+ $ZodGUID.init(inst, def);
4584
+ ZodStringFormat.init(inst, def);
4585
+ });
4586
+ const ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
4587
+ $ZodUUID.init(inst, def);
4588
+ ZodStringFormat.init(inst, def);
4589
+ });
4590
+ const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
4591
+ $ZodURL.init(inst, def);
4592
+ ZodStringFormat.init(inst, def);
4593
+ });
4594
+ const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
4595
+ $ZodEmoji.init(inst, def);
4596
+ ZodStringFormat.init(inst, def);
4597
+ });
4598
+ const ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
4599
+ $ZodNanoID.init(inst, def);
4600
+ ZodStringFormat.init(inst, def);
4601
+ });
4602
+ const ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
4603
+ $ZodCUID.init(inst, def);
4604
+ ZodStringFormat.init(inst, def);
4605
+ });
4606
+ const ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
4607
+ $ZodCUID2.init(inst, def);
4608
+ ZodStringFormat.init(inst, def);
4609
+ });
4610
+ const ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
4611
+ $ZodULID.init(inst, def);
4612
+ ZodStringFormat.init(inst, def);
4613
+ });
4614
+ const ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
4615
+ $ZodXID.init(inst, def);
4616
+ ZodStringFormat.init(inst, def);
4617
+ });
4618
+ const ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
4619
+ $ZodKSUID.init(inst, def);
4620
+ ZodStringFormat.init(inst, def);
4621
+ });
4622
+ const ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
4623
+ $ZodIPv4.init(inst, def);
4624
+ ZodStringFormat.init(inst, def);
4625
+ });
4626
+ const ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
4627
+ $ZodIPv6.init(inst, def);
4628
+ ZodStringFormat.init(inst, def);
4629
+ });
4630
+ const ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
4631
+ $ZodCIDRv4.init(inst, def);
4632
+ ZodStringFormat.init(inst, def);
4633
+ });
4634
+ const ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
4635
+ $ZodCIDRv6.init(inst, def);
4636
+ ZodStringFormat.init(inst, def);
4637
+ });
4638
+ const ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
4639
+ $ZodBase64.init(inst, def);
4640
+ ZodStringFormat.init(inst, def);
4641
+ });
4642
+ const ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
4643
+ $ZodBase64URL.init(inst, def);
4644
+ ZodStringFormat.init(inst, def);
4645
+ });
4646
+ const ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
4647
+ $ZodE164.init(inst, def);
4648
+ ZodStringFormat.init(inst, def);
4649
+ });
4650
+ const ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
4651
+ $ZodJWT.init(inst, def);
4652
+ ZodStringFormat.init(inst, def);
4653
+ });
4654
+ const ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
4655
+ $ZodNumber.init(inst, def);
4656
+ ZodType.init(inst, def);
4657
+ inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
4658
+ inst.gt = (value, params) => inst.check(_gt(value, params));
4659
+ inst.gte = (value, params) => inst.check(_gte(value, params));
4660
+ inst.min = (value, params) => inst.check(_gte(value, params));
4661
+ inst.lt = (value, params) => inst.check(_lt(value, params));
4662
+ inst.lte = (value, params) => inst.check(_lte(value, params));
4663
+ inst.max = (value, params) => inst.check(_lte(value, params));
4664
+ inst.int = (params) => inst.check(int(params));
4665
+ inst.safe = (params) => inst.check(int(params));
4666
+ inst.positive = (params) => inst.check(_gt(0, params));
4667
+ inst.nonnegative = (params) => inst.check(_gte(0, params));
4668
+ inst.negative = (params) => inst.check(_lt(0, params));
4669
+ inst.nonpositive = (params) => inst.check(_lte(0, params));
4670
+ inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
4671
+ inst.step = (value, params) => inst.check(_multipleOf(value, params));
4672
+ inst.finite = () => inst;
4673
+ const bag = inst._zod.bag;
4674
+ inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
4675
+ inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
4676
+ inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
4677
+ inst.isFinite = true;
4678
+ inst.format = bag.format ?? null;
4679
+ });
4680
+ function number(params) {
4681
+ return _number(ZodNumber, params);
4682
+ }
4683
+ const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
4684
+ $ZodNumberFormat.init(inst, def);
4685
+ ZodNumber.init(inst, def);
4686
+ });
4687
+ function int(params) {
4688
+ return _int(ZodNumberFormat, params);
4689
+ }
2383
4690
  const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
2384
4691
  $ZodUnknown.init(inst, def);
2385
4692
  ZodType.init(inst, def);
@@ -2388,6 +4695,14 @@ const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
2388
4695
  function unknown() {
2389
4696
  return _unknown(ZodUnknown);
2390
4697
  }
4698
+ const ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
4699
+ $ZodNever.init(inst, def);
4700
+ ZodType.init(inst, def);
4701
+ inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
4702
+ });
4703
+ function never(params) {
4704
+ return _never(ZodNever, params);
4705
+ }
2391
4706
  const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
2392
4707
  $ZodArray.init(inst, def);
2393
4708
  ZodType.init(inst, def);
@@ -2402,6 +4717,53 @@ const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
2402
4717
  function array(element, params) {
2403
4718
  return _array(ZodArray, element, params);
2404
4719
  }
4720
+ const ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
4721
+ $ZodObjectJIT.init(inst, def);
4722
+ ZodType.init(inst, def);
4723
+ inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
4724
+ defineLazy(inst, "shape", () => {
4725
+ return def.shape;
4726
+ });
4727
+ inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
4728
+ inst.catchall = (catchall) => inst.clone({
4729
+ ...inst._zod.def,
4730
+ catchall
4731
+ });
4732
+ inst.passthrough = () => inst.clone({
4733
+ ...inst._zod.def,
4734
+ catchall: unknown()
4735
+ });
4736
+ inst.loose = () => inst.clone({
4737
+ ...inst._zod.def,
4738
+ catchall: unknown()
4739
+ });
4740
+ inst.strict = () => inst.clone({
4741
+ ...inst._zod.def,
4742
+ catchall: never()
4743
+ });
4744
+ inst.strip = () => inst.clone({
4745
+ ...inst._zod.def,
4746
+ catchall: void 0
4747
+ });
4748
+ inst.extend = (incoming) => {
4749
+ return extend(inst, incoming);
4750
+ };
4751
+ inst.safeExtend = (incoming) => {
4752
+ return safeExtend(inst, incoming);
4753
+ };
4754
+ inst.merge = (other) => merge(inst, other);
4755
+ inst.pick = (mask) => pick(inst, mask);
4756
+ inst.omit = (mask) => omit(inst, mask);
4757
+ inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
4758
+ inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
4759
+ });
4760
+ function object(shape, params) {
4761
+ return new ZodObject({
4762
+ type: "object",
4763
+ shape: shape ?? {},
4764
+ ...normalizeParams(params)
4765
+ });
4766
+ }
2405
4767
  const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
2406
4768
  $ZodUnion.init(inst, def);
2407
4769
  ZodType.init(inst, def);
@@ -2427,6 +4789,58 @@ function intersection(left, right) {
2427
4789
  right
2428
4790
  });
2429
4791
  }
4792
+ const ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
4793
+ $ZodRecord.init(inst, def);
4794
+ ZodType.init(inst, def);
4795
+ inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
4796
+ inst.keyType = def.keyType;
4797
+ inst.valueType = def.valueType;
4798
+ });
4799
+ function record(keyType, valueType, params) {
4800
+ return new ZodRecord({
4801
+ type: "record",
4802
+ keyType,
4803
+ valueType,
4804
+ ...normalizeParams(params)
4805
+ });
4806
+ }
4807
+ const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
4808
+ $ZodEnum.init(inst, def);
4809
+ ZodType.init(inst, def);
4810
+ inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
4811
+ inst.enum = def.entries;
4812
+ inst.options = Object.values(def.entries);
4813
+ const keys = new Set(Object.keys(def.entries));
4814
+ inst.extract = (values, params) => {
4815
+ const newEntries = {};
4816
+ for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
4817
+ else throw new Error(`Key ${value} not found in enum`);
4818
+ return new ZodEnum({
4819
+ ...def,
4820
+ checks: [],
4821
+ ...normalizeParams(params),
4822
+ entries: newEntries
4823
+ });
4824
+ };
4825
+ inst.exclude = (values, params) => {
4826
+ const newEntries = { ...def.entries };
4827
+ for (const value of values) if (keys.has(value)) delete newEntries[value];
4828
+ else throw new Error(`Key ${value} not found in enum`);
4829
+ return new ZodEnum({
4830
+ ...def,
4831
+ checks: [],
4832
+ ...normalizeParams(params),
4833
+ entries: newEntries
4834
+ });
4835
+ };
4836
+ });
4837
+ function _enum(values, params) {
4838
+ return new ZodEnum({
4839
+ type: "enum",
4840
+ entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values,
4841
+ ...normalizeParams(params)
4842
+ });
4843
+ }
2430
4844
  const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
2431
4845
  $ZodTransform.init(inst, def);
2432
4846
  ZodType.init(inst, def);
@@ -2601,31 +5015,26 @@ let AgentStructuredOutputRunner = class AgentStructuredOutputRunner$1 {
2601
5015
  _AgentStructuredOutputRunner = this;
2602
5016
  }
2603
5017
  static repairAttemptCount = 2;
2604
- constructor(repairPromptFactory, openAiStructuredOutputMethodFactory) {
5018
+ static structuredOutputSchemaName = "agent_output";
5019
+ constructor(repairPromptFactory, openAiStrictJsonSchemaFactory) {
2605
5020
  this.repairPromptFactory = repairPromptFactory;
2606
- this.openAiStructuredOutputMethodFactory = openAiStructuredOutputMethodFactory;
5021
+ this.openAiStrictJsonSchemaFactory = openAiStrictJsonSchemaFactory;
2607
5022
  }
2608
5023
  async resolve(args) {
2609
5024
  let lastFailure;
2610
- if (args.rawFinalResponse) {
2611
- const directResult = this.tryParseAndValidate(AgentMessageFactory.extractContent(args.rawFinalResponse), args.schema);
2612
- if (directResult.ok) return directResult.value;
2613
- lastFailure = directResult;
2614
- } else if (!this.supportsNativeStructuredOutput(args.model)) {
2615
- const rawResponse = await args.invokeTextModel(args.conversation);
2616
- const directResult = this.tryParseAndValidate(AgentMessageFactory.extractContent(rawResponse), args.schema);
5025
+ if (args.rawFinalText !== void 0) {
5026
+ const directResult = this.tryParseAndValidate(args.rawFinalText, args.schema);
2617
5027
  if (directResult.ok) return directResult.value;
2618
5028
  lastFailure = directResult;
2619
5029
  }
2620
5030
  try {
2621
- const nativeStructuredModel = this.createStructuredOutputModel(args.model, args.chatModelConfig, args.schema);
2622
- if (nativeStructuredModel) {
2623
- const nativeResult = this.tryValidateStructuredValue(await args.invokeStructuredModel(nativeStructuredModel, args.conversation), args.schema);
2624
- if (nativeResult.ok) return nativeResult.value;
2625
- lastFailure = nativeResult;
2626
- }
5031
+ const structuredOptions = this.resolveStructuredOutputOptions(args.chatModelConfig);
5032
+ const schemaForModel = this.resolveOutputSchemaForModel(args.schema, structuredOptions);
5033
+ const nativeResult = this.tryValidateStructuredValue(await args.invokeStructuredModel(schemaForModel, args.conversation, structuredOptions), args.schema);
5034
+ if (nativeResult.ok) return nativeResult.value;
5035
+ lastFailure = nativeResult;
2627
5036
  } catch (error) {
2628
- lastFailure = {
5037
+ lastFailure = lastFailure ?? {
2629
5038
  ok: false,
2630
5039
  invalidContent: "",
2631
5040
  validationError: `Native structured output failed: ${this.summarizeError(error)}`
@@ -2649,22 +5058,26 @@ let AgentStructuredOutputRunner = class AgentStructuredOutputRunner$1 {
2649
5058
  validationError: failure.validationError
2650
5059
  }))];
2651
5060
  const repairResponse = await args.invokeTextModel(repairMessages);
2652
- const repairResult = this.tryParseAndValidate(AgentMessageFactory.extractContent(repairResponse), args.schema);
5061
+ const repairResult = this.tryParseAndValidate(repairResponse.text, args.schema);
2653
5062
  if (repairResult.ok) return repairResult.value;
2654
5063
  failure = repairResult;
2655
5064
  }
2656
5065
  throw new Error(`Structured output required for AIAgent "${args.agentName}" (${args.nodeId}) but validation still failed after ${_AgentStructuredOutputRunner.repairAttemptCount} repair attempts: ${failure.validationError}`);
2657
5066
  }
2658
- createStructuredOutputModel(model, chatModelConfig, schema) {
2659
- if (!this.supportsNativeStructuredOutput(model)) return;
2660
- const options = this.getStructuredOutputOptions(chatModelConfig);
2661
- return model.withStructuredOutput(schema, options);
2662
- }
2663
- getStructuredOutputOptions(chatModelConfig) {
2664
- return this.openAiStructuredOutputMethodFactory.create(chatModelConfig) ?? { strict: true };
5067
+ /**
5068
+ * Chooses strict mode for OpenAI chat-model configs, off otherwise. Extendable in future for
5069
+ * other providers that adopt the same "supply a JSON Schema record directly" contract.
5070
+ */
5071
+ resolveStructuredOutputOptions(chatModelConfig) {
5072
+ if (chatModelConfig.type !== OpenAIChatModelFactory) return;
5073
+ return {
5074
+ strict: true,
5075
+ schemaName: _AgentStructuredOutputRunner.structuredOutputSchemaName
5076
+ };
2665
5077
  }
2666
- supportsNativeStructuredOutput(model) {
2667
- return typeof model.withStructuredOutput === "function";
5078
+ resolveOutputSchemaForModel(schema, options) {
5079
+ if (!options?.strict) return schema;
5080
+ return this.openAiStrictJsonSchemaFactory.createStructuredOutputRecord(schema, { schemaName: options.schemaName ?? _AgentStructuredOutputRunner.structuredOutputSchemaName });
2668
5081
  }
2669
5082
  tryParseAndValidate(content, schema) {
2670
5083
  try {
@@ -2698,7 +5111,7 @@ let AgentStructuredOutputRunner = class AgentStructuredOutputRunner$1 {
2698
5111
  }
2699
5112
  toJson(value) {
2700
5113
  try {
2701
- return JSON.stringify(value);
5114
+ return JSON.stringify(value) ?? String(value);
2702
5115
  } catch (error) {
2703
5116
  return `<<unserializable: ${this.summarizeError(error)}>>`;
2704
5117
  }
@@ -2707,8 +5120,8 @@ let AgentStructuredOutputRunner = class AgentStructuredOutputRunner$1 {
2707
5120
  AgentStructuredOutputRunner = _AgentStructuredOutputRunner = __decorate([
2708
5121
  (0, __codemation_core.injectable)(),
2709
5122
  __decorateParam(0, (0, __codemation_core.inject)(AgentStructuredOutputRepairPromptFactory)),
2710
- __decorateParam(1, (0, __codemation_core.inject)(OpenAIStructuredOutputMethodFactory)),
2711
- __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])
5123
+ __decorateParam(1, (0, __codemation_core.inject)(OpenAiStrictJsonSchemaFactory)),
5124
+ __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])
2712
5125
  ], AgentStructuredOutputRunner);
2713
5126
 
2714
5127
  //#endregion
@@ -2845,7 +5258,7 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2845
5258
  async executePlannedToolCall(args) {
2846
5259
  const { plannedToolCall, ctx } = args;
2847
5260
  const toolCallInputsByPort = AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {});
2848
- const invocationId = __codemation_core.ConnectionInvocationIdFactory.create();
5261
+ const invocationId = plannedToolCall.invocationId;
2849
5262
  const startedAt = /* @__PURE__ */ new Date();
2850
5263
  const span = ctx.telemetry.startChildSpan({
2851
5264
  name: "agent.tool.call",
@@ -2853,7 +5266,10 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2853
5266
  startedAt,
2854
5267
  attributes: {
2855
5268
  [__codemation_core.CodemationTelemetryAttributeNames.connectionInvocationId]: invocationId,
2856
- [__codemation_core.CodemationTelemetryAttributeNames.toolName]: plannedToolCall.binding.config.name
5269
+ [__codemation_core.CodemationTelemetryAttributeNames.toolName]: plannedToolCall.binding.config.name,
5270
+ ...ctx.iterationId ? { [__codemation_core.CodemationTelemetryAttributeNames.iterationId]: ctx.iterationId } : {},
5271
+ ...typeof ctx.itemIndex === "number" ? { [__codemation_core.CodemationTelemetryAttributeNames.iterationIndex]: ctx.itemIndex } : {},
5272
+ ...ctx.parentInvocationId ? { [__codemation_core.CodemationTelemetryAttributeNames.parentInvocationId]: ctx.parentInvocationId } : {}
2857
5273
  }
2858
5274
  });
2859
5275
  await ctx.nodeState?.markRunning({
@@ -2861,9 +5277,24 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2861
5277
  activationId: ctx.activationId,
2862
5278
  inputsByPort: toolCallInputsByPort
2863
5279
  });
5280
+ await ctx.nodeState?.appendConnectionInvocation({
5281
+ invocationId,
5282
+ connectionNodeId: plannedToolCall.nodeId,
5283
+ parentAgentNodeId: ctx.nodeId,
5284
+ parentAgentActivationId: ctx.activationId,
5285
+ status: "running",
5286
+ managedInput: this.toJsonValue(plannedToolCall.toolCall.input),
5287
+ queuedAt: startedAt.toISOString(),
5288
+ startedAt: startedAt.toISOString(),
5289
+ iterationId: ctx.iterationId,
5290
+ parentInvocationId: ctx.parentInvocationId
5291
+ });
2864
5292
  try {
2865
- const serialized = await plannedToolCall.binding.langChainTool.invoke(plannedToolCall.toolCall.input ?? {});
2866
- const result = this.parseToolOutput(serialized);
5293
+ const result = await plannedToolCall.binding.execute(plannedToolCall.toolCall.input ?? {}, {
5294
+ parentSpan: span,
5295
+ parentInvocationId: invocationId
5296
+ });
5297
+ const serialized = typeof result === "string" ? result : JSON.stringify(result);
2867
5298
  const finishedAt = /* @__PURE__ */ new Date();
2868
5299
  await ctx.nodeState?.markCompleted({
2869
5300
  nodeId: plannedToolCall.nodeId,
@@ -2895,7 +5326,9 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2895
5326
  managedOutput: this.toJsonValue(result),
2896
5327
  queuedAt: startedAt.toISOString(),
2897
5328
  startedAt: startedAt.toISOString(),
2898
- finishedAt: finishedAt.toISOString()
5329
+ finishedAt: finishedAt.toISOString(),
5330
+ iterationId: ctx.iterationId,
5331
+ parentInvocationId: ctx.parentInvocationId
2899
5332
  });
2900
5333
  return {
2901
5334
  toolName: plannedToolCall.binding.config.name,
@@ -2907,7 +5340,7 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2907
5340
  const classification = this.errorClassifier.classify({
2908
5341
  error,
2909
5342
  toolName: plannedToolCall.binding.config.name,
2910
- schema: plannedToolCall.binding.langChainTool.schema
5343
+ schema: plannedToolCall.binding.inputSchema
2911
5344
  });
2912
5345
  if (classification.kind !== "repairable_validation_error") {
2913
5346
  const effectiveError = classification.effectiveError;
@@ -3036,7 +5469,9 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
3036
5469
  },
3037
5470
  queuedAt: args.startedAt.toISOString(),
3038
5471
  startedAt: args.startedAt.toISOString(),
3039
- finishedAt: finishedAt.toISOString()
5472
+ finishedAt: finishedAt.toISOString(),
5473
+ iterationId: args.ctx.iterationId,
5474
+ parentInvocationId: args.ctx.parentInvocationId
3040
5475
  });
3041
5476
  }
3042
5477
  createRepairPayload(args) {
@@ -3070,14 +5505,6 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
3070
5505
  if (!firstIssue) return `Your previous tool call for "${toolName}" was invalid and did not match the expected schema.`;
3071
5506
  return `Your previous tool call for "${toolName}" was invalid because field "${firstIssue.path.length > 0 ? firstIssue.path.join(".") : "<root>"}" failed validation: ${firstIssue.message}`;
3072
5507
  }
3073
- parseToolOutput(serialized) {
3074
- if (typeof serialized !== "string") return serialized;
3075
- try {
3076
- return JSON.parse(serialized);
3077
- } catch {
3078
- return serialized;
3079
- }
3080
- }
3081
5508
  toJsonValue(value) {
3082
5509
  if (value === void 0) return;
3083
5510
  return JSON.parse(JSON.stringify(value));
@@ -3105,13 +5532,14 @@ AgentToolExecutionCoordinator = __decorate([
3105
5532
 
3106
5533
  //#endregion
3107
5534
  //#region src/nodes/NodeBackedToolRuntime.ts
3108
- var _ref$1, _ref2$1, _ref3$1;
5535
+ var _ref$1, _ref2$1, _ref3$1, _ref4$1;
3109
5536
  let NodeBackedToolRuntime = class NodeBackedToolRuntime$1 {
3110
- constructor(nodeResolver, itemExprResolver, outputNormalizer, outputBehaviorResolver) {
5537
+ constructor(nodeResolver, itemExprResolver, outputNormalizer, outputBehaviorResolver, childExecutionScopeFactory) {
3111
5538
  this.nodeResolver = nodeResolver;
3112
5539
  this.itemExprResolver = itemExprResolver;
3113
5540
  this.outputNormalizer = outputNormalizer;
3114
5541
  this.outputBehaviorResolver = outputBehaviorResolver;
5542
+ this.childExecutionScopeFactory = childExecutionScopeFactory;
3115
5543
  }
3116
5544
  async execute(config$1, args) {
3117
5545
  const nodeInput = config$1.toNodeItem({
@@ -3122,10 +5550,7 @@ let NodeBackedToolRuntime = class NodeBackedToolRuntime$1 {
3122
5550
  ctx: args.ctx,
3123
5551
  node: config$1.node
3124
5552
  });
3125
- const nodeCtx = {
3126
- ...args.ctx,
3127
- config: config$1.node
3128
- };
5553
+ const nodeCtx = this.resolveNodeCtx(config$1, args);
3129
5554
  const resolvedNode = this.nodeResolver.resolve(config$1.node.type);
3130
5555
  const outputs = await this.executeResolvedNode(resolvedNode, nodeInput, nodeCtx);
3131
5556
  return config$1.toToolOutput({
@@ -3138,6 +5563,35 @@ let NodeBackedToolRuntime = class NodeBackedToolRuntime$1 {
3138
5563
  outputs
3139
5564
  });
3140
5565
  }
5566
+ /**
5567
+ * Returns a re-rooted child ctx for nested-agent tools (so their LLM/tool connection ids derive
5568
+ * from the tool connection node, telemetry parents under the tool-call span, and connection
5569
+ * invocations carry `parentInvocationId`). Plain runnable tools (non-agent) keep the orchestrator
5570
+ * ctx with only `config` swapped — no nesting concern.
5571
+ *
5572
+ * The caller (`AIAgentNode.createItemScopedTools`) already wraps the orchestrator ctx via
5573
+ * `ConnectionCredentialExecutionContextFactory.forConnectionNode`, so `args.ctx.nodeId` is the
5574
+ * tool's own connection node id (e.g. `AIAgentNode:2__conn__tool__searchInMail`). We pass that
5575
+ * through as the sub-agent's `nodeId`; deriving another `toolConnectionNodeId(args.ctx.nodeId,
5576
+ * config.name)` here would prepend a duplicate `__conn__tool__<name>` segment and exponentially
5577
+ * deepen ids on each invocation, which also breaks credential resolution because user-provided
5578
+ * bindings sit on the single-level connection node id.
5579
+ */
5580
+ resolveNodeCtx(config$1, args) {
5581
+ const isNestedAgent = __codemation_core.AgentConfigInspector.isAgentNodeConfig(config$1.node);
5582
+ const hooks = args.hooks;
5583
+ if (!isNestedAgent || !hooks?.parentSpan || !hooks.parentInvocationId) return {
5584
+ ...args.ctx,
5585
+ config: config$1.node
5586
+ };
5587
+ return this.childExecutionScopeFactory.forSubAgent({
5588
+ parentCtx: args.ctx,
5589
+ childNodeId: args.ctx.nodeId,
5590
+ childConfig: config$1.node,
5591
+ parentInvocationId: hooks.parentInvocationId,
5592
+ parentSpan: hooks.parentSpan
5593
+ });
5594
+ }
3141
5595
  async executeResolvedNode(resolvedNode, nodeInput, ctx) {
3142
5596
  if (this.isMultiInputNode(resolvedNode)) return await resolvedNode.executeMulti({ in: [nodeInput] }, ctx);
3143
5597
  if (this.isRunnableNode(resolvedNode)) {
@@ -3175,11 +5629,13 @@ NodeBackedToolRuntime = __decorate([
3175
5629
  __decorateParam(1, (0, __codemation_core.inject)(__codemation_core.ItemExprResolver)),
3176
5630
  __decorateParam(2, (0, __codemation_core.inject)(__codemation_core.NodeOutputNormalizer)),
3177
5631
  __decorateParam(3, (0, __codemation_core.inject)(__codemation_core.RunnableOutputBehaviorResolver)),
5632
+ __decorateParam(4, (0, __codemation_core.inject)(__codemation_core.ChildExecutionScopeFactory)),
3178
5633
  __decorateMetadata("design:paramtypes", [
3179
5634
  Object,
3180
5635
  typeof (_ref$1 = typeof __codemation_core.ItemExprResolver !== "undefined" && __codemation_core.ItemExprResolver) === "function" ? _ref$1 : Object,
3181
5636
  typeof (_ref2$1 = typeof __codemation_core.NodeOutputNormalizer !== "undefined" && __codemation_core.NodeOutputNormalizer) === "function" ? _ref2$1 : Object,
3182
- typeof (_ref3$1 = typeof __codemation_core.RunnableOutputBehaviorResolver !== "undefined" && __codemation_core.RunnableOutputBehaviorResolver) === "function" ? _ref3$1 : Object
5637
+ typeof (_ref3$1 = typeof __codemation_core.RunnableOutputBehaviorResolver !== "undefined" && __codemation_core.RunnableOutputBehaviorResolver) === "function" ? _ref3$1 : Object,
5638
+ typeof (_ref4$1 = typeof __codemation_core.ChildExecutionScopeFactory !== "undefined" && __codemation_core.ChildExecutionScopeFactory) === "function" ? _ref4$1 : Object
3183
5639
  ])
3184
5640
  ], NodeBackedToolRuntime);
3185
5641
 
@@ -3197,14 +5653,8 @@ var _ref, _ref2, _ref3, _ref4;
3197
5653
  let AIAgentNode = class AIAgentNode$1 {
3198
5654
  kind = "node";
3199
5655
  outputPorts = ["main"];
3200
- /**
3201
- * Engine validates {@link RunnableNodeConfig.inputSchema} (Zod) on {@code item.json} before enqueue, then resolves
3202
- * per-item **`itemExpr`** leaves on config before {@link #execute}. Prefer modeling prompts as
3203
- * {@code { messages: [{ role, content }, ...] }} (on input or config) so persisted inputs are visible in the UI.
3204
- */
3205
5656
  inputSchema = unknown();
3206
5657
  connectionCredentialExecutionContextFactory;
3207
- /** One resolved model/tools bundle per activation context (same ctx across items in a batch). */
3208
5658
  preparedByExecutionContext = /* @__PURE__ */ new WeakMap();
3209
5659
  constructor(nodeResolver, credentialSessions, nodeBackedToolRuntime, executionHelpers, structuredOutputRunner, toolExecutionCoordinator) {
3210
5660
  this.nodeResolver = nodeResolver;
@@ -3235,9 +5685,6 @@ let AIAgentNode = class AIAgentNode$1 {
3235
5685
  throw error;
3236
5686
  }
3237
5687
  }
3238
- /**
3239
- * Resolves the chat model and tools once per activation, then reuses for every item in the batch.
3240
- */
3241
5688
  async prepareExecution(ctx) {
3242
5689
  const chatModelFactory = this.nodeResolver.resolve(ctx.config.chatModel.type);
3243
5690
  const languageModelCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {
@@ -3255,9 +5702,6 @@ let AIAgentNode = class AIAgentNode$1 {
3255
5702
  languageModelConnectionNodeId: __codemation_core.ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId)
3256
5703
  };
3257
5704
  }
3258
- /**
3259
- * One item: build prompts, optionally bind tools, run the multi-turn loop, map the final model message to workflow JSON.
3260
- */
3261
5705
  async runAgentForItem(prepared, item, itemIndex, items) {
3262
5706
  const { ctx } = prepared;
3263
5707
  const itemInputsByPort = AgentItemPortMap.fromItem(item);
@@ -3271,8 +5715,8 @@ let AIAgentNode = class AIAgentNode$1 {
3271
5715
  conversation,
3272
5716
  agentName: this.getAgentDisplayName(ctx),
3273
5717
  nodeId: ctx.nodeId,
3274
- invokeTextModel: async (messages) => await this.invokeModel(prepared.model, prepared.languageModelConnectionNodeId, messages, ctx, itemInputsByPort, prepared.guardrails.modelInvocationOptions),
3275
- invokeStructuredModel: async (structuredModel, messages) => await this.invokeStructuredModel(structuredModel, prepared.languageModelConnectionNodeId, messages, ctx, itemInputsByPort, prepared.guardrails.modelInvocationOptions)
5718
+ invokeTextModel: async (messages) => await this.invokeTextTurn(prepared, itemInputsByPort, messages, []),
5719
+ invokeStructuredModel: async (schema, messages, structuredOptions) => await this.invokeStructuredTurn(prepared, itemInputsByPort, schema, messages, structuredOptions)
3276
5720
  });
3277
5721
  await ctx.telemetry.recordMetric({
3278
5722
  name: __codemation_core.CodemationTelemetryMetricNames.agentTurns,
@@ -3284,13 +5728,11 @@ let AIAgentNode = class AIAgentNode$1 {
3284
5728
  });
3285
5729
  return this.buildOutputItem(item, structuredOutput);
3286
5730
  }
3287
- const modelWithTools = this.bindToolsToModel(prepared.model, itemScopedTools);
3288
5731
  const loopResult = await this.runTurnLoopUntilFinalAnswer({
3289
5732
  prepared,
3290
5733
  itemInputsByPort,
3291
5734
  itemScopedTools,
3292
- conversation,
3293
- modelWithTools
5735
+ conversation
3294
5736
  });
3295
5737
  await ctx.telemetry.recordMetric({
3296
5738
  name: __codemation_core.CodemationTelemetryMetricNames.agentTurns,
@@ -3300,30 +5742,34 @@ let AIAgentNode = class AIAgentNode$1 {
3300
5742
  name: __codemation_core.CodemationTelemetryMetricNames.agentToolCalls,
3301
5743
  value: loopResult.toolCallCount
3302
5744
  });
3303
- const outputJson = await this.resolveFinalOutputJson(prepared, itemInputsByPort, conversation, loopResult.finalResponse, itemScopedTools.length > 0);
5745
+ const outputJson = await this.resolveFinalOutputJson(prepared, itemInputsByPort, conversation, loopResult.finalText, itemScopedTools.length > 0);
3304
5746
  return this.buildOutputItem(item, outputJson);
3305
5747
  }
3306
5748
  /**
3307
- * Repeatedly invokes the model until it returns without tool calls, or guardrails end the loop.
5749
+ * Multi-turn loop:
5750
+ * - Each turn is a single `generateText` call with tools exposed but **not auto-executed**
5751
+ * (we control tool dispatch so that {@link AgentToolExecutionCoordinator} drives repair /
5752
+ * connection-invocation recording / transient-error handling exactly like before).
5753
+ * - When the model returns no tool calls the loop ends with the model's text as the final answer.
5754
+ * - Respects `guardrails.maxTurns` and `guardrails.onTurnLimitReached`.
3308
5755
  */
3309
5756
  async runTurnLoopUntilFinalAnswer(args) {
3310
- const { prepared, itemInputsByPort, itemScopedTools, conversation, modelWithTools } = args;
3311
- const { ctx, guardrails, languageModelConnectionNodeId } = prepared;
3312
- let finalResponse;
5757
+ const { prepared, itemInputsByPort, itemScopedTools, conversation } = args;
5758
+ const { ctx, guardrails } = prepared;
5759
+ let finalText = "";
3313
5760
  let toolCallCount = 0;
3314
5761
  let turnCount = 0;
3315
5762
  const repairAttemptsByToolName = /* @__PURE__ */ new Map();
3316
5763
  for (let turn = 1; turn <= guardrails.maxTurns; turn++) {
3317
5764
  turnCount = turn;
3318
- const response = await this.invokeModel(modelWithTools, languageModelConnectionNodeId, conversation, ctx, itemInputsByPort, guardrails.modelInvocationOptions);
3319
- finalResponse = response;
3320
- const toolCalls = AgentMessageFactory.extractToolCalls(response);
3321
- if (toolCalls.length === 0) break;
5765
+ const result = await this.invokeTextTurn(prepared, itemInputsByPort, conversation, itemScopedTools);
5766
+ finalText = result.text;
5767
+ if (result.toolCalls.length === 0) break;
3322
5768
  if (this.cannotExecuteAnotherToolRound(turn, guardrails)) {
3323
5769
  this.finishOrThrowWhenTurnCapHitWithToolCalls(ctx, guardrails);
3324
5770
  break;
3325
5771
  }
3326
- const plannedToolCalls = this.planToolCalls(itemScopedTools, toolCalls, ctx.nodeId);
5772
+ const plannedToolCalls = this.planToolCalls(itemScopedTools, result.toolCalls, ctx.nodeId);
3327
5773
  toolCallCount += plannedToolCalls.length;
3328
5774
  await this.markQueuedTools(plannedToolCalls, ctx);
3329
5775
  const executedToolCalls = await this.toolExecutionCoordinator.execute({
@@ -3332,11 +5778,10 @@ let AIAgentNode = class AIAgentNode$1 {
3332
5778
  agentName: this.getAgentDisplayName(ctx),
3333
5779
  repairAttemptsByToolName
3334
5780
  });
3335
- this.appendAssistantAndToolMessages(conversation, response, executedToolCalls);
5781
+ this.appendAssistantAndToolMessages(conversation, result.assistantMessage, result.text, result.toolCalls, executedToolCalls);
3336
5782
  }
3337
- if (!finalResponse) throw new Error(`AIAgent "${ctx.config.name ?? ctx.nodeId}" did not produce a model response.`);
3338
5783
  return {
3339
- finalResponse,
5784
+ finalText,
3340
5785
  turnCount,
3341
5786
  toolCallCount
3342
5787
  };
@@ -3348,30 +5793,30 @@ let AIAgentNode = class AIAgentNode$1 {
3348
5793
  if (guardrails.onTurnLimitReached === "respondWithLastMessage") return;
3349
5794
  throw new Error(`AIAgent "${ctx.config.name ?? ctx.nodeId}" reached maxTurns=${guardrails.maxTurns} before producing a final response.`);
3350
5795
  }
3351
- appendAssistantAndToolMessages(conversation, assistantMessage, executedToolCalls) {
3352
- conversation.push(assistantMessage, ...executedToolCalls.map((toolCall) => AgentMessageFactory.createToolMessage(toolCall.toolCallId, toolCall.serialized)));
5796
+ appendAssistantAndToolMessages(conversation, assistantMessage, text, toolCalls, executedToolCalls) {
5797
+ conversation.push(assistantMessage ?? AgentMessageFactory.createAssistantWithToolCalls(text, toolCalls), AgentMessageFactory.createToolResultsMessage(executedToolCalls));
3353
5798
  }
3354
- async resolveFinalOutputJson(prepared, itemInputsByPort, conversation, finalResponse, wasToolEnabledRun) {
3355
- if (!prepared.ctx.config.outputSchema) return AgentOutputFactory.fromAgentContent(AgentMessageFactory.extractContent(finalResponse));
5799
+ async resolveFinalOutputJson(prepared, itemInputsByPort, conversation, finalText, wasToolEnabledRun) {
5800
+ if (!prepared.ctx.config.outputSchema) return AgentOutputFactory.fromAgentContent(finalText);
5801
+ const conversationWithFinal = wasToolEnabledRun ? [...conversation, {
5802
+ role: "assistant",
5803
+ content: finalText
5804
+ }] : conversation;
3356
5805
  return await this.structuredOutputRunner.resolve({
3357
5806
  model: prepared.model,
3358
5807
  chatModelConfig: prepared.ctx.config.chatModel,
3359
5808
  schema: prepared.ctx.config.outputSchema,
3360
- conversation: wasToolEnabledRun ? [...conversation, finalResponse] : conversation,
3361
- rawFinalResponse: finalResponse,
5809
+ conversation: conversationWithFinal,
5810
+ rawFinalText: finalText,
3362
5811
  agentName: this.getAgentDisplayName(prepared.ctx),
3363
5812
  nodeId: prepared.ctx.nodeId,
3364
- invokeTextModel: async (messages) => await this.invokeModel(prepared.model, prepared.languageModelConnectionNodeId, messages, prepared.ctx, itemInputsByPort, prepared.guardrails.modelInvocationOptions),
3365
- invokeStructuredModel: async (structuredModel, messages) => await this.invokeStructuredModel(structuredModel, prepared.languageModelConnectionNodeId, messages, prepared.ctx, itemInputsByPort, prepared.guardrails.modelInvocationOptions)
5813
+ invokeTextModel: async (messages) => await this.invokeTextTurn(prepared, itemInputsByPort, messages, []),
5814
+ invokeStructuredModel: async (schema, messages, structuredOptions) => await this.invokeStructuredTurn(prepared, itemInputsByPort, schema, messages, structuredOptions)
3366
5815
  });
3367
5816
  }
3368
5817
  buildOutputItem(item, outputJson) {
3369
5818
  return AgentOutputFactory.replaceJson(item, outputJson);
3370
5819
  }
3371
- bindToolsToModel(model, itemScopedTools) {
3372
- if (itemScopedTools.length === 0 || !model.bindTools) return model;
3373
- return model.bindTools(itemScopedTools.map((entry) => entry.langChainTool));
3374
- }
3375
5820
  resolveTools(toolConfigs) {
3376
5821
  const resolvedTools = toolConfigs.map((config$1) => ({
3377
5822
  config: config$1,
@@ -3390,38 +5835,120 @@ let AIAgentNode = class AIAgentNode$1 {
3390
5835
  connectionNodeId: __codemation_core.ConnectionNodeIdFactory.toolConnectionNodeId(ctx.nodeId, entry.config.name),
3391
5836
  getCredentialRequirements: () => entry.config.getCredentialRequirements?.() ?? []
3392
5837
  });
3393
- const langChainTool = this.executionHelpers.createDynamicStructuredTool(entry, toolCredentialContext, item, itemIndex, items);
3394
5838
  return {
3395
5839
  config: entry.config,
3396
- langChainTool
5840
+ inputSchema: entry.runtime.inputSchema,
5841
+ execute: async (input, hooks) => {
5842
+ const validated = entry.runtime.inputSchema.parse(input);
5843
+ return await entry.runtime.execute({
5844
+ config: entry.config,
5845
+ input: validated,
5846
+ ctx: toolCredentialContext,
5847
+ item,
5848
+ itemIndex,
5849
+ items,
5850
+ hooks
5851
+ });
5852
+ }
3397
5853
  };
3398
5854
  });
3399
5855
  }
3400
- async invokeModel(model, nodeId, messages, ctx, inputsByPort, options) {
5856
+ /**
5857
+ * Builds an AI SDK {@link ToolSet} where every tool ships a pre-converted JSON Schema (via
5858
+ * {@link jsonSchema}) — not the raw Zod schema — and carries **no** `execute`. Two reasons:
5859
+ *
5860
+ * 1. Codemation owns tool dispatch + the per-tool repair loop (see {@link AgentToolExecutionCoordinator}),
5861
+ * so the AI SDK must surface tool calls back to us instead of auto-running them.
5862
+ * 2. The AI SDK's `asSchema` helper discriminates between Zod v3 / Zod v4 / Standard Schema via
5863
+ * runtime feature-detection (`~standard`, `_zod`, etc.). Handing it a pre-built
5864
+ * {@link jsonSchema} record — which is tagged with `Symbol.for('vercel.ai.schema')` — skips all
5865
+ * of that detection and guarantees the provider receives a draft-07 JSON Schema with
5866
+ * `additionalProperties: false` at every object depth (see {@link OpenAiStrictJsonSchemaFactory}
5867
+ * for the same logic applied to structured-output schemas). Codemation still runs its own Zod
5868
+ * validation on tool inputs before execute — the schema handed to the model is advisory.
5869
+ */
5870
+ buildToolSet(itemScopedTools) {
5871
+ if (itemScopedTools.length === 0) return void 0;
5872
+ const toolSet = {};
5873
+ for (const entry of itemScopedTools) {
5874
+ const schemaRecord = this.executionHelpers.createJsonSchemaRecord(entry.inputSchema, {
5875
+ schemaName: entry.config.name,
5876
+ requireObjectRoot: true
5877
+ });
5878
+ toolSet[entry.config.name] = {
5879
+ description: entry.config.description,
5880
+ inputSchema: (0, ai.jsonSchema)(schemaRecord)
5881
+ };
5882
+ }
5883
+ return toolSet;
5884
+ }
5885
+ /**
5886
+ * One `generateText` turn (no auto tool execution) with Codemation-owned child-span telemetry
5887
+ * and connection-invocation state recording.
5888
+ */
5889
+ async invokeTextTurn(prepared, itemInputsByPort, messages, itemScopedTools) {
3401
5890
  const invocationId = __codemation_core.ConnectionInvocationIdFactory.create();
3402
5891
  const startedAt = /* @__PURE__ */ new Date();
3403
5892
  const summarizedInput = this.summarizeLlmMessages(messages);
5893
+ const { ctx, model, languageModelConnectionNodeId, guardrails } = prepared;
3404
5894
  const span = this.createModelInvocationSpan(ctx, invocationId, startedAt);
3405
5895
  await ctx.nodeState?.markQueued({
3406
- nodeId,
5896
+ nodeId: languageModelConnectionNodeId,
3407
5897
  activationId: ctx.activationId,
3408
- inputsByPort
5898
+ inputsByPort: itemInputsByPort
5899
+ });
5900
+ await ctx.nodeState?.appendConnectionInvocation({
5901
+ invocationId,
5902
+ connectionNodeId: languageModelConnectionNodeId,
5903
+ parentAgentNodeId: ctx.nodeId,
5904
+ parentAgentActivationId: ctx.activationId,
5905
+ status: "queued",
5906
+ managedInput: summarizedInput,
5907
+ queuedAt: startedAt.toISOString(),
5908
+ iterationId: ctx.iterationId,
5909
+ itemIndex: ctx.itemIndex,
5910
+ parentInvocationId: ctx.parentInvocationId
3409
5911
  });
3410
5912
  await ctx.nodeState?.markRunning({
3411
- nodeId,
5913
+ nodeId: languageModelConnectionNodeId,
3412
5914
  activationId: ctx.activationId,
3413
- inputsByPort
5915
+ inputsByPort: itemInputsByPort
5916
+ });
5917
+ await ctx.nodeState?.appendConnectionInvocation({
5918
+ invocationId,
5919
+ connectionNodeId: languageModelConnectionNodeId,
5920
+ parentAgentNodeId: ctx.nodeId,
5921
+ parentAgentActivationId: ctx.activationId,
5922
+ status: "running",
5923
+ managedInput: summarizedInput,
5924
+ queuedAt: startedAt.toISOString(),
5925
+ startedAt: startedAt.toISOString(),
5926
+ iterationId: ctx.iterationId,
5927
+ itemIndex: ctx.itemIndex,
5928
+ parentInvocationId: ctx.parentInvocationId
3414
5929
  });
3415
5930
  try {
3416
- const response = await model.invoke(messages, options);
5931
+ const tools = this.buildToolSet(itemScopedTools);
5932
+ const callOptions = this.resolveCallOptions(model, guardrails.modelInvocationOptions);
5933
+ const result = await (0, ai.generateText)({
5934
+ model: model.languageModel,
5935
+ messages: [...messages],
5936
+ tools,
5937
+ toolChoice: tools ? "auto" : void 0,
5938
+ maxOutputTokens: callOptions.maxOutputTokens,
5939
+ temperature: callOptions.temperature,
5940
+ providerOptions: callOptions.providerOptions,
5941
+ maxRetries: 0
5942
+ });
5943
+ const turnResult = this.extractTurnResult(result);
3417
5944
  const finishedAt = /* @__PURE__ */ new Date();
5945
+ const managedOutput = this.summarizeTurnOutput(turnResult);
3418
5946
  await ctx.nodeState?.markCompleted({
3419
- nodeId,
5947
+ nodeId: languageModelConnectionNodeId,
3420
5948
  activationId: ctx.activationId,
3421
- inputsByPort,
3422
- outputs: AgentOutputFactory.fromUnknown({ content: AgentMessageFactory.extractContent(response) })
5949
+ inputsByPort: itemInputsByPort,
5950
+ outputs: AgentOutputFactory.fromUnknown(managedOutput)
3423
5951
  });
3424
- const content = AgentMessageFactory.extractContent(response);
3425
5952
  await span.attachArtifact({
3426
5953
  kind: "ai.messages",
3427
5954
  contentType: "application/json",
@@ -3430,26 +5957,29 @@ let AIAgentNode = class AIAgentNode$1 {
3430
5957
  await span.attachArtifact({
3431
5958
  kind: "ai.response",
3432
5959
  contentType: "application/json",
3433
- previewJson: content
5960
+ previewJson: turnResult.text
3434
5961
  });
3435
- await this.recordModelUsageMetrics(span, response, ctx);
5962
+ await this.recordModelUsageMetrics(span, turnResult.usage, ctx);
3436
5963
  await span.end({
3437
5964
  status: "ok",
3438
5965
  endedAt: finishedAt
3439
5966
  });
3440
5967
  await ctx.nodeState?.appendConnectionInvocation({
3441
5968
  invocationId,
3442
- connectionNodeId: nodeId,
5969
+ connectionNodeId: languageModelConnectionNodeId,
3443
5970
  parentAgentNodeId: ctx.nodeId,
3444
5971
  parentAgentActivationId: ctx.activationId,
3445
5972
  status: "completed",
3446
5973
  managedInput: summarizedInput,
3447
- managedOutput: content,
5974
+ managedOutput,
3448
5975
  queuedAt: startedAt.toISOString(),
3449
5976
  startedAt: startedAt.toISOString(),
3450
- finishedAt: finishedAt.toISOString()
5977
+ finishedAt: finishedAt.toISOString(),
5978
+ iterationId: ctx.iterationId,
5979
+ itemIndex: ctx.itemIndex,
5980
+ parentInvocationId: ctx.parentInvocationId
3451
5981
  });
3452
- return response;
5982
+ return turnResult;
3453
5983
  } catch (error) {
3454
5984
  await span.end({
3455
5985
  status: "error",
@@ -3460,36 +5990,78 @@ let AIAgentNode = class AIAgentNode$1 {
3460
5990
  error,
3461
5991
  invocationId,
3462
5992
  startedAt,
3463
- nodeId,
5993
+ nodeId: languageModelConnectionNodeId,
3464
5994
  ctx,
3465
- inputsByPort,
3466
- managedInput: this.summarizeLlmMessages(messages)
5995
+ inputsByPort: itemInputsByPort,
5996
+ managedInput: summarizedInput
3467
5997
  });
3468
5998
  }
3469
5999
  }
3470
- async invokeStructuredModel(model, nodeId, messages, ctx, inputsByPort, options) {
6000
+ /**
6001
+ * Structured-output turn: runs `generateText({ output: Output.object({ schema }) })` via the
6002
+ * structured-output runner. We keep this as a separate helper because the runner needs the raw
6003
+ * validated value (not just text) back, and must be able to retry on Zod failures.
6004
+ */
6005
+ async invokeStructuredTurn(prepared, itemInputsByPort, schema, messages, structuredOptions) {
3471
6006
  const invocationId = __codemation_core.ConnectionInvocationIdFactory.create();
3472
6007
  const startedAt = /* @__PURE__ */ new Date();
3473
6008
  const summarizedInput = this.summarizeLlmMessages(messages);
6009
+ const { ctx, model, languageModelConnectionNodeId, guardrails } = prepared;
3474
6010
  const span = this.createModelInvocationSpan(ctx, invocationId, startedAt);
3475
6011
  await ctx.nodeState?.markQueued({
3476
- nodeId,
6012
+ nodeId: languageModelConnectionNodeId,
3477
6013
  activationId: ctx.activationId,
3478
- inputsByPort
6014
+ inputsByPort: itemInputsByPort
6015
+ });
6016
+ await ctx.nodeState?.appendConnectionInvocation({
6017
+ invocationId,
6018
+ connectionNodeId: languageModelConnectionNodeId,
6019
+ parentAgentNodeId: ctx.nodeId,
6020
+ parentAgentActivationId: ctx.activationId,
6021
+ status: "queued",
6022
+ managedInput: summarizedInput,
6023
+ queuedAt: startedAt.toISOString(),
6024
+ iterationId: ctx.iterationId,
6025
+ itemIndex: ctx.itemIndex,
6026
+ parentInvocationId: ctx.parentInvocationId
3479
6027
  });
3480
6028
  await ctx.nodeState?.markRunning({
3481
- nodeId,
6029
+ nodeId: languageModelConnectionNodeId,
3482
6030
  activationId: ctx.activationId,
3483
- inputsByPort
6031
+ inputsByPort: itemInputsByPort
6032
+ });
6033
+ await ctx.nodeState?.appendConnectionInvocation({
6034
+ invocationId,
6035
+ connectionNodeId: languageModelConnectionNodeId,
6036
+ parentAgentNodeId: ctx.nodeId,
6037
+ parentAgentActivationId: ctx.activationId,
6038
+ status: "running",
6039
+ managedInput: summarizedInput,
6040
+ queuedAt: startedAt.toISOString(),
6041
+ startedAt: startedAt.toISOString(),
6042
+ iterationId: ctx.iterationId,
6043
+ itemIndex: ctx.itemIndex,
6044
+ parentInvocationId: ctx.parentInvocationId
3484
6045
  });
3485
6046
  try {
3486
- const response = await model.invoke(messages, options);
6047
+ const callOptions = this.resolveCallOptions(model, guardrails.modelInvocationOptions);
6048
+ const outputSchema = structuredOptions?.strict && !this.isZodSchema(schema) ? ai.Output.object({ schema: (0, ai.jsonSchema)(schema) }) : ai.Output.object({ schema });
6049
+ const result = await (0, ai.generateText)({
6050
+ model: model.languageModel,
6051
+ messages: [...messages],
6052
+ experimental_output: outputSchema,
6053
+ maxOutputTokens: callOptions.maxOutputTokens,
6054
+ temperature: callOptions.temperature,
6055
+ providerOptions: callOptions.providerOptions,
6056
+ maxRetries: 0
6057
+ });
6058
+ const turnResult = this.extractTurnResult(result);
3487
6059
  const finishedAt = /* @__PURE__ */ new Date();
3488
6060
  await ctx.nodeState?.markCompleted({
3489
- nodeId,
6061
+ nodeId: languageModelConnectionNodeId,
3490
6062
  activationId: ctx.activationId,
3491
- inputsByPort,
3492
- outputs: AgentOutputFactory.fromUnknown(response)
6063
+ inputsByPort: itemInputsByPort,
6064
+ outputs: AgentOutputFactory.fromUnknown(result.experimental_output)
3493
6065
  });
3494
6066
  await span.attachArtifact({
3495
6067
  kind: "ai.messages",
@@ -3499,26 +6071,29 @@ let AIAgentNode = class AIAgentNode$1 {
3499
6071
  await span.attachArtifact({
3500
6072
  kind: "ai.response.structured",
3501
6073
  contentType: "application/json",
3502
- previewJson: this.resultToJsonValue(response)
6074
+ previewJson: this.resultToJsonValue(result.experimental_output)
3503
6075
  });
3504
- await this.recordModelUsageMetrics(span, response, ctx);
6076
+ await this.recordModelUsageMetrics(span, turnResult.usage, ctx);
3505
6077
  await span.end({
3506
6078
  status: "ok",
3507
6079
  endedAt: finishedAt
3508
6080
  });
3509
6081
  await ctx.nodeState?.appendConnectionInvocation({
3510
6082
  invocationId,
3511
- connectionNodeId: nodeId,
6083
+ connectionNodeId: languageModelConnectionNodeId,
3512
6084
  parentAgentNodeId: ctx.nodeId,
3513
6085
  parentAgentActivationId: ctx.activationId,
3514
6086
  status: "completed",
3515
6087
  managedInput: summarizedInput,
3516
- managedOutput: this.resultToJsonValue(response),
6088
+ managedOutput: this.resultToJsonValue(result.experimental_output),
3517
6089
  queuedAt: startedAt.toISOString(),
3518
6090
  startedAt: startedAt.toISOString(),
3519
- finishedAt: finishedAt.toISOString()
6091
+ finishedAt: finishedAt.toISOString(),
6092
+ iterationId: ctx.iterationId,
6093
+ itemIndex: ctx.itemIndex,
6094
+ parentInvocationId: ctx.parentInvocationId
3520
6095
  });
3521
- return response;
6096
+ return result.experimental_output;
3522
6097
  } catch (error) {
3523
6098
  await span.end({
3524
6099
  status: "error",
@@ -3529,13 +6104,77 @@ let AIAgentNode = class AIAgentNode$1 {
3529
6104
  error,
3530
6105
  invocationId,
3531
6106
  startedAt,
3532
- nodeId,
6107
+ nodeId: languageModelConnectionNodeId,
3533
6108
  ctx,
3534
- inputsByPort,
3535
- managedInput: this.summarizeLlmMessages(messages)
6109
+ inputsByPort: itemInputsByPort,
6110
+ managedInput: summarizedInput
3536
6111
  });
3537
6112
  }
3538
6113
  }
6114
+ isZodSchema(schema) {
6115
+ return typeof schema.parse === "function";
6116
+ }
6117
+ resolveCallOptions(model, overrides) {
6118
+ const defaults = model.defaultCallOptions ?? {};
6119
+ return {
6120
+ maxOutputTokens: overrides?.maxTokens ?? defaults.maxOutputTokens,
6121
+ temperature: defaults.temperature,
6122
+ providerOptions: overrides?.providerOptions ?? defaults.providerOptions
6123
+ };
6124
+ }
6125
+ /**
6126
+ * Build a no-code-friendly output payload for an LLM round.
6127
+ *
6128
+ * Always includes `content` (matching the canvas snapshot shape used elsewhere) and adds a
6129
+ * `toolCalls` array when the round produced tool calls so the execution inspector surfaces the
6130
+ * planned calls instead of just an empty `""` for tool-only rounds.
6131
+ */
6132
+ summarizeTurnOutput(turnResult) {
6133
+ if (turnResult.toolCalls.length === 0) return { content: turnResult.text };
6134
+ const toolCalls = turnResult.toolCalls.map((toolCall) => ({
6135
+ name: toolCall.name,
6136
+ args: this.resultToJsonValue(toolCall.input) ?? null
6137
+ }));
6138
+ return {
6139
+ content: turnResult.text,
6140
+ toolCalls
6141
+ };
6142
+ }
6143
+ extractTurnResult(result) {
6144
+ const usage = this.extractUsageFromResult(result);
6145
+ const text = result.text;
6146
+ const toolCalls = result.toolCalls.map((toolCall) => ({
6147
+ id: toolCall.toolCallId,
6148
+ name: toolCall.toolName,
6149
+ input: toolCall.input
6150
+ }));
6151
+ return {
6152
+ assistantMessage: this.extractAssistantMessage(result),
6153
+ text,
6154
+ toolCalls,
6155
+ usage
6156
+ };
6157
+ }
6158
+ extractAssistantMessage(result) {
6159
+ const assistantMessages = result.response.messages.filter((m) => m.role === "assistant");
6160
+ return assistantMessages[assistantMessages.length - 1];
6161
+ }
6162
+ extractUsageFromResult(result) {
6163
+ const usage = result.usage;
6164
+ const inputTokens = this.toFiniteNumber(usage.inputTokens);
6165
+ const outputTokens = this.toFiniteNumber(usage.outputTokens);
6166
+ return {
6167
+ inputTokens,
6168
+ outputTokens,
6169
+ totalTokens: this.toFiniteNumber(usage.totalTokens) ?? (inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0),
6170
+ cachedInputTokens: this.toFiniteNumber(usage.cachedInputTokens),
6171
+ reasoningTokens: this.toFiniteNumber(usage.reasoningTokens)
6172
+ };
6173
+ }
6174
+ toFiniteNumber(value) {
6175
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
6176
+ return value;
6177
+ }
3539
6178
  createModelInvocationSpan(ctx, invocationId, startedAt) {
3540
6179
  return ctx.telemetry.startChildSpan({
3541
6180
  name: "gen_ai.chat.completion",
@@ -3544,13 +6183,22 @@ let AIAgentNode = class AIAgentNode$1 {
3544
6183
  attributes: {
3545
6184
  [__codemation_core.CodemationTelemetryAttributeNames.connectionInvocationId]: invocationId,
3546
6185
  [__codemation_core.GenAiTelemetryAttributeNames.operationName]: "chat",
3547
- [__codemation_core.GenAiTelemetryAttributeNames.requestModel]: this.resolveChatModelName(ctx.config.chatModel)
6186
+ [__codemation_core.GenAiTelemetryAttributeNames.requestModel]: this.resolveChatModelName(ctx.config.chatModel),
6187
+ ...ctx.iterationId ? { [__codemation_core.CodemationTelemetryAttributeNames.iterationId]: ctx.iterationId } : {},
6188
+ ...typeof ctx.itemIndex === "number" ? { [__codemation_core.CodemationTelemetryAttributeNames.iterationIndex]: ctx.itemIndex } : {},
6189
+ ...ctx.parentInvocationId ? { [__codemation_core.CodemationTelemetryAttributeNames.parentInvocationId]: ctx.parentInvocationId } : {}
3548
6190
  }
3549
6191
  });
3550
6192
  }
3551
- async recordModelUsageMetrics(span, response, ctx) {
3552
- const usage = this.extractModelUsageMetrics(response);
3553
- for (const [name, value] of Object.entries(usage)) {
6193
+ async recordModelUsageMetrics(span, usage, ctx) {
6194
+ const entries = [
6195
+ [__codemation_core.GenAiTelemetryAttributeNames.usageInputTokens, usage.inputTokens],
6196
+ [__codemation_core.GenAiTelemetryAttributeNames.usageOutputTokens, usage.outputTokens],
6197
+ [__codemation_core.GenAiTelemetryAttributeNames.usageTotalTokens, usage.totalTokens],
6198
+ [__codemation_core.GenAiTelemetryAttributeNames.usageCacheReadInputTokens, usage.cachedInputTokens],
6199
+ [__codemation_core.GenAiTelemetryAttributeNames.usageReasoningTokens, usage.reasoningTokens]
6200
+ ];
6201
+ for (const [name, value] of entries) {
3554
6202
  if (value === void 0) continue;
3555
6203
  await span.recordMetric({
3556
6204
  name,
@@ -3565,99 +6213,49 @@ let AIAgentNode = class AIAgentNode$1 {
3565
6213
  const provider = ctx.config.chatModel.provider;
3566
6214
  const pricingKey = ctx.config.chatModel.modelName;
3567
6215
  if (!provider || !pricingKey) return;
3568
- const inputTokens = usage[__codemation_core.GenAiTelemetryAttributeNames.usageInputTokens];
3569
- const outputTokens = usage[__codemation_core.GenAiTelemetryAttributeNames.usageOutputTokens];
3570
- if (inputTokens !== void 0) await costTracking.captureUsage({
6216
+ if (usage.inputTokens !== void 0) await costTracking.captureUsage({
3571
6217
  component: "chat",
3572
6218
  provider,
3573
6219
  operation: "completion.input",
3574
6220
  pricingKey,
3575
6221
  usageUnit: "input_tokens",
3576
- quantity: inputTokens,
6222
+ quantity: usage.inputTokens,
3577
6223
  modelName: pricingKey
3578
6224
  });
3579
- if (outputTokens !== void 0) await costTracking.captureUsage({
6225
+ if (usage.outputTokens !== void 0) await costTracking.captureUsage({
3580
6226
  component: "chat",
3581
6227
  provider,
3582
6228
  operation: "completion.output",
3583
6229
  pricingKey,
3584
6230
  usageUnit: "output_tokens",
3585
- quantity: outputTokens,
6231
+ quantity: usage.outputTokens,
3586
6232
  modelName: pricingKey
3587
6233
  });
3588
6234
  }
3589
6235
  resolveChatModelName(chatModel$1) {
3590
6236
  return chatModel$1.modelName ?? chatModel$1.name;
3591
6237
  }
3592
- extractModelUsageMetrics(response) {
3593
- const usage = this.extractUsageObject(response);
3594
- const inputTokens = this.readUsageNumber(usage, [
3595
- "input_tokens",
3596
- "inputTokens",
3597
- "prompt_tokens",
3598
- "promptTokens"
3599
- ]);
3600
- const outputTokens = this.readUsageNumber(usage, [
3601
- "output_tokens",
3602
- "outputTokens",
3603
- "completion_tokens",
3604
- "completionTokens"
3605
- ]);
3606
- const totalTokens = this.readUsageNumber(usage, ["total_tokens", "totalTokens"]) ?? (inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0);
3607
- const cachedInputTokens = this.readUsageNumber(usage, [
3608
- "cache_read_input_tokens",
3609
- "cacheReadInputTokens",
3610
- "input_token_details.cached_tokens"
3611
- ]);
3612
- const reasoningTokens = this.readUsageNumber(usage, [
3613
- "reasoning_tokens",
3614
- "reasoningTokens",
3615
- "output_token_details.reasoning_tokens"
3616
- ]);
3617
- return {
3618
- [__codemation_core.GenAiTelemetryAttributeNames.usageInputTokens]: inputTokens,
3619
- [__codemation_core.GenAiTelemetryAttributeNames.usageOutputTokens]: outputTokens,
3620
- [__codemation_core.GenAiTelemetryAttributeNames.usageTotalTokens]: totalTokens,
3621
- [__codemation_core.GenAiTelemetryAttributeNames.usageCacheReadInputTokens]: cachedInputTokens,
3622
- [__codemation_core.GenAiTelemetryAttributeNames.usageReasoningTokens]: reasoningTokens
3623
- };
3624
- }
3625
- extractUsageObject(response) {
3626
- if (!this.isRecord(response)) return;
3627
- const usageMetadata = response["usage_metadata"];
3628
- if (this.isRecord(usageMetadata)) return usageMetadata;
3629
- const responseMetadata = response["response_metadata"];
3630
- if (this.isRecord(responseMetadata)) {
3631
- const tokenUsage = responseMetadata["tokenUsage"];
3632
- if (this.isRecord(tokenUsage)) return tokenUsage;
3633
- const usage = responseMetadata["usage"];
3634
- if (this.isRecord(usage)) return usage;
3635
- }
3636
- }
3637
- readUsageNumber(source, keys) {
3638
- for (const key of keys) {
3639
- const value = this.readNestedUsageValue(source, key);
3640
- if (typeof value === "number" && Number.isFinite(value)) return value;
3641
- }
3642
- }
3643
- readNestedUsageValue(source, dottedKey) {
3644
- if (!source) return;
3645
- let current = source;
3646
- for (const segment of dottedKey.split(".")) {
3647
- if (!this.isRecord(current)) return;
3648
- current = current[segment];
3649
- }
3650
- return current;
3651
- }
3652
- isRecord(value) {
3653
- return typeof value === "object" && value !== null;
3654
- }
3655
6238
  async markQueuedTools(plannedToolCalls, ctx) {
3656
- for (const plannedToolCall of plannedToolCalls) await ctx.nodeState?.markQueued({
3657
- nodeId: plannedToolCall.nodeId,
3658
- activationId: ctx.activationId,
3659
- inputsByPort: AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {})
3660
- });
6239
+ const queuedAt = (/* @__PURE__ */ new Date()).toISOString();
6240
+ for (const plannedToolCall of plannedToolCalls) {
6241
+ await ctx.nodeState?.markQueued({
6242
+ nodeId: plannedToolCall.nodeId,
6243
+ activationId: ctx.activationId,
6244
+ inputsByPort: AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {})
6245
+ });
6246
+ await ctx.nodeState?.appendConnectionInvocation({
6247
+ invocationId: plannedToolCall.invocationId,
6248
+ connectionNodeId: plannedToolCall.nodeId,
6249
+ parentAgentNodeId: ctx.nodeId,
6250
+ parentAgentActivationId: ctx.activationId,
6251
+ status: "queued",
6252
+ managedInput: this.resultToJsonValue(plannedToolCall.toolCall.input),
6253
+ queuedAt,
6254
+ iterationId: ctx.iterationId,
6255
+ itemIndex: ctx.itemIndex,
6256
+ parentInvocationId: ctx.parentInvocationId
6257
+ });
6258
+ }
3661
6259
  }
3662
6260
  planToolCalls(bindings, toolCalls, parentNodeId) {
3663
6261
  const invocationCountByToolName = /* @__PURE__ */ new Map();
@@ -3670,7 +6268,8 @@ let AIAgentNode = class AIAgentNode$1 {
3670
6268
  binding,
3671
6269
  toolCall,
3672
6270
  invocationIndex,
3673
- nodeId: __codemation_core.ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, binding.config.name)
6271
+ nodeId: __codemation_core.ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, binding.config.name),
6272
+ invocationId: __codemation_core.ConnectionInvocationIdFactory.create()
3674
6273
  };
3675
6274
  });
3676
6275
  }
@@ -3698,7 +6297,10 @@ let AIAgentNode = class AIAgentNode$1 {
3698
6297
  },
3699
6298
  queuedAt: args.startedAt.toISOString(),
3700
6299
  startedAt: args.startedAt.toISOString(),
3701
- finishedAt: finishedAt.toISOString()
6300
+ finishedAt: finishedAt.toISOString(),
6301
+ iterationId: args.ctx.iterationId,
6302
+ itemIndex: args.ctx.itemIndex,
6303
+ parentInvocationId: args.ctx.parentInvocationId
3702
6304
  });
3703
6305
  return effectiveError;
3704
6306
  }
@@ -3711,7 +6313,7 @@ let AIAgentNode = class AIAgentNode$1 {
3711
6313
  };
3712
6314
  }
3713
6315
  resultToJsonValue(value) {
3714
- if (value === void 0) return;
6316
+ if (value === void 0) return void 0;
3715
6317
  const json = JSON.stringify(value);
3716
6318
  return JSON.parse(json);
3717
6319
  }
@@ -3726,7 +6328,7 @@ let AIAgentNode = class AIAgentNode$1 {
3726
6328
  resolveToolRuntime(config$1) {
3727
6329
  if (this.isNodeBackedToolConfig(config$1)) {
3728
6330
  const inputSchema = config$1.getInputSchema();
3729
- if (inputSchema == null) throw new Error(`AIAgent tool "${config$1.name}": node-backed tool is missing inputSchema (cannot build LangChain tool).`);
6331
+ if (inputSchema == null) throw new Error(`AIAgent tool "${config$1.name}": node-backed tool is missing inputSchema (cannot build AI SDK tool).`);
3730
6332
  return {
3731
6333
  defaultDescription: `Run workflow node "${config$1.node.name ?? config$1.name}" as an AI tool.`,
3732
6334
  inputSchema,
@@ -3735,7 +6337,7 @@ let AIAgentNode = class AIAgentNode$1 {
3735
6337
  }
3736
6338
  if (this.isCallableToolConfig(config$1)) {
3737
6339
  const inputSchema = config$1.getInputSchema();
3738
- if (inputSchema == null) throw new Error(`AIAgent tool "${config$1.name}": callable tool is missing inputSchema (cannot build LangChain tool).`);
6340
+ if (inputSchema == null) throw new Error(`AIAgent tool "${config$1.name}": callable tool is missing inputSchema (cannot build AI SDK tool).`);
3739
6341
  return {
3740
6342
  defaultDescription: config$1.description ?? `Callable tool "${config$1.name}".`,
3741
6343
  inputSchema,
@@ -3753,17 +6355,9 @@ let AIAgentNode = class AIAgentNode$1 {
3753
6355
  execute: async (args) => await Promise.resolve(tool.execute(args))
3754
6356
  };
3755
6357
  }
3756
- /**
3757
- * Consumer apps can resolve two copies of `@codemation/core`, breaking `instanceof NodeBackedToolConfig` and
3758
- * sending node-backed tools down the plugin-tool branch with `inputSchema: undefined` (LangChain then crashes in
3759
- * json-schema validation). {@link NodeBackedToolConfig#toolKind} is stable across copies.
3760
- */
3761
6358
  isNodeBackedToolConfig(config$1) {
3762
6359
  return config$1 instanceof __codemation_core.NodeBackedToolConfig || typeof config$1 === "object" && config$1 !== null && config$1.toolKind === "nodeBacked";
3763
6360
  }
3764
- /**
3765
- * Callable tools use {@link CallableToolConfig#toolKind} for cross-package / JSON round-trip safety.
3766
- */
3767
6361
  isCallableToolConfig(config$1) {
3768
6362
  return config$1 instanceof __codemation_core.CallableToolConfig || typeof config$1 === "object" && config$1 !== null && config$1.toolKind === "callable";
3769
6363
  }
@@ -3834,6 +6428,52 @@ var AIAgent = class {
3834
6428
  }
3835
6429
  };
3836
6430
 
6431
+ //#endregion
6432
+ //#region src/nodes/AssertionNode.ts
6433
+ let AssertionNode = class AssertionNode$1 {
6434
+ kind = "node";
6435
+ outputPorts = ["main"];
6436
+ async execute(args) {
6437
+ const ctx = args.ctx;
6438
+ const config$1 = ctx.config;
6439
+ try {
6440
+ return [...await config$1.assertions(args.item, ctx)];
6441
+ } catch (err) {
6442
+ const message = err instanceof Error ? err.message : String(err);
6443
+ return [{
6444
+ name: config$1.name ?? "assertion",
6445
+ score: 0,
6446
+ errored: true,
6447
+ message
6448
+ }];
6449
+ }
6450
+ }
6451
+ };
6452
+ AssertionNode = __decorate([(0, __codemation_core.node)({ packageName: "@codemation/core-nodes" })], AssertionNode);
6453
+
6454
+ //#endregion
6455
+ //#region src/nodes/assertion.ts
6456
+ /**
6457
+ * Generic assertion node — the "callback" form. For declarative shorthands (StringEquals,
6458
+ * JudgeByAgent) compose this with helpers added in later phases. Sets `emitsAssertions: true`
6459
+ * so host-side persisters know to record its outputs as `TestAssertion` rows.
6460
+ */
6461
+ var Assertion = class {
6462
+ kind = "node";
6463
+ type = AssertionNode;
6464
+ icon;
6465
+ name;
6466
+ id;
6467
+ emitsAssertions = true;
6468
+ assertions;
6469
+ constructor(options) {
6470
+ this.name = options.name ?? "Assertion";
6471
+ this.id = options.id;
6472
+ this.icon = options.icon ?? "lucide:check-circle";
6473
+ this.assertions = options.assertions;
6474
+ }
6475
+ };
6476
+
3837
6477
  //#endregion
3838
6478
  //#region src/nodes/CallbackResultNormalizerFactory.ts
3839
6479
  var CallbackResultNormalizer = class {
@@ -3903,32 +6543,113 @@ let HttpRequestNode = class HttpRequestNode$1 {
3903
6543
  }
3904
6544
  async executeItem(item, ctx) {
3905
6545
  const url = this.resolveUrl(item, ctx);
3906
- const response = await fetch(url, { method: ctx.config.method });
6546
+ const credential = await this.resolveCredential(ctx);
6547
+ const spec = {
6548
+ url,
6549
+ method: ctx.config.method,
6550
+ headers: ctx.config.args.headers,
6551
+ query: ctx.config.args.query,
6552
+ body: ctx.config.args.body,
6553
+ credential,
6554
+ download: {
6555
+ mode: ctx.config.downloadMode,
6556
+ binaryName: ctx.config.binaryName
6557
+ },
6558
+ responseFormat: ctx.config.responseFormat,
6559
+ responseBinarySlot: ctx.config.responseBinarySlot,
6560
+ responseSizeCapBytes: ctx.config.responseSizeCapBytes,
6561
+ ctx
6562
+ };
6563
+ const { url: resolvedUrl, init } = await new HttpRequestExecutor(globalThis.fetch, new HttpBodyBuilder(), new HttpUrlBuilder()).buildRequest(spec, item);
6564
+ const response = await globalThis.fetch(resolvedUrl, init);
3907
6565
  const headers = this.readHeaders(response.headers);
3908
6566
  const mimeType = this.resolveMimeType(headers);
3909
- const bodyBinaryName = ctx.config.binaryName;
3910
- const shouldAttachBody = this.shouldAttachBody(ctx.config.downloadMode, mimeType);
3911
- let outputItem = { json: {
3912
- url,
6567
+ if (ctx.config.responseFormat === "binary") return await this.handleBinaryResponse(response, resolvedUrl, headers, mimeType, ctx);
6568
+ const binaryName = ctx.config.binaryName;
6569
+ if (this.shouldAttachBody(ctx.config.downloadMode, mimeType)) {
6570
+ const outputJson = {
6571
+ url: resolvedUrl,
6572
+ method: ctx.config.method,
6573
+ ok: response.ok,
6574
+ status: response.status,
6575
+ statusText: response.statusText,
6576
+ mimeType,
6577
+ headers,
6578
+ bodyBinaryName: binaryName
6579
+ };
6580
+ const attachment = await ctx.binary.attach({
6581
+ name: binaryName,
6582
+ body: response.body ? response.body : new Uint8Array(await response.arrayBuffer()),
6583
+ mimeType,
6584
+ filename: this.resolveFilename(resolvedUrl, headers)
6585
+ });
6586
+ let outputItem = { json: outputJson };
6587
+ outputItem = ctx.binary.withAttachment(outputItem, binaryName, attachment);
6588
+ return outputItem;
6589
+ }
6590
+ const isJson = this.isJsonMimeType(mimeType);
6591
+ let json;
6592
+ let text;
6593
+ if (isJson) try {
6594
+ json = await response.json();
6595
+ } catch {
6596
+ text = await response.text();
6597
+ }
6598
+ else text = await response.text();
6599
+ return { json: {
6600
+ url: resolvedUrl,
3913
6601
  method: ctx.config.method,
3914
6602
  ok: response.ok,
3915
6603
  status: response.status,
3916
6604
  statusText: response.statusText,
3917
6605
  mimeType,
3918
6606
  headers,
3919
- ...shouldAttachBody ? { bodyBinaryName } : {}
6607
+ ...json !== void 0 ? { json } : {},
6608
+ ...text !== void 0 ? { text } : {}
3920
6609
  } };
3921
- if (!shouldAttachBody) return outputItem;
6610
+ }
6611
+ async handleBinaryResponse(response, resolvedUrl, headers, mimeType, ctx) {
6612
+ const slotName = ctx.config.responseBinarySlot;
6613
+ const sizeCap = ctx.config.responseSizeCapBytes;
6614
+ const contentLengthHeader = headers["content-length"];
6615
+ if (contentLengthHeader) {
6616
+ const declaredSize = parseInt(contentLengthHeader, 10);
6617
+ if (!isNaN(declaredSize) && declaredSize > sizeCap) throw new Error(`HttpRequest responseFormat "binary": response Content-Length (${declaredSize} bytes) exceeds responseSizeCapBytes (${sizeCap} bytes).`);
6618
+ }
6619
+ const filename = this.resolveFilename(resolvedUrl, headers);
3922
6620
  const attachment = await ctx.binary.attach({
3923
- name: bodyBinaryName,
6621
+ name: slotName,
3924
6622
  body: response.body ? response.body : new Uint8Array(await response.arrayBuffer()),
3925
6623
  mimeType,
3926
- filename: this.resolveFilename(url, headers)
6624
+ filename
3927
6625
  });
3928
- outputItem = ctx.binary.withAttachment(outputItem, bodyBinaryName, attachment);
6626
+ let outputItem = { json: {
6627
+ url: resolvedUrl,
6628
+ method: ctx.config.method,
6629
+ ok: response.ok,
6630
+ status: response.status,
6631
+ statusText: response.statusText,
6632
+ headers,
6633
+ binarySlot: slotName,
6634
+ contentType: mimeType,
6635
+ size: attachment.size,
6636
+ ...filename !== void 0 ? { filename } : {}
6637
+ } };
6638
+ outputItem = ctx.binary.withAttachment(outputItem, slotName, attachment);
3929
6639
  return outputItem;
3930
6640
  }
6641
+ async resolveCredential(ctx) {
6642
+ const slotKey = ctx.config.args.credentialSlot;
6643
+ if (!slotKey) return;
6644
+ try {
6645
+ return await ctx.getCredential(slotKey);
6646
+ } catch {
6647
+ return;
6648
+ }
6649
+ }
3931
6650
  resolveUrl(item, ctx) {
6651
+ const literalUrl = ctx.config.args.url;
6652
+ if (literalUrl && literalUrl.trim().length > 0) return literalUrl.trim();
3932
6653
  const candidate = this.asRecord(item.json)[ctx.config.urlField];
3933
6654
  if (typeof candidate !== "string" || candidate.trim() === "") throw new Error(`HttpRequest node expected item.json.${ctx.config.urlField} to contain a URL string.`);
3934
6655
  return candidate;
@@ -3949,6 +6670,9 @@ let HttpRequestNode = class HttpRequestNode$1 {
3949
6670
  if (!contentType) return "application/octet-stream";
3950
6671
  return contentType.split(";")[0]?.trim() || "application/octet-stream";
3951
6672
  }
6673
+ isJsonMimeType(mimeType) {
6674
+ return mimeType === "application/json" || mimeType.endsWith("+json");
6675
+ }
3952
6676
  shouldAttachBody(mode, mimeType) {
3953
6677
  if (mode === "always") return true;
3954
6678
  if (mode === "never") return false;
@@ -3975,10 +6699,23 @@ HttpRequestNode = __decorate([(0, __codemation_core.node)({ packageName: "@codem
3975
6699
 
3976
6700
  //#endregion
3977
6701
  //#region src/nodes/httpRequest.ts
6702
+ /**
6703
+ * The built-in HTTP request credential type IDs accepted by the `HttpRequest` node.
6704
+ * These match the four generic credential types shipped with `@codemation/core-nodes`.
6705
+ */
6706
+ const HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES = [
6707
+ bearerTokenCredentialType.definition.typeId,
6708
+ apiKeyCredentialType.definition.typeId,
6709
+ basicAuthCredentialType.definition.typeId,
6710
+ oauth2ClientCredentialsType.definition.typeId
6711
+ ];
6712
+ /** Default maximum response size for binary mode: 100 MiB. */
6713
+ const DEFAULT_RESPONSE_SIZE_CAP_BYTES = 100 * 1024 * 1024;
3978
6714
  var HttpRequest = class {
3979
6715
  kind = "node";
3980
6716
  type = HttpRequestNode;
3981
6717
  execution = { hint: "local" };
6718
+ icon = "lucide:globe";
3982
6719
  constructor(name, args = {}, retryPolicy = __codemation_core.RetryPolicy.defaultForHttp) {
3983
6720
  this.name = name;
3984
6721
  this.args = args;
@@ -3999,6 +6736,25 @@ var HttpRequest = class {
3999
6736
  get downloadMode() {
4000
6737
  return this.args.downloadMode ?? "auto";
4001
6738
  }
6739
+ get responseFormat() {
6740
+ return this.args.responseFormat;
6741
+ }
6742
+ get responseBinarySlot() {
6743
+ return this.args.responseBinarySlot ?? "response";
6744
+ }
6745
+ get responseSizeCapBytes() {
6746
+ return this.args.responseSizeCapBytes ?? DEFAULT_RESPONSE_SIZE_CAP_BYTES;
6747
+ }
6748
+ getCredentialRequirements() {
6749
+ if (!this.args.credentialSlot) return [];
6750
+ return [{
6751
+ slotKey: this.args.credentialSlot,
6752
+ label: "Authentication",
6753
+ acceptedTypes: HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES,
6754
+ optional: true,
6755
+ helpText: "Optional credential for authenticating the HTTP request."
6756
+ }];
6757
+ }
4002
6758
  };
4003
6759
 
4004
6760
  //#endregion
@@ -4020,7 +6776,7 @@ var Aggregate = class {
4020
6776
  type = AggregateNode;
4021
6777
  execution = { hint: "local" };
4022
6778
  keepBinaries = true;
4023
- icon = "lucide:layers";
6779
+ icon = "builtin:aggregate-rows";
4024
6780
  constructor(name, aggregate, id) {
4025
6781
  this.name = name;
4026
6782
  this.aggregate = aggregate;
@@ -4115,7 +6871,7 @@ var If = class {
4115
6871
  kind = "node";
4116
6872
  type = IfNode;
4117
6873
  execution = { hint: "local" };
4118
- icon = "lucide:split";
6874
+ icon = "lucide:split@rot=90";
4119
6875
  declaredOutputPorts = ["true", "false"];
4120
6876
  constructor(name, predicate, id) {
4121
6877
  this.name = name;
@@ -4124,6 +6880,40 @@ var If = class {
4124
6880
  }
4125
6881
  };
4126
6882
 
6883
+ //#endregion
6884
+ //#region src/nodes/IsTestRunNode.ts
6885
+ let IsTestRunNode = class IsTestRunNode$1 {
6886
+ kind = "node";
6887
+ execute(args) {
6888
+ const isTest = args.ctx.testContext !== void 0;
6889
+ return (0, __codemation_core.emitPorts)({
6890
+ true: isTest ? [args.item] : [],
6891
+ false: isTest ? [] : [args.item]
6892
+ });
6893
+ }
6894
+ };
6895
+ IsTestRunNode = __decorate([(0, __codemation_core.node)({ packageName: "@codemation/core-nodes" })], IsTestRunNode);
6896
+
6897
+ //#endregion
6898
+ //#region src/nodes/isTestRun.ts
6899
+ /**
6900
+ * Branches per-item on whether the current run is a test run. Output ports: `true`, `false`.
6901
+ * The wire payload is unchanged — this is a router, not a transform.
6902
+ */
6903
+ var IsTestRun = class {
6904
+ kind = "node";
6905
+ type = IsTestRunNode;
6906
+ execution = { hint: "local" };
6907
+ icon = "lucide:flask-conical";
6908
+ declaredOutputPorts = ["true", "false"];
6909
+ name;
6910
+ id;
6911
+ constructor(name = "Is test run?", id) {
6912
+ this.name = name;
6913
+ this.id = id;
6914
+ }
6915
+ };
6916
+
4127
6917
  //#endregion
4128
6918
  //#region src/nodes/SwitchNode.ts
4129
6919
  let SwitchNode = class SwitchNode$1 {
@@ -4180,7 +6970,7 @@ var Split = class {
4180
6970
  * Mirrors {@link MapData}'s empty-output behavior.
4181
6971
  */
4182
6972
  continueWhenEmptyOutput = true;
4183
- icon = "lucide:ungroup";
6973
+ icon = "builtin:split-rows";
4184
6974
  constructor(name, getElements, id) {
4185
6975
  this.name = name;
4186
6976
  this.getElements = getElements;
@@ -4188,6 +6978,75 @@ var Split = class {
4188
6978
  }
4189
6979
  };
4190
6980
 
6981
+ //#endregion
6982
+ //#region src/nodes/CronTriggerNode.ts
6983
+ let CronTriggerNode = class CronTriggerNode$1 {
6984
+ kind = "trigger";
6985
+ outputPorts = ["main"];
6986
+ async setup(ctx) {
6987
+ const job = ctx.config.createJob(async (self) => {
6988
+ const scheduledFor = self.currentRun()?.toISOString() ?? ctx.now().toISOString();
6989
+ await ctx.emit([{ json: {
6990
+ firedAt: ctx.now().toISOString(),
6991
+ scheduledFor
6992
+ } }]);
6993
+ });
6994
+ ctx.registerCleanup({ stop: () => {
6995
+ job.stop();
6996
+ } });
6997
+ }
6998
+ async execute(items, _ctx) {
6999
+ return { main: items };
7000
+ }
7001
+ async getTestItems(ctx) {
7002
+ const nowIso = ctx.now().toISOString();
7003
+ return [{ json: {
7004
+ firedAt: nowIso,
7005
+ scheduledFor: nowIso
7006
+ } }];
7007
+ }
7008
+ };
7009
+ CronTriggerNode = __decorate([(0, __codemation_core.node)({ packageName: "@codemation/core-nodes" })], CronTriggerNode);
7010
+
7011
+ //#endregion
7012
+ //#region src/nodes/CronTriggerFactory.ts
7013
+ /**
7014
+ * Schedules a workflow on a standard cron expression.
7015
+ *
7016
+ * Each tick emits one item: `{ firedAt: string, scheduledFor: string }` — both ISO-8601 timestamps.
7017
+ * `firedAt` is the wall-clock moment the callback ran; `scheduledFor` is the cron-computed
7018
+ * firing instant (these differ when the job was delayed).
7019
+ *
7020
+ * Timezone defaults to UTC when omitted — cron without an explicit TZ is a DST footgun.
7021
+ */
7022
+ var CronTrigger = class {
7023
+ kind = "trigger";
7024
+ type = CronTriggerNode;
7025
+ icon = "lucide:clock";
7026
+ id;
7027
+ constructor(name, args, id) {
7028
+ this.name = name;
7029
+ this.args = args;
7030
+ new croner.Cron(args.schedule, {
7031
+ paused: true,
7032
+ timezone: args.timezone
7033
+ });
7034
+ this.id = id;
7035
+ }
7036
+ get schedule() {
7037
+ return this.args.schedule;
7038
+ }
7039
+ get timezone() {
7040
+ return this.args.timezone;
7041
+ }
7042
+ createJob(callback) {
7043
+ return new croner.Cron(this.args.schedule, {
7044
+ timezone: this.args.timezone,
7045
+ protect: true
7046
+ }, callback);
7047
+ }
7048
+ };
7049
+
4191
7050
  //#endregion
4192
7051
  //#region src/nodes/ManualTriggerNode.ts
4193
7052
  let ManualTriggerNode = class ManualTriggerNode$1 {
@@ -4251,6 +7110,7 @@ var MapData = class {
4251
7110
  execution = { hint: "local" };
4252
7111
  /** Zero mapped items should still allow downstream nodes to run. */
4253
7112
  continueWhenEmptyOutput = true;
7113
+ icon = "lucide:square-pen";
4254
7114
  keepBinaries;
4255
7115
  constructor(name, map, options = {}) {
4256
7116
  this.name = name;
@@ -4320,7 +7180,7 @@ MergeNode = __decorate([(0, __codemation_core.node)({ packageName: "@codemation/
4320
7180
  var Merge = class {
4321
7181
  kind = "node";
4322
7182
  type = MergeNode;
4323
- icon = "lucide:git-merge";
7183
+ icon = "lucide:merge@rot=90";
4324
7184
  constructor(name, cfg = { mode: "passThrough" }, id) {
4325
7185
  this.name = name;
4326
7186
  this.cfg = cfg;
@@ -4345,6 +7205,7 @@ var NoOp = class {
4345
7205
  kind = "node";
4346
7206
  type = NoOpNode;
4347
7207
  execution = { hint: "local" };
7208
+ icon = "lucide:circle-dashed";
4348
7209
  constructor(name = "NoOp", id) {
4349
7210
  this.name = name;
4350
7211
  this.id = id;
@@ -4417,6 +7278,52 @@ var SubWorkflow = class {
4417
7278
  }
4418
7279
  };
4419
7280
 
7281
+ //#endregion
7282
+ //#region src/nodes/TestTriggerNode.ts
7283
+ let TestTriggerNode = class TestTriggerNode$1 {
7284
+ kind = "trigger";
7285
+ outputPorts = ["main"];
7286
+ async setup(_ctx) {}
7287
+ async execute(items, _ctx) {
7288
+ return { main: items };
7289
+ }
7290
+ };
7291
+ TestTriggerNode = __decorate([(0, __codemation_core.node)({ packageName: "@codemation/core-nodes" })], TestTriggerNode);
7292
+
7293
+ //#endregion
7294
+ //#region src/nodes/testTrigger.ts
7295
+ /**
7296
+ * Trigger config for a test fixture source. Drop one (or more) of these on the canvas alongside
7297
+ * a workflow's live triggers; clicking "Run tests" on the Tests tab invokes
7298
+ * {@link TestTriggerOptions.generateItems} via the TestSuiteOrchestrator.
7299
+ */
7300
+ var TestTrigger = class {
7301
+ kind = "trigger";
7302
+ triggerKind = "test";
7303
+ type = TestTriggerNode;
7304
+ icon;
7305
+ name;
7306
+ id;
7307
+ concurrency;
7308
+ description;
7309
+ generateItems;
7310
+ caseLabel;
7311
+ credentialRequirements;
7312
+ constructor(options) {
7313
+ this.name = options.name ?? "Test trigger";
7314
+ this.id = options.id;
7315
+ this.icon = options.icon ?? "lucide:flask-conical";
7316
+ this.concurrency = options.concurrency;
7317
+ this.description = options.description;
7318
+ this.credentialRequirements = options.credentialRequirements ?? [];
7319
+ this.generateItems = options.generateItems;
7320
+ this.caseLabel = options.caseLabel;
7321
+ }
7322
+ getCredentialRequirements() {
7323
+ return this.credentialRequirements;
7324
+ }
7325
+ };
7326
+
4420
7327
  //#endregion
4421
7328
  //#region src/nodes/WaitDurationFactory.ts
4422
7329
  var WaitDuration = class {
@@ -4450,6 +7357,7 @@ var Wait = class {
4450
7357
  execution = { hint: "local" };
4451
7358
  /** Pass-through empty batches should still advance to downstream nodes. */
4452
7359
  continueWhenEmptyOutput = true;
7360
+ icon = "lucide:hourglass";
4453
7361
  constructor(name, milliseconds, id) {
4454
7362
  this.name = name;
4455
7363
  this.milliseconds = milliseconds;
@@ -4500,7 +7408,7 @@ WebhookTriggerNode = __decorate([(0, __codemation_core.node)({ packageName: "@co
4500
7408
  var WebhookTrigger = class WebhookTrigger {
4501
7409
  kind = "trigger";
4502
7410
  type = WebhookTriggerNode;
4503
- icon = "lucide:globe";
7411
+ icon = "lucide:webhook";
4504
7412
  constructor(name, args, handler = WebhookTrigger.defaultHandler, id) {
4505
7413
  this.name = name;
4506
7414
  this.args = args;
@@ -4596,10 +7504,10 @@ var WorkflowDefinedNodeResolver = class {
4596
7504
  //#endregion
4597
7505
  //#region src/workflowAuthoring/WorkflowDurationParser.types.ts
4598
7506
  var WorkflowDurationParser = class {
4599
- static parse(duration) {
4600
- if (typeof duration === "number") return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0;
4601
- const match = duration.trim().toLowerCase().match(/^(\d+)(ms|s|m|h)$/);
4602
- if (!match) throw new Error(`Unsupported wait duration "${duration}". Use a number of milliseconds or values like "500ms", "2s", "5m".`);
7507
+ static parse(duration$2) {
7508
+ if (typeof duration$2 === "number") return Number.isFinite(duration$2) && duration$2 > 0 ? Math.floor(duration$2) : 0;
7509
+ const match = duration$2.trim().toLowerCase().match(/^(\d+)(ms|s|m|h)$/);
7510
+ if (!match) throw new Error(`Unsupported wait duration "${duration$2}". Use a number of milliseconds or values like "500ms", "2s", "5m".`);
4603
7511
  const value = Number(match[1]);
4604
7512
  const unit = match[2];
4605
7513
  if (unit === "ms") return value;
@@ -4625,8 +7533,8 @@ var WorkflowBranchBuilder = class WorkflowBranchBuilder {
4625
7533
  }
4626
7534
  wait(nameOrDuration, durationOrUndefined, id) {
4627
7535
  const name = typeof nameOrDuration === "string" && durationOrUndefined !== void 0 ? nameOrDuration : "Wait";
4628
- const duration = durationOrUndefined ?? nameOrDuration;
4629
- return this.then(new Wait(name, WorkflowDurationParser.parse(duration), id));
7536
+ const duration$2 = durationOrUndefined ?? nameOrDuration;
7537
+ return this.then(new Wait(name, WorkflowDurationParser.parse(duration$2), id));
4630
7538
  }
4631
7539
  split(nameOrGetter, getElementsOrUndefined, id) {
4632
7540
  const name = typeof nameOrGetter === "string" ? nameOrGetter : "Split";
@@ -4671,8 +7579,8 @@ var WorkflowChain = class WorkflowChain {
4671
7579
  }
4672
7580
  wait(nameOrDuration, durationOrUndefined, id) {
4673
7581
  const name = typeof nameOrDuration === "string" && durationOrUndefined !== void 0 ? nameOrDuration : "Wait";
4674
- const duration = durationOrUndefined ?? nameOrDuration;
4675
- return this.then(new Wait(name, WorkflowDurationParser.parse(duration), id));
7582
+ const duration$2 = durationOrUndefined ?? nameOrDuration;
7583
+ return this.then(new Wait(name, WorkflowDurationParser.parse(duration$2), id));
4676
7584
  }
4677
7585
  split(nameOrGetter, getElementsOrUndefined, id) {
4678
7586
  const name = typeof nameOrGetter === "string" ? nameOrGetter : "Split";
@@ -4772,9 +7680,9 @@ var AIAgentConnectionWorkflowExpander = class {
4772
7680
  const connectionsByParentAndName = this.createConnectionsByParentAndName(workflow$1);
4773
7681
  const extraNodes = [];
4774
7682
  let connectionsChanged = false;
4775
- for (const node$16 of workflow$1.nodes) {
4776
- if (node$16.type !== AIAgentNode || !__codemation_core.AgentConfigInspector.isAgentNodeConfig(node$16.config)) continue;
4777
- for (const connectionNode of __codemation_core.AgentConnectionNodeCollector.collect(node$16.id, node$16.config)) {
7683
+ for (const node$20 of workflow$1.nodes) {
7684
+ if (node$20.type !== AIAgentNode || !__codemation_core.AgentConfigInspector.isAgentNodeConfig(node$20.config)) continue;
7685
+ for (const connectionNode of __codemation_core.AgentConnectionNodeCollector.collect(node$20.id, node$20.config)) {
4778
7686
  if (!existingChildIds.has(connectionNode.nodeId)) {
4779
7687
  this.assertNoIdCollision(workflow$1, extraNodes, existingChildIds, connectionNode.nodeId);
4780
7688
  extraNodes.push({
@@ -4853,6 +7761,129 @@ var ConnectionCredentialNodeConfigFactory = class {
4853
7761
  }
4854
7762
  };
4855
7763
 
7764
+ //#endregion
7765
+ //#region src/nodes/collections/collectionInsertNode.types.ts
7766
+ const collectionInsertNode = (0, __codemation_core.defineNode)({
7767
+ key: "collection-insert",
7768
+ title: "Collection: Insert",
7769
+ description: "Insert a new row into a collection.",
7770
+ icon: "lucide:boxes",
7771
+ configSchema: object({
7772
+ collectionName: string(),
7773
+ data: record(string(), unknown())
7774
+ }),
7775
+ async execute(_args, { config: config$1, execution }) {
7776
+ const store = execution.collections?.[config$1.collectionName];
7777
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7778
+ return await store.insert(config$1.data);
7779
+ }
7780
+ });
7781
+
7782
+ //#endregion
7783
+ //#region src/nodes/collections/collectionGetNode.types.ts
7784
+ const collectionGetNode = (0, __codemation_core.defineNode)({
7785
+ key: "collection-get",
7786
+ title: "Collection: Get",
7787
+ description: "Get a single row by id from a collection.",
7788
+ icon: "lucide:layers",
7789
+ configSchema: object({
7790
+ collectionName: string(),
7791
+ id: string()
7792
+ }),
7793
+ async execute(_args, { config: config$1, execution }) {
7794
+ const store = execution.collections?.[config$1.collectionName];
7795
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7796
+ const row = await store.get(config$1.id);
7797
+ if (row === null) return [];
7798
+ return row;
7799
+ }
7800
+ });
7801
+
7802
+ //#endregion
7803
+ //#region src/nodes/collections/collectionFindOneNode.types.ts
7804
+ const collectionFindOneNode = (0, __codemation_core.defineNode)({
7805
+ key: "collection-find-one",
7806
+ title: "Collection: Find One",
7807
+ description: "Find a single row matching a filter in a collection.",
7808
+ icon: "lucide:filter",
7809
+ configSchema: object({
7810
+ collectionName: string(),
7811
+ where: record(string(), unknown())
7812
+ }),
7813
+ async execute(_args, { config: config$1, execution }) {
7814
+ const store = execution.collections?.[config$1.collectionName];
7815
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7816
+ const row = await store.findOne(config$1.where);
7817
+ if (row === null) return [];
7818
+ return row;
7819
+ }
7820
+ });
7821
+
7822
+ //#endregion
7823
+ //#region src/nodes/collections/collectionListNode.types.ts
7824
+ const collectionListNode = (0, __codemation_core.defineNode)({
7825
+ key: "collection-list",
7826
+ title: "Collection: List",
7827
+ description: "List rows from a collection with optional pagination and filtering.",
7828
+ icon: "lucide:split",
7829
+ configSchema: object({
7830
+ collectionName: string(),
7831
+ limit: number().int().positive().optional(),
7832
+ offset: number().int().nonnegative().optional(),
7833
+ where: record(string(), unknown()).optional()
7834
+ }),
7835
+ async execute(_args, { config: config$1, execution }) {
7836
+ const store = execution.collections?.[config$1.collectionName];
7837
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7838
+ const { rows } = await store.list({
7839
+ limit: config$1.limit,
7840
+ offset: config$1.offset,
7841
+ where: config$1.where
7842
+ });
7843
+ return [...rows];
7844
+ }
7845
+ });
7846
+
7847
+ //#endregion
7848
+ //#region src/nodes/collections/collectionUpdateNode.types.ts
7849
+ const collectionUpdateNode = (0, __codemation_core.defineNode)({
7850
+ key: "collection-update",
7851
+ title: "Collection: Update",
7852
+ description: "Update a row by id in a collection.",
7853
+ icon: "lucide:square-pen",
7854
+ configSchema: object({
7855
+ collectionName: string(),
7856
+ id: string(),
7857
+ patch: record(string(), unknown())
7858
+ }),
7859
+ async execute(_args, { config: config$1, execution }) {
7860
+ const store = execution.collections?.[config$1.collectionName];
7861
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7862
+ return await store.update(config$1.id, config$1.patch);
7863
+ }
7864
+ });
7865
+
7866
+ //#endregion
7867
+ //#region src/nodes/collections/collectionDeleteNode.types.ts
7868
+ const collectionDeleteNode = (0, __codemation_core.defineNode)({
7869
+ key: "collection-delete",
7870
+ title: "Collection: Delete",
7871
+ description: "Delete a row by id from a collection.",
7872
+ icon: "lucide:braces",
7873
+ configSchema: object({
7874
+ collectionName: string(),
7875
+ id: string()
7876
+ }),
7877
+ async execute(_args, { config: config$1, execution }) {
7878
+ const store = execution.collections?.[config$1.collectionName];
7879
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7880
+ return {
7881
+ deleted: (await store.delete(config$1.id)).deleted,
7882
+ id: config$1.id
7883
+ };
7884
+ }
7885
+ });
7886
+
4856
7887
  //#endregion
4857
7888
  exports.AIAgent = AIAgent;
4858
7889
  exports.AIAgentConnectionWorkflowExpander = AIAgentConnectionWorkflowExpander;
@@ -4910,6 +7941,13 @@ Object.defineProperty(exports, 'AggregateNode', {
4910
7941
  return AggregateNode;
4911
7942
  }
4912
7943
  });
7944
+ exports.Assertion = Assertion;
7945
+ Object.defineProperty(exports, 'AssertionNode', {
7946
+ enumerable: true,
7947
+ get: function () {
7948
+ return AssertionNode;
7949
+ }
7950
+ });
4913
7951
  exports.Callback = Callback;
4914
7952
  Object.defineProperty(exports, 'CallbackNode', {
4915
7953
  enumerable: true,
@@ -4927,6 +7965,13 @@ Object.defineProperty(exports, 'ConnectionCredentialNode', {
4927
7965
  });
4928
7966
  exports.ConnectionCredentialNodeConfig = ConnectionCredentialNodeConfig;
4929
7967
  exports.ConnectionCredentialNodeConfigFactory = ConnectionCredentialNodeConfigFactory;
7968
+ exports.CronTrigger = CronTrigger;
7969
+ Object.defineProperty(exports, 'CronTriggerNode', {
7970
+ enumerable: true,
7971
+ get: function () {
7972
+ return CronTriggerNode;
7973
+ }
7974
+ });
4930
7975
  exports.Filter = Filter;
4931
7976
  Object.defineProperty(exports, 'FilterNode', {
4932
7977
  enumerable: true,
@@ -4934,6 +7979,7 @@ Object.defineProperty(exports, 'FilterNode', {
4934
7979
  return FilterNode;
4935
7980
  }
4936
7981
  });
7982
+ exports.HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES = HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES;
4937
7983
  exports.HttpRequest = HttpRequest;
4938
7984
  Object.defineProperty(exports, 'HttpRequestNode', {
4939
7985
  enumerable: true,
@@ -4948,6 +7994,13 @@ Object.defineProperty(exports, 'IfNode', {
4948
7994
  return IfNode;
4949
7995
  }
4950
7996
  });
7997
+ exports.IsTestRun = IsTestRun;
7998
+ Object.defineProperty(exports, 'IsTestRunNode', {
7999
+ enumerable: true,
8000
+ get: function () {
8001
+ return IsTestRunNode;
8002
+ }
8003
+ });
4951
8004
  exports.ManualTrigger = ManualTrigger;
4952
8005
  Object.defineProperty(exports, 'ManualTriggerNode', {
4953
8006
  enumerable: true,
@@ -4983,13 +8036,13 @@ Object.defineProperty(exports, 'OpenAIChatModelFactory', {
4983
8036
  return OpenAIChatModelFactory;
4984
8037
  }
4985
8038
  });
4986
- Object.defineProperty(exports, 'OpenAIStructuredOutputMethodFactory', {
8039
+ exports.OpenAiChatModelPresets = OpenAiChatModelPresets;
8040
+ Object.defineProperty(exports, 'OpenAiStrictJsonSchemaFactory', {
4987
8041
  enumerable: true,
4988
8042
  get: function () {
4989
- return OpenAIStructuredOutputMethodFactory;
8043
+ return OpenAiStrictJsonSchemaFactory;
4990
8044
  }
4991
8045
  });
4992
- exports.OpenAiChatModelPresets = OpenAiChatModelPresets;
4993
8046
  exports.Split = Split;
4994
8047
  Object.defineProperty(exports, 'SplitNode', {
4995
8048
  enumerable: true,
@@ -5011,6 +8064,13 @@ Object.defineProperty(exports, 'SwitchNode', {
5011
8064
  return SwitchNode;
5012
8065
  }
5013
8066
  });
8067
+ exports.TestTrigger = TestTrigger;
8068
+ Object.defineProperty(exports, 'TestTriggerNode', {
8069
+ enumerable: true,
8070
+ get: function () {
8071
+ return TestTriggerNode;
8072
+ }
8073
+ });
5014
8074
  exports.Wait = Wait;
5015
8075
  exports.WaitDuration = WaitDuration;
5016
8076
  Object.defineProperty(exports, 'WaitNode', {
@@ -5031,7 +8091,18 @@ Object.defineProperty(exports, 'WebhookTriggerNode', {
5031
8091
  exports.WorkflowAuthoringBuilder = WorkflowAuthoringBuilder;
5032
8092
  exports.WorkflowBranchBuilder = WorkflowBranchBuilder;
5033
8093
  exports.WorkflowChain = WorkflowChain;
8094
+ exports.apiKeyCredentialType = apiKeyCredentialType;
8095
+ exports.basicAuthCredentialType = basicAuthCredentialType;
8096
+ exports.bearerTokenCredentialType = bearerTokenCredentialType;
8097
+ exports.collectionDeleteNode = collectionDeleteNode;
8098
+ exports.collectionFindOneNode = collectionFindOneNode;
8099
+ exports.collectionGetNode = collectionGetNode;
8100
+ exports.collectionInsertNode = collectionInsertNode;
8101
+ exports.collectionListNode = collectionListNode;
8102
+ exports.collectionUpdateNode = collectionUpdateNode;
5034
8103
  exports.createWorkflowBuilder = createWorkflowBuilder;
8104
+ exports.defineRestNode = defineRestNode;
8105
+ exports.oauth2ClientCredentialsType = oauth2ClientCredentialsType;
5035
8106
  exports.openAiChatModelPresets = openAiChatModelPresets;
5036
8107
  exports.registerCoreNodes = registerCoreNodes;
5037
8108
  exports.workflow = workflow;