@google/adk 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/dist/cjs/a2a/a2a_remote_agent.js +4 -1
  2. package/dist/cjs/a2a/agent_card.js +102 -26
  3. package/dist/cjs/a2a/agent_to_a2a.js +1 -1
  4. package/dist/cjs/a2a/event_converter_utils.js +5 -1
  5. package/dist/cjs/a2a/metadata_converter_utils.js +2 -1
  6. package/dist/cjs/agents/functions.js +199 -25
  7. package/dist/cjs/agents/instructions.js +4 -1
  8. package/dist/cjs/agents/invocation_context.js +26 -4
  9. package/dist/cjs/agents/langgraph_agent.js +152 -0
  10. package/dist/cjs/agents/llm_agent.js +175 -101
  11. package/dist/cjs/agents/processors/code_execution_request_processor.js +10 -6
  12. package/dist/cjs/agents/remote_agent.js +187 -0
  13. package/dist/cjs/artifacts/in_memory_artifact_service.js +14 -0
  14. package/dist/cjs/auth/auth_handler.js +37 -5
  15. package/dist/cjs/auth/auth_schemes.js +9 -0
  16. package/dist/cjs/cli/cli_eval.js +532 -0
  17. package/dist/cjs/cli/utils/envs.js +116 -0
  18. package/dist/cjs/cli/utils/evals.js +137 -0
  19. package/dist/cjs/cli/utils/logs.js +150 -0
  20. package/dist/cjs/code_executors/agent_engine_sandbox_code_executor.js +7 -2
  21. package/dist/cjs/code_executors/code_execution_utils.js +48 -16
  22. package/dist/cjs/code_executors/code_executor_context.js +6 -2
  23. package/dist/cjs/common.js +90 -0
  24. package/dist/cjs/context/summarizers/llm_summarizer.js +12 -10
  25. package/dist/cjs/context/token_based_context_compactor.js +2 -1
  26. package/dist/cjs/events/abort_events.js +135 -0
  27. package/dist/cjs/events/event.js +4 -2
  28. package/dist/cjs/events/internal_metadata.js +131 -0
  29. package/dist/cjs/examples/example_util.js +23 -2
  30. package/dist/cjs/flows/llm_flows/audio_transcriber.js +170 -0
  31. package/dist/cjs/index.js +97 -1
  32. package/dist/cjs/integrations/agent_registry/helpers.js +1 -1
  33. package/dist/cjs/models/gemini_llm_connection.js +16 -8
  34. package/dist/cjs/models/google_llm.js +13 -16
  35. package/dist/cjs/models/llm_response.js +9 -1
  36. package/dist/cjs/models/registry.js +1 -1
  37. package/dist/cjs/models/routed_llm.js +9 -8
  38. package/dist/cjs/planners/plan_re_act_planner.js +1 -1
  39. package/dist/cjs/plugins/debug_logging_plugin.js +653 -0
  40. package/dist/cjs/plugins/plugin_manager.js +1 -1
  41. package/dist/cjs/plugins/tool_call_integrity_plugin.js +364 -0
  42. package/dist/cjs/runner/in_memory_runner.js +6 -11
  43. package/dist/cjs/runner/runner.js +121 -35
  44. package/dist/cjs/sessions/db/operations.js +1 -1
  45. package/dist/cjs/sessions/in_memory_session_service.js +3 -1
  46. package/dist/cjs/sessions/state.js +8 -4
  47. package/dist/cjs/sessions/vertex_ai_session_service.js +34 -15
  48. package/dist/cjs/telemetry/tracing.js +97 -66
  49. package/dist/cjs/tools/agent_tool.js +44 -0
  50. package/dist/cjs/tools/apihub_tool/apihub_toolset.js +142 -0
  51. package/dist/cjs/tools/apihub_tool/clients/apihub_client.js +272 -0
  52. package/dist/cjs/tools/apihub_tool/clients/secret_client.js +148 -0
  53. package/dist/cjs/tools/apihub_tool/clients/service_account.js +48 -0
  54. package/dist/cjs/tools/application_integration_tool/application_integration_toolset.js +185 -0
  55. package/dist/cjs/tools/application_integration_tool/clients/cloud_request.js +133 -0
  56. package/dist/cjs/tools/application_integration_tool/clients/connections_client.js +603 -0
  57. package/dist/cjs/tools/application_integration_tool/clients/integration_client.js +219 -0
  58. package/dist/cjs/tools/crewai_tool.js +132 -0
  59. package/dist/cjs/tools/example_tool.js +10 -0
  60. package/dist/cjs/tools/function_tool.js +319 -0
  61. package/dist/cjs/tools/google_api_tool/google_api_tool.js +97 -0
  62. package/dist/cjs/tools/google_api_tool/google_api_tool_set.js +226 -0
  63. package/dist/cjs/tools/google_api_tool/google_api_tool_sets.js +58 -0
  64. package/dist/cjs/tools/google_api_tool/googleapi_to_openapi_converter.js +440 -0
  65. package/dist/cjs/tools/google_api_tool/index.js +64 -0
  66. package/dist/cjs/tools/langchain_tool.js +172 -0
  67. package/dist/cjs/tools/mcp/index.js +12 -0
  68. package/dist/cjs/tools/mcp/mcp_session_manager.js +25 -0
  69. package/dist/cjs/tools/openapi_tool/auth/auth_helpers.js +1 -2
  70. package/dist/cjs/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.js +46 -2
  71. package/dist/cjs/tools/openapi_tool/auth/credential_exchangers/oauth2_exchanger.js +2 -1
  72. package/dist/cjs/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.js +94 -10
  73. package/dist/cjs/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +14 -2
  74. package/dist/cjs/tools/retrieval/base_retrieval_tool.js +18 -3
  75. package/dist/cjs/tools/toolbox_tool.js +108 -0
  76. package/dist/cjs/utils/env_aware_utils.js +6 -8
  77. package/dist/cjs/utils/error_utils.js +11 -11
  78. package/dist/cjs/utils/file_extension_utils.js +11 -0
  79. package/dist/cjs/utils/file_utils.js +2 -24
  80. package/dist/cjs/utils/gemini_schema_util.js +4 -1
  81. package/dist/cjs/utils/json_utils.js +49 -0
  82. package/dist/cjs/utils/live_connection_utils.js +4 -5
  83. package/dist/cjs/utils/logger_node.js +7 -1
  84. package/dist/cjs/utils/object_notation_utils.js +6 -3
  85. package/dist/cjs/utils/streaming_utils.js +12 -12
  86. package/dist/cjs/version.js +1 -1
  87. package/dist/esm/a2a/a2a_remote_agent.js +4 -1
  88. package/dist/esm/a2a/agent_card.js +103 -27
  89. package/dist/esm/a2a/agent_to_a2a.js +5 -2
  90. package/dist/esm/a2a/event_converter_utils.js +5 -1
  91. package/dist/esm/a2a/metadata_converter_utils.js +2 -1
  92. package/dist/esm/agents/functions.js +198 -25
  93. package/dist/esm/agents/instructions.js +4 -1
  94. package/dist/esm/agents/invocation_context.js +24 -4
  95. package/dist/esm/agents/langgraph_agent.js +123 -0
  96. package/dist/esm/agents/llm_agent.js +185 -104
  97. package/dist/esm/agents/processors/code_execution_request_processor.js +13 -8
  98. package/dist/esm/agents/remote_agent.js +164 -0
  99. package/dist/esm/artifacts/in_memory_artifact_service.js +14 -0
  100. package/dist/esm/auth/auth_handler.js +37 -5
  101. package/dist/esm/auth/auth_schemes.js +8 -0
  102. package/dist/esm/cli/cli_eval.js +510 -0
  103. package/dist/esm/cli/utils/envs.js +78 -0
  104. package/dist/esm/cli/utils/evals.js +109 -0
  105. package/dist/esm/cli/utils/logs.js +111 -0
  106. package/dist/esm/code_executors/agent_engine_sandbox_code_executor.js +7 -2
  107. package/dist/esm/code_executors/code_execution_utils.js +46 -16
  108. package/dist/esm/code_executors/code_executor_context.js +5 -2
  109. package/dist/esm/common.js +87 -3
  110. package/dist/esm/context/summarizers/llm_summarizer.js +12 -10
  111. package/dist/esm/context/token_based_context_compactor.js +2 -1
  112. package/dist/esm/events/abort_events.js +110 -0
  113. package/dist/esm/events/event.js +4 -2
  114. package/dist/esm/events/internal_metadata.js +97 -0
  115. package/dist/esm/examples/example_util.js +21 -1
  116. package/dist/esm/flows/llm_flows/audio_transcriber.js +142 -0
  117. package/dist/esm/index.js +99 -1
  118. package/dist/esm/integrations/agent_registry/helpers.js +1 -1
  119. package/dist/esm/models/gemini_llm_connection.js +16 -8
  120. package/dist/esm/models/google_llm.js +14 -17
  121. package/dist/esm/models/llm_response.js +9 -1
  122. package/dist/esm/models/registry.js +1 -1
  123. package/dist/esm/models/routed_llm.js +9 -8
  124. package/dist/esm/planners/plan_re_act_planner.js +1 -1
  125. package/dist/esm/plugins/debug_logging_plugin.js +615 -0
  126. package/dist/esm/plugins/plugin_manager.js +1 -1
  127. package/dist/esm/plugins/tool_call_integrity_plugin.js +339 -0
  128. package/dist/esm/runner/in_memory_runner.js +6 -11
  129. package/dist/esm/runner/runner.js +124 -35
  130. package/dist/esm/sessions/db/operations.js +1 -1
  131. package/dist/esm/sessions/in_memory_session_service.js +3 -1
  132. package/dist/esm/sessions/state.js +8 -4
  133. package/dist/esm/sessions/vertex_ai_session_service.js +34 -15
  134. package/dist/esm/telemetry/tracing.js +97 -66
  135. package/dist/esm/tools/agent_tool.js +44 -0
  136. package/dist/esm/tools/apihub_tool/apihub_toolset.js +106 -0
  137. package/dist/esm/tools/apihub_tool/clients/apihub_client.js +244 -0
  138. package/dist/esm/tools/apihub_tool/clients/secret_client.js +132 -0
  139. package/dist/esm/tools/apihub_tool/clients/service_account.js +21 -0
  140. package/dist/esm/tools/application_integration_tool/application_integration_toolset.js +163 -0
  141. package/dist/esm/tools/application_integration_tool/clients/cloud_request.js +103 -0
  142. package/dist/esm/tools/application_integration_tool/clients/connections_client.js +561 -0
  143. package/dist/esm/tools/application_integration_tool/clients/integration_client.js +215 -0
  144. package/dist/esm/tools/crewai_tool.js +107 -0
  145. package/dist/esm/tools/example_tool.js +13 -1
  146. package/dist/esm/tools/function_tool.js +316 -0
  147. package/dist/esm/tools/google_api_tool/google_api_tool.js +70 -0
  148. package/dist/esm/tools/google_api_tool/google_api_tool_set.js +188 -0
  149. package/dist/esm/tools/google_api_tool/google_api_tool_sets.js +24 -0
  150. package/dist/esm/tools/google_api_tool/googleapi_to_openapi_converter.js +393 -0
  151. package/dist/esm/tools/google_api_tool/index.js +33 -0
  152. package/dist/esm/tools/langchain_tool.js +148 -0
  153. package/dist/esm/tools/mcp/index.js +6 -0
  154. package/dist/esm/tools/mcp/mcp_session_manager.js +25 -0
  155. package/dist/esm/tools/openapi_tool/auth/auth_helpers.js +1 -2
  156. package/dist/esm/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.js +50 -3
  157. package/dist/esm/tools/openapi_tool/auth/credential_exchangers/oauth2_exchanger.js +2 -1
  158. package/dist/esm/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.js +94 -10
  159. package/dist/esm/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +15 -2
  160. package/dist/esm/tools/retrieval/base_retrieval_tool.js +16 -2
  161. package/dist/esm/tools/toolbox_tool.js +80 -0
  162. package/dist/esm/utils/env_aware_utils.js +6 -8
  163. package/dist/esm/utils/error_utils.js +9 -10
  164. package/dist/esm/utils/file_extension_utils.js +11 -0
  165. package/dist/esm/utils/file_utils.js +2 -23
  166. package/dist/esm/utils/gemini_schema_util.js +4 -1
  167. package/dist/esm/utils/json_utils.js +21 -0
  168. package/dist/esm/utils/live_connection_utils.js +4 -5
  169. package/dist/esm/utils/logger_node.js +7 -1
  170. package/dist/esm/utils/object_notation_utils.js +4 -2
  171. package/dist/esm/utils/streaming_utils.js +11 -11
  172. package/dist/esm/version.js +1 -1
  173. package/dist/types/a2a/a2a_remote_agent.d.ts +9 -0
  174. package/dist/types/a2a/agent_card.d.ts +44 -1
  175. package/dist/types/a2a/agent_to_a2a.d.ts +9 -0
  176. package/dist/types/a2a/index.d.ts +1 -0
  177. package/dist/types/agents/functions.d.ts +33 -1
  178. package/dist/types/agents/invocation_context.d.ts +20 -1
  179. package/dist/types/agents/langgraph_agent.d.ts +153 -0
  180. package/dist/types/agents/remote_agent.d.ts +68 -0
  181. package/dist/types/auth/auth_handler.d.ts +28 -1
  182. package/dist/types/auth/auth_schemes.d.ts +13 -0
  183. package/dist/types/cli/cli_eval.d.ts +173 -0
  184. package/dist/types/cli/utils/envs.d.ts +23 -0
  185. package/dist/types/cli/utils/evals.d.ts +47 -0
  186. package/dist/types/cli/utils/logs.d.ts +38 -0
  187. package/dist/types/code_executors/code_execution_utils.d.ts +39 -0
  188. package/dist/types/code_executors/code_executor_context.d.ts +1 -0
  189. package/dist/types/common.d.ts +30 -4
  190. package/dist/types/events/abort_events.d.ts +43 -0
  191. package/dist/types/events/event.d.ts +4 -0
  192. package/dist/types/events/internal_metadata.d.ts +78 -0
  193. package/dist/types/examples/example_util.d.ts +17 -0
  194. package/dist/types/flows/llm_flows/audio_transcriber.d.ts +85 -0
  195. package/dist/types/index.d.ts +16 -1
  196. package/dist/types/models/gemini_llm_connection.d.ts +6 -7
  197. package/dist/types/models/routed_llm.d.ts +1 -1
  198. package/dist/types/plugins/debug_logging_plugin.d.ts +157 -0
  199. package/dist/types/plugins/tool_call_integrity_plugin.d.ts +116 -0
  200. package/dist/types/runner/in_memory_runner.d.ts +2 -1
  201. package/dist/types/runner/runner.d.ts +34 -0
  202. package/dist/types/sessions/state.d.ts +5 -1
  203. package/dist/types/sessions/vertex_ai_session_service.d.ts +8 -0
  204. package/dist/types/skills/skill.d.ts +1 -1
  205. package/dist/types/telemetry/tracing.d.ts +4 -2
  206. package/dist/types/tools/apihub_tool/apihub_toolset.d.ts +122 -0
  207. package/dist/types/tools/apihub_tool/clients/apihub_client.d.ts +142 -0
  208. package/dist/types/tools/apihub_tool/clients/secret_client.d.ts +55 -0
  209. package/dist/types/tools/apihub_tool/clients/service_account.d.ts +11 -0
  210. package/dist/types/tools/application_integration_tool/application_integration_toolset.d.ts +86 -0
  211. package/dist/types/tools/application_integration_tool/clients/cloud_request.d.ts +53 -0
  212. package/dist/types/tools/application_integration_tool/clients/connections_client.d.ts +215 -0
  213. package/dist/types/tools/application_integration_tool/clients/integration_client.d.ts +72 -0
  214. package/dist/types/tools/crewai_tool.d.ts +85 -0
  215. package/dist/types/tools/example_tool.d.ts +10 -0
  216. package/dist/types/tools/function_tool.d.ts +32 -0
  217. package/dist/types/tools/google_api_tool/google_api_tool.d.ts +30 -0
  218. package/dist/types/tools/google_api_tool/google_api_tool_set.d.ts +78 -0
  219. package/dist/types/tools/google_api_tool/google_api_tool_sets.d.ts +33 -0
  220. package/dist/types/tools/google_api_tool/googleapi_to_openapi_converter.d.ts +164 -0
  221. package/dist/types/tools/google_api_tool/index.d.ts +11 -0
  222. package/dist/types/tools/langchain_tool.d.ts +103 -0
  223. package/dist/types/tools/mcp/index.d.ts +3 -0
  224. package/dist/types/tools/mcp/mcp_session_manager.d.ts +34 -1
  225. package/dist/types/tools/mcp/mcp_toolset.d.ts +15 -0
  226. package/dist/types/tools/openapi_tool/auth/auth_helpers.d.ts +19 -0
  227. package/dist/types/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.d.ts +18 -1
  228. package/dist/types/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.d.ts +2 -1
  229. package/dist/types/tools/retrieval/base_retrieval_tool.d.ts +15 -0
  230. package/dist/types/tools/toolbox_tool.d.ts +73 -0
  231. package/dist/types/utils/env_aware_utils.d.ts +18 -2
  232. package/dist/types/utils/error_utils.d.ts +7 -0
  233. package/dist/types/utils/file_utils.d.ts +6 -1
  234. package/dist/types/utils/gemini_schema_util.d.ts +1 -2
  235. package/dist/types/utils/json_utils.d.ts +11 -0
  236. package/dist/types/utils/object_notation_utils.d.ts +7 -0
  237. package/dist/types/utils/streaming_utils.d.ts +11 -4
  238. package/dist/types/version.d.ts +1 -1
  239. package/dist/web/index_web.js +105 -106
  240. package/dist/web/index_web.js.map +4 -4
  241. package/package.json +8 -3
@@ -0,0 +1,339 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ var __defProp = Object.defineProperty;
4
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
5
+ /**
6
+ * @license
7
+ * Copyright 2026 Google LLC
8
+ * SPDX-License-Identifier: Apache-2.0
9
+ */
10
+ import { createEvent, getFunctionCalls } from "../events/event.js";
11
+ import {
12
+ INTERNAL_METADATA_PREFIX,
13
+ markRestored,
14
+ RESTORED_EVENT_KEY
15
+ } from "../events/internal_metadata.js";
16
+ import { logger } from "../utils/logger.js";
17
+ import { BasePlugin } from "./base_plugin.js";
18
+ const TOOL_CALL_HMAC_METADATA_KEY = `${INTERNAL_METADATA_PREFIX}fc_hmac`;
19
+ const STAMP_PREFIX = "v1:";
20
+ const _ToolCallIntegrityError = class _ToolCallIntegrityError extends Error {
21
+ constructor(message) {
22
+ super(message);
23
+ this.name = "ToolCallIntegrityError";
24
+ }
25
+ };
26
+ __name(_ToolCallIntegrityError, "ToolCallIntegrityError");
27
+ let ToolCallIntegrityError = _ToolCallIntegrityError;
28
+ function jsonForm(value) {
29
+ const json = JSON.stringify(value);
30
+ return json === void 0 ? null : JSON.parse(json);
31
+ }
32
+ __name(jsonForm, "jsonForm");
33
+ function canonicalJson(value) {
34
+ if (Array.isArray(value)) {
35
+ return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
36
+ }
37
+ if (value !== null && typeof value === "object") {
38
+ const object = value;
39
+ const entries = Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`);
40
+ return `{${entries.join(",")}}`;
41
+ }
42
+ return JSON.stringify(value);
43
+ }
44
+ __name(canonicalJson, "canonicalJson");
45
+ function jsonArgs(args) {
46
+ const json = jsonForm(args != null ? args : {});
47
+ return json != null ? json : {};
48
+ }
49
+ __name(jsonArgs, "jsonArgs");
50
+ function canonicalPayload(session, event, functionCall) {
51
+ var _a, _b, _c, _d, _e;
52
+ return new TextEncoder().encode(
53
+ canonicalJson({
54
+ app_name: session.appName,
55
+ user_id: session.userId,
56
+ session_id: session.id,
57
+ invocation_id: (_a = event.invocationId) != null ? _a : null,
58
+ branch: (_b = event.branch) != null ? _b : null,
59
+ author: (_c = event.author) != null ? _c : null,
60
+ name: (_d = functionCall.name) != null ? _d : null,
61
+ id: (_e = functionCall.id) != null ? _e : null,
62
+ args: jsonArgs(functionCall.args)
63
+ })
64
+ );
65
+ }
66
+ __name(canonicalPayload, "canonicalPayload");
67
+ function isStampMap(value) {
68
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.values(value).every(
69
+ // eslint-disable-next-line no-control-regex
70
+ (stamp) => typeof stamp === "string" && /^[\x00-\x7f]*$/.test(stamp)
71
+ );
72
+ }
73
+ __name(isStampMap, "isStampMap");
74
+ function isRestored(event) {
75
+ var _a;
76
+ return Boolean((_a = event.customMetadata) == null ? void 0 : _a[RESTORED_EVENT_KEY]);
77
+ }
78
+ __name(isRestored, "isRestored");
79
+ function getStamps(event) {
80
+ var _a;
81
+ const stamps = (_a = event.customMetadata) == null ? void 0 : _a[TOOL_CALL_HMAC_METADATA_KEY];
82
+ if (stamps === void 0 || stamps === null) {
83
+ return {};
84
+ }
85
+ if (!isStampMap(stamps)) {
86
+ throw new ToolCallIntegrityError(
87
+ `Event '${event.id}' has a malformed integrity stamp.`
88
+ );
89
+ }
90
+ return stamps;
91
+ }
92
+ __name(getStamps, "getStamps");
93
+ function hasStamp(stamps, callId) {
94
+ return Object.hasOwn(stamps, callId);
95
+ }
96
+ __name(hasStamp, "hasStamp");
97
+ function toHex(bytes) {
98
+ return Array.from(
99
+ new Uint8Array(bytes),
100
+ (b) => b.toString(16).padStart(2, "0")
101
+ ).join("");
102
+ }
103
+ __name(toHex, "toHex");
104
+ function fromHex(hex) {
105
+ if (!/^[0-9a-f]{64}$/.test(hex)) {
106
+ return void 0;
107
+ }
108
+ const bytes = new Uint8Array(hex.length / 2);
109
+ for (let i = 0; i < bytes.length; i++) {
110
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
111
+ }
112
+ return bytes;
113
+ }
114
+ __name(fromHex, "fromHex");
115
+ function getSubtleCrypto() {
116
+ var _a;
117
+ const subtle = (_a = globalThis.crypto) == null ? void 0 : _a.subtle;
118
+ if (!subtle) {
119
+ throw new Error(
120
+ "ToolCallIntegrityPlugin requires the Web Crypto API (globalThis.crypto.subtle), which is not available in this environment."
121
+ );
122
+ }
123
+ return subtle;
124
+ }
125
+ __name(getSubtleCrypto, "getSubtleCrypto");
126
+ const _ToolCallIntegrityPlugin = class _ToolCallIntegrityPlugin extends BasePlugin {
127
+ /**
128
+ * @throws {Error} If `secretKey` is empty or contains a key that is not
129
+ * non-empty bytes.
130
+ */
131
+ constructor(options) {
132
+ var _a, _b;
133
+ super((_a = options.name) != null ? _a : "tool_call_integrity");
134
+ const secretKey = options.secretKey;
135
+ const rawKeys = secretKey instanceof Uint8Array ? [secretKey] : Array.isArray(secretKey) ? [...secretKey] : [];
136
+ if (rawKeys.length === 0 || !rawKeys.every((key) => key instanceof Uint8Array && key.length > 0)) {
137
+ throw new Error(
138
+ "secretKey must be non-empty bytes or a non-empty list of them."
139
+ );
140
+ }
141
+ this.keys = rawKeys.map((key) => new Uint8Array(key));
142
+ this.allowUnstampedCalls = (_b = options.allowUnstampedCalls) != null ? _b : false;
143
+ }
144
+ /**
145
+ * Returns a copy with internal metadata removed and marked as restored.
146
+ *
147
+ * Use it on events that your code copies into another session, so that the
148
+ * history passes the integrity check. The copy only keeps the history: its
149
+ * function calls are never executed.
150
+ *
151
+ * @param event The event to copy. It is not modified.
152
+ * @returns The marked copy, ready to append to the new session.
153
+ */
154
+ static prepareRestoredEvent(event) {
155
+ return markRestored(createEvent(structuredClone(event)));
156
+ }
157
+ getCryptoKeys() {
158
+ if (!this.cryptoKeys) {
159
+ const subtle = getSubtleCrypto();
160
+ this.cryptoKeys = Promise.all(
161
+ this.keys.map(
162
+ (key) => subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, [
163
+ "sign",
164
+ "verify"
165
+ ])
166
+ )
167
+ );
168
+ }
169
+ return this.cryptoKeys;
170
+ }
171
+ async sign(payload) {
172
+ const [primary] = await this.getCryptoKeys();
173
+ const digest = await getSubtleCrypto().sign("HMAC", primary, payload);
174
+ return STAMP_PREFIX + toHex(digest);
175
+ }
176
+ /** `subtle.verify` compares in constant time. */
177
+ async verify(payload, stamp) {
178
+ if (!stamp.startsWith(STAMP_PREFIX)) {
179
+ return false;
180
+ }
181
+ const signature = fromHex(stamp.slice(STAMP_PREFIX.length));
182
+ if (!signature) {
183
+ return false;
184
+ }
185
+ const subtle = getSubtleCrypto();
186
+ for (const key of await this.getCryptoKeys()) {
187
+ if (await subtle.verify("HMAC", key, signature, payload)) {
188
+ return true;
189
+ }
190
+ }
191
+ return false;
192
+ }
193
+ unstamped(name, callId) {
194
+ const message = `${name} call '${callId}' has no integrity stamp.`;
195
+ if (!this.allowUnstampedCalls) {
196
+ throw new ToolCallIntegrityError(message);
197
+ }
198
+ logger.warn(message);
199
+ }
200
+ async onEventCallback({
201
+ invocationContext,
202
+ event
203
+ }) {
204
+ var _a;
205
+ const session = invocationContext.session;
206
+ const calls = getFunctionCalls(event).filter((fc) => fc.id);
207
+ if (!event.partial) {
208
+ const seen = /* @__PURE__ */ new Set();
209
+ for (const fc of calls) {
210
+ if (seen.has(fc.id)) {
211
+ throw new ToolCallIntegrityError(
212
+ `Event '${event.id}' repeats function call ID '${fc.id}'.`
213
+ );
214
+ }
215
+ seen.add(fc.id);
216
+ }
217
+ }
218
+ const stamps = {};
219
+ for (const fc of calls) {
220
+ stamps[fc.id] = await this.sign(canonicalPayload(session, event, fc));
221
+ }
222
+ if (Object.keys(stamps).length > 0) {
223
+ event.customMetadata = {
224
+ ...(_a = event.customMetadata) != null ? _a : {},
225
+ [TOOL_CALL_HMAC_METADATA_KEY]: stamps
226
+ };
227
+ }
228
+ return void 0;
229
+ }
230
+ async beforeRunCallback({
231
+ invocationContext
232
+ }) {
233
+ const session = invocationContext.session;
234
+ for (const event of session.events) {
235
+ const calls = getFunctionCalls(event);
236
+ if (calls.length === 0 || isRestored(event)) {
237
+ continue;
238
+ }
239
+ const stamps = getStamps(event);
240
+ const verified = /* @__PURE__ */ new Set();
241
+ for (const fc of calls) {
242
+ if (!fc.id) {
243
+ continue;
244
+ }
245
+ if (!hasStamp(stamps, fc.id)) {
246
+ this.unstamped(fc.name, fc.id);
247
+ continue;
248
+ }
249
+ if (verified.has(fc.id)) {
250
+ throw new ToolCallIntegrityError(
251
+ `Event '${event.id}' has duplicate function call ID '${fc.id}'.`
252
+ );
253
+ }
254
+ const payload = canonicalPayload(session, event, fc);
255
+ if (!await this.verify(payload, stamps[fc.id])) {
256
+ throw new ToolCallIntegrityError(
257
+ `${fc.name} call '${fc.id}' does not match its integrity stamp.`
258
+ );
259
+ }
260
+ verified.add(fc.id);
261
+ }
262
+ const unmatched = Object.keys(stamps).filter((id) => !verified.has(id)).sort();
263
+ if (unmatched.length > 0) {
264
+ throw new ToolCallIntegrityError(
265
+ `Event '${event.id}' has integrity stamps with no matching call: ${JSON.stringify(unmatched)}.`
266
+ );
267
+ }
268
+ }
269
+ return void 0;
270
+ }
271
+ async beforeToolCallback({
272
+ tool,
273
+ toolArgs,
274
+ toolContext
275
+ }) {
276
+ const callId = toolContext.functionCallId;
277
+ if (!callId) {
278
+ throw new ToolCallIntegrityError(
279
+ `${tool.name} call has no ID, so its integrity cannot be checked.`
280
+ );
281
+ }
282
+ const session = toolContext.invocationContext.session;
283
+ const stored = [];
284
+ let restored = false;
285
+ for (const event of session.events) {
286
+ for (const fc of getFunctionCalls(event)) {
287
+ if (fc.id !== callId) {
288
+ continue;
289
+ }
290
+ if (isRestored(event)) {
291
+ restored = true;
292
+ } else {
293
+ stored.push([event, fc]);
294
+ }
295
+ }
296
+ }
297
+ if (stored.length === 0) {
298
+ if (restored) {
299
+ throw new ToolCallIntegrityError(
300
+ `${tool.name} call '${callId}' comes from restored history and cannot be executed.`
301
+ );
302
+ }
303
+ this.unstamped(tool.name, callId);
304
+ return void 0;
305
+ }
306
+ const trusted = [];
307
+ for (const [event, fc] of stored) {
308
+ const stamps = getStamps(event);
309
+ if (!hasStamp(stamps, callId)) {
310
+ this.unstamped(tool.name, callId);
311
+ } else if (!await this.verify(
312
+ canonicalPayload(session, event, fc),
313
+ stamps[callId]
314
+ )) {
315
+ throw new ToolCallIntegrityError(
316
+ `${tool.name} call '${callId}' does not match its integrity stamp.`
317
+ );
318
+ }
319
+ trusted.push(fc);
320
+ }
321
+ const executed = canonicalJson(jsonArgs(toolArgs));
322
+ const matches = trusted.some(
323
+ (fc) => fc.name === tool.name && canonicalJson(jsonArgs(fc.args)) === executed
324
+ );
325
+ if (!matches) {
326
+ throw new ToolCallIntegrityError(
327
+ `${tool.name} call '${callId}' arguments do not match its stored call.`
328
+ );
329
+ }
330
+ return void 0;
331
+ }
332
+ };
333
+ __name(_ToolCallIntegrityPlugin, "ToolCallIntegrityPlugin");
334
+ let ToolCallIntegrityPlugin = _ToolCallIntegrityPlugin;
335
+ export {
336
+ TOOL_CALL_HMAC_METADATA_KEY,
337
+ ToolCallIntegrityError,
338
+ ToolCallIntegrityPlugin
339
+ };
@@ -18,28 +18,23 @@ const _InMemoryRunner = class _InMemoryRunner extends Runner {
18
18
  * @param params The configuration for the runner.
19
19
  * @param params.app An optional application instance to run.
20
20
  * @param params.agent The root agent to run.
21
- * @param params.appName The application name. Defaults to `'InMemoryRunner'`.
21
+ * @param params.appName The application name. Defaults to `app.name` when
22
+ * `app` is provided, or `'InMemoryRunner'` otherwise.
22
23
  * @param params.plugins An optional list of plugins.
23
24
  * @param params.resumabilityConfig An optional resumability configuration.
24
25
  */
25
26
  constructor(params) {
26
- var _a;
27
- const {
28
- agent,
29
- appName = "InMemoryRunner",
30
- plugins = [],
31
- app,
32
- resumabilityConfig
33
- } = params;
27
+ var _a, _b;
28
+ const { agent, appName, plugins = [], app, resumabilityConfig } = params;
34
29
  super({
35
30
  app,
36
- appName,
31
+ appName: (_a = appName != null ? appName : app == null ? void 0 : app.name) != null ? _a : "InMemoryRunner",
37
32
  agent,
38
33
  plugins,
39
34
  artifactService: new InMemoryArtifactService(),
40
35
  sessionService: new InMemorySessionService(),
41
36
  memoryService: new InMemoryMemoryService(),
42
- resumabilityConfig: (_a = app == null ? void 0 : app.resumabilityConfig) != null ? _a : resumabilityConfig
37
+ resumabilityConfig: (_b = app == null ? void 0 : app.resumabilityConfig) != null ? _b : resumabilityConfig
43
38
  });
44
39
  }
45
40
  };
@@ -31,8 +31,13 @@ import {
31
31
  BuiltInCodeExecutor,
32
32
  isBuiltInCodeExecutor
33
33
  } from "../code_executors/built_in_code_executor.js";
34
+ import { buildAbortEvents, isAbortEvent } from "../events/abort_events.js";
34
35
  import { createEvent } from "../events/event.js";
35
36
  import { createEventActions } from "../events/event_actions.js";
37
+ import {
38
+ internalMetadata,
39
+ withoutInternalMetadata
40
+ } from "../events/internal_metadata.js";
36
41
  import { PluginManager } from "../plugins/plugin_manager.js";
37
42
  import {
38
43
  runAsyncGeneratorWithOtelContext,
@@ -60,8 +65,8 @@ const _Runner = class _Runner {
60
65
  */
61
66
  constructor(input) {
62
67
  this[_a] = true;
63
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i;
64
- const appName = (_b = (_a2 = input.app) == null ? void 0 : _a2.name) != null ? _b : input.appName;
68
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j;
69
+ const appName = (_b = input.appName) != null ? _b : (_a2 = input.app) == null ? void 0 : _a2.name;
65
70
  const agent = (_d = (_c = input.app) == null ? void 0 : _c.rootAgent) != null ? _d : input.agent;
66
71
  if (!agent) {
67
72
  throw new Error(
@@ -78,6 +83,20 @@ const _Runner = class _Runner {
78
83
  this.memoryService = input.memoryService;
79
84
  this.credentialService = input.credentialService;
80
85
  this.resumabilityConfig = (_i = (_h = input.app) == null ? void 0 : _h.resumabilityConfig) != null ? _i : input.resumabilityConfig;
86
+ this.autoCreateSession = (_j = input.autoCreateSession) != null ? _j : false;
87
+ }
88
+ /**
89
+ * Looks the session up, creating it first when `autoCreateSession` is set.
90
+ *
91
+ * A runner with no `appName` cannot address a session, so it falls through to
92
+ * the plain lookup rather than creating one under an undefined app name.
93
+ */
94
+ async resolveSession(userId, sessionId) {
95
+ const key = { appName: this.appName, userId, sessionId };
96
+ if (this.autoCreateSession && this.appName) {
97
+ return this.sessionService.getOrCreateSession(key);
98
+ }
99
+ return this.sessionService.getSession(key);
81
100
  }
82
101
  /**
83
102
  * Runs the agent with a new, ephemeral session.
@@ -138,12 +157,8 @@ const _Runner = class _Runner {
138
157
  ctx,
139
158
  this,
140
159
  async function* () {
141
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
142
- const session = await this.sessionService.getSession({
143
- appName: this.appName,
144
- userId,
145
- sessionId
146
- });
160
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
161
+ const session = await this.resolveSession(userId, sessionId);
147
162
  if ((_a2 = params.abortSignal) == null ? void 0 : _a2.aborted) {
148
163
  return;
149
164
  }
@@ -218,7 +233,8 @@ const _Runner = class _Runner {
218
233
  author: "user",
219
234
  actions: stateDelta ? createEventActions({ stateDelta }) : void 0,
220
235
  content: newMessage,
221
- customMetadata: params.customMetadata
236
+ // Callers cannot set ADK-internal keys.
237
+ customMetadata: withoutInternalMetadata(params.customMetadata)
222
238
  })
223
239
  });
224
240
  if ((_e = params.abortSignal) == null ? void 0 : _e.aborted) {
@@ -253,35 +269,45 @@ const _Runner = class _Runner {
253
269
  }
254
270
  yield earlyExitEvent;
255
271
  } else {
256
- for await (const event of this.runRoot(invocationContext)) {
257
- if ((_h = params.abortSignal) == null ? void 0 : _h.aborted) {
258
- return;
259
- }
260
- const modifiedEvent = await this.pluginManager.runOnEventCallback({
261
- invocationContext,
262
- event
263
- });
264
- const outputEvent = modifiedEvent ? {
265
- ...modifiedEvent,
266
- id: event.id,
267
- invocationId: event.invocationId,
268
- timestamp: event.timestamp,
269
- author: modifiedEvent.author || event.author,
270
- branch: (_i = modifiedEvent.branch) != null ? _i : event.branch
271
- } : event;
272
- if (!event.partial) {
273
- await this.sessionService.appendEvent({
274
- session,
275
- event: outputEvent
276
- });
272
+ let abortSealed = false;
273
+ const sealAbortedInvocation = /* @__PURE__ */ __name(() => {
274
+ abortSealed = true;
275
+ return this.synthesizeAbortEvents(invocationContext);
276
+ }, "sealAbortedInvocation");
277
+ try {
278
+ for await (const event of this.runRoot(invocationContext)) {
279
+ if ((_h = params.abortSignal) == null ? void 0 : _h.aborted) {
280
+ break;
281
+ }
282
+ const outputEvent = await this.processAndAppendEvent(
283
+ invocationContext,
284
+ event
285
+ );
286
+ if ((_i = params.abortSignal) == null ? void 0 : _i.aborted) {
287
+ break;
288
+ }
289
+ yield outputEvent;
277
290
  }
278
291
  if ((_j = params.abortSignal) == null ? void 0 : _j.aborted) {
292
+ for (const abortEvent of await sealAbortedInvocation()) {
293
+ yield abortEvent;
294
+ }
279
295
  return;
280
296
  }
281
- yield outputEvent;
297
+ } finally {
298
+ if (((_k = params.abortSignal) == null ? void 0 : _k.aborted) && !abortSealed) {
299
+ try {
300
+ await sealAbortedInvocation();
301
+ } catch (e) {
302
+ logger.error(
303
+ `Failed to seal aborted invocation ${invocationContext.invocationId}.`,
304
+ e
305
+ );
306
+ }
307
+ }
282
308
  }
283
309
  await this.pluginManager.runAfterRunCallback({ invocationContext });
284
- if ((_k = params.abortSignal) == null ? void 0 : _k.aborted) {
310
+ if ((_l = params.abortSignal) == null ? void 0 : _l.aborted) {
285
311
  return;
286
312
  }
287
313
  }
@@ -313,6 +339,56 @@ const _Runner = class _Runner {
313
339
  }
314
340
  yield* runNodeAsInvocation(this.agent, invocationContext);
315
341
  }
342
+ /**
343
+ * Runs the on_event plugin callbacks on an event and appends the result to
344
+ * the session unless it is partial.
345
+ *
346
+ * @returns The event as streamed to the caller.
347
+ */
348
+ async processAndAppendEvent(invocationContext, event) {
349
+ var _a2;
350
+ const modifiedEvent = await this.pluginManager.runOnEventCallback({
351
+ invocationContext,
352
+ event
353
+ });
354
+ const outputEvent = modifiedEvent ? {
355
+ ...withInternalMetadataOf(event, modifiedEvent),
356
+ id: event.id,
357
+ invocationId: event.invocationId,
358
+ timestamp: event.timestamp,
359
+ author: modifiedEvent.author || event.author,
360
+ branch: (_a2 = modifiedEvent.branch) != null ? _a2 : event.branch
361
+ } : event;
362
+ if (!event.partial) {
363
+ await this.sessionService.appendEvent({
364
+ session: invocationContext.session,
365
+ event: outputEvent
366
+ });
367
+ }
368
+ return outputEvent;
369
+ }
370
+ /**
371
+ * Seals an aborted invocation in session history: answers its dangling
372
+ * function calls with error responses, or records a plain abort event when
373
+ * there is nothing to answer.
374
+ *
375
+ * @returns The synthetic events after plugin processing and persistence.
376
+ */
377
+ async synthesizeAbortEvents(invocationContext) {
378
+ const abortEvents = buildAbortEvents({
379
+ events: invocationContext.session.events,
380
+ invocationId: invocationContext.invocationId,
381
+ rootAgentName: this.agent.name,
382
+ branch: invocationContext.branch
383
+ });
384
+ const outputEvents = [];
385
+ for (const event of abortEvents) {
386
+ outputEvents.push(
387
+ await this.processAndAppendEvent(invocationContext, event)
388
+ );
389
+ }
390
+ return outputEvents;
391
+ }
316
392
  /**
317
393
  * Saves artifacts from the message parts and replaces the inline data with
318
394
  * a file name placeholder and optional file reference.
@@ -514,7 +590,7 @@ const _Runner = class _Runner {
514
590
  if ((_d2 = params.abortSignal) == null ? void 0 : _d2.aborted) {
515
591
  return;
516
592
  }
517
- const eventToProcess = modifiedEvent != null ? modifiedEvent : event;
593
+ const eventToProcess = modifiedEvent ? withInternalMetadataOf(event, modifiedEvent) : event;
518
594
  if (!eventToProcess.partial && !isLiveModelMediaEventWithInlineData(eventToProcess)) {
519
595
  await this.sessionService.appendEvent({
520
596
  session,
@@ -533,6 +609,18 @@ const _Runner = class _Runner {
533
609
  };
534
610
  __name(_Runner, "Runner");
535
611
  let Runner = _Runner;
612
+ function withInternalMetadataOf(original, replacement) {
613
+ var _a2;
614
+ const internal = internalMetadata(original.customMetadata);
615
+ if (Object.keys(internal).length === 0) {
616
+ return replacement;
617
+ }
618
+ return {
619
+ ...replacement,
620
+ customMetadata: { ...(_a2 = replacement.customMetadata) != null ? _a2 : {}, ...internal }
621
+ };
622
+ }
623
+ __name(withInternalMetadataOf, "withInternalMetadataOf");
536
624
  function isLiveModelMediaEventWithInlineData(event) {
537
625
  var _a2;
538
626
  const parts = (_a2 = event.content) == null ? void 0 : _a2.parts;
@@ -547,7 +635,8 @@ function isLiveModelMediaEventWithInlineData(event) {
547
635
  }
548
636
  __name(isLiveModelMediaEventWithInlineData, "isLiveModelMediaEventWithInlineData");
549
637
  function determineAgentForResumption(session, rootAgent, resumabilityConfig) {
550
- const event = findEventByLastFunctionResponseId(session.events);
638
+ const lastEvent = session.events[session.events.length - 1];
639
+ const event = lastEvent && !isAbortEvent(lastEvent) ? findEventByLastFunctionResponseId(session.events) : null;
551
640
  const isResumable = Boolean(resumabilityConfig == null ? void 0 : resumabilityConfig.isResumable);
552
641
  if (event && event.author && isResumable) {
553
642
  const conflictingAuthors = getConflictingFunctionResponseAuthors(
@@ -571,7 +660,7 @@ function determineAgentForResumption(session, rootAgent, resumabilityConfig) {
571
660
  for (let i = session.events.length - 1; i >= 0; i--) {
572
661
  logger.debug("event:", stringifyWithRedactedInlineData(session.events[i]));
573
662
  const event2 = session.events[i];
574
- if (event2.author === "user" || !event2.author) {
663
+ if (event2.author === "user" || !event2.author || isAbortEvent(event2)) {
575
664
  continue;
576
665
  }
577
666
  if (event2.author === rootAgent.name) {
@@ -281,7 +281,7 @@ async function getConnectionOptionsFromUri(uri) {
281
281
  );
282
282
  return {
283
283
  entities: ENTITIES,
284
- dbName: uri === "sqlite://:memory:" ? ":memory:" : uri.substring("sqlite://".length),
284
+ dbName: uri === "sqlite://:memory:" || uri === "sqlite:///:memory:" ? ":memory:" : uri.substring("sqlite://".length),
285
285
  driver: SqliteDriver
286
286
  };
287
287
  }
@@ -47,7 +47,9 @@ const _InMemorySessionService = class _InMemorySessionService extends BaseSessio
47
47
  var _a;
48
48
  const filteredState = state ? trimTempState(state) : void 0;
49
49
  const session = createSession({
50
- id: sessionId || randomUUID(),
50
+ // Surrounding whitespace is dropped so that a later lookup by the bare
51
+ // id finds the session, and a blank id gets a generated one.
52
+ id: (sessionId == null ? void 0 : sessionId.trim()) || randomUUID(),
51
53
  appName,
52
54
  userId,
53
55
  state: filteredState,
@@ -74,16 +74,19 @@ const _State = class _State {
74
74
  /**
75
75
  * Returns the value of the state dict for the given key.
76
76
  *
77
+ * Only keys the state holds itself are found. Names inherited from
78
+ * `Object.prototype`, such as `toString`, are treated as missing.
79
+ *
77
80
  * @param key The key to get the value for.
78
81
  * @param defaultValue The default value to return if the key is not found.
79
82
  * @return The value of the state for the given key, or the default value if
80
83
  * not found.
81
84
  */
82
85
  get(key, defaultValue) {
83
- if (key in this.delta) {
86
+ if (Object.hasOwn(this.delta, key)) {
84
87
  return this.delta[key];
85
88
  }
86
- if (key in this.value) {
89
+ if (Object.hasOwn(this.value, key)) {
87
90
  return this.value[key];
88
91
  }
89
92
  return defaultValue;
@@ -101,10 +104,11 @@ const _State = class _State {
101
104
  recordStateWrite(this.value, this.delta, key);
102
105
  }
103
106
  /**
104
- * Whether the state has pending delta.
107
+ * Whether the state holds the given key, either as a stored value or as a
108
+ * pending delta. Names inherited from `Object.prototype` are not keys.
105
109
  */
106
110
  has(key) {
107
- return key in this.value || key in this.delta;
111
+ return Object.hasOwn(this.value, key) || Object.hasOwn(this.delta, key);
108
112
  }
109
113
  /**
110
114
  * Whether the state has pending delta.