@iqai/adk 0.2.4 → 0.2.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @iqai/adk
2
2
 
3
+ ## 0.2.5
4
+
5
+ ### Patch Changes
6
+
7
+ - e1dc750: - Implements output schema to work with tools and agent transfers
8
+
3
9
  ## 0.2.4
4
10
 
5
11
  ### Patch Changes
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;
@@ -7111,6 +7111,7 @@ var AuthLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7111
7111
  var requestProcessor = new AuthLlmRequestProcessor();
7112
7112
 
7113
7113
  // src/flows/llm-flows/basic.ts
7114
+ init_logger();
7114
7115
  var BasicLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7115
7116
  async *runAsync(invocationContext, llmRequest) {
7116
7117
  const agent = invocationContext.agent;
@@ -7126,7 +7127,21 @@ var BasicLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7126
7127
  llmRequest.config = {};
7127
7128
  }
7128
7129
  if (agent.outputSchema) {
7129
- llmRequest.setOutputSchema(agent.outputSchema);
7130
+ const hasTools = await _asyncOptionalChain([(await _optionalChain([agent, 'access', _211 => _211.canonicalTools, 'optionalCall', _212 => _212(invocationContext)])), 'optionalAccess', async _213 => _213.length]) > 0;
7131
+ const hasTransfers = !!("subAgents" in agent && agent.subAgents && agent.subAgents.length > 0 && !(agent.disallowTransferToParent && agent.disallowTransferToPeers));
7132
+ if (!hasTools && !hasTransfers) {
7133
+ llmRequest.setOutputSchema(agent.outputSchema);
7134
+ } else {
7135
+ (() => {
7136
+ try {
7137
+ const logger = new Logger({ name: "BasicLlmRequestProcessor" });
7138
+ logger.debug(
7139
+ `Skipping request-level output schema for agent ${agent.name} because tools/transfers are present. Schema will be validated during response processing.`
7140
+ );
7141
+ } catch (e) {
7142
+ }
7143
+ })();
7144
+ }
7130
7145
  }
7131
7146
  const runConfig = invocationContext.runConfig;
7132
7147
  if (!llmRequest.liveConnectConfig) {
@@ -7204,7 +7219,7 @@ var BuiltInCodeExecutor = class extends BaseCodeExecutor {
7204
7219
  * Pre-process the LLM request for Gemini 2.0+ models to use the code execution tool
7205
7220
  */
7206
7221
  processLlmRequest(llmRequest) {
7207
- if (!_optionalChain([llmRequest, 'access', _211 => _211.model, 'optionalAccess', _212 => _212.startsWith, 'call', _213 => _213("gemini-2")])) {
7222
+ if (!_optionalChain([llmRequest, 'access', _214 => _214.model, 'optionalAccess', _215 => _215.startsWith, 'call', _216 => _216("gemini-2")])) {
7208
7223
  throw new Error(
7209
7224
  `Gemini code execution tool is not supported for model ${llmRequest.model}`
7210
7225
  );
@@ -7249,7 +7264,7 @@ var CodeExecutionUtils = class _CodeExecutionUtils {
7249
7264
  * Extracts the first code block from the content and truncates everything after it
7250
7265
  */
7251
7266
  static extractCodeAndTruncateContent(content, codeBlockDelimiters) {
7252
- if (!_optionalChain([content, 'optionalAccess', _214 => _214.parts, 'optionalAccess', _215 => _215.length])) {
7267
+ if (!_optionalChain([content, 'optionalAccess', _217 => _217.parts, 'optionalAccess', _218 => _218.length])) {
7253
7268
  return null;
7254
7269
  }
7255
7270
  for (let idx = 0; idx < content.parts.length; idx++) {
@@ -7335,7 +7350,7 @@ ${fileNames}`);
7335
7350
  * Converts the code execution parts to text parts in a Content
7336
7351
  */
7337
7352
  static convertCodeExecutionParts(content, codeBlockDelimiter, executionResultDelimiters) {
7338
- if (!_optionalChain([content, 'access', _216 => _216.parts, 'optionalAccess', _217 => _217.length])) {
7353
+ if (!_optionalChain([content, 'access', _219 => _219.parts, 'optionalAccess', _220 => _220.length])) {
7339
7354
  return;
7340
7355
  }
7341
7356
  const lastPart = content.parts[content.parts.length - 1];
@@ -7728,7 +7743,7 @@ async function* runPostProcessor(invocationContext, llmResponse) {
7728
7743
  function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
7729
7744
  const allInputFiles = codeExecutorContext.getInputFiles();
7730
7745
  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++) {
7746
+ for (let i = 0; i < (_optionalChain([llmRequest, 'access', _221 => _221.contents, 'optionalAccess', _222 => _222.length]) || 0); i++) {
7732
7747
  const content = llmRequest.contents[i];
7733
7748
  if (content.role !== "user" || !content.parts) {
7734
7749
  continue;
@@ -7760,7 +7775,7 @@ Available file: \`${fileName}\`
7760
7775
  }
7761
7776
  function getOrSetExecutionId(invocationContext, codeExecutorContext) {
7762
7777
  const agent = invocationContext.agent;
7763
- if (!hasCodeExecutor(agent) || !_optionalChain([agent, 'access', _220 => _220.codeExecutor, 'optionalAccess', _221 => _221.stateful])) {
7778
+ if (!hasCodeExecutor(agent) || !_optionalChain([agent, 'access', _223 => _223.codeExecutor, 'optionalAccess', _224 => _224.stateful])) {
7764
7779
  return void 0;
7765
7780
  }
7766
7781
  let executionId = codeExecutorContext.getExecutionId();
@@ -7991,7 +8006,7 @@ function rearrangeEventsForLatestFunctionResponse(events) {
7991
8006
  continue;
7992
8007
  }
7993
8008
  const functionResponses2 = event.getFunctionResponses();
7994
- if (_optionalChain([functionResponses2, 'optionalAccess', _222 => _222.some, 'call', _223 => _223((fr) => fr.id && functionResponsesIds.has(fr.id))])) {
8009
+ if (_optionalChain([functionResponses2, 'optionalAccess', _225 => _225.some, 'call', _226 => _226((fr) => fr.id && functionResponsesIds.has(fr.id))])) {
7995
8010
  functionResponseEvents.push(event);
7996
8011
  }
7997
8012
  }
@@ -8090,7 +8105,7 @@ function mergeFunctionResponseEvents(functionResponseEvents) {
8090
8105
  const partIndicesInMergedEvent = {};
8091
8106
  for (let idx = 0; idx < partsInMergedEvent.length; idx++) {
8092
8107
  const part = partsInMergedEvent[idx];
8093
- if (_optionalChain([part, 'access', _224 => _224.functionResponse, 'optionalAccess', _225 => _225.id])) {
8108
+ if (_optionalChain([part, 'access', _227 => _227.functionResponse, 'optionalAccess', _228 => _228.id])) {
8094
8109
  partIndicesInMergedEvent[part.functionResponse.id] = idx;
8095
8110
  }
8096
8111
  }
@@ -8099,7 +8114,7 @@ function mergeFunctionResponseEvents(functionResponseEvents) {
8099
8114
  throw new Error("There should be at least one function_response part.");
8100
8115
  }
8101
8116
  for (const part of event.content.parts) {
8102
- if (_optionalChain([part, 'access', _226 => _226.functionResponse, 'optionalAccess', _227 => _227.id])) {
8117
+ if (_optionalChain([part, 'access', _229 => _229.functionResponse, 'optionalAccess', _230 => _230.id])) {
8103
8118
  const functionCallId = part.functionResponse.id;
8104
8119
  if (functionCallId in partIndicesInMergedEvent) {
8105
8120
  partsInMergedEvent[partIndicesInMergedEvent[functionCallId]] = part;
@@ -8278,10 +8293,11 @@ var InstructionsLlmRequestProcessor = class extends BaseLlmRequestProcessor {
8278
8293
  });
8279
8294
  const { $schema, ...json } = raw || {};
8280
8295
  llmRequest.appendInstructions([
8281
- "You must respond with application/json that validates against this JSON Schema:",
8282
- "```json",
8283
- JSON.stringify(json, null, 2),
8284
- "```"
8296
+ "You must respond with application/json that validates against this JSON Schema (do NOT wrap the output in markdown or code fences):",
8297
+ JSON.stringify(json, null, 2)
8298
+ ]);
8299
+ llmRequest.appendInstructions([
8300
+ '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.'
8285
8301
  ]);
8286
8302
  } catch (e5) {
8287
8303
  }
@@ -8368,7 +8384,7 @@ var PlanReActPlanner = class extends BasePlanner {
8368
8384
  let firstFcPartIndex = -1;
8369
8385
  for (let i = 0; i < responseParts.length; i++) {
8370
8386
  if (responseParts[i].functionCall) {
8371
- if (!_optionalChain([responseParts, 'access', _228 => _228[i], 'access', _229 => _229.functionCall, 'optionalAccess', _230 => _230.name])) {
8387
+ if (!_optionalChain([responseParts, 'access', _231 => _231[i], 'access', _232 => _232.functionCall, 'optionalAccess', _233 => _233.name])) {
8372
8388
  continue;
8373
8389
  }
8374
8390
  preservedParts.push(responseParts[i]);
@@ -8407,7 +8423,7 @@ var PlanReActPlanner = class extends BasePlanner {
8407
8423
  * Handles non-function-call parts of the response
8408
8424
  */
8409
8425
  _handleNonFunctionCallParts(responsePart, preservedParts) {
8410
- if (_optionalChain([responsePart, 'access', _231 => _231.text, 'optionalAccess', _232 => _232.includes, 'call', _233 => _233(FINAL_ANSWER_TAG)])) {
8426
+ if (_optionalChain([responsePart, 'access', _234 => _234.text, 'optionalAccess', _235 => _235.includes, 'call', _236 => _236(FINAL_ANSWER_TAG)])) {
8411
8427
  const [reasoningText, finalAnswerText] = this._splitByLastPattern(
8412
8428
  responsePart.text,
8413
8429
  FINAL_ANSWER_TAG
@@ -8578,6 +8594,7 @@ var requestProcessor7 = new NlPlanningRequestProcessor();
8578
8594
  var responseProcessor2 = new NlPlanningResponseProcessor();
8579
8595
 
8580
8596
  // src/flows/llm-flows/output-schema.ts
8597
+ var _jsonrepair = require('jsonrepair');
8581
8598
  init_logger();
8582
8599
  var OutputSchemaResponseProcessor = (_class26 = class extends BaseLlmResponseProcessor {constructor(...args2) { super(...args2); _class26.prototype.__init46.call(this); }
8583
8600
  __init46() {this.logger = new Logger({ name: "OutputSchemaResponseProcessor" })}
@@ -8599,7 +8616,8 @@ var OutputSchemaResponseProcessor = (_class26 = class extends BaseLlmResponsePro
8599
8616
  return;
8600
8617
  }
8601
8618
  try {
8602
- const parsed = JSON.parse(textContent);
8619
+ const candidate = this.stripCodeFences(textContent);
8620
+ const parsed = this.tryParseJson(candidate, agent.name);
8603
8621
  const validated = agent.outputSchema.parse(parsed);
8604
8622
  textContent = JSON.stringify(validated, null, 2);
8605
8623
  llmResponse.content.parts = llmResponse.content.parts.map((part) => {
@@ -8647,6 +8665,38 @@ var OutputSchemaResponseProcessor = (_class26 = class extends BaseLlmResponsePro
8647
8665
  yield errorEvent;
8648
8666
  }
8649
8667
  }
8668
+ // Strip common code fences and surrounding explanatory text from LLM output.
8669
+ stripCodeFences(raw) {
8670
+ const fencePattern = /```(?:json)?\s*([\s\S]*?)```/i;
8671
+ const fenceMatch = raw.match(fencePattern);
8672
+ if (_optionalChain([fenceMatch, 'optionalAccess', _237 => _237[1]])) {
8673
+ return fenceMatch[1].trim();
8674
+ }
8675
+ const lines = raw.split(/\r?\n/).map((l) => l.trim());
8676
+ const startIdx = lines.findIndex(
8677
+ (l) => l.startsWith("{") || l.startsWith("[")
8678
+ );
8679
+ if (startIdx >= 0) {
8680
+ return lines.slice(startIdx).join("\n").trim();
8681
+ }
8682
+ return raw.trim();
8683
+ }
8684
+ // Try parsing JSON; if parse fails, attempt to repair using jsonrepair and parse again.
8685
+ tryParseJson(candidate, agentName) {
8686
+ try {
8687
+ return JSON.parse(candidate);
8688
+ } catch (err) {
8689
+ this.logger.debug("Initial JSON.parse failed, attempting jsonrepair", {
8690
+ agent: agentName
8691
+ });
8692
+ try {
8693
+ const repaired = _jsonrepair.jsonrepair.call(void 0, candidate);
8694
+ return JSON.parse(repaired);
8695
+ } catch (repairErr) {
8696
+ throw err;
8697
+ }
8698
+ }
8699
+ }
8650
8700
  }, _class26);
8651
8701
  var responseProcessor3 = new OutputSchemaResponseProcessor();
8652
8702
 
@@ -8656,7 +8706,7 @@ var SharedMemoryRequestProcessor = class extends BaseLlmRequestProcessor {
8656
8706
  const memoryService = invocationContext.memoryService;
8657
8707
  if (!memoryService) return;
8658
8708
  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])
8709
+ (e) => e.author === "user" && _optionalChain([e, 'access', _238 => _238.content, 'optionalAccess', _239 => _239.parts, 'optionalAccess', _240 => _240.length])
8660
8710
  );
8661
8711
  if (!lastUserEvent) return;
8662
8712
  const query = (_nullishCoalesce(lastUserEvent.content.parts, () => ( []))).map((p) => p.text || "").join(" ");
@@ -8667,7 +8717,7 @@ var SharedMemoryRequestProcessor = class extends BaseLlmRequestProcessor {
8667
8717
  });
8668
8718
  const sessionTexts = new Set(
8669
8719
  (llmRequest.contents || []).flatMap(
8670
- (c) => _optionalChain([c, 'access', _237 => _237.parts, 'optionalAccess', _238 => _238.map, 'call', _239 => _239((p) => p.text)]) || []
8720
+ (c) => _optionalChain([c, 'access', _241 => _241.parts, 'optionalAccess', _242 => _242.map, 'call', _243 => _243((p) => p.text)]) || []
8671
8721
  )
8672
8722
  );
8673
8723
  for (const memory of results.memories) {
@@ -9069,19 +9119,17 @@ var LlmAgent = (_class27 = class _LlmAgent extends BaseAgent {
9069
9119
  }
9070
9120
  if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {
9071
9121
  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`
9122
+ `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
9123
  );
9074
- this.disallowTransferToParent = true;
9075
- this.disallowTransferToPeers = true;
9076
9124
  }
9077
9125
  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.`
9126
+ this.logger.warn(
9127
+ `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
9128
  );
9081
9129
  }
9082
9130
  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`
9131
+ this.logger.warn(
9132
+ `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
9133
  );
9086
9134
  }
9087
9135
  }
@@ -9090,7 +9138,7 @@ var LlmAgent = (_class27 = class _LlmAgent extends BaseAgent {
9090
9138
  * This matches the Python implementation's _llm_flow property
9091
9139
  */
9092
9140
  get llmFlow() {
9093
- if (this.disallowTransferToParent && this.disallowTransferToPeers && !_optionalChain([this, 'access', _240 => _240.subAgents, 'optionalAccess', _241 => _241.length])) {
9141
+ if (this.disallowTransferToParent && this.disallowTransferToPeers && !_optionalChain([this, 'access', _244 => _244.subAgents, 'optionalAccess', _245 => _245.length])) {
9094
9142
  return new SingleFlow();
9095
9143
  }
9096
9144
  return new AutoFlow();
@@ -9106,7 +9154,7 @@ var LlmAgent = (_class27 = class _LlmAgent extends BaseAgent {
9106
9154
  );
9107
9155
  return;
9108
9156
  }
9109
- if (this.outputKey && event.isFinalResponse() && _optionalChain([event, 'access', _242 => _242.content, 'optionalAccess', _243 => _243.parts])) {
9157
+ if (this.outputKey && event.isFinalResponse() && _optionalChain([event, 'access', _246 => _246.content, 'optionalAccess', _247 => _247.parts])) {
9110
9158
  let result = event.content.parts.map((part) => part.text || "").join("");
9111
9159
  if (this.outputSchema) {
9112
9160
  if (!result.trim()) {
@@ -9334,7 +9382,7 @@ var LoopAgent = class extends BaseAgent {
9334
9382
  for (const subAgent of this.subAgents) {
9335
9383
  for await (const event of subAgent.runAsync(ctx)) {
9336
9384
  yield event;
9337
- if (_optionalChain([event, 'access', _244 => _244.actions, 'optionalAccess', _245 => _245.escalate])) {
9385
+ if (_optionalChain([event, 'access', _248 => _248.actions, 'optionalAccess', _249 => _249.escalate])) {
9338
9386
  return;
9339
9387
  }
9340
9388
  }
@@ -9646,17 +9694,17 @@ var RunConfig = class {
9646
9694
  */
9647
9695
 
9648
9696
  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));
9697
+ this.speechConfig = _optionalChain([config, 'optionalAccess', _250 => _250.speechConfig]);
9698
+ this.responseModalities = _optionalChain([config, 'optionalAccess', _251 => _251.responseModalities]);
9699
+ this.saveInputBlobsAsArtifacts = _optionalChain([config, 'optionalAccess', _252 => _252.saveInputBlobsAsArtifacts]) || false;
9700
+ this.supportCFC = _optionalChain([config, 'optionalAccess', _253 => _253.supportCFC]) || false;
9701
+ this.streamingMode = _optionalChain([config, 'optionalAccess', _254 => _254.streamingMode]) || "NONE" /* NONE */;
9702
+ this.outputAudioTranscription = _optionalChain([config, 'optionalAccess', _255 => _255.outputAudioTranscription]);
9703
+ this.inputAudioTranscription = _optionalChain([config, 'optionalAccess', _256 => _256.inputAudioTranscription]);
9704
+ this.realtimeInputConfig = _optionalChain([config, 'optionalAccess', _257 => _257.realtimeInputConfig]);
9705
+ this.enableAffectiveDialog = _optionalChain([config, 'optionalAccess', _258 => _258.enableAffectiveDialog]);
9706
+ this.proactivity = _optionalChain([config, 'optionalAccess', _259 => _259.proactivity]);
9707
+ this.maxLlmCalls = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _260 => _260.maxLlmCalls]), () => ( 500));
9660
9708
  this.validateMaxLlmCalls();
9661
9709
  }
9662
9710
  /**
@@ -9800,7 +9848,7 @@ var InMemoryMemoryService = (_class30 = class {
9800
9848
  }
9801
9849
  const userSessions = this._sessionEvents.get(userKey);
9802
9850
  const filteredEvents = session.events.filter(
9803
- (event) => _optionalChain([event, 'access', _257 => _257.content, 'optionalAccess', _258 => _258.parts])
9851
+ (event) => _optionalChain([event, 'access', _261 => _261.content, 'optionalAccess', _262 => _262.parts])
9804
9852
  );
9805
9853
  userSessions.set(session.id, filteredEvents);
9806
9854
  }
@@ -9939,7 +9987,7 @@ var InMemorySessionService = (_class31 = class extends BaseSessionService {const
9939
9987
  return this.createSessionImpl(appName, userId, state, sessionId);
9940
9988
  }
9941
9989
  createSessionImpl(appName, userId, state, sessionId) {
9942
- const finalSessionId = _optionalChain([sessionId, 'optionalAccess', _259 => _259.trim, 'call', _260 => _260()]) || _crypto.randomUUID.call(void 0, );
9990
+ const finalSessionId = _optionalChain([sessionId, 'optionalAccess', _263 => _263.trim, 'call', _264 => _264()]) || _crypto.randomUUID.call(void 0, );
9943
9991
  const session = {
9944
9992
  appName,
9945
9993
  userId,
@@ -10096,7 +10144,7 @@ var InMemorySessionService = (_class31 = class extends BaseSessionService {const
10096
10144
  warning(`sessionId ${sessionId} not in sessions[appName][userId]`);
10097
10145
  return event;
10098
10146
  }
10099
- if (_optionalChain([event, 'access', _261 => _261.actions, 'optionalAccess', _262 => _262.stateDelta])) {
10147
+ if (_optionalChain([event, 'access', _265 => _265.actions, 'optionalAccess', _266 => _266.stateDelta])) {
10100
10148
  for (const key in event.actions.stateDelta) {
10101
10149
  const value = event.actions.stateDelta[key];
10102
10150
  if (key.startsWith(State.APP_PREFIX)) {
@@ -10130,14 +10178,14 @@ function _findFunctionCallEventIfLastEventIsFunctionResponse(session) {
10130
10178
  return null;
10131
10179
  }
10132
10180
  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(
10181
+ if (_optionalChain([lastEvent, 'access', _267 => _267.content, 'optionalAccess', _268 => _268.parts, 'optionalAccess', _269 => _269.some, 'call', _270 => _270((part) => part.functionResponse)])) {
10182
+ const functionCallId = _optionalChain([lastEvent, 'access', _271 => _271.content, 'access', _272 => _272.parts, 'access', _273 => _273.find, 'call', _274 => _274(
10135
10183
  (part) => part.functionResponse
10136
- ), 'optionalAccess', _271 => _271.functionResponse, 'optionalAccess', _272 => _272.id]);
10184
+ ), 'optionalAccess', _275 => _275.functionResponse, 'optionalAccess', _276 => _276.id]);
10137
10185
  if (!functionCallId) return null;
10138
10186
  for (let i = events.length - 2; i >= 0; i--) {
10139
10187
  const event = events[i];
10140
- const functionCalls = _optionalChain([event, 'access', _273 => _273.getFunctionCalls, 'optionalCall', _274 => _274()]) || [];
10188
+ const functionCalls = _optionalChain([event, 'access', _277 => _277.getFunctionCalls, 'optionalCall', _278 => _278()]) || [];
10141
10189
  for (const functionCall of functionCalls) {
10142
10190
  if (functionCall.id === functionCallId) {
10143
10191
  return event;
@@ -10340,15 +10388,15 @@ var Runner = (_class32 = class {
10340
10388
  */
10341
10389
  _findAgentToRun(session, rootAgent) {
10342
10390
  const event = _findFunctionCallEventIfLastEventIsFunctionResponse(session);
10343
- if (_optionalChain([event, 'optionalAccess', _275 => _275.author])) {
10391
+ if (_optionalChain([event, 'optionalAccess', _279 => _279.author])) {
10344
10392
  return rootAgent.findAgent(event.author);
10345
10393
  }
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()]) || [];
10394
+ 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
10395
  for (const event2 of nonUserEvents) {
10348
10396
  if (event2.author === rootAgent.name) {
10349
10397
  return rootAgent;
10350
10398
  }
10351
- const agent = _optionalChain([rootAgent, 'access', _281 => _281.findSubAgent, 'optionalCall', _282 => _282(event2.author)]);
10399
+ const agent = _optionalChain([rootAgent, 'access', _285 => _285.findSubAgent, 'optionalCall', _286 => _286(event2.author)]);
10352
10400
  if (!agent) {
10353
10401
  this.logger.debug(
10354
10402
  `Event from an unknown agent: ${event2.author}, event id: ${event2.id}`
@@ -10842,7 +10890,7 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10842
10890
  async ask(message) {
10843
10891
  const newMessage = typeof message === "string" ? { parts: [{ text: message }] } : typeof message === "object" && "contents" in message ? { parts: message.contents[message.contents.length - 1].parts } : message;
10844
10892
  let response = "";
10845
- if (!_optionalChain([sessionOptions, 'optionalAccess', _283 => _283.userId])) {
10893
+ if (!_optionalChain([sessionOptions, 'optionalAccess', _287 => _287.userId])) {
10846
10894
  throw new Error("Session configuration is required");
10847
10895
  }
10848
10896
  for await (const event of baseRunner.runAsync({
@@ -10850,7 +10898,7 @@ var AgentBuilder = (_class33 = class _AgentBuilder {
10850
10898
  sessionId: session.id,
10851
10899
  newMessage
10852
10900
  })) {
10853
- if (_optionalChain([event, 'access', _284 => _284.content, 'optionalAccess', _285 => _285.parts]) && Array.isArray(event.content.parts)) {
10901
+ if (_optionalChain([event, 'access', _288 => _288.content, 'optionalAccess', _289 => _289.parts]) && Array.isArray(event.content.parts)) {
10854
10902
  const content = event.content.parts.map(
10855
10903
  (part) => (part && typeof part === "object" && "text" in part ? part.text : "") || ""
10856
10904
  ).join("");
@@ -10958,7 +11006,7 @@ var VertexAiSessionService = class extends BaseSessionService {
10958
11006
  path: `operations/${operationId}`,
10959
11007
  request_dict: {}
10960
11008
  });
10961
- if (_optionalChain([lroResponse, 'optionalAccess', _286 => _286.done])) {
11009
+ if (_optionalChain([lroResponse, 'optionalAccess', _290 => _290.done])) {
10962
11010
  break;
10963
11011
  }
10964
11012
  await new Promise((resolve) => setTimeout(resolve, 1e3));
@@ -11329,12 +11377,12 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11329
11377
  }
11330
11378
  async createSession(appName, userId, state, sessionId) {
11331
11379
  await this.ensureInitialized();
11332
- const id = _optionalChain([sessionId, 'optionalAccess', _287 => _287.trim, 'call', _288 => _288()]) || this.generateSessionId();
11380
+ const id = _optionalChain([sessionId, 'optionalAccess', _291 => _291.trim, 'call', _292 => _292()]) || this.generateSessionId();
11333
11381
  return await this.db.transaction().execute(async (trx) => {
11334
11382
  const appState = await trx.selectFrom("app_states").selectAll().where("app_name", "=", appName).executeTakeFirst();
11335
11383
  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]), {});
11384
+ let currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _293 => _293.state]), {});
11385
+ let currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _294 => _294.state]), {});
11338
11386
  if (!appState) {
11339
11387
  await trx.insertInto("app_states").values({
11340
11388
  app_name: appName,
@@ -11393,21 +11441,21 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11393
11441
  return void 0;
11394
11442
  }
11395
11443
  let eventQuery = trx.selectFrom("events").selectAll().where("session_id", "=", sessionId).orderBy("timestamp", "desc");
11396
- if (_optionalChain([config, 'optionalAccess', _291 => _291.afterTimestamp])) {
11444
+ if (_optionalChain([config, 'optionalAccess', _295 => _295.afterTimestamp])) {
11397
11445
  eventQuery = eventQuery.where(
11398
11446
  "timestamp",
11399
11447
  ">=",
11400
11448
  new Date(config.afterTimestamp * 1e3)
11401
11449
  );
11402
11450
  }
11403
- if (_optionalChain([config, 'optionalAccess', _292 => _292.numRecentEvents])) {
11451
+ if (_optionalChain([config, 'optionalAccess', _296 => _296.numRecentEvents])) {
11404
11452
  eventQuery = eventQuery.limit(config.numRecentEvents);
11405
11453
  }
11406
11454
  const storageEvents = await eventQuery.execute();
11407
11455
  const appState = await trx.selectFrom("app_states").selectAll().where("app_name", "=", appName).executeTakeFirst();
11408
11456
  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]), {});
11457
+ const currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _297 => _297.state]), {});
11458
+ const currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _298 => _298.state]), {});
11411
11459
  const sessionState = this.parseJsonSafely(storageSession.state, {});
11412
11460
  const mergedState = this.mergeState(
11413
11461
  currentAppState,
@@ -11465,13 +11513,13 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11465
11513
  }
11466
11514
  const appState = await trx.selectFrom("app_states").selectAll().where("app_name", "=", session.appName).executeTakeFirst();
11467
11515
  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]), {});
11516
+ let currentAppState = this.parseJsonSafely(_optionalChain([appState, 'optionalAccess', _299 => _299.state]), {});
11517
+ let currentUserState = this.parseJsonSafely(_optionalChain([userState, 'optionalAccess', _300 => _300.state]), {});
11470
11518
  let sessionState = this.parseJsonSafely(storageSession.state, {});
11471
11519
  let appStateDelta = {};
11472
11520
  let userStateDelta = {};
11473
11521
  let sessionStateDelta = {};
11474
- if (_optionalChain([event, 'access', _297 => _297.actions, 'optionalAccess', _298 => _298.stateDelta])) {
11522
+ if (_optionalChain([event, 'access', _301 => _301.actions, 'optionalAccess', _302 => _302.stateDelta])) {
11475
11523
  const deltas = this.extractStateDelta(event.actions.stateDelta);
11476
11524
  appStateDelta = deltas.appStateDelta;
11477
11525
  userStateDelta = deltas.userStateDelta;
@@ -11617,7 +11665,7 @@ var DatabaseSessionService = (_class34 = class extends BaseSessionService {
11617
11665
  * Overrides the base class method to work with plain object state.
11618
11666
  */
11619
11667
  updateSessionState(session, event) {
11620
- if (!_optionalChain([event, 'access', _299 => _299.actions, 'optionalAccess', _300 => _300.stateDelta])) {
11668
+ if (!_optionalChain([event, 'access', _303 => _303.actions, 'optionalAccess', _304 => _304.stateDelta])) {
11621
11669
  return;
11622
11670
  }
11623
11671
  for (const [key, value] of Object.entries(event.actions.stateDelta)) {
@@ -11787,7 +11835,7 @@ var GcsArtifactService = class {
11787
11835
  };
11788
11836
  return part;
11789
11837
  } catch (error) {
11790
- if (_optionalChain([error, 'optionalAccess', _301 => _301.code]) === 404) {
11838
+ if (_optionalChain([error, 'optionalAccess', _305 => _305.code]) === 404) {
11791
11839
  return null;
11792
11840
  }
11793
11841
  throw error;
@@ -12038,13 +12086,13 @@ var VertexAiEvalFacade = class _VertexAiEvalFacade {
12038
12086
  };
12039
12087
  }
12040
12088
  _getText(content) {
12041
- if (_optionalChain([content, 'optionalAccess', _302 => _302.parts])) {
12089
+ if (_optionalChain([content, 'optionalAccess', _306 => _306.parts])) {
12042
12090
  return content.parts.map((p) => p.text || "").filter((text) => text.length > 0).join("\n");
12043
12091
  }
12044
12092
  return "";
12045
12093
  }
12046
12094
  _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)) {
12095
+ if (_optionalChain([evalResult, 'optionalAccess', _307 => _307.summaryMetrics, 'optionalAccess', _308 => _308[0], 'optionalAccess', _309 => _309.meanScore]) !== void 0 && typeof evalResult.summaryMetrics[0].meanScore === "number" && !Number.isNaN(evalResult.summaryMetrics[0].meanScore)) {
12048
12096
  return evalResult.summaryMetrics[0].meanScore;
12049
12097
  }
12050
12098
  return void 0;
@@ -12194,7 +12242,7 @@ var ResponseEvaluator = class extends Evaluator {
12194
12242
  return fmeasure;
12195
12243
  }
12196
12244
  extractText(content) {
12197
- if (_optionalChain([content, 'optionalAccess', _306 => _306.parts])) {
12245
+ if (_optionalChain([content, 'optionalAccess', _310 => _310.parts])) {
12198
12246
  return content.parts.map((p) => p.text || "").filter((text) => text.length > 0).join(" ");
12199
12247
  }
12200
12248
  return "";
@@ -12227,7 +12275,7 @@ var TrajectoryEvaluator = class extends Evaluator {
12227
12275
  for (let i = 0; i < actualInvocations.length; i++) {
12228
12276
  const actual = actualInvocations[i];
12229
12277
  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])) {
12278
+ if (!_optionalChain([actual, 'access', _311 => _311.intermediateData, 'optionalAccess', _312 => _312.toolUses]) || !_optionalChain([expected, 'access', _313 => _313.intermediateData, 'optionalAccess', _314 => _314.toolUses])) {
12231
12279
  perInvocationResults.push({
12232
12280
  actualInvocation: actual,
12233
12281
  expectedInvocation: expected,
@@ -12315,7 +12363,7 @@ var SafetyEvaluatorV1 = class extends Evaluator {
12315
12363
 
12316
12364
  // src/evaluation/llm-as-judge-utils.ts
12317
12365
  function getTextFromContent(content) {
12318
- if (_optionalChain([content, 'optionalAccess', _311 => _311.parts])) {
12366
+ if (_optionalChain([content, 'optionalAccess', _315 => _315.parts])) {
12319
12367
  return content.parts.map((part) => part.text).filter(Boolean).join("\n");
12320
12368
  }
12321
12369
  return "";
@@ -12327,9 +12375,9 @@ function getEvalStatus(score, threshold) {
12327
12375
  // src/evaluation/llm-as-judge.ts
12328
12376
  var LlmAsJudge = class {
12329
12377
  async sampleJudge(prompt, numSamples, critiqueParser, judgeModelOptions) {
12330
- const modelName = _optionalChain([judgeModelOptions, 'optionalAccess', _312 => _312.judgeModel]) || "gemini-2.5-flash";
12378
+ const modelName = _optionalChain([judgeModelOptions, 'optionalAccess', _316 => _316.judgeModel]) || "gemini-2.5-flash";
12331
12379
  const model = LLMRegistry.getModelOrCreate(modelName);
12332
- const config = _optionalChain([judgeModelOptions, 'optionalAccess', _313 => _313.judgeModelConfig]) || {};
12380
+ const config = _optionalChain([judgeModelOptions, 'optionalAccess', _317 => _317.judgeModelConfig]) || {};
12333
12381
  const samples = [];
12334
12382
  for (let i = 0; i < numSamples; i++) {
12335
12383
  try {
@@ -12395,7 +12443,7 @@ function parseCritique(response) {
12395
12443
  const labelMatchIsResponseValid = response.match(
12396
12444
  /"is_the_agent_response_valid":\s*\[*[\n\s]*"*([^"^\]^\s]*)"*[\n\s]*\]*\s*[,\n\}]/
12397
12445
  );
12398
- if (_optionalChain([labelMatchIsResponseValid, 'optionalAccess', _314 => _314[1]])) {
12446
+ if (_optionalChain([labelMatchIsResponseValid, 'optionalAccess', _318 => _318[1]])) {
12399
12447
  const label = labelMatchIsResponseValid[1].toLowerCase();
12400
12448
  return label === "valid" ? "valid" /* VALID */ : "invalid" /* INVALID */;
12401
12449
  }
@@ -12440,7 +12488,7 @@ var FinalResponseMatchV2Evaluator = class extends Evaluator {
12440
12488
  "{prompt}",
12441
12489
  prompt
12442
12490
  ).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));
12491
+ const numSamples = _nullishCoalesce(_optionalChain([this, 'access', _319 => _319.metric, 'access', _320 => _320.judgeModelOptions, 'optionalAccess', _321 => _321.numSamples]), () => ( DEFAULT_NUM_SAMPLES));
12444
12492
  const labels = await this.llmAsJudge.sampleJudge(
12445
12493
  formattedPrompt,
12446
12494
  numSamples,
@@ -12480,7 +12528,7 @@ var MetricEvaluatorRegistry = (_class35 = class {constructor() { _class35.protot
12480
12528
  const metricName = metricInfo.metricName;
12481
12529
  if (this.registry.has(metricName)) {
12482
12530
  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}`
12531
+ `Updating Evaluator class for ${metricName} from ${_optionalChain([this, 'access', _322 => _322.registry, 'access', _323 => _323.get, 'call', _324 => _324(metricName), 'optionalAccess', _325 => _325.evaluator, 'access', _326 => _326.name])} to ${evaluator.name}`
12484
12532
  );
12485
12533
  }
12486
12534
  this.registry.set(metricName, {
@@ -12594,10 +12642,10 @@ var LocalEvalService = class extends BaseEvalService {
12594
12642
  for (const evalMetric of evaluateConfig.evalMetrics) {
12595
12643
  const evaluator = DEFAULT_METRIC_EVALUATOR_REGISTRY.getEvaluator(evalMetric);
12596
12644
  const actual = results.filter(
12597
- (r) => !_optionalChain([r, 'access', _323 => _323.invocationId, 'optionalAccess', _324 => _324.includes, 'call', _325 => _325("expected")])
12645
+ (r) => !_optionalChain([r, 'access', _327 => _327.invocationId, 'optionalAccess', _328 => _328.includes, 'call', _329 => _329("expected")])
12598
12646
  );
12599
12647
  const expected = results.filter(
12600
- (r) => _optionalChain([r, 'access', _326 => _326.invocationId, 'optionalAccess', _327 => _327.includes, 'call', _328 => _328("expected")])
12648
+ (r) => _optionalChain([r, 'access', _330 => _330.invocationId, 'optionalAccess', _331 => _331.includes, 'call', _332 => _332("expected")])
12601
12649
  );
12602
12650
  const result = await evaluator.evaluateInvocations(actual, expected);
12603
12651
  evalResult.evalCaseResults.push({
@@ -12989,13 +13037,13 @@ ${failures.join(
12989
13037
  console.log("\n\n");
12990
13038
  }
12991
13039
  static _convertContentToText(content) {
12992
- if (_optionalChain([content, 'optionalAccess', _329 => _329.parts])) {
13040
+ if (_optionalChain([content, 'optionalAccess', _333 => _333.parts])) {
12993
13041
  return content.parts.map((p) => p.text || "").filter((text) => text.length > 0).join("\n");
12994
13042
  }
12995
13043
  return "";
12996
13044
  }
12997
13045
  static _convertToolCallsToText(intermediateData) {
12998
- if (_optionalChain([intermediateData, 'optionalAccess', _330 => _330.toolUses])) {
13046
+ if (_optionalChain([intermediateData, 'optionalAccess', _334 => _334.toolUses])) {
12999
13047
  return intermediateData.toolUses.map((t) => JSON.stringify(t)).join("\n");
13000
13048
  }
13001
13049
  return "";
@@ -13050,7 +13098,7 @@ ${failures.join(
13050
13098
  for (const [metricName, evalMetricResultsWithInvocations] of Object.entries(
13051
13099
  evalMetricResults
13052
13100
  )) {
13053
- const threshold = _optionalChain([evalMetricResultsWithInvocations, 'access', _331 => _331[0], 'optionalAccess', _332 => _332.evalMetricResult, 'access', _333 => _333.threshold]) || 0;
13101
+ const threshold = _optionalChain([evalMetricResultsWithInvocations, 'access', _335 => _335[0], 'optionalAccess', _336 => _336.evalMetricResult, 'access', _337 => _337.threshold]) || 0;
13054
13102
  const scores = evalMetricResultsWithInvocations.map((m) => m.evalMetricResult.score).filter((s) => s !== void 0);
13055
13103
  let overallScore;
13056
13104
  let overallEvalStatus;
@@ -13139,7 +13187,7 @@ var RougeEvaluator = class extends Evaluator {
13139
13187
  }
13140
13188
  };
13141
13189
  function getTextFromContent2(content) {
13142
- if (_optionalChain([content, 'optionalAccess', _334 => _334.parts])) {
13190
+ if (_optionalChain([content, 'optionalAccess', _338 => _338.parts])) {
13143
13191
  return content.parts.map((part) => part.text).filter(Boolean).join("\n");
13144
13192
  }
13145
13193
  return "";
package/dist/index.mjs CHANGED
@@ -7111,6 +7111,7 @@ var AuthLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7111
7111
  var requestProcessor = new AuthLlmRequestProcessor();
7112
7112
 
7113
7113
  // src/flows/llm-flows/basic.ts
7114
+ init_logger();
7114
7115
  var BasicLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7115
7116
  async *runAsync(invocationContext, llmRequest) {
7116
7117
  const agent = invocationContext.agent;
@@ -7126,7 +7127,21 @@ var BasicLlmRequestProcessor = class extends BaseLlmRequestProcessor {
7126
7127
  llmRequest.config = {};
7127
7128
  }
7128
7129
  if (agent.outputSchema) {
7129
- llmRequest.setOutputSchema(agent.outputSchema);
7130
+ const hasTools = (await agent.canonicalTools?.(invocationContext))?.length > 0;
7131
+ const hasTransfers = !!("subAgents" in agent && agent.subAgents && agent.subAgents.length > 0 && !(agent.disallowTransferToParent && agent.disallowTransferToPeers));
7132
+ if (!hasTools && !hasTransfers) {
7133
+ llmRequest.setOutputSchema(agent.outputSchema);
7134
+ } else {
7135
+ (() => {
7136
+ try {
7137
+ const logger = new Logger({ name: "BasicLlmRequestProcessor" });
7138
+ logger.debug(
7139
+ `Skipping request-level output schema for agent ${agent.name} because tools/transfers are present. Schema will be validated during response processing.`
7140
+ );
7141
+ } catch (e) {
7142
+ }
7143
+ })();
7144
+ }
7130
7145
  }
7131
7146
  const runConfig = invocationContext.runConfig;
7132
7147
  if (!llmRequest.liveConnectConfig) {
@@ -8278,10 +8293,11 @@ var InstructionsLlmRequestProcessor = class extends BaseLlmRequestProcessor {
8278
8293
  });
8279
8294
  const { $schema, ...json } = raw || {};
8280
8295
  llmRequest.appendInstructions([
8281
- "You must respond with application/json that validates against this JSON Schema:",
8282
- "```json",
8283
- JSON.stringify(json, null, 2),
8284
- "```"
8296
+ "You must respond with application/json that validates against this JSON Schema (do NOT wrap the output in markdown or code fences):",
8297
+ JSON.stringify(json, null, 2)
8298
+ ]);
8299
+ llmRequest.appendInstructions([
8300
+ '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.'
8285
8301
  ]);
8286
8302
  } catch {
8287
8303
  }
@@ -8578,6 +8594,7 @@ var requestProcessor7 = new NlPlanningRequestProcessor();
8578
8594
  var responseProcessor2 = new NlPlanningResponseProcessor();
8579
8595
 
8580
8596
  // src/flows/llm-flows/output-schema.ts
8597
+ import { jsonrepair } from "jsonrepair";
8581
8598
  init_logger();
8582
8599
  var OutputSchemaResponseProcessor = class extends BaseLlmResponseProcessor {
8583
8600
  logger = new Logger({ name: "OutputSchemaResponseProcessor" });
@@ -8599,7 +8616,8 @@ var OutputSchemaResponseProcessor = class extends BaseLlmResponseProcessor {
8599
8616
  return;
8600
8617
  }
8601
8618
  try {
8602
- const parsed = JSON.parse(textContent);
8619
+ const candidate = this.stripCodeFences(textContent);
8620
+ const parsed = this.tryParseJson(candidate, agent.name);
8603
8621
  const validated = agent.outputSchema.parse(parsed);
8604
8622
  textContent = JSON.stringify(validated, null, 2);
8605
8623
  llmResponse.content.parts = llmResponse.content.parts.map((part) => {
@@ -8647,6 +8665,38 @@ var OutputSchemaResponseProcessor = class extends BaseLlmResponseProcessor {
8647
8665
  yield errorEvent;
8648
8666
  }
8649
8667
  }
8668
+ // Strip common code fences and surrounding explanatory text from LLM output.
8669
+ stripCodeFences(raw) {
8670
+ const fencePattern = /```(?:json)?\s*([\s\S]*?)```/i;
8671
+ const fenceMatch = raw.match(fencePattern);
8672
+ if (fenceMatch?.[1]) {
8673
+ return fenceMatch[1].trim();
8674
+ }
8675
+ const lines = raw.split(/\r?\n/).map((l) => l.trim());
8676
+ const startIdx = lines.findIndex(
8677
+ (l) => l.startsWith("{") || l.startsWith("[")
8678
+ );
8679
+ if (startIdx >= 0) {
8680
+ return lines.slice(startIdx).join("\n").trim();
8681
+ }
8682
+ return raw.trim();
8683
+ }
8684
+ // Try parsing JSON; if parse fails, attempt to repair using jsonrepair and parse again.
8685
+ tryParseJson(candidate, agentName) {
8686
+ try {
8687
+ return JSON.parse(candidate);
8688
+ } catch (err) {
8689
+ this.logger.debug("Initial JSON.parse failed, attempting jsonrepair", {
8690
+ agent: agentName
8691
+ });
8692
+ try {
8693
+ const repaired = jsonrepair(candidate);
8694
+ return JSON.parse(repaired);
8695
+ } catch (repairErr) {
8696
+ throw err;
8697
+ }
8698
+ }
8699
+ }
8650
8700
  };
8651
8701
  var responseProcessor3 = new OutputSchemaResponseProcessor();
8652
8702
 
@@ -9069,19 +9119,17 @@ var LlmAgent = class _LlmAgent extends BaseAgent {
9069
9119
  }
9070
9120
  if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {
9071
9121
  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`
9122
+ `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
9123
  );
9074
- this.disallowTransferToParent = true;
9075
- this.disallowTransferToPeers = true;
9076
9124
  }
9077
9125
  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.`
9126
+ this.logger.warn(
9127
+ `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
9128
  );
9081
9129
  }
9082
9130
  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`
9131
+ this.logger.warn(
9132
+ `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
9133
  );
9086
9134
  }
9087
9135
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iqai/adk",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Agent Development Kit for TypeScript with multi-provider LLM support",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -55,6 +55,7 @@
55
55
  "ts-node": "^10.9.2",
56
56
  "uuid": "^11.1.0",
57
57
  "zod": "^3.25.67",
58
+ "jsonrepair": "^3.13.0",
58
59
  "zod-to-json-schema": "^3.24.6"
59
60
  },
60
61
  "peerDependencies": {