@jterrazz/intelligence 2.0.0 → 3.0.1

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 (113) hide show
  1. package/README.md +56 -268
  2. package/dist/index.cjs +652 -2017
  3. package/dist/index.d.ts +5 -15
  4. package/dist/index.js +5 -33
  5. package/dist/index.js.map +1 -1
  6. package/dist/middleware/__tests__/logging.middleware.test.js +390 -0
  7. package/dist/middleware/__tests__/logging.middleware.test.js.map +1 -0
  8. package/dist/middleware/logging.middleware.d.ts +21 -0
  9. package/dist/middleware/logging.middleware.js +296 -0
  10. package/dist/middleware/logging.middleware.js.map +1 -0
  11. package/dist/parsing/__tests__/create-schema-prompt.test.js +53 -0
  12. package/dist/parsing/__tests__/create-schema-prompt.test.js.map +1 -0
  13. package/dist/parsing/__tests__/parse-object.test.d.ts +1 -0
  14. package/dist/parsing/__tests__/parse-object.test.js +193 -0
  15. package/dist/parsing/__tests__/parse-object.test.js.map +1 -0
  16. package/dist/parsing/__tests__/parse-text.test.d.ts +1 -0
  17. package/dist/parsing/__tests__/parse-text.test.js +167 -0
  18. package/dist/parsing/__tests__/parse-text.test.js.map +1 -0
  19. package/dist/parsing/create-schema-prompt.d.ts +28 -0
  20. package/dist/parsing/create-schema-prompt.js +42 -0
  21. package/dist/parsing/create-schema-prompt.js.map +1 -0
  22. package/dist/parsing/parse-object.d.ts +33 -0
  23. package/dist/parsing/parse-object.js +360 -0
  24. package/dist/parsing/parse-object.js.map +1 -0
  25. package/dist/parsing/parse-text.d.ts +14 -0
  26. package/dist/parsing/parse-text.js +76 -0
  27. package/dist/parsing/parse-text.js.map +1 -0
  28. package/dist/providers/openrouter.provider.d.ts +36 -0
  29. package/dist/providers/openrouter.provider.js +58 -0
  30. package/dist/providers/openrouter.provider.js.map +1 -0
  31. package/package.json +14 -15
  32. package/dist/adapters/agents/chat-agent.adapter.d.ts +0 -27
  33. package/dist/adapters/agents/chat-agent.adapter.js +0 -356
  34. package/dist/adapters/agents/chat-agent.adapter.js.map +0 -1
  35. package/dist/adapters/agents/resilient-agent.adapter.d.ts +0 -20
  36. package/dist/adapters/agents/resilient-agent.adapter.js +0 -263
  37. package/dist/adapters/agents/resilient-agent.adapter.js.map +0 -1
  38. package/dist/adapters/agents/tool-agent.adapter.d.ts +0 -30
  39. package/dist/adapters/agents/tool-agent.adapter.js +0 -400
  40. package/dist/adapters/agents/tool-agent.adapter.js.map +0 -1
  41. package/dist/adapters/models/openrouter-model.adapter.d.ts +0 -23
  42. package/dist/adapters/models/openrouter-model.adapter.js +0 -148
  43. package/dist/adapters/models/openrouter-model.adapter.js.map +0 -1
  44. package/dist/adapters/prompts/__tests__/__snapshots__/presets.test.ts.snap +0 -120
  45. package/dist/adapters/prompts/__tests__/presets.test.js +0 -31
  46. package/dist/adapters/prompts/__tests__/presets.test.js.map +0 -1
  47. package/dist/adapters/prompts/library/categories/domain.d.ts +0 -11
  48. package/dist/adapters/prompts/library/categories/domain.js +0 -12
  49. package/dist/adapters/prompts/library/categories/domain.js.map +0 -1
  50. package/dist/adapters/prompts/library/categories/format.d.ts +0 -10
  51. package/dist/adapters/prompts/library/categories/format.js +0 -11
  52. package/dist/adapters/prompts/library/categories/format.js.map +0 -1
  53. package/dist/adapters/prompts/library/categories/foundations.d.ts +0 -12
  54. package/dist/adapters/prompts/library/categories/foundations.js +0 -13
  55. package/dist/adapters/prompts/library/categories/foundations.js.map +0 -1
  56. package/dist/adapters/prompts/library/categories/language.d.ts +0 -11
  57. package/dist/adapters/prompts/library/categories/language.js +0 -12
  58. package/dist/adapters/prompts/library/categories/language.js.map +0 -1
  59. package/dist/adapters/prompts/library/categories/persona.d.ts +0 -13
  60. package/dist/adapters/prompts/library/categories/persona.js +0 -14
  61. package/dist/adapters/prompts/library/categories/persona.js.map +0 -1
  62. package/dist/adapters/prompts/library/categories/response.d.ts +0 -9
  63. package/dist/adapters/prompts/library/categories/response.js +0 -10
  64. package/dist/adapters/prompts/library/categories/response.js.map +0 -1
  65. package/dist/adapters/prompts/library/categories/tone.d.ts +0 -9
  66. package/dist/adapters/prompts/library/categories/tone.js +0 -10
  67. package/dist/adapters/prompts/library/categories/tone.js.map +0 -1
  68. package/dist/adapters/prompts/library/categories/verbosity.d.ts +0 -8
  69. package/dist/adapters/prompts/library/categories/verbosity.js +0 -9
  70. package/dist/adapters/prompts/library/categories/verbosity.js.map +0 -1
  71. package/dist/adapters/prompts/library/index.d.ts +0 -68
  72. package/dist/adapters/prompts/library/index.js +0 -26
  73. package/dist/adapters/prompts/library/index.js.map +0 -1
  74. package/dist/adapters/prompts/library/presets.d.ts +0 -17
  75. package/dist/adapters/prompts/library/presets.js +0 -45
  76. package/dist/adapters/prompts/library/presets.js.map +0 -1
  77. package/dist/adapters/prompts/system-prompt.adapter.d.ts +0 -9
  78. package/dist/adapters/prompts/system-prompt.adapter.js +0 -57
  79. package/dist/adapters/prompts/system-prompt.adapter.js.map +0 -1
  80. package/dist/adapters/prompts/user-prompt.adapter.d.ts +0 -9
  81. package/dist/adapters/prompts/user-prompt.adapter.js +0 -57
  82. package/dist/adapters/prompts/user-prompt.adapter.js.map +0 -1
  83. package/dist/adapters/providers/openrouter-provider.adapter.d.ts +0 -34
  84. package/dist/adapters/providers/openrouter-provider.adapter.js +0 -57
  85. package/dist/adapters/providers/openrouter-provider.adapter.js.map +0 -1
  86. package/dist/adapters/tools/safe-tool.adapter.d.ts +0 -27
  87. package/dist/adapters/tools/safe-tool.adapter.js +0 -283
  88. package/dist/adapters/tools/safe-tool.adapter.js.map +0 -1
  89. package/dist/adapters/utils/__tests__/structured-response-parser.test.js +0 -289
  90. package/dist/adapters/utils/__tests__/structured-response-parser.test.js.map +0 -1
  91. package/dist/adapters/utils/structured-response-parser-error.d.ts +0 -8
  92. package/dist/adapters/utils/structured-response-parser-error.js +0 -136
  93. package/dist/adapters/utils/structured-response-parser-error.js.map +0 -1
  94. package/dist/adapters/utils/structured-response-parser.d.ts +0 -60
  95. package/dist/adapters/utils/structured-response-parser.js +0 -347
  96. package/dist/adapters/utils/structured-response-parser.js.map +0 -1
  97. package/dist/ports/agent.port.d.ts +0 -17
  98. package/dist/ports/agent.port.js +0 -7
  99. package/dist/ports/agent.port.js.map +0 -1
  100. package/dist/ports/model.port.d.ts +0 -37
  101. package/dist/ports/model.port.js +0 -5
  102. package/dist/ports/model.port.js.map +0 -1
  103. package/dist/ports/prompt.port.d.ts +0 -9
  104. package/dist/ports/prompt.port.js +0 -5
  105. package/dist/ports/prompt.port.js.map +0 -1
  106. package/dist/ports/provider.port.d.ts +0 -13
  107. package/dist/ports/provider.port.js +0 -5
  108. package/dist/ports/provider.port.js.map +0 -1
  109. package/dist/ports/tool.port.d.ts +0 -11
  110. package/dist/ports/tool.port.js +0 -5
  111. package/dist/ports/tool.port.js.map +0 -1
  112. /package/dist/{adapters/prompts/__tests__/presets.test.d.ts → middleware/__tests__/logging.middleware.test.d.ts} +0 -0
  113. /package/dist/{adapters/utils/__tests__/structured-response-parser.test.d.ts → parsing/__tests__/create-schema-prompt.test.d.ts} +0 -0
package/dist/index.cjs CHANGED
@@ -1,17 +1,348 @@
1
1
  'use strict';
2
2
 
3
- var ai = require('ai');
4
3
  var v4 = require('zod/v4');
5
4
  var jsonrepair = require('jsonrepair');
6
- var prompts = require('@langchain/core/prompts');
7
- var agents = require('langchain/agents');
8
- var openai = require('@langchain/openai');
9
5
  var aiSdkProvider = require('@openrouter/ai-sdk-provider');
10
- var tools = require('langchain/tools');
6
+
7
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
8
+ try {
9
+ var info = gen[key](arg);
10
+ var value = info.value;
11
+ } catch (error) {
12
+ reject(error);
13
+ return;
14
+ }
15
+ if (info.done) {
16
+ resolve(value);
17
+ } else {
18
+ Promise.resolve(value).then(_next, _throw);
19
+ }
20
+ }
21
+ function _async_to_generator(fn) {
22
+ return function() {
23
+ var self = this, args = arguments;
24
+ return new Promise(function(resolve, reject) {
25
+ var gen = fn.apply(self, args);
26
+ function _next(value) {
27
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
28
+ }
29
+ function _throw(err) {
30
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
31
+ }
32
+ _next(undefined);
33
+ });
34
+ };
35
+ }
36
+ function _define_property$2(obj, key, value) {
37
+ if (key in obj) {
38
+ Object.defineProperty(obj, key, {
39
+ value: value,
40
+ enumerable: true,
41
+ configurable: true,
42
+ writable: true
43
+ });
44
+ } else {
45
+ obj[key] = value;
46
+ }
47
+ return obj;
48
+ }
49
+ function _instanceof$1(left, right) {
50
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
51
+ return !!right[Symbol.hasInstance](left);
52
+ } else {
53
+ return left instanceof right;
54
+ }
55
+ }
56
+ function _object_spread$1(target) {
57
+ for(var i = 1; i < arguments.length; i++){
58
+ var source = arguments[i] != null ? arguments[i] : {};
59
+ var ownKeys = Object.keys(source);
60
+ if (typeof Object.getOwnPropertySymbols === "function") {
61
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
62
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
63
+ }));
64
+ }
65
+ ownKeys.forEach(function(key) {
66
+ _define_property$2(target, key, source[key]);
67
+ });
68
+ }
69
+ return target;
70
+ }
71
+ function ownKeys(object, enumerableOnly) {
72
+ var keys = Object.keys(object);
73
+ if (Object.getOwnPropertySymbols) {
74
+ var symbols = Object.getOwnPropertySymbols(object);
75
+ keys.push.apply(keys, symbols);
76
+ }
77
+ return keys;
78
+ }
79
+ function _object_spread_props(target, source) {
80
+ source = source != null ? source : {};
81
+ if (Object.getOwnPropertyDescriptors) {
82
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
83
+ } else {
84
+ ownKeys(Object(source)).forEach(function(key) {
85
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
86
+ });
87
+ }
88
+ return target;
89
+ }
90
+ function _ts_generator(thisArg, body) {
91
+ var f, y, t, _ = {
92
+ label: 0,
93
+ sent: function() {
94
+ if (t[0] & 1) throw t[1];
95
+ return t[1];
96
+ },
97
+ trys: [],
98
+ ops: []
99
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
100
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
101
+ return this;
102
+ }), g;
103
+ function verb(n) {
104
+ return function(v) {
105
+ return step([
106
+ n,
107
+ v
108
+ ]);
109
+ };
110
+ }
111
+ function step(op) {
112
+ if (f) throw new TypeError("Generator is already executing.");
113
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
114
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
115
+ if (y = 0, t) op = [
116
+ op[0] & 2,
117
+ t.value
118
+ ];
119
+ switch(op[0]){
120
+ case 0:
121
+ case 1:
122
+ t = op;
123
+ break;
124
+ case 4:
125
+ _.label++;
126
+ return {
127
+ value: op[1],
128
+ done: false
129
+ };
130
+ case 5:
131
+ _.label++;
132
+ y = op[1];
133
+ op = [
134
+ 0
135
+ ];
136
+ continue;
137
+ case 7:
138
+ op = _.ops.pop();
139
+ _.trys.pop();
140
+ continue;
141
+ default:
142
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
143
+ _ = 0;
144
+ continue;
145
+ }
146
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
147
+ _.label = op[1];
148
+ break;
149
+ }
150
+ if (op[0] === 6 && _.label < t[1]) {
151
+ _.label = t[1];
152
+ t = op;
153
+ break;
154
+ }
155
+ if (t && _.label < t[2]) {
156
+ _.label = t[2];
157
+ _.ops.push(op);
158
+ break;
159
+ }
160
+ if (t[2]) _.ops.pop();
161
+ _.trys.pop();
162
+ continue;
163
+ }
164
+ op = body.call(thisArg, _);
165
+ } catch (e) {
166
+ op = [
167
+ 6,
168
+ e
169
+ ];
170
+ y = 0;
171
+ } finally{
172
+ f = t = 0;
173
+ }
174
+ if (op[0] & 5) throw op[1];
175
+ return {
176
+ value: op[0] ? op[1] : void 0,
177
+ done: true
178
+ };
179
+ }
180
+ }
181
+ /**
182
+ * Creates AI SDK middleware that logs model requests and responses.
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * import { wrapLanguageModel } from 'ai';
187
+ *
188
+ * const model = wrapLanguageModel({
189
+ * model: openrouter('anthropic/claude-sonnet-4-20250514'),
190
+ * middleware: createLoggingMiddleware({ logger }),
191
+ * });
192
+ * ```
193
+ */ function createLoggingMiddleware(options) {
194
+ var logger = options.logger, _options_verbose = options.verbose, verbose = _options_verbose === void 0 ? false : _options_verbose;
195
+ return {
196
+ middlewareVersion: 'v2',
197
+ wrapGenerate: function(param) {
198
+ var doGenerate = param.doGenerate, params = param.params;
199
+ return _async_to_generator(function() {
200
+ var startTime, result, error;
201
+ return _ts_generator(this, function(_state) {
202
+ switch(_state.label){
203
+ case 0:
204
+ startTime = Date.now();
205
+ logger.debug('Model request started', _object_spread$1({}, verbose && {
206
+ params: params
207
+ }));
208
+ _state.label = 1;
209
+ case 1:
210
+ _state.trys.push([
211
+ 1,
212
+ 3,
213
+ ,
214
+ 4
215
+ ]);
216
+ return [
217
+ 4,
218
+ doGenerate()
219
+ ];
220
+ case 2:
221
+ result = _state.sent();
222
+ logger.debug('Model request completed', _object_spread$1({
223
+ durationMs: Date.now() - startTime,
224
+ finishReason: result.finishReason,
225
+ usage: result.usage
226
+ }, verbose && {
227
+ content: result.content
228
+ }));
229
+ return [
230
+ 2,
231
+ result
232
+ ];
233
+ case 3:
234
+ error = _state.sent();
235
+ logger.error('Model request failed', {
236
+ durationMs: Date.now() - startTime,
237
+ error: _instanceof$1(error, Error) ? error.message : 'Unknown error'
238
+ });
239
+ throw error;
240
+ case 4:
241
+ return [
242
+ 2
243
+ ];
244
+ }
245
+ });
246
+ })();
247
+ },
248
+ wrapStream: function(param) {
249
+ var doStream = param.doStream, params = param.params;
250
+ return _async_to_generator(function() {
251
+ var startTime, result, error;
252
+ return _ts_generator(this, function(_state) {
253
+ switch(_state.label){
254
+ case 0:
255
+ startTime = Date.now();
256
+ logger.debug('Model stream started', _object_spread$1({}, verbose && {
257
+ params: params
258
+ }));
259
+ _state.label = 1;
260
+ case 1:
261
+ _state.trys.push([
262
+ 1,
263
+ 3,
264
+ ,
265
+ 4
266
+ ]);
267
+ return [
268
+ 4,
269
+ doStream()
270
+ ];
271
+ case 2:
272
+ result = _state.sent();
273
+ return [
274
+ 2,
275
+ _object_spread_props(_object_spread$1({}, result), {
276
+ stream: result.stream
277
+ })
278
+ ];
279
+ case 3:
280
+ error = _state.sent();
281
+ logger.error('Model stream failed', {
282
+ durationMs: Date.now() - startTime,
283
+ error: _instanceof$1(error, Error) ? error.message : 'Unknown error'
284
+ });
285
+ throw error;
286
+ case 4:
287
+ return [
288
+ 2
289
+ ];
290
+ }
291
+ });
292
+ })();
293
+ }
294
+ };
295
+ }
11
296
 
12
297
  /**
13
- * Custom error for structured response parsing failures
14
- */ function _assert_this_initialized(self) {
298
+ * Creates a system prompt that instructs the model to output structured data
299
+ * matching the provided Zod schema.
300
+ *
301
+ * Use this with `generateText` when the provider doesn't support native
302
+ * structured outputs, then parse the response with `parseObject`.
303
+ *
304
+ * @param schema - A Zod schema defining the expected output structure
305
+ * @returns A system prompt string with JSON schema instructions
306
+ *
307
+ * @example
308
+ * ```ts
309
+ * import { generateText } from 'ai';
310
+ * import { createSchemaPrompt, parseObject } from '@jterrazz/intelligence';
311
+ *
312
+ * const schema = z.object({ title: z.string(), tags: z.array(z.string()) });
313
+ *
314
+ * const { text } = await generateText({
315
+ * model,
316
+ * prompt: 'Generate an article about TypeScript',
317
+ * system: createSchemaPrompt(schema),
318
+ * });
319
+ *
320
+ * const result = parseObject(text, schema);
321
+ * ```
322
+ */ function createSchemaPrompt(schema) {
323
+ var jsonSchema = v4.z.toJSONSchema(schema);
324
+ var schemaJson = JSON.stringify(jsonSchema, null, 2);
325
+ var isPrimitive = [
326
+ 'boolean',
327
+ 'integer',
328
+ 'number',
329
+ 'string'
330
+ ].includes(jsonSchema.type);
331
+ if (isPrimitive) {
332
+ return "<OUTPUT_FORMAT>\nYou must respond with a ".concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(schemaJson, "\n```\n\nYour response should be only the ").concat(jsonSchema.type, " value, without any JSON wrapping or additional text.\n</OUTPUT_FORMAT>");
333
+ }
334
+ return "<OUTPUT_FORMAT>\nYou must respond with valid JSON that matches this JSON schema:\n\n```json\n".concat(schemaJson, "\n```\n\nYour response must be parseable JSON that validates against this schema. Do not include any text outside the JSON.\n</OUTPUT_FORMAT>");
335
+ }
336
+
337
+ function _array_like_to_array(arr, len) {
338
+ if (len == null || len > arr.length) len = arr.length;
339
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
340
+ return arr2;
341
+ }
342
+ function _array_with_holes(arr) {
343
+ if (Array.isArray(arr)) return arr;
344
+ }
345
+ function _assert_this_initialized(self) {
15
346
  if (self === void 0) {
16
347
  throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
17
348
  }
@@ -21,7 +352,7 @@ function _call_super(_this, derived, args) {
21
352
  derived = _get_prototype_of(derived);
22
353
  return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
23
354
  }
24
- function _class_call_check$9(instance, Constructor) {
355
+ function _class_call_check(instance, Constructor) {
25
356
  if (!(instance instanceof Constructor)) {
26
357
  throw new TypeError("Cannot call a class as a function");
27
358
  }
@@ -43,7 +374,7 @@ function _construct(Parent, args, Class) {
43
374
  }
44
375
  return _construct.apply(null, arguments);
45
376
  }
46
- function _define_property$9(obj, key, value) {
377
+ function _define_property$1(obj, key, value) {
47
378
  if (key in obj) {
48
379
  Object.defineProperty(obj, key, {
49
380
  value: value,
@@ -75,11 +406,45 @@ function _inherits(subClass, superClass) {
75
406
  });
76
407
  if (superClass) _set_prototype_of(subClass, superClass);
77
408
  }
409
+ function _instanceof(left, right) {
410
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
411
+ return !!right[Symbol.hasInstance](left);
412
+ } else {
413
+ return left instanceof right;
414
+ }
415
+ }
78
416
  function _is_native_function(fn) {
79
417
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
80
418
  }
419
+ function _iterable_to_array_limit(arr, i) {
420
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
421
+ if (_i == null) return;
422
+ var _arr = [];
423
+ var _n = true;
424
+ var _d = false;
425
+ var _s, _e;
426
+ try {
427
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
428
+ _arr.push(_s.value);
429
+ if (i && _arr.length === i) break;
430
+ }
431
+ } catch (err) {
432
+ _d = true;
433
+ _e = err;
434
+ } finally{
435
+ try {
436
+ if (!_n && _i["return"] != null) _i["return"]();
437
+ } finally{
438
+ if (_d) throw _e;
439
+ }
440
+ }
441
+ return _arr;
442
+ }
443
+ function _non_iterable_rest() {
444
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
445
+ }
81
446
  function _possible_constructor_return(self, call) {
82
- if (call && (_type_of$1(call) === "object" || typeof call === "function")) {
447
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
83
448
  return call;
84
449
  }
85
450
  return _assert_this_initialized(self);
@@ -91,10 +456,21 @@ function _set_prototype_of(o, p) {
91
456
  };
92
457
  return _set_prototype_of(o, p);
93
458
  }
94
- function _type_of$1(obj) {
459
+ function _sliced_to_array(arr, i) {
460
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
461
+ }
462
+ function _type_of(obj) {
95
463
  "@swc/helpers - typeof";
96
464
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
97
465
  }
466
+ function _unsupported_iterable_to_array(o, minLen) {
467
+ if (!o) return;
468
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
469
+ var n = Object.prototype.toString.call(o).slice(8, -1);
470
+ if (n === "Object" && o.constructor) n = o.constructor.name;
471
+ if (n === "Map" || n === "Set") return Array.from(n);
472
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
473
+ }
98
474
  function _wrap_native_super(Class) {
99
475
  var _cache = typeof Map === "function" ? new Map() : undefined;
100
476
  _wrap_native_super = function wrapNativeSuper(Class) {
@@ -129,1827 +505,266 @@ function _is_native_reflect_construct() {
129
505
  return !!result;
130
506
  })();
131
507
  }
132
- var StructuredResponseParserError = /*#__PURE__*/ function(Error1) {
133
- _inherits(StructuredResponseParserError, Error1);
134
- function StructuredResponseParserError(message, cause, text) {
135
- _class_call_check$9(this, StructuredResponseParserError);
508
+ /**
509
+ * Error thrown when object parsing fails.
510
+ * Contains the original text for debugging purposes.
511
+ */ var ParseObjectError = /*#__PURE__*/ function(Error1) {
512
+ _inherits(ParseObjectError, Error1);
513
+ function ParseObjectError(message, cause, text) {
514
+ _class_call_check(this, ParseObjectError);
136
515
  var _this;
137
- _this = _call_super(this, StructuredResponseParserError, [
516
+ _this = _call_super(this, ParseObjectError, [
138
517
  message
139
- ]), _define_property$9(_this, "cause", void 0), _define_property$9(_this, "text", void 0), _this.cause = cause, _this.text = text;
140
- _this.name = 'StructuredResponseParserError';
518
+ ]), _define_property$1(_this, "cause", void 0), _define_property$1(_this, "text", void 0), _define_property$1(_this, "name", void 0), _this.cause = cause, _this.text = text, _this.name = 'ParseObjectError';
141
519
  return _this;
142
520
  }
143
- return StructuredResponseParserError;
521
+ return ParseObjectError;
144
522
  }(_wrap_native_super(Error));
145
-
146
- function _array_like_to_array(arr, len) {
147
- if (len == null || len > arr.length) len = arr.length;
148
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
149
- return arr2;
523
+ /**
524
+ * Parses AI-generated text into structured data validated against a Zod schema.
525
+ *
526
+ * Handles common AI response formats:
527
+ * - JSON wrapped in markdown code blocks
528
+ * - JSON embedded in prose text
529
+ * - Malformed JSON (auto-repaired)
530
+ * - Escaped unicode and special characters
531
+ *
532
+ * @param text - The raw AI response text
533
+ * @param schema - A Zod schema to validate and type the result
534
+ * @returns The parsed and validated data
535
+ * @throws {ParseObjectError} When parsing or validation fails
536
+ *
537
+ * @example
538
+ * ```ts
539
+ * const schema = z.object({ title: z.string(), tags: z.array(z.string()) });
540
+ * const result = parseObject(aiResponse, schema);
541
+ * // result is typed as { title: string; tags: string[] }
542
+ * ```
543
+ */ function parseObject(text, schema) {
544
+ try {
545
+ var jsonString = extractJsonString(text);
546
+ var extracted = extractBySchemaType(jsonString, schema, text);
547
+ var unescaped = unescapeJsonValues(extracted);
548
+ return schema.parse(unescaped);
549
+ } catch (error) {
550
+ if (_instanceof(error, ParseObjectError)) {
551
+ throw error;
552
+ }
553
+ if (_instanceof(error, v4.z.ZodError)) {
554
+ throw new ParseObjectError('Failed to validate response against schema', error, text);
555
+ }
556
+ throw error;
557
+ }
150
558
  }
151
- function _array_with_holes(arr) {
152
- if (Array.isArray(arr)) return arr;
559
+ var MARKDOWN_CODE_BLOCK_RE = /```(?:json)?\r?\n([^`]*?)\r?\n```/g;
560
+ function convertToPrimitive(value, schema) {
561
+ if (_instanceof(schema, v4.z.ZodBoolean)) return Boolean(value);
562
+ if (_instanceof(schema, v4.z.ZodNull)) return null;
563
+ if (_instanceof(schema, v4.z.ZodNumber)) return Number(value);
564
+ if (_instanceof(schema, v4.z.ZodString)) return String(value);
565
+ return value;
153
566
  }
154
- function _class_call_check$8(instance, Constructor) {
155
- if (!(instance instanceof Constructor)) {
156
- throw new TypeError("Cannot call a class as a function");
567
+ function extractArray(text, originalText) {
568
+ var start = text.indexOf('[');
569
+ var end = text.lastIndexOf(']');
570
+ if (start === -1 || end === -1) {
571
+ throw new ParseObjectError('No array found in response', undefined, originalText);
157
572
  }
158
- }
159
- function _defineProperties$8(target, props) {
160
- for(var i = 0; i < props.length; i++){
161
- var descriptor = props[i];
162
- descriptor.enumerable = descriptor.enumerable || false;
163
- descriptor.configurable = true;
164
- if ("value" in descriptor) descriptor.writable = true;
165
- Object.defineProperty(target, descriptor.key, descriptor);
166
- }
167
- }
168
- function _create_class$8(Constructor, protoProps, staticProps) {
169
- if (protoProps) _defineProperties$8(Constructor.prototype, protoProps);
170
- return Constructor;
171
- }
172
- function _define_property$8(obj, key, value) {
173
- if (key in obj) {
174
- Object.defineProperty(obj, key, {
175
- value: value,
176
- enumerable: true,
177
- configurable: true,
178
- writable: true
179
- });
180
- } else {
181
- obj[key] = value;
182
- }
183
- return obj;
184
- }
185
- function _instanceof$4(left, right) {
186
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
187
- return !!right[Symbol.hasInstance](left);
188
- } else {
189
- return left instanceof right;
190
- }
191
- }
192
- function _iterable_to_array_limit(arr, i) {
193
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
194
- if (_i == null) return;
195
- var _arr = [];
196
- var _n = true;
197
- var _d = false;
198
- var _s, _e;
199
- try {
200
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
201
- _arr.push(_s.value);
202
- if (i && _arr.length === i) break;
203
- }
204
- } catch (err) {
205
- _d = true;
206
- _e = err;
207
- } finally{
208
- try {
209
- if (!_n && _i["return"] != null) _i["return"]();
210
- } finally{
211
- if (_d) throw _e;
212
- }
213
- }
214
- return _arr;
215
- }
216
- function _non_iterable_rest() {
217
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
218
- }
219
- function _sliced_to_array(arr, i) {
220
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
221
- }
222
- function _type_of(obj) {
223
- "@swc/helpers - typeof";
224
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
225
- }
226
- function _unsupported_iterable_to_array(o, minLen) {
227
- if (!o) return;
228
- if (typeof o === "string") return _array_like_to_array(o, minLen);
229
- var n = Object.prototype.toString.call(o).slice(8, -1);
230
- if (n === "Object" && o.constructor) n = o.constructor.name;
231
- if (n === "Map" || n === "Set") return Array.from(n);
232
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
233
- }
234
- /**
235
- * Parses AI response text into structured data based on Zod schema
236
- */ var StructuredResponseParser = /*#__PURE__*/ function() {
237
- function StructuredResponseParser(schema) {
238
- _class_call_check$8(this, StructuredResponseParser);
239
- _define_property$8(this, "schema", void 0);
240
- this.schema = schema;
241
- }
242
- _create_class$8(StructuredResponseParser, [
243
- {
244
- key: "parse",
245
- value: /**
246
- * Parses the AI response text based on the configured schema
247
- */ function parse(text) {
248
- try {
249
- var cleanedText = this.cleanText(text);
250
- var json = this.extractJsonFromText(cleanedText);
251
- var unescapedJson = this.unescapeJsonValues(json);
252
- return this.schema.parse(unescapedJson);
253
- } catch (error) {
254
- if (_instanceof$4(error, v4.z.ZodError)) {
255
- throw new StructuredResponseParserError('Failed to validate response against schema', error, text);
256
- }
257
- throw error;
258
- }
259
- }
260
- },
261
- {
262
- key: "cleanText",
263
- value: /**
264
- * Cleans text and finds the largest schema-compatible structure
265
- */ function cleanText(text) {
266
- var _this = this;
267
- // First try to extract from markdown code blocks
268
- var codeBlocks = text.match(/```(?:json)?\r?\n([^`]*?)\r?\n```/g);
269
- if (codeBlocks) {
270
- // Try each code block and return the largest valid one
271
- var validBlocks = codeBlocks.map(function(block) {
272
- return _this.extractJsonFromCodeBlock(block);
273
- }).filter(function(block) {
274
- return block !== null;
275
- });
276
- if (validBlocks.length > 0) {
277
- return this.findLargestString(validBlocks);
278
- }
279
- }
280
- // If no valid code blocks, try to find JSON-like structures in the text
281
- var jsonMatches = this.findJsonStructures(text);
282
- if (jsonMatches.length > 0) {
283
- return this.findLargestString(jsonMatches);
284
- }
285
- // If no JSON structures found, clean and return the original text
286
- return text.replace(/\s+/g, ' ').trim();
287
- }
288
- },
289
- {
290
- key: "convertToPrimitive",
291
- value: /**
292
- * Converts value to appropriate primitive type based on schema
293
- */ function convertToPrimitive(value, schema) {
294
- if (_instanceof$4(schema, v4.z.ZodString)) {
295
- return String(value);
296
- }
297
- if (_instanceof$4(schema, v4.z.ZodNumber)) {
298
- return Number(value);
299
- }
300
- if (_instanceof$4(schema, v4.z.ZodBoolean)) {
301
- return Boolean(value);
302
- }
303
- if (_instanceof$4(schema, v4.z.ZodNull)) {
304
- return null;
305
- }
306
- return value;
307
- }
308
- },
309
- {
310
- key: "extractArray",
311
- value: /**
312
- * Extracts array from text
313
- */ function extractArray(text) {
314
- var arrayStart = text.indexOf('[');
315
- var arrayEnd = text.lastIndexOf(']');
316
- if (arrayStart === -1 || arrayEnd === -1) {
317
- throw new StructuredResponseParserError('No array found in response', undefined, text);
318
- }
319
- try {
320
- var raw = text.slice(arrayStart, arrayEnd + 1);
321
- var repaired = this.repairJson(raw);
322
- return JSON.parse(repaired);
323
- } catch (error) {
324
- throw new StructuredResponseParserError('Failed to parse array JSON', error, text);
325
- }
326
- }
327
- },
328
- {
329
- key: "extractJsonFromCodeBlock",
330
- value: /**
331
- * Extracts and validates JSON content from a code block
332
- */ function extractJsonFromCodeBlock(block) {
333
- var content = block.replace(/```(?:json)?\r?\n([^`]*?)\r?\n```/, '$1').trim();
334
- try {
335
- // Attempt to parse as JSON to validate structure
336
- JSON.parse(content);
337
- return content;
338
- } catch (e) {
339
- return null;
340
- }
341
- }
342
- },
343
- {
344
- key: "extractJsonFromText",
345
- value: /**
346
- * Extracts and parses JSON from text based on schema type
347
- */ function extractJsonFromText(text) {
348
- if (_instanceof$4(this.schema, v4.z.ZodArray)) {
349
- return this.extractArray(text);
350
- }
351
- if (_instanceof$4(this.schema, v4.z.ZodObject)) {
352
- return this.extractObject(text);
353
- }
354
- if (_instanceof$4(this.schema, v4.z.ZodString) || _instanceof$4(this.schema, v4.z.ZodNumber) || _instanceof$4(this.schema, v4.z.ZodBoolean) || _instanceof$4(this.schema, v4.z.ZodNull)) {
355
- return this.extractPrimitive(text, this.schema);
356
- }
357
- throw new StructuredResponseParserError('Unsupported schema type', undefined, text);
358
- }
359
- },
360
- {
361
- key: "extractObject",
362
- value: /**
363
- * Extracts object from text
364
- */ function extractObject(text) {
365
- var objectStart = text.indexOf('{');
366
- var objectEnd = text.lastIndexOf('}');
367
- if (objectStart === -1 || objectEnd === -1) {
368
- throw new StructuredResponseParserError('No object found in response', undefined, text);
369
- }
370
- try {
371
- var raw = text.slice(objectStart, objectEnd + 1);
372
- var repaired = this.repairJson(raw);
373
- return JSON.parse(repaired);
374
- } catch (error) {
375
- throw new StructuredResponseParserError('Failed to parse object JSON', error, text);
376
- }
377
- }
378
- },
379
- {
380
- key: "extractPrimitive",
381
- value: /**
382
- * Extracts and converts primitive value from text
383
- */ function extractPrimitive(text, schema) {
384
- var trimmed = text.trim();
385
- // Try to parse as JSON first in case it's quoted
386
- try {
387
- var parsed = JSON.parse(trimmed);
388
- return this.convertToPrimitive(parsed, schema);
389
- } catch (e) {
390
- // If not valid JSON, use the raw string
391
- return this.convertToPrimitive(trimmed, schema);
392
- }
393
- }
394
- },
395
- {
396
- key: "findJsonStructures",
397
- value: /**
398
- * Finds valid JSON structures in raw text
399
- */ function findJsonStructures(text) {
400
- var jsonMatches = [];
401
- var depth = 0;
402
- var start = -1;
403
- for(var i = 0; i < text.length; i++){
404
- var char = text[i];
405
- if (char === '{' || char === '[') {
406
- if (depth === 0) start = i;
407
- depth++;
408
- } else if (char === '}' || char === ']') {
409
- depth--;
410
- if (depth === 0 && start !== -1) {
411
- var potentialJson = text.slice(start, i + 1);
412
- try {
413
- JSON.parse(potentialJson);
414
- jsonMatches.push(potentialJson);
415
- } catch (e) {
416
- // Invalid JSON, ignore
417
- }
418
- }
419
- }
420
- }
421
- return jsonMatches;
422
- }
423
- },
424
- {
425
- key: "findLargestString",
426
- value: /**
427
- * Returns the largest string from an array of strings
428
- */ function findLargestString(strings) {
429
- return strings.reduce(function(largest, current) {
430
- return current.length > largest.length ? current : largest;
431
- }, strings[0]);
432
- }
433
- },
434
- {
435
- key: "repairJson",
436
- value: /**
437
- * Repairs common JSON issues using jsonrepair library
438
- */ function repairJson(jsonString) {
439
- return jsonrepair.jsonrepair(jsonString);
440
- }
441
- },
442
- {
443
- key: "unescapeJsonValues",
444
- value: /**
445
- * Recursively unescapes all string values in a JSON object/array
446
- */ function unescapeJsonValues(json) {
447
- var _this = this;
448
- if (typeof json === 'string') {
449
- return this.unescapeText(json);
450
- }
451
- if (Array.isArray(json)) {
452
- return json.map(function(item) {
453
- return _this.unescapeJsonValues(item);
454
- });
455
- }
456
- if ((typeof json === "undefined" ? "undefined" : _type_of(json)) === 'object' && json !== null) {
457
- return Object.fromEntries(Object.entries(json).map(function(param) {
458
- var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1];
459
- return [
460
- key,
461
- _this.unescapeJsonValues(value)
462
- ];
463
- }));
464
- }
465
- return json;
466
- }
467
- },
468
- {
469
- key: "unescapeText",
470
- value: /**
471
- * Unescapes common escaped characters in text
472
- */ function unescapeText(text) {
473
- return text.replace(/\\"/g, '"') // Unescape quotes
474
- .replace(/\\n/g, '\n') // Unescape newlines
475
- .replace(/\\r/g, '\r') // Unescape carriage returns
476
- .replace(/\\t/g, '\t') // Unescape tabs
477
- .replace(/\\\\/g, '\\') // Unescape backslashes
478
- .replace(/\\u([0-9a-fA-F]{4})/g, function(_, code) {
479
- return String.fromCharCode(parseInt(code, 16));
480
- }); // Unescape unicode
481
- }
482
- }
483
- ]);
484
- return StructuredResponseParser;
485
- }();
486
-
487
- function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) {
488
- try {
489
- var info = gen[key](arg);
490
- var value = info.value;
491
- } catch (error) {
492
- reject(error);
493
- return;
494
- }
495
- if (info.done) {
496
- resolve(value);
497
- } else {
498
- Promise.resolve(value).then(_next, _throw);
499
- }
500
- }
501
- function _async_to_generator$3(fn) {
502
- return function() {
503
- var self = this, args = arguments;
504
- return new Promise(function(resolve, reject) {
505
- var gen = fn.apply(self, args);
506
- function _next(value) {
507
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value);
508
- }
509
- function _throw(err) {
510
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err);
511
- }
512
- _next(undefined);
513
- });
514
- };
515
- }
516
- function _class_call_check$7(instance, Constructor) {
517
- if (!(instance instanceof Constructor)) {
518
- throw new TypeError("Cannot call a class as a function");
519
- }
520
- }
521
- function _defineProperties$7(target, props) {
522
- for(var i = 0; i < props.length; i++){
523
- var descriptor = props[i];
524
- descriptor.enumerable = descriptor.enumerable || false;
525
- descriptor.configurable = true;
526
- if ("value" in descriptor) descriptor.writable = true;
527
- Object.defineProperty(target, descriptor.key, descriptor);
528
- }
529
- }
530
- function _create_class$7(Constructor, protoProps, staticProps) {
531
- if (protoProps) _defineProperties$7(Constructor.prototype, protoProps);
532
- return Constructor;
533
- }
534
- function _define_property$7(obj, key, value) {
535
- if (key in obj) {
536
- Object.defineProperty(obj, key, {
537
- value: value,
538
- enumerable: true,
539
- configurable: true,
540
- writable: true
541
- });
542
- } else {
543
- obj[key] = value;
544
- }
545
- return obj;
546
- }
547
- function _instanceof$3(left, right) {
548
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
549
- return !!right[Symbol.hasInstance](left);
550
- } else {
551
- return left instanceof right;
552
- }
553
- }
554
- function _ts_generator$3(thisArg, body) {
555
- var f, y, t, _ = {
556
- label: 0,
557
- sent: function() {
558
- if (t[0] & 1) throw t[1];
559
- return t[1];
560
- },
561
- trys: [],
562
- ops: []
563
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
564
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
565
- return this;
566
- }), g;
567
- function verb(n) {
568
- return function(v) {
569
- return step([
570
- n,
571
- v
572
- ]);
573
- };
574
- }
575
- function step(op) {
576
- if (f) throw new TypeError("Generator is already executing.");
577
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
578
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
579
- if (y = 0, t) op = [
580
- op[0] & 2,
581
- t.value
582
- ];
583
- switch(op[0]){
584
- case 0:
585
- case 1:
586
- t = op;
587
- break;
588
- case 4:
589
- _.label++;
590
- return {
591
- value: op[1],
592
- done: false
593
- };
594
- case 5:
595
- _.label++;
596
- y = op[1];
597
- op = [
598
- 0
599
- ];
600
- continue;
601
- case 7:
602
- op = _.ops.pop();
603
- _.trys.pop();
604
- continue;
605
- default:
606
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
607
- _ = 0;
608
- continue;
609
- }
610
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
611
- _.label = op[1];
612
- break;
613
- }
614
- if (op[0] === 6 && _.label < t[1]) {
615
- _.label = t[1];
616
- t = op;
617
- break;
618
- }
619
- if (t && _.label < t[2]) {
620
- _.label = t[2];
621
- _.ops.push(op);
622
- break;
623
- }
624
- if (t[2]) _.ops.pop();
625
- _.trys.pop();
626
- continue;
627
- }
628
- op = body.call(thisArg, _);
629
- } catch (e) {
630
- op = [
631
- 6,
632
- e
633
- ];
634
- y = 0;
635
- } finally{
636
- f = t = 0;
637
- }
638
- if (op[0] & 5) throw op[1];
639
- return {
640
- value: op[0] ? op[1] : void 0,
641
- done: true
642
- };
643
- }
644
- }
645
- /**
646
- * A conversational agent for direct, one-shot interactions with a model.
647
- * It supports optional response parsing against a Zod schema but does not use tools.
648
- * @template TOutput - The TypeScript type of the output
649
- */ var ChatAgent = /*#__PURE__*/ function() {
650
- function ChatAgent(name, options) {
651
- _class_call_check$7(this, ChatAgent);
652
- _define_property$7(this, "name", void 0);
653
- _define_property$7(this, "options", void 0);
654
- this.name = name;
655
- this.options = options;
656
- }
657
- _create_class$7(ChatAgent, [
658
- {
659
- key: "run",
660
- value: function run(input) {
661
- return _async_to_generator$3(function() {
662
- var _this_options_logger, content, _this_options_logger1, parsedResponse, _this_options_logger2, error, _this_options_logger3;
663
- return _ts_generator$3(this, function(_state) {
664
- switch(_state.label){
665
- case 0:
666
- (_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.debug('Starting query execution', {
667
- agent: this.name
668
- });
669
- _state.label = 1;
670
- case 1:
671
- _state.trys.push([
672
- 1,
673
- 3,
674
- ,
675
- 4
676
- ]);
677
- return [
678
- 4,
679
- this.invokeModel(input)
680
- ];
681
- case 2:
682
- content = _state.sent();
683
- if (this.options.schema) {
684
- parsedResponse = this.parseResponse(content, this.options.schema);
685
- (_this_options_logger1 = this.options.logger) === null || _this_options_logger1 === void 0 ? void 0 : _this_options_logger1.debug('Execution finished and response parsed', {
686
- agent: this.name
687
- });
688
- return [
689
- 2,
690
- parsedResponse
691
- ];
692
- } else {
693
- (_this_options_logger2 = this.options.logger) === null || _this_options_logger2 === void 0 ? void 0 : _this_options_logger2.debug('Execution finished', {
694
- agent: this.name
695
- });
696
- return [
697
- 2,
698
- content
699
- ];
700
- }
701
- case 3:
702
- error = _state.sent();
703
- (_this_options_logger3 = this.options.logger) === null || _this_options_logger3 === void 0 ? void 0 : _this_options_logger3.error('Execution failed', {
704
- agent: this.name,
705
- error: _instanceof$3(error, Error) ? error.message : 'Unknown error',
706
- errorStack: _instanceof$3(error, Error) ? error.stack : undefined
707
- });
708
- return [
709
- 2,
710
- null
711
- ];
712
- case 4:
713
- return [
714
- 2
715
- ];
716
- }
717
- });
718
- }).call(this);
719
- }
720
- },
721
- {
722
- key: "invokeModel",
723
- value: function invokeModel(input) {
724
- return _async_to_generator$3(function() {
725
- var _this_options_logger, userInput, systemMessage, jsonSchema, isPrimitiveType, messages, _this_options_logger1, generateConfig, jsonSchema1, text;
726
- return _ts_generator$3(this, function(_state) {
727
- switch(_state.label){
728
- case 0:
729
- userInput = this.resolveUserInput(input);
730
- systemMessage = this.options.systemPrompt.generate();
731
- if (this.options.schema) {
732
- jsonSchema = v4.z.toJSONSchema(this.options.schema);
733
- isPrimitiveType = [
734
- 'boolean',
735
- 'integer',
736
- 'number',
737
- 'string'
738
- ].includes(jsonSchema.type);
739
- if (isPrimitiveType) {
740
- systemMessage += "\n\n<OUTPUT_FORMAT>\nYou must respond with a ".concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(JSON.stringify(jsonSchema, null, 2), "\n```\n\nYour response should be only the ").concat(jsonSchema.type, " value, without any JSON wrapping or additional text.\n</OUTPUT_FORMAT>");
741
- } else {
742
- systemMessage += "\n\n<OUTPUT_FORMAT>\nYou must respond with valid JSON that matches this JSON schema description:\n\n```json\n".concat(JSON.stringify(jsonSchema, null, 2), "\n```\n\nYour response must be parseable JSON that validates against this schema. Do not include any text outside the JSON.\n</OUTPUT_FORMAT>");
743
- }
744
- }
745
- messages = [
746
- {
747
- content: systemMessage,
748
- role: 'system'
749
- },
750
- {
751
- content: userInput,
752
- role: 'user'
753
- }
754
- ];
755
- (_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.debug('Invoking model...', {
756
- agent: this.name,
757
- hasSchema: !!this.options.schema
758
- });
759
- if (this.options.verbose) {
760
- (_this_options_logger1 = this.options.logger) === null || _this_options_logger1 === void 0 ? void 0 : _this_options_logger1.debug('Sending messages to model...', {
761
- agent: this.name,
762
- messages: messages
763
- });
764
- }
765
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
766
- generateConfig = {
767
- messages: messages,
768
- model: this.options.model.getVercelModel()
769
- };
770
- // Prepare structured outputs configuration for better schema validation when schema is provided
771
- // NOTE: OpenRouter supports structured outputs, but @openrouter/ai-sdk-provider (v0.7.3)
772
- // doesn't pass through responseFormat parameter yet. Currently relies on prompt-based instructions.
773
- // Once provider support is added, this will provide stronger guarantees than prompts alone.
774
- // See: https://openrouter.ai/docs/features/structured-outputs
775
- if (this.options.schema) {
776
- jsonSchema1 = v4.z.toJSONSchema(this.options.schema);
777
- generateConfig.responseFormat = {
778
- json_schema: {
779
- name: 'response',
780
- schema: jsonSchema1,
781
- strict: true
782
- },
783
- type: 'json_schema'
784
- };
785
- }
786
- return [
787
- 4,
788
- ai.generateText(generateConfig)
789
- ];
790
- case 1:
791
- text = _state.sent().text;
792
- return [
793
- 2,
794
- text
795
- ];
796
- }
797
- });
798
- }).call(this);
799
- }
800
- },
801
- {
802
- key: "parseResponse",
803
- value: function parseResponse(content, schema) {
804
- try {
805
- return new StructuredResponseParser(schema).parse(content);
806
- } catch (error) {
807
- var _this_options_logger;
808
- (_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error('Failed to parse model response.', {
809
- agent: this.name,
810
- error: _instanceof$3(error, Error) ? error.message : 'Unknown error',
811
- rawContent: content
812
- });
813
- throw new Error('Invalid response format from model.');
814
- }
815
- }
816
- },
817
- {
818
- key: "resolveUserInput",
819
- value: function resolveUserInput(input) {
820
- if (input) {
821
- return input.generate();
822
- }
823
- return 'Proceed with your instructions.';
824
- }
825
- }
826
- ]);
827
- return ChatAgent;
828
- }();
829
-
830
- function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
831
- try {
832
- var info = gen[key](arg);
833
- var value = info.value;
834
- } catch (error) {
835
- reject(error);
836
- return;
837
- }
838
- if (info.done) {
839
- resolve(value);
840
- } else {
841
- Promise.resolve(value).then(_next, _throw);
842
- }
843
- }
844
- function _async_to_generator$2(fn) {
845
- return function() {
846
- var self = this, args = arguments;
847
- return new Promise(function(resolve, reject) {
848
- var gen = fn.apply(self, args);
849
- function _next(value) {
850
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
851
- }
852
- function _throw(err) {
853
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
854
- }
855
- _next(undefined);
856
- });
857
- };
858
- }
859
- function _class_call_check$6(instance, Constructor) {
860
- if (!(instance instanceof Constructor)) {
861
- throw new TypeError("Cannot call a class as a function");
862
- }
863
- }
864
- function _defineProperties$6(target, props) {
865
- for(var i = 0; i < props.length; i++){
866
- var descriptor = props[i];
867
- descriptor.enumerable = descriptor.enumerable || false;
868
- descriptor.configurable = true;
869
- if ("value" in descriptor) descriptor.writable = true;
870
- Object.defineProperty(target, descriptor.key, descriptor);
871
- }
872
- }
873
- function _create_class$6(Constructor, protoProps, staticProps) {
874
- if (protoProps) _defineProperties$6(Constructor.prototype, protoProps);
875
- return Constructor;
876
- }
877
- function _define_property$6(obj, key, value) {
878
- if (key in obj) {
879
- Object.defineProperty(obj, key, {
880
- value: value,
881
- enumerable: true,
882
- configurable: true,
883
- writable: true
884
- });
885
- } else {
886
- obj[key] = value;
887
- }
888
- return obj;
889
- }
890
- function _instanceof$2(left, right) {
891
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
892
- return !!right[Symbol.hasInstance](left);
893
- } else {
894
- return left instanceof right;
895
- }
896
- }
897
- function _ts_generator$2(thisArg, body) {
898
- var f, y, t, _ = {
899
- label: 0,
900
- sent: function() {
901
- if (t[0] & 1) throw t[1];
902
- return t[1];
903
- },
904
- trys: [],
905
- ops: []
906
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
907
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
908
- return this;
909
- }), g;
910
- function verb(n) {
911
- return function(v) {
912
- return step([
913
- n,
914
- v
915
- ]);
916
- };
917
- }
918
- function step(op) {
919
- if (f) throw new TypeError("Generator is already executing.");
920
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
921
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
922
- if (y = 0, t) op = [
923
- op[0] & 2,
924
- t.value
925
- ];
926
- switch(op[0]){
927
- case 0:
928
- case 1:
929
- t = op;
930
- break;
931
- case 4:
932
- _.label++;
933
- return {
934
- value: op[1],
935
- done: false
936
- };
937
- case 5:
938
- _.label++;
939
- y = op[1];
940
- op = [
941
- 0
942
- ];
943
- continue;
944
- case 7:
945
- op = _.ops.pop();
946
- _.trys.pop();
947
- continue;
948
- default:
949
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
950
- _ = 0;
951
- continue;
952
- }
953
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
954
- _.label = op[1];
955
- break;
956
- }
957
- if (op[0] === 6 && _.label < t[1]) {
958
- _.label = t[1];
959
- t = op;
960
- break;
961
- }
962
- if (t && _.label < t[2]) {
963
- _.label = t[2];
964
- _.ops.push(op);
965
- break;
966
- }
967
- if (t[2]) _.ops.pop();
968
- _.trys.pop();
969
- continue;
970
- }
971
- op = body.call(thisArg, _);
972
- } catch (e) {
973
- op = [
974
- 6,
975
- e
976
- ];
977
- y = 0;
978
- } finally{
979
- f = t = 0;
980
- }
981
- if (op[0] & 5) throw op[1];
982
- return {
983
- value: op[0] ? op[1] : void 0,
984
- done: true
985
- };
986
- }
987
- }
988
- /**
989
- * A decorator agent that adds retry logic to an existing agent for resilient execution.
990
- * @template TInput - The TypeScript type of the input
991
- * @template TOutput - The TypeScript type of the output
992
- */ var ResilientAgent = /*#__PURE__*/ function() {
993
- function ResilientAgent(agent) {
994
- var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
995
- _class_call_check$6(this, ResilientAgent);
996
- _define_property$6(this, "agent", void 0);
997
- _define_property$6(this, "name", void 0);
998
- _define_property$6(this, "logger", void 0);
999
- _define_property$6(this, "retries", void 0);
1000
- this.agent = agent;
1001
- var logger = options.logger, _options_retries = options.retries, retries = _options_retries === void 0 ? 1 : _options_retries;
1002
- this.name = "Resilient(".concat(agent.name, ")");
1003
- this.logger = logger;
1004
- this.retries = retries;
1005
- }
1006
- _create_class$6(ResilientAgent, [
1007
- {
1008
- key: "run",
1009
- value: function run(input) {
1010
- return _async_to_generator$2(function() {
1011
- var _this_logger, maxAttempts, attempt, _this_logger1, _this_logger2, result, _this_logger3, error, _this_logger4;
1012
- return _ts_generator$2(this, function(_state) {
1013
- switch(_state.label){
1014
- case 0:
1015
- maxAttempts = this.retries + 1;
1016
- attempt = 1;
1017
- _state.label = 1;
1018
- case 1:
1019
- if (!(attempt <= maxAttempts)) return [
1020
- 3,
1021
- 6
1022
- ];
1023
- _state.label = 2;
1024
- case 2:
1025
- _state.trys.push([
1026
- 2,
1027
- 4,
1028
- ,
1029
- 5
1030
- ]);
1031
- (_this_logger1 = this.logger) === null || _this_logger1 === void 0 ? void 0 : _this_logger1.debug("Attempt ".concat(attempt, " of ").concat(maxAttempts), {
1032
- agent: this.name
1033
- });
1034
- return [
1035
- 4,
1036
- this.agent.run(input)
1037
- ];
1038
- case 3:
1039
- result = _state.sent();
1040
- if (result !== null) {
1041
- (_this_logger3 = this.logger) === null || _this_logger3 === void 0 ? void 0 : _this_logger3.debug("Attempt ".concat(attempt, " of ").concat(maxAttempts, " succeeded"), {
1042
- agent: this.name
1043
- });
1044
- return [
1045
- 2,
1046
- result
1047
- ];
1048
- }
1049
- (_this_logger2 = this.logger) === null || _this_logger2 === void 0 ? void 0 : _this_logger2.debug("Attempt ".concat(attempt, " of ").concat(maxAttempts, " failed: agent returned null"), {
1050
- agent: this.name
1051
- });
1052
- return [
1053
- 3,
1054
- 5
1055
- ];
1056
- case 4:
1057
- error = _state.sent();
1058
- (_this_logger4 = this.logger) === null || _this_logger4 === void 0 ? void 0 : _this_logger4.debug("Attempt ".concat(attempt, " of ").concat(maxAttempts, " failed with an error"), {
1059
- agent: this.name,
1060
- error: _instanceof$2(error, Error) ? error.message : 'Unknown error'
1061
- });
1062
- return [
1063
- 3,
1064
- 5
1065
- ];
1066
- case 5:
1067
- attempt++;
1068
- return [
1069
- 3,
1070
- 1
1071
- ];
1072
- case 6:
1073
- (_this_logger = this.logger) === null || _this_logger === void 0 ? void 0 : _this_logger.error("All ".concat(maxAttempts, " attempts failed"), {
1074
- agent: this.name
1075
- });
1076
- return [
1077
- 2,
1078
- null
1079
- ];
1080
- }
1081
- });
1082
- }).call(this);
1083
- }
1084
- }
1085
- ]);
1086
- return ResilientAgent;
1087
- }();
1088
-
1089
- function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
1090
573
  try {
1091
- var info = gen[key](arg);
1092
- var value = info.value;
574
+ var raw = text.slice(start, end + 1);
575
+ return JSON.parse(jsonrepair.jsonrepair(raw));
1093
576
  } catch (error) {
1094
- reject(error);
1095
- return;
1096
- }
1097
- if (info.done) {
1098
- resolve(value);
1099
- } else {
1100
- Promise.resolve(value).then(_next, _throw);
1101
- }
1102
- }
1103
- function _async_to_generator$1(fn) {
1104
- return function() {
1105
- var self = this, args = arguments;
1106
- return new Promise(function(resolve, reject) {
1107
- var gen = fn.apply(self, args);
1108
- function _next(value) {
1109
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
1110
- }
1111
- function _throw(err) {
1112
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
1113
- }
1114
- _next(undefined);
1115
- });
1116
- };
1117
- }
1118
- function _class_call_check$5(instance, Constructor) {
1119
- if (!(instance instanceof Constructor)) {
1120
- throw new TypeError("Cannot call a class as a function");
1121
- }
1122
- }
1123
- function _defineProperties$5(target, props) {
1124
- for(var i = 0; i < props.length; i++){
1125
- var descriptor = props[i];
1126
- descriptor.enumerable = descriptor.enumerable || false;
1127
- descriptor.configurable = true;
1128
- if ("value" in descriptor) descriptor.writable = true;
1129
- Object.defineProperty(target, descriptor.key, descriptor);
1130
- }
1131
- }
1132
- function _create_class$5(Constructor, protoProps, staticProps) {
1133
- if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
1134
- return Constructor;
1135
- }
1136
- function _define_property$5(obj, key, value) {
1137
- if (key in obj) {
1138
- Object.defineProperty(obj, key, {
1139
- value: value,
1140
- enumerable: true,
1141
- configurable: true,
1142
- writable: true
1143
- });
1144
- } else {
1145
- obj[key] = value;
1146
- }
1147
- return obj;
1148
- }
1149
- function _instanceof$1(left, right) {
1150
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
1151
- return !!right[Symbol.hasInstance](left);
1152
- } else {
1153
- return left instanceof right;
1154
- }
1155
- }
1156
- function _ts_generator$1(thisArg, body) {
1157
- var f, y, t, _ = {
1158
- label: 0,
1159
- sent: function() {
1160
- if (t[0] & 1) throw t[1];
1161
- return t[1];
1162
- },
1163
- trys: [],
1164
- ops: []
1165
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
1166
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
1167
- return this;
1168
- }), g;
1169
- function verb(n) {
1170
- return function(v) {
1171
- return step([
1172
- n,
1173
- v
1174
- ]);
1175
- };
1176
- }
1177
- function step(op) {
1178
- if (f) throw new TypeError("Generator is already executing.");
1179
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1180
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1181
- if (y = 0, t) op = [
1182
- op[0] & 2,
1183
- t.value
1184
- ];
1185
- switch(op[0]){
1186
- case 0:
1187
- case 1:
1188
- t = op;
1189
- break;
1190
- case 4:
1191
- _.label++;
1192
- return {
1193
- value: op[1],
1194
- done: false
1195
- };
1196
- case 5:
1197
- _.label++;
1198
- y = op[1];
1199
- op = [
1200
- 0
1201
- ];
1202
- continue;
1203
- case 7:
1204
- op = _.ops.pop();
1205
- _.trys.pop();
1206
- continue;
1207
- default:
1208
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1209
- _ = 0;
1210
- continue;
1211
- }
1212
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1213
- _.label = op[1];
1214
- break;
1215
- }
1216
- if (op[0] === 6 && _.label < t[1]) {
1217
- _.label = t[1];
1218
- t = op;
1219
- break;
1220
- }
1221
- if (t && _.label < t[2]) {
1222
- _.label = t[2];
1223
- _.ops.push(op);
1224
- break;
1225
- }
1226
- if (t[2]) _.ops.pop();
1227
- _.trys.pop();
1228
- continue;
1229
- }
1230
- op = body.call(thisArg, _);
1231
- } catch (e) {
1232
- op = [
1233
- 6,
1234
- e
1235
- ];
1236
- y = 0;
1237
- } finally{
1238
- f = t = 0;
1239
- }
1240
- if (op[0] & 5) throw op[1];
1241
- return {
1242
- value: op[0] ? op[1] : void 0,
1243
- done: true
1244
- };
1245
- }
1246
- }
1247
- var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<GLOBAL_WRAPPER_OUTPUT_FORMAT>\nCRITICAL: The format instructions in this section are the ONLY valid way to structure your response. Your entire response MUST be a single JSON markdown code block. Any formatting guidelines within the <OBJECTIVE> section apply ONLY to the content inside the "RESPOND:" part of your final "action_input".\n\nREQUIRED: You have two ways to respond:\n\n1. **Call a tool** to gather information. For this, you MUST output a JSON blob with the tool\'s name and its input.\n *Valid tool names are: {tool_names}*\n ```json\n {{\n "action": "tool_name_to_use",\n "action_input": "the input for the tool, or an empty object {{}} if no input is needed"\n }}\n ```\n\n2. **Provide the Final Answer** once you have enough information. For this, you MUST output a JSON blob with the "Final Answer" action.\n The "action_input" for a "Final Answer" MUST be a string that begins with either "RESPOND: " for a message or "SILENT: " for no message. This prefix is a literal part of the output string and MUST NOT be omitted.\n - To send a message:\n ```json\n {{\n "action": "Final Answer",\n "action_input": "RESPOND: <your response message>"\n }}\n ```\n - To stay silent:\n ```json\n {{\n "action": "Final Answer",\n "action_input": "SILENT: <your reason for staying silent>"\n }}\n ```\n\n YOU MUST ALWAYS INCLUDE "RESPOND:" OR "SILENT:" IN YOUR FINAL ANSWER\'S "action_input". FAILURE TO DO SO WILL CAUSE AN ERROR.\n\n{schema_format}\n</OUTPUT_FORMAT>\n\n<EXECUTION_CONTEXT>\nThis is internal data for your reference.\n\n<TOOLS>\n{tools}\n</TOOLS>\n\n<WORKING_MEMORY>\nThis is your internal thought process and previous tool usage.\n{agent_scratchpad}\n</WORKING_MEMORY>\n</EXECUTION_CONTEXT>\n';
1248
- /**
1249
- * A tool-enabled agent that uses tools and a structured prompt to accomplish tasks.
1250
- * It can decide whether to respond or remain silent and supports schema-validated responses.
1251
- * @template TOutput - The TypeScript type of the output
1252
- */ var ToolAgent = /*#__PURE__*/ function() {
1253
- function ToolAgent(name, options) {
1254
- _class_call_check$5(this, ToolAgent);
1255
- _define_property$5(this, "name", void 0);
1256
- _define_property$5(this, "options", void 0);
1257
- this.name = name;
1258
- this.options = options;
1259
- }
1260
- _create_class$5(ToolAgent, [
1261
- {
1262
- key: "run",
1263
- value: function run(input) {
1264
- return _async_to_generator$1(function() {
1265
- var _this_options_logger, _this_options_logger1, executor, userInput, result, agentResponse, _this_options_logger2, _agentResponse_message, message, _this_options_logger3, validatedResponse, _this_options_logger4, error, _this_options_logger5;
1266
- return _ts_generator$1(this, function(_state) {
1267
- switch(_state.label){
1268
- case 0:
1269
- (_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.debug('Starting chat execution', {
1270
- agent: this.name
1271
- });
1272
- _state.label = 1;
1273
- case 1:
1274
- _state.trys.push([
1275
- 1,
1276
- 4,
1277
- ,
1278
- 5
1279
- ]);
1280
- return [
1281
- 4,
1282
- this.createExecutor()
1283
- ];
1284
- case 2:
1285
- executor = _state.sent();
1286
- userInput = this.resolveUserInput(input);
1287
- return [
1288
- 4,
1289
- executor.invoke({
1290
- input: userInput
1291
- })
1292
- ];
1293
- case 3:
1294
- result = _state.sent();
1295
- (_this_options_logger1 = this.options.logger) === null || _this_options_logger1 === void 0 ? void 0 : _this_options_logger1.debug('Agent execution completed', {
1296
- agent: this.name,
1297
- hasOutput: 'output' in result
1298
- });
1299
- if (!result || typeof result.output !== 'string') {
1300
- throw new Error('Agent returned an invalid result structure.');
1301
- }
1302
- agentResponse = this.parseAgentOutput(result.output);
1303
- if (!agentResponse) {
1304
- return [
1305
- 2,
1306
- null
1307
- ];
1308
- }
1309
- if (!agentResponse.shouldRespond) {
1310
- (_this_options_logger2 = this.options.logger) === null || _this_options_logger2 === void 0 ? void 0 : _this_options_logger2.debug('Agent chose to remain silent', {
1311
- agent: this.name,
1312
- reason: agentResponse.reason
1313
- });
1314
- return [
1315
- 2,
1316
- null
1317
- ];
1318
- }
1319
- message = (_agentResponse_message = agentResponse.message) !== null && _agentResponse_message !== void 0 ? _agentResponse_message : '';
1320
- if (this.options.schema) {
1321
- validatedResponse = this.validateResponseContent(message, this.options.schema);
1322
- (_this_options_logger3 = this.options.logger) === null || _this_options_logger3 === void 0 ? void 0 : _this_options_logger3.debug('Execution finished; response content validated.', {
1323
- agent: this.name
1324
- });
1325
- return [
1326
- 2,
1327
- validatedResponse
1328
- ];
1329
- } else {
1330
- (_this_options_logger4 = this.options.logger) === null || _this_options_logger4 === void 0 ? void 0 : _this_options_logger4.debug('Execution finished', {
1331
- agent: this.name
1332
- });
1333
- // When no schema is provided, we assume TOutput is string (default), so message is the result
1334
- return [
1335
- 2,
1336
- message
1337
- ];
1338
- }
1339
- case 4:
1340
- error = _state.sent();
1341
- (_this_options_logger5 = this.options.logger) === null || _this_options_logger5 === void 0 ? void 0 : _this_options_logger5.error('Chat execution failed', {
1342
- agent: this.name,
1343
- error: _instanceof$1(error, Error) ? error.message : 'Unknown error'
1344
- });
1345
- return [
1346
- 2,
1347
- null
1348
- ];
1349
- case 5:
1350
- return [
1351
- 2
1352
- ];
1353
- }
1354
- });
1355
- }).call(this);
1356
- }
1357
- },
1358
- {
1359
- key: "createExecutor",
1360
- value: function createExecutor() {
1361
- return _async_to_generator$1(function() {
1362
- var model, tools, schemaFormatInstructions, jsonSchema, isPrimitiveType, jsonSchemaString, prompt, agent;
1363
- return _ts_generator$1(this, function(_state) {
1364
- switch(_state.label){
1365
- case 0:
1366
- model = this.options.model.getLangchainModel();
1367
- tools = this.options.tools.map(function(tool) {
1368
- return tool.getDynamicTool();
1369
- });
1370
- // Add schema format instructions if schema is provided
1371
- schemaFormatInstructions = '';
1372
- if (this.options.schema) {
1373
- jsonSchema = v4.z.toJSONSchema(this.options.schema);
1374
- isPrimitiveType = [
1375
- 'boolean',
1376
- 'integer',
1377
- 'number',
1378
- 'string'
1379
- ].includes(jsonSchema.type);
1380
- jsonSchemaString = JSON.stringify(jsonSchema, null, 2).replace(/{/g, '{{').replace(/}/g, '}}');
1381
- if (isPrimitiveType) {
1382
- schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be a '.concat(jsonSchema.type, " value that matches this schema description:\n\n```json\n").concat(jsonSchemaString, '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: your ').concat(jsonSchema.type, ' value here"\n}}\n```\n\nDo not wrap the ').concat(jsonSchema.type, ' value in JSON - just provide the raw value after "RESPOND: ".');
1383
- } else {
1384
- schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be valid JSON that matches this JSON schema description:\n\n```json\n'.concat(jsonSchemaString, '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: {{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}"\n}}\n```\n');
1385
- }
1386
- }
1387
- prompt = prompts.ChatPromptTemplate.fromMessages([
1388
- [
1389
- 'system',
1390
- SYSTEM_PROMPT_TEMPLATE.replace('{mission_prompt}', this.options.systemPrompt.generate()).replace('{schema_format}', schemaFormatInstructions)
1391
- ],
1392
- [
1393
- 'human',
1394
- '{input}'
1395
- ]
1396
- ]);
1397
- return [
1398
- 4,
1399
- agents.createStructuredChatAgent({
1400
- llm: model,
1401
- prompt: prompt,
1402
- tools: tools
1403
- })
1404
- ];
1405
- case 1:
1406
- agent = _state.sent();
1407
- return [
1408
- 2,
1409
- agents.AgentExecutor.fromAgentAndTools({
1410
- agent: agent,
1411
- tools: tools,
1412
- verbose: this.options.verbose
1413
- })
1414
- ];
1415
- }
1416
- });
1417
- }).call(this);
1418
- }
1419
- },
1420
- {
1421
- key: "parseAgentOutput",
1422
- value: function parseAgentOutput(output) {
1423
- var _this_options_logger;
1424
- var text = output.trim();
1425
- var respondMatch = text.match(/^RESPOND:\s*([\s\S]+)$/i);
1426
- if (respondMatch) {
1427
- return {
1428
- message: respondMatch[1].trim(),
1429
- shouldRespond: true
1430
- };
1431
- }
1432
- var silentMatch = text.match(/^SILENT:\s*([\s\S]+)$/i);
1433
- if (silentMatch) {
1434
- return {
1435
- reason: silentMatch[1].trim(),
1436
- shouldRespond: false
1437
- };
1438
- }
1439
- (_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error("Agent output was missing 'RESPOND:' or 'SILENT:' prefix.", {
1440
- agent: this.name,
1441
- rawOutput: output
1442
- });
1443
- return null;
1444
- }
1445
- },
1446
- {
1447
- key: "resolveUserInput",
1448
- value: function resolveUserInput(input) {
1449
- if (input) {
1450
- return input.generate();
1451
- }
1452
- return 'Proceed with your instructions.';
1453
- }
1454
- },
1455
- {
1456
- key: "validateResponseContent",
1457
- value: function validateResponseContent(content, schema) {
1458
- try {
1459
- return new StructuredResponseParser(schema).parse(content);
1460
- } catch (error) {
1461
- var _this_options_logger;
1462
- (_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error('Failed to validate response content against schema.', {
1463
- agent: this.name,
1464
- error: _instanceof$1(error, Error) ? error.message : 'Unknown error',
1465
- rawContent: content
1466
- });
1467
- throw new Error('Invalid response content from model.');
1468
- }
1469
- }
1470
- }
1471
- ]);
1472
- return ToolAgent;
1473
- }();
1474
-
1475
- function _class_call_check$4(instance, Constructor) {
1476
- if (!(instance instanceof Constructor)) {
1477
- throw new TypeError("Cannot call a class as a function");
1478
- }
1479
- }
1480
- function _defineProperties$4(target, props) {
1481
- for(var i = 0; i < props.length; i++){
1482
- var descriptor = props[i];
1483
- descriptor.enumerable = descriptor.enumerable || false;
1484
- descriptor.configurable = true;
1485
- if ("value" in descriptor) descriptor.writable = true;
1486
- Object.defineProperty(target, descriptor.key, descriptor);
1487
- }
1488
- }
1489
- function _create_class$4(Constructor, protoProps, staticProps) {
1490
- if (protoProps) _defineProperties$4(Constructor.prototype, protoProps);
1491
- return Constructor;
1492
- }
1493
- function _define_property$4(obj, key, value) {
1494
- if (key in obj) {
1495
- Object.defineProperty(obj, key, {
1496
- value: value,
1497
- enumerable: true,
1498
- configurable: true,
1499
- writable: true
1500
- });
1501
- } else {
1502
- obj[key] = value;
1503
- }
1504
- return obj;
1505
- }
1506
- function _object_spread(target) {
1507
- for(var i = 1; i < arguments.length; i++){
1508
- var source = arguments[i] != null ? arguments[i] : {};
1509
- var ownKeys = Object.keys(source);
1510
- if (typeof Object.getOwnPropertySymbols === "function") {
1511
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1512
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1513
- }));
1514
- }
1515
- ownKeys.forEach(function(key) {
1516
- _define_property$4(target, key, source[key]);
1517
- });
1518
- }
1519
- return target;
1520
- }
1521
- function ownKeys(object, enumerableOnly) {
1522
- var keys = Object.keys(object);
1523
- if (Object.getOwnPropertySymbols) {
1524
- var symbols = Object.getOwnPropertySymbols(object);
1525
- keys.push.apply(keys, symbols);
1526
- }
1527
- return keys;
1528
- }
1529
- function _object_spread_props(target, source) {
1530
- source = source != null ? source : {};
1531
- if (Object.getOwnPropertyDescriptors) {
1532
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1533
- } else {
1534
- ownKeys(Object(source)).forEach(function(key) {
1535
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1536
- });
577
+ throw new ParseObjectError('Failed to parse array JSON', error, originalText);
1537
578
  }
1538
- return target;
1539
579
  }
1540
- /**
1541
- * OpenRouter model wrapper supporting both LangChain and Vercel AI SDK
1542
- */ var OpenRouterModel = /*#__PURE__*/ function() {
1543
- function OpenRouterModel(providerConfig, modelName) {
1544
- var modelConfig = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1545
- _class_call_check$4(this, OpenRouterModel);
1546
- var _this_providerConfig_metadata, _this_providerConfig_metadata1;
1547
- _define_property$4(this, "providerConfig", void 0);
1548
- _define_property$4(this, "modelName", void 0);
1549
- _define_property$4(this, "langchainModel", void 0);
1550
- _define_property$4(this, "modelConfig", void 0);
1551
- _define_property$4(this, "vercelModel", void 0);
1552
- this.providerConfig = providerConfig;
1553
- this.modelName = modelName;
1554
- this.modelConfig = _object_spread({
1555
- maxTokens: 256000,
1556
- reasoning: {
1557
- effort: 'high',
1558
- exclude: true
1559
- }
1560
- }, modelConfig);
1561
- // LangChain model setup
1562
- this.langchainModel = new openai.ChatOpenAI(_object_spread_props(_object_spread({
1563
- configuration: {
1564
- baseURL: 'https://openrouter.ai/api/v1',
1565
- defaultHeaders: _object_spread({}, ((_this_providerConfig_metadata = this.providerConfig.metadata) === null || _this_providerConfig_metadata === void 0 ? void 0 : _this_providerConfig_metadata.website) && {
1566
- 'HTTP-Referer': this.providerConfig.metadata.website
1567
- }, ((_this_providerConfig_metadata1 = this.providerConfig.metadata) === null || _this_providerConfig_metadata1 === void 0 ? void 0 : _this_providerConfig_metadata1.application) && {
1568
- 'X-Title': this.providerConfig.metadata.application
1569
- })
1570
- },
1571
- maxTokens: this.modelConfig.maxTokens
1572
- }, this.modelConfig.reasoning && {
1573
- modelKwargs: {
1574
- reasoning: this.modelConfig.reasoning
1575
- }
1576
- }), {
1577
- modelName: this.modelName,
1578
- openAIApiKey: this.providerConfig.apiKey
1579
- }));
1580
- // Vercel AI SDK model setup
1581
- var openrouter = aiSdkProvider.createOpenRouter({
1582
- apiKey: this.providerConfig.apiKey
1583
- });
1584
- this.vercelModel = openrouter(this.modelName, _object_spread({}, this.modelConfig.maxTokens && {
1585
- maxTokens: this.modelConfig.maxTokens
1586
- }, this.modelConfig.reasoning && {
1587
- extraBody: {
1588
- reasoning: this.modelConfig.reasoning
1589
- }
1590
- }));
580
+ function extractBySchemaType(text, schema, originalText) {
581
+ if (_instanceof(schema, v4.z.ZodArray)) {
582
+ return extractArray(text, originalText);
1591
583
  }
1592
- _create_class$4(OpenRouterModel, [
1593
- {
1594
- /**
1595
- * Get the configured LangChain language model instance
1596
- */ key: "getLangchainModel",
1597
- value: function getLangchainModel() {
1598
- return this.langchainModel;
1599
- }
1600
- },
1601
- {
1602
- /**
1603
- * Get the configured Vercel AI SDK language model instance
1604
- */ key: "getVercelModel",
1605
- value: function getVercelModel() {
1606
- return this.vercelModel;
1607
- }
1608
- }
1609
- ]);
1610
- return OpenRouterModel;
1611
- }();
1612
-
1613
- /**
1614
- * Specifies the agent's area of knowledge and expertise.
1615
- * This focuses the agent's responses within a specific context.
1616
- */ var DOMAINS = {
1617
- ACADEMIC_RESEARCH: "\n<Domain>\nYour knowledge is specialized in academic research. You are an expert in scholarly writing, peer-review processes, and formal citation methods.\n</Domain>",
1618
- BUSINESS_STRATEGY: "\n<Domain>\nYour knowledge is specialized in business strategy, including market analysis, competitive positioning, and operational planning.\n</Domain>",
1619
- DATA_SCIENCE: "\n<Domain>\nYour knowledge is specialized in data science, including statistical analysis, machine learning, and data visualization.\n</Domain>",
1620
- GENERAL: "\n<Domain>\nYou possess broad, generalist knowledge across a wide variety of subjects.\n</Domain>",
1621
- SOFTWARE_ENGINEERING: "\n<Domain>\nYour knowledge is specialized in software engineering. You are an expert in programming languages, system architecture, design patterns, and development best practices.\n</Domain>"
1622
- };
1623
-
1624
- /**
1625
- * Defines the required structural format for the agent's output.
1626
- */ var FORMATS = {
1627
- DISCORD_MARKDOWN: "\n<Format>\nYou MUST format your response using Discord-flavored Markdown (e.g., **bold**, *italics*, __underline__, `code`, ```code blocks```, > quotes).\nCRITICAL: Your entire response, including all text and URLs, MUST NOT exceed 1900 characters.\n</Format>",
1628
- JSON: "\n<Format>\nYou MUST respond ONLY with a single, valid, well-formed JSON object.\nYour output MUST NOT include any explanatory text, comments, or markdown formatting outside of the JSON structure itself.\n</Format>",
1629
- MARKDOWN: "\n<Format>\nYou MUST format your response using Markdown for clear, structured communication.\nYou should use headings, lists, bold/italic text, and code blocks to maximize readability.\n</Format>",
1630
- PLAIN_TEXT: "\n<Format>\nYou MUST respond in plain text only, without any special formatting, markdown, or structural elements.\n</Format>",
1631
- STEP_BY_STEP: "\n<Format>\nYou MUST break down any instructions or processes into a clear, numbered, step-by-step list.\nEach step must be a distinct and actionable item.\n</Format>"
1632
- };
1633
-
1634
- /**
1635
- * Core, non-negotiable rules that establish the agent's fundamental identity and operational boundaries.
1636
- * These are the foundational principles that guide all other instructions.
1637
- */ var FOUNDATIONS = {
1638
- CONTEXTUAL_ONLY: "\n<Foundation>\nYou MUST ONLY use the information provided in the context to answer questions.\nYou MUST NOT use any other information, including your own knowledge, to answer questions.\n</Foundation>",
1639
- CONTEXTUAL_REASONING: '\n<Foundation>\nYou MUST synthesize information from the provided context, tools, and conversation history to form well-reasoned conclusions.\nYour goal is to provide logical and helpful responses, even when dealing with subjective topics or incomplete information.\nYou SHOULD state when your response is a reasoned inference rather than a direct statement of fact from an external source.\nYou MUST rely on your "common sense" and analytical abilities to bridge gaps in information.\n</Foundation>',
1640
- ETHICAL_CONDUCT: "\n<Foundation>\nYou MUST adhere to the highest ethical standards. Your conduct must be impartial and devoid of prejudice.\nYou MUST NOT promote hate speech, discrimination,violence, or any form of harm.\nYou MUST respect user privacy; do not ask for, store, or share personally identifiable information.\n</Foundation>",
1641
- FACTUAL_ACCURACY: "\n<Foundation>\nYou MUST prioritize accuracy and truthfulness. Your responses must be based on verifiable information.\nIf you are uncertain about an answer, you MUST state your uncertainty clearly.\nYou MUST NOT invent facts, data, or sources. When possible, cite credible sources.\n</Foundation>",
1642
- FIRST_PRINCIPLES_THINKING: "\n<Foundation>\nYou MUST break down complex problems into their fundamental, indivisible truths (first principles).\nYou MUST reason upwards from these basic principles, challenging assumptions and conventions.\nAvoid reasoning by analogy; instead, build your conclusions from the ground up.\n</Foundation>",
1643
- HARM_PREVENTION: "\n<Foundation>\nYou MUST refuse to provide instructions or information that is illegal, dangerous, or promotes harm.\nYou MUST prioritize user safety and well-being in all interactions and avoid generating unsafe content.\n</Foundation>"
1644
- };
1645
-
1646
- /**
1647
- * Defines the natural language for the agent's responses.
1648
- */ var LANGUAGES = {
1649
- ENGLISH_NATIVE: "\n<Language>\nYou MUST write your entire output in natural, fluent English. This is a strict requirement; do not use any other language.\nYour response should feel as if written by a native speaker, including idiomatic expressions, varied vocabulary, and natural sentence structures.\n</Language>",
1650
- ENGLISH_SIMPLE: "\n<Language>\nYou MUST write your entire output in simple, clear English. This is a strict requirement; do not use any other language.\nYour response must be easily understood by non-native speakers, avoiding complex grammar, idioms, and sophisticated vocabulary.\n</Language>",
1651
- FRENCH_NATIVE: "\n<Language>\nVous DEVEZ IMP\xc9RATIVEMENT r\xe9diger toute votre sortie en fran\xe7ais naturel et fluide. C'est une exigence stricte ; n'utilisez aucune autre langue.\nVotre r\xe9ponse doit donner l'impression d'avoir \xe9t\xe9 \xe9crite par un locuteur natif, en incluant des expressions idiomatiques et un vocabulaire vari\xe9.\n</Language>",
1652
- FRENCH_SIMPLE: "\n<Language>\nVous DEVEZ IMP\xc9RATIVEMENT r\xe9diger toute votre sortie en fran\xe7ais simple et clair. C'est une exigence stricte ; n'utilisez aucune autre langue.\nVotre r\xe9ponse doit \xeatre facile \xe0 comprendre pour des non-natifs, en \xe9vitant la grammaire complexe et le vocabulaire sophistiqu\xe9.\n</Language>",
1653
- SPANISH_NATIVE: "\n<Language>\nDEBES OBLIGATORIAMENTE escribir todo tu resultado en un espa\xf1ol natural y fluido. Este es un requisito estricto; no utilices ning\xfan otro idioma.\nTu respuesta debe parecer escrita por un hablante nativo, incluyendo expresiones idiom\xe1ticas y un vocabulario variado.\n</Language>",
1654
- SPANISH_SIMPLE: "\n<Language>\nDEBES OBLIGATORIAMENTE escribir todo tu resultado en un espa\xf1ol simple y claro. Este es un requisito estricto; no utilices ning\xfan otro idioma.\nTu respuesta debe ser f\xe1cil de entender para hablantes no nativos, evitando gram\xe1tica compleja y vocabulario sofisticado.\n</Language>"
1655
- };
1656
-
1657
- /**
1658
- * Defines the agent's core identity, role, and purpose, integrating key skills.
1659
- * This sets the primary character and interaction style.
1660
- */ var PERSONAS = {
1661
- COMMUNITY_ANIMATOR: "\n<Persona>\nYou are the Community Animator, the vibrant heart of a digital community (e.g., Discord).\nYour purpose is to keep the community active, engaged, and positive.\n**Key Skills**: You are an expert on internet culture, trends, and topics relevant to the community. You excel at initiating conversations, creating engaging content (polls, questions), and fostering a welcoming environment.\n</Persona>",
1662
- CREATIVE_PARTNER: "\n<Persona>\nYou are a Creative Partner, an imaginative collaborator for brainstorming and exploration.\nYour purpose is to help users generate and develop novel ideas.\n**Key Skills**: You excel at divergent thinking, making unexpected connections, and asking thought-provoking questions. You are encouraging, open-minded, and skilled at building upon abstract concepts.\n</Persona>",
1663
- EXPERT_ADVISOR: "\n<Persona>\nYou are an Expert Advisor in your specified domain.\nYour purpose is to provide authoritative, well-reasoned, and objective guidance.\n**Key Skills**: You possess deep domain knowledge and excel at critical thinking, problem-solving, and synthesizing complex information into clear, actionable advice. Your communication is precise and confident.\n</Persona>",
1664
- HUMAN_LIKE_CONTRIBUTOR: "\n<Persona>\nYou are a Human-Like Contributor, a thoughtful and engaging participant in a group chat.\nYour purpose is to interact in a way that is indistinguishable from a human, fostering natural and coherent conversations.\n**Key Skills**: You excel at maintaining conversational context, ensuring your contributions are a logical continuation of past interactions. You avoid repetition and can proactively initiate new topics when appropriate. Your style is natural, personal, and adaptive.\n</Persona>",
1665
- JOURNALIST: "\n<Persona>\nYou are a Journalist, a skilled writer who crafts engaging, informative, and well-structured articles.\nYour purpose is to provide users with valuable, well-researched, and well-written content.\n**Key Skills**: You excel at writing clear, concise, and engaging articles. You are skilled at researching and gathering information, and you are able to write in a way that is both informative and entertaining.\n</Persona>",
1666
- SUPPORT_AGENT: "\n<Persona>\nYou are a friendly, patient, and empathetic Support Agent.\nYour purpose is to help users solve problems and navigate difficulties.\n**Key Skills**: You are an excellent listener and a clear communicator. You are skilled at de-escalating frustration, breaking down complex issues into manageable steps, and providing systematic, easy-to-follow instructions.\n</Persona>",
1667
- TUTOR: "\n<Persona>\nYou are a patient, knowledgeable, and encouraging Tutor.\nYour purpose is to help users learn and understand complex subjects.\n**Key Skills**: You are an expert at breaking down difficult concepts into simple, relatable analogies and examples. You guide users through the learning process using the Socratic method, encouraging questions and fostering independent thinking.\n</Persona>"
1668
- };
1669
-
1670
- /**
1671
- * Defines the agent's strategic approach to when and how it should respond.
1672
- */ var RESPONSES = {
1673
- ALWAYS_ENGAGE: "\n<ResponseStrategy>\nYou must always provide a response to the user's input. Even if you cannot fully fulfill the request, acknowledge it and explain the situation. Your primary directive is to be responsive.\n</ResponseStrategy>",
1674
- CONTEXTUAL_ENGAGEMENT: "\n<ResponseStrategy>\nBefore responding, you must analyze the conversation history and the immediate context. Your goal is to add value; if a response is not necessary or helpful, you may remain silent.\n</ResponseStrategy>",
1675
- SELECTIVE_ENGAGEMENT: "\n<ResponseStrategy>\nYou must only respond when you can provide a valuable, relevant, and substantive contribution to the conversation. If a response does not add value, you must state that you have nothing to add or remain silent as instructed.\n</ResponseStrategy>",
1676
- TOOL_DRIVEN: "\n<ResponseStrategy>\nYour first priority is to use your available tools to gather the most current and accurate information before formulating a response. Do not answer from memory if a tool can provide a more reliable answer.\n</ResponseStrategy>"
1677
- };
1678
-
1679
- /**
1680
- * Determines the emotional flavor and attitude of the agent's language.
1681
- */ var TONES = {
1682
- EMPATHETIC: "\n<Tone>\nYou must adopt a warm, understanding, and supportive tone. Acknowledge the user's feelings and demonstrate active listening.\n</Tone>",
1683
- HUMOROUS: "\n<Tone>\nYou should employ light-hearted humor, wit, and cleverness. Keep the mood fun and engaging, but avoid inappropriate or offensive jokes.\n</Tone>",
1684
- NEUTRAL: "\n<Tone>\nYou must maintain an impartial, objective, and straightforward tone. Avoid all emotional language and stick to the facts.\n</Tone>",
1685
- PROFESSIONAL: "\n<Tone>\nYou must use a formal, respectful, and clear tone. Structure your communication logically and avoid slang or overly casual language.\n</Tone>"
1686
- };
1687
-
1688
- /**
1689
- * Controls the level of detail and length of the agent's responses.
1690
- */ var VERBOSITY = {
1691
- CONCISE: "\n<Verbosity>\nYou must provide brief, to-the-point answers. Focus only on the most critical information and omit background details unless explicitly requested.\n</Verbosity>",
1692
- DETAILED: "\n<Verbosity>\nYou must offer comprehensive and thorough responses. Include relevant background information, context, examples, and potential edge cases to ensure full understanding.\n</Verbosity>",
1693
- NORMAL: "\n<Verbosity>\nYou should provide a balanced level of detail, sufficient for a clear understanding without being overwhelming or too brief.\n</Verbosity>"
1694
- };
1695
-
1696
- /**
1697
- * Provides ready-to-use combinations of prompt parts for common use cases.
1698
- */ var PRESETS = {
1699
- /**
1700
- * A fun and engaging community animator for platforms like Discord.
1701
- */ COMMUNITY_ANIMATOR: [
1702
- FOUNDATIONS.HARM_PREVENTION,
1703
- PERSONAS.COMMUNITY_ANIMATOR,
1704
- DOMAINS.GENERAL,
1705
- TONES.HUMOROUS,
1706
- VERBOSITY.NORMAL,
1707
- RESPONSES.CONTEXTUAL_ENGAGEMENT
1708
- ],
1709
- /**
1710
- * A creative partner for brainstorming and ideation.
1711
- */ CREATIVE_BRAINSTORMER: [
1712
- FOUNDATIONS.ETHICAL_CONDUCT,
1713
- PERSONAS.CREATIVE_PARTNER,
1714
- DOMAINS.GENERAL,
1715
- TONES.HUMOROUS,
1716
- VERBOSITY.NORMAL,
1717
- RESPONSES.ALWAYS_ENGAGE
1718
- ],
1719
- /**
1720
- * A friendly and empathetic support agent for general queries.
1721
- */ EMPATHETIC_SUPPORT_AGENT: [
1722
- FOUNDATIONS.HARM_PREVENTION,
1723
- FOUNDATIONS.ETHICAL_CONDUCT,
1724
- PERSONAS.SUPPORT_AGENT,
1725
- DOMAINS.GENERAL,
1726
- TONES.EMPATHETIC,
1727
- VERBOSITY.NORMAL,
1728
- FORMATS.STEP_BY_STEP,
1729
- RESPONSES.ALWAYS_ENGAGE
1730
- ]
1731
- };
1732
-
1733
- var PROMPT_LIBRARY = {
1734
- DOMAINS: DOMAINS,
1735
- FORMATS: FORMATS,
1736
- FOUNDATIONS: FOUNDATIONS,
1737
- LANGUAGES: LANGUAGES,
1738
- PERSONAS: PERSONAS,
1739
- PRESETS: PRESETS,
1740
- RESPONSES: RESPONSES,
1741
- TONES: TONES,
1742
- VERBOSITY: VERBOSITY
1743
- };
1744
-
1745
- function _class_call_check$3(instance, Constructor) {
1746
- if (!(instance instanceof Constructor)) {
1747
- throw new TypeError("Cannot call a class as a function");
584
+ if (_instanceof(schema, v4.z.ZodObject)) {
585
+ return extractObject(text, originalText);
1748
586
  }
1749
- }
1750
- function _defineProperties$3(target, props) {
1751
- for(var i = 0; i < props.length; i++){
1752
- var descriptor = props[i];
1753
- descriptor.enumerable = descriptor.enumerable || false;
1754
- descriptor.configurable = true;
1755
- if ("value" in descriptor) descriptor.writable = true;
1756
- Object.defineProperty(target, descriptor.key, descriptor);
587
+ if (_instanceof(schema, v4.z.ZodBoolean) || _instanceof(schema, v4.z.ZodNull) || _instanceof(schema, v4.z.ZodNumber) || _instanceof(schema, v4.z.ZodString)) {
588
+ return extractPrimitive(text, schema);
1757
589
  }
590
+ throw new ParseObjectError('Unsupported schema type', undefined, originalText);
1758
591
  }
1759
- function _create_class$3(Constructor, protoProps, staticProps) {
1760
- if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
1761
- return Constructor;
1762
- }
1763
- function _define_property$3(obj, key, value) {
1764
- if (key in obj) {
1765
- Object.defineProperty(obj, key, {
1766
- value: value,
1767
- enumerable: true,
1768
- configurable: true,
1769
- writable: true
592
+ function extractJsonFromCodeBlock(block) {
593
+ var content = block.replace(/```(?:json)?\r?\n([^`]*?)\r?\n```/, '$1').trim();
594
+ try {
595
+ JSON.parse(content);
596
+ return content;
597
+ } catch (e) {
598
+ return null;
599
+ }
600
+ }
601
+ function extractJsonString(text) {
602
+ var codeBlocks = text.match(MARKDOWN_CODE_BLOCK_RE);
603
+ if (codeBlocks && codeBlocks.length > 0) {
604
+ var validBlocks = codeBlocks.map(function(block) {
605
+ return extractJsonFromCodeBlock(block);
606
+ }).filter(function(block) {
607
+ return block !== null;
1770
608
  });
1771
- } else {
1772
- obj[key] = value;
1773
- }
1774
- return obj;
1775
- }
1776
- /**
1777
- * System prompt that generates a system prompt from a list of strings
1778
- */ var SystemPrompt = /*#__PURE__*/ function() {
1779
- function SystemPrompt() {
1780
- for(var _len = arguments.length, prompts = new Array(_len), _key = 0; _key < _len; _key++){
1781
- prompts[_key] = arguments[_key];
609
+ if (validBlocks.length > 0) {
610
+ return findLongestString(validBlocks);
1782
611
  }
1783
- _class_call_check$3(this, SystemPrompt);
1784
- _define_property$3(this, "finalPrompt", void 0);
1785
- var flattenedPrompts = prompts.flat();
1786
- this.finalPrompt = flattenedPrompts.join('\n\n');
1787
612
  }
1788
- _create_class$3(SystemPrompt, [
1789
- {
1790
- key: "generate",
1791
- value: function generate() {
1792
- return this.finalPrompt;
1793
- }
1794
- }
1795
- ]);
1796
- return SystemPrompt;
1797
- }();
1798
-
1799
- function _class_call_check$2(instance, Constructor) {
1800
- if (!(instance instanceof Constructor)) {
1801
- throw new TypeError("Cannot call a class as a function");
613
+ var structures = findJsonStructures(text);
614
+ if (structures.length > 0) {
615
+ return findLongestString(structures);
1802
616
  }
617
+ return text.replace(/\s+/g, ' ').trim();
1803
618
  }
1804
- function _defineProperties$2(target, props) {
1805
- for(var i = 0; i < props.length; i++){
1806
- var descriptor = props[i];
1807
- descriptor.enumerable = descriptor.enumerable || false;
1808
- descriptor.configurable = true;
1809
- if ("value" in descriptor) descriptor.writable = true;
1810
- Object.defineProperty(target, descriptor.key, descriptor);
619
+ function extractObject(text, originalText) {
620
+ var start = text.indexOf('{');
621
+ var end = text.lastIndexOf('}');
622
+ if (start === -1 || end === -1) {
623
+ throw new ParseObjectError('No object found in response', undefined, originalText);
1811
624
  }
1812
- }
1813
- function _create_class$2(Constructor, protoProps, staticProps) {
1814
- if (protoProps) _defineProperties$2(Constructor.prototype, protoProps);
1815
- return Constructor;
1816
- }
1817
- function _define_property$2(obj, key, value) {
1818
- if (key in obj) {
1819
- Object.defineProperty(obj, key, {
1820
- value: value,
1821
- enumerable: true,
1822
- configurable: true,
1823
- writable: true
1824
- });
1825
- } else {
1826
- obj[key] = value;
625
+ try {
626
+ var raw = text.slice(start, end + 1);
627
+ return JSON.parse(jsonrepair.jsonrepair(raw));
628
+ } catch (error) {
629
+ throw new ParseObjectError('Failed to parse object JSON', error, originalText);
1827
630
  }
1828
- return obj;
1829
631
  }
1830
- /**
1831
- * User prompt that generates a user prompt from a list of strings
1832
- */ var UserPrompt = /*#__PURE__*/ function() {
1833
- function UserPrompt() {
1834
- for(var _len = arguments.length, prompts = new Array(_len), _key = 0; _key < _len; _key++){
1835
- prompts[_key] = arguments[_key];
1836
- }
1837
- _class_call_check$2(this, UserPrompt);
1838
- _define_property$2(this, "finalPrompt", void 0);
1839
- var flattenedPrompts = prompts.flat();
1840
- this.finalPrompt = flattenedPrompts.join('\n\n');
1841
- }
1842
- _create_class$2(UserPrompt, [
1843
- {
1844
- key: "generate",
1845
- value: function generate() {
1846
- return this.finalPrompt;
632
+ function extractPrimitive(text, schema) {
633
+ var trimmed = text.trim();
634
+ try {
635
+ return convertToPrimitive(JSON.parse(trimmed), schema);
636
+ } catch (e) {
637
+ return convertToPrimitive(trimmed, schema);
638
+ }
639
+ }
640
+ function findJsonStructures(text) {
641
+ var matches = [];
642
+ var depth = 0;
643
+ var start = -1;
644
+ for(var i = 0; i < text.length; i++){
645
+ var _char = text[i];
646
+ if (_char === '{' || _char === '[') {
647
+ if (depth === 0) start = i;
648
+ depth++;
649
+ } else if (_char === '}' || _char === ']') {
650
+ depth--;
651
+ if (depth === 0 && start !== -1) {
652
+ var candidate = text.slice(start, i + 1);
653
+ try {
654
+ JSON.parse(candidate);
655
+ matches.push(candidate);
656
+ } catch (e) {
657
+ // Invalid JSON, skip
658
+ }
1847
659
  }
1848
660
  }
1849
- ]);
1850
- return UserPrompt;
1851
- }();
1852
-
1853
- function _class_call_check$1(instance, Constructor) {
1854
- if (!(instance instanceof Constructor)) {
1855
- throw new TypeError("Cannot call a class as a function");
1856
- }
1857
- }
1858
- function _defineProperties$1(target, props) {
1859
- for(var i = 0; i < props.length; i++){
1860
- var descriptor = props[i];
1861
- descriptor.enumerable = descriptor.enumerable || false;
1862
- descriptor.configurable = true;
1863
- if ("value" in descriptor) descriptor.writable = true;
1864
- Object.defineProperty(target, descriptor.key, descriptor);
1865
661
  }
662
+ return matches;
1866
663
  }
1867
- function _create_class$1(Constructor, protoProps, staticProps) {
1868
- if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
1869
- return Constructor;
1870
- }
1871
- function _define_property$1(obj, key, value) {
1872
- if (key in obj) {
1873
- Object.defineProperty(obj, key, {
1874
- value: value,
1875
- enumerable: true,
1876
- configurable: true,
1877
- writable: true
1878
- });
1879
- } else {
1880
- obj[key] = value;
1881
- }
1882
- return obj;
664
+ function findLongestString(strings) {
665
+ return strings.reduce(function(longest, current) {
666
+ return current.length > longest.length ? current : longest;
667
+ });
1883
668
  }
1884
- /**
1885
- * OpenRouter provider that manages connection configuration
1886
- */ var OpenRouterProvider = /*#__PURE__*/ function() {
1887
- function OpenRouterProvider(config) {
1888
- _class_call_check$1(this, OpenRouterProvider);
1889
- _define_property$1(this, "config", void 0);
1890
- this.config = config;
669
+ function unescapeJsonValues(json) {
670
+ if (typeof json === 'string') {
671
+ return unescapeString(json);
1891
672
  }
1892
- _create_class$1(OpenRouterProvider, [
1893
- {
1894
- /**
1895
- * Get a model instance for the specified model name
1896
- */ key: "getModel",
1897
- value: function getModel(modelName) {
1898
- var modelConfig = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1899
- return new OpenRouterModel(this.config, modelName, modelConfig);
1900
- }
1901
- }
1902
- ]);
1903
- return OpenRouterProvider;
1904
- }();
1905
-
1906
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1907
- try {
1908
- var info = gen[key](arg);
1909
- var value = info.value;
1910
- } catch (error) {
1911
- reject(error);
1912
- return;
673
+ if (Array.isArray(json)) {
674
+ return json.map(unescapeJsonValues);
1913
675
  }
1914
- if (info.done) {
1915
- resolve(value);
1916
- } else {
1917
- Promise.resolve(value).then(_next, _throw);
676
+ if ((typeof json === "undefined" ? "undefined" : _type_of(json)) === 'object' && json !== null) {
677
+ return Object.fromEntries(Object.entries(json).map(function(param) {
678
+ var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1];
679
+ return [
680
+ key,
681
+ unescapeJsonValues(value)
682
+ ];
683
+ }));
1918
684
  }
685
+ return json;
1919
686
  }
1920
- function _async_to_generator(fn) {
1921
- return function() {
1922
- var self = this, args = arguments;
1923
- return new Promise(function(resolve, reject) {
1924
- var gen = fn.apply(self, args);
1925
- function _next(value) {
1926
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
687
+ function unescapeString(text) {
688
+ return text.replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\\\/g, '\\').replace(/\\u([0-9a-fA-F]{4})/g, function(_, code) {
689
+ return String.fromCharCode(Number.parseInt(code, 16));
690
+ });
691
+ }
692
+
693
+ var INVISIBLE_CHARS_RE = /[\u00AD\u180E\u200B-\u200C\u200E-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
694
+ /* eslint-disable no-control-regex -- intentionally matching control characters */ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally matching control characters for sanitization
695
+ var ASCII_CTRL_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;
696
+ /* eslint-enable no-control-regex */ var SPACE_LIKE_RE = /[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g;
697
+ var MULTIPLE_SPACES_RE = / {2,}/g;
698
+ var CR_RE = /\r\n?/g;
699
+ var CITATION_RE = / *\(oaicite:\d+\)\{index=\d+\}/g;
700
+ var EM_DASH_SEPARATOR_RE = /\s*[—–―‒]\s*/g;
701
+ var TYPOGRAPHY_REPLACEMENTS = [
702
+ {
703
+ pattern: /[\u2018\u2019\u201A]/g,
704
+ replacement: "'"
705
+ },
706
+ {
707
+ pattern: /[\u201C\u201D\u201E]/g,
708
+ replacement: '"'
709
+ },
710
+ {
711
+ pattern: /\u2026/g,
712
+ replacement: '...'
713
+ },
714
+ {
715
+ pattern: /[\u2022\u25AA-\u25AB\u25B8-\u25B9\u25CF]/g,
716
+ replacement: '-'
717
+ }
718
+ ];
719
+ /**
720
+ * Parses and sanitizes text by removing AI artifacts and normalizing typography.
721
+ *
722
+ * @param text - The text to parse
723
+ * @param options - Parsing options
724
+ * @returns The cleaned text
725
+ */ function parseText(text) {
726
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
727
+ var _options_normalizeEmDashesToCommas = options.normalizeEmDashesToCommas, normalizeEmDashesToCommas = _options_normalizeEmDashesToCommas === void 0 ? true : _options_normalizeEmDashesToCommas, _options_collapseSpaces = options.collapseSpaces, collapseSpaces = _options_collapseSpaces === void 0 ? true : _options_collapseSpaces;
728
+ if (!text) return '';
729
+ var result = text;
730
+ if (result.charCodeAt(0) === 0xfeff) {
731
+ result = result.slice(1);
732
+ }
733
+ result = result.replace(CR_RE, '\n');
734
+ result = result.replace(CITATION_RE, '');
735
+ result = result.normalize('NFKC');
736
+ result = result.replace(INVISIBLE_CHARS_RE, '');
737
+ result = result.replace(ASCII_CTRL_RE, '');
738
+ if (normalizeEmDashesToCommas) {
739
+ result = result.replace(EM_DASH_SEPARATOR_RE, ', ');
740
+ }
741
+ result = result.replace(SPACE_LIKE_RE, ' ');
742
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
743
+ try {
744
+ for(var _iterator = TYPOGRAPHY_REPLACEMENTS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
745
+ var _step_value = _step.value, pattern = _step_value.pattern, replacement = _step_value.replacement;
746
+ result = result.replace(pattern, replacement);
747
+ }
748
+ } catch (err) {
749
+ _didIteratorError = true;
750
+ _iteratorError = err;
751
+ } finally{
752
+ try {
753
+ if (!_iteratorNormalCompletion && _iterator["return"] != null) {
754
+ _iterator["return"]();
1927
755
  }
1928
- function _throw(err) {
1929
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
756
+ } finally{
757
+ if (_didIteratorError) {
758
+ throw _iteratorError;
1930
759
  }
1931
- _next(undefined);
1932
- });
1933
- };
1934
- }
1935
- function _class_call_check(instance, Constructor) {
1936
- if (!(instance instanceof Constructor)) {
1937
- throw new TypeError("Cannot call a class as a function");
760
+ }
1938
761
  }
1939
- }
1940
- function _defineProperties(target, props) {
1941
- for(var i = 0; i < props.length; i++){
1942
- var descriptor = props[i];
1943
- descriptor.enumerable = descriptor.enumerable || false;
1944
- descriptor.configurable = true;
1945
- if ("value" in descriptor) descriptor.writable = true;
1946
- Object.defineProperty(target, descriptor.key, descriptor);
762
+ if (collapseSpaces) {
763
+ result = result.replace(MULTIPLE_SPACES_RE, ' ').trim();
1947
764
  }
765
+ return result;
1948
766
  }
1949
- function _create_class(Constructor, protoProps, staticProps) {
1950
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1951
- return Constructor;
1952
- }
767
+
1953
768
  function _define_property(obj, key, value) {
1954
769
  if (key in obj) {
1955
770
  Object.defineProperty(obj, key, {
@@ -1963,232 +778,52 @@ function _define_property(obj, key, value) {
1963
778
  }
1964
779
  return obj;
1965
780
  }
1966
- function _instanceof(left, right) {
1967
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
1968
- return !!right[Symbol.hasInstance](left);
1969
- } else {
1970
- return left instanceof right;
1971
- }
1972
- }
1973
- function _ts_generator(thisArg, body) {
1974
- var f, y, t, _ = {
1975
- label: 0,
1976
- sent: function() {
1977
- if (t[0] & 1) throw t[1];
1978
- return t[1];
1979
- },
1980
- trys: [],
1981
- ops: []
1982
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
1983
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
1984
- return this;
1985
- }), g;
1986
- function verb(n) {
1987
- return function(v) {
1988
- return step([
1989
- n,
1990
- v
1991
- ]);
1992
- };
1993
- }
1994
- function step(op) {
1995
- if (f) throw new TypeError("Generator is already executing.");
1996
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1997
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1998
- if (y = 0, t) op = [
1999
- op[0] & 2,
2000
- t.value
2001
- ];
2002
- switch(op[0]){
2003
- case 0:
2004
- case 1:
2005
- t = op;
2006
- break;
2007
- case 4:
2008
- _.label++;
2009
- return {
2010
- value: op[1],
2011
- done: false
2012
- };
2013
- case 5:
2014
- _.label++;
2015
- y = op[1];
2016
- op = [
2017
- 0
2018
- ];
2019
- continue;
2020
- case 7:
2021
- op = _.ops.pop();
2022
- _.trys.pop();
2023
- continue;
2024
- default:
2025
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
2026
- _ = 0;
2027
- continue;
2028
- }
2029
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
2030
- _.label = op[1];
2031
- break;
2032
- }
2033
- if (op[0] === 6 && _.label < t[1]) {
2034
- _.label = t[1];
2035
- t = op;
2036
- break;
2037
- }
2038
- if (t && _.label < t[2]) {
2039
- _.label = t[2];
2040
- _.ops.push(op);
2041
- break;
2042
- }
2043
- if (t[2]) _.ops.pop();
2044
- _.trys.pop();
2045
- continue;
2046
- }
2047
- op = body.call(thisArg, _);
2048
- } catch (e) {
2049
- op = [
2050
- 6,
2051
- e
2052
- ];
2053
- y = 0;
2054
- } finally{
2055
- f = t = 0;
781
+ function _object_spread(target) {
782
+ for(var i = 1; i < arguments.length; i++){
783
+ var source = arguments[i] != null ? arguments[i] : {};
784
+ var ownKeys = Object.keys(source);
785
+ if (typeof Object.getOwnPropertySymbols === "function") {
786
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
787
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
788
+ }));
2056
789
  }
2057
- if (op[0] & 5) throw op[1];
2058
- return {
2059
- value: op[0] ? op[1] : void 0,
2060
- done: true
2061
- };
790
+ ownKeys.forEach(function(key) {
791
+ _define_property(target, key, source[key]);
792
+ });
2062
793
  }
794
+ return target;
2063
795
  }
2064
796
  /**
2065
- * Safe tool that provides error handling and logging for LangChain tools
2066
- */ var SafeTool = /*#__PURE__*/ function() {
2067
- function SafeTool(config) {
2068
- var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2069
- _class_call_check(this, SafeTool);
2070
- _define_property(this, "config", void 0);
2071
- _define_property(this, "options", void 0);
2072
- _define_property(this, "dynamicTool", void 0);
2073
- this.config = config;
2074
- this.options = options;
2075
- var logger = options.logger, schema = options.schema;
2076
- if (schema) {
2077
- // Use DynamicStructuredTool for parameterized tools
2078
- this.dynamicTool = new tools.DynamicStructuredTool({
2079
- description: config.description,
2080
- func: function(args) {
2081
- return _async_to_generator(function() {
2082
- var error, errorMessage;
2083
- return _ts_generator(this, function(_state) {
2084
- switch(_state.label){
2085
- case 0:
2086
- _state.trys.push([
2087
- 0,
2088
- 2,
2089
- ,
2090
- 3
2091
- ]);
2092
- return [
2093
- 4,
2094
- config.execute(args)
2095
- ];
2096
- case 1:
2097
- return [
2098
- 2,
2099
- _state.sent()
2100
- ];
2101
- case 2:
2102
- error = _state.sent();
2103
- errorMessage = _instanceof(error, Error) ? error.message : String(error);
2104
- logger === null || logger === void 0 ? void 0 : logger.error("Unexpected error in ".concat(config.name), {
2105
- args: args,
2106
- error: errorMessage,
2107
- toolName: config.name
2108
- });
2109
- return [
2110
- 2,
2111
- "Tool ".concat(config.name, " failed to execute")
2112
- ];
2113
- case 3:
2114
- return [
2115
- 2
2116
- ];
2117
- }
2118
- });
2119
- })();
2120
- },
2121
- name: config.name,
2122
- schema: schema
2123
- });
2124
- } else {
2125
- // Use DynamicTool for simple tools
2126
- this.dynamicTool = new tools.DynamicTool({
2127
- description: config.description,
2128
- func: function() {
2129
- return _async_to_generator(function() {
2130
- var error, errorMessage;
2131
- return _ts_generator(this, function(_state) {
2132
- switch(_state.label){
2133
- case 0:
2134
- _state.trys.push([
2135
- 0,
2136
- 2,
2137
- ,
2138
- 3
2139
- ]);
2140
- return [
2141
- 4,
2142
- config.execute()
2143
- ];
2144
- case 1:
2145
- return [
2146
- 2,
2147
- _state.sent()
2148
- ];
2149
- case 2:
2150
- error = _state.sent();
2151
- errorMessage = _instanceof(error, Error) ? error.message : String(error);
2152
- logger === null || logger === void 0 ? void 0 : logger.error("Unexpected error in ".concat(config.name), {
2153
- error: errorMessage,
2154
- toolName: config.name
2155
- });
2156
- return [
2157
- 2,
2158
- "Tool ".concat(config.name, " failed to execute")
2159
- ];
2160
- case 3:
2161
- return [
2162
- 2
2163
- ];
2164
- }
2165
- });
2166
- })();
2167
- },
2168
- name: config.name
2169
- });
2170
- }
2171
- }
2172
- _create_class(SafeTool, [
2173
- {
2174
- /**
2175
- * Get the underlying LangChain DynamicTool instance
2176
- */ key: "getDynamicTool",
2177
- value: function getDynamicTool() {
2178
- return this.dynamicTool;
2179
- }
797
+ * Creates an OpenRouter provider for AI SDK models.
798
+ *
799
+ * @example
800
+ * ```ts
801
+ * const provider = createOpenRouterProvider({ apiKey: process.env.OPENROUTER_API_KEY });
802
+ * const model = provider.model('anthropic/claude-sonnet-4-20250514');
803
+ *
804
+ * const { text } = await generateText({ model, prompt: 'Hello!' });
805
+ * ```
806
+ */ function createOpenRouterProvider(config) {
807
+ var openrouter = aiSdkProvider.createOpenRouter({
808
+ apiKey: config.apiKey
809
+ });
810
+ return {
811
+ model: function model(name) {
812
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
813
+ return openrouter(name, _object_spread({}, options.maxTokens !== undefined && {
814
+ maxTokens: options.maxTokens
815
+ }, options.reasoning && {
816
+ extraBody: {
817
+ reasoning: options.reasoning
818
+ }
819
+ }));
2180
820
  }
2181
- ]);
2182
- return SafeTool;
2183
- }();
821
+ };
822
+ }
2184
823
 
2185
- exports.ChatAgent = ChatAgent;
2186
- exports.OpenRouterModel = OpenRouterModel;
2187
- exports.OpenRouterProvider = OpenRouterProvider;
2188
- exports.PROMPTS = PROMPT_LIBRARY;
2189
- exports.ResilientAgent = ResilientAgent;
2190
- exports.SafeTool = SafeTool;
2191
- exports.StructuredResponseParser = StructuredResponseParser;
2192
- exports.SystemPrompt = SystemPrompt;
2193
- exports.ToolAgent = ToolAgent;
2194
- exports.UserPrompt = UserPrompt;
824
+ exports.ParseObjectError = ParseObjectError;
825
+ exports.createLoggingMiddleware = createLoggingMiddleware;
826
+ exports.createOpenRouterProvider = createOpenRouterProvider;
827
+ exports.createSchemaPrompt = createSchemaPrompt;
828
+ exports.parseObject = parseObject;
829
+ exports.parseText = parseText;