@google/adk 0.4.0 → 0.6.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 (221) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/a2a/a2a_event.js +317 -0
  3. package/dist/cjs/a2a/a2a_remote_agent.js +174 -0
  4. package/dist/cjs/a2a/a2a_remote_agent_run_processor.js +198 -0
  5. package/dist/cjs/a2a/a2a_remote_agent_utils.js +165 -0
  6. package/dist/cjs/a2a/agent_card.js +380 -0
  7. package/dist/cjs/a2a/agent_executor.js +221 -0
  8. package/dist/cjs/a2a/agent_to_a2a.js +115 -0
  9. package/dist/cjs/a2a/event_converter_utils.js +201 -0
  10. package/dist/cjs/a2a/event_processor_utils.js +180 -0
  11. package/dist/cjs/a2a/executor_context.js +53 -0
  12. package/dist/cjs/a2a/metadata_converter_utils.js +126 -0
  13. package/dist/cjs/a2a/part_converter_utils.js +47 -34
  14. package/dist/cjs/agents/base_agent.js +3 -3
  15. package/dist/cjs/{tools/tool_context.js → agents/context.js} +70 -15
  16. package/dist/cjs/agents/functions.js +2 -2
  17. package/dist/cjs/agents/llm_agent.js +38 -674
  18. package/dist/cjs/agents/processors/agent_transfer_llm_request_processor.js +132 -0
  19. package/dist/cjs/agents/processors/basic_llm_request_processor.js +68 -0
  20. package/dist/cjs/agents/processors/code_execution_request_processor.js +389 -0
  21. package/dist/cjs/agents/{content_processor_utils.js → processors/content_processor_utils.js} +21 -2
  22. package/dist/cjs/agents/processors/content_request_processor.js +87 -0
  23. package/dist/cjs/agents/processors/context_compactor_request_processor.js +61 -0
  24. package/dist/cjs/agents/processors/identity_llm_request_processor.js +54 -0
  25. package/dist/cjs/agents/processors/instructions_llm_request_processor.js +85 -0
  26. package/dist/cjs/agents/processors/request_confirmation_llm_request_processor.js +165 -0
  27. package/dist/cjs/artifacts/file_artifact_service.js +35 -4
  28. package/dist/cjs/common.js +48 -7
  29. package/dist/cjs/context/base_context_compactor.js +27 -0
  30. package/dist/cjs/context/summarizers/base_summarizer.js +27 -0
  31. package/dist/cjs/context/summarizers/llm_summarizer.js +93 -0
  32. package/dist/cjs/context/token_based_context_compactor.js +135 -0
  33. package/dist/cjs/context/truncating_context_compactor.js +58 -0
  34. package/dist/cjs/events/compacted_event.js +53 -0
  35. package/dist/cjs/index.js +113 -53
  36. package/dist/cjs/index.js.map +7 -0
  37. package/dist/cjs/memory/in_memory_memory_service.js +1 -1
  38. package/dist/cjs/models/llm_response.js +2 -0
  39. package/dist/cjs/plugins/base_plugin.js +1 -1
  40. package/dist/cjs/runner/runner.js +20 -11
  41. package/dist/cjs/sessions/database_session_service.js +4 -1
  42. package/dist/cjs/sessions/db/operations.js +25 -23
  43. package/dist/cjs/sessions/state.js +2 -2
  44. package/dist/cjs/tools/agent_tool.js +6 -5
  45. package/dist/cjs/tools/base_tool.js +3 -0
  46. package/dist/cjs/tools/base_toolset.js +13 -3
  47. package/dist/cjs/tools/exit_loop_tool.js +63 -0
  48. package/dist/cjs/tools/load_artifacts_tool.js +188 -0
  49. package/dist/cjs/tools/load_memory_tool.js +107 -0
  50. package/dist/cjs/tools/mcp/mcp_toolset.js +9 -5
  51. package/dist/cjs/tools/preload_memory_tool.js +109 -0
  52. package/dist/cjs/utils/logger.js +62 -54
  53. package/dist/cjs/version.js +1 -1
  54. package/dist/esm/a2a/a2a_event.js +269 -0
  55. package/dist/esm/a2a/a2a_remote_agent.js +148 -0
  56. package/dist/esm/a2a/a2a_remote_agent_run_processor.js +175 -0
  57. package/dist/esm/a2a/a2a_remote_agent_utils.js +131 -0
  58. package/dist/esm/a2a/agent_card.js +340 -0
  59. package/dist/esm/a2a/agent_executor.js +202 -0
  60. package/dist/esm/a2a/agent_to_a2a.js +80 -0
  61. package/dist/esm/a2a/event_converter_utils.js +187 -0
  62. package/dist/esm/a2a/event_processor_utils.js +159 -0
  63. package/dist/esm/a2a/executor_context.js +23 -0
  64. package/dist/esm/a2a/metadata_converter_utils.js +91 -0
  65. package/dist/esm/a2a/part_converter_utils.js +49 -34
  66. package/dist/esm/agents/base_agent.js +3 -3
  67. package/dist/{web/tools/tool_context.js → esm/agents/context.js} +66 -11
  68. package/dist/esm/agents/functions.js +2 -2
  69. package/dist/esm/agents/llm_agent.js +31 -683
  70. package/dist/esm/agents/processors/agent_transfer_llm_request_processor.js +101 -0
  71. package/dist/esm/agents/processors/basic_llm_request_processor.js +37 -0
  72. package/dist/esm/agents/processors/code_execution_request_processor.js +363 -0
  73. package/dist/esm/agents/{content_processor_utils.js → processors/content_processor_utils.js} +23 -2
  74. package/dist/esm/agents/processors/content_request_processor.js +59 -0
  75. package/dist/esm/agents/processors/context_compactor_request_processor.js +31 -0
  76. package/dist/esm/agents/processors/identity_llm_request_processor.js +23 -0
  77. package/dist/esm/agents/processors/instructions_llm_request_processor.js +54 -0
  78. package/dist/esm/agents/processors/request_confirmation_llm_request_processor.js +140 -0
  79. package/dist/esm/artifacts/file_artifact_service.js +30 -3
  80. package/dist/esm/common.js +44 -10
  81. package/dist/esm/context/base_context_compactor.js +5 -0
  82. package/dist/esm/context/summarizers/base_summarizer.js +5 -0
  83. package/dist/esm/context/summarizers/llm_summarizer.js +65 -0
  84. package/dist/esm/context/token_based_context_compactor.js +105 -0
  85. package/dist/esm/context/truncating_context_compactor.js +28 -0
  86. package/dist/esm/events/compacted_event.js +22 -0
  87. package/dist/esm/index.js +119 -18
  88. package/dist/esm/index.js.map +7 -0
  89. package/dist/esm/memory/in_memory_memory_service.js +1 -1
  90. package/dist/esm/models/llm_response.js +2 -0
  91. package/dist/esm/plugins/base_plugin.js +1 -1
  92. package/dist/esm/runner/runner.js +18 -10
  93. package/dist/esm/sessions/database_session_service.js +4 -1
  94. package/dist/esm/sessions/db/operations.js +32 -18
  95. package/dist/esm/sessions/state.js +2 -2
  96. package/dist/esm/tools/agent_tool.js +6 -5
  97. package/dist/esm/tools/base_tool.js +3 -0
  98. package/dist/esm/tools/base_toolset.js +11 -2
  99. package/dist/esm/tools/exit_loop_tool.js +32 -0
  100. package/dist/esm/tools/load_artifacts_tool.js +159 -0
  101. package/dist/esm/tools/load_memory_tool.js +78 -0
  102. package/dist/esm/tools/mcp/mcp_toolset.js +9 -5
  103. package/dist/esm/tools/preload_memory_tool.js +80 -0
  104. package/dist/esm/utils/logger.js +52 -54
  105. package/dist/esm/version.js +1 -1
  106. package/dist/types/a2a/a2a_event.d.ts +139 -0
  107. package/dist/types/a2a/a2a_remote_agent.d.ts +63 -0
  108. package/dist/types/a2a/a2a_remote_agent_run_processor.d.ts +31 -0
  109. package/dist/types/a2a/a2a_remote_agent_utils.d.ts +38 -0
  110. package/dist/types/a2a/agent_card.d.ts +23 -0
  111. package/dist/types/a2a/agent_executor.d.ts +52 -0
  112. package/dist/types/a2a/agent_to_a2a.d.ts +45 -0
  113. package/dist/types/a2a/event_converter_utils.d.ts +20 -0
  114. package/dist/types/a2a/event_processor_utils.d.ts +24 -0
  115. package/dist/types/a2a/executor_context.d.ts +33 -0
  116. package/dist/types/a2a/metadata_converter_utils.d.ts +63 -0
  117. package/dist/types/a2a/part_converter_utils.d.ts +4 -3
  118. package/dist/types/agents/base_agent.d.ts +2 -2
  119. package/dist/types/{tools/tool_context.d.ts → agents/context.d.ts} +43 -8
  120. package/dist/types/agents/llm_agent.d.ts +14 -31
  121. package/dist/types/agents/loop_agent.d.ts +1 -1
  122. package/dist/types/agents/processors/agent_transfer_llm_request_processor.d.ts +18 -0
  123. package/dist/types/agents/{base_llm_processor.d.ts → processors/base_llm_processor.d.ts} +4 -4
  124. package/dist/types/agents/processors/basic_llm_request_processor.d.ts +13 -0
  125. package/dist/types/agents/processors/code_execution_request_processor.d.ts +34 -0
  126. package/dist/types/agents/{content_processor_utils.d.ts → processors/content_processor_utils.d.ts} +1 -1
  127. package/dist/types/agents/processors/content_request_processor.d.ts +13 -0
  128. package/dist/types/agents/processors/context_compactor_request_processor.d.ts +22 -0
  129. package/dist/types/agents/processors/identity_llm_request_processor.d.ts +13 -0
  130. package/dist/types/agents/processors/instructions_llm_request_processor.d.ts +16 -0
  131. package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +13 -0
  132. package/dist/types/artifacts/file_artifact_service.d.ts +4 -0
  133. package/dist/types/auth/credential_service/base_credential_service.d.ts +3 -3
  134. package/dist/types/auth/credential_service/in_memory_credential_service.d.ts +3 -3
  135. package/dist/types/common.d.ts +20 -5
  136. package/dist/types/context/base_context_compactor.d.ts +24 -0
  137. package/dist/types/context/summarizers/base_summarizer.d.ts +19 -0
  138. package/dist/types/context/summarizers/llm_summarizer.d.ts +23 -0
  139. package/dist/types/context/token_based_context_compactor.d.ts +33 -0
  140. package/dist/types/context/truncating_context_compactor.d.ts +24 -0
  141. package/dist/types/events/compacted_event.d.ts +33 -0
  142. package/dist/types/index.d.ts +8 -0
  143. package/dist/types/models/llm_response.d.ts +5 -1
  144. package/dist/types/plugins/base_plugin.d.ts +12 -13
  145. package/dist/types/plugins/logging_plugin.d.ts +9 -10
  146. package/dist/types/plugins/plugin_manager.d.ts +9 -10
  147. package/dist/types/plugins/security_plugin.d.ts +2 -2
  148. package/dist/types/runner/runner.d.ts +13 -0
  149. package/dist/types/sessions/database_session_service.d.ts +2 -1
  150. package/dist/types/sessions/db/operations.d.ts +3 -4
  151. package/dist/types/tools/base_tool.d.ts +3 -3
  152. package/dist/types/tools/base_toolset.d.ts +12 -3
  153. package/dist/types/tools/exit_loop_tool.d.ts +24 -0
  154. package/dist/types/tools/forwarding_artifact_service.d.ts +2 -2
  155. package/dist/types/tools/function_tool.d.ts +2 -2
  156. package/dist/types/tools/load_artifacts_tool.d.ts +21 -0
  157. package/dist/types/tools/load_memory_tool.d.ts +22 -0
  158. package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -1
  159. package/dist/types/tools/preload_memory_tool.d.ts +23 -0
  160. package/dist/types/utils/logger.d.ts +5 -9
  161. package/dist/types/version.d.ts +1 -1
  162. package/dist/web/a2a/a2a_event.js +269 -0
  163. package/dist/web/a2a/a2a_remote_agent.js +193 -0
  164. package/dist/web/a2a/a2a_remote_agent_run_processor.js +175 -0
  165. package/dist/web/a2a/a2a_remote_agent_utils.js +131 -0
  166. package/dist/web/a2a/agent_card.js +340 -0
  167. package/dist/web/a2a/agent_executor.js +216 -0
  168. package/dist/web/a2a/agent_to_a2a.js +80 -0
  169. package/dist/web/a2a/event_converter_utils.js +201 -0
  170. package/dist/web/a2a/event_processor_utils.js +168 -0
  171. package/dist/web/a2a/executor_context.js +23 -0
  172. package/dist/web/a2a/metadata_converter_utils.js +108 -0
  173. package/dist/web/a2a/part_converter_utils.js +49 -34
  174. package/dist/web/agents/base_agent.js +3 -3
  175. package/dist/{esm/tools/tool_context.js → web/agents/context.js} +66 -11
  176. package/dist/web/agents/functions.js +2 -2
  177. package/dist/web/agents/llm_agent.js +31 -661
  178. package/dist/web/agents/processors/agent_transfer_llm_request_processor.js +100 -0
  179. package/dist/web/agents/processors/basic_llm_request_processor.js +71 -0
  180. package/dist/web/agents/processors/code_execution_request_processor.js +365 -0
  181. package/dist/web/agents/{content_processor_utils.js → processors/content_processor_utils.js} +22 -2
  182. package/dist/web/agents/processors/content_request_processor.js +77 -0
  183. package/dist/web/agents/processors/context_compactor_request_processor.js +49 -0
  184. package/dist/web/agents/processors/identity_llm_request_processor.js +41 -0
  185. package/dist/web/agents/processors/instructions_llm_request_processor.js +72 -0
  186. package/dist/web/agents/processors/request_confirmation_llm_request_processor.js +158 -0
  187. package/dist/web/artifacts/file_artifact_service.js +30 -3
  188. package/dist/web/common.js +44 -10
  189. package/dist/web/context/base_context_compactor.js +5 -0
  190. package/dist/web/context/summarizers/base_summarizer.js +5 -0
  191. package/dist/web/context/summarizers/llm_summarizer.js +74 -0
  192. package/dist/web/context/token_based_context_compactor.js +105 -0
  193. package/dist/web/context/truncating_context_compactor.js +28 -0
  194. package/dist/web/events/compacted_event.js +40 -0
  195. package/dist/web/index.js +13 -18
  196. package/dist/web/index.js.map +7 -0
  197. package/dist/web/memory/in_memory_memory_service.js +1 -1
  198. package/dist/web/models/llm_response.js +2 -0
  199. package/dist/web/plugins/base_plugin.js +1 -1
  200. package/dist/web/runner/runner.js +18 -10
  201. package/dist/web/sessions/database_session_service.js +4 -1
  202. package/dist/web/sessions/db/operations.js +32 -18
  203. package/dist/web/sessions/state.js +2 -2
  204. package/dist/web/tools/agent_tool.js +6 -5
  205. package/dist/web/tools/base_tool.js +3 -0
  206. package/dist/web/tools/base_toolset.js +11 -2
  207. package/dist/web/tools/exit_loop_tool.js +32 -0
  208. package/dist/web/tools/load_artifacts_tool.js +150 -0
  209. package/dist/web/tools/load_memory_tool.js +77 -0
  210. package/dist/web/tools/mcp/mcp_toolset.js +27 -5
  211. package/dist/web/tools/preload_memory_tool.js +75 -0
  212. package/dist/web/utils/logger.js +52 -54
  213. package/dist/web/version.js +1 -1
  214. package/package.json +7 -4
  215. package/dist/cjs/agents/callback_context.js +0 -101
  216. package/dist/esm/agents/callback_context.js +0 -71
  217. package/dist/types/agents/callback_context.d.ts +0 -42
  218. package/dist/web/agents/callback_context.js +0 -71
  219. /package/dist/cjs/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
  220. /package/dist/esm/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
  221. /package/dist/web/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { appendInstructions } from "../../models/llm_request.js";
7
+ import { injectSessionState } from "../instructions.js";
8
+ import { isLlmAgent } from "../llm_agent.js";
9
+ import { ReadonlyContext } from "../readonly_context.js";
10
+ import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
11
+ class InstructionsLlmRequestProcessor extends BaseLlmRequestProcessor {
12
+ /**
13
+ * Handles instructions and global instructions for LLM flow.
14
+ */
15
+ // eslint-disable-next-line require-yield
16
+ async *runAsync(invocationContext, llmRequest) {
17
+ const agent = invocationContext.agent;
18
+ if (!isLlmAgent(agent)) {
19
+ return;
20
+ }
21
+ const rootAgent = agent.rootAgent;
22
+ if (isLlmAgent(rootAgent) && rootAgent.globalInstruction) {
23
+ const { instruction, requireStateInjection } = await rootAgent.canonicalGlobalInstruction(
24
+ new ReadonlyContext(invocationContext)
25
+ );
26
+ let instructionWithState = instruction;
27
+ if (requireStateInjection) {
28
+ instructionWithState = await injectSessionState(
29
+ instruction,
30
+ new ReadonlyContext(invocationContext)
31
+ );
32
+ }
33
+ appendInstructions(llmRequest, [instructionWithState]);
34
+ }
35
+ if (agent.instruction) {
36
+ const { instruction, requireStateInjection } = await agent.canonicalInstruction(
37
+ new ReadonlyContext(invocationContext)
38
+ );
39
+ let instructionWithState = instruction;
40
+ if (requireStateInjection) {
41
+ instructionWithState = await injectSessionState(
42
+ instruction,
43
+ new ReadonlyContext(invocationContext)
44
+ );
45
+ }
46
+ appendInstructions(llmRequest, [instructionWithState]);
47
+ }
48
+ }
49
+ }
50
+ const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
51
+ export {
52
+ INSTRUCTIONS_LLM_REQUEST_PROCESSOR,
53
+ InstructionsLlmRequestProcessor
54
+ };
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import {
7
+ getFunctionCalls,
8
+ getFunctionResponses
9
+ } from "../../events/event.js";
10
+ import { ToolConfirmation } from "../../tools/tool_confirmation.js";
11
+ import {
12
+ REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
13
+ handleFunctionCallList
14
+ } from "../functions.js";
15
+ import { isLlmAgent } from "../llm_agent.js";
16
+ import { ReadonlyContext } from "../readonly_context.js";
17
+ import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
18
+ class RequestConfirmationLlmRequestProcessor extends BaseLlmRequestProcessor {
19
+ /** Handles tool confirmation information to build the LLM request. */
20
+ async *runAsync(invocationContext) {
21
+ const agent = invocationContext.agent;
22
+ if (!isLlmAgent(agent)) {
23
+ return;
24
+ }
25
+ const events = invocationContext.session.events;
26
+ if (!events || events.length === 0) {
27
+ return;
28
+ }
29
+ const requestConfirmationFunctionResponses = {};
30
+ let confirmationEventIndex = -1;
31
+ for (let i = events.length - 1; i >= 0; i--) {
32
+ const event = events[i];
33
+ if (event.author !== "user") {
34
+ continue;
35
+ }
36
+ const responses = getFunctionResponses(event);
37
+ if (!responses) {
38
+ continue;
39
+ }
40
+ let foundConfirmation = false;
41
+ for (const functionResponse of responses) {
42
+ if (functionResponse.name !== REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
43
+ continue;
44
+ }
45
+ foundConfirmation = true;
46
+ let toolConfirmation = null;
47
+ if (functionResponse.response && Object.keys(functionResponse.response).length === 1 && "response" in functionResponse.response) {
48
+ toolConfirmation = JSON.parse(
49
+ functionResponse.response["response"]
50
+ );
51
+ } else if (functionResponse.response) {
52
+ toolConfirmation = new ToolConfirmation({
53
+ hint: functionResponse.response["hint"],
54
+ payload: functionResponse.response["payload"],
55
+ confirmed: functionResponse.response["confirmed"]
56
+ });
57
+ }
58
+ if (functionResponse.id && toolConfirmation) {
59
+ requestConfirmationFunctionResponses[functionResponse.id] = toolConfirmation;
60
+ }
61
+ }
62
+ if (foundConfirmation) {
63
+ confirmationEventIndex = i;
64
+ break;
65
+ }
66
+ }
67
+ if (Object.keys(requestConfirmationFunctionResponses).length === 0) {
68
+ return;
69
+ }
70
+ for (let i = confirmationEventIndex - 1; i >= 0; i--) {
71
+ const event = events[i];
72
+ const functionCalls = getFunctionCalls(event);
73
+ if (!functionCalls) {
74
+ continue;
75
+ }
76
+ const toolsToResumeWithConfirmation = {};
77
+ const toolsToResumeWithArgs = {};
78
+ for (const functionCall of functionCalls) {
79
+ if (!functionCall.id || !(functionCall.id in requestConfirmationFunctionResponses)) {
80
+ continue;
81
+ }
82
+ const args = functionCall.args;
83
+ if (!args || !("originalFunctionCall" in args)) {
84
+ continue;
85
+ }
86
+ const originalFunctionCall = args["originalFunctionCall"];
87
+ if (originalFunctionCall.id) {
88
+ toolsToResumeWithConfirmation[originalFunctionCall.id] = requestConfirmationFunctionResponses[functionCall.id];
89
+ toolsToResumeWithArgs[originalFunctionCall.id] = originalFunctionCall;
90
+ }
91
+ }
92
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
93
+ continue;
94
+ }
95
+ for (let j = events.length - 1; j > confirmationEventIndex; j--) {
96
+ const eventToCheck = events[j];
97
+ const functionResponses = getFunctionResponses(eventToCheck);
98
+ if (!functionResponses) {
99
+ continue;
100
+ }
101
+ for (const fr of functionResponses) {
102
+ if (fr.id && fr.id in toolsToResumeWithConfirmation) {
103
+ delete toolsToResumeWithConfirmation[fr.id];
104
+ delete toolsToResumeWithArgs[fr.id];
105
+ }
106
+ }
107
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
108
+ break;
109
+ }
110
+ }
111
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
112
+ continue;
113
+ }
114
+ const toolsList = await agent.canonicalTools(
115
+ new ReadonlyContext(invocationContext)
116
+ );
117
+ const toolsDict = Object.fromEntries(
118
+ toolsList.map((tool) => [tool.name, tool])
119
+ );
120
+ const functionResponseEvent = await handleFunctionCallList({
121
+ invocationContext,
122
+ functionCalls: Object.values(toolsToResumeWithArgs),
123
+ toolsDict,
124
+ beforeToolCallbacks: agent.canonicalBeforeToolCallbacks,
125
+ afterToolCallbacks: agent.canonicalAfterToolCallbacks,
126
+ filters: new Set(Object.keys(toolsToResumeWithConfirmation)),
127
+ toolConfirmationDict: toolsToResumeWithConfirmation
128
+ });
129
+ if (functionResponseEvent) {
130
+ yield functionResponseEvent;
131
+ }
132
+ return;
133
+ }
134
+ }
135
+ }
136
+ const REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR = new RequestConfirmationLlmRequestProcessor();
137
+ export {
138
+ REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
139
+ RequestConfirmationLlmRequestProcessor
140
+ };
@@ -307,8 +307,28 @@ class FileArtifactService {
307
307
  }
308
308
  }
309
309
  }
310
+ const SAFE_SEGMENT_RE = /^[a-zA-Z0-9_@-][a-zA-Z0-9_.@-]{0,255}$/;
311
+ function assertSafeSegment(value, label) {
312
+ if (!value || !SAFE_SEGMENT_RE.test(value)) {
313
+ throw new Error(
314
+ `[FileArtifactService] Invalid ${label}: value contains disallowed characters.`
315
+ );
316
+ }
317
+ }
318
+ function assertInsideRoot(resolvedPath, rootDir, label) {
319
+ const root = path.resolve(rootDir);
320
+ const resolved = path.resolve(resolvedPath);
321
+ if (!resolved.startsWith(root + path.sep) && resolved !== root) {
322
+ throw new Error(
323
+ `[FileArtifactService] ${label} escapes storage root. Resolved: ${resolved}, Root: ${root}`
324
+ );
325
+ }
326
+ }
310
327
  function getUserRoot(rootDir, userId) {
311
- return path.join(rootDir, "users", userId);
328
+ assertSafeSegment(userId, "userId");
329
+ const result = path.join(rootDir, "users", userId);
330
+ assertInsideRoot(result, rootDir, "userRoot");
331
+ return result;
312
332
  }
313
333
  function isUserScoped(sessionId, filename) {
314
334
  return !sessionId || filename.startsWith(USER_NAMESPACE_PREFIX);
@@ -317,7 +337,10 @@ function getUserArtifactsDir(userRoot) {
317
337
  return path.join(userRoot, "artifacts");
318
338
  }
319
339
  function getSessionArtifactsDir(baseRoot, sessionId) {
320
- return path.join(baseRoot, "sessions", sessionId, "artifacts");
340
+ assertSafeSegment(sessionId, "sessionId");
341
+ const result = path.join(baseRoot, "sessions", sessionId, "artifacts");
342
+ assertInsideRoot(result, baseRoot, "sessionArtifactsDir");
343
+ return result;
321
344
  }
322
345
  function getVersionsDir(artifactDir) {
323
346
  return path.join(artifactDir, "versions");
@@ -447,5 +470,9 @@ function asPosixPath(p) {
447
470
  return p.split(path.sep).join("/");
448
471
  }
449
472
  export {
450
- FileArtifactService
473
+ FileArtifactService,
474
+ assertInsideRoot,
475
+ assertSafeSegment,
476
+ getSessionArtifactsDir,
477
+ getUserRoot
451
478
  };
@@ -5,17 +5,22 @@
5
5
  */
6
6
  import { ActiveStreamingTool } from "./agents/active_streaming_tool.js";
7
7
  import { BaseAgent, isBaseAgent } from "./agents/base_agent.js";
8
- import {
9
- BaseLlmRequestProcessor,
10
- BaseLlmResponseProcessor
11
- } from "./agents/base_llm_processor.js";
12
- import { CallbackContext } from "./agents/callback_context.js";
8
+ import { Context } from "./agents/context.js";
13
9
  import { functionsExportedForTestingOnly } from "./agents/functions.js";
14
10
  import { InvocationContext } from "./agents/invocation_context.js";
15
11
  import { LiveRequestQueue } from "./agents/live_request_queue.js";
16
12
  import { LlmAgent, isLlmAgent } from "./agents/llm_agent.js";
17
13
  import { LoopAgent, isLoopAgent } from "./agents/loop_agent.js";
18
14
  import { ParallelAgent, isParallelAgent } from "./agents/parallel_agent.js";
15
+ import {
16
+ BaseLlmRequestProcessor,
17
+ BaseLlmResponseProcessor
18
+ } from "./agents/processors/base_llm_processor.js";
19
+ import {
20
+ CONTENT_REQUEST_PROCESSOR,
21
+ ContentRequestProcessor
22
+ } from "./agents/processors/content_request_processor.js";
23
+ import { ContextCompactorRequestProcessor } from "./agents/processors/context_compactor_request_processor.js";
19
24
  import { ReadonlyContext } from "./agents/readonly_context.js";
20
25
  import { StreamingMode } from "./agents/run_config.js";
21
26
  import { SequentialAgent, isSequentialAgent } from "./agents/sequential_agent.js";
@@ -23,6 +28,10 @@ import { InMemoryArtifactService } from "./artifacts/in_memory_artifact_service.
23
28
  import { AuthCredentialTypes } from "./auth/auth_credential.js";
24
29
  import { BaseCodeExecutor } from "./code_executors/base_code_executor.js";
25
30
  import { BuiltInCodeExecutor } from "./code_executors/built_in_code_executor.js";
31
+ import { LlmSummarizer } from "./context/summarizers/llm_summarizer.js";
32
+ import { TokenBasedContextCompactor } from "./context/token_based_context_compactor.js";
33
+ import { TruncatingContextCompactor } from "./context/truncating_context_compactor.js";
34
+ import { isCompactedEvent } from "./events/compacted_event.js";
26
35
  import {
27
36
  createEvent,
28
37
  getFunctionCalls,
@@ -53,19 +62,28 @@ import {
53
62
  getAskUserConfirmationFunctionCalls
54
63
  } from "./plugins/security_plugin.js";
55
64
  import { InMemoryRunner } from "./runner/in_memory_runner.js";
56
- import { Runner } from "./runner/runner.js";
65
+ import { Runner, isRunner } from "./runner/runner.js";
57
66
  import { BaseSessionService } from "./sessions/base_session_service.js";
58
67
  import { InMemorySessionService } from "./sessions/in_memory_session_service.js";
59
68
  import { createSession } from "./sessions/session.js";
60
69
  import { State } from "./sessions/state.js";
61
70
  import { AgentTool, isAgentTool } from "./tools/agent_tool.js";
62
71
  import { BaseTool, isBaseTool } from "./tools/base_tool.js";
63
- import { BaseToolset } from "./tools/base_toolset.js";
72
+ import { BaseToolset, isBaseToolset } from "./tools/base_toolset.js";
73
+ import { EXIT_LOOP, ExitLoopTool } from "./tools/exit_loop_tool.js";
64
74
  import { FunctionTool, isFunctionTool } from "./tools/function_tool.js";
65
75
  import { GOOGLE_SEARCH, GoogleSearchTool } from "./tools/google_search_tool.js";
76
+ import {
77
+ LOAD_ARTIFACTS,
78
+ LoadArtifactsTool
79
+ } from "./tools/load_artifacts_tool.js";
80
+ import { LOAD_MEMORY, LoadMemoryTool } from "./tools/load_memory_tool.js";
66
81
  import { LongRunningFunctionTool } from "./tools/long_running_tool.js";
82
+ import {
83
+ PRELOAD_MEMORY,
84
+ PreloadMemoryTool
85
+ } from "./tools/preload_memory_tool.js";
67
86
  import { ToolConfirmation } from "./tools/tool_confirmation.js";
68
- import { ToolContext } from "./tools/tool_context.js";
69
87
  import { LogLevel, getLogger, setLogLevel, setLogger } from "./utils/logger.js";
70
88
  import { isGemini2OrAbove } from "./utils/model_name.js";
71
89
  import { zodObjectToSchema } from "./utils/simple_zod_to_json.js";
@@ -91,8 +109,13 @@ export {
91
109
  BaseTool,
92
110
  BaseToolset,
93
111
  BuiltInCodeExecutor,
94
- CallbackContext,
112
+ CONTENT_REQUEST_PROCESSOR,
113
+ ContentRequestProcessor,
114
+ Context,
115
+ ContextCompactorRequestProcessor,
116
+ EXIT_LOOP,
95
117
  EventType,
118
+ ExitLoopTool,
96
119
  FunctionTool,
97
120
  GOOGLE_SEARCH,
98
121
  Gemini,
@@ -105,15 +128,22 @@ export {
105
128
  InMemorySessionService,
106
129
  InvocationContext,
107
130
  LLMRegistry,
131
+ LOAD_ARTIFACTS,
132
+ LOAD_MEMORY,
108
133
  LiveRequestQueue,
109
134
  LlmAgent,
135
+ LlmSummarizer,
136
+ LoadArtifactsTool,
137
+ LoadMemoryTool,
110
138
  LogLevel,
111
139
  LoggingPlugin,
112
140
  LongRunningFunctionTool,
113
141
  LoopAgent,
142
+ PRELOAD_MEMORY,
114
143
  ParallelAgent,
115
144
  PluginManager,
116
145
  PolicyOutcome,
146
+ PreloadMemoryTool,
117
147
  REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
118
148
  ReadonlyContext,
119
149
  Runner,
@@ -121,8 +151,9 @@ export {
121
151
  SequentialAgent,
122
152
  State,
123
153
  StreamingMode,
154
+ TokenBasedContextCompactor,
124
155
  ToolConfirmation,
125
- ToolContext,
156
+ TruncatingContextCompactor,
126
157
  createEvent,
127
158
  createEventActions,
128
159
  createSession,
@@ -138,12 +169,15 @@ export {
138
169
  isBaseExampleProvider,
139
170
  isBaseLlm,
140
171
  isBaseTool,
172
+ isBaseToolset,
173
+ isCompactedEvent,
141
174
  isFinalResponse,
142
175
  isFunctionTool,
143
176
  isGemini2OrAbove,
144
177
  isLlmAgent,
145
178
  isLoopAgent,
146
179
  isParallelAgent,
180
+ isRunner,
147
181
  isSequentialAgent,
148
182
  setLogLevel,
149
183
  setLogger,
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import {
7
+ createCompactedEvent
8
+ } from "../../events/compacted_event.js";
9
+ import { stringifyContent } from "../../events/event.js";
10
+ const DEFAULT_PROMPT = "The following is a conversation history between a user and an AI agent. Please summarize the conversation, focusing on key information and decisions made, as well as any unresolved questions or tasks. The summary should be concise and capture the essence of the interaction.";
11
+ class LlmSummarizer {
12
+ constructor(options) {
13
+ this.llm = options.llm;
14
+ this.prompt = options.prompt || DEFAULT_PROMPT;
15
+ }
16
+ async summarize(events) {
17
+ var _a, _b, _c, _d, _e, _f;
18
+ if (events.length === 0) {
19
+ throw new Error("Cannot summarize an empty list of events.");
20
+ }
21
+ const startTime = events[0].timestamp;
22
+ const endTime = events[events.length - 1].timestamp;
23
+ let formattedEvents = "";
24
+ for (let i = 0; i < events.length; i++) {
25
+ formattedEvents += `[Event ${i + 1} - Author: ${events[i].author}]
26
+ `;
27
+ formattedEvents += `${stringifyContent(events[i])}
28
+
29
+ `;
30
+ }
31
+ const fullPrompt = `${this.prompt}
32
+
33
+ ${formattedEvents}`;
34
+ const request = {
35
+ contents: [{ role: "user", parts: [{ text: fullPrompt }] }],
36
+ toolsDict: {},
37
+ liveConnectConfig: {}
38
+ };
39
+ const responseGen = this.llm.generateContentAsync(request, false);
40
+ let compactedContent = "";
41
+ const firstResponse = await responseGen.next();
42
+ if (firstResponse.done || !((_c = (_b = (_a = firstResponse.value.content) == null ? void 0 : _a.parts) == null ? void 0 : _b[0]) == null ? void 0 : _c.text)) {
43
+ throw new Error("LLM failed to return a valid summary.");
44
+ }
45
+ compactedContent += firstResponse.value.content.parts[0].text;
46
+ for await (const chunk of responseGen) {
47
+ if ((_f = (_e = (_d = chunk.content) == null ? void 0 : _d.parts) == null ? void 0 : _e[0]) == null ? void 0 : _f.text) {
48
+ compactedContent += chunk.content.parts[0].text;
49
+ }
50
+ }
51
+ return createCompactedEvent({
52
+ author: "system",
53
+ content: {
54
+ role: "model",
55
+ parts: [{ text: compactedContent }]
56
+ },
57
+ startTime,
58
+ endTime,
59
+ compactedContent
60
+ });
61
+ }
62
+ }
63
+ export {
64
+ LlmSummarizer
65
+ };
@@ -0,0 +1,105 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { isCompactedEvent } from "../events/compacted_event.js";
7
+ import { stringifyContent } from "../events/event.js";
8
+ class TokenBasedContextCompactor {
9
+ constructor(options) {
10
+ this.tokenThreshold = options.tokenThreshold;
11
+ this.eventRetentionSize = options.eventRetentionSize;
12
+ this.summarizer = options.summarizer;
13
+ }
14
+ getActiveEvents(events) {
15
+ let latestCompactedEvent = void 0;
16
+ for (let i = events.length - 1; i >= 0; i--) {
17
+ const e = events[i];
18
+ if (isCompactedEvent(e)) {
19
+ if (!latestCompactedEvent || e.endTime > latestCompactedEvent.endTime) {
20
+ latestCompactedEvent = e;
21
+ }
22
+ }
23
+ }
24
+ if (!latestCompactedEvent) {
25
+ return events;
26
+ }
27
+ const activeRawEvents = events.filter(
28
+ (e) => !isCompactedEvent(e) && e.timestamp > latestCompactedEvent.endTime
29
+ );
30
+ return [latestCompactedEvent, ...activeRawEvents];
31
+ }
32
+ shouldCompact(invocationContext) {
33
+ const events = invocationContext.session.events;
34
+ const activeEvents = this.getActiveEvents(events);
35
+ const rawEvents = activeEvents.filter((e) => !isCompactedEvent(e));
36
+ if (rawEvents.length <= this.eventRetentionSize) {
37
+ return false;
38
+ }
39
+ let totalTokens = 0;
40
+ for (const event of activeEvents) {
41
+ totalTokens += getEventTokens(event);
42
+ }
43
+ return totalTokens > this.tokenThreshold;
44
+ }
45
+ async compact(invocationContext) {
46
+ const events = invocationContext.session.events;
47
+ const activeEvents = this.getActiveEvents(events);
48
+ const rawEvents = activeEvents.filter((e) => !isCompactedEvent(e));
49
+ if (rawEvents.length <= this.eventRetentionSize) {
50
+ return;
51
+ }
52
+ let retainStartIndex = Math.max(
53
+ 0,
54
+ rawEvents.length - this.eventRetentionSize
55
+ );
56
+ while (retainStartIndex > 0) {
57
+ const eventToRetain = rawEvents[retainStartIndex];
58
+ const previousEvent = rawEvents[retainStartIndex - 1];
59
+ if (hasFunctionResponse(eventToRetain) && hasFunctionCall(previousEvent)) {
60
+ retainStartIndex--;
61
+ } else {
62
+ break;
63
+ }
64
+ }
65
+ if (retainStartIndex === 0) {
66
+ return;
67
+ }
68
+ const rawEventsToCompact = rawEvents.slice(0, retainStartIndex);
69
+ const compactedEventPresent = activeEvents.find(isCompactedEvent);
70
+ const eventsToCompact = compactedEventPresent ? [compactedEventPresent, ...rawEventsToCompact] : rawEventsToCompact;
71
+ const compactedEvent = await this.summarizer.summarize(eventsToCompact);
72
+ if (!compactedEvent.actions) {
73
+ compactedEvent.actions = {
74
+ stateDelta: {},
75
+ artifactDelta: {},
76
+ requestedAuthConfigs: [],
77
+ requestedToolConfirmations: {}
78
+ };
79
+ }
80
+ invocationContext.session.events.push(compactedEvent);
81
+ }
82
+ }
83
+ function getEventTokens(event) {
84
+ var _a;
85
+ if (((_a = event.usageMetadata) == null ? void 0 : _a.promptTokenCount) !== void 0) {
86
+ return event.usageMetadata.promptTokenCount;
87
+ }
88
+ const contentStr = stringifyContent(event);
89
+ return Math.ceil(contentStr.length / 4);
90
+ }
91
+ function hasFunctionCall(event) {
92
+ var _a, _b;
93
+ return !!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.some(
94
+ (part) => part.functionCall !== void 0
95
+ ));
96
+ }
97
+ function hasFunctionResponse(event) {
98
+ var _a, _b;
99
+ return !!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.some(
100
+ (part) => part.functionResponse !== void 0
101
+ ));
102
+ }
103
+ export {
104
+ TokenBasedContextCompactor
105
+ };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ class TruncatingContextCompactor {
7
+ constructor(options) {
8
+ var _a;
9
+ this.threshold = options.threshold;
10
+ this.preserveLeadingEvents = (_a = options.preserveLeadingEvents) != null ? _a : 0;
11
+ }
12
+ shouldCompact(invocationContext) {
13
+ const eventsLength = invocationContext.session.events.length;
14
+ return eventsLength > this.threshold + Math.max(0, this.preserveLeadingEvents);
15
+ }
16
+ compact(invocationContext) {
17
+ const events = invocationContext.session.events;
18
+ const excess = events.length - this.threshold - Math.max(0, this.preserveLeadingEvents);
19
+ if (excess <= 0) {
20
+ return;
21
+ }
22
+ const startIndexToRemove = Math.max(0, this.preserveLeadingEvents);
23
+ events.splice(startIndexToRemove, excess);
24
+ }
25
+ }
26
+ export {
27
+ TruncatingContextCompactor
28
+ };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { createEvent } from "./event.js";
7
+ function isCompactedEvent(event) {
8
+ return "isCompacted" in event && event.isCompacted === true;
9
+ }
10
+ function createCompactedEvent(params = {}) {
11
+ return {
12
+ ...createEvent(params),
13
+ isCompacted: params.isCompacted || true,
14
+ startTime: params.startTime,
15
+ endTime: params.endTime,
16
+ compactedContent: params.compactedContent
17
+ };
18
+ }
19
+ export {
20
+ createCompactedEvent,
21
+ isCompactedEvent
22
+ };