@iqai/adk 0.1.13 → 0.1.14

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
  },
@@ -4603,6 +4869,7 @@ var TransferToAgentTool = class extends BaseTool {
4603
4869
  // src/tools/common/load-memory-tool.ts
4604
4870
  init_logger();
4605
4871
  init_base_tool();
4872
+ import { Type as Type8 } from "@google/genai";
4606
4873
  var LoadMemoryTool = class extends BaseTool {
4607
4874
  logger = new Logger({ name: "LoadMemoryTool" });
4608
4875
  /**
@@ -4622,10 +4889,10 @@ var LoadMemoryTool = class extends BaseTool {
4622
4889
  name: this.name,
4623
4890
  description: this.description,
4624
4891
  parameters: {
4625
- type: "object",
4892
+ type: Type8.OBJECT,
4626
4893
  properties: {
4627
4894
  query: {
4628
- type: "string",
4895
+ type: Type8.STRING,
4629
4896
  description: "The query to load memories for"
4630
4897
  }
4631
4898
  },
@@ -4656,6 +4923,7 @@ var LoadMemoryTool = class extends BaseTool {
4656
4923
 
4657
4924
  // src/tools/common/load-artifacts-tool.ts
4658
4925
  init_base_tool();
4926
+ import { Type as Type9 } from "@google/genai";
4659
4927
  var LoadArtifactsTool = class extends BaseTool {
4660
4928
  constructor() {
4661
4929
  super({
@@ -4671,12 +4939,12 @@ var LoadArtifactsTool = class extends BaseTool {
4671
4939
  name: this.name,
4672
4940
  description: this.description,
4673
4941
  parameters: {
4674
- type: "object",
4942
+ type: Type9.OBJECT,
4675
4943
  properties: {
4676
4944
  artifact_names: {
4677
- type: "array",
4945
+ type: Type9.ARRAY,
4678
4946
  items: {
4679
- type: "string"
4947
+ type: Type9.STRING
4680
4948
  },
4681
4949
  description: "List of artifact names to load"
4682
4950
  }
@@ -5295,6 +5563,7 @@ init_logger();
5295
5563
  init_base_tool();
5296
5564
 
5297
5565
  // src/tools/mcp/schema-conversion.ts
5566
+ import { Type as Type10 } from "@google/genai";
5298
5567
  function adkToMcpToolType(tool) {
5299
5568
  const declaration = tool.getDeclaration();
5300
5569
  const params = declarationToJsonSchema(declaration);
@@ -5323,13 +5592,13 @@ function jsonSchemaToDeclaration(name, description, schema) {
5323
5592
  parameters = schema;
5324
5593
  } else {
5325
5594
  parameters = {
5326
- type: "object",
5595
+ type: Type10.OBJECT,
5327
5596
  properties: schema
5328
5597
  };
5329
5598
  }
5330
5599
  } else {
5331
5600
  parameters = {
5332
- type: "object",
5601
+ type: Type10.OBJECT,
5333
5602
  properties: {}
5334
5603
  };
5335
5604
  }
@@ -5341,7 +5610,7 @@ function jsonSchemaToDeclaration(name, description, schema) {
5341
5610
  }
5342
5611
  function normalizeJsonSchema(schema) {
5343
5612
  if (!schema) {
5344
- return { type: "object", properties: {} };
5613
+ return { type: Type10.OBJECT, properties: {} };
5345
5614
  }
5346
5615
  const normalizedSchema = { ...schema };
5347
5616
  if (!normalizedSchema.type) {
@@ -5358,39 +5627,39 @@ function normalizeJsonSchema(schema) {
5358
5627
  case "integer":
5359
5628
  return normalizeNumberSchema(normalizedSchema);
5360
5629
  case "boolean":
5361
- return { type: "boolean" };
5630
+ return { type: Type10.BOOLEAN };
5362
5631
  case "null":
5363
- return { type: "null" };
5632
+ return { type: Type10.NULL };
5364
5633
  default:
5365
5634
  return normalizedSchema;
5366
5635
  }
5367
5636
  }
5368
5637
  function determineSchemaType(schema) {
5369
5638
  if (schema.properties || schema.required || schema.additionalProperties !== void 0) {
5370
- return "object";
5639
+ return Type10.OBJECT;
5371
5640
  }
5372
5641
  if (schema.items) {
5373
- return "array";
5642
+ return Type10.ARRAY;
5374
5643
  }
5375
5644
  if (schema.enum !== void 0) {
5376
- if (schema.enum.length === 0) return "string";
5645
+ if (schema.enum.length === 0) return Type10.STRING;
5377
5646
  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";
5647
+ if (typeof firstItem === "string") return Type10.STRING;
5648
+ if (typeof firstItem === "number") return Type10.NUMBER;
5649
+ if (typeof firstItem === "boolean") return Type10.BOOLEAN;
5650
+ return Type10.STRING;
5382
5651
  }
5383
5652
  if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern) {
5384
- return "string";
5653
+ return Type10.STRING;
5385
5654
  }
5386
5655
  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";
5656
+ return schema.multipleOf === void 0 || schema.multipleOf % 1 === 0 ? Type10.INTEGER : Type10.NUMBER;
5388
5657
  }
5389
- return "object";
5658
+ return Type10.OBJECT;
5390
5659
  }
5391
5660
  function normalizeObjectSchema(schema) {
5392
5661
  const normalizedSchema = {
5393
- type: "object",
5662
+ type: Type10.OBJECT,
5394
5663
  properties: {}
5395
5664
  };
5396
5665
  if (schema.properties) {
@@ -5402,15 +5671,13 @@ function normalizeObjectSchema(schema) {
5402
5671
  }
5403
5672
  }
5404
5673
  if (schema.required) normalizedSchema.required = schema.required;
5405
- if (schema.additionalProperties !== void 0)
5406
- normalizedSchema.additionalProperties = schema.additionalProperties;
5407
5674
  if (schema.title) normalizedSchema.title = schema.title;
5408
5675
  if (schema.description) normalizedSchema.description = schema.description;
5409
5676
  return normalizedSchema;
5410
5677
  }
5411
5678
  function normalizeArraySchema(schema) {
5412
5679
  const normalizedSchema = {
5413
- type: "array"
5680
+ type: Type10.ARRAY
5414
5681
  };
5415
5682
  if (schema.items) {
5416
5683
  normalizedSchema.items = normalizeJsonSchema(
@@ -5421,15 +5688,13 @@ function normalizeArraySchema(schema) {
5421
5688
  normalizedSchema.minItems = schema.minItems;
5422
5689
  if (schema.maxItems !== void 0)
5423
5690
  normalizedSchema.maxItems = schema.maxItems;
5424
- if (schema.uniqueItems !== void 0)
5425
- normalizedSchema.uniqueItems = schema.uniqueItems;
5426
5691
  if (schema.title) normalizedSchema.title = schema.title;
5427
5692
  if (schema.description) normalizedSchema.description = schema.description;
5428
5693
  return normalizedSchema;
5429
5694
  }
5430
5695
  function normalizeStringSchema(schema) {
5431
5696
  const normalizedSchema = {
5432
- type: "string"
5697
+ type: Type10.STRING
5433
5698
  };
5434
5699
  if (schema.minLength !== void 0)
5435
5700
  normalizedSchema.minLength = schema.minLength;
@@ -5448,12 +5713,6 @@ function normalizeNumberSchema(schema) {
5448
5713
  };
5449
5714
  if (schema.minimum !== void 0) normalizedSchema.minimum = schema.minimum;
5450
5715
  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
5716
  if (schema.enum) normalizedSchema.enum = schema.enum;
5458
5717
  if (schema.title) normalizedSchema.title = schema.title;
5459
5718
  if (schema.description) normalizedSchema.description = schema.description;
@@ -5468,7 +5727,7 @@ function mcpSchemaToParameters(mcpTool) {
5468
5727
  }
5469
5728
  if (!schema) {
5470
5729
  return {
5471
- type: "object",
5730
+ type: Type10.OBJECT,
5472
5731
  properties: {}
5473
5732
  };
5474
5733
  }
@@ -5961,7 +6220,7 @@ function generateAuthEvent(invocationContext, functionResponseEvent) {
5961
6220
  }
5962
6221
  async function handleFunctionCallsAsync(invocationContext, functionCallEvent, toolsDict, filters) {
5963
6222
  const agent = invocationContext.agent;
5964
- if (!isLlmAgent(agent)) {
6223
+ if (!isLlmAgent2(agent)) {
5965
6224
  return null;
5966
6225
  }
5967
6226
  const functionCalls = functionCallEvent.getFunctionCalls();
@@ -6085,7 +6344,7 @@ function mergeParallelFunctionResponseEvents(functionResponseEvents) {
6085
6344
  mergedEvent.timestamp = baseEvent.timestamp;
6086
6345
  return mergedEvent;
6087
6346
  }
6088
- function isLlmAgent(agent) {
6347
+ function isLlmAgent2(agent) {
6089
6348
  return agent && typeof agent === "object" && "canonicalModel" in agent;
6090
6349
  }
6091
6350
 
@@ -8133,6 +8392,42 @@ function removeThoughtFromRequest(llmRequest) {
8133
8392
  var requestProcessor7 = new NlPlanningRequestProcessor();
8134
8393
  var responseProcessor2 = new NlPlanningResponseProcessor();
8135
8394
 
8395
+ // src/flows/llm-flows/shared-memory.ts
8396
+ var SharedMemoryRequestProcessor = class extends BaseLlmRequestProcessor {
8397
+ async *runAsync(invocationContext, llmRequest) {
8398
+ const memoryService = invocationContext.memoryService;
8399
+ if (!memoryService) return;
8400
+ const lastUserEvent = invocationContext.session.events.findLast((e) => e.author === "user" && e.content?.parts?.length);
8401
+ if (!lastUserEvent) return;
8402
+ const query = (lastUserEvent.content.parts ?? []).map((p) => p.text || "").join(" ");
8403
+ const results = await memoryService.searchMemory({
8404
+ appName: invocationContext.appName,
8405
+ userId: invocationContext.userId,
8406
+ query
8407
+ });
8408
+ const sessionTexts = new Set(
8409
+ (llmRequest.contents || []).flatMap(
8410
+ (c) => c.parts?.map((p) => p.text) || []
8411
+ )
8412
+ );
8413
+ for (const memory of results.memories) {
8414
+ const memoryText = (memory.content.parts ?? []).map((p) => p.text || "").join(" ");
8415
+ if (!sessionTexts.has(memoryText)) {
8416
+ llmRequest.contents = llmRequest.contents || [];
8417
+ llmRequest.contents.push({
8418
+ role: "user",
8419
+ parts: [
8420
+ {
8421
+ text: `[${memory.author}] said: ${memoryText}`
8422
+ }
8423
+ ]
8424
+ });
8425
+ }
8426
+ }
8427
+ }
8428
+ };
8429
+ var sharedMemoryRequestProcessor = new SharedMemoryRequestProcessor();
8430
+
8136
8431
  // src/flows/llm-flows/single-flow.ts
8137
8432
  var SingleFlow = class extends BaseLlmFlow {
8138
8433
  /**
@@ -8147,6 +8442,7 @@ var SingleFlow = class extends BaseLlmFlow {
8147
8442
  requestProcessor6,
8148
8443
  requestProcessor5,
8149
8444
  requestProcessor4,
8445
+ sharedMemoryRequestProcessor,
8150
8446
  // Some implementations of NL Planning mark planning contents as thoughts
8151
8447
  // in the post processor. Since these need to be unmarked, NL Planning
8152
8448
  // should be after contents.
@@ -8187,14 +8483,7 @@ var AgentTransferLlmRequestProcessor = class extends BaseLlmRequestProcessor {
8187
8483
  agent,
8188
8484
  transferTargets
8189
8485
  );
8190
- if (llmRequest.appendInstructions) {
8191
- llmRequest.appendInstructions([transferInstructions]);
8192
- } else {
8193
- const existingInstructions = llmRequest.instructions || "";
8194
- llmRequest.instructions = `${existingInstructions}
8195
-
8196
- ${transferInstructions}`;
8197
- }
8486
+ llmRequest.appendInstructions([transferInstructions]);
8198
8487
  const transferToAgentTool = new TransferToAgentTool();
8199
8488
  const toolContext = new ToolContext(invocationContext);
8200
8489
  await transferToAgentTool.processLlmRequest(toolContext, llmRequest);
@@ -8549,155 +8838,6 @@ do not generate any text other than the function call.`;
8549
8838
  }
8550
8839
  };
8551
8840
 
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
8841
  // src/agents/parallel-agent.ts
8702
8842
  function createBranchContextForSubAgent(agent, subAgent, invocationContext) {
8703
8843
  const branchSuffix = `${agent.name}.${subAgent.name}`;
@@ -9745,6 +9885,9 @@ var Runner = class {
9745
9885
  )) {
9746
9886
  if (!event.partial) {
9747
9887
  await this.sessionService.appendEvent(session, event);
9888
+ if (this.memoryService) {
9889
+ await this.memoryService.addSessionToMemory(session);
9890
+ }
9748
9891
  }
9749
9892
  yield event;
9750
9893
  }
@@ -9885,10 +10028,12 @@ var InMemoryRunner = class extends Runner {
9885
10028
  // src/agents/agent-builder.ts
9886
10029
  var AgentBuilder = class _AgentBuilder {
9887
10030
  config;
9888
- sessionConfig;
10031
+ sessionService;
10032
+ sessionOptions;
9889
10033
  memoryService;
9890
10034
  artifactService;
9891
10035
  agentType = "llm";
10036
+ existingSession;
9892
10037
  /**
9893
10038
  * Private constructor - use static create() method
9894
10039
  */
@@ -9956,6 +10101,24 @@ var AgentBuilder = class _AgentBuilder {
9956
10101
  this.config.planner = planner;
9957
10102
  return this;
9958
10103
  }
10104
+ /**
10105
+ * Set the code executor for the agent
10106
+ * @param codeExecutor The code executor to use for running code
10107
+ * @returns This builder instance for chaining
10108
+ */
10109
+ withCodeExecutor(codeExecutor) {
10110
+ this.config.codeExecutor = codeExecutor;
10111
+ return this;
10112
+ }
10113
+ /**
10114
+ * Set the output key for the agent
10115
+ * @param outputKey The output key in session state to store the output of the agent
10116
+ * @returns This builder instance for chaining
10117
+ */
10118
+ withOutputKey(outputKey) {
10119
+ this.config.outputKey = outputKey;
10120
+ return this;
10121
+ }
9959
10122
  /**
9960
10123
  * Configure as a sequential agent
9961
10124
  * @param subAgents Sub-agents to execute in sequence
@@ -10006,14 +10169,38 @@ var AgentBuilder = class _AgentBuilder {
10006
10169
  * @param options Session configuration options (userId and appName)
10007
10170
  * @returns This builder instance for chaining
10008
10171
  */
10009
- withSession(service, options = {}) {
10010
- this.sessionConfig = {
10011
- service,
10172
+ withSessionService(service, options = {}) {
10173
+ this.sessionService = service;
10174
+ this.sessionOptions = {
10012
10175
  userId: options.userId || this.generateDefaultUserId(),
10013
- appName: options.appName || this.generateDefaultAppName()
10176
+ appName: options.appName || this.generateDefaultAppName(),
10177
+ state: options.state,
10178
+ sessionId: options.sessionId
10014
10179
  };
10015
10180
  return this;
10016
10181
  }
10182
+ /**
10183
+ * Configure with an existing session instance
10184
+ * @param session Existing session to use
10185
+ * @returns This builder instance for chaining
10186
+ * @throws Error if no session service has been configured via withSessionService()
10187
+ */
10188
+ withSession(session) {
10189
+ if (!this.sessionService) {
10190
+ throw new Error(
10191
+ "Session service must be configured before using withSession(). Call withSessionService() first, or use withQuickSession() for in-memory sessions."
10192
+ );
10193
+ }
10194
+ this.sessionOptions = {
10195
+ ...this.sessionOptions,
10196
+ userId: session.userId,
10197
+ appName: session.appName,
10198
+ sessionId: session.id,
10199
+ state: session.state
10200
+ };
10201
+ this.existingSession = session;
10202
+ return this;
10203
+ }
10017
10204
  /**
10018
10205
  * Configure memory service for the agent
10019
10206
  * @param memoryService Memory service to use for conversation history and context
@@ -10039,7 +10226,7 @@ var AgentBuilder = class _AgentBuilder {
10039
10226
  * @returns This builder instance for chaining
10040
10227
  */
10041
10228
  withQuickSession(options = {}) {
10042
- return this.withSession(new InMemorySessionService(), options);
10229
+ return this.withSessionService(new InMemorySessionService(), options);
10043
10230
  }
10044
10231
  /**
10045
10232
  * Build the agent and optionally create runner and session
@@ -10049,18 +10236,24 @@ var AgentBuilder = class _AgentBuilder {
10049
10236
  const agent = this.createAgent();
10050
10237
  let runner;
10051
10238
  let session;
10052
- if (!this.sessionConfig) {
10239
+ if (!this.sessionService) {
10053
10240
  this.withQuickSession();
10054
10241
  }
10055
- if (this.sessionConfig) {
10056
- session = await this.sessionConfig.service.createSession(
10057
- this.sessionConfig.appName,
10058
- this.sessionConfig.userId
10059
- );
10242
+ if (this.sessionService && this.sessionOptions) {
10243
+ if (this.existingSession) {
10244
+ session = this.existingSession;
10245
+ } else {
10246
+ session = await this.sessionService.createSession(
10247
+ this.sessionOptions.appName,
10248
+ this.sessionOptions.userId,
10249
+ this.sessionOptions.state,
10250
+ this.sessionOptions.sessionId
10251
+ );
10252
+ }
10060
10253
  const runnerConfig = {
10061
- appName: this.sessionConfig.appName,
10254
+ appName: this.sessionOptions.appName,
10062
10255
  agent,
10063
- sessionService: this.sessionConfig.service,
10256
+ sessionService: this.sessionService,
10064
10257
  memoryService: this.memoryService,
10065
10258
  artifactService: this.artifactService
10066
10259
  };
@@ -10095,7 +10288,12 @@ var AgentBuilder = class _AgentBuilder {
10095
10288
  description: this.config.description,
10096
10289
  instruction: this.config.instruction,
10097
10290
  tools: this.config.tools,
10098
- planner: this.config.planner
10291
+ planner: this.config.planner,
10292
+ codeExecutor: this.config.codeExecutor,
10293
+ memoryService: this.memoryService,
10294
+ artifactService: this.artifactService,
10295
+ outputKey: this.config.outputKey,
10296
+ sessionService: this.sessionService
10099
10297
  });
10100
10298
  }
10101
10299
  case "sequential":
@@ -10160,16 +10358,16 @@ var AgentBuilder = class _AgentBuilder {
10160
10358
  * @returns Enhanced runner with simplified API
10161
10359
  */
10162
10360
  createEnhancedRunner(baseRunner, session) {
10163
- const sessionConfig = this.sessionConfig;
10361
+ const sessionOptions = this.sessionOptions;
10164
10362
  return {
10165
10363
  async ask(message) {
10166
10364
  const newMessage = typeof message === "string" ? { parts: [{ text: message }] } : typeof message === "object" && "contents" in message ? { parts: message.contents[message.contents.length - 1].parts } : message;
10167
10365
  let response = "";
10168
- if (!sessionConfig) {
10366
+ if (!sessionOptions?.userId) {
10169
10367
  throw new Error("Session configuration is required");
10170
10368
  }
10171
10369
  for await (const event of baseRunner.runAsync({
10172
- userId: sessionConfig.userId,
10370
+ userId: sessionOptions.userId,
10173
10371
  sessionId: session.id,
10174
10372
  newMessage
10175
10373
  })) {
@@ -10182,7 +10380,7 @@ var AgentBuilder = class _AgentBuilder {
10182
10380
  }
10183
10381
  }
10184
10382
  }
10185
- return response;
10383
+ return response.trim();
10186
10384
  },
10187
10385
  runAsync(params) {
10188
10386
  return baseRunner.runAsync(params);
@@ -11182,6 +11380,7 @@ export {
11182
11380
  AF_FUNCTION_CALL_ID_PREFIX,
11183
11381
  LlmAgent as Agent,
11184
11382
  AgentBuilder,
11383
+ AgentTool,
11185
11384
  agents_exports as Agents,
11186
11385
  AiSdkLlm,
11187
11386
  AnthropicLlm,