@google/adk 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/dist/cjs/a2a/agent_to_a2a.js +18 -2
  2. package/dist/cjs/a2a/event_converter_utils.js +8 -4
  3. package/dist/cjs/a2a/metadata_converter_utils.js +1 -1
  4. package/dist/cjs/agents/base_agent.js +39 -0
  5. package/dist/cjs/agents/functions.js +6 -21
  6. package/dist/cjs/agents/llm_agent.js +2 -1
  7. package/dist/cjs/agents/loop_agent.js +15 -3
  8. package/dist/cjs/agents/processors/content_processor_utils.js +2 -1
  9. package/dist/cjs/agents/routed_agent.js +31 -0
  10. package/dist/cjs/agents/run_config.js +3 -2
  11. package/dist/cjs/artifacts/in_memory_artifact_service.js +7 -0
  12. package/dist/cjs/common.js +29 -0
  13. package/dist/cjs/context/anchored_context_compactor.js +127 -0
  14. package/dist/cjs/context/compaction_utils.js +52 -0
  15. package/dist/cjs/context/token_based_context_compactor.js +11 -24
  16. package/dist/cjs/events/compacted_event.js +9 -3
  17. package/dist/cjs/events/event.js +28 -0
  18. package/dist/cjs/index.js +4 -0
  19. package/dist/cjs/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  20. package/dist/cjs/plugins/global_instruction_plugin.js +97 -0
  21. package/dist/cjs/runner/runner.js +51 -12
  22. package/dist/cjs/tools/enterprise_web_search_tool.js +81 -0
  23. package/dist/cjs/tools/example_tool.js +68 -0
  24. package/dist/cjs/tools/load_web_page.js +250 -0
  25. package/dist/cjs/tools/mcp/load_mcp_resource_tool.js +140 -0
  26. package/dist/cjs/tools/mcp/mcp_toolset.js +63 -0
  27. package/dist/cjs/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +13 -10
  28. package/dist/cjs/tools/skill/run_skill_inline_script_tool.js +54 -4
  29. package/dist/cjs/tools/skill/skill_toolset.js +4 -2
  30. package/dist/cjs/utils/branch_trie.js +41 -0
  31. package/dist/cjs/utils/streaming_utils.js +5 -5
  32. package/dist/cjs/version.js +1 -1
  33. package/dist/esm/a2a/agent_to_a2a.js +18 -2
  34. package/dist/esm/a2a/event_converter_utils.js +8 -4
  35. package/dist/esm/a2a/metadata_converter_utils.js +1 -1
  36. package/dist/esm/agents/base_agent.js +39 -0
  37. package/dist/esm/agents/functions.js +7 -17
  38. package/dist/esm/agents/llm_agent.js +4 -3
  39. package/dist/esm/agents/loop_agent.js +15 -3
  40. package/dist/esm/agents/processors/content_processor_utils.js +2 -1
  41. package/dist/esm/agents/routed_agent.js +31 -0
  42. package/dist/esm/agents/run_config.js +3 -2
  43. package/dist/esm/artifacts/in_memory_artifact_service.js +7 -0
  44. package/dist/esm/common.js +25 -1
  45. package/dist/esm/context/anchored_context_compactor.js +99 -0
  46. package/dist/esm/context/compaction_utils.js +27 -0
  47. package/dist/esm/context/token_based_context_compactor.js +11 -24
  48. package/dist/esm/events/compacted_event.js +7 -2
  49. package/dist/esm/events/event.js +24 -0
  50. package/dist/esm/index.js +6 -1
  51. package/dist/esm/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  52. package/dist/esm/plugins/global_instruction_plugin.js +69 -0
  53. package/dist/esm/runner/runner.js +51 -12
  54. package/dist/esm/tools/enterprise_web_search_tool.js +55 -0
  55. package/dist/esm/tools/example_tool.js +42 -0
  56. package/dist/esm/tools/load_web_page.js +221 -0
  57. package/dist/esm/tools/mcp/load_mcp_resource_tool.js +114 -0
  58. package/dist/esm/tools/mcp/mcp_toolset.js +63 -0
  59. package/dist/esm/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +13 -10
  60. package/dist/esm/tools/skill/run_skill_inline_script_tool.js +53 -4
  61. package/dist/esm/tools/skill/skill_toolset.js +4 -2
  62. package/dist/esm/utils/branch_trie.js +13 -0
  63. package/dist/esm/utils/streaming_utils.js +1 -1
  64. package/dist/esm/version.js +1 -1
  65. package/dist/types/a2a/a2a_remote_agent.d.ts +5 -1
  66. package/dist/types/a2a/agent_to_a2a.d.ts +38 -0
  67. package/dist/types/agents/base_agent.d.ts +29 -1
  68. package/dist/types/agents/functions.d.ts +1 -9
  69. package/dist/types/agents/llm_agent.d.ts +5 -1
  70. package/dist/types/agents/loop_agent.d.ts +2 -2
  71. package/dist/types/agents/routed_agent.d.ts +24 -1
  72. package/dist/types/agents/run_config.d.ts +1 -1
  73. package/dist/types/common.d.ts +9 -2
  74. package/dist/types/context/anchored_context_compactor.d.ts +35 -0
  75. package/dist/types/context/compaction_utils.d.ts +15 -0
  76. package/dist/types/events/compacted_event.d.ts +10 -0
  77. package/dist/types/events/event.d.ts +13 -0
  78. package/dist/types/index.d.ts +3 -2
  79. package/dist/types/plugins/global_instruction_plugin.d.ts +38 -0
  80. package/dist/types/runner/runner.d.ts +1 -1
  81. package/dist/types/tools/enterprise_web_search_tool.d.ts +26 -0
  82. package/dist/types/tools/example_tool.d.ts +21 -0
  83. package/dist/types/tools/load_web_page.d.ts +33 -0
  84. package/dist/types/tools/mcp/load_mcp_resource_tool.d.ts +26 -0
  85. package/dist/types/tools/mcp/mcp_toolset.d.ts +27 -0
  86. package/dist/types/tools/skill/run_skill_inline_script_tool.d.ts +25 -0
  87. package/dist/types/tools/skill/skill_toolset.d.ts +9 -0
  88. package/dist/types/utils/branch_trie.d.ts +14 -0
  89. package/dist/types/version.d.ts +1 -1
  90. package/dist/web/a2a/agent_to_a2a.js +18 -2
  91. package/dist/web/a2a/event_converter_utils.js +8 -4
  92. package/dist/web/a2a/metadata_converter_utils.js +1 -1
  93. package/dist/web/agents/base_agent.js +39 -0
  94. package/dist/web/agents/functions.js +7 -17
  95. package/dist/web/agents/llm_agent.js +4 -3
  96. package/dist/web/agents/loop_agent.js +27 -3
  97. package/dist/web/agents/processors/content_processor_utils.js +2 -1
  98. package/dist/web/agents/routed_agent.js +31 -0
  99. package/dist/web/agents/run_config.js +8 -3
  100. package/dist/web/artifacts/in_memory_artifact_service.js +7 -0
  101. package/dist/web/common.js +25 -1
  102. package/dist/web/context/anchored_context_compactor.js +117 -0
  103. package/dist/web/context/compaction_utils.js +27 -0
  104. package/dist/web/context/token_based_context_compactor.js +11 -24
  105. package/dist/web/events/compacted_event.js +7 -2
  106. package/dist/web/events/event.js +24 -0
  107. package/dist/web/index.js +6 -1
  108. package/dist/web/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  109. package/dist/web/plugins/global_instruction_plugin.js +67 -0
  110. package/dist/web/runner/runner.js +48 -11
  111. package/dist/web/tools/enterprise_web_search_tool.js +55 -0
  112. package/dist/web/tools/example_tool.js +42 -0
  113. package/dist/web/tools/load_web_page.js +221 -0
  114. package/dist/web/tools/mcp/load_mcp_resource_tool.js +107 -0
  115. package/dist/web/tools/mcp/mcp_toolset.js +63 -0
  116. package/dist/web/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +13 -10
  117. package/dist/web/tools/skill/run_skill_inline_script_tool.js +51 -4
  118. package/dist/web/tools/skill/skill_toolset.js +4 -2
  119. package/dist/web/utils/branch_trie.js +13 -0
  120. package/dist/web/utils/streaming_utils.js +1 -1
  121. package/dist/web/version.js +1 -1
  122. package/package.json +1 -1
@@ -75,10 +75,34 @@ class LoopAgent extends (_b = BaseAgent, _a = LOOP_AGENT_SIGNATURE_SYMBOL, _b) {
75
75
  return;
76
76
  });
77
77
  }
78
- // eslint-disable-next-line require-yield
79
- runLiveImpl(_context) {
78
+ runLiveImpl(context) {
80
79
  return __asyncGenerator(this, null, function* () {
81
- throw new Error("This is not supported yet for LoopAgent.");
80
+ var _a2, _b2;
81
+ for (let iteration = 0; iteration < this.maxIterations; iteration++) {
82
+ for (const subAgent of this.subAgents) {
83
+ try {
84
+ for (var iter = __forAwait(subAgent.runLive(context)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
85
+ const event = temp.value;
86
+ if ((_a2 = context.abortSignal) == null ? void 0 : _a2.aborted) {
87
+ return;
88
+ }
89
+ yield event;
90
+ if ((_b2 = event.actions) == null ? void 0 : _b2.escalate) {
91
+ return;
92
+ }
93
+ }
94
+ } catch (temp) {
95
+ error = [temp];
96
+ } finally {
97
+ try {
98
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
99
+ } finally {
100
+ if (error)
101
+ throw error[0];
102
+ }
103
+ }
104
+ }
105
+ }
82
106
  });
83
107
  }
84
108
  }
@@ -34,6 +34,7 @@ import {
34
34
  getFunctionCalls,
35
35
  getFunctionResponses
36
36
  } from "../../events/event.js";
37
+ import { isSegmentPrefix } from "../../utils/branch_trie.js";
37
38
  import {
38
39
  AF_FUNCTION_CALL_ID_PREFIX,
39
40
  REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
@@ -61,7 +62,7 @@ function getContents(events, agentName, currentBranch) {
61
62
  if (!((_a = event.content) == null ? void 0 : _a.role) || ((_c = (_b = event.content.parts) == null ? void 0 : _b[0]) == null ? void 0 : _c.text) === "") {
62
63
  continue;
63
64
  }
64
- if (currentBranch && event.branch && !currentBranch.startsWith(event.branch)) {
65
+ if (currentBranch && event.branch && !isSegmentPrefix(currentBranch, event.branch)) {
65
66
  continue;
66
67
  }
67
68
  if (isAuthEvent(event)) {
@@ -102,6 +102,29 @@ let RoutedAgent = class extends (_b = BaseAgent, _a = ROUTED_AGENT_SIGNATURE_SYM
102
102
  }
103
103
  this.router = config.router;
104
104
  }
105
+ /**
106
+ * Creates a detached copy of this routed agent.
107
+ *
108
+ * The inherited {@link BaseAgent.clone} only deep-clones `subAgents`, but a
109
+ * `RoutedAgent` derives its routing targets from `config.agents`. Rebuilding
110
+ * through the base clone alone would re-read the already-parented original
111
+ * agents and throw "already has a parent agent". This override deep-clones the
112
+ * routing targets (unless the caller overrides `agents`) so the rebuilt
113
+ * constructor re-parents fresh, detached copies. The array-vs-record shape
114
+ * and, for records, the keys are preserved so the router keeps selecting the
115
+ * same targets.
116
+ *
117
+ * @param overrides Config fields to override on the clone. Overriding
118
+ * `parentAgent` is rejected by the base implementation.
119
+ * @returns A new detached `RoutedAgent` of the same concrete class.
120
+ */
121
+ clone(overrides) {
122
+ const nextOverrides = __spreadValues({}, overrides);
123
+ if (!("agents" in nextOverrides)) {
124
+ nextOverrides.agents = cloneRoutingTargets(this.config.agents);
125
+ }
126
+ return super.clone(nextOverrides);
127
+ }
105
128
  /**
106
129
  * Runs the selected agent via text-based conversation.
107
130
  */
@@ -132,6 +155,14 @@ let RoutedAgent = class extends (_b = BaseAgent, _a = ROUTED_AGENT_SIGNATURE_SYM
132
155
  RoutedAgent = __decorateClass([
133
156
  experimental
134
157
  ], RoutedAgent);
158
+ function cloneRoutingTargets(agents) {
159
+ if (Array.isArray(agents)) {
160
+ return agents.map((agent) => agent.clone());
161
+ }
162
+ return Object.fromEntries(
163
+ Object.entries(agents).map(([key, agent]) => [key, agent.clone()])
164
+ );
165
+ }
135
166
  export {
136
167
  RoutedAgent,
137
168
  isRoutedAgent
@@ -1,6 +1,8 @@
1
1
  import {createRequire as topLevelCreateRequire} from 'module';
2
2
  const require = topLevelCreateRequire(import.meta.url);
3
3
  var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
6
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -16,6 +18,7 @@ var __spreadValues = (a, b) => {
16
18
  }
17
19
  return a;
18
20
  };
21
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
19
22
  /**
20
23
  * @license
21
24
  * Copyright 2025 Google LLC
@@ -29,14 +32,16 @@ var StreamingMode = /* @__PURE__ */ ((StreamingMode2) => {
29
32
  return StreamingMode2;
30
33
  })(StreamingMode || {});
31
34
  function createRunConfig(params = {}) {
32
- return __spreadValues({
35
+ var _a;
36
+ return __spreadProps(__spreadValues({
33
37
  saveInputBlobsAsArtifacts: false,
34
38
  supportCfc: false,
35
39
  enableAffectiveDialog: false,
36
40
  streamingMode: "none" /* NONE */,
37
- maxLlmCalls: validateMaxLlmCalls(params.maxLlmCalls || 500),
38
41
  pauseOnToolCalls: false
39
- }, params);
42
+ }, params), {
43
+ maxLlmCalls: validateMaxLlmCalls((_a = params.maxLlmCalls) != null ? _a : 500)
44
+ });
40
45
  }
41
46
  function validateMaxLlmCalls(value) {
42
47
  if (value > Number.MAX_SAFE_INTEGER) {
@@ -5,6 +5,7 @@ const require = topLevelCreateRequire(import.meta.url);
5
5
  * Copyright 2025 Google LLC
6
6
  * SPDX-License-Identifier: Apache-2.0
7
7
  */
8
+ import { logger } from "../utils/logger.js";
8
9
  function isInMemoryConnectionString(uri) {
9
10
  return uri === "memory://";
10
11
  }
@@ -56,6 +57,12 @@ class InMemoryArtifactService {
56
57
  if (version === void 0) {
57
58
  version = versions.length - 1;
58
59
  }
60
+ if (!versions[version]) {
61
+ logger.warn(
62
+ "[InMemoryArtifactService] loadArtifact: Artifact ".concat(filename, " version ").concat(version, " not found")
63
+ );
64
+ return Promise.resolve(void 0);
65
+ }
59
66
  return Promise.resolve(versions[version].part);
60
67
  }
61
68
  listArtifactKeys({
@@ -56,17 +56,22 @@ import {
56
56
  FileContentEncoding
57
57
  } from "./code_executors/code_execution_utils.js";
58
58
  import { AgentControlledContextCompactor } from "./context/agent_controlled_context_compactor.js";
59
+ import { AnchoredContextCompactor } from "./context/anchored_context_compactor.js";
59
60
  import { LlmSummarizer } from "./context/summarizers/llm_summarizer.js";
60
61
  import { TokenBasedContextCompactor } from "./context/token_based_context_compactor.js";
61
62
  import { TrajectoryThoughtPruningCompactor } from "./context/trajectory_thought_pruning_compactor.js";
62
63
  import { TruncatingContextCompactor } from "./context/truncating_context_compactor.js";
63
- import { isCompactedEvent } from "./events/compacted_event.js";
64
+ import { isCompactedEvent, isScratchpadEvent } from "./events/compacted_event.js";
64
65
  import {
65
66
  createEvent,
67
+ generateClientFunctionCallId,
66
68
  getFunctionCalls,
67
69
  getFunctionResponses,
70
+ hasThoughts,
68
71
  hasTrailingCodeExecutionResult,
69
72
  isFinalResponse,
73
+ populateClientFunctionCallId,
74
+ pruneThoughts,
70
75
  stringifyContent
71
76
  } from "./events/event.js";
72
77
  import { createEventActions } from "./events/event_actions.js";
@@ -83,6 +88,7 @@ import { Gemini, geminiInitParams } from "./models/google_llm.js";
83
88
  import { LLMRegistry } from "./models/registry.js";
84
89
  import { RoutedLlm } from "./models/routed_llm.js";
85
90
  import { BasePlugin, ContextCompactionTrigger } from "./plugins/base_plugin.js";
91
+ import { GlobalInstructionPlugin } from "./plugins/global_instruction_plugin.js";
86
92
  import { LoggingPlugin } from "./plugins/logging_plugin.js";
87
93
  import { PluginManager } from "./plugins/plugin_manager.js";
88
94
  import {
@@ -108,6 +114,11 @@ import { AgentTool, isAgentTool } from "./tools/agent_tool.js";
108
114
  import { BaseTool, isBaseTool } from "./tools/base_tool.js";
109
115
  import { BaseToolset, isBaseToolset } from "./tools/base_toolset.js";
110
116
  import { ConsolidateContextTool } from "./tools/consolidate_context_tool.js";
117
+ import {
118
+ ENTERPRISE_WEB_SEARCH,
119
+ EnterpriseWebSearchTool
120
+ } from "./tools/enterprise_web_search_tool.js";
121
+ import { ExampleTool } from "./tools/example_tool.js";
111
122
  import { EXIT_LOOP, ExitLoopTool } from "./tools/exit_loop_tool.js";
112
123
  import { FunctionTool, isFunctionTool } from "./tools/function_tool.js";
113
124
  import {
@@ -120,6 +131,7 @@ import {
120
131
  LoadArtifactsTool
121
132
  } from "./tools/load_artifacts_tool.js";
122
133
  import { LOAD_MEMORY, LoadMemoryTool } from "./tools/load_memory_tool.js";
134
+ import { LOAD_WEB_PAGE, loadWebPage } from "./tools/load_web_page.js";
123
135
  import { LongRunningFunctionTool } from "./tools/long_running_tool.js";
124
136
  import {
125
137
  PRELOAD_MEMORY,
@@ -174,6 +186,7 @@ export {
174
186
  AgentControlledContextCompactor,
175
187
  AgentTool,
176
188
  AgentTransferLlmRequestProcessor,
189
+ AnchoredContextCompactor,
177
190
  ApigeeLlm,
178
191
  AuthCredentialTypes,
179
192
  AuthHandler,
@@ -199,8 +212,11 @@ export {
199
212
  ContextCompactorRequestProcessor,
200
213
  CredentialExchangeError,
201
214
  CredentialRefresherRegistry,
215
+ ENTERPRISE_WEB_SEARCH,
202
216
  EXIT_LOOP,
217
+ EnterpriseWebSearchTool,
203
218
  EventType,
219
+ ExampleTool,
204
220
  ExitLoopTool,
205
221
  FileContentEncoding,
206
222
  FunctionTool,
@@ -208,6 +224,7 @@ export {
208
224
  GOOGLE_MAPS_GROUNDING,
209
225
  GOOGLE_SEARCH,
210
226
  Gemini,
227
+ GlobalInstructionPlugin,
211
228
  GoogleLLMVariant,
212
229
  GoogleMapsGroundingTool,
213
230
  GoogleSearchTool,
@@ -223,6 +240,7 @@ export {
223
240
  LLMRegistry,
224
241
  LOAD_ARTIFACTS,
225
242
  LOAD_MEMORY,
243
+ LOAD_WEB_PAGE,
226
244
  ListSkillsTool,
227
245
  LiveRequestQueue,
228
246
  LlmAgent2 as LlmAgent,
@@ -281,11 +299,13 @@ export {
281
299
  findMatchingFunctionCall,
282
300
  functionsExportedForTestingOnly,
283
301
  geminiInitParams,
302
+ generateClientFunctionCallId,
284
303
  getAskUserConfirmationFunctionCalls,
285
304
  getClientLabels,
286
305
  getFunctionCalls,
287
306
  getFunctionResponses,
288
307
  getLogger,
308
+ hasThoughts,
289
309
  hasTrailingCodeExecutionResult,
290
310
  isAgentTool,
291
311
  isBaseAgent,
@@ -304,10 +324,14 @@ export {
304
324
  isRoutableLlmAgent,
305
325
  isRoutedAgent,
306
326
  isRunner,
327
+ isScratchpadEvent,
307
328
  isSequentialAgent,
308
329
  loadAllSkillsInDir,
309
330
  loadSkillFromDir,
310
331
  loadSkillFromZipBuffer,
332
+ loadWebPage,
333
+ populateClientFunctionCallId,
334
+ pruneThoughts,
311
335
  runWithClientLabel,
312
336
  setLogLevel,
313
337
  setLogger,
@@ -0,0 +1,117 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __spreadValues = (a, b) => {
11
+ for (var prop in b || (b = {}))
12
+ if (__hasOwnProp.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ if (__getOwnPropSymbols)
15
+ for (var prop of __getOwnPropSymbols(b)) {
16
+ if (__propIsEnum.call(b, prop))
17
+ __defNormalProp(a, prop, b[prop]);
18
+ }
19
+ return a;
20
+ };
21
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
22
+ /**
23
+ * @license
24
+ * Copyright 2026 Google LLC
25
+ * SPDX-License-Identifier: Apache-2.0
26
+ */
27
+ import { isScratchpadEvent } from "../events/compacted_event.js";
28
+ import { getEventTokens } from "../events/event.js";
29
+ import { calculateRetainStartIndex } from "./compaction_utils.js";
30
+ class AnchoredContextCompactor {
31
+ constructor(options) {
32
+ this.tokenThreshold = options.tokenThreshold;
33
+ this.eventRetentionSize = options.eventRetentionSize;
34
+ this.summarizer = options.summarizer;
35
+ }
36
+ getActiveEvents(events) {
37
+ let latestScratchpad = void 0;
38
+ for (let i = events.length - 1; i >= 0; i--) {
39
+ const e = events[i];
40
+ if (isScratchpadEvent(e)) {
41
+ latestScratchpad = e;
42
+ break;
43
+ }
44
+ }
45
+ if (!latestScratchpad) {
46
+ return events;
47
+ }
48
+ const activeRawEvents = events.filter(
49
+ (e) => e.timestamp > latestScratchpad.endTime && !isScratchpadEvent(e)
50
+ );
51
+ return [latestScratchpad, ...activeRawEvents];
52
+ }
53
+ shouldCompact(invocationContext) {
54
+ const events = invocationContext.session.events;
55
+ const activeEvents = this.getActiveEvents(events);
56
+ const hasScratchpad = activeEvents.length > 0 && isScratchpadEvent(activeEvents[0]);
57
+ const rawEvents = hasScratchpad ? activeEvents.slice(1) : activeEvents;
58
+ if (rawEvents.length <= this.eventRetentionSize) {
59
+ return false;
60
+ }
61
+ const retainStartIndex = calculateRetainStartIndex(
62
+ rawEvents,
63
+ this.eventRetentionSize
64
+ );
65
+ if (retainStartIndex === 0) {
66
+ return false;
67
+ }
68
+ const totalTokens = activeEvents.reduce(
69
+ (sum, event) => sum + getEventTokens(event),
70
+ 0
71
+ );
72
+ return totalTokens > this.tokenThreshold;
73
+ }
74
+ async compact(invocationContext) {
75
+ const events = invocationContext.session.events;
76
+ const activeEvents = this.getActiveEvents(events);
77
+ const hasScratchpad = activeEvents.length > 0 && isScratchpadEvent(activeEvents[0]);
78
+ const rawEvents = hasScratchpad ? activeEvents.slice(1) : activeEvents;
79
+ if (rawEvents.length <= this.eventRetentionSize) {
80
+ return;
81
+ }
82
+ const retainStartIndex = calculateRetainStartIndex(
83
+ rawEvents,
84
+ this.eventRetentionSize
85
+ );
86
+ if (retainStartIndex === 0) {
87
+ return;
88
+ }
89
+ const rawEventsToCompact = rawEvents.slice(0, retainStartIndex);
90
+ let scratchpadEvent;
91
+ if (hasScratchpad) {
92
+ const existingScratchpad = activeEvents[0];
93
+ scratchpadEvent = await this.summarizer.summarize([
94
+ existingScratchpad,
95
+ ...rawEventsToCompact
96
+ ]);
97
+ } else {
98
+ scratchpadEvent = await this.summarizer.summarize(rawEventsToCompact);
99
+ }
100
+ const updatedScratchpad = __spreadProps(__spreadValues({}, scratchpadEvent), {
101
+ isScratchpad: true,
102
+ author: "system"
103
+ });
104
+ const inactiveEvents = events.slice(0, events.indexOf(activeEvents[0]));
105
+ const retainedRawEvents = rawEvents.slice(retainStartIndex);
106
+ const newEventsList = [
107
+ ...inactiveEvents,
108
+ updatedScratchpad,
109
+ ...retainedRawEvents
110
+ ];
111
+ events.length = 0;
112
+ events.push(...newEventsList);
113
+ }
114
+ }
115
+ export {
116
+ AnchoredContextCompactor
117
+ };
@@ -0,0 +1,27 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Google LLC
6
+ * SPDX-License-Identifier: Apache-2.0
7
+ */
8
+ import {
9
+ getFunctionCalls,
10
+ getFunctionResponses
11
+ } from "../events/event.js";
12
+ function calculateRetainStartIndex(rawEvents, eventRetentionSize) {
13
+ let retainStartIndex = Math.max(0, rawEvents.length - eventRetentionSize);
14
+ while (retainStartIndex > 0) {
15
+ const eventToRetain = rawEvents[retainStartIndex];
16
+ const previousEvent = rawEvents[retainStartIndex - 1];
17
+ if (getFunctionResponses(eventToRetain).length > 0 && getFunctionCalls(previousEvent).length > 0) {
18
+ retainStartIndex--;
19
+ } else {
20
+ break;
21
+ }
22
+ }
23
+ return retainStartIndex;
24
+ }
25
+ export {
26
+ calculateRetainStartIndex
27
+ };
@@ -7,6 +7,7 @@ const require = topLevelCreateRequire(import.meta.url);
7
7
  */
8
8
  import { getContents } from "../agents/processors/content_processor_utils.js";
9
9
  import { isCompactedEvent } from "../events/compacted_event.js";
10
+ import { calculateRetainStartIndex } from "./compaction_utils.js";
10
11
  const CHARS_PER_TOKEN = 4;
11
12
  class TokenBasedContextCompactor {
12
13
  constructor(options) {
@@ -39,6 +40,13 @@ class TokenBasedContextCompactor {
39
40
  if (rawEvents.length <= this.eventRetentionSize) {
40
41
  return false;
41
42
  }
43
+ const retainStartIndex = calculateRetainStartIndex(
44
+ rawEvents,
45
+ this.eventRetentionSize
46
+ );
47
+ if (retainStartIndex === 0) {
48
+ return false;
49
+ }
42
50
  const promptTokenCount = latestPromptTokenCount(
43
51
  activeEvents,
44
52
  invocationContext
@@ -55,19 +63,10 @@ class TokenBasedContextCompactor {
55
63
  if (rawEvents.length <= this.eventRetentionSize) {
56
64
  return;
57
65
  }
58
- let retainStartIndex = Math.max(
59
- 0,
60
- rawEvents.length - this.eventRetentionSize
66
+ const retainStartIndex = calculateRetainStartIndex(
67
+ rawEvents,
68
+ this.eventRetentionSize
61
69
  );
62
- while (retainStartIndex > 0) {
63
- const eventToRetain = rawEvents[retainStartIndex];
64
- const previousEvent = rawEvents[retainStartIndex - 1];
65
- if (hasFunctionResponse(eventToRetain) && hasFunctionCall(previousEvent)) {
66
- retainStartIndex--;
67
- } else {
68
- break;
69
- }
70
- }
71
70
  if (retainStartIndex === 0) {
72
71
  return;
73
72
  }
@@ -122,18 +121,6 @@ function estimatePromptTokenCount(activeEvents, invocationContext) {
122
121
  }
123
122
  return Math.ceil(totalChars / CHARS_PER_TOKEN);
124
123
  }
125
- function hasFunctionCall(event) {
126
- var _a, _b;
127
- return !!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.some(
128
- (part) => part.functionCall !== void 0
129
- ));
130
- }
131
- function hasFunctionResponse(event) {
132
- var _a, _b;
133
- return !!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.some(
134
- (part) => part.functionResponse !== void 0
135
- ));
136
- }
137
124
  export {
138
125
  TokenBasedContextCompactor
139
126
  };
@@ -28,15 +28,20 @@ import { createEvent } from "./event.js";
28
28
  function isCompactedEvent(event) {
29
29
  return "isCompacted" in event && event.isCompacted === true;
30
30
  }
31
+ function isScratchpadEvent(event) {
32
+ return isCompactedEvent(event) && event.isScratchpad === true;
33
+ }
31
34
  function createCompactedEvent(params = {}) {
32
35
  return __spreadProps(__spreadValues({}, createEvent(params)), {
33
36
  isCompacted: params.isCompacted || true,
34
37
  startTime: params.startTime,
35
38
  endTime: params.endTime,
36
- compactedContent: params.compactedContent
39
+ compactedContent: params.compactedContent,
40
+ isScratchpad: params.isScratchpad
37
41
  });
38
42
  }
39
43
  export {
40
44
  createCompactedEvent,
41
- isCompactedEvent
45
+ isCompactedEvent,
46
+ isScratchpadEvent
42
47
  };
@@ -24,6 +24,7 @@ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
24
  * Copyright 2026 Google LLC
25
25
  * SPDX-License-Identifier: Apache-2.0
26
26
  */
27
+ import { randomUUID } from "../utils/env_aware_utils.js";
27
28
  import { toCamelCase, toSnakeCase } from "../utils/object_notation_utils.js";
28
29
  import { createEventActions } from "./event_actions.js";
29
30
  function createEvent(params = {}) {
@@ -54,6 +55,17 @@ function getFunctionCalls(event) {
54
55
  }
55
56
  return funcCalls;
56
57
  }
58
+ const AF_FUNCTION_CALL_ID_PREFIX = "adk-";
59
+ function generateClientFunctionCallId() {
60
+ return "".concat(AF_FUNCTION_CALL_ID_PREFIX).concat(randomUUID());
61
+ }
62
+ function populateClientFunctionCallId(modelResponseEvent) {
63
+ for (const functionCall of getFunctionCalls(modelResponseEvent)) {
64
+ if (!functionCall.id) {
65
+ functionCall.id = generateClientFunctionCallId();
66
+ }
67
+ }
68
+ }
57
69
  function getFunctionResponses(event) {
58
70
  const funcResponses = [];
59
71
  if (event.content && event.content.parts) {
@@ -83,6 +95,14 @@ function stringifyContent(event) {
83
95
  return (_a2 = part.text) != null ? _a2 : "";
84
96
  }).join("");
85
97
  }
98
+ function getEventTokens(event) {
99
+ var _a;
100
+ if (((_a = event.usageMetadata) == null ? void 0 : _a.promptTokenCount) !== void 0) {
101
+ return event.usageMetadata.promptTokenCount;
102
+ }
103
+ const contentStr = stringifyContent(event);
104
+ return Math.ceil(contentStr.length / 4);
105
+ }
86
106
  function hasThoughts(event) {
87
107
  var _a, _b;
88
108
  return !!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.some((part) => part.thought === true));
@@ -136,13 +156,17 @@ function transformToSnakeCaseEvent(event) {
136
156
  return toSnakeCase(event, PRESERVE_KEYS_CAMEL_CASE);
137
157
  }
138
158
  export {
159
+ AF_FUNCTION_CALL_ID_PREFIX,
139
160
  createEvent,
140
161
  createNewEventId,
162
+ generateClientFunctionCallId,
163
+ getEventTokens,
141
164
  getFunctionCalls,
142
165
  getFunctionResponses,
143
166
  hasThoughts,
144
167
  hasTrailingCodeExecutionResult,
145
168
  isFinalResponse,
169
+ populateClientFunctionCallId,
146
170
  pruneThoughts,
147
171
  stringifyContent,
148
172
  transformToCamelCaseEvent,
package/dist/web/index.js CHANGED
@@ -29,11 +29,15 @@ import {
29
29
  loadSkillFromDir,
30
30
  validateSkillDir
31
31
  } from "./skills/loader.js";
32
- import { RunSkillInlineScriptTool } from "./tools/skill/run_skill_inline_script_tool.js";
32
+ import {
33
+ RunSkillInlineScriptErrorCode,
34
+ RunSkillInlineScriptTool
35
+ } from "./tools/skill/run_skill_inline_script_tool.js";
33
36
  import { RunSkillScriptTool } from "./tools/skill/run_skill_script_tool.js";
34
37
  export * from "./integrations/agent_registry/agent_registry.js";
35
38
  export * from "./telemetry/google_cloud.js";
36
39
  export * from "./telemetry/setup.js";
40
+ export * from "./tools/mcp/load_mcp_resource_tool.js";
37
41
  export * from "./tools/mcp/mcp_session_manager.js";
38
42
  export * from "./tools/mcp/mcp_tool.js";
39
43
  export * from "./tools/mcp/mcp_toolset.js";
@@ -47,6 +51,7 @@ export {
47
51
  GcsArtifactService,
48
52
  InvocationContext,
49
53
  RemoteA2AAgent,
54
+ RunSkillInlineScriptErrorCode,
50
55
  RunSkillInlineScriptTool,
51
56
  RunSkillScriptTool,
52
57
  UnsafeLocalCodeExecutor,
@@ -29,6 +29,7 @@ import {
29
29
  MCPSessionManager
30
30
  } from "../../tools/mcp/mcp_session_manager.js";
31
31
  import { MCPTool } from "../../tools/mcp/mcp_tool.js";
32
+ import { logger } from "../../utils/logger.js";
32
33
  import { GCP_MCP_SERVER_DESTINATION_ID } from "./types.js";
33
34
  class AgentRegistrySingleMCPToolset extends BaseToolset {
34
35
  /**
@@ -78,7 +79,14 @@ class AgentRegistrySingleMCPToolset extends BaseToolset {
78
79
  });
79
80
  const sessionManager = new MCPSessionManager(connectionParamsCopy);
80
81
  const session = await sessionManager.createSession();
81
- const listResult = await session.listTools();
82
+ let listResult;
83
+ try {
84
+ listResult = await session.listTools();
85
+ } finally {
86
+ await sessionManager.closeSession(session).catch((e) => {
87
+ logger.warn("Failed to close MCP discovery session", e);
88
+ });
89
+ }
82
90
  const tools = listResult.tools.map((tool) => {
83
91
  const prefixedName = this.prefix ? "".concat(this.prefix, "_").concat(tool.name) : tool.name;
84
92
  const mcpTool = new MCPTool(
@@ -0,0 +1,67 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Google LLC
6
+ * SPDX-License-Identifier: Apache-2.0
7
+ */
8
+ import { injectSessionState } from "../agents/instructions.js";
9
+ import { ReadonlyContext } from "../agents/readonly_context.js";
10
+ import { BasePlugin } from "./base_plugin.js";
11
+ class GlobalInstructionPlugin extends BasePlugin {
12
+ /**
13
+ * Initializes the GlobalInstructionPlugin.
14
+ *
15
+ * @param globalInstruction The instruction to apply globally. Can be a string
16
+ * or an InstructionProvider function that takes ReadonlyContext and
17
+ * returns a string (sync or async).
18
+ * @param name The name of the plugin (defaults to 'global_instruction').
19
+ */
20
+ constructor(globalInstruction, name = "global_instruction") {
21
+ super(name);
22
+ this.globalInstruction = globalInstruction;
23
+ }
24
+ async beforeModelCallback(params) {
25
+ if (!this.globalInstruction) {
26
+ return;
27
+ }
28
+ const readonlyContext = new ReadonlyContext(
29
+ params.callbackContext.invocationContext
30
+ );
31
+ const finalGlobalInstruction = await this.resolveGlobalInstruction(readonlyContext);
32
+ if (!finalGlobalInstruction) {
33
+ return;
34
+ }
35
+ if (!params.llmRequest.config) {
36
+ params.llmRequest.config = {};
37
+ }
38
+ const existingInstruction = params.llmRequest.config.systemInstruction;
39
+ if (!existingInstruction || Array.isArray(existingInstruction) && existingInstruction.length === 0) {
40
+ params.llmRequest.config.systemInstruction = finalGlobalInstruction;
41
+ return;
42
+ }
43
+ if (typeof existingInstruction === "string") {
44
+ params.llmRequest.config.systemInstruction = "".concat(finalGlobalInstruction, "\n\n").concat(existingInstruction);
45
+ } else if (Array.isArray(existingInstruction)) {
46
+ params.llmRequest.config.systemInstruction = [
47
+ finalGlobalInstruction,
48
+ ...existingInstruction
49
+ ];
50
+ } else {
51
+ params.llmRequest.config.systemInstruction = [
52
+ finalGlobalInstruction,
53
+ existingInstruction
54
+ ];
55
+ }
56
+ return;
57
+ }
58
+ async resolveGlobalInstruction(readonlyContext) {
59
+ if (typeof this.globalInstruction === "string") {
60
+ return await injectSessionState(this.globalInstruction, readonlyContext);
61
+ }
62
+ return await this.globalInstruction(readonlyContext);
63
+ }
64
+ }
65
+ export {
66
+ GlobalInstructionPlugin
67
+ };