@iqai/adk 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19; var _class20; var _class21; var _class22; var _class23; var _class24; var _class25; var _class26; var _class27; var _class28; var _class29; var _class30; var _class31; var _class32; var _class33; var _class34; var _class35;var __defProp = Object.defineProperty;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19; var _class20; var _class21; var _class22; var _class23; var _class24; var _class25; var _class26; var _class27; var _class28; var _class29; var _class30; var _class31; var _class32; var _class33; var _class34; var _class35;var __defProp = Object.defineProperty;
2
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
@@ -30,98 +30,269 @@ var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk);
30
30
  function isDebugEnabled() {
31
31
  return process.env.NODE_ENV === "development" || process.env.ADK_DEBUG === "true";
32
32
  }
33
- var Logger;
33
+ var LOG_LEVELS, Logger;
34
34
  var init_logger = __esm({
35
35
  "src/logger/index.ts"() {
36
+ LOG_LEVELS = {
37
+ debug: { icon: "\u{1F41B}", color: _chalk2.default.blue, method: console.log },
38
+ info: { icon: "\u2139\uFE0F", color: _chalk2.default.cyan, method: console.debug },
39
+ warn: { icon: "\u{1F6A7}", color: _chalk2.default.yellow, method: console.warn },
40
+ error: { icon: "\u274C", color: _chalk2.default.red, method: console.error }
41
+ };
36
42
  Logger = (_class = class {
37
43
 
38
44
  __init2() {this.isDebugEnabled = isDebugEnabled()}
39
45
  constructor({ name }) {;_class.prototype.__init2.call(this);
40
46
  this.name = name;
41
47
  }
42
- colorize(message) {
43
- return _chalk2.default.blue(message);
44
- }
45
48
  debug(message, ...args) {
46
49
  if (this.isDebugEnabled) {
47
- const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
48
- console.log(
49
- this.colorize(`[${time}] \u{1F41B} [${this.name}] ${message}`),
50
- ...args
51
- );
50
+ this.log("debug", message, ...args);
52
51
  }
53
52
  }
54
53
  info(message, ...args) {
55
- const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
56
- console.debug(
57
- this.colorize(`[${time}] \u2139\uFE0F [${this.name}] ${message}`),
58
- ...args
59
- );
54
+ this.log("info", message, ...args);
60
55
  }
61
56
  warn(message, ...args) {
62
- const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
63
- console.warn(
64
- this.colorize(`[${time}] \u{1F6A7} [${this.name}] ${message}`),
65
- ...args
66
- );
57
+ this.log("warn", message, ...args);
67
58
  }
68
59
  error(message, ...args) {
60
+ this.log("error", message, ...args);
61
+ }
62
+ log(level, message, ...args) {
63
+ const { icon, color, method } = LOG_LEVELS[level];
69
64
  const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
70
- console.error(
71
- this.colorize(`[${time}] \u274C [${this.name}] ${message}`),
72
- ...args
65
+ const isProd = process.env.NODE_ENV === "production";
66
+ const forceBoxes = process.env.ADK_FORCE_BOXES === "true";
67
+ const { meta, otherArgs } = this.extractMeta(args);
68
+ const lines = this.formatArgs(otherArgs, level === "error");
69
+ if (meta.suggestion) lines.unshift(`\u2022 Suggestion: ${meta.suggestion}`);
70
+ if (meta.context && Object.keys(meta.context).length) {
71
+ const contextStr = Object.entries(meta.context).map(([k, v]) => `${k}=${this.stringify(v)}`).join(" ");
72
+ lines.unshift(`\u2022 Context: ${contextStr}`);
73
+ }
74
+ if (isProd && !forceBoxes) {
75
+ const header = `[${time}] ${icon} [${this.name}] ${message}`;
76
+ const output = lines.length ? [header, ...lines].join("\n") : header;
77
+ method(color(output));
78
+ return;
79
+ }
80
+ if (level === "warn" || level === "error") {
81
+ const box = this.formatBox({
82
+ title: `${icon} ${this.capitalize(level)} @ ${time} (${this.name})`,
83
+ description: message,
84
+ lines,
85
+ color
86
+ });
87
+ method(box);
88
+ } else {
89
+ const header = `[${time}] ${icon} [${this.name}] ${message}`;
90
+ const output = lines.length ? [header, ...lines].join("\n") : header;
91
+ method(color(output));
92
+ }
93
+ }
94
+ extractMeta(args) {
95
+ const meta = {};
96
+ const otherArgs = [];
97
+ let metaFound = false;
98
+ for (const arg of args) {
99
+ if (!arg) continue;
100
+ if (!metaFound && typeof arg === "object" && !(arg instanceof Error) && ("suggestion" in arg || "context" in arg)) {
101
+ meta.suggestion = arg.suggestion;
102
+ meta.context = arg.context;
103
+ metaFound = true;
104
+ } else {
105
+ otherArgs.push(arg);
106
+ }
107
+ }
108
+ return { meta, otherArgs };
109
+ }
110
+ formatArgs(args, includeStack = false) {
111
+ const lines = [];
112
+ const maxFrames = Number(process.env.ADK_ERROR_STACK_FRAMES || 8);
113
+ for (const arg of args) {
114
+ if (!arg) continue;
115
+ if (arg instanceof Error) {
116
+ lines.push(`\u2022 ${arg.name}: ${arg.message}`);
117
+ if (includeStack && arg.stack) {
118
+ const frames = this.parseStackFrames(arg.stack, maxFrames);
119
+ if (frames.length) {
120
+ lines.push("\u2022 Stack:", ...frames);
121
+ }
122
+ }
123
+ } else {
124
+ lines.push(`\u2022 ${this.stringify(arg)}`);
125
+ }
126
+ }
127
+ return lines;
128
+ }
129
+ parseStackFrames(stack, maxFrames) {
130
+ const frames = stack.split(/\n/).slice(1).map((f) => f.trim()).filter(Boolean).slice(0, maxFrames);
131
+ const result = frames.map((frame) => {
132
+ const cleaned = frame.replace(/^at\s+/, "").replace(process.cwd(), ".");
133
+ return ` \u21B3 ${cleaned}`;
134
+ });
135
+ const totalFrames = stack.split(/\n/).length - 1;
136
+ if (totalFrames > maxFrames) {
137
+ result.push(` \u21B3 \u2026 ${totalFrames - maxFrames} more frames`);
138
+ }
139
+ return result;
140
+ }
141
+ stringify(value) {
142
+ if (typeof value === "string") return value;
143
+ if (typeof value === "number" || typeof value === "boolean")
144
+ return String(value);
145
+ if (value === null || value === void 0) return String(value);
146
+ try {
147
+ return JSON.stringify(value);
148
+ } catch (e2) {
149
+ return String(value);
150
+ }
151
+ }
152
+ capitalize(str) {
153
+ return str.charAt(0).toUpperCase() + str.slice(1);
154
+ }
155
+ formatBox(params) {
156
+ const {
157
+ title,
158
+ description,
159
+ lines = [],
160
+ width = 60,
161
+ maxWidthPct = 0.9,
162
+ color = _chalk2.default.yellow,
163
+ pad = 1,
164
+ borderChar = "\u2500"
165
+ } = params;
166
+ const isProd = process.env.NODE_ENV === "production";
167
+ const forceBoxes = process.env.ADK_FORCE_BOXES === "true";
168
+ if (isProd && !forceBoxes) {
169
+ return [`${title}: ${description}`, ...lines].join("\n");
170
+ }
171
+ const termWidth = process.stdout.columns || 80;
172
+ const maxWidth = Math.floor(termWidth * maxWidthPct);
173
+ const contentWidth = Math.max(
174
+ width,
175
+ title.length + 2,
176
+ description.length,
177
+ ...lines.map((l) => l.length)
73
178
  );
179
+ const innerWidth = Math.min(contentWidth + pad * 2, maxWidth - 2);
180
+ const horizontal = borderChar.repeat(innerWidth + 2);
181
+ const top = `\u250C${horizontal}\u2510`;
182
+ const separator = `\u251C${horizontal}\u2524`;
183
+ const bottom = `\u2514${horizontal}\u2518`;
184
+ const padLine = (text) => {
185
+ const maxContent = innerWidth - pad * 2;
186
+ const truncated = text.length > maxContent ? `${text.slice(0, maxContent - 1)}\u2026` : text;
187
+ const padded = " ".repeat(pad) + truncated;
188
+ return padded + " ".repeat(innerWidth - padded.length);
189
+ };
190
+ const content = [
191
+ top,
192
+ `\u2502 ${padLine(title)} \u2502`,
193
+ separator,
194
+ `\u2502 ${padLine(description)} \u2502`,
195
+ ...lines.map((line) => `\u2502 ${padLine(line)} \u2502`),
196
+ bottom
197
+ ];
198
+ return `
199
+ ${content.map((line) => color(line)).join("\n")}`;
74
200
  }
75
201
  /**
76
- * Logs structured data in a visually appealing table format.
77
- * Uses vertical layout for better readability and respects debug settings.
202
+ * Structured warning with code, suggestion, context.
78
203
  */
204
+ warnStructured(warning, opts = {}) {
205
+ const format = opts.format || process.env.ADK_WARN_FORMAT || "pretty";
206
+ const verbose = opts.verbose || process.env.ADK_AGENT_BUILDER_WARN === "verbose";
207
+ const timestamp = warning.timestamp || (/* @__PURE__ */ new Date()).toISOString();
208
+ const severity = warning.severity || "warn";
209
+ if (format === "json") {
210
+ this.warn(
211
+ JSON.stringify({
212
+ level: severity,
213
+ source: this.name,
214
+ timestamp,
215
+ ...warning
216
+ })
217
+ );
218
+ return;
219
+ }
220
+ const { icon } = LOG_LEVELS[severity] || LOG_LEVELS.warn;
221
+ const base = `${icon} ${warning.code} ${warning.message}`;
222
+ const parts = [base];
223
+ if (warning.suggestion) {
224
+ parts.push(` \u2022 Suggestion: ${warning.suggestion}`);
225
+ }
226
+ if (verbose && warning.context && Object.keys(warning.context).length) {
227
+ const contextStr = Object.entries(warning.context).map(([k, v]) => `${k}=${this.stringify(v)}`).join(" ");
228
+ parts.push(` \u2022 Context: ${contextStr}`);
229
+ }
230
+ if (format === "pretty") {
231
+ this.warn(parts.join("\n"));
232
+ } else {
233
+ const textParts = [`[${warning.code}] ${warning.message}`];
234
+ if (warning.suggestion) textParts.push(` -> ${warning.suggestion}`);
235
+ if (verbose && warning.context && Object.keys(warning.context).length) {
236
+ const contextStr = Object.entries(warning.context).map(([k, v]) => `${k}=${this.stringify(v)}`).join(" ");
237
+ textParts.push(` \u2022 Context: ${contextStr}`);
238
+ }
239
+ this.warn(textParts.join("\n"));
240
+ }
241
+ }
79
242
  debugStructured(title, data) {
80
243
  if (!this.isDebugEnabled) return;
81
- const terminalWidth = process.stdout.columns || 60;
82
- const width = Math.min(terminalWidth, 100);
83
- const contentWidth = width - 4;
84
- const topBorder = `\u250C${"\u2500".repeat(width - 2)}\u2510`;
85
- const bottomBorder = `\u2514${"\u2500".repeat(width - 2)}\u2518`;
86
- const middleBorder = `\u251C${"\u2500".repeat(width - 2)}\u2524`;
87
- console.log(this.colorize(topBorder));
88
- console.log(this.colorize(`\u2502 ${title.padEnd(contentWidth)} \u2502`));
89
- console.log(this.colorize(middleBorder));
90
- Object.entries(data).forEach(([key, value]) => {
91
- const formattedKey = key.padEnd(20);
92
- const formattedValue = String(value);
93
- const availableValueSpace = contentWidth - 20 - 2;
94
- const truncatedValue = formattedValue.length > availableValueSpace ? `${formattedValue.substring(0, availableValueSpace - 3)}...` : formattedValue;
95
- const content = `${formattedKey}: ${truncatedValue}`;
96
- const paddedContent = content.padEnd(contentWidth);
97
- console.log(this.colorize(`\u2502 ${paddedContent} \u2502`));
244
+ const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
245
+ const lines = this.objectToLines(data);
246
+ const box = this.formatBox({
247
+ title: `\u{1F41B} Debug @ ${time} (${this.name})`,
248
+ description: title,
249
+ lines,
250
+ color: _chalk2.default.blue
98
251
  });
99
- console.log(this.colorize(bottomBorder));
252
+ console.log(box);
100
253
  }
101
- /**
102
- * Logs array data in a compact, readable format.
103
- */
104
254
  debugArray(title, items) {
105
255
  if (!this.isDebugEnabled) return;
106
- const terminalWidth = process.stdout.columns || 78;
107
- const width = Math.min(terminalWidth, 120);
108
- const contentWidth = width - 4;
109
- const topBorder = `\u250C${"\u2500".repeat(width - 2)}\u2510`;
110
- const bottomBorder = `\u2514${"\u2500".repeat(width - 2)}\u2518`;
111
- const middleBorder = `\u251C${"\u2500".repeat(width - 2)}\u2524`;
112
- console.log(this.colorize(topBorder));
113
- console.log(this.colorize(`\u2502 ${title.padEnd(contentWidth)} \u2502`));
114
- console.log(this.colorize(middleBorder));
115
- items.forEach((item, index) => {
116
- const itemStr = Object.entries(item).map(([k, v]) => `${k}: ${v}`).join(" \u2022 ");
117
- const indexPart = `[${index + 1}] `;
118
- const availableSpace = contentWidth - indexPart.length;
119
- const truncatedItem = itemStr.length > availableSpace ? `${itemStr.substring(0, availableSpace - 3)}...` : itemStr;
120
- const content = `${indexPart}${truncatedItem}`;
121
- const paddedContent = content.padEnd(contentWidth);
122
- console.log(this.colorize(`\u2502 ${paddedContent} \u2502`));
256
+ const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
257
+ const lines = this.arrayToLines(items);
258
+ const box = this.formatBox({
259
+ title: `\u{1F41B} Debug List @ ${time} (${this.name})`,
260
+ description: title,
261
+ lines,
262
+ color: _chalk2.default.blue,
263
+ width: 78,
264
+ maxWidthPct: 0.95
265
+ });
266
+ console.log(box);
267
+ }
268
+ objectToLines(obj) {
269
+ const entries = Object.entries(obj || {});
270
+ if (!entries.length) return ["(empty)"];
271
+ const keyWidth = Math.min(
272
+ 30,
273
+ Math.max(6, ...entries.map(([k]) => k.length))
274
+ );
275
+ return entries.slice(0, 200).map(([k, v]) => {
276
+ const value = this.stringify(v);
277
+ const truncated = value.length > 140 ? `${value.slice(0, 139)}\u2026` : value;
278
+ return `${k.padEnd(keyWidth)}: ${truncated}`;
279
+ });
280
+ }
281
+ arrayToLines(items) {
282
+ if (!items.length) return ["(empty list)"];
283
+ const maxItems = 50;
284
+ const lines = items.slice(0, maxItems).map((obj, i) => {
285
+ const props = Object.entries(obj).map(([k, v]) => {
286
+ const value = this.stringify(v);
287
+ const truncated = value.length > 160 ? `${value.slice(0, 159)}\u2026` : value;
288
+ return `${k}=${truncated}`;
289
+ }).join(" \u2022 ");
290
+ return `[${i + 1}] ${props}`;
123
291
  });
124
- console.log(this.colorize(bottomBorder));
292
+ if (items.length > maxItems) {
293
+ lines.push(`\u2026 ${items.length - maxItems} more items omitted`);
294
+ }
295
+ return lines;
125
296
  }
126
297
  }, _class);
127
298
  }
@@ -4237,7 +4408,7 @@ var AgentTool = (_class15 = class extends BaseTool {
4237
4408
  let toolResult;
4238
4409
  try {
4239
4410
  toolResult = JSON.parse(mergedText);
4240
- } catch (e2) {
4411
+ } catch (e3) {
4241
4412
  toolResult = mergedText;
4242
4413
  }
4243
4414
  if (this.outputKey && _optionalChain([context4, 'optionalAccess', _145 => _145.state])) {
@@ -4688,7 +4859,7 @@ var FileOperationsTool = class extends BaseTool {
4688
4859
  success: true,
4689
4860
  data: true
4690
4861
  };
4691
- } catch (e3) {
4862
+ } catch (e4) {
4692
4863
  return {
4693
4864
  success: true,
4694
4865
  data: false
@@ -7111,6 +7282,7 @@ var AuthLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7111
7282
  var requestProcessor = new AuthLlmRequestProcessor();
7112
7283
 
7113
7284
  // src/flows/llm-flows/basic.ts
7285
+ init_logger();
7114
7286
  var BasicLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7115
7287
  async *runAsync(invocationContext, llmRequest) {
7116
7288
  const agent = invocationContext.agent;
@@ -7126,7 +7298,21 @@ var BasicLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7126
7298
  llmRequest.config = {};
7127
7299
  }
7128
7300
  if (agent.outputSchema) {
7129
- llmRequest.setOutputSchema(agent.outputSchema);
7301
+ const hasTools = await _asyncOptionalChain([(await _optionalChain([agent, 'access', _211 => _211.canonicalTools, 'optionalCall', _212 => _212(invocationContext)])), 'optionalAccess', async _213 => _213.length]) > 0;
7302
+ const hasTransfers = !!("subAgents" in agent && agent.subAgents && agent.subAgents.length > 0 && !(agent.disallowTransferToParent && agent.disallowTransferToPeers));
7303
+ if (!hasTools && !hasTransfers) {
7304
+ llmRequest.setOutputSchema(agent.outputSchema);
7305
+ } else {
7306
+ (() => {
7307
+ try {
7308
+ const logger = new Logger({ name: "BasicLlmRequestProcessor" });
7309
+ logger.debug(
7310
+ `Skipping request-level output schema for agent ${agent.name} because tools/transfers are present. Schema will be validated during response processing.`
7311
+ );
7312
+ } catch (e) {
7313
+ }
7314
+ })();
7315
+ }
7130
7316
  }
7131
7317
  const runConfig = invocationContext.runConfig;
7132
7318
  if (!llmRequest.liveConnectConfig) {
@@ -7204,7 +7390,7 @@ var BuiltInCodeExecutor = class extends BaseCodeExecutor {
7204
7390
  * Pre-process the LLM request for Gemini 2.0+ models to use the code execution tool
7205
7391
  */
7206
7392
  processLlmRequest(llmRequest) {
7207
- if (!_optionalChain([llmRequest, 'access', _211 => _211.model, 'optionalAccess', _212 => _212.startsWith, 'call', _213 => _213("gemini-2")])) {
7393
+ if (!_optionalChain([llmRequest, 'access', _214 => _214.model, 'optionalAccess', _215 => _215.startsWith, 'call', _216 => _216("gemini-2")])) {
7208
7394
  throw new Error(
7209
7395
  `Gemini code execution tool is not supported for model ${llmRequest.model}`
7210
7396
  );
@@ -7241,7 +7427,7 @@ var CodeExecutionUtils = class _CodeExecutionUtils {
7241
7427
  static isBase64Encoded(str) {
7242
7428
  try {
7243
7429
  return btoa(atob(str)) === str;
7244
- } catch (e4) {
7430
+ } catch (e5) {
7245
7431
  return false;
7246
7432
  }
7247
7433
  }
@@ -7249,7 +7435,7 @@ var CodeExecutionUtils = class _CodeExecutionUtils {
7249
7435
  * Extracts the first code block from the content and truncates everything after it
7250
7436
  */
7251
7437
  static extractCodeAndTruncateContent(content, codeBlockDelimiters) {
7252
- if (!_optionalChain([content, 'optionalAccess', _214 => _214.parts, 'optionalAccess', _215 => _215.length])) {
7438
+ if (!_optionalChain([content, 'optionalAccess', _217 => _217.parts, 'optionalAccess', _218 => _218.length])) {
7253
7439
  return null;
7254
7440
  }
7255
7441
  for (let idx = 0; idx < content.parts.length; idx++) {
@@ -7335,7 +7521,7 @@ ${fileNames}`);
7335
7521
  * Converts the code execution parts to text parts in a Content
7336
7522
  */
7337
7523
  static convertCodeExecutionParts(content, codeBlockDelimiter, executionResultDelimiters) {
7338
- if (!_optionalChain([content, 'access', _216 => _216.parts, 'optionalAccess', _217 => _217.length])) {
7524
+ if (!_optionalChain([content, 'access', _219 => _219.parts, 'optionalAccess', _220 => _220.length])) {
7339
7525
  return;
7340
7526
  }
7341
7527
  const lastPart = content.parts[content.parts.length - 1];
@@ -7728,7 +7914,7 @@ async function* runPostProcessor(invocationContext, llmResponse) {
7728
7914
  function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
7729
7915
  const allInputFiles = codeExecutorContext.getInputFiles();
7730
7916
  const savedFileNames = new Set(allInputFiles.map((f) => f.name));
7731
- for (let i = 0; i < (_optionalChain([llmRequest, 'access', _218 => _218.contents, 'optionalAccess', _219 => _219.length]) || 0); i++) {
7917
+ for (let i = 0; i < (_optionalChain([llmRequest, 'access', _221 => _221.contents, 'optionalAccess', _222 => _222.length]) || 0); i++) {
7732
7918
  const content = llmRequest.contents[i];
7733
7919
  if (content.role !== "user" || !content.parts) {
7734
7920
  continue;
@@ -7760,7 +7946,7 @@ Available file: \`${fileName}\`
7760
7946
  }
7761
7947
  function getOrSetExecutionId(invocationContext, codeExecutorContext) {
7762
7948
  const agent = invocationContext.agent;
7763
- if (!hasCodeExecutor(agent) || !_optionalChain([agent, 'access', _220 => _220.codeExecutor, 'optionalAccess', _221 => _221.stateful])) {
7949
+ if (!hasCodeExecutor(agent) || !_optionalChain([agent, 'access', _223 => _223.codeExecutor, 'optionalAccess', _224 => _224.stateful])) {
7764
7950
  return void 0;
7765
7951
  }
7766
7952
  let executionId = codeExecutorContext.getExecutionId();
@@ -7991,7 +8177,7 @@ function rearrangeEventsForLatestFunctionResponse(events) {
7991
8177
  continue;
7992
8178
  }
7993
8179
  const functionResponses2 = event.getFunctionResponses();
7994
- if (_optionalChain([functionResponses2, 'optionalAccess', _222 => _222.some, 'call', _223 => _223((fr) => fr.id && functionResponsesIds.has(fr.id))])) {
8180
+ if (_optionalChain([functionResponses2, 'optionalAccess', _225 => _225.some, 'call', _226 => _226((fr) => fr.id && functionResponsesIds.has(fr.id))])) {
7995
8181
  functionResponseEvents.push(event);
7996
8182
  }
7997
8183
  }
@@ -8090,7 +8276,7 @@ function mergeFunctionResponseEvents(functionResponseEvents) {
8090
8276
  const partIndicesInMergedEvent = {};
8091
8277
  for (let idx = 0; idx < partsInMergedEvent.length; idx++) {
8092
8278
  const part = partsInMergedEvent[idx];
8093
- if (_optionalChain([part, 'access', _224 => _224.functionResponse, 'optionalAccess', _225 => _225.id])) {
8279
+ if (_optionalChain([part, 'access', _227 => _227.functionResponse, 'optionalAccess', _228 => _228.id])) {
8094
8280
  partIndicesInMergedEvent[part.functionResponse.id] = idx;
8095
8281
  }
8096
8282
  }
@@ -8099,7 +8285,7 @@ function mergeFunctionResponseEvents(functionResponseEvents) {
8099
8285
  throw new Error("There should be at least one function_response part.");
8100
8286
  }
8101
8287
  for (const part of event.content.parts) {
8102
- if (_optionalChain([part, 'access', _226 => _226.functionResponse, 'optionalAccess', _227 => _227.id])) {
8288
+ if (_optionalChain([part, 'access', _229 => _229.functionResponse, 'optionalAccess', _230 => _230.id])) {
8103
8289
  const functionCallId = part.functionResponse.id;
8104
8290
  if (functionCallId in partIndicesInMergedEvent) {
8105
8291
  partsInMergedEvent[partIndicesInMergedEvent[functionCallId]] = part;
@@ -8278,12 +8464,13 @@ var InstructionsLlmRequestProcessor = class extends BaseLlmRequestProcessor {
8278
8464
  });
8279
8465
  const { $schema, ...json } = raw || {};
8280
8466
  llmRequest.appendInstructions([
8281
- "You must respond with application/json that validates against this JSON Schema:",
8282
- "```json",
8283
- JSON.stringify(json, null, 2),
8284
- "```"
8467
+ "You must respond with application/json that validates against this JSON Schema (do NOT wrap the output in markdown or code fences):",
8468
+ JSON.stringify(json, null, 2)
8285
8469
  ]);
8286
- } catch (e5) {
8470
+ llmRequest.appendInstructions([
8471
+ 'IMPORTANT: After any tool calls, function calls, or agent transfers have completed, produce ONE final assistant message whose entire content is ONLY the JSON object that conforms to the schema provided above. Do NOT include any explanatory text, markdown, or additional messages. Do NOT wrap the JSON in code fences (for example, do NOT use ```json or ```). If you cannot produce valid JSON that matches the schema, return a JSON object with an "error" field describing the problem.'
8472
+ ]);
8473
+ } catch (e6) {
8287
8474
  }
8288
8475
  }
8289
8476
  for await (const _ of []) {
@@ -8368,7 +8555,7 @@ var PlanReActPlanner = class extends BasePlanner {
8368
8555
  let firstFcPartIndex = -1;
8369
8556
  for (let i = 0; i < responseParts.length; i++) {
8370
8557
  if (responseParts[i].functionCall) {
8371
- if (!_optionalChain([responseParts, 'access', _228 => _228[i], 'access', _229 => _229.functionCall, 'optionalAccess', _230 => _230.name])) {
8558
+ if (!_optionalChain([responseParts, 'access', _231 => _231[i], 'access', _232 => _232.functionCall, 'optionalAccess', _233 => _233.name])) {
8372
8559
  continue;
8373
8560
  }
8374
8561
  preservedParts.push(responseParts[i]);
@@ -8407,7 +8594,7 @@ var PlanReActPlanner = class extends BasePlanner {
8407
8594
  * Handles non-function-call parts of the response
8408
8595
  */
8409
8596
  _handleNonFunctionCallParts(responsePart, preservedParts) {
8410
- if (_optionalChain([responsePart, 'access', _231 => _231.text, 'optionalAccess', _232 => _232.includes, 'call', _233 => _233(FINAL_ANSWER_TAG)])) {
8597
+ if (_optionalChain([responsePart, 'access', _234 => _234.text, 'optionalAccess', _235 => _235.includes, 'call', _236 => _236(FINAL_ANSWER_TAG)])) {
8411
8598
  const [reasoningText, finalAnswerText] = this._splitByLastPattern(
8412
8599
  responsePart.text,
8413
8600
  FINAL_ANSWER_TAG
@@ -8578,6 +8765,7 @@ var requestProcessor7 = new NlPlanningRequestProcessor();
8578
8765
  var responseProcessor2 = new NlPlanningResponseProcessor();
8579
8766
 
8580
8767
  // src/flows/llm-flows/output-schema.ts
8768
+ var _jsonrepair = require('jsonrepair');
8581
8769
  init_logger();
8582
8770
  var OutputSchemaResponseProcessor = (_class26 = class extends BaseLlmResponseProcessor {constructor(...args2) { super(...args2); _class26.prototype.__init46.call(this); }
8583
8771
  __init46() {this.logger = new Logger({ name: "OutputSchemaResponseProcessor" })}
@@ -8599,7 +8787,8 @@ var OutputSchemaResponseProcessor = (_class26 = class extends BaseLlmResponsePro
8599
8787
  return;
8600
8788
  }
8601
8789
  try {
8602
- const parsed = JSON.parse(textContent);
8790
+ const candidate = this.stripCodeFences(textContent);
8791
+ const parsed = this.tryParseJson(candidate, agent.name);
8603
8792
  const validated = agent.outputSchema.parse(parsed);
8604
8793
  textContent = JSON.stringify(validated, null, 2);
8605
8794
  llmResponse.content.parts = llmResponse.content.parts.map((part) => {
@@ -8647,6 +8836,38 @@ var OutputSchemaResponseProcessor = (_class26 = class extends BaseLlmResponsePro
8647
8836
  yield errorEvent;
8648
8837
  }
8649
8838
  }
8839
+ // Strip common code fences and surrounding explanatory text from LLM output.
8840
+ stripCodeFences(raw) {
8841
+ const fencePattern = /```(?:json)?\s*([\s\S]*?)```/i;
8842
+ const fenceMatch = raw.match(fencePattern);
8843
+ if (_optionalChain([fenceMatch, 'optionalAccess', _237 => _237[1]])) {
8844
+ return fenceMatch[1].trim();
8845
+ }
8846
+ const lines = raw.split(/\r?\n/).map((l) => l.trim());
8847
+ const startIdx = lines.findIndex(
8848
+ (l) => l.startsWith("{") || l.startsWith("[")
8849
+ );
8850
+ if (startIdx >= 0) {
8851
+ return lines.slice(startIdx).join("\n").trim();
8852
+ }
8853
+ return raw.trim();
8854
+ }
8855
+ // Try parsing JSON; if parse fails, attempt to repair using jsonrepair and parse again.
8856
+ tryParseJson(candidate, agentName) {
8857
+ try {
8858
+ return JSON.parse(candidate);
8859
+ } catch (err) {
8860
+ this.logger.debug("Initial JSON.parse failed, attempting jsonrepair", {
8861
+ agent: agentName
8862
+ });
8863
+ try {
8864
+ const repaired = _jsonrepair.jsonrepair.call(void 0, candidate);
8865
+ return JSON.parse(repaired);
8866
+ } catch (repairErr) {
8867
+ throw err;
8868
+ }
8869
+ }
8870
+ }
8650
8871
  }, _class26);
8651
8872
  var responseProcessor3 = new OutputSchemaResponseProcessor();
8652
8873
 
@@ -8656,7 +8877,7 @@ var SharedMemoryRequestProcessor = class extends BaseLlmRequestProcessor {
8656
8877
  const memoryService = invocationContext.memoryService;
8657
8878
  if (!memoryService) return;
8658
8879
  const lastUserEvent = invocationContext.session.events.findLast(
8659
- (e) => e.author === "user" && _optionalChain([e, 'access', _234 => _234.content, 'optionalAccess', _235 => _235.parts, 'optionalAccess', _236 => _236.length])
8880
+ (e) => e.author === "user" && _optionalChain([e, 'access', _238 => _238.content, 'optionalAccess', _239 => _239.parts, 'optionalAccess', _240 => _240.length])
8660
8881
  );
8661
8882
  if (!lastUserEvent) return;
8662
8883
  const query = (_nullishCoalesce(lastUserEvent.content.parts, () => ( []))).map((p) => p.text || "").join(" ");
@@ -8667,7 +8888,7 @@ var SharedMemoryRequestProcessor = class extends BaseLlmRequestProcessor {
8667
8888
  });
8668
8889
  const sessionTexts = new Set(
8669
8890
  (llmRequest.contents || []).flatMap(
8670
- (c) => _optionalChain([c, 'access', _237 => _237.parts, 'optionalAccess', _238 => _238.map, 'call', _239 => _239((p) => p.text)]) || []
8891
+ (c) => _optionalChain([c, 'access', _241 => _241.parts, 'optionalAccess', _242 => _242.map, 'call', _243 => _243((p) => p.text)]) || []
8671
8892
  )
8672
8893
  );
8673
8894
  for (const memory of results.memories) {
@@ -9069,19 +9290,17 @@ var LlmAgent = (_class27 = class _LlmAgent extends BaseAgent {
9069
9290
  }
9070
9291
  if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {
9071
9292
  this.logger.warn(
9072
- `Invalid config for agent ${this.name}: output_schema cannot co-exist with agent transfer configurations. Setting disallow_transfer_to_parent=true, disallow_transfer_to_peers=true`
9293
+ `Agent ${this.name}: outputSchema is set while transfer flags allow transfers. The output schema will be applied in response post-processing to preserve tool-calling and transfer behavior.`
9073
9294
  );
9074
- this.disallowTransferToParent = true;
9075
- this.disallowTransferToPeers = true;
9076
9295
  }
9077
9296
  if (this.subAgents && this.subAgents.length > 0) {
9078
- throw new Error(
9079
- `Invalid config for agent ${this.name}: if output_schema is set, sub_agents must be empty to disable agent transfer.`
9297
+ this.logger.warn(
9298
+ `Agent ${this.name}: outputSchema is set and subAgents are present. Agent transfers to sub-agents will remain enabled; the schema will be validated after transfers/tools complete.`
9080
9299
  );
9081
9300
  }
9082
9301
  if (this.tools && this.tools.length > 0) {
9083
- throw new Error(
9084
- `Invalid config for agent ${this.name}: if output_schema is set, tools must be empty`
9302
+ this.logger.warn(
9303
+ `Agent ${this.name}: outputSchema is set and tools are configured. Tools will be callable; the output schema will be applied during response post-processing.`
9085
9304
  );
9086
9305
  }
9087
9306
  }
@@ -9090,7 +9309,7 @@ var LlmAgent = (_class27 = class _LlmAgent extends BaseAgent {
9090
9309
  * This matches the Python implementation's _llm_flow property
9091
9310
  */
9092
9311
  get llmFlow() {
9093
- if (this.disallowTransferToParent && this.disallowTransferToPeers && !_optionalChain([this, 'access', _240 => _240.subAgents, 'optionalAccess', _241 => _241.length])) {
9312
+ if (this.disallowTransferToParent && this.disallowTransferToPeers && !_optionalChain([this, 'access', _244 => _244.subAgents, 'optionalAccess', _245 => _245.length])) {
9094
9313
  return new SingleFlow();
9095
9314
  }
9096
9315
  return new AutoFlow();
@@ -9106,7 +9325,7 @@ var LlmAgent = (_class27 = class _LlmAgent extends BaseAgent {
9106
9325
  );
9107
9326
  return;
9108
9327
  }
9109
- if (this.outputKey && event.isFinalResponse() && _optionalChain([event, 'access', _242 => _242.content, 'optionalAccess', _243 => _243.parts])) {
9328
+ if (this.outputKey && event.isFinalResponse() && _optionalChain([event, 'access', _246 => _246.content, 'optionalAccess', _247 => _247.parts])) {
9110
9329
  let result = event.content.parts.map((part) => part.text || "").join("");
9111
9330
  if (this.outputSchema) {
9112
9331
  if (!result.trim()) {
@@ -9243,37 +9462,29 @@ async function* mergeAgentRun(agentRuns) {
9243
9462
  if (agentRuns.length === 0) {
9244
9463
  return;
9245
9464
  }
9246
- const promises = agentRuns.map(async (generator, index) => {
9247
- try {
9248
- const result = await generator.next();
9249
- return { index, result };
9250
- } catch (error) {
9251
- return { index, result: { done: true, value: void 0 }, error };
9465
+ const nextFor = (gen, index) => gen.next().then((result) => ({ index, result })).catch((error) => ({
9466
+ index,
9467
+ result: { done: true, value: void 0 },
9468
+ error
9469
+ }));
9470
+ const entries = agentRuns.map((gen, i) => ({ index: i, promise: nextFor(gen, i) }));
9471
+ const activePromises = () => entries.filter((e) => !!e).map((e) => e.promise);
9472
+ while (true) {
9473
+ const currentActivePromises = activePromises();
9474
+ if (currentActivePromises.length === 0) {
9475
+ break;
9252
9476
  }
9253
- });
9254
- let pendingPromises = [...promises];
9255
- while (pendingPromises.length > 0) {
9256
- const { index, result, error } = await Promise.race(pendingPromises);
9257
- pendingPromises = pendingPromises.filter((_, i) => i !== index);
9477
+ const { index, result, error } = await Promise.race(currentActivePromises);
9258
9478
  if (error) {
9259
9479
  console.error(`Error in parallel agent ${index}:`, error);
9480
+ entries[index] = void 0;
9260
9481
  continue;
9261
9482
  }
9262
9483
  if (!result.done) {
9263
9484
  yield result.value;
9264
- const nextPromise = (async () => {
9265
- try {
9266
- const nextResult = await agentRuns[index].next();
9267
- return { index, result: nextResult };
9268
- } catch (nextError) {
9269
- return {
9270
- index,
9271
- result: { done: true, value: void 0 },
9272
- error: nextError
9273
- };
9274
- }
9275
- })();
9276
- pendingPromises.push(nextPromise);
9485
+ entries[index] = { index, promise: nextFor(agentRuns[index], index) };
9486
+ } else {
9487
+ entries[index] = void 0;
9277
9488
  }
9278
9489
  }
9279
9490
  }
@@ -9334,7 +9545,7 @@ var LoopAgent = class extends BaseAgent {
9334
9545
  for (const subAgent of this.subAgents) {
9335
9546
  for await (const event of subAgent.runAsync(ctx)) {
9336
9547
  yield event;
9337
- if (_optionalChain([event, 'access', _244 => _244.actions, 'optionalAccess', _245 => _245.escalate])) {
9548
+ if (_optionalChain([event, 'access', _248 => _248.actions, 'optionalAccess', _249 => _249.escalate])) {
9338
9549
  return;
9339
9550
  }
9340
9551
  }
@@ -9646,17 +9857,17 @@ var RunConfig = class {
9646
9857
  */
9647
9858
 
9648
9859
  constructor(config) {
9649
- this.speechConfig = _optionalChain([config, 'optionalAccess', _246 => _246.speechConfig]);
9650
- this.responseModalities = _optionalChain([config, 'optionalAccess', _247 => _247.responseModalities]);
9651
- this.saveInputBlobsAsArtifacts = _optionalChain([config, 'optionalAccess', _248 => _248.saveInputBlobsAsArtifacts]) || false;
9652
- this.supportCFC = _optionalChain([config, 'optionalAccess', _249 => _249.supportCFC]) || false;
9653
- this.streamingMode = _optionalChain([config, 'optionalAccess', _250 => _250.streamingMode]) || "NONE" /* NONE */;
9654
- this.outputAudioTranscription = _optionalChain([config, 'optionalAccess', _251 => _251.outputAudioTranscription]);
9655
- this.inputAudioTranscription = _optionalChain([config, 'optionalAccess', _252 => _252.inputAudioTranscription]);
9656
- this.realtimeInputConfig = _optionalChain([config, 'optionalAccess', _253 => _253.realtimeInputConfig]);
9657
- this.enableAffectiveDialog = _optionalChain([config, 'optionalAccess', _254 => _254.enableAffectiveDialog]);
9658
- this.proactivity = _optionalChain([config, 'optionalAccess', _255 => _255.proactivity]);
9659
- this.maxLlmCalls = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _256 => _256.maxLlmCalls]), () => ( 500));
9860
+ this.speechConfig = _optionalChain([config, 'optionalAccess', _250 => _250.speechConfig]);
9861
+ this.responseModalities = _optionalChain([config, 'optionalAccess', _251 => _251.responseModalities]);
9862
+ this.saveInputBlobsAsArtifacts = _optionalChain([config, 'optionalAccess', _252 => _252.saveInputBlobsAsArtifacts]) || false;
9863
+ this.supportCFC = _optionalChain([config, 'optionalAccess', _253 => _253.supportCFC]) || false;
9864
+ this.streamingMode = _optionalChain([config, 'optionalAccess', _254 => _254.streamingMode]) || "NONE" /* NONE */;
9865
+ this.outputAudioTranscription = _optionalChain([config, 'optionalAccess', _255 => _255.outputAudioTranscription]);
9866
+ this.inputAudioTranscription = _optionalChain([config, 'optionalAccess', _256 => _256.inputAudioTranscription]);
9867
+ this.realtimeInputConfig = _optionalChain([config, 'optionalAccess', _257 => _257.realtimeInputConfig]);
9868
+ this.enableAffectiveDialog = _optionalChain([config, 'optionalAccess', _258 => _258.enableAffectiveDialog]);
9869
+ this.proactivity = _optionalChain([config, 'optionalAccess', _259 => _259.proactivity]);
9870
+ this.maxLlmCalls = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _260 => _260.maxLlmCalls]), () => ( 500));
9660
9871
  this.validateMaxLlmCalls();
9661
9872
  }
9662
9873
  /**
@@ -9800,7 +10011,7 @@ var InMemoryMemoryService = (_class30 = class {
9800
10011
  }
9801
10012
  const userSessions = this._sessionEvents.get(userKey);
9802
10013
  const filteredEvents = session.events.filter(
9803
- (event) => _optionalChain([event, 'access', _257 => _257.content, 'optionalAccess', _258 => _258.parts])
10014
+ (event) => _optionalChain([event, 'access', _261 => _261.content, 'optionalAccess', _262 => _262.parts])
9804
10015
  );
9805
10016
  userSessions.set(session.id, filteredEvents);
9806
10017
  }
@@ -9939,7 +10150,7 @@ var InMemorySessionService = (_class31 = class extends BaseSessionService {const
9939
10150
  return this.createSessionImpl(appName, userId, state, sessionId);
9940
10151
  }
9941
10152
  createSessionImpl(appName, userId, state, sessionId) {
9942
- const finalSessionId = _optionalChain([sessionId, 'optionalAccess', _259 => _259.trim, 'call', _260 => _260()]) || _crypto.randomUUID.call(void 0, );
10153
+ const finalSessionId = _optionalChain([sessionId, 'optionalAccess', _263 => _263.trim, 'call', _264 => _264()]) || _crypto.randomUUID.call(void 0, );
9943
10154
  const session = {
9944
10155
  appName,
9945
10156
  userId,
@@ -10096,7 +10307,7 @@ var InMemorySessionService = (_class31 = class extends BaseSessionService {const
10096
10307
  warning(`sessionId ${sessionId} not in sessions[appName][userId]`);
10097
10308
  return event;
10098
10309
  }
10099
- if (_optionalChain([event, 'access', _261 => _261.actions, 'optionalAccess', _262 => _262.stateDelta])) {
10310
+ if (_optionalChain([event, 'access', _265 => _265.actions, 'optionalAccess', _266 => _266.stateDelta])) {
10100
10311
  for (const key in event.actions.stateDelta) {
10101
10312
  const value = event.actions.stateDelta[key];
10102
10313
  if (key.startsWith(State.APP_PREFIX)) {
@@ -10130,14 +10341,14 @@ function _findFunctionCallEventIfLastEventIsFunctionResponse(session) {
10130
10341
  return null;
10131
10342
  }
10132
10343
  const lastEvent = events[events.length - 1];
10133
- if (_optionalChain([lastEvent, 'access', _263 => _263.content, 'optionalAccess', _264 => _264.parts, 'optionalAccess', _265 => _265.some, 'call', _266 => _266((part) => part.functionResponse)])) {
10134
- const functionCallId = _optionalChain([lastEvent, 'access', _267 => _267.content, 'access', _268 => _268.parts, 'access', _269 => _269.find, 'call', _270 => _270(
10344
+ if (_optionalChain([lastEvent, 'access', _267 => _267.content, 'optionalAccess', _268 => _268.parts, 'optionalAccess', _269 => _269.some, 'call', _270 => _270((part) => part.functionResponse)])) {
10345
+ const functionCallId = _optionalChain([lastEvent, 'access', _271 => _271.content, 'access', _272 => _272.parts, 'access', _273 => _273.find, 'call', _274 => _274(
10135
10346
  (part) => part.functionResponse
10136
- ), 'optionalAccess', _271 => _271.functionResponse, 'optionalAccess', _272 => _272.id]);
10347
+ ), 'optionalAccess', _275 => _275.functionResponse, 'optionalAccess', _276 => _276.id]);
10137
10348
  if (!functionCallId) return null;
10138
10349
  for (let i = events.length - 2; i >= 0; i--) {
10139
10350
  const event = events[i];
10140
- const functionCalls = _optionalChain([event, 'access', _273 => _273.getFunctionCalls, 'optionalCall', _274 => _274()]) || [];
10351
+ const functionCalls = _optionalChain([event, 'access', _277 => _277.getFunctionCalls, 'optionalCall', _278 => _278()]) || [];
10141
10352
  for (const functionCall of functionCalls) {
10142
10353
  if (functionCall.id === functionCallId) {
10143
10354
  return event;
@@ -10340,15 +10551,15 @@ var Runner = (_class32 = class {
10340
10551
  */
10341
10552
  _findAgentToRun(session, rootAgent) {
10342
10553
  const event = _findFunctionCallEventIfLastEventIsFunctionResponse(session);
10343
- if (_optionalChain([event, 'optionalAccess', _275 => _275.author])) {
10554
+ if (_optionalChain([event, 'optionalAccess', _279 => _279.author])) {
10344
10555
  return rootAgent.findAgent(event.author);
10345
10556
  }
10346
- const nonUserEvents = _optionalChain([session, 'access', _276 => _276.events, 'optionalAccess', _277 => _277.filter, 'call', _278 => _278((e) => e.author !== "user"), 'access', _279 => _279.reverse, 'call', _280 => _280()]) || [];
10557
+ const nonUserEvents = _optionalChain([session, 'access', _280 => _280.events, 'optionalAccess', _281 => _281.filter, 'call', _282 => _282((e) => e.author !== "user"), 'access', _283 => _283.reverse, 'call', _284 => _284()]) || [];
10347
10558
  for (const event2 of nonUserEvents) {
10348
10559
  if (event2.author === rootAgent.name) {
10349
10560
  return rootAgent;
10350
10561
  }
10351
- const agent = _optionalChain([rootAgent, 'access', _281 => _281.findSubAgent, 'optionalCall', _282 => _282(event2.author)]);
10562
+ const agent = _optionalChain([rootAgent, 'access', _285 => _285.findSubAgent, 'optionalCall', _286 => _286(event2.author)]);
10352
10563
  if (!agent) {
10353
10564
  this.logger.debug(
10354
10565
  `Event from an unknown agent: ${event2.author}, event id: ${event2.id}`
@@ -10432,12 +10643,24 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10432
10643
  // If provided, reuse directly
10433
10644
  __init57() {this.definitionLocked = false}
10434
10645
  // Lock further definition mutation after withAgent
10435
- __init58() {this.warnedMethods = /* @__PURE__ */ new Set()}
10436
- __init59() {this.logger = new Logger({ name: "AgentBuilder" })}
10646
+ __init58() {this.logger = new Logger({ name: "AgentBuilder" })}
10647
+ /**
10648
+ * Warn (once per method) if the definition has been locked by withAgent().
10649
+ */
10650
+ warnIfLocked(method) {
10651
+ if (!this.definitionLocked) return;
10652
+ this.logger.warn(
10653
+ `AgentBuilder: ${method}() ignored because builder is locked by withAgent()`,
10654
+ {
10655
+ suggestion: "Configure model/tools/etc. before calling withAgent(), or avoid withAgent() if you intend to mutate afterwards.",
10656
+ context: { method, agentName: this.config.name }
10657
+ }
10658
+ );
10659
+ }
10437
10660
  /**
10438
10661
  * Private constructor - use static create() method
10439
10662
  */
10440
- constructor(name) {;_class33.prototype.__init56.call(this);_class33.prototype.__init57.call(this);_class33.prototype.__init58.call(this);_class33.prototype.__init59.call(this);
10663
+ constructor(name) {;_class33.prototype.__init56.call(this);_class33.prototype.__init57.call(this);_class33.prototype.__init58.call(this);
10441
10664
  this.config = { name };
10442
10665
  }
10443
10666
  /**
@@ -10493,6 +10716,16 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10493
10716
  }
10494
10717
  withOutputSchema(schema) {
10495
10718
  this.warnIfLocked("withOutputSchema");
10719
+ if (this.agentType === "sequential" || this.agentType === "parallel") {
10720
+ const msg = "Output schemas cannot be applied to sequential or parallel agents. Define output schemas on each sub-agent instead.";
10721
+ this.logger.error(msg, {
10722
+ suggestion: "Apply outputSchema to each sub-agent individually.",
10723
+ context: {
10724
+ agentType: this.agentType
10725
+ }
10726
+ });
10727
+ throw new Error(msg);
10728
+ }
10496
10729
  this.config.outputSchema = schema;
10497
10730
  return this;
10498
10731
  }
@@ -10533,6 +10766,16 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10533
10766
  */
10534
10767
  withOutputKey(outputKey) {
10535
10768
  this.warnIfLocked("withOutputKey");
10769
+ if (this.agentType === "sequential" || this.agentType === "parallel") {
10770
+ this.logger.warn(
10771
+ "AgentBuilder: outputKey ignored for sequential/parallel aggregator",
10772
+ {
10773
+ suggestion: "Set outputKey on each sub-agent instead.",
10774
+ context: { attemptedOutputKey: outputKey, agentType: this.agentType }
10775
+ }
10776
+ );
10777
+ return this;
10778
+ }
10536
10779
  this.config.outputKey = outputKey;
10537
10780
  return this;
10538
10781
  }
@@ -10584,9 +10827,37 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10584
10827
  * @returns This builder instance for chaining
10585
10828
  */
10586
10829
  asSequential(subAgents) {
10587
- this.warnIfLocked("asSequential");
10830
+ if (this.definitionLocked) {
10831
+ this.logger.warn(
10832
+ "AgentBuilder: asSequential() ignored; builder locked by withAgent()",
10833
+ {
10834
+ suggestion: "Call asSequential() before withAgent().",
10835
+ context: { agentName: this.config.name }
10836
+ }
10837
+ );
10838
+ return this;
10839
+ }
10588
10840
  this.agentType = "sequential";
10589
10841
  this.config.subAgents = subAgents;
10842
+ if (this.config.outputKey) {
10843
+ this.logger.warn(
10844
+ "AgentBuilder: outputKey ignored for sequential agent aggregator; removed",
10845
+ {
10846
+ suggestion: "Assign outputKey on individual sub-agents if needed.",
10847
+ context: { previousValue: this.config.outputKey }
10848
+ }
10849
+ );
10850
+ this.config.outputKey = void 0;
10851
+ }
10852
+ if (this.config.outputSchema) {
10853
+ this.logger.warn(
10854
+ "AgentBuilder: outputSchema cannot be applied to sequential aggregator; removed",
10855
+ {
10856
+ suggestion: "Apply schemas to sub-agents individually."
10857
+ }
10858
+ );
10859
+ this.config.outputSchema = void 0;
10860
+ }
10590
10861
  return this;
10591
10862
  }
10592
10863
  /**
@@ -10595,9 +10866,37 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10595
10866
  * @returns This builder instance for chaining
10596
10867
  */
10597
10868
  asParallel(subAgents) {
10598
- this.warnIfLocked("asParallel");
10869
+ if (this.definitionLocked) {
10870
+ this.logger.warn(
10871
+ "AgentBuilder: asParallel() ignored; builder locked by withAgent()",
10872
+ {
10873
+ suggestion: "Call asParallel() before withAgent().",
10874
+ context: { agentName: this.config.name }
10875
+ }
10876
+ );
10877
+ return this;
10878
+ }
10599
10879
  this.agentType = "parallel";
10600
10880
  this.config.subAgents = subAgents;
10881
+ if (this.config.outputKey) {
10882
+ this.logger.warn(
10883
+ "AgentBuilder: outputKey ignored for parallel agent aggregator; removed",
10884
+ {
10885
+ suggestion: "Assign outputKey on individual sub-agents if needed.",
10886
+ context: { previousValue: this.config.outputKey }
10887
+ }
10888
+ );
10889
+ this.config.outputKey = void 0;
10890
+ }
10891
+ if (this.config.outputSchema) {
10892
+ this.logger.warn(
10893
+ "AgentBuilder: outputSchema cannot be applied to parallel aggregator; removed",
10894
+ {
10895
+ suggestion: "Apply schemas to sub-agents individually."
10896
+ }
10897
+ );
10898
+ this.config.outputSchema = void 0;
10899
+ }
10601
10900
  return this;
10602
10901
  }
10603
10902
  /**
@@ -10650,9 +10949,11 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10650
10949
  */
10651
10950
  withSession(session) {
10652
10951
  if (!this.sessionService) {
10653
- throw new Error(
10654
- "Session service must be configured before using withSession(). Call withSessionService() first, or use withQuickSession() for in-memory sessions."
10655
- );
10952
+ const msg = "Session service must be configured before using withSession(). Call withSessionService() first, or use withQuickSession() for in-memory sessions.";
10953
+ this.logger.error(msg, {
10954
+ suggestion: "Invoke withSessionService() prior to withSession()."
10955
+ });
10956
+ throw new Error(msg);
10656
10957
  }
10657
10958
  this.sessionOptions = {
10658
10959
  ...this.sessionOptions,
@@ -10723,7 +11024,12 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10723
11024
  const baseRunner = new Runner(runnerConfig);
10724
11025
  runner = this.createEnhancedRunner(baseRunner, session);
10725
11026
  }
10726
- return { agent, runner, session };
11027
+ return {
11028
+ agent,
11029
+ runner,
11030
+ session,
11031
+ sessionService: this.sessionService
11032
+ };
10727
11033
  }
10728
11034
  /**
10729
11035
  * Type-safe build method for agents with output schemas
@@ -10751,7 +11057,11 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10751
11057
  switch (this.agentType) {
10752
11058
  case "llm": {
10753
11059
  if (!this.config.model) {
10754
- throw new Error("Model is required for LLM agent");
11060
+ const msg = "Model is required for LLM agent";
11061
+ this.logger.error(msg, {
11062
+ suggestion: "Call withModel() before build()."
11063
+ });
11064
+ throw new Error(msg);
10755
11065
  }
10756
11066
  const model = this.config.model;
10757
11067
  return new LlmAgent({
@@ -10775,7 +11085,11 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10775
11085
  }
10776
11086
  case "sequential":
10777
11087
  if (!this.config.subAgents || !Array.isArray(this.config.subAgents) || this.config.subAgents.length === 0) {
10778
- throw new Error("Sub-agents required for sequential agent");
11088
+ const msg = "Sub-agents required for sequential agent";
11089
+ this.logger.error(msg, {
11090
+ suggestion: "Provide at least one sub-agent."
11091
+ });
11092
+ throw new Error(msg);
10779
11093
  }
10780
11094
  return new SequentialAgent({
10781
11095
  name: this.config.name,
@@ -10784,7 +11098,11 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10784
11098
  });
10785
11099
  case "parallel":
10786
11100
  if (!this.config.subAgents || !Array.isArray(this.config.subAgents) || this.config.subAgents.length === 0) {
10787
- throw new Error("Sub-agents required for parallel agent");
11101
+ const msg = "Sub-agents required for parallel agent";
11102
+ this.logger.error(msg, {
11103
+ suggestion: "Provide at least one sub-agent."
11104
+ });
11105
+ throw new Error(msg);
10788
11106
  }
10789
11107
  return new ParallelAgent({
10790
11108
  name: this.config.name,
@@ -10793,7 +11111,11 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10793
11111
  });
10794
11112
  case "loop":
10795
11113
  if (!this.config.subAgents || !Array.isArray(this.config.subAgents) || this.config.subAgents.length === 0) {
10796
- throw new Error("Sub-agents required for loop agent");
11114
+ const msg = "Sub-agents required for loop agent";
11115
+ this.logger.error(msg, {
11116
+ suggestion: "Provide at least one sub-agent."
11117
+ });
11118
+ throw new Error(msg);
10797
11119
  }
10798
11120
  return new LoopAgent({
10799
11121
  name: this.config.name,
@@ -10803,7 +11125,11 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10803
11125
  });
10804
11126
  case "langgraph":
10805
11127
  if (!this.config.nodes || !Array.isArray(this.config.nodes) || this.config.nodes.length === 0 || !this.config.rootNode || typeof this.config.rootNode !== "string") {
10806
- throw new Error("Nodes and root node required for LangGraph agent");
11128
+ const msg = "Nodes and root node required for LangGraph agent";
11129
+ this.logger.error(msg, {
11130
+ suggestion: "Provide nodes[] and a valid rootNode string."
11131
+ });
11132
+ throw new Error(msg);
10807
11133
  }
10808
11134
  return new LangGraphAgent({
10809
11135
  name: this.config.name,
@@ -10837,12 +11163,17 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10837
11163
  createEnhancedRunner(baseRunner, session) {
10838
11164
  const sessionOptions = this.sessionOptions;
10839
11165
  const outputSchema = this.config.outputSchema;
11166
+ const agentType = this.agentType;
11167
+ const isMulti = agentType === "parallel" || agentType === "sequential";
11168
+ const subAgentNames = _optionalChain([this, 'access', _287 => _287.config, 'access', _288 => _288.subAgents, 'optionalAccess', _289 => _289.map, 'call', _290 => _290((a) => a.name)]) || [];
10840
11169
  return {
10841
11170
  __outputSchema: outputSchema,
10842
11171
  async ask(message) {
10843
11172
  const newMessage = typeof message === "string" ? { parts: [{ text: message }] } : typeof message === "object" && "contents" in message ? { parts: message.contents[message.contents.length - 1].parts } : message;
10844
- let response = "";
10845
- if (!_optionalChain([sessionOptions, 'optionalAccess', _283 => _283.userId])) {
11173
+ let combinedResponse = "";
11174
+ const perAgentBuffers = {};
11175
+ const authors = /* @__PURE__ */ new Set();
11176
+ if (!_optionalChain([sessionOptions, 'optionalAccess', _291 => _291.userId])) {
10846
11177
  throw new Error("Session configuration is required");
10847
11178
  }
10848
11179
  for await (const event of baseRunner.runAsync({
@@ -10850,50 +11181,50 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10850
11181
  sessionId: session.id,
10851
11182
  newMessage
10852
11183
  })) {
10853
- if (_optionalChain([event, 'access', _284 => _284.content, 'optionalAccess', _285 => _285.parts]) && Array.isArray(event.content.parts)) {
11184
+ if (_optionalChain([event, 'access', _292 => _292.content, 'optionalAccess', _293 => _293.parts]) && Array.isArray(event.content.parts)) {
10854
11185
  const content = event.content.parts.map(
10855
11186
  (part) => (part && typeof part === "object" && "text" in part ? part.text : "") || ""
10856
11187
  ).join("");
10857
11188
  if (content) {
10858
- response += content;
11189
+ combinedResponse += content;
11190
+ const author = event.author || "";
11191
+ if (author && author !== "user") {
11192
+ authors.add(author);
11193
+ perAgentBuffers[author] = (perAgentBuffers[author] || "") + content;
11194
+ }
10859
11195
  }
10860
11196
  }
10861
11197
  }
11198
+ if (isMulti) {
11199
+ return subAgentNames.map((name) => ({
11200
+ agent: name,
11201
+ response: (perAgentBuffers[name] || "").trim()
11202
+ }));
11203
+ }
10862
11204
  if (outputSchema) {
10863
11205
  try {
10864
- const parsed = JSON.parse(response);
11206
+ const parsed = JSON.parse(combinedResponse);
10865
11207
  return outputSchema.parse(parsed);
10866
11208
  } catch (parseError) {
10867
11209
  try {
10868
- return outputSchema.parse(response);
11210
+ return outputSchema.parse(combinedResponse);
10869
11211
  } catch (validationError) {
10870
- return response.trim();
11212
+ throw new Error(
11213
+ `Failed to parse and validate LLM output against the schema.
11214
+ JSON parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}
11215
+ Zod validation error: ${validationError instanceof Error ? validationError.message : String(validationError)}
11216
+ Raw output: "${combinedResponse}"`
11217
+ );
10871
11218
  }
10872
11219
  }
10873
11220
  }
10874
- return response.trim();
11221
+ return combinedResponse.trim();
10875
11222
  },
10876
11223
  runAsync(params) {
10877
11224
  return baseRunner.runAsync(params);
10878
11225
  }
10879
11226
  };
10880
11227
  }
10881
- /**
10882
- * Warn (once per method) if the definition has been locked by withAgent().
10883
- */
10884
- warnIfLocked(method) {
10885
- if (!this.definitionLocked) return;
10886
- if (this.warnedMethods.has(method)) return;
10887
- this.warnedMethods.add(method);
10888
- if (process.env.NODE_ENV !== "production") {
10889
- const msg = `AgentBuilder: attempted to call ${method} after withAgent(); ignoring. (Wrap the agent first OR configure before withAgent).`;
10890
- if (this.logger && typeof this.logger.warn === "function") {
10891
- this.logger.warn(msg);
10892
- } else {
10893
- console.warn(msg);
10894
- }
10895
- }
10896
- }
10897
11228
  }, _class33);
10898
11229
 
10899
11230
  // src/memory/index.ts
@@ -10958,7 +11289,7 @@ var VertexAiSessionService = class extends BaseSessionService {
10958
11289
  path: `operations/${operationId}`,
10959
11290
  request_dict: {}
10960
11291
  });
10961
- if (_optionalChain([lroResponse, 'optionalAccess', _286 => _286.done])) {
11292
+ if (_optionalChain([lroResponse, 'optionalAccess', _294 => _294.done])) {
10962
11293
  break;
10963
11294
  }
10964
11295
  await new Promise((resolve) => setTimeout(resolve, 1e3));
@@ -11230,9 +11561,9 @@ var VertexAiSessionService = class extends BaseSessionService {
11230
11561
  var _kysely = require('kysely');
11231
11562
  var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11232
11563
 
11233
- __init60() {this.initialized = false}
11564
+ __init59() {this.initialized = false}
11234
11565
  constructor(config) {
11235
- super();_class34.prototype.__init60.call(this);;
11566
+ super();_class34.prototype.__init59.call(this);;
11236
11567
  this.db = config.db;
11237
11568
  if (!config.skipTableCreation) {
11238
11569
  this.initializeDatabase().catch((error) => {
@@ -11307,7 +11638,7 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11307
11638
  if (!jsonString) return defaultValue;
11308
11639
  try {
11309
11640
  return JSON.parse(jsonString);
11310
- } catch (e6) {
11641
+ } catch (e7) {
11311
11642
  return defaultValue;
11312
11643
  }
11313
11644
  }
@@ -11329,12 +11660,12 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11329
11660
  }
11330
11661
  async createSession(appName, userId, state, sessionId) {
11331
11662
  await this.ensureInitialized();
11332
- const id = _optionalChain([sessionId, 'optionalAccess', _287 => _287.trim, 'call', _288 => _288()]) || this.generateSessionId();
11663
+ const id = _optionalChain([sessionId, 'optionalAccess', _295 => _295.trim, 'call', _296 => _296()]) || this.generateSessionId();
11333
11664
  return await this.db.transaction().execute(async (trx) => {
11334
11665
  const appState = await trx.selectFrom("app_states").selectAll().where("app_name", "=", appName).executeTakeFirst();
11335
11666
  const userState = await trx.selectFrom("user_states").selectAll().where("app_name", "=", appName).where("user_id", "=", userId).executeTakeFirst();
11336
- let currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _289 => _289.state]), {});
11337
- let currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _290 => _290.state]), {});
11667
+ let currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _297 => _297.state]), {});
11668
+ let currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _298 => _298.state]), {});
11338
11669
  if (!appState) {
11339
11670
  await trx.insertInto("app_states").values({
11340
11671
  app_name: appName,
@@ -11393,21 +11724,21 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11393
11724
  return void 0;
11394
11725
  }
11395
11726
  let eventQuery = trx.selectFrom("events").selectAll().where("session_id", "=", sessionId).orderBy("timestamp", "desc");
11396
- if (_optionalChain([config, 'optionalAccess', _291 => _291.afterTimestamp])) {
11727
+ if (_optionalChain([config, 'optionalAccess', _299 => _299.afterTimestamp])) {
11397
11728
  eventQuery = eventQuery.where(
11398
11729
  "timestamp",
11399
11730
  ">=",
11400
11731
  new Date(config.afterTimestamp * 1e3)
11401
11732
  );
11402
11733
  }
11403
- if (_optionalChain([config, 'optionalAccess', _292 => _292.numRecentEvents])) {
11734
+ if (_optionalChain([config, 'optionalAccess', _300 => _300.numRecentEvents])) {
11404
11735
  eventQuery = eventQuery.limit(config.numRecentEvents);
11405
11736
  }
11406
11737
  const storageEvents = await eventQuery.execute();
11407
11738
  const appState = await trx.selectFrom("app_states").selectAll().where("app_name", "=", appName).executeTakeFirst();
11408
11739
  const userState = await trx.selectFrom("user_states").selectAll().where("app_name", "=", appName).where("user_id", "=", userId).executeTakeFirst();
11409
- const currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _293 => _293.state]), {});
11410
- const currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _294 => _294.state]), {});
11740
+ const currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _301 => _301.state]), {});
11741
+ const currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _302 => _302.state]), {});
11411
11742
  const sessionState = this.parseJsonSafely(storageSession.state, {});
11412
11743
  const mergedState = this.mergeState(
11413
11744
  currentAppState,
@@ -11465,13 +11796,13 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11465
11796
  }
11466
11797
  const appState = await trx.selectFrom("app_states").selectAll().where("app_name", "=", session.appName).executeTakeFirst();
11467
11798
  const userState = await trx.selectFrom("user_states").selectAll().where("app_name", "=", session.appName).where("user_id", "=", session.userId).executeTakeFirst();
11468
- let currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _295 => _295.state]), {});
11469
- let currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _296 => _296.state]), {});
11799
+ let currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _303 => _303.state]), {});
11800
+ let currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _304 => _304.state]), {});
11470
11801
  let sessionState = this.parseJsonSafely(storageSession.state, {});
11471
11802
  let appStateDelta = {};
11472
11803
  let userStateDelta = {};
11473
11804
  let sessionStateDelta = {};
11474
- if (_optionalChain([event, 'access', _297 => _297.actions, 'optionalAccess', _298 => _298.stateDelta])) {
11805
+ if (_optionalChain([event, 'access', _305 => _305.actions, 'optionalAccess', _306 => _306.stateDelta])) {
11475
11806
  const deltas = this.extractStateDelta(event.actions.stateDelta);
11476
11807
  appStateDelta = deltas.appStateDelta;
11477
11808
  userStateDelta = deltas.userStateDelta;
@@ -11617,7 +11948,7 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11617
11948
  * Overrides the base class method to work with plain object state.
11618
11949
  */
11619
11950
  updateSessionState(session, event) {
11620
- if (!_optionalChain([event, 'access', _299 => _299.actions, 'optionalAccess', _300 => _300.stateDelta])) {
11951
+ if (!_optionalChain([event, 'access', _307 => _307.actions, 'optionalAccess', _308 => _308.stateDelta])) {
11621
11952
  return;
11622
11953
  }
11623
11954
  for (const [key, value] of Object.entries(event.actions.stateDelta)) {
@@ -11787,7 +12118,7 @@ var GcsArtifactService = class {
11787
12118
  };
11788
12119
  return part;
11789
12120
  } catch (error) {
11790
- if (_optionalChain([error, 'optionalAccess', _301 => _301.code]) === 404) {
12121
+ if (_optionalChain([error, 'optionalAccess', _309 => _309.code]) === 404) {
11791
12122
  return null;
11792
12123
  }
11793
12124
  throw error;
@@ -12038,13 +12369,13 @@ var VertexAiEvalFacade = class _VertexAiEvalFacade {
12038
12369
  };
12039
12370
  }
12040
12371
  _getText(content) {
12041
- if (_optionalChain([content, 'optionalAccess', _302 => _302.parts])) {
12372
+ if (_optionalChain([content, 'optionalAccess', _310 => _310.parts])) {
12042
12373
  return content.parts.map((p) => p.text || "").filter((text) => text.length > 0).join("\n");
12043
12374
  }
12044
12375
  return "";
12045
12376
  }
12046
12377
  _getScore(evalResult) {
12047
- if (_optionalChain([evalResult, 'optionalAccess', _303 => _303.summaryMetrics, 'optionalAccess', _304 => _304[0], 'optionalAccess', _305 => _305.meanScore]) !== void 0 && typeof evalResult.summaryMetrics[0].meanScore === "number" && !Number.isNaN(evalResult.summaryMetrics[0].meanScore)) {
12378
+ if (_optionalChain([evalResult, 'optionalAccess', _311 => _311.summaryMetrics, 'optionalAccess', _312 => _312[0], 'optionalAccess', _313 => _313.meanScore]) !== void 0 && typeof evalResult.summaryMetrics[0].meanScore === "number" && !Number.isNaN(evalResult.summaryMetrics[0].meanScore)) {
12048
12379
  return evalResult.summaryMetrics[0].meanScore;
12049
12380
  }
12050
12381
  return void 0;
@@ -12194,7 +12525,7 @@ var ResponseEvaluator = class extends Evaluator {
12194
12525
  return fmeasure;
12195
12526
  }
12196
12527
  extractText(content) {
12197
- if (_optionalChain([content, 'optionalAccess', _306 => _306.parts])) {
12528
+ if (_optionalChain([content, 'optionalAccess', _314 => _314.parts])) {
12198
12529
  return content.parts.map((p) => p.text || "").filter((text) => text.length > 0).join(" ");
12199
12530
  }
12200
12531
  return "";
@@ -12227,7 +12558,7 @@ var TrajectoryEvaluator = class extends Evaluator {
12227
12558
  for (let i = 0; i < actualInvocations.length; i++) {
12228
12559
  const actual = actualInvocations[i];
12229
12560
  const expected = expectedInvocations[i];
12230
- if (!_optionalChain([actual, 'access', _307 => _307.intermediateData, 'optionalAccess', _308 => _308.toolUses]) || !_optionalChain([expected, 'access', _309 => _309.intermediateData, 'optionalAccess', _310 => _310.toolUses])) {
12561
+ if (!_optionalChain([actual, 'access', _315 => _315.intermediateData, 'optionalAccess', _316 => _316.toolUses]) || !_optionalChain([expected, 'access', _317 => _317.intermediateData, 'optionalAccess', _318 => _318.toolUses])) {
12231
12562
  perInvocationResults.push({
12232
12563
  actualInvocation: actual,
12233
12564
  expectedInvocation: expected,
@@ -12315,7 +12646,7 @@ var SafetyEvaluatorV1 = class extends Evaluator {
12315
12646
 
12316
12647
  // src/evaluation/llm-as-judge-utils.ts
12317
12648
  function getTextFromContent(content) {
12318
- if (_optionalChain([content, 'optionalAccess', _311 => _311.parts])) {
12649
+ if (_optionalChain([content, 'optionalAccess', _319 => _319.parts])) {
12319
12650
  return content.parts.map((part) => part.text).filter(Boolean).join("\n");
12320
12651
  }
12321
12652
  return "";
@@ -12327,9 +12658,9 @@ function getEvalStatus(score, threshold) {
12327
12658
  // src/evaluation/llm-as-judge.ts
12328
12659
  var LlmAsJudge = class {
12329
12660
  async sampleJudge(prompt, numSamples, critiqueParser, judgeModelOptions) {
12330
- const modelName = _optionalChain([judgeModelOptions, 'optionalAccess', _312 => _312.judgeModel]) || "gemini-2.5-flash";
12661
+ const modelName = _optionalChain([judgeModelOptions, 'optionalAccess', _320 => _320.judgeModel]) || "gemini-2.5-flash";
12331
12662
  const model = LLMRegistry.getModelOrCreate(modelName);
12332
- const config = _optionalChain([judgeModelOptions, 'optionalAccess', _313 => _313.judgeModelConfig]) || {};
12663
+ const config = _optionalChain([judgeModelOptions, 'optionalAccess', _321 => _321.judgeModelConfig]) || {};
12333
12664
  const samples = [];
12334
12665
  for (let i = 0; i < numSamples; i++) {
12335
12666
  try {
@@ -12395,7 +12726,7 @@ function parseCritique(response) {
12395
12726
  const labelMatchIsResponseValid = response.match(
12396
12727
  /"is_the_agent_response_valid":\s*\[*[\n\s]*"*([^"^\]^\s]*)"*[\n\s]*\]*\s*[,\n\}]/
12397
12728
  );
12398
- if (_optionalChain([labelMatchIsResponseValid, 'optionalAccess', _314 => _314[1]])) {
12729
+ if (_optionalChain([labelMatchIsResponseValid, 'optionalAccess', _322 => _322[1]])) {
12399
12730
  const label = labelMatchIsResponseValid[1].toLowerCase();
12400
12731
  return label === "valid" ? "valid" /* VALID */ : "invalid" /* INVALID */;
12401
12732
  }
@@ -12440,7 +12771,7 @@ var FinalResponseMatchV2Evaluator = class extends Evaluator {
12440
12771
  "{prompt}",
12441
12772
  prompt
12442
12773
  ).replace("{response}", response).replace("{golden_response}", goldenResponse);
12443
- const numSamples = _nullishCoalesce(_optionalChain([this, 'access', _315 => _315.metric, 'access', _316 => _316.judgeModelOptions, 'optionalAccess', _317 => _317.numSamples]), () => ( DEFAULT_NUM_SAMPLES));
12774
+ const numSamples = _nullishCoalesce(_optionalChain([this, 'access', _323 => _323.metric, 'access', _324 => _324.judgeModelOptions, 'optionalAccess', _325 => _325.numSamples]), () => ( DEFAULT_NUM_SAMPLES));
12444
12775
  const labels = await this.llmAsJudge.sampleJudge(
12445
12776
  formattedPrompt,
12446
12777
  numSamples,
@@ -12467,8 +12798,8 @@ var FinalResponseMatchV2Evaluator = class extends Evaluator {
12467
12798
  };
12468
12799
 
12469
12800
  // src/evaluation/metric-evaluator-registry.ts
12470
- var MetricEvaluatorRegistry = (_class35 = class {constructor() { _class35.prototype.__init61.call(this); }
12471
- __init61() {this.registry = /* @__PURE__ */ new Map()}
12801
+ var MetricEvaluatorRegistry = (_class35 = class {constructor() { _class35.prototype.__init60.call(this); }
12802
+ __init60() {this.registry = /* @__PURE__ */ new Map()}
12472
12803
  getEvaluator(evalMetric) {
12473
12804
  const entry = this.registry.get(evalMetric.metricName);
12474
12805
  if (!entry) {
@@ -12480,7 +12811,7 @@ var MetricEvaluatorRegistry = (_class35 = class {constructor() { _class35.protot
12480
12811
  const metricName = metricInfo.metricName;
12481
12812
  if (this.registry.has(metricName)) {
12482
12813
  console.info(
12483
- `Updating Evaluator class for ${metricName} from ${_optionalChain([this, 'access', _318 => _318.registry, 'access', _319 => _319.get, 'call', _320 => _320(metricName), 'optionalAccess', _321 => _321.evaluator, 'access', _322 => _322.name])} to ${evaluator.name}`
12814
+ `Updating Evaluator class for ${metricName} from ${_optionalChain([this, 'access', _326 => _326.registry, 'access', _327 => _327.get, 'call', _328 => _328(metricName), 'optionalAccess', _329 => _329.evaluator, 'access', _330 => _330.name])} to ${evaluator.name}`
12484
12815
  );
12485
12816
  }
12486
12817
  this.registry.set(metricName, {
@@ -12594,10 +12925,10 @@ var LocalEvalService = class extends BaseEvalService {
12594
12925
  for (const evalMetric of evaluateConfig.evalMetrics) {
12595
12926
  const evaluator = DEFAULT_METRIC_EVALUATOR_REGISTRY.getEvaluator(evalMetric);
12596
12927
  const actual = results.filter(
12597
- (r) => !_optionalChain([r, 'access', _323 => _323.invocationId, 'optionalAccess', _324 => _324.includes, 'call', _325 => _325("expected")])
12928
+ (r) => !_optionalChain([r, 'access', _331 => _331.invocationId, 'optionalAccess', _332 => _332.includes, 'call', _333 => _333("expected")])
12598
12929
  );
12599
12930
  const expected = results.filter(
12600
- (r) => _optionalChain([r, 'access', _326 => _326.invocationId, 'optionalAccess', _327 => _327.includes, 'call', _328 => _328("expected")])
12931
+ (r) => _optionalChain([r, 'access', _334 => _334.invocationId, 'optionalAccess', _335 => _335.includes, 'call', _336 => _336("expected")])
12601
12932
  );
12602
12933
  const result = await evaluator.evaluateInvocations(actual, expected);
12603
12934
  evalResult.evalCaseResults.push({
@@ -12989,13 +13320,13 @@ ${failures.join(
12989
13320
  console.log("\n\n");
12990
13321
  }
12991
13322
  static _convertContentToText(content) {
12992
- if (_optionalChain([content, 'optionalAccess', _329 => _329.parts])) {
13323
+ if (_optionalChain([content, 'optionalAccess', _337 => _337.parts])) {
12993
13324
  return content.parts.map((p) => p.text || "").filter((text) => text.length > 0).join("\n");
12994
13325
  }
12995
13326
  return "";
12996
13327
  }
12997
13328
  static _convertToolCallsToText(intermediateData) {
12998
- if (_optionalChain([intermediateData, 'optionalAccess', _330 => _330.toolUses])) {
13329
+ if (_optionalChain([intermediateData, 'optionalAccess', _338 => _338.toolUses])) {
12999
13330
  return intermediateData.toolUses.map((t) => JSON.stringify(t)).join("\n");
13000
13331
  }
13001
13332
  return "";
@@ -13050,7 +13381,7 @@ ${failures.join(
13050
13381
  for (const [metricName, evalMetricResultsWithInvocations] of Object.entries(
13051
13382
  evalMetricResults
13052
13383
  )) {
13053
- const threshold = _optionalChain([evalMetricResultsWithInvocations, 'access', _331 => _331[0], 'optionalAccess', _332 => _332.evalMetricResult, 'access', _333 => _333.threshold]) || 0;
13384
+ const threshold = _optionalChain([evalMetricResultsWithInvocations, 'access', _339 => _339[0], 'optionalAccess', _340 => _340.evalMetricResult, 'access', _341 => _341.threshold]) || 0;
13054
13385
  const scores = evalMetricResultsWithInvocations.map((m) => m.evalMetricResult.score).filter((s) => s !== void 0);
13055
13386
  let overallScore;
13056
13387
  let overallEvalStatus;
@@ -13139,7 +13470,7 @@ var RougeEvaluator = class extends Evaluator {
13139
13470
  }
13140
13471
  };
13141
13472
  function getTextFromContent2(content) {
13142
- if (_optionalChain([content, 'optionalAccess', _334 => _334.parts])) {
13473
+ if (_optionalChain([content, 'optionalAccess', _342 => _342.parts])) {
13143
13474
  return content.parts.map((part) => part.text).filter(Boolean).join("\n");
13144
13475
  }
13145
13476
  return "";