@iqai/adk 0.1.13 → 0.1.15

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.mjs CHANGED
@@ -323,15 +323,17 @@ var init_base_tool = __esm({
323
323
  if (!llmRequest.config || !llmRequest.config.tools) {
324
324
  return null;
325
325
  }
326
- return llmRequest.config.tools.find(
327
- (tool) => tool.functionDeclarations && tool.functionDeclarations.length > 0
326
+ const toolWithFunctionDeclaration = llmRequest.config.tools.find(
327
+ (tool) => "functionDeclarations" in tool && tool.functionDeclarations && tool.functionDeclarations.length > 0
328
328
  ) || null;
329
+ return toolWithFunctionDeclaration;
329
330
  }
330
331
  };
331
332
  }
332
333
  });
333
334
 
334
335
  // src/tools/function/function-utils.ts
336
+ import { Type as Type2 } from "@google/genai";
335
337
  function buildFunctionDeclaration(func, options = {}) {
336
338
  const funcStr = func.toString();
337
339
  const name = options.name || func.name;
@@ -352,10 +354,10 @@ function buildFunctionDeclaration(func, options = {}) {
352
354
  function extractParametersSchema(func, ignoreParams = []) {
353
355
  const funcStr = func.toString();
354
356
  const paramMatch = funcStr.match(/\(([^)]*)\)/);
355
- if (!paramMatch) return { type: "object", properties: {} };
357
+ if (!paramMatch) return { type: Type2.OBJECT, properties: {} };
356
358
  const paramList = paramMatch[1].split(",").map((param) => param.trim()).filter((param) => param !== "");
357
359
  if (paramList.length === 0 || paramList.length === 1 && paramList[0] === "") {
358
- return { type: "object", properties: {} };
360
+ return { type: Type2.OBJECT, properties: {} };
359
361
  }
360
362
  const jsDocParams = extractJSDocParams(funcStr);
361
363
  const jsDocTypes = extractJSDocTypes(funcStr);
@@ -395,7 +397,7 @@ function extractParametersSchema(func, ignoreParams = []) {
395
397
  }
396
398
  }
397
399
  const schema = {
398
- type: "object",
400
+ type: Type2.OBJECT,
399
401
  properties
400
402
  };
401
403
  if (required.length > 0) {
@@ -1397,7 +1399,7 @@ var GoogleLlm = class extends BaseLlm {
1397
1399
  this.preprocessRequest(llmRequest);
1398
1400
  const model = llmRequest.model || this.model;
1399
1401
  const contents = this.convertContents(llmRequest.contents || []);
1400
- const config = this.convertConfig(llmRequest.config);
1402
+ const config = llmRequest.config;
1401
1403
  if (stream) {
1402
1404
  const responses = await this.apiClient.models.generateContentStream({
1403
1405
  model,
@@ -1491,19 +1493,6 @@ var GoogleLlm = class extends BaseLlm {
1491
1493
  parts: content.parts || [{ text: content.content || "" }]
1492
1494
  }));
1493
1495
  }
1494
- /**
1495
- * Convert LlmRequest config to GoogleGenAI format
1496
- */
1497
- convertConfig(config) {
1498
- if (!config) return {};
1499
- return {
1500
- temperature: config.temperature,
1501
- topP: config.top_p,
1502
- maxOutputTokens: config.max_tokens,
1503
- tools: config.tools,
1504
- systemInstruction: config.system_instruction
1505
- };
1506
- }
1507
1496
  /**
1508
1497
  * Preprocesses the request based on the API backend.
1509
1498
  */
@@ -3295,7 +3284,7 @@ var CallbackContext = class extends ReadonlyContext {
3295
3284
  constructor(invocationContext, options = {}) {
3296
3285
  super(invocationContext);
3297
3286
  this._eventActions = options.eventActions || new EventActions();
3298
- this._state = new State(
3287
+ this._state = State.create(
3299
3288
  invocationContext.session.state,
3300
3289
  this._eventActions.stateDelta
3301
3290
  );
@@ -3821,6 +3810,7 @@ ${argsStr}
3821
3810
  // src/tools/index.ts
3822
3811
  var tools_exports = {};
3823
3812
  __export(tools_exports, {
3813
+ AgentTool: () => AgentTool,
3824
3814
  BaseTool: () => BaseTool,
3825
3815
  ExitLoopTool: () => ExitLoopTool,
3826
3816
  FileOperationsTool: () => FileOperationsTool,
@@ -3925,6 +3915,283 @@ function createTool(config) {
3925
3915
  return new CreatedTool(config);
3926
3916
  }
3927
3917
 
3918
+ // src/tools/common/agent-tool.ts
3919
+ init_logger();
3920
+ import { Type } from "@google/genai";
3921
+ import { v4 as uuidv42 } from "uuid";
3922
+
3923
+ // src/agents/invocation-context.ts
3924
+ var LlmCallsLimitExceededError = class extends Error {
3925
+ constructor(message) {
3926
+ super(message);
3927
+ this.name = "LlmCallsLimitExceededError";
3928
+ }
3929
+ };
3930
+ var InvocationCostManager = class {
3931
+ /**
3932
+ * A counter that keeps track of number of llm calls made.
3933
+ */
3934
+ _numberOfLlmCalls = 0;
3935
+ /**
3936
+ * Increments _numberOfLlmCalls and enforces the limit.
3937
+ */
3938
+ incrementAndEnforceLlmCallsLimit(runConfig) {
3939
+ this._numberOfLlmCalls += 1;
3940
+ if (runConfig && runConfig.maxLlmCalls > 0 && this._numberOfLlmCalls > runConfig.maxLlmCalls) {
3941
+ throw new LlmCallsLimitExceededError(
3942
+ `Max number of llm calls limit of \`${runConfig.maxLlmCalls}\` exceeded`
3943
+ );
3944
+ }
3945
+ }
3946
+ };
3947
+ function newInvocationContextId() {
3948
+ return `e-${crypto.randomUUID()}`;
3949
+ }
3950
+ var InvocationContext = class _InvocationContext {
3951
+ artifactService;
3952
+ sessionService;
3953
+ memoryService;
3954
+ /**
3955
+ * The id of this invocation context. Readonly.
3956
+ */
3957
+ invocationId;
3958
+ /**
3959
+ * The branch of the invocation context.
3960
+ *
3961
+ * The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of
3962
+ * agent_2, and agent_2 is the parent of agent_3.
3963
+ *
3964
+ * Branch is used when multiple sub-agents shouldn't see their peer agents'
3965
+ * conversation history.
3966
+ */
3967
+ branch;
3968
+ /**
3969
+ * The current agent of this invocation context. Readonly.
3970
+ */
3971
+ agent;
3972
+ /**
3973
+ * The user content that started this invocation. Readonly.
3974
+ */
3975
+ userContent;
3976
+ /**
3977
+ * The current session of this invocation context. Readonly.
3978
+ */
3979
+ session;
3980
+ /**
3981
+ * Whether to end this invocation.
3982
+ *
3983
+ * Set to True in callbacks or tools to terminate this invocation.
3984
+ */
3985
+ endInvocation = false;
3986
+ /**
3987
+ * The queue to receive live requests.
3988
+ */
3989
+ liveRequestQueue;
3990
+ /**
3991
+ * The running streaming tools of this invocation.
3992
+ */
3993
+ activeStreamingTools;
3994
+ /**
3995
+ * Caches necessary, data audio or contents, that are needed by transcription.
3996
+ */
3997
+ transcriptionCache;
3998
+ /**
3999
+ * Configurations for live agents under this invocation.
4000
+ */
4001
+ runConfig;
4002
+ /**
4003
+ * A container to keep track of different kinds of costs incurred as a part
4004
+ * of this invocation.
4005
+ */
4006
+ _invocationCostManager = new InvocationCostManager();
4007
+ /**
4008
+ * Constructor for InvocationContext
4009
+ */
4010
+ constructor(options) {
4011
+ this.artifactService = options.artifactService;
4012
+ this.sessionService = options.sessionService;
4013
+ this.memoryService = options.memoryService;
4014
+ this.invocationId = options.invocationId || newInvocationContextId();
4015
+ this.branch = options.branch;
4016
+ this.agent = options.agent;
4017
+ this.userContent = options.userContent;
4018
+ this.session = options.session;
4019
+ this.endInvocation = options.endInvocation || false;
4020
+ this.liveRequestQueue = options.liveRequestQueue;
4021
+ this.activeStreamingTools = options.activeStreamingTools;
4022
+ this.transcriptionCache = options.transcriptionCache;
4023
+ this.runConfig = options.runConfig;
4024
+ }
4025
+ /**
4026
+ * App name from the session
4027
+ */
4028
+ get appName() {
4029
+ return this.session.appName;
4030
+ }
4031
+ /**
4032
+ * User ID from the session
4033
+ */
4034
+ get userId() {
4035
+ return this.session.userId;
4036
+ }
4037
+ /**
4038
+ * Tracks number of llm calls made.
4039
+ *
4040
+ * @throws {LlmCallsLimitExceededError} If number of llm calls made exceed the set threshold.
4041
+ */
4042
+ incrementLlmCallCount() {
4043
+ this._invocationCostManager.incrementAndEnforceLlmCallsLimit(
4044
+ this.runConfig
4045
+ );
4046
+ }
4047
+ /**
4048
+ * Creates a child invocation context for a sub-agent
4049
+ */
4050
+ createChildContext(agent) {
4051
+ return new _InvocationContext({
4052
+ artifactService: this.artifactService,
4053
+ sessionService: this.sessionService,
4054
+ memoryService: this.memoryService,
4055
+ invocationId: this.invocationId,
4056
+ // Keep same invocation ID
4057
+ branch: this.branch ? `${this.branch}.${agent.name}` : agent.name,
4058
+ // Update branch
4059
+ agent,
4060
+ // Update to the new agent
4061
+ userContent: this.userContent,
4062
+ session: this.session,
4063
+ endInvocation: this.endInvocation,
4064
+ liveRequestQueue: this.liveRequestQueue,
4065
+ activeStreamingTools: this.activeStreamingTools,
4066
+ transcriptionCache: this.transcriptionCache,
4067
+ runConfig: this.runConfig
4068
+ });
4069
+ }
4070
+ };
4071
+
4072
+ // src/tools/common/agent-tool.ts
4073
+ init_base_tool();
4074
+ function isLlmAgent(agent) {
4075
+ return true;
4076
+ }
4077
+ var AgentTool = class extends BaseTool {
4078
+ /**
4079
+ * The agent used by this tool
4080
+ */
4081
+ agent;
4082
+ /**
4083
+ * The function declaration schema
4084
+ */
4085
+ functionDeclaration;
4086
+ /**
4087
+ * The key to store the tool output in the state
4088
+ */
4089
+ outputKey;
4090
+ /**
4091
+ * Whether to skip summarization of the agent's response
4092
+ */
4093
+ skipSummarization;
4094
+ logger = new Logger({ name: "AgentTool" });
4095
+ /**
4096
+ * Create a new agent tool
4097
+ */
4098
+ constructor(config) {
4099
+ super({
4100
+ name: config.name,
4101
+ description: config.description || config.agent.description,
4102
+ isLongRunning: config.isLongRunning || false,
4103
+ shouldRetryOnFailure: config.shouldRetryOnFailure || false,
4104
+ maxRetryAttempts: config.maxRetryAttempts || 3
4105
+ });
4106
+ this.agent = config.agent;
4107
+ this.functionDeclaration = config.functionDeclaration;
4108
+ this.outputKey = config.outputKey;
4109
+ this.skipSummarization = config.skipSummarization || false;
4110
+ }
4111
+ /**
4112
+ * Get the function declaration for the tool
4113
+ */
4114
+ getDeclaration() {
4115
+ if (this.functionDeclaration) {
4116
+ return this.functionDeclaration;
4117
+ }
4118
+ const description = isLlmAgent(this.agent) ? typeof this.agent.instruction === "string" ? this.agent.instruction : this.description : this.description;
4119
+ return {
4120
+ name: this.name,
4121
+ description,
4122
+ parameters: {
4123
+ type: Type.OBJECT,
4124
+ properties: {
4125
+ input: {
4126
+ type: Type.STRING,
4127
+ description: "The input to provide to the agent"
4128
+ }
4129
+ },
4130
+ required: ["input"]
4131
+ }
4132
+ };
4133
+ }
4134
+ /**
4135
+ * Execute the tool by running the agent with the provided input
4136
+ */
4137
+ async runAsync(params, context) {
4138
+ try {
4139
+ const input = params.input || Object.values(params)[0];
4140
+ if (!isLlmAgent(this.agent)) {
4141
+ throw new Error(
4142
+ `Agent ${this.name} does not support running as a tool`
4143
+ );
4144
+ }
4145
+ const parentInvocation = context._invocationContext;
4146
+ const childInvocationContext = new InvocationContext({
4147
+ invocationId: uuidv42(),
4148
+ agent: this.agent,
4149
+ session: parentInvocation.session,
4150
+ artifactService: parentInvocation.artifactService,
4151
+ sessionService: parentInvocation.sessionService,
4152
+ memoryService: parentInvocation.memoryService,
4153
+ runConfig: parentInvocation.runConfig,
4154
+ userContent: {
4155
+ role: "user",
4156
+ parts: [{ text: String(input) }]
4157
+ },
4158
+ branch: parentInvocation.branch ? `${parentInvocation.branch}.${this.agent.name}` : this.agent.name
4159
+ });
4160
+ let lastEvent = null;
4161
+ for await (const event of this.agent.runAsync(childInvocationContext)) {
4162
+ if (!event.partial) {
4163
+ await childInvocationContext.sessionService.appendEvent(
4164
+ childInvocationContext.session,
4165
+ event
4166
+ );
4167
+ }
4168
+ if (event.content && event.author === this.agent.name) {
4169
+ lastEvent = event;
4170
+ }
4171
+ }
4172
+ if (!lastEvent || !lastEvent.content || !lastEvent.content.parts) {
4173
+ return "";
4174
+ }
4175
+ const mergedText = lastEvent.content.parts.filter((part) => part.text !== void 0 && part.text !== null).map((part) => part.text).join("\n");
4176
+ let toolResult;
4177
+ try {
4178
+ toolResult = JSON.parse(mergedText);
4179
+ } catch {
4180
+ toolResult = mergedText;
4181
+ }
4182
+ if (this.outputKey && context?.state) {
4183
+ context.state[this.outputKey] = toolResult;
4184
+ }
4185
+ return toolResult;
4186
+ } catch (error) {
4187
+ this.logger.error(`Error executing agent tool ${this.name}:`, error);
4188
+ throw new Error(
4189
+ `Agent tool execution failed: ${error instanceof Error ? error.message : String(error)}`
4190
+ );
4191
+ }
4192
+ }
4193
+ };
4194
+
3928
4195
  // src/tools/tool-context.ts
3929
4196
  var ToolContext = class extends CallbackContext {
3930
4197
  /**
@@ -3992,6 +4259,7 @@ init_function_utils();
3992
4259
  // src/tools/common/google-search.ts
3993
4260
  init_logger();
3994
4261
  init_base_tool();
4262
+ import { Type as Type3 } from "@google/genai";
3995
4263
  var GoogleSearch = class extends BaseTool {
3996
4264
  logger = new Logger({ name: "GoogleSearch" });
3997
4265
  /**
@@ -4011,14 +4279,14 @@ var GoogleSearch = class extends BaseTool {
4011
4279
  name: this.name,
4012
4280
  description: this.description,
4013
4281
  parameters: {
4014
- type: "object",
4282
+ type: Type3.OBJECT,
4015
4283
  properties: {
4016
4284
  query: {
4017
- type: "string",
4285
+ type: Type3.STRING,
4018
4286
  description: "The search query to execute"
4019
4287
  },
4020
4288
  num_results: {
4021
- type: "integer",
4289
+ type: Type3.INTEGER,
4022
4290
  description: "Number of results to return (max 10)",
4023
4291
  default: 5
4024
4292
  }
@@ -4054,6 +4322,7 @@ var GoogleSearch = class extends BaseTool {
4054
4322
 
4055
4323
  // src/tools/common/http-request-tool.ts
4056
4324
  init_base_tool();
4325
+ import { Type as Type4 } from "@google/genai";
4057
4326
  var HttpRequestTool = class extends BaseTool {
4058
4327
  constructor() {
4059
4328
  super({
@@ -4069,38 +4338,32 @@ var HttpRequestTool = class extends BaseTool {
4069
4338
  name: this.name,
4070
4339
  description: this.description,
4071
4340
  parameters: {
4072
- type: "object",
4341
+ type: Type4.OBJECT,
4073
4342
  properties: {
4074
4343
  url: {
4075
- type: "string",
4344
+ type: Type4.STRING,
4076
4345
  description: "The URL to send the request to"
4077
4346
  },
4078
4347
  method: {
4079
- type: "string",
4348
+ type: Type4.STRING,
4080
4349
  description: "The HTTP method to use (GET, POST, PUT, DELETE, etc.)",
4081
4350
  enum: ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"],
4082
4351
  default: "GET"
4083
4352
  },
4084
4353
  headers: {
4085
- type: "object",
4086
- description: "Request headers to include",
4087
- additionalProperties: {
4088
- type: "string"
4089
- }
4354
+ type: Type4.OBJECT,
4355
+ description: "Request headers to include"
4090
4356
  },
4091
4357
  body: {
4092
- type: "string",
4358
+ type: Type4.STRING,
4093
4359
  description: "Request body content (as string, typically JSON)"
4094
4360
  },
4095
4361
  params: {
4096
- type: "object",
4097
- description: "URL query parameters to include",
4098
- additionalProperties: {
4099
- type: "string"
4100
- }
4362
+ type: Type4.OBJECT,
4363
+ description: "URL query parameters to include"
4101
4364
  },
4102
4365
  timeout: {
4103
- type: "integer",
4366
+ type: Type4.INTEGER,
4104
4367
  description: "Request timeout in milliseconds",
4105
4368
  default: 1e4
4106
4369
  }
@@ -4175,6 +4438,7 @@ var HttpRequestTool = class extends BaseTool {
4175
4438
  init_base_tool();
4176
4439
  import fs from "fs/promises";
4177
4440
  import path from "path";
4441
+ import { Type as Type5 } from "@google/genai";
4178
4442
  var FileOperationsTool = class extends BaseTool {
4179
4443
  basePath;
4180
4444
  constructor(options) {
@@ -4192,10 +4456,10 @@ var FileOperationsTool = class extends BaseTool {
4192
4456
  name: this.name,
4193
4457
  description: this.description,
4194
4458
  parameters: {
4195
- type: "object",
4459
+ type: Type5.OBJECT,
4196
4460
  properties: {
4197
4461
  operation: {
4198
- type: "string",
4462
+ type: Type5.STRING,
4199
4463
  description: "The file operation to perform",
4200
4464
  enum: [
4201
4465
  "read",
@@ -4208,15 +4472,15 @@ var FileOperationsTool = class extends BaseTool {
4208
4472
  ]
4209
4473
  },
4210
4474
  filepath: {
4211
- type: "string",
4475
+ type: Type5.STRING,
4212
4476
  description: "Path to the file or directory (relative to the base path)"
4213
4477
  },
4214
4478
  content: {
4215
- type: "string",
4479
+ type: Type5.STRING,
4216
4480
  description: "Content to write to the file (for write and append operations)"
4217
4481
  },
4218
4482
  encoding: {
4219
- type: "string",
4483
+ type: Type5.STRING,
4220
4484
  description: "File encoding to use",
4221
4485
  default: "utf8"
4222
4486
  }
@@ -4422,6 +4686,7 @@ var FileOperationsTool = class extends BaseTool {
4422
4686
 
4423
4687
  // src/tools/common/user-interaction-tool.ts
4424
4688
  init_base_tool();
4689
+ import { Type as Type6 } from "@google/genai";
4425
4690
  var UserInteractionTool = class extends BaseTool {
4426
4691
  constructor() {
4427
4692
  super({
@@ -4438,21 +4703,21 @@ var UserInteractionTool = class extends BaseTool {
4438
4703
  name: this.name,
4439
4704
  description: this.description,
4440
4705
  parameters: {
4441
- type: "object",
4706
+ type: Type6.OBJECT,
4442
4707
  properties: {
4443
4708
  prompt: {
4444
- type: "string",
4709
+ type: Type6.STRING,
4445
4710
  description: "The prompt message to display to the user"
4446
4711
  },
4447
4712
  options: {
4448
- type: "array",
4713
+ type: Type6.ARRAY,
4449
4714
  description: "Optional array of choices to present to the user",
4450
4715
  items: {
4451
- type: "string"
4716
+ type: Type6.STRING
4452
4717
  }
4453
4718
  },
4454
4719
  defaultValue: {
4455
- type: "string",
4720
+ type: Type6.STRING,
4456
4721
  description: "Optional default value for the input field"
4457
4722
  }
4458
4723
  },
@@ -4522,6 +4787,7 @@ var ExitLoopTool = class extends BaseTool {
4522
4787
  // src/tools/common/get-user-choice-tool.ts
4523
4788
  init_logger();
4524
4789
  init_base_tool();
4790
+ import { Type as Type7 } from "@google/genai";
4525
4791
  var GetUserChoiceTool = class extends BaseTool {
4526
4792
  logger = new Logger({ name: "GetUserChoiceTool" });
4527
4793
  /**
@@ -4542,17 +4808,17 @@ var GetUserChoiceTool = class extends BaseTool {
4542
4808
  name: this.name,
4543
4809
  description: this.description,
4544
4810
  parameters: {
4545
- type: "object",
4811
+ type: Type7.OBJECT,
4546
4812
  properties: {
4547
4813
  options: {
4548
- type: "array",
4814
+ type: Type7.ARRAY,
4549
4815
  description: "List of options for the user to choose from",
4550
4816
  items: {
4551
- type: "string"
4817
+ type: Type7.STRING
4552
4818
  }
4553
4819
  },
4554
4820
  question: {
4555
- type: "string",
4821
+ type: Type7.STRING,
4556
4822
  description: "The question or prompt to show the user before presenting options"
4557
4823
  }
4558
4824
  },
@@ -4580,6 +4846,7 @@ var GetUserChoiceTool = class extends BaseTool {
4580
4846
  // src/tools/common/transfer-to-agent-tool.ts
4581
4847
  init_logger();
4582
4848
  init_base_tool();
4849
+ import { Type as Type8 } from "@google/genai";
4583
4850
  var TransferToAgentTool = class extends BaseTool {
4584
4851
  logger = new Logger({ name: "TransferToAgentTool" });
4585
4852
  /**
@@ -4588,9 +4855,28 @@ var TransferToAgentTool = class extends BaseTool {
4588
4855
  constructor() {
4589
4856
  super({
4590
4857
  name: "transfer_to_agent",
4591
- description: "Transfer the question to another agent."
4858
+ description: "Transfer the question to another agent when it's more suitable to answer the user's question according to the agent's description. Use this function when you determine that another agent in the system would be better equipped to handle the user's request based on their specialized capabilities and expertise areas."
4592
4859
  });
4593
4860
  }
4861
+ /**
4862
+ * Get the function declaration for the tool
4863
+ */
4864
+ getDeclaration() {
4865
+ return {
4866
+ name: this.name,
4867
+ description: this.description,
4868
+ parameters: {
4869
+ type: Type8.OBJECT,
4870
+ properties: {
4871
+ agent_name: {
4872
+ type: Type8.STRING,
4873
+ description: "The name of the agent to transfer control to"
4874
+ }
4875
+ },
4876
+ required: ["agent_name"]
4877
+ }
4878
+ };
4879
+ }
4594
4880
  /**
4595
4881
  * Execute the transfer to agent action
4596
4882
  */
@@ -4603,6 +4889,7 @@ var TransferToAgentTool = class extends BaseTool {
4603
4889
  // src/tools/common/load-memory-tool.ts
4604
4890
  init_logger();
4605
4891
  init_base_tool();
4892
+ import { Type as Type9 } from "@google/genai";
4606
4893
  var LoadMemoryTool = class extends BaseTool {
4607
4894
  logger = new Logger({ name: "LoadMemoryTool" });
4608
4895
  /**
@@ -4622,10 +4909,10 @@ var LoadMemoryTool = class extends BaseTool {
4622
4909
  name: this.name,
4623
4910
  description: this.description,
4624
4911
  parameters: {
4625
- type: "object",
4912
+ type: Type9.OBJECT,
4626
4913
  properties: {
4627
4914
  query: {
4628
- type: "string",
4915
+ type: Type9.STRING,
4629
4916
  description: "The query to load memories for"
4630
4917
  }
4631
4918
  },
@@ -4656,6 +4943,7 @@ var LoadMemoryTool = class extends BaseTool {
4656
4943
 
4657
4944
  // src/tools/common/load-artifacts-tool.ts
4658
4945
  init_base_tool();
4946
+ import { Type as Type10 } from "@google/genai";
4659
4947
  var LoadArtifactsTool = class extends BaseTool {
4660
4948
  constructor() {
4661
4949
  super({
@@ -4671,12 +4959,12 @@ var LoadArtifactsTool = class extends BaseTool {
4671
4959
  name: this.name,
4672
4960
  description: this.description,
4673
4961
  parameters: {
4674
- type: "object",
4962
+ type: Type10.OBJECT,
4675
4963
  properties: {
4676
4964
  artifact_names: {
4677
- type: "array",
4965
+ type: Type10.ARRAY,
4678
4966
  items: {
4679
- type: "string"
4967
+ type: Type10.STRING
4680
4968
  },
4681
4969
  description: "List of artifact names to load"
4682
4970
  }
@@ -5295,6 +5583,7 @@ init_logger();
5295
5583
  init_base_tool();
5296
5584
 
5297
5585
  // src/tools/mcp/schema-conversion.ts
5586
+ import { Type as Type11 } from "@google/genai";
5298
5587
  function adkToMcpToolType(tool) {
5299
5588
  const declaration = tool.getDeclaration();
5300
5589
  const params = declarationToJsonSchema(declaration);
@@ -5323,13 +5612,13 @@ function jsonSchemaToDeclaration(name, description, schema) {
5323
5612
  parameters = schema;
5324
5613
  } else {
5325
5614
  parameters = {
5326
- type: "object",
5615
+ type: Type11.OBJECT,
5327
5616
  properties: schema
5328
5617
  };
5329
5618
  }
5330
5619
  } else {
5331
5620
  parameters = {
5332
- type: "object",
5621
+ type: Type11.OBJECT,
5333
5622
  properties: {}
5334
5623
  };
5335
5624
  }
@@ -5341,7 +5630,7 @@ function jsonSchemaToDeclaration(name, description, schema) {
5341
5630
  }
5342
5631
  function normalizeJsonSchema(schema) {
5343
5632
  if (!schema) {
5344
- return { type: "object", properties: {} };
5633
+ return { type: Type11.OBJECT, properties: {} };
5345
5634
  }
5346
5635
  const normalizedSchema = { ...schema };
5347
5636
  if (!normalizedSchema.type) {
@@ -5358,39 +5647,39 @@ function normalizeJsonSchema(schema) {
5358
5647
  case "integer":
5359
5648
  return normalizeNumberSchema(normalizedSchema);
5360
5649
  case "boolean":
5361
- return { type: "boolean" };
5650
+ return { type: Type11.BOOLEAN };
5362
5651
  case "null":
5363
- return { type: "null" };
5652
+ return { type: Type11.NULL };
5364
5653
  default:
5365
5654
  return normalizedSchema;
5366
5655
  }
5367
5656
  }
5368
5657
  function determineSchemaType(schema) {
5369
5658
  if (schema.properties || schema.required || schema.additionalProperties !== void 0) {
5370
- return "object";
5659
+ return Type11.OBJECT;
5371
5660
  }
5372
5661
  if (schema.items) {
5373
- return "array";
5662
+ return Type11.ARRAY;
5374
5663
  }
5375
5664
  if (schema.enum !== void 0) {
5376
- if (schema.enum.length === 0) return "string";
5665
+ if (schema.enum.length === 0) return Type11.STRING;
5377
5666
  const firstItem = schema.enum[0];
5378
- if (typeof firstItem === "string") return "string";
5379
- if (typeof firstItem === "number") return "number";
5380
- if (typeof firstItem === "boolean") return "boolean";
5381
- return "string";
5667
+ if (typeof firstItem === "string") return Type11.STRING;
5668
+ if (typeof firstItem === "number") return Type11.NUMBER;
5669
+ if (typeof firstItem === "boolean") return Type11.BOOLEAN;
5670
+ return Type11.STRING;
5382
5671
  }
5383
5672
  if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern) {
5384
- return "string";
5673
+ return Type11.STRING;
5385
5674
  }
5386
5675
  if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.exclusiveMinimum !== void 0 || schema.exclusiveMaximum !== void 0) {
5387
- return schema.multipleOf === void 0 || schema.multipleOf % 1 === 0 ? "integer" : "number";
5676
+ return schema.multipleOf === void 0 || schema.multipleOf % 1 === 0 ? Type11.INTEGER : Type11.NUMBER;
5388
5677
  }
5389
- return "object";
5678
+ return Type11.OBJECT;
5390
5679
  }
5391
5680
  function normalizeObjectSchema(schema) {
5392
5681
  const normalizedSchema = {
5393
- type: "object",
5682
+ type: Type11.OBJECT,
5394
5683
  properties: {}
5395
5684
  };
5396
5685
  if (schema.properties) {
@@ -5402,15 +5691,13 @@ function normalizeObjectSchema(schema) {
5402
5691
  }
5403
5692
  }
5404
5693
  if (schema.required) normalizedSchema.required = schema.required;
5405
- if (schema.additionalProperties !== void 0)
5406
- normalizedSchema.additionalProperties = schema.additionalProperties;
5407
5694
  if (schema.title) normalizedSchema.title = schema.title;
5408
5695
  if (schema.description) normalizedSchema.description = schema.description;
5409
5696
  return normalizedSchema;
5410
5697
  }
5411
5698
  function normalizeArraySchema(schema) {
5412
5699
  const normalizedSchema = {
5413
- type: "array"
5700
+ type: Type11.ARRAY
5414
5701
  };
5415
5702
  if (schema.items) {
5416
5703
  normalizedSchema.items = normalizeJsonSchema(
@@ -5421,15 +5708,13 @@ function normalizeArraySchema(schema) {
5421
5708
  normalizedSchema.minItems = schema.minItems;
5422
5709
  if (schema.maxItems !== void 0)
5423
5710
  normalizedSchema.maxItems = schema.maxItems;
5424
- if (schema.uniqueItems !== void 0)
5425
- normalizedSchema.uniqueItems = schema.uniqueItems;
5426
5711
  if (schema.title) normalizedSchema.title = schema.title;
5427
5712
  if (schema.description) normalizedSchema.description = schema.description;
5428
5713
  return normalizedSchema;
5429
5714
  }
5430
5715
  function normalizeStringSchema(schema) {
5431
5716
  const normalizedSchema = {
5432
- type: "string"
5717
+ type: Type11.STRING
5433
5718
  };
5434
5719
  if (schema.minLength !== void 0)
5435
5720
  normalizedSchema.minLength = schema.minLength;
@@ -5448,12 +5733,6 @@ function normalizeNumberSchema(schema) {
5448
5733
  };
5449
5734
  if (schema.minimum !== void 0) normalizedSchema.minimum = schema.minimum;
5450
5735
  if (schema.maximum !== void 0) normalizedSchema.maximum = schema.maximum;
5451
- if (schema.exclusiveMinimum !== void 0)
5452
- normalizedSchema.exclusiveMinimum = schema.exclusiveMinimum;
5453
- if (schema.exclusiveMaximum !== void 0)
5454
- normalizedSchema.exclusiveMaximum = schema.exclusiveMaximum;
5455
- if (schema.multipleOf !== void 0)
5456
- normalizedSchema.multipleOf = schema.multipleOf;
5457
5736
  if (schema.enum) normalizedSchema.enum = schema.enum;
5458
5737
  if (schema.title) normalizedSchema.title = schema.title;
5459
5738
  if (schema.description) normalizedSchema.description = schema.description;
@@ -5468,7 +5747,7 @@ function mcpSchemaToParameters(mcpTool) {
5468
5747
  }
5469
5748
  if (!schema) {
5470
5749
  return {
5471
- type: "object",
5750
+ type: Type11.OBJECT,
5472
5751
  properties: {}
5473
5752
  };
5474
5753
  }
@@ -5961,7 +6240,7 @@ function generateAuthEvent(invocationContext, functionResponseEvent) {
5961
6240
  }
5962
6241
  async function handleFunctionCallsAsync(invocationContext, functionCallEvent, toolsDict, filters) {
5963
6242
  const agent = invocationContext.agent;
5964
- if (!isLlmAgent(agent)) {
6243
+ if (!isLlmAgent2(agent)) {
5965
6244
  return null;
5966
6245
  }
5967
6246
  const functionCalls = functionCallEvent.getFunctionCalls();
@@ -6085,7 +6364,7 @@ function mergeParallelFunctionResponseEvents(functionResponseEvents) {
6085
6364
  mergedEvent.timestamp = baseEvent.timestamp;
6086
6365
  return mergedEvent;
6087
6366
  }
6088
- function isLlmAgent(agent) {
6367
+ function isLlmAgent2(agent) {
6089
6368
  return agent && typeof agent === "object" && "canonicalModel" in agent;
6090
6369
  }
6091
6370
 
@@ -8133,6 +8412,42 @@ function removeThoughtFromRequest(llmRequest) {
8133
8412
  var requestProcessor7 = new NlPlanningRequestProcessor();
8134
8413
  var responseProcessor2 = new NlPlanningResponseProcessor();
8135
8414
 
8415
+ // src/flows/llm-flows/shared-memory.ts
8416
+ var SharedMemoryRequestProcessor = class extends BaseLlmRequestProcessor {
8417
+ async *runAsync(invocationContext, llmRequest) {
8418
+ const memoryService = invocationContext.memoryService;
8419
+ if (!memoryService) return;
8420
+ const lastUserEvent = invocationContext.session.events.findLast((e) => e.author === "user" && e.content?.parts?.length);
8421
+ if (!lastUserEvent) return;
8422
+ const query = (lastUserEvent.content.parts ?? []).map((p) => p.text || "").join(" ");
8423
+ const results = await memoryService.searchMemory({
8424
+ appName: invocationContext.appName,
8425
+ userId: invocationContext.userId,
8426
+ query
8427
+ });
8428
+ const sessionTexts = new Set(
8429
+ (llmRequest.contents || []).flatMap(
8430
+ (c) => c.parts?.map((p) => p.text) || []
8431
+ )
8432
+ );
8433
+ for (const memory of results.memories) {
8434
+ const memoryText = (memory.content.parts ?? []).map((p) => p.text || "").join(" ");
8435
+ if (!sessionTexts.has(memoryText)) {
8436
+ llmRequest.contents = llmRequest.contents || [];
8437
+ llmRequest.contents.push({
8438
+ role: "user",
8439
+ parts: [
8440
+ {
8441
+ text: `[${memory.author}] said: ${memoryText}`
8442
+ }
8443
+ ]
8444
+ });
8445
+ }
8446
+ }
8447
+ }
8448
+ };
8449
+ var sharedMemoryRequestProcessor = new SharedMemoryRequestProcessor();
8450
+
8136
8451
  // src/flows/llm-flows/single-flow.ts
8137
8452
  var SingleFlow = class extends BaseLlmFlow {
8138
8453
  /**
@@ -8147,6 +8462,7 @@ var SingleFlow = class extends BaseLlmFlow {
8147
8462
  requestProcessor6,
8148
8463
  requestProcessor5,
8149
8464
  requestProcessor4,
8465
+ sharedMemoryRequestProcessor,
8150
8466
  // Some implementations of NL Planning mark planning contents as thoughts
8151
8467
  // in the post processor. Since these need to be unmarked, NL Planning
8152
8468
  // should be after contents.
@@ -8168,12 +8484,12 @@ var SingleFlow = class extends BaseLlmFlow {
8168
8484
  };
8169
8485
 
8170
8486
  // src/flows/llm-flows/agent-transfer.ts
8487
+ import dedent from "dedent";
8171
8488
  var AgentTransferLlmRequestProcessor = class extends BaseLlmRequestProcessor {
8172
8489
  /**
8173
8490
  * Processes agent transfer by adding transfer instructions and tools
8174
8491
  * if the agent has transfer targets available
8175
8492
  */
8176
- // eslint-disable-next-line @typescript-eslint/require-yield
8177
8493
  async *runAsync(invocationContext, llmRequest) {
8178
8494
  const agent = invocationContext.agent;
8179
8495
  if (!("subAgents" in agent) || typeof agent.subAgents !== "object") {
@@ -8187,71 +8503,65 @@ var AgentTransferLlmRequestProcessor = class extends BaseLlmRequestProcessor {
8187
8503
  agent,
8188
8504
  transferTargets
8189
8505
  );
8190
- if (llmRequest.appendInstructions) {
8191
- llmRequest.appendInstructions([transferInstructions]);
8192
- } else {
8193
- const existingInstructions = llmRequest.instructions || "";
8194
- llmRequest.instructions = `${existingInstructions}
8195
-
8196
- ${transferInstructions}`;
8197
- }
8506
+ llmRequest.appendInstructions([transferInstructions]);
8198
8507
  const transferToAgentTool = new TransferToAgentTool();
8199
8508
  const toolContext = new ToolContext(invocationContext);
8200
8509
  await transferToAgentTool.processLlmRequest(toolContext, llmRequest);
8201
- for await (const _ of []) {
8202
- yield _;
8510
+ const shouldYield = false;
8511
+ if (shouldYield) {
8512
+ yield {};
8203
8513
  }
8204
8514
  }
8205
8515
  };
8206
8516
  function buildTargetAgentsInfo(targetAgent) {
8207
- return `
8208
- Agent name: ${targetAgent.name}
8209
- Agent description: ${targetAgent.description}
8210
- `;
8517
+ return dedent`
8518
+ Agent name: ${targetAgent.name}
8519
+ Agent description: ${targetAgent.description}
8520
+ `;
8211
8521
  }
8212
8522
  function buildTargetAgentsInstructions(agent, targetAgents) {
8213
8523
  const lineBreak = "\n";
8214
8524
  const transferFunctionName = "transfer_to_agent";
8215
- let instructions = `
8216
- You have a list of other agents to transfer to:
8525
+ let instructions = dedent`
8526
+ You have a list of other agents to transfer to:
8217
8527
 
8218
- ${targetAgents.map((targetAgent) => buildTargetAgentsInfo(targetAgent)).join(lineBreak)}
8528
+ ${targetAgents.map((targetAgent) => buildTargetAgentsInfo(targetAgent)).join(lineBreak)}
8219
8529
 
8220
- If you are the best to answer the question according to your description, you
8221
- can answer it.
8530
+ If you are the best to answer the question according to your description, you
8531
+ can answer it.
8222
8532
 
8223
- If another agent is better for answering the question according to its
8224
- description, call \`${transferFunctionName}\` function to transfer the
8225
- question to that agent. When transferring, do not generate any text other than
8226
- the function call.
8533
+ If another agent is better for answering the question according to its
8534
+ description, call \`${transferFunctionName}\` function to transfer the
8535
+ question to that agent. When transferring, do not generate any text other than
8536
+ the function call.
8227
8537
  `;
8228
8538
  if (agent.parentAgent && !agent.disallowTransferToParent) {
8229
- instructions += `
8230
- Your parent agent is ${agent.parentAgent.name}. If neither the other agents nor
8231
- you are best for answering the question according to the descriptions, transfer
8232
- to your parent agent.
8233
- `;
8539
+ instructions += dedent`
8540
+ Your parent agent is ${agent.parentAgent.name}. If neither the other agents nor
8541
+ you are best for answering the question according to the descriptions, transfer
8542
+ to your parent agent.
8543
+ `;
8234
8544
  }
8235
8545
  return instructions;
8236
8546
  }
8237
8547
  function getTransferTargets(agent) {
8238
- const result = [];
8548
+ const targets = [];
8239
8549
  if (agent.subAgents && Array.isArray(agent.subAgents)) {
8240
- result.push(...agent.subAgents);
8550
+ targets.push(...agent.subAgents);
8241
8551
  }
8242
8552
  if (!agent.parentAgent || !("subAgents" in agent.parentAgent)) {
8243
- return result;
8553
+ return targets;
8244
8554
  }
8245
8555
  if (!agent.disallowTransferToParent) {
8246
- result.push(agent.parentAgent);
8556
+ targets.push(agent.parentAgent);
8247
8557
  }
8248
8558
  if (!agent.disallowTransferToPeers && agent.parentAgent.subAgents) {
8249
8559
  const peerAgents = agent.parentAgent.subAgents.filter(
8250
8560
  (peerAgent) => peerAgent.name !== agent.name
8251
8561
  );
8252
- result.push(...peerAgents);
8562
+ targets.push(...peerAgents);
8253
8563
  }
8254
- return result;
8564
+ return targets;
8255
8565
  }
8256
8566
  var requestProcessor8 = new AgentTransferLlmRequestProcessor();
8257
8567
 
@@ -8353,7 +8663,10 @@ var LlmAgent = class _LlmAgent extends BaseAgent {
8353
8663
  constructor(config) {
8354
8664
  super({
8355
8665
  name: config.name,
8356
- description: config.description
8666
+ description: config.description,
8667
+ subAgents: config.subAgents,
8668
+ beforeAgentCallback: config.beforeAgentCallback,
8669
+ afterAgentCallback: config.afterAgentCallback
8357
8670
  });
8358
8671
  this.model = config.model || "";
8359
8672
  this.instruction = config.instruction || "";
@@ -8549,155 +8862,6 @@ do not generate any text other than the function call.`;
8549
8862
  }
8550
8863
  };
8551
8864
 
8552
- // src/agents/invocation-context.ts
8553
- var LlmCallsLimitExceededError = class extends Error {
8554
- constructor(message) {
8555
- super(message);
8556
- this.name = "LlmCallsLimitExceededError";
8557
- }
8558
- };
8559
- var InvocationCostManager = class {
8560
- /**
8561
- * A counter that keeps track of number of llm calls made.
8562
- */
8563
- _numberOfLlmCalls = 0;
8564
- /**
8565
- * Increments _numberOfLlmCalls and enforces the limit.
8566
- */
8567
- incrementAndEnforceLlmCallsLimit(runConfig) {
8568
- this._numberOfLlmCalls += 1;
8569
- if (runConfig && runConfig.maxLlmCalls > 0 && this._numberOfLlmCalls > runConfig.maxLlmCalls) {
8570
- throw new LlmCallsLimitExceededError(
8571
- `Max number of llm calls limit of \`${runConfig.maxLlmCalls}\` exceeded`
8572
- );
8573
- }
8574
- }
8575
- };
8576
- function newInvocationContextId() {
8577
- return `e-${crypto.randomUUID()}`;
8578
- }
8579
- var InvocationContext = class _InvocationContext {
8580
- artifactService;
8581
- sessionService;
8582
- memoryService;
8583
- /**
8584
- * The id of this invocation context. Readonly.
8585
- */
8586
- invocationId;
8587
- /**
8588
- * The branch of the invocation context.
8589
- *
8590
- * The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of
8591
- * agent_2, and agent_2 is the parent of agent_3.
8592
- *
8593
- * Branch is used when multiple sub-agents shouldn't see their peer agents'
8594
- * conversation history.
8595
- */
8596
- branch;
8597
- /**
8598
- * The current agent of this invocation context. Readonly.
8599
- */
8600
- agent;
8601
- /**
8602
- * The user content that started this invocation. Readonly.
8603
- */
8604
- userContent;
8605
- /**
8606
- * The current session of this invocation context. Readonly.
8607
- */
8608
- session;
8609
- /**
8610
- * Whether to end this invocation.
8611
- *
8612
- * Set to True in callbacks or tools to terminate this invocation.
8613
- */
8614
- endInvocation = false;
8615
- /**
8616
- * The queue to receive live requests.
8617
- */
8618
- liveRequestQueue;
8619
- /**
8620
- * The running streaming tools of this invocation.
8621
- */
8622
- activeStreamingTools;
8623
- /**
8624
- * Caches necessary, data audio or contents, that are needed by transcription.
8625
- */
8626
- transcriptionCache;
8627
- /**
8628
- * Configurations for live agents under this invocation.
8629
- */
8630
- runConfig;
8631
- /**
8632
- * A container to keep track of different kinds of costs incurred as a part
8633
- * of this invocation.
8634
- */
8635
- _invocationCostManager = new InvocationCostManager();
8636
- /**
8637
- * Constructor for InvocationContext
8638
- */
8639
- constructor(options) {
8640
- this.artifactService = options.artifactService;
8641
- this.sessionService = options.sessionService;
8642
- this.memoryService = options.memoryService;
8643
- this.invocationId = options.invocationId || newInvocationContextId();
8644
- this.branch = options.branch;
8645
- this.agent = options.agent;
8646
- this.userContent = options.userContent;
8647
- this.session = options.session;
8648
- this.endInvocation = options.endInvocation || false;
8649
- this.liveRequestQueue = options.liveRequestQueue;
8650
- this.activeStreamingTools = options.activeStreamingTools;
8651
- this.transcriptionCache = options.transcriptionCache;
8652
- this.runConfig = options.runConfig;
8653
- }
8654
- /**
8655
- * App name from the session
8656
- */
8657
- get appName() {
8658
- return this.session.appName;
8659
- }
8660
- /**
8661
- * User ID from the session
8662
- */
8663
- get userId() {
8664
- return this.session.userId;
8665
- }
8666
- /**
8667
- * Tracks number of llm calls made.
8668
- *
8669
- * @throws {LlmCallsLimitExceededError} If number of llm calls made exceed the set threshold.
8670
- */
8671
- incrementLlmCallCount() {
8672
- this._invocationCostManager.incrementAndEnforceLlmCallsLimit(
8673
- this.runConfig
8674
- );
8675
- }
8676
- /**
8677
- * Creates a child invocation context for a sub-agent
8678
- */
8679
- createChildContext(agent) {
8680
- return new _InvocationContext({
8681
- artifactService: this.artifactService,
8682
- sessionService: this.sessionService,
8683
- memoryService: this.memoryService,
8684
- invocationId: this.invocationId,
8685
- // Keep same invocation ID
8686
- branch: this.branch ? `${this.branch}.${agent.name}` : agent.name,
8687
- // Update branch
8688
- agent,
8689
- // Update to the new agent
8690
- userContent: this.userContent,
8691
- session: this.session,
8692
- endInvocation: this.endInvocation,
8693
- liveRequestQueue: this.liveRequestQueue,
8694
- activeStreamingTools: this.activeStreamingTools,
8695
- transcriptionCache: this.transcriptionCache,
8696
- runConfig: this.runConfig
8697
- });
8698
- }
8699
- };
8700
-
8701
8865
  // src/agents/parallel-agent.ts
8702
8866
  function createBranchContextForSubAgent(agent, subAgent, invocationContext) {
8703
8867
  const branchSuffix = `${agent.name}.${subAgent.name}`;
@@ -9745,6 +9909,9 @@ var Runner = class {
9745
9909
  )) {
9746
9910
  if (!event.partial) {
9747
9911
  await this.sessionService.appendEvent(session, event);
9912
+ if (this.memoryService) {
9913
+ await this.memoryService.addSessionToMemory(session);
9914
+ }
9748
9915
  }
9749
9916
  yield event;
9750
9917
  }
@@ -9885,10 +10052,12 @@ var InMemoryRunner = class extends Runner {
9885
10052
  // src/agents/agent-builder.ts
9886
10053
  var AgentBuilder = class _AgentBuilder {
9887
10054
  config;
9888
- sessionConfig;
10055
+ sessionService;
10056
+ sessionOptions;
9889
10057
  memoryService;
9890
10058
  artifactService;
9891
10059
  agentType = "llm";
10060
+ existingSession;
9892
10061
  /**
9893
10062
  * Private constructor - use static create() method
9894
10063
  */
@@ -9956,6 +10125,51 @@ var AgentBuilder = class _AgentBuilder {
9956
10125
  this.config.planner = planner;
9957
10126
  return this;
9958
10127
  }
10128
+ /**
10129
+ * Set the code executor for the agent
10130
+ * @param codeExecutor The code executor to use for running code
10131
+ * @returns This builder instance for chaining
10132
+ */
10133
+ withCodeExecutor(codeExecutor) {
10134
+ this.config.codeExecutor = codeExecutor;
10135
+ return this;
10136
+ }
10137
+ /**
10138
+ * Set the output key for the agent
10139
+ * @param outputKey The output key in session state to store the output of the agent
10140
+ * @returns This builder instance for chaining
10141
+ */
10142
+ withOutputKey(outputKey) {
10143
+ this.config.outputKey = outputKey;
10144
+ return this;
10145
+ }
10146
+ /**
10147
+ * Add sub-agents to the agent
10148
+ * @param subAgents Sub-agents to add to the agent
10149
+ * @returns This builder instance for chaining
10150
+ */
10151
+ withSubAgents(subAgents) {
10152
+ this.config.subAgents = subAgents;
10153
+ return this;
10154
+ }
10155
+ /**
10156
+ * Set the before agent callback
10157
+ * @param callback Callback to invoke before agent execution
10158
+ * @returns This builder instance for chaining
10159
+ */
10160
+ withBeforeAgentCallback(callback) {
10161
+ this.config.beforeAgentCallback = callback;
10162
+ return this;
10163
+ }
10164
+ /**
10165
+ * Set the after agent callback
10166
+ * @param callback Callback to invoke after agent execution
10167
+ * @returns This builder instance for chaining
10168
+ */
10169
+ withAfterAgentCallback(callback) {
10170
+ this.config.afterAgentCallback = callback;
10171
+ return this;
10172
+ }
9959
10173
  /**
9960
10174
  * Configure as a sequential agent
9961
10175
  * @param subAgents Sub-agents to execute in sequence
@@ -10006,14 +10220,38 @@ var AgentBuilder = class _AgentBuilder {
10006
10220
  * @param options Session configuration options (userId and appName)
10007
10221
  * @returns This builder instance for chaining
10008
10222
  */
10009
- withSession(service, options = {}) {
10010
- this.sessionConfig = {
10011
- service,
10223
+ withSessionService(service, options = {}) {
10224
+ this.sessionService = service;
10225
+ this.sessionOptions = {
10012
10226
  userId: options.userId || this.generateDefaultUserId(),
10013
- appName: options.appName || this.generateDefaultAppName()
10227
+ appName: options.appName || this.generateDefaultAppName(),
10228
+ state: options.state,
10229
+ sessionId: options.sessionId
10014
10230
  };
10015
10231
  return this;
10016
10232
  }
10233
+ /**
10234
+ * Configure with an existing session instance
10235
+ * @param session Existing session to use
10236
+ * @returns This builder instance for chaining
10237
+ * @throws Error if no session service has been configured via withSessionService()
10238
+ */
10239
+ withSession(session) {
10240
+ if (!this.sessionService) {
10241
+ throw new Error(
10242
+ "Session service must be configured before using withSession(). Call withSessionService() first, or use withQuickSession() for in-memory sessions."
10243
+ );
10244
+ }
10245
+ this.sessionOptions = {
10246
+ ...this.sessionOptions,
10247
+ userId: session.userId,
10248
+ appName: session.appName,
10249
+ sessionId: session.id,
10250
+ state: session.state
10251
+ };
10252
+ this.existingSession = session;
10253
+ return this;
10254
+ }
10017
10255
  /**
10018
10256
  * Configure memory service for the agent
10019
10257
  * @param memoryService Memory service to use for conversation history and context
@@ -10039,7 +10277,7 @@ var AgentBuilder = class _AgentBuilder {
10039
10277
  * @returns This builder instance for chaining
10040
10278
  */
10041
10279
  withQuickSession(options = {}) {
10042
- return this.withSession(new InMemorySessionService(), options);
10280
+ return this.withSessionService(new InMemorySessionService(), options);
10043
10281
  }
10044
10282
  /**
10045
10283
  * Build the agent and optionally create runner and session
@@ -10049,18 +10287,24 @@ var AgentBuilder = class _AgentBuilder {
10049
10287
  const agent = this.createAgent();
10050
10288
  let runner;
10051
10289
  let session;
10052
- if (!this.sessionConfig) {
10290
+ if (!this.sessionService) {
10053
10291
  this.withQuickSession();
10054
10292
  }
10055
- if (this.sessionConfig) {
10056
- session = await this.sessionConfig.service.createSession(
10057
- this.sessionConfig.appName,
10058
- this.sessionConfig.userId
10059
- );
10293
+ if (this.sessionService && this.sessionOptions) {
10294
+ if (this.existingSession) {
10295
+ session = this.existingSession;
10296
+ } else {
10297
+ session = await this.sessionService.createSession(
10298
+ this.sessionOptions.appName,
10299
+ this.sessionOptions.userId,
10300
+ this.sessionOptions.state,
10301
+ this.sessionOptions.sessionId
10302
+ );
10303
+ }
10060
10304
  const runnerConfig = {
10061
- appName: this.sessionConfig.appName,
10305
+ appName: this.sessionOptions.appName,
10062
10306
  agent,
10063
- sessionService: this.sessionConfig.service,
10307
+ sessionService: this.sessionService,
10064
10308
  memoryService: this.memoryService,
10065
10309
  artifactService: this.artifactService
10066
10310
  };
@@ -10095,7 +10339,15 @@ var AgentBuilder = class _AgentBuilder {
10095
10339
  description: this.config.description,
10096
10340
  instruction: this.config.instruction,
10097
10341
  tools: this.config.tools,
10098
- planner: this.config.planner
10342
+ planner: this.config.planner,
10343
+ codeExecutor: this.config.codeExecutor,
10344
+ subAgents: this.config.subAgents,
10345
+ beforeAgentCallback: this.config.beforeAgentCallback,
10346
+ afterAgentCallback: this.config.afterAgentCallback,
10347
+ memoryService: this.memoryService,
10348
+ artifactService: this.artifactService,
10349
+ outputKey: this.config.outputKey,
10350
+ sessionService: this.sessionService
10099
10351
  });
10100
10352
  }
10101
10353
  case "sequential":
@@ -10160,16 +10412,16 @@ var AgentBuilder = class _AgentBuilder {
10160
10412
  * @returns Enhanced runner with simplified API
10161
10413
  */
10162
10414
  createEnhancedRunner(baseRunner, session) {
10163
- const sessionConfig = this.sessionConfig;
10415
+ const sessionOptions = this.sessionOptions;
10164
10416
  return {
10165
10417
  async ask(message) {
10166
10418
  const newMessage = typeof message === "string" ? { parts: [{ text: message }] } : typeof message === "object" && "contents" in message ? { parts: message.contents[message.contents.length - 1].parts } : message;
10167
10419
  let response = "";
10168
- if (!sessionConfig) {
10420
+ if (!sessionOptions?.userId) {
10169
10421
  throw new Error("Session configuration is required");
10170
10422
  }
10171
10423
  for await (const event of baseRunner.runAsync({
10172
- userId: sessionConfig.userId,
10424
+ userId: sessionOptions.userId,
10173
10425
  sessionId: session.id,
10174
10426
  newMessage
10175
10427
  })) {
@@ -10182,7 +10434,7 @@ var AgentBuilder = class _AgentBuilder {
10182
10434
  }
10183
10435
  }
10184
10436
  }
10185
- return response;
10437
+ return response.trim();
10186
10438
  },
10187
10439
  runAsync(params) {
10188
10440
  return baseRunner.runAsync(params);
@@ -10924,11 +11176,11 @@ var DatabaseSessionService = class extends BaseSessionService {
10924
11176
  };
10925
11177
 
10926
11178
  // src/sessions/database-factories.ts
10927
- import dedent from "dedent";
11179
+ import dedent2 from "dedent";
10928
11180
  import { Kysely, MysqlDialect, PostgresDialect, SqliteDialect } from "kysely";
10929
11181
  function createDependencyError(packageName, dbType) {
10930
11182
  return new Error(
10931
- dedent`
11183
+ dedent2`
10932
11184
  Missing required peer dependency: ${packageName}
10933
11185
  To use ${dbType} sessions, install the required package:
10934
11186
  npm install ${packageName}
@@ -11182,6 +11434,7 @@ export {
11182
11434
  AF_FUNCTION_CALL_ID_PREFIX,
11183
11435
  LlmAgent as Agent,
11184
11436
  AgentBuilder,
11437
+ AgentTool,
11185
11438
  agents_exports as Agents,
11186
11439
  AiSdkLlm,
11187
11440
  AnthropicLlm,