@google/adk 0.4.0 → 0.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.
- package/dist/cjs/a2a/a2a_event.js +290 -0
- package/dist/cjs/a2a/event_converter_utils.js +201 -0
- package/dist/cjs/a2a/executor_context.js +53 -0
- package/dist/cjs/a2a/metadata_converter_utils.js +125 -0
- package/dist/cjs/a2a/part_converter_utils.js +23 -21
- package/dist/cjs/agents/base_agent.js +3 -3
- package/dist/cjs/{tools/tool_context.js → agents/context.js} +70 -15
- package/dist/cjs/agents/functions.js +2 -2
- package/dist/cjs/agents/llm_agent.js +21 -674
- package/dist/cjs/agents/processors/agent_transfer_llm_request_processor.js +132 -0
- package/dist/cjs/agents/processors/basic_llm_request_processor.js +68 -0
- package/dist/cjs/agents/processors/code_execution_request_processor.js +389 -0
- package/dist/cjs/agents/processors/content_request_processor.js +66 -0
- package/dist/cjs/agents/processors/identity_llm_request_processor.js +54 -0
- package/dist/cjs/agents/processors/instructions_llm_request_processor.js +85 -0
- package/dist/cjs/agents/processors/request_confirmation_llm_request_processor.js +165 -0
- package/dist/cjs/common.js +11 -7
- package/dist/cjs/index.js +89 -53
- package/dist/cjs/index.js.map +7 -0
- package/dist/cjs/models/llm_response.js +2 -0
- package/dist/cjs/plugins/base_plugin.js +1 -1
- package/dist/cjs/runner/runner.js +1 -1
- package/dist/cjs/sessions/database_session_service.js +4 -1
- package/dist/cjs/sessions/db/operations.js +24 -12
- package/dist/cjs/tools/base_tool.js +3 -0
- package/dist/cjs/tools/base_toolset.js +13 -3
- package/dist/cjs/tools/exit_loop_tool.js +63 -0
- package/dist/cjs/tools/mcp/mcp_toolset.js +9 -5
- package/dist/cjs/utils/logger.js +61 -54
- package/dist/cjs/version.js +1 -1
- package/dist/esm/a2a/a2a_event.js +243 -0
- package/dist/esm/a2a/event_converter_utils.js +187 -0
- package/dist/esm/a2a/executor_context.js +23 -0
- package/dist/esm/a2a/metadata_converter_utils.js +90 -0
- package/dist/esm/a2a/part_converter_utils.js +25 -21
- package/dist/esm/agents/base_agent.js +3 -3
- package/dist/esm/{tools/tool_context.js → agents/context.js} +66 -11
- package/dist/esm/agents/functions.js +2 -2
- package/dist/esm/agents/llm_agent.js +14 -683
- package/dist/esm/agents/processors/agent_transfer_llm_request_processor.js +101 -0
- package/dist/esm/agents/processors/basic_llm_request_processor.js +37 -0
- package/dist/esm/agents/processors/code_execution_request_processor.js +363 -0
- package/dist/esm/agents/processors/content_request_processor.js +38 -0
- package/dist/esm/agents/processors/identity_llm_request_processor.js +23 -0
- package/dist/esm/agents/processors/instructions_llm_request_processor.js +54 -0
- package/dist/esm/agents/processors/request_confirmation_llm_request_processor.js +140 -0
- package/dist/esm/common.js +11 -9
- package/dist/esm/index.js +95 -18
- package/dist/esm/index.js.map +7 -0
- package/dist/esm/models/llm_response.js +2 -0
- package/dist/esm/plugins/base_plugin.js +1 -1
- package/dist/esm/runner/runner.js +1 -1
- package/dist/esm/sessions/database_session_service.js +4 -1
- package/dist/esm/sessions/db/operations.js +31 -7
- package/dist/esm/tools/base_tool.js +3 -0
- package/dist/esm/tools/base_toolset.js +11 -2
- package/dist/esm/tools/exit_loop_tool.js +32 -0
- package/dist/esm/tools/mcp/mcp_toolset.js +9 -5
- package/dist/esm/utils/logger.js +51 -54
- package/dist/esm/version.js +1 -1
- package/dist/types/a2a/a2a_event.d.ts +122 -0
- package/dist/types/a2a/event_converter_utils.d.ts +20 -0
- package/dist/types/a2a/executor_context.d.ts +33 -0
- package/dist/types/a2a/metadata_converter_utils.d.ts +62 -0
- package/dist/types/a2a/part_converter_utils.d.ts +4 -3
- package/dist/types/agents/base_agent.d.ts +2 -2
- package/dist/types/{tools/tool_context.d.ts → agents/context.d.ts} +43 -8
- package/dist/types/agents/llm_agent.d.ts +8 -31
- package/dist/types/agents/processors/agent_transfer_llm_request_processor.d.ts +18 -0
- package/dist/types/agents/{base_llm_processor.d.ts → processors/base_llm_processor.d.ts} +4 -4
- package/dist/types/agents/processors/basic_llm_request_processor.d.ts +13 -0
- package/dist/types/agents/processors/code_execution_request_processor.d.ts +34 -0
- package/dist/types/agents/processors/content_request_processor.d.ts +13 -0
- package/dist/types/agents/processors/identity_llm_request_processor.d.ts +13 -0
- package/dist/types/agents/processors/instructions_llm_request_processor.d.ts +16 -0
- package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +13 -0
- package/dist/types/auth/credential_service/base_credential_service.d.ts +3 -3
- package/dist/types/auth/credential_service/in_memory_credential_service.d.ts +3 -3
- package/dist/types/common.d.ts +4 -4
- package/dist/types/models/llm_response.d.ts +5 -1
- package/dist/types/plugins/base_plugin.d.ts +12 -13
- package/dist/types/plugins/logging_plugin.d.ts +9 -10
- package/dist/types/plugins/plugin_manager.d.ts +9 -10
- package/dist/types/plugins/security_plugin.d.ts +2 -2
- package/dist/types/sessions/database_session_service.d.ts +2 -1
- package/dist/types/sessions/db/operations.d.ts +1 -1
- package/dist/types/tools/base_tool.d.ts +3 -3
- package/dist/types/tools/base_toolset.d.ts +12 -3
- package/dist/types/tools/exit_loop_tool.d.ts +24 -0
- package/dist/types/tools/forwarding_artifact_service.d.ts +2 -2
- package/dist/types/tools/function_tool.d.ts +2 -2
- package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -1
- package/dist/types/utils/logger.d.ts +5 -9
- package/dist/types/version.d.ts +1 -1
- package/dist/web/a2a/a2a_event.js +243 -0
- package/dist/web/a2a/event_converter_utils.js +201 -0
- package/dist/web/a2a/executor_context.js +23 -0
- package/dist/web/a2a/metadata_converter_utils.js +107 -0
- package/dist/web/a2a/part_converter_utils.js +25 -21
- package/dist/web/agents/base_agent.js +3 -3
- package/dist/web/{tools/tool_context.js → agents/context.js} +66 -11
- package/dist/web/agents/functions.js +2 -2
- package/dist/web/agents/llm_agent.js +14 -661
- package/dist/web/agents/processors/agent_transfer_llm_request_processor.js +100 -0
- package/dist/web/agents/processors/basic_llm_request_processor.js +71 -0
- package/dist/web/agents/processors/code_execution_request_processor.js +365 -0
- package/dist/web/agents/processors/content_request_processor.js +56 -0
- package/dist/web/agents/processors/identity_llm_request_processor.js +41 -0
- package/dist/web/agents/processors/instructions_llm_request_processor.js +72 -0
- package/dist/web/agents/processors/request_confirmation_llm_request_processor.js +158 -0
- package/dist/web/common.js +11 -9
- package/dist/web/index.js +13 -18
- package/dist/web/index.js.map +7 -0
- package/dist/web/models/llm_response.js +2 -0
- package/dist/web/plugins/base_plugin.js +1 -1
- package/dist/web/runner/runner.js +1 -1
- package/dist/web/sessions/database_session_service.js +4 -1
- package/dist/web/sessions/db/operations.js +31 -7
- package/dist/web/tools/base_tool.js +3 -0
- package/dist/web/tools/base_toolset.js +11 -2
- package/dist/web/tools/exit_loop_tool.js +32 -0
- package/dist/web/tools/mcp/mcp_toolset.js +27 -5
- package/dist/web/utils/logger.js +51 -54
- package/dist/web/version.js +1 -1
- package/package.json +3 -2
- package/dist/cjs/agents/callback_context.js +0 -101
- package/dist/esm/agents/callback_context.js +0 -71
- package/dist/types/agents/callback_context.d.ts +0 -42
- package/dist/web/agents/callback_context.js +0 -71
- /package/dist/cjs/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
- /package/dist/esm/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
- /package/dist/web/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
|
|
2
|
+
var __await = function(promise, isYieldStar) {
|
|
3
|
+
this[0] = promise;
|
|
4
|
+
this[1] = isYieldStar;
|
|
5
|
+
};
|
|
6
|
+
var __asyncGenerator = (__this, __arguments, generator) => {
|
|
7
|
+
var resume = (k, v, yes, no) => {
|
|
8
|
+
try {
|
|
9
|
+
var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
|
|
10
|
+
Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
|
|
11
|
+
} catch (e) {
|
|
12
|
+
no(e);
|
|
13
|
+
}
|
|
14
|
+
}, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
|
|
15
|
+
return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* @license
|
|
19
|
+
* Copyright 2025 Google LLC
|
|
20
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
21
|
+
*/
|
|
22
|
+
import { appendInstructions } from "../../models/llm_request.js";
|
|
23
|
+
import { injectSessionState } from "../instructions.js";
|
|
24
|
+
import { isLlmAgent } from "../llm_agent.js";
|
|
25
|
+
import { ReadonlyContext } from "../readonly_context.js";
|
|
26
|
+
import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
|
|
27
|
+
class InstructionsLlmRequestProcessor extends BaseLlmRequestProcessor {
|
|
28
|
+
/**
|
|
29
|
+
* Handles instructions and global instructions for LLM flow.
|
|
30
|
+
*/
|
|
31
|
+
// eslint-disable-next-line require-yield
|
|
32
|
+
runAsync(invocationContext, llmRequest) {
|
|
33
|
+
return __asyncGenerator(this, null, function* () {
|
|
34
|
+
const agent = invocationContext.agent;
|
|
35
|
+
if (!isLlmAgent(agent) || !isLlmAgent(agent.rootAgent)) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const rootAgent = agent.rootAgent;
|
|
39
|
+
if (isLlmAgent(rootAgent) && rootAgent.globalInstruction) {
|
|
40
|
+
const { instruction, requireStateInjection } = yield new __await(rootAgent.canonicalGlobalInstruction(
|
|
41
|
+
new ReadonlyContext(invocationContext)
|
|
42
|
+
));
|
|
43
|
+
let instructionWithState = instruction;
|
|
44
|
+
if (requireStateInjection) {
|
|
45
|
+
instructionWithState = yield new __await(injectSessionState(
|
|
46
|
+
instruction,
|
|
47
|
+
new ReadonlyContext(invocationContext)
|
|
48
|
+
));
|
|
49
|
+
}
|
|
50
|
+
appendInstructions(llmRequest, [instructionWithState]);
|
|
51
|
+
}
|
|
52
|
+
if (agent.instruction) {
|
|
53
|
+
const { instruction, requireStateInjection } = yield new __await(agent.canonicalInstruction(
|
|
54
|
+
new ReadonlyContext(invocationContext)
|
|
55
|
+
));
|
|
56
|
+
let instructionWithState = instruction;
|
|
57
|
+
if (requireStateInjection) {
|
|
58
|
+
instructionWithState = yield new __await(injectSessionState(
|
|
59
|
+
instruction,
|
|
60
|
+
new ReadonlyContext(invocationContext)
|
|
61
|
+
));
|
|
62
|
+
}
|
|
63
|
+
appendInstructions(llmRequest, [instructionWithState]);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
|
|
69
|
+
export {
|
|
70
|
+
INSTRUCTIONS_LLM_REQUEST_PROCESSOR,
|
|
71
|
+
InstructionsLlmRequestProcessor
|
|
72
|
+
};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
|
|
2
|
+
var __await = function(promise, isYieldStar) {
|
|
3
|
+
this[0] = promise;
|
|
4
|
+
this[1] = isYieldStar;
|
|
5
|
+
};
|
|
6
|
+
var __asyncGenerator = (__this, __arguments, generator) => {
|
|
7
|
+
var resume = (k, v, yes, no) => {
|
|
8
|
+
try {
|
|
9
|
+
var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
|
|
10
|
+
Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
|
|
11
|
+
} catch (e) {
|
|
12
|
+
no(e);
|
|
13
|
+
}
|
|
14
|
+
}, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
|
|
15
|
+
return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* @license
|
|
19
|
+
* Copyright 2025 Google LLC
|
|
20
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
21
|
+
*/
|
|
22
|
+
import {
|
|
23
|
+
getFunctionCalls,
|
|
24
|
+
getFunctionResponses
|
|
25
|
+
} from "../../events/event.js";
|
|
26
|
+
import { ToolConfirmation } from "../../tools/tool_confirmation.js";
|
|
27
|
+
import {
|
|
28
|
+
REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
|
|
29
|
+
handleFunctionCallList
|
|
30
|
+
} from "../functions.js";
|
|
31
|
+
import { isLlmAgent } from "../llm_agent.js";
|
|
32
|
+
import { ReadonlyContext } from "../readonly_context.js";
|
|
33
|
+
import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
|
|
34
|
+
class RequestConfirmationLlmRequestProcessor extends BaseLlmRequestProcessor {
|
|
35
|
+
/** Handles tool confirmation information to build the LLM request. */
|
|
36
|
+
runAsync(invocationContext) {
|
|
37
|
+
return __asyncGenerator(this, null, function* () {
|
|
38
|
+
const agent = invocationContext.agent;
|
|
39
|
+
if (!isLlmAgent(agent)) {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const events = invocationContext.session.events;
|
|
43
|
+
if (!events || events.length === 0) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const requestConfirmationFunctionResponses = {};
|
|
47
|
+
let confirmationEventIndex = -1;
|
|
48
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
49
|
+
const event = events[i];
|
|
50
|
+
if (event.author !== "user") {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const responses = getFunctionResponses(event);
|
|
54
|
+
if (!responses) {
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
let foundConfirmation = false;
|
|
58
|
+
for (const functionResponse of responses) {
|
|
59
|
+
if (functionResponse.name !== REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
foundConfirmation = true;
|
|
63
|
+
let toolConfirmation = null;
|
|
64
|
+
if (functionResponse.response && Object.keys(functionResponse.response).length === 1 && "response" in functionResponse.response) {
|
|
65
|
+
toolConfirmation = JSON.parse(
|
|
66
|
+
functionResponse.response["response"]
|
|
67
|
+
);
|
|
68
|
+
} else if (functionResponse.response) {
|
|
69
|
+
toolConfirmation = new ToolConfirmation({
|
|
70
|
+
hint: functionResponse.response["hint"],
|
|
71
|
+
payload: functionResponse.response["payload"],
|
|
72
|
+
confirmed: functionResponse.response["confirmed"]
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
if (functionResponse.id && toolConfirmation) {
|
|
76
|
+
requestConfirmationFunctionResponses[functionResponse.id] = toolConfirmation;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (foundConfirmation) {
|
|
80
|
+
confirmationEventIndex = i;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (Object.keys(requestConfirmationFunctionResponses).length === 0) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
for (let i = confirmationEventIndex - 1; i >= 0; i--) {
|
|
88
|
+
const event = events[i];
|
|
89
|
+
const functionCalls = getFunctionCalls(event);
|
|
90
|
+
if (!functionCalls) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const toolsToResumeWithConfirmation = {};
|
|
94
|
+
const toolsToResumeWithArgs = {};
|
|
95
|
+
for (const functionCall of functionCalls) {
|
|
96
|
+
if (!functionCall.id || !(functionCall.id in requestConfirmationFunctionResponses)) {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const args = functionCall.args;
|
|
100
|
+
if (!args || !("originalFunctionCall" in args)) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const originalFunctionCall = args["originalFunctionCall"];
|
|
104
|
+
if (originalFunctionCall.id) {
|
|
105
|
+
toolsToResumeWithConfirmation[originalFunctionCall.id] = requestConfirmationFunctionResponses[functionCall.id];
|
|
106
|
+
toolsToResumeWithArgs[originalFunctionCall.id] = originalFunctionCall;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
for (let j = events.length - 1; j > confirmationEventIndex; j--) {
|
|
113
|
+
const eventToCheck = events[j];
|
|
114
|
+
const functionResponses = getFunctionResponses(eventToCheck);
|
|
115
|
+
if (!functionResponses) {
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
for (const fr of functionResponses) {
|
|
119
|
+
if (fr.id && fr.id in toolsToResumeWithConfirmation) {
|
|
120
|
+
delete toolsToResumeWithConfirmation[fr.id];
|
|
121
|
+
delete toolsToResumeWithArgs[fr.id];
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const toolsList = yield new __await(agent.canonicalTools(
|
|
132
|
+
new ReadonlyContext(invocationContext)
|
|
133
|
+
));
|
|
134
|
+
const toolsDict = Object.fromEntries(
|
|
135
|
+
toolsList.map((tool) => [tool.name, tool])
|
|
136
|
+
);
|
|
137
|
+
const functionResponseEvent = yield new __await(handleFunctionCallList({
|
|
138
|
+
invocationContext,
|
|
139
|
+
functionCalls: Object.values(toolsToResumeWithArgs),
|
|
140
|
+
toolsDict,
|
|
141
|
+
beforeToolCallbacks: agent.canonicalBeforeToolCallbacks,
|
|
142
|
+
afterToolCallbacks: agent.canonicalAfterToolCallbacks,
|
|
143
|
+
filters: new Set(Object.keys(toolsToResumeWithConfirmation)),
|
|
144
|
+
toolConfirmationDict: toolsToResumeWithConfirmation
|
|
145
|
+
}));
|
|
146
|
+
if (functionResponseEvent) {
|
|
147
|
+
yield functionResponseEvent;
|
|
148
|
+
}
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR = new RequestConfirmationLlmRequestProcessor();
|
|
155
|
+
export {
|
|
156
|
+
REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
|
|
157
|
+
RequestConfirmationLlmRequestProcessor
|
|
158
|
+
};
|
package/dist/web/common.js
CHANGED
|
@@ -5,17 +5,17 @@
|
|
|
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
19
|
import { ReadonlyContext } from "./agents/readonly_context.js";
|
|
20
20
|
import { StreamingMode } from "./agents/run_config.js";
|
|
21
21
|
import { SequentialAgent, isSequentialAgent } from "./agents/sequential_agent.js";
|
|
@@ -60,12 +60,12 @@ import { createSession } from "./sessions/session.js";
|
|
|
60
60
|
import { State } from "./sessions/state.js";
|
|
61
61
|
import { AgentTool, isAgentTool } from "./tools/agent_tool.js";
|
|
62
62
|
import { BaseTool, isBaseTool } from "./tools/base_tool.js";
|
|
63
|
-
import { BaseToolset } from "./tools/base_toolset.js";
|
|
63
|
+
import { BaseToolset, isBaseToolset } from "./tools/base_toolset.js";
|
|
64
|
+
import { EXIT_LOOP, ExitLoopTool } from "./tools/exit_loop_tool.js";
|
|
64
65
|
import { FunctionTool, isFunctionTool } from "./tools/function_tool.js";
|
|
65
66
|
import { GOOGLE_SEARCH, GoogleSearchTool } from "./tools/google_search_tool.js";
|
|
66
67
|
import { LongRunningFunctionTool } from "./tools/long_running_tool.js";
|
|
67
68
|
import { ToolConfirmation } from "./tools/tool_confirmation.js";
|
|
68
|
-
import { ToolContext } from "./tools/tool_context.js";
|
|
69
69
|
import { LogLevel, getLogger, setLogLevel, setLogger } from "./utils/logger.js";
|
|
70
70
|
import { isGemini2OrAbove } from "./utils/model_name.js";
|
|
71
71
|
import { zodObjectToSchema } from "./utils/simple_zod_to_json.js";
|
|
@@ -91,8 +91,10 @@ export {
|
|
|
91
91
|
BaseTool,
|
|
92
92
|
BaseToolset,
|
|
93
93
|
BuiltInCodeExecutor,
|
|
94
|
-
|
|
94
|
+
Context,
|
|
95
|
+
EXIT_LOOP,
|
|
95
96
|
EventType,
|
|
97
|
+
ExitLoopTool,
|
|
96
98
|
FunctionTool,
|
|
97
99
|
GOOGLE_SEARCH,
|
|
98
100
|
Gemini,
|
|
@@ -122,7 +124,6 @@ export {
|
|
|
122
124
|
State,
|
|
123
125
|
StreamingMode,
|
|
124
126
|
ToolConfirmation,
|
|
125
|
-
ToolContext,
|
|
126
127
|
createEvent,
|
|
127
128
|
createEventActions,
|
|
128
129
|
createSession,
|
|
@@ -138,6 +139,7 @@ export {
|
|
|
138
139
|
isBaseExampleProvider,
|
|
139
140
|
isBaseLlm,
|
|
140
141
|
isBaseTool,
|
|
142
|
+
isBaseToolset,
|
|
141
143
|
isFinalResponse,
|
|
142
144
|
isFunctionTool,
|
|
143
145
|
isGemini2OrAbove,
|
package/dist/web/index.js
CHANGED
|
@@ -1,23 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
var Mo=Object.defineProperty,No=Object.defineProperties;var Fo=Object.getOwnPropertyDescriptors;var Le=Object.getOwnPropertySymbols;var en=Object.prototype.hasOwnProperty,tn=Object.prototype.propertyIsEnumerable;var ce=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),Do=n=>{throw TypeError(n)};var Xt=(n,e,t)=>e in n?Mo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,y=(n,e)=>{for(var t in e||(e={}))en.call(e,t)&&Xt(n,t,e[t]);if(Le)for(var t of Le(e))tn.call(e,t)&&Xt(n,t,e[t]);return n},j=(n,e)=>No(n,Fo(e));var nn=(n,e)=>{var t={};for(var o in n)en.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&Le)for(var o of Le(n))e.indexOf(o)<0&&tn.call(n,o)&&(t[o]=n[o]);return t};var f=function(n,e){this[0]=n,this[1]=e},d=(n,e,t)=>{var o=(s,a,c,l)=>{try{var u=t[s](a),p=(a=u.value)instanceof f,m=u.done;Promise.resolve(p?a[0]:a).then(v=>p?o(s==="return"?s:"next",a[1]?{done:v.done,value:v.value}:v,c,l):c({value:v,done:m})).catch(v=>o("throw",v,c,l))}catch(v){l(v)}},r=s=>i[s]=a=>new Promise((c,l)=>o(s,a,c,l)),i={};return t=t.apply(n,e),i[ce("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i},N=n=>{var e=n[ce("asyncIterator")],t=!1,o,r={};return e==null?(e=n[ce("iterator")](),o=i=>r[i]=s=>e[i](s)):(e=e.call(n),o=i=>r[i]=s=>{if(t){if(t=!1,i==="throw")throw s;return s}return t=!0,{done:!1,value:new f(new Promise(a=>{var c=e[i](s);c instanceof Object||Do("Object expected"),a(c)}),1)}}),r[ce("iterator")]=()=>r,o("next"),"throw"in e?o("throw"):r.throw=i=>{throw i},"return"in e&&o("return"),r},T=(n,e,t)=>(e=n[ce("asyncIterator")])?e.call(n):(n=n[ce("iterator")](),e={},t=(o,r)=>(r=n[o])&&(e[o]=i=>new Promise((s,a,c)=>(i=r.call(n,i),c=i.done,Promise.resolve(i.value).then(l=>s({value:l,done:c}),a)))),t("next"),t("return"),e);var je=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};import{context as Cn,trace as vn}from"@opentelemetry/api";function U(n={}){return y({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},n)}function on(n,e){let t=U();e&&Object.assign(t,e);for(let o of n)o&&(o.stateDelta&&Object.assign(t.stateDelta,o.stateDelta),o.artifactDelta&&Object.assign(t.artifactDelta,o.artifactDelta),o.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,o.requestedAuthConfigs),o.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,o.requestedToolConfirmations),o.skipSummarization!==void 0&&(t.skipSummarization=o.skipSummarization),o.transferToAgent!==void 0&&(t.transferToAgent=o.transferToAgent),o.escalate!==void 0&&(t.escalate=o.escalate));return t}function b(n={}){return j(y({},n),{id:n.id||Ke(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||U(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()})}function K(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:w(n).length===0&&B(n).length===0&&!n.partial&&!sn(n)}function w(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionCall&&e.push(t.functionCall);return e}function B(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function sn(n){var e;return n.content&&((e=n.content.parts)!=null&&e.length)?n.content.parts[n.content.parts.length-1].codeExecutionResult!==void 0:!1}function Go(n){var e;return(e=n.content)!=null&&e.parts?n.content.parts.map(t=>{var o;return(o=t.text)!=null?o:""}).join(""):""}var rn="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Ke(){let n="";for(let e=0;e<8;e++)n+=rn[Math.floor(Math.random()*rn.length)];return n}import{context as He,trace as ve}from"@opentelemetry/api";var ge="0.5.0";var qo="gen_ai.agent.description",Uo="gen_ai.agent.name",$o="gen_ai.conversation.id",Ze="gen_ai.operation.name",an="gen_ai.tool.call.id",cn="gen_ai.tool.description",ln="gen_ai.tool.name",Vo="gen_ai.tool.type",$=ve.getTracer("gcp.vertex.agent",ge);function he(n){try{return JSON.stringify(n)}catch(e){return"<not serializable>"}}function un({agent:n,invocationContext:e}){let t=ve.getActiveSpan();t&&t.setAttributes({[Ze]:"invoke_agent",[qo]:n.description,[Uo]:n.name,[$o]:e.session.id})}function fn({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=ve.getActiveSpan();if(!o)return;o.setAttributes({[Ze]:"execute_tool",[cn]:n.description||"",[ln]:n.name,[Vo]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":Ce()?he(e):"{}"});let r="<not specified>",i="<not specified>";if((s=t.content)!=null&&s.parts){let l=(a=t.content.parts[0])==null?void 0:a.functionResponse;l!=null&&l.id&&(r=l.id),l!=null&&l.response&&(i=l.response)}(typeof i!="object"||i===null)&&(i={result:i}),o.setAttributes({[an]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":Ce()?he(i):"{}"})}function pn({responseEventId:n,functionResponseEvent:e}){let t=ve.getActiveSpan();t&&(t.setAttributes({[Ze]:"execute_tool",[ln]:"(merged tools)",[cn]:"(merged tools)",[an]:n,"gcp.vertex.agent.tool_call_args":"N/A","gcp.vertex.agent.event_id":n,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}"}),t.setAttribute("gcp.vertex.agent.tool_response",Ce()?he(e):"{}"))}function dn({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=ve.getActiveSpan();if(r&&(r.setAttributes({"gen_ai.system":"gcp.vertex.agent","gen_ai.request.model":t.model,"gcp.vertex.agent.invocation_id":n.invocationId,"gcp.vertex.agent.session_id":n.session.id,"gcp.vertex.agent.event_id":e,"gcp.vertex.agent.llm_request":Ce()?he(zo(t)):"{}"}),(i=t.config)!=null&&i.topP&&r.setAttribute("gen_ai.request.top_p",t.config.topP),((s=t.config)==null?void 0:s.maxOutputTokens)!==void 0&&r.setAttribute("gen_ai.request.max_tokens",t.config.maxOutputTokens),r.setAttribute("gcp.vertex.agent.llm_response",Ce()?he(o):"{}"),o.usageMetadata&&r.setAttribute("gen_ai.usage.input_tokens",o.usageMetadata.promptTokenCount||0),(a=o.usageMetadata)!=null&&a.candidatesTokenCount&&r.setAttribute("gen_ai.usage.output_tokens",o.usageMetadata.candidatesTokenCount),o.finishReason)){let c=typeof o.finishReason=="string"?o.finishReason.toLowerCase():String(o.finishReason).toLowerCase();r.setAttribute("gen_ai.response.finish_reasons",[c])}}function zo(n){let e={model:n.model,contents:[]};if(n.config){let t=n.config,{responseSchema:o}=t,r=nn(t,["responseSchema"]);e.config=r}return e.contents=n.contents.map(o=>{var r;return{role:o.role,parts:((r=o.parts)==null?void 0:r.filter(i=>!i.inlineData))||[]}}),e}function mn(n,e){return{next:He.bind(n,e.next.bind(e)),return:He.bind(n,e.return.bind(e)),throw:He.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return mn(n,e[Symbol.asyncIterator]())}}}function Q(n,e,t){let o=t.call(e);return mn(n,o)}function Ce(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}var Ae=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,o;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((o=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&o.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".concat(e," requires authCredential."));if(!this.authConfig.rawAuthCredential.oauth2)throw new Error("Auth Scheme ".concat(e," requires oauth2 in authCredential."));if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error("Auth Scheme ".concat(e," requires both clientId and clientSecret in authCredential.oauth2."));return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var S=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta=y(y({},this.delta),e),this.value=y(y({},this.value),e)}toRecord(){return y(y({},this.value),this.delta)}};S.APP_PREFIX="app:",S.USER_PREFIX="user:",S.TEMP_PREFIX="temp:";var W=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var _=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get userId(){return this.invocationContext.userId}get sessionId(){return this.invocationContext.session.id}get agentName(){return this.invocationContext.agent.name}get state(){return new S(this.invocationContext.session.state,{})}};var k=class extends _{constructor(e){super(e.invocationContext),this.eventActions=e.eventActions||U(),this._state=new S(e.invocationContext.session.state,this.eventActions.stateDelta),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get state(){return this._state}get actions(){return this.eventActions}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let o=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=o,o}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new Ae(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Ae(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new W({hint:e,confirmed:!1,payload:t})}};function F(){return typeof window<"u"}var _e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function le(){let n="";for(let e=0;e<_e.length;e++){let t=Math.random()*16|0;_e[e]==="x"?n+=t.toString(16):_e[e]==="y"?n+=(t&3|8).toString(16):n+=_e[e]}return n}function gn(n){return F()?window.atob(n):Buffer.from(n,"base64").toString()}function ke(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}var Ye=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error("Max number of llm calls limit of ".concat(e.maxLlmCalls," exceeded"))}},V=class{constructor(e){this.invocationCostManager=new Ye;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function hn(){return"e-".concat(le())}var Qe=Symbol.for("google.adk.baseAgent");function jo(n){return typeof n=="object"&&n!==null&&Qe in n&&n[Qe]===!0}var xn;xn=Qe;var D=class{constructor(e){this[xn]=!0;this.name=Ko(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=An(e.beforeAgentCallback),this.afterAgentCallback=An(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return Zo(this)}runAsync(e){return d(this,null,function*(){let t=$.startSpan("invoke_agent ".concat(this.name)),o=vn.setSpan(Cn.active(),t);try{yield*N(Q(o,this,function(){return d(this,null,function*(){let r=this.createInvocationContext(e),i=yield new f(this.handleBeforeAgentCallback(r));if(i&&(yield i),r.endInvocation)return;un({agent:this,invocationContext:r});try{for(var a=T(this.runAsyncImpl(r)),c,l,u;c=!(l=yield new f(a.next())).done;c=!1){let p=l.value;yield p}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new f(l.call(a)))}finally{if(u)throw u[0]}}if(r.endInvocation)return;let s=yield new f(this.handleAfterAgentCallback(r));s&&(yield s)})}))}finally{t.end()}})}runLive(e){return d(this,null,function*(){let t=$.startSpan("invoke_agent ".concat(this.name)),o=vn.setSpan(Cn.active(),t);try{throw yield*N(Q(o,this,function(){return d(this,null,function*(){})})),new Error("Live mode is not implemented yet.")}finally{t.end()}})}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let o=t.findAgent(e);if(o)return o}}createInvocationContext(e){return new V(j(y({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new k({invocationContext:e});for(let o of this.beforeAgentCallback){let r=await o(t);if(r)return e.endInvocation=!0,b({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return b({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new k({invocationContext:e});for(let o of this.afterAgentCallback){let r=await o(t);if(r)return b({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return b({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error('Agent "'.concat(e.name,'" already has a parent agent, current parent: "').concat(e.parentAgent.name,'", trying to add: "').concat(this.name,'"'));e.parentAgent=this}}};function Ko(n){if(!Ho(n))throw new Error('Found invalid agent name: "'.concat(n,'". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), underscores, and hyphens.'));if(n==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return n}function Ho(n){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_-]*$","u").test(n)}function Zo(n){for(;n.parentAgent;)n=n.parentAgent;return n}function An(n){return n?Array.isArray(n)?n:[n]:[]}import{createUserContent as Jo}from"@google/genai";import{isEmpty as yn}from"lodash-es";import*as G from"winston";var En=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(En||{}),We=class{constructor(){this.logLevel=1;this.logger=G.createLogger({levels:{debug:0,info:1,warn:2,error:3},format:G.format.combine(G.format.label({label:"ADK"}),G.format(e=>(e.level=e.level.toUpperCase(),e))(),G.format.colorize(),G.format.timestamp(),G.format.printf(e=>"".concat(e.level,": [").concat(e.label,"] ").concat(e.timestamp," ").concat(e.message))),transports:[new G.transports.Console]})}setLogLevel(e){this.logLevel=e}log(e,...t){this.logLevel>e||this.logger.log(e.toString(),t.join(" "))}debug(...e){this.logLevel>0||this.logger.debug(e.join(" "))}info(...e){this.logLevel>1||this.logger.info(e.join(" "))}warn(...e){this.logLevel>2||this.logger.warn(e.join(" "))}error(...e){this.logLevel>3||this.logger.error(e.join(" "))}},Je=class{setLogLevel(e){}log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},H=new We;function Yo(n){H=n!=null?n:new Je}function Qo(){return H}function Wo(n){h.setLogLevel(n)}var h={setLogLevel(n){H.setLogLevel(n)},log(n,...e){H.log(n,...e)},debug(...n){H.debug(...n)},info(...n){H.info(...n)},warn(...n){H.warn(...n)},error(...n){H.error(...n)}};var Xe="adk-",Pe="adk_request_credential",ue="adk_request_confirmation",Xo={handleFunctionCallList:Oe,generateAuthEvent:tt,generateRequestConfirmationEvent:nt};function et(){return"".concat(Xe).concat(le())}function Tn(n){let e=w(n);if(e)for(let t of e)t.id||(t.id=et())}function Sn(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Xe)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Xe)&&(e.functionResponse.id=void 0)}function bn(n,e){let t=new Set;for(let o of n)o.name&&o.name in e&&e[o.name].isLongRunning&&o.id&&t.add(o.id);return t}function tt(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||yn(e.actions.requestedAuthConfigs))return;let t=[],o=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:Pe,args:{function_call_id:i,auth_config:s},id:et()};o.add(a.id),t.push({functionCall:a})}return b({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function nt({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||yn(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=w(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(a=i.find(m=>m.id===c))!=null?a:void 0;if(!u)continue;let p={name:ue,args:{originalFunctionCall:u,toolConfirmation:l},id:et()};r.add(p.id),o.push({functionCall:p})}return b({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:o,role:t.content.role},actions:t.actions,longRunningToolIds:Array.from(r)})}async function er(n,e,t){return $.startActiveSpan("execute_tool ".concat(n.name),async o=>{try{h.debug("callToolAsync ".concat(n.name));let r=await n.runAsync({args:e,toolContext:t});return fn({tool:n,args:e,functionResponseEvent:tr(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function tr(n,e,t,o){let r;typeof e!="object"||e==null?r={result:e}:r=e;let s={role:"user",parts:[{functionResponse:{name:n.name,response:r,id:t.functionCallId}}]};return b({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function Rn({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=w(e);return await Oe({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Oe({invocationContext:n,functionCalls:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u;let a=[],c=e.filter(p=>!i||p.id&&i.has(p.id));for(let p of c){let m;s&&p.id&&(m=s[p.id]);let{tool:v,toolContext:C}=nr({invocationContext:n,functionCall:p,toolsDict:t,toolConfirmation:m});h.debug("execute_tool ".concat(v.name));let A=(u=p.args)!=null?u:{},g=null,x;if(g=await n.pluginManager.runBeforeToolCallback({tool:v,toolArgs:A,toolContext:C}),g==null){for(let L of o)if(g=await L({tool:v,args:A,context:C}),g)break}if(g==null)try{g=await er(v,A,C)}catch(L){if(L instanceof Error){let R=await n.pluginManager.runOnToolErrorCallback({tool:v,toolArgs:A,toolContext:C,error:L});R?g=R:x=L.message}else x=L}let I=await n.pluginManager.runAfterToolCallback({tool:v,toolArgs:A,toolContext:C,result:g});if(I==null){for(let L of r)if(I=await L({tool:v,args:A,context:C,response:g}),I)break}if(I!=null&&(g=I),v.isLongRunning&&!g)continue;x?g={error:x}:(typeof g!="object"||g==null)&&(g={result:g});let O=b({invocationId:n.invocationId,author:n.agent.name,content:Jo({functionResponse:{id:C.functionCallId,name:v.name,response:g}}),actions:C.actions,branch:n.branch});h.debug("traceToolCall",{tool:v.name,args:A,functionResponseEvent:O.id}),a.push(O)}if(!a.length)return null;let l=or(a);return a.length>1&&$.startActiveSpan("execute_tool (merged)",p=>{try{h.debug("execute_tool (merged)"),h.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),pn({responseEventId:l.id,functionResponseEvent:l})}finally{p.end()}}),l}function nr({invocationContext:n,functionCall:e,toolsDict:t,toolConfirmation:o}){if(!e.name||!(e.name in t))throw new Error("Function ".concat(e.name," is not found in the toolsDict."));let r=new k({invocationContext:n,functionCallId:e.id||void 0,toolConfirmation:o});return{tool:t[e.name],toolContext:r}}function or(n){if(!n.length)throw new Error("No function response events provided.");if(n.length===1)return n[0];let e=[];for(let i of n)i.content&&i.content.parts&&e.push(...i.content.parts);let t=n[0],o=n.map(i=>i.actions||{}),r=on(o);return b({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var ot=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),o=this.queue.shift();t(o)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}[Symbol.asyncIterator](){return d(this,null,function*(){for(;;){let e=yield new f(this.get());if(yield e,e.close)break}})}};import{context as qr,trace as Ur}from"@opentelemetry/api";var rr="google-adk",ir="gl-typescript",sr="remote_reasoning_engine",ar="GOOGLE_CLOUD_AGENT_ENGINE_ID";function cr(){let n="".concat(rr,"/").concat(ge);!F()&&process.env[ar]&&(n="".concat(n,"+").concat(sr));let e="".concat(ir,"/").concat(F()?window.navigator.userAgent:process.version);return[n,e]}function In(){return cr()}var rt=Symbol.for("google.adk.baseModel");function it(n){return typeof n=="object"&&n!==null&&rt in n&&n[rt]===!0}var wn;wn=rt;var fe=class{constructor({model:e}){this[wn]=!0;this.model=e}get trackingHeaders(){let t=In().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};fe.supportedModels=[];import{createPartFromText as _n,FinishReason as lr,GoogleGenAI as at}from"@google/genai";var Be=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(Be||{});function Ln(){return ke("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}var Me=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(o=>{var r;return o.parts&&((r=o.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):h.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(o=>o.functionResponse).filter(o=>!!o);h.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else h.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){h.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}receive(){return d(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};function st(n){var t;let e=n.usageMetadata;if(n.candidates&&n.candidates.length>0){let o=n.candidates[0];return(t=o.content)!=null&&t.parts&&o.content.parts.length>0?{content:o.content,groundingMetadata:o.groundingMetadata,citationMetadata:o.citationMetadata,usageMetadata:e,finishReason:o.finishReason}:{errorCode:o.finishReason,errorMessage:o.finishMessage,usageMetadata:e,citationMetadata:o.citationMetadata,finishReason:o.finishReason}}return n.promptFeedback?{errorCode:n.promptFeedback.blockReason,errorMessage:n.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var Z=class extends fe{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e});let a=Ne({model:e,vertexai:o,project:r,location:i,apiKey:t});if(!a.vertexai&&!a.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.");this.project=a.project,this.location=a.location,this.apiKey=a.apiKey,this.headers=s,this.vertexai=!!a.vertexai}generateContentAsync(e,t=!1){return d(this,null,function*(){var o,r,i,s,p,m,v;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),h.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(o=e.config)!=null&&o.httpOptions&&(e.config.httpOptions.headers=y(y({},e.config.httpOptions.headers),this.trackingHeaders)),t){let C=yield new f(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),A="",g="",x,I;try{for(var a=T(C),c,l,u;c=!(l=yield new f(a.next())).done;c=!1){let O=l.value;I=O;let L=st(O);x=L.usageMetadata;let R=(s=(i=L.content)==null?void 0:i.parts)==null?void 0:s[0];if(R!=null&&R.text)"thought"in R&&R.thought?A+=R.text:g+=R.text,L.partial=!0;else if((A||g)&&(!R||!R.inlineData)){let Y=[];A&&Y.push({text:A,thought:!0}),g&&Y.push(_n(g)),yield{content:{role:"model",parts:Y},usageMetadata:L.usageMetadata},A="",g=""}yield L}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new f(l.call(a)))}finally{if(u)throw u[0]}}if((g||A)&&((m=(p=I==null?void 0:I.candidates)==null?void 0:p[0])==null?void 0:m.finishReason)===lr.STOP){let O=[];A&&O.push({text:A,thought:!0}),g&&O.push({text:g}),yield{content:{role:"model",parts:O},usageMetadata:x}}}else{let C=yield new f(this.apiClient.models.generateContent({model:(v=e.model)!=null?v:this.model,contents:e.contents,config:e.config}));yield st(C)}})}getHttpOptions(){return{headers:y(y({},this.trackingHeaders),this.headers)}}get apiClient(){return this._apiClient?this._apiClient:(this.vertexai?this._apiClient=new at({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:this.getHttpOptions()}):this._apiClient=new at({apiKey:this.apiKey,httpOptions:this.getHttpOptions()}),this._apiClient)}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}getLiveHttpOptions(){return{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new at({apiKey:this.apiKey,httpOptions:this.getLiveHttpOptions()})),this._liveApiClient}async connect(e){var o,r,i,s;(o=e.liveConnectConfig)!=null&&o.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[_n(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new Me(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let o of t.parts)kn(o.inlineData),kn(o.fileData)}}};Z.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function kn(n){n&&n.displayName&&(n.displayName=void 0)}function Ne({model:n,vertexai:e,project:t,location:o,apiKey:r}){let i={model:n,vertexai:e,project:t,location:o,apiKey:r};if(i.vertexai=!!e,!i.vertexai&&!F()&&(i.vertexai=ke("GOOGLE_GENAI_USE_VERTEXAI")),i.vertexai){if(!F()&&!i.project&&(i.project=process.env.GOOGLE_CLOUD_PROJECT),!F()&&!i.location&&(i.location=process.env.GOOGLE_CLOUD_LOCATION),!i.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!i.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else!i.apiKey&&!F()&&(i.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY);return i}var Pn="APIGEE_PROXY_URL",pe=class extends Z{constructor({model:e,proxyUrl:t,apiKey:o,vertexai:r,location:i,project:s,headers:a}){var c;if(!Bn(e))throw new Error("Model ".concat(e," is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>"));if(super(j(y({},ur({model:e,vertexai:r,project:s,location:i,apiKey:o})),{headers:a})),this.proxyUrl=t!=null?t:"",!F()&&!this.proxyUrl&&(this.proxyUrl=(c=process.env[Pn])!=null?c:""),!this.proxyUrl)throw new Error("Proxy URL must be provided via the constructor or ".concat(Pn," environment variable."))}getHttpOptions(){let e=super.getHttpOptions();return e.baseUrl=this.proxyUrl,e}getLiveHttpOptions(){let e=super.getLiveHttpOptions();return e.baseUrl=this.proxyUrl,e}identifyApiVersion(){let t=(this.model.startsWith("apigee/")?this.model.substring(7):this.model).split("/");return t.length===3?t[1]:t.length===2&&t[0]!="vertex_ai"&&t[0]!="gemini"&&t[0].startsWith("v")?t[0]:this.vertexai?"v1beta1":"v1alpha"}get liveApiVersion(){return this._apigeeLiveApiVersion||(this._apigeeLiveApiVersion=this.identifyApiVersion()),this._apigeeLiveApiVersion}generateContentAsync(e,t=!1){return d(this,null,function*(){var r;let o=(r=e.model)!=null?r:this.model;e.model=On(o),yield*N(super.generateContentAsync(e,t))})}async connect(e){var o;let t=(o=e.model)!=null?o:this.model;return e.model=On(t),super.connect(e)}};pe.supportedModels=[/apigee\/.*/];function ur({model:n,vertexai:e,project:t,location:o,apiKey:r}){var s;let i=Ne({model:n,vertexai:e,project:t,location:o,apiKey:r});return i.vertexai=i.vertexai||((s=i.model)==null?void 0:s.startsWith("apigee/vertex_ai/")),i.vertexai||i.apiKey||(h.warn('No API key provided when using a Gemini model, using a fake key "-".'),i.apiKey="-"),i}function On(n){if(!Bn(n))throw new Error("Model ".concat(n," is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>"));let e=n.split("/");return e[e.length-1]}function Bn(n){let e=["vertex_ai","gemini"];if(!n.startsWith("apigee/"))return!1;let t=n.substring(7);if(t.length===0)return!1;let o=t.split("/",-1);return o[o.length-1].length===0?!1:o.length==1?!0:o.length==2?e.includes(o[0])?!0:o[0].startsWith("v"):o.length==3&&e.includes(o[0])?o[1].startsWith("v"):!1}var ct=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}},M=class M{static newLlm(e){return new(M.resolve(e))({model:e})}static _register(e,t){M.llmRegistryDict.has(e)&&h.info("Updating LLM class for ".concat(e," from ").concat(M.llmRegistryDict.get(e)," to ").concat(t)),M.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)M._register(t,e)}static resolve(e){let t=M.resolveCache.get(e);if(t)return t;for(let[o,r]of M.llmRegistryDict.entries())if(new RegExp("^".concat(o instanceof RegExp?o.source:o,"$"),o instanceof RegExp?o.flags:void 0).test(e))return M.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};M.llmRegistryDict=new Map,M.resolveCache=new ct(32);var J=M;J.register(Z);J.register(pe);var lt=Symbol.for("google.adk.baseTool");function ut(n){return typeof n=="object"&&n!==null&< in n&&n[lt]===!0}var Mn;Mn=lt;var q=class{constructor(e){this[Mn]=!0;var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({llmRequest:e}){let t=this._getDeclaration();if(!t)return;if(this.name in e.toolsDict)throw new Error("Duplicate tool name: ".concat(this.name));e.toolsDict[this.name]=this;let o=fr(e);o?(o.functionDeclarations||(o.functionDeclarations=[]),o.functionDeclarations.push(t)):(e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({functionDeclarations:[t]}))}get apiVariant(){return Ln()}};function fr(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Nn}from"@google/genai";import{zodToJsonSchema as pr}from"zod-to-json-schema";import{toJSONSchema as dr}from"zod/v4";function ft(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function mr(n){return ft(n)&&!("_zod"in n)}function gr(n){return ft(n)&&"_zod"in n}function hr(n){var o,r;let e=n;if((o=e._def)!=null&&o.typeName)return e._def.typeName;let t=(r=e._def)==null?void 0:r.type;if(typeof t=="string"&&t)return"Zod"+t.charAt(0).toUpperCase()+t.slice(1)}function X(n){return ft(n)&&hr(n)==="ZodObject"}function de(n){if(!X(n))throw new Error("Expected a Zod Object");if(gr(n))return dr(n,{target:"openapi-3.0",io:"input",override:e=>{var o;let{jsonSchema:t}=e;t.additionalProperties!==void 0&&delete t.additionalProperties,t.readOnly!==void 0&&delete t.readOnly,t.maxItems!==void 0&&(t.maxItems=t.maxItems.toString()),(t.format==="email"||t.format==="uuid")&&delete t.pattern,t.minItems!==void 0&&(t.minItems=t.minItems.toString()),t.minLength!==void 0&&(t.minLength=t.minLength.toString()),t.maxLength!==void 0&&(t.maxLength=t.maxLength.toString()),((o=t.enum)==null?void 0:o.length)===1&&t.enum[0]===null&&(t.type=Nn.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(mr(n))return pr(n,{target:"openApi3",emailStrategy:"format:email",postProcess:e=>{var t,o,r,i,s,a,c;if(e)return e.additionalProperties!==void 0&&delete e.additionalProperties,e.maxItems!==void 0&&(e.maxItems=(t=e.maxItems)==null?void 0:t.toString()),e.minItems!==void 0&&(e.minItems=(o=e.minItems)==null?void 0:o.toString()),e.minLength!==void 0&&(e.minLength=(r=e.minLength)==null?void 0:r.toString()),e.maxLength!==void 0&&(e.maxLength=(i=e.maxLength)==null?void 0:i.toString()),((s=e.enum)==null?void 0:s.length)===1&&e.enum[0]==="null"&&(e.type=Nn.NULL,delete e.enum),e.type==="integer"&&e.format!=="int64"&&((a=e.minimum)!=null||(e.minimum=Number.MIN_SAFE_INTEGER),(c=e.maximum)!=null||(e.maximum=Number.MAX_SAFE_INTEGER)),e.type!==void 0&&(e.type=e.type.toUpperCase()),e}});throw new Error("Unsupported Zod schema version.")}import{z as qn}from"zod";function ee(n,e){n.config||(n.config={});let t=e.join("\n\n");n.config.systemInstruction?n.config.systemInstruction+="\n\n"+t:n.config.systemInstruction=t}function Fn(n,e){n.config||(n.config={}),n.config.responseSchema=e,n.config.responseMimeType="application/json"}import{Type as Cr}from"@google/genai";function vr(n){return n===void 0?{type:Cr.OBJECT,properties:{}}:X(n)?de(n):n}var pt=Symbol.for("google.adk.functionTool");function Ar(n){return typeof n=="object"&&n!==null&&pt in n&&n[pt]===!0}var Dn,Gn,z=class extends(Gn=q,Dn=pt,Gn){constructor(t){var r;let o=(r=t.name)!=null?r:t.execute.name;if(!o)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:o,description:t.description,isLongRunning:t.isLongRunning});this[Dn]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:vr(this.parameters)}}async runAsync(t){try{let o=t.args;return X(this.parameters)&&(o=this.parameters.parse(t.args)),await this.execute(o,t.toolContext)}catch(o){let r=o instanceof Error?o.message:String(o);throw new Error("Error in tool '".concat(this.name,"': ").concat(r))}}};var P=class{},dt=class{};var mt=class extends P{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new z({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:qn.object({agentName:qn.string().describe("the agent name to transfer to.")}),execute:function(t,o){if(!o)throw new Error("toolContext is required.");return o.actions.transferToAgent=t.agentName,"Transfer queued"}})}runAsync(t,o){return d(this,null,function*(){if(!E(t.agent))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;ee(o,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new k({invocationContext:t});yield new f(this.tool.processLlmRequest({toolContext:i,llmRequest:o}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,o){let r="\nYou have a list of other agents to transfer to:\n\n".concat(o.map(i=>this.buildTargetAgentsInfo(i)).join("\n"),"\n\nIf you are the best to answer the question according to your description, you\ncan answer it.\n\nIf another agent is better for answering the question according to its\ndescription, call `").concat(this.toolName,"` function to transfer the\nquestion to that agent. When transferring, do not generate any text other than\nthe function call.\n");return t.parentAgent&&!t.disallowTransferToParent&&(r+="\nYour parent agent is ".concat(t.parentAgent.name,". If neither the other agents nor\nyou are best for answering the question according to the descriptions, transfer\nto your parent agent.\n")),r}getTransferTargets(t){let o=[];return o.push(...t.subAgents),!t.parentAgent||!E(t.parentAgent)||(t.disallowTransferToParent||o.push(t.parentAgent),t.disallowTransferToPeers||o.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),o}},Un=new mt;var gt=class extends P{runAsync(e,t){return d(this,null,function*(){var r;let o=e.agent;E(o)&&(t.model=o.canonicalModel.model,t.config=y({},(r=o.generateContentConfig)!=null?r:{}),o.outputSchema&&Fn(t,o.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))})}},$n=new gt;import{cloneDeep as Jn}from"lodash-es";var ht=Symbol.for("google.adk.baseCodeExecutor");function Fe(n){return typeof n=="object"&&n!==null&&ht in n&&n[ht]===!0}var Vn;Vn=ht;var xe=class{constructor(){this[Vn]=!0;this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var xr="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Ct(n){let e=n.match(xr);return e?e[1]:n}function zn(n){return Ct(n).startsWith("gemini-")}function Er(n){if(!/^\d+(\.\d+)*$/.test(n))return{valid:!1,major:0,minor:0,patch:0};let e=n.split(".").map(t=>parseInt(t,10));return{valid:!0,major:e[0],minor:e.length>1?e[1]:0,patch:e.length>2?e[2]:0}}function jn(n){return Ct(n).startsWith("gemini-1")}function Ee(n){if(!n)return!1;let e=Ct(n);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],o=Er(t);return o.valid&&o.major>=2}var vt=Symbol.for("google.adk.builtInCodeExecutor");function Te(n){return typeof n=="object"&&n!==null&&vt in n&&n[vt]===!0}var Kn,Hn,ye=class extends(Hn=xe,Kn=vt,Hn){constructor(){super(...arguments);this[Kn]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&Ee(t.model)){t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({codeExecution:{}});return}throw new Error("Gemini code execution tool is not supported for model ".concat(t.model))}};import{Language as yr,Outcome as Zn}from"@google/genai";import{cloneDeep as Tr}from"lodash-es";function Yn(n,e){var u;if(!((u=n.parts)!=null&&u.length))return"";for(let p=0;p<n.parts.length;p++){let m=n.parts[p];if(m.executableCode&&(p===n.parts.length-1||!n.parts[p+1].codeExecutionResult))return n.parts=n.parts.slice(0,p+1),m.executableCode.code}let t=n.parts.filter(p=>p.text);if(!t.length)return"";let o=Tr(t[0]),r=t.map(p=>p.text).join("\n"),i=e.map(p=>p[0]).join("|"),s=e.map(p=>p[1]).join("|"),a=new RegExp("?<prefix>.*?)(".concat(i,")(?<codeStr>.*?)(").concat(s,")(?<suffix>.*?)$"),"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(n.parts=[],c&&(o.text=c,n.parts.push(o)),n.parts.push(At(l)),l):""}function At(n){return{text:n,executableCode:{code:n,language:yr.PYTHON}}}function Qn(n){if(n.stderr)return{text:n.stderr,codeExecutionResult:{outcome:Zn.OUTCOME_FAILED}};let e=[];return(n.stdout||!n.outputFiles)&&e.push("Code execution result:\n".concat(n.stdout,"\n")),n.outputFiles&&e.push("Saved artifacts:\n"+n.outputFiles.map(t=>t.name).join(", ")),{text:e.join("\n\n"),codeExecutionResult:{outcome:Zn.OUTCOME_OK}}}function Wn(n,e,t){var r;if(!((r=n.parts)!=null&&r.length))return;let o=n.parts[n.parts.length-1];o.executableCode?n.parts[n.parts.length-1]={text:e[0]+o.executableCode.code+e[1]}:n.parts.length==1&&o.codeExecutionResult&&(n.parts[n.parts.length-1]={text:t[0]+o.codeExecutionResult.output+t[1]},n.role="user")}import{cloneDeep as Sr}from"lodash-es";var xt="_code_execution_context",Et="execution_session_id",te="processed_input_files",ne="_code_executor_input_files",oe="_code_executor_error_counts",yt="_code_execution_results",Se=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(xt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[xt]:Sr(this.context)}}getExecutionId(){if(Et in this.context)return this.context[Et]}setExecutionId(e){this.context[Et]=e}getProcessedFileNames(){return te in this.context?this.context[te]:[]}addProcessedFileNames(e){te in this.context||(this.context[te]=[]),this.context[te].push(...e)}getInputFiles(){return ne in this.sessionState?this.sessionState.get(ne):[]}addInputFiles(e){ne in this.sessionState||this.sessionState.set(ne,[]),this.sessionState.get(ne).push(...e)}clearInputFiles(){ne in this.sessionState&&this.sessionState.set(ne,[]),te in this.context&&(this.context[te]=[])}getErrorCount(e){return oe in this.sessionState&&this.sessionState.get(oe)[e]||0}incrementErrorCount(e){oe in this.sessionState||this.sessionState.set(oe,{}),this.sessionState.get(oe)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(oe in this.sessionState))return;let t=this.sessionState.get(oe);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:o,resultStderr:r}){yt in this.sessionState||this.sessionState.set(yt,{});let i=this.sessionState.get(yt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:o,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(){return this.sessionState.get(xt)||{}}};var Tt=class extends P{runAsync(e,t){return d(this,null,function*(){if(E(e.agent)&&e.agent.codeExecutor){try{for(var o=T(Rr(e,t)),r,i,s;r=!(i=yield new f(o.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new f(i.call(o)))}finally{if(s)throw s[0]}}if(Fe(e.agent.codeExecutor))for(let a of t.contents){let c=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""];Wn(a,c,e.agent.codeExecutor.executionResultDelimiters)}}})}},De={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},br="\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n",St=class{runAsync(e,t){return d(this,null,function*(){if(!t.partial)try{for(var o=T(Ir(e,t)),r,i,s;r=!(i=yield new f(o.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new f(i.call(o)))}finally{if(s)throw s[0]}}})}},fc=new St;function Rr(n,e){return d(this,null,function*(){let t=n.agent;if(!E(t))return;let o=t.codeExecutor;if(!o||!Fe(o))return;if(Te(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new Se(new S(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=wr(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=Lr(c);if(!l)return;let u={role:"model",parts:[{text:"Processing input file: `".concat(c.name,"`")},At(l)]};e.contents.push(Jn(u)),yield b({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let p=Xn(n,r),m=yield new f(o.executeCode({invocationContext:n,codeExecutionInput:{code:l,inputFiles:[c],executionId:p}}));r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:m.stdout,resultStderr:m.stderr}),r.addProcessedFileNames([c.name]);let v=yield new f(eo(n,r,m));yield v,e.contents.push(Jn(v.content))}})}function Ir(n,e){return d(this,null,function*(){let t=n.agent;if(!E(t))return;let o=t.codeExecutor;if(!o||!Fe(o)||!e||!e.content||Te(o))return;let r=new Se(new S(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=Yn(i,o.codeBlockDelimiters);if(!s)return;yield b({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=Xn(n,r),c=yield new f(o.executeCode({invocationContext:n,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}}));r.updateCodeExecutionResult({invocationId:n.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield yield new f(eo(n,r,c)),e.content=void 0})}function wr(n,e){var r;let t=n.getInputFiles(),o=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let a=0;a<s.parts.length;a++){let c=s.parts[a],l=(r=c.inlineData)==null?void 0:r.mimeType;if(!l||!c.inlineData||!De[l])continue;let u="data_".concat(i+1,"_").concat(a+1).concat(De[l].extension);c.text="\nAvailable file: `".concat(u,"`\n");let p={name:u,content:gn(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([p]),t.push(p))}}return t}function Xn(n,e){var r;let t=n.agent;if(!E(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function eo(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[Qn(t)]},r=U({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(n.invocationId):e.resetErrorCount(n.invocationId);for(let i of t.outputFiles){let s=await n.artifactService.saveArtifact({appName:n.appName||"",userId:n.userId||"",sessionId:n.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return b({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function Lr(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!De[n.mimeType])return;let t=e(n.name),o=De[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return"\n".concat(br,"\n\n# Load the dataframe.\n").concat(t," = ").concat(o,"\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(t,")\n")}var to=new Tt;import{cloneDeep as _r}from"lodash-es";function bt(n,e,t){var s,a,c;let o=[];for(let l of n)!((s=l.content)!=null&&s.role)||((c=(a=l.content.parts)==null?void 0:a[0])==null?void 0:c.text)===""||t&&l.branch&&!t.startsWith(l.branch)||kr(l)||Pr(l)||o.push(ro(e,l)?Or(l):l);let r=Br(o);r=Mr(r);let i=[];for(let l of r){let u=_r(l.content);Sn(u),i.push(u)}return i}function oo(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||ro(e,r))return bt(n.slice(o),e,t)}return[]}function kr(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===Pe||((o=r.functionResponse)==null?void 0:o.name)===Pe)return!0;return!1}function Pr(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===ue||((o=r.functionResponse)==null?void 0:o.name)===ue)return!0;return!1}function ro(n,e){return!!n&&e.author!==n&&e.author!=="user"}function Or(n){var t,o,r,i,s,a;if(!((o=(t=n.content)==null?void 0:t.parts)!=null&&o.length))return n;let e={role:"user",parts:[{text:"For context:"}]};for(let c of n.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:"[".concat(n.author,"] said: ").concat(c.text)});else if(c.functionCall){let l=no(c.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(n.author,"] called tool `").concat(c.functionCall.name,"` with parameters: ").concat(l)})}else if(c.functionResponse){let l=no(c.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(n.author,"] tool `").concat(c.functionResponse.name,"` returned result: ").concat(l)})}else(a=e.parts)==null||a.push(c);return b({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function io(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=b(n[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let o={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(o[s.functionResponse.id]=i)}for(let i of n.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in o?t[o[a]]=s:(t.push(s),o[a]=t.length-1)}else t.push(s)}return e}function Br(n){if(n.length===0)return n;let e=n[n.length-1],t=B(e);if(!(t!=null&&t.length))return n;let o=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=n.at(-2);if(r){let c=w(r);if(c){for(let l of c)if(l.id&&o.has(l.id))return n}}let i=-1;for(let c=n.length-2;c>=0;c--){let l=n[c],u=w(l);if(u!=null&&u.length){for(let p of u)if(p.id&&o.has(p.id)){i=c;let m=new Set(u.map(C=>C.id).filter(C=>!!C));if(!Array.from(o).every(C=>m.has(C)))throw new Error("Last response event should only contain the responses for the function calls in the same function call event. Function"+" call ids found : ".concat(Array.from(m).join(", "),", function response")+" ids provided: ".concat(Array.from(o).join(", ")));o=m;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(o).join(", ")));let s=[];for(let c=i+1;c<n.length-1;c++){let l=n[c],u=B(l);u&&u.some(p=>p.id&&o.has(p.id))&&s.push(l)}s.push(n[n.length-1]);let a=n.slice(0,i+1);return a.push(io(s)),a}function Mr(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=B(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,o)}let t=[];for(let o of n){if(B(o).length>0)continue;let r=w(o);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(o),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(n[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>n[c]);t.push(io(a))}}else t.push(o)}return t}function no(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch(e){return String(n)}}var Rt=class{runAsync(e,t){return d(this,null,function*(){let o=e.agent;!o||!E(o)||(o.includeContents==="default"?t.contents=bt(e.session.events,o.name,e.branch):t.contents=oo(e.session.events,o.name,e.branch))})}},so=new Rt;var It=class extends P{runAsync(e,t){return d(this,null,function*(){let o=e.agent,r=['You are an agent. Your internal name is "'.concat(o.name,'".')];o.description&&r.push('The description about you is "'.concat(o.description,'"')),ee(t,r)})}},ao=new It;async function wt(n,e){let t=e.invocationContext;async function o(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let p=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let m=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:p});if(!m)throw new Error("Artifact ".concat(p," not found."));return String(m)}if(!Dr(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(u)return"";throw new Error("Context variable not found: `".concat(l,"`."))}let r=/\{+[^{}]*}+/g,i=[],s=0,a=n.matchAll(r);for(let c of a){i.push(n.slice(s,c.index));let l=await o(c);i.push(l),s=c.index+c[0].length}return i.push(n.slice(s)),i.join("")}var Nr=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function co(n){return n===""||n===void 0?!1:Nr.test(n)}var Fr=[S.APP_PREFIX,S.USER_PREFIX,S.TEMP_PREFIX];function Dr(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?co(n):Fr.includes(e[0]+":")?co(e[1]):!1}var Lt=class extends P{runAsync(e,t){return d(this,null,function*(){let o=e.agent;if(!E(o)||!E(o.rootAgent))return;let r=o.rootAgent;if(E(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new f(r.canonicalGlobalInstruction(new _(e))),a=i;s&&(a=yield new f(wt(i,new _(e)))),ee(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=yield new f(o.canonicalInstruction(new _(e))),a=i;s&&(a=yield new f(wt(i,new _(e)))),ee(t,[a])}})}},lo=new Lt;var _t=class extends P{runAsync(e){return d(this,null,function*(){let t=e.agent;if(!E(t))return;let o=e.session.events;if(!o||o.length===0)return;let r={},i=-1;for(let s=o.length-1;s>=0;s--){let a=o[s];if(a.author!=="user")continue;let c=B(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==ue)continue;l=!0;let p=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?p=JSON.parse(u.response.response):u.response&&(p=new W({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&p&&(r[u.id]=p)}if(l){i=s;break}}if(Object.keys(r).length!==0)for(let s=i-1;s>=0;s--){let a=o[s],c=w(a);if(!c)continue;let l={},u={};for(let C of c){if(!C.id||!(C.id in r))continue;let A=C.args;if(!A||!("originalFunctionCall"in A))continue;let g=A.originalFunctionCall;g.id&&(l[g.id]=r[C.id],u[g.id]=g)}if(Object.keys(l).length===0)continue;for(let C=o.length-1;C>i;C--){let A=o[C],g=B(A);if(g){for(let x of g)x.id&&x.id in l&&(delete l[x.id],delete u[x.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let p=yield new f(t.canonicalTools(new _(e))),m=Object.fromEntries(p.map(C=>[C.name,C])),v=yield new f(Oe({invocationContext:e,functionCalls:Object.values(u),toolsDict:m,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l}));v&&(yield v);return}})}},uo=new _t;var kt=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(kt||{});function fo(n={}){return y({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Gr(n.maxLlmCalls||500),pauseOnToolCalls:!1},n)}function Gr(n){if(n>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(Number.MAX_SAFE_INTEGER,"."));return n<=0&&h.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),n}var po="adk_agent_name";async function mo(n,e){return ut(n)?[n]:await n.getTools(e)}var Pt=Symbol.for("google.adk.llmAgent");function E(n){return typeof n=="object"&&n!==null&&Pt in n&&n[Pt]===!0}var go,ho,Ot=class n extends(ho=D,go=Pt,ho){constructor(t){var r,i,s,a,c,l,u,p,m;super(t);this[go]=!0;if(this.model=t.model,this.instruction=(r=t.instruction)!=null?r:"",this.globalInstruction=(i=t.globalInstruction)!=null?i:"",this.tools=(s=t.tools)!=null?s:[],this.generateContentConfig=t.generateContentConfig,this.disallowTransferToParent=(a=t.disallowTransferToParent)!=null?a:!1,this.disallowTransferToPeers=(c=t.disallowTransferToPeers)!=null?c:!1,this.includeContents=(l=t.includeContents)!=null?l:"default",this.inputSchema=X(t.inputSchema)?de(t.inputSchema):t.inputSchema,this.outputSchema=X(t.outputSchema)?de(t.outputSchema):t.outputSchema,this.outputKey=t.outputKey,this.beforeModelCallback=t.beforeModelCallback,this.afterModelCallback=t.afterModelCallback,this.beforeToolCallback=t.beforeToolCallback,this.afterToolCallback=t.afterToolCallback,this.codeExecutor=t.codeExecutor,this.requestProcessors=(u=t.requestProcessors)!=null?u:[$n,ao,lo,uo,so,to],this.responseProcessors=(p=t.responseProcessors)!=null?p:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((m=this.subAgents)!=null&&m.length)||this.requestProcessors.push(Un),t.generateContentConfig){if(t.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(t.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(t.generateContentConfig.responseSchema)throw new Error("Response schema must be set via LlmAgent.output_schema.")}else this.generateContentConfig={};this.outputSchema&&(!this.disallowTransferToParent||!this.disallowTransferToPeers)&&(h.warn("Invalid config for agent ".concat(this.name,": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0)}get canonicalModel(){if(it(this.model))return this.model;if(typeof this.model=="string"&&this.model)return J.newLlm(this.model);let t=this.parentAgent;for(;t;){if(E(t))return t.canonicalModel;t=t.parentAgent}throw new Error("No model found for ".concat(this.name,"."))}async canonicalInstruction(t){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(t),requireStateInjection:!1}}async canonicalGlobalInstruction(t){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(t),requireStateInjection:!1}}async canonicalTools(t){let o=[];for(let r of this.tools){let i=await mo(r,t);o.push(...i)}return o}static normalizeCallbackArray(t){return t?Array.isArray(t)?t:[t]:[]}get canonicalBeforeModelCallbacks(){return n.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return n.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return n.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return n.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(t){var i,s;if(t.author!==this.name){h.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(t.author));return}if(!this.outputKey){h.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!K(t)){h.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((s=(i=t.content)==null?void 0:i.parts)!=null&&s.length)){h.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let o=t.content.parts.map(a=>a.text?a.text:"").join(""),r=o;if(this.outputSchema){if(!o.trim())return;try{r=JSON.parse(o)}catch(a){h.error("Error parsing output for agent ".concat(this.name),a)}}t.actions.stateDelta[this.outputKey]=r}runAsyncImpl(t){return d(this,null,function*(){for(;;){let a;try{for(var o=T(this.runOneStepAsync(t)),r,i,s;r=!(i=yield new f(o.next())).done;r=!1){let c=i.value;a=c,this.maybeSaveOutputToState(c),yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new f(i.call(o)))}finally{if(s)throw s[0]}}if(!a||K(a))break;if(a.partial){h.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(t){return d(this,null,function*(){try{for(var o=T(this.runLiveFlow(t)),r,i,s;r=!(i=yield new f(o.next())).done;r=!1){let a=i.value;this.maybeSaveOutputToState(a),yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new f(i.call(o)))}finally{if(s)throw s[0]}}t.endInvocation})}runLiveFlow(t){return d(this,null,function*(){throw yield new f(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(t){return d(this,null,function*(){let o={contents:[],toolsDict:{},liveConnectConfig:{}};for(let p of this.requestProcessors)try{for(var a=T(p.runAsync(t,o)),c,l,u;c=!(l=yield new f(a.next())).done;c=!1){let m=l.value;yield m}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new f(l.call(a)))}finally{if(u)throw u[0]}}for(let p of this.tools){let m=new k({invocationContext:t}),v=yield new f(mo(p,new _(t)));for(let C of v)yield new f(C.processLlmRequest({toolContext:m,llmRequest:o}))}if(t.endInvocation)return;let r=b({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=$.startSpan("call_llm"),s=Ur.setSpan(qr.active(),i);yield*N(Q(s,this,function(){return d(this,null,function*(){let p=function(){return d(this,null,function*(){try{for(var g=T(this.callLlmAsync(t,o,r)),x,I,O;x=!(I=yield new f(g.next())).done;x=!1){let L=I.value;try{for(var m=T(this.postprocess(t,o,L,r)),v,C,A;v=!(C=yield new f(m.next())).done;v=!1){let R=C.value;r.id=Ke(),r.timestamp=new Date().getTime(),yield R}}catch(C){A=[C]}finally{try{v&&(C=m.return)&&(yield new f(C.call(m)))}finally{if(A)throw A[0]}}}}catch(I){O=[I]}finally{try{x&&(I=g.return)&&(yield new f(I.call(g)))}finally{if(O)throw O[0]}}})};yield*N(this.runAndHandleError(p.call(this),t,o,r))})})),i.end()})}postprocess(t,o,r,i){return d(this,null,function*(){var A,g;for(let R of this.responseProcessors)try{for(var p=T(R.runAsync(t,r)),m,v,C;m=!(v=yield new f(p.next())).done;m=!1){let Y=v.value;yield Y}}catch(v){C=[v]}finally{try{m&&(v=p.return)&&(yield new f(v.call(p)))}finally{if(C)throw C[0]}}if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=b(y(y({},i),r));if(s.content){let R=w(s);R!=null&&R.length&&(Tn(s),s.longRunningToolIds=Array.from(bn(R,o.toolsDict)))}if(yield s,!((A=w(s))!=null&&A.length))return;if((g=t.runConfig)!=null&&g.pauseOnToolCalls){t.endInvocation=!0;return}let a=yield new f(Rn({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!a)return;let c=tt(t,a);c&&(yield c);let l=nt({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});if(l){yield l,t.endInvocation=!0;return}yield a;let u=a.actions.transferToAgent;if(u){let R=this.getAgentByName(t,u);try{for(var x=T(R.runAsync(t)),I,O,L;I=!(O=yield new f(x.next())).done;I=!1){let Y=O.value;yield Y}}catch(O){L=[O]}finally{try{I&&(O=x.return)&&(yield new f(O.call(x)))}finally{if(L)throw L[0]}}}})}getAgentByName(t,o){let i=t.agent.rootAgent.findAgent(o);if(!i)throw new Error("Agent ".concat(o," not found in the agent tree."));return i}callLlmAsync(t,o,r){return d(this,null,function*(){var a,c,l,u,p;let i=yield new f(this.handleBeforeModelCallback(t,o,r));if(i){yield i;return}(a=o.config)!=null||(o.config={}),(l=(c=o.config).labels)!=null||(c.labels={}),o.config.labels[po]||(o.config.labels[po]=this.name);let s=this.canonicalModel;if((u=t.runConfig)!=null&&u.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let g=s.generateContentAsync(o,((p=t.runConfig)==null?void 0:p.streamingMode)==="sse");try{for(var m=T(g),v,C,A;v=!(C=yield new f(m.next())).done;v=!1){let x=C.value;dn({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:x});let I=yield new f(this.handleAfterModelCallback(t,x,r));yield I!=null?I:x}}catch(C){A=[C]}finally{try{v&&(C=m.return)&&(yield new f(C.call(m)))}finally{if(A)throw A[0]}}}})}async handleBeforeModelCallback(t,o,r){let i=new k({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:o});if(s)return s;for(let a of this.canonicalBeforeModelCallbacks){let c=await a({context:i,request:o});if(c)return c}}async handleAfterModelCallback(t,o,r){let i=new k({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:o});if(s)return s;for(let a of this.canonicalAfterModelCallbacks){let c=await a({context:i,response:o});if(c)return c}}runAndHandleError(t,o,r,i){return d(this,null,function*(){try{try{for(var s=T(t),a,c,l;a=!(c=yield new f(s.next())).done;a=!1){let u=c.value;yield u}}catch(c){l=[c]}finally{try{a&&(c=s.return)&&(yield new f(c.call(s)))}finally{if(l)throw l[0]}}}catch(u){let p=new k({invocationContext:o,eventActions:i.actions});if(u instanceof Error){let m=yield new f(o.pluginManager.runOnModelErrorCallback({callbackContext:p,llmRequest:r,error:u}));if(m)yield m;else{let v="UNKNOWN_ERROR",C=u.message;try{let A=JSON.parse(u.message);A!=null&&A.error&&(v=String(A.error.code||"UNKNOWN_ERROR"),C=A.error.message||C)}catch(A){}i.actions?yield b({invocationId:o.invocationId,author:this.name,errorCode:v,errorMessage:C}):yield{errorCode:v,errorMessage:C}}}else throw h.error("Unknown error during response generation",u),u}})}};var Bt=Symbol.for("google.adk.loopAgent");function $r(n){return typeof n=="object"&&n!==null&&Bt in n&&n[Bt]===!0}var Co,vo,Mt=class extends(vo=D,Co=Bt,vo){constructor(t){var o;super(t);this[Co]=!0;this.maxIterations=(o=t.maxIterations)!=null?o:Number.MAX_SAFE_INTEGER}runAsyncImpl(t){return d(this,null,function*(){let o=0;for(;o<this.maxIterations;){for(let c of this.subAgents){let l=!1;try{for(var r=T(c.runAsync(t)),i,s,a;i=!(s=yield new f(r.next())).done;i=!1){let u=s.value;yield u,u.actions.escalate&&(l=!0)}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new f(s.call(r)))}finally{if(a)throw a[0]}}if(l)return}o++}})}runLiveImpl(t){return d(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var Nt=Symbol.for("google.adk.parallelAgent");function Vr(n){return typeof n=="object"&&n!==null&&Nt in n&&n[Nt]===!0}var Ao,xo,Ft=class extends(xo=D,Ao=Nt,xo){constructor(){super(...arguments);this[Ao]=!0}runAsyncImpl(t){return d(this,null,function*(){let o=this.subAgents.map(c=>c.runAsync(zr(this,c,t)));try{for(var r=T(jr(o)),i,s,a;i=!(s=yield new f(r.next())).done;i=!1){let c=s.value;yield c}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new f(s.call(r)))}finally{if(a)throw a[0]}}})}runLiveImpl(t){return d(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function zr(n,e,t){let o=new V(t),r="".concat(n.name,".").concat(e.name);return o.branch=o.branch?"".concat(o.branch,".").concat(r):r,o}function jr(n){return d(this,null,function*(){let e=new Map;for(let[t,o]of n.entries()){let r=o.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:o}=yield new f(Promise.race(e.values()));if(t.done){e.delete(o);continue}yield t.value;let r=n[o].next().then(i=>({result:i,index:o}));e.set(o,r)}})}var Dt="task_completed",Gt=Symbol.for("google.adk.sequentialAgent");function Kr(n){return typeof n=="object"&&n!==null&&Gt in n&&n[Gt]===!0}var Eo,yo,qt=class extends(yo=D,Eo=Gt,yo){constructor(){super(...arguments);this[Eo]=!0}runAsyncImpl(t){return d(this,null,function*(){for(let a of this.subAgents)try{for(var o=T(a.runAsync(t)),r,i,s;r=!(i=yield new f(o.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new f(i.call(o)))}finally{if(s)throw s[0]}}})}runLiveImpl(t){return d(this,null,function*(){for(let a of this.subAgents)E(a)&&((yield new f(a.canonicalTools(new _(t)))).some(u=>u.name===Dt)||(a.tools.push(new z({name:Dt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),a.instruction+="If you finished the user's request according to its description, call the ".concat(Dt," function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.")));for(let a of this.subAgents)try{for(var o=T(a.runLive(t)),r,i,s;r=!(i=yield new f(o.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new f(i.call(o)))}finally{if(s)throw s[0]}}})}};var be=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:o,filename:r,artifact:i,customMetadata:s}){if(!i.inlineData&&!i.text)return Promise.reject(new Error("Artifact must have either inlineData or text content."));let a=me(e,t,o,r);this.artifacts[a]||(this.artifacts[a]=[]);let c=this.artifacts[a].length,l={version:c,customMetadata:s};return this.artifacts[a].push({part:i,metadata:l}),Promise.resolve(c)}loadArtifact({appName:e,userId:t,sessionId:o,filename:r,version:i}){let s=me(e,t,o,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i].part)):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:o}){let r="".concat(e,"/").concat(t,"/").concat(o,"/"),i="".concat(e,"/").concat(t,"/user/"),s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:o,filename:r}){let i=me(e,t,o,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:o,filename:r}){let i=me(e,t,o,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let a=[];for(let c=0;c<s.length;c++)a.push(c);return Promise.resolve(a)}listArtifactVersions({appName:e,userId:t,sessionId:o,filename:r}){let i=me(e,t,o,r),s=this.artifacts[i];return s?Promise.resolve(s.map(a=>a.metadata)):Promise.resolve([])}getArtifactVersion({appName:e,userId:t,sessionId:o,filename:r,version:i}){let s=me(e,t,o,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),a[i]?Promise.resolve(a[i].metadata):Promise.resolve(void 0)):Promise.resolve(void 0)}};function me(n,e,t,o){return Hr(o)?"".concat(n,"/").concat(e,"/user/").concat(o):"".concat(n,"/").concat(e,"/").concat(t,"/").concat(o)}function Hr(n){return n.startsWith("user:")}var To=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(To||{});import{isEmpty as Re}from"lodash-es";var So=(u=>(u.THOUGHT="thought",u.CONTENT="content",u.TOOL_CALL="tool_call",u.TOOL_RESULT="tool_result",u.CALL_CODE="call_code",u.CODE_RESULT="code_result",u.ERROR="error",u.ACTIVITY="activity",u.TOOL_CONFIRMATION="tool_confirmation",u.FINISHED="finished",u))(So||{});function Zr(n){var t,o;let e=[];if(n.errorCode)return e.push({type:"error",error:new Error(n.errorMessage||n.errorCode)}),e;for(let r of(o=(t=n.content)==null?void 0:t.parts)!=null?o:[])r.functionCall&&!Re(r.functionCall)?e.push({type:"tool_call",call:r.functionCall}):r.functionResponse&&!Re(r.functionResponse)?e.push({type:"tool_result",result:r.functionResponse}):r.executableCode&&!Re(r.executableCode)?e.push({type:"call_code",code:r.executableCode}):r.codeExecutionResult&&!Re(r.codeExecutionResult)?e.push({type:"code_result",result:r.codeExecutionResult}):r.text&&(r.thought?e.push({type:"thought",content:r.text}):e.push({type:"content",content:r.text}));return n.actions.requestedToolConfirmations&&!Re(n.actions.requestedToolConfirmations)&&e.push({type:"tool_confirmation",confirmations:n.actions.requestedToolConfirmations}),K(n)&&e.push({type:"finished",output:void 0}),e}var Ut=Symbol.for("google.adk.baseExampleProvider");function Yr(n){return typeof n=="object"&&n!==null&&Ut in n&&n[Ut]===!0}var bo;bo=Ut;var $t=class{constructor(){this[bo]=!0}};var re=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Ro(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(o=>{var r,i,s;return((s=(i=(r=o.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=Ro(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let o=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(m=>m.text).filter(m=>!!m).join(" "),u=Qr(l);if(!u.size)continue;o.some(m=>u.has(m))&&r.memories.push({content:c.content,author:c.author,timestamp:Wr(c.timestamp)})}return r}};function Ro(n,e){return"".concat(n,"/").concat(e)}function Qr(n){return new Set([...n.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Wr(n){return new Date(n).toISOString()}var ie=class{constructor(e){this.name=e}async onUserMessageCallback(e){}async beforeRunCallback(e){}async onEventCallback(e){}async afterRunCallback(e){}async beforeAgentCallback(e){}async afterAgentCallback(e){}async beforeModelCallback(e){}async afterModelCallback(e){}async onModelErrorCallback(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};var Vt=class extends ie{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var o;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Session ID: ".concat(e.session.id)),this.log(" User ID: ".concat(e.userId)),this.log(" App Name: ".concat(e.appName)),this.log(" Root Agent: ".concat((o=e.agent.name)!=null?o:"Unknown")),this.log(" User Content: ".concat(this.formatContent(t))),e.branch&&this.log(" Branch: ".concat(e.branch))}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Starting Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async onEventCallback({event:e}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(e.id)),this.log(" Author: ".concat(e.author)),this.log(" Content: ".concat(this.formatContent(e.content))),this.log(" Final Response: ".concat(K(e)));let t=w(e);if(t.length>0){let r=t.map(i=>i.name);this.log(" Function Calls: ".concat(r))}let o=B(e);if(o.length>0){let r=o.map(i=>i.name);this.log(" Function Responses: ".concat(r))}e.longRunningToolIds&&e.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...e.longRunningToolIds]))}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Final Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async beforeAgentCallback({callbackContext:e}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(e.agentName)),this.log(" Invocation ID: ".concat(e.invocationId)),e.invocationContext.branch&&this.log(" Branch: ".concat(e.invocationContext.branch))}async afterAgentCallback({callbackContext:e}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(e.agentName)),this.log(" Invocation ID: ".concat(e.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var o;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((o=t.model)!=null?o:"default")),this.log(" Agent: ".concat(e.agentName)),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(" System Instruction: '".concat(r,"'"))}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(" Available Tools: ".concat(r))}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(" Agent: ".concat(e.agentName)),t.errorCode?(this.log(" \u274C ERROR - Code: ".concat(t.errorCode)),this.log(" Error Message: ".concat(t.errorMessage))):(this.log(" Content: ".concat(this.formatContent(t.content))),t.partial&&this.log(" Partial: ".concat(t.partial)),t.turnComplete!==void 0&&this.log(" Turn Complete: ".concat(t.turnComplete))),t.usageMetadata&&this.log(" Token Usage - Input: ".concat(t.usageMetadata.promptTokenCount,", Output: ").concat(t.usageMetadata.candidatesTokenCount))}async beforeToolCallback({tool:e,toolArgs:t,toolContext:o}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(o.agentName)),this.log(" Function Call ID: ".concat(o.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolContext:t,result:o}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(t.agentName)),this.log(" Function Call ID: ".concat(t.functionCallId)),this.log(" Result: ".concat(this.formatArgs(o)))}async onModelErrorCallback({callbackContext:e,error:t}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(t))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(o.agentName)),this.log(" Function Call ID: ".concat(o.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");h.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let o=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),o.push("text: '".concat(i,"'"))}else r.functionCall?o.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?o.push("function_response: ".concat(r.functionResponse.name)):r.codeExecutionResult?o.push("code_execution_result"):o.push("other_part");return o.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let o=JSON.stringify(e);return o.length>t&&(o=o.substring(0,t)+"...}"),o}};var Ie=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error("Plugin '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),h.info("Plugin '".concat(e.name,"' registered."))}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,o){for(let r of e)try{let i=await t(r);if(i!==void 0)return h.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(o,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(o,"' callback: ").concat(i);throw h.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,o=>o.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,o=>o.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:o}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:o}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:o}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:o}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,o=>o.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,o=>o.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}),"onToolErrorCallback")}};var wo="adk_request_confirmation",zt="orcas_tool_call_security_check_states",Io="This tool call needs external confirmation before completion.",Lo=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(Lo||{}),Ge=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},jt=class extends ie{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Ge}async beforeToolCallback({tool:e,toolArgs:t,toolContext:o}){let r=this.getToolCallCheckState(o);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o});if(r==="CONFIRM"){if(!o.toolConfirmation)return{partial:Io};if(this.setToolCallCheckState(o,o.toolConfirmation),!o.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};o.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(zt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(zt))!=null?i:{};r[o]=t,e.state.set(zt,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(o,r.outcome),r.outcome){case"DENY":return{error:"This tool call is rejected by policy engine. Reason: ".concat(r.reason)};case"CONFIRM":return o.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:Io};case"ALLOW":return;default:return}}};function Jr(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===wo&&e.push(t.functionCall);return e}import{cloneDeep as _o}from"lodash-es";import{cloneDeep as Xr}from"lodash-es";var we=class{async getOrCreateSession(e){if(!e.sessionId)return this.createSession(e);let t=await this.getSession({appName:e.appName,userId:e.userId,sessionId:e.sessionId});return t||this.createSession(e)}async appendEvent({session:e,event:t}){return t.partial||(t=ei(t),this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[o,r]of Object.entries(t.actions.stateDelta))o.startsWith(S.TEMP_PREFIX)||(e.state[o]=r)}};function ei(n){if(!n.actions||!n.actions.stateDelta)return n;let e=n.actions.stateDelta,t={};for(let[o,r]of Object.entries(e))o.startsWith(S.TEMP_PREFIX)||(t[o]=r);return n.actions.stateDelta=t,n}function Kt(n={},e={},t={}){let o=Xr(t);for(let[r,i]of Object.entries(n))o[S.APP_PREFIX+r]=i;for(let[r,i]of Object.entries(e))o[S.USER_PREFIX+r]=i;return o}function qe(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}var se=class extends we{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}async createSession({appName:t,userId:o,state:r,sessionId:i}){var c;let s=qe({id:i||le(),appName:t,userId:o,state:r,events:[],lastUpdateTime:Date.now()});this.sessions[t]||(this.sessions[t]={}),this.sessions[t][o]||(this.sessions[t][o]={}),this.sessions[t][o][s.id]=s;let a=_o(s);return a.state=Kt(this.appState[t],(c=this.userState[t])==null?void 0:c[o],a.state),a}async getSession({appName:t,userId:o,sessionId:r,config:i}){var c;if(!this.sessions[t]||!this.sessions[t][o]||!this.sessions[t][o][r])return Promise.resolve(void 0);let s=this.sessions[t][o][r],a=_o(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let l=a.events.length-1;for(;l>=0&&!(a.events[l].timestamp<i.afterTimestamp);)l--;l>=0&&(a.events=a.events.slice(l+1))}return a.state=Kt(this.appState[t],(c=this.userState[t])==null?void 0:c[o],a.state),a}listSessions({appName:t,userId:o}){if(!this.sessions[t]||!this.sessions[t][o])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][o]))r.push(qe({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:o,sessionId:r}){await this.getSession({appName:t,userId:o,sessionId:r})&&delete this.sessions[t][o][r]}async appendEvent({session:t,event:o}){await super.appendEvent({session:t,event:o}),t.lastUpdateTime=o.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{h.warn("Failed to append event to session ".concat(s,": ").concat(l))};if(!this.sessions[r])return a("appName ".concat(r," not in sessions")),o;if(!this.sessions[r][i])return a("userId ".concat(i," not in sessions[appName]")),o;if(!this.sessions[r][i][s])return a("sessionId ".concat(s," not in sessions[appName][userId]")),o;if(o.actions&&o.actions.stateDelta)for(let l of Object.keys(o.actions.stateDelta))l.startsWith(S.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(S.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(S.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(S.USER_PREFIX,"")]=o.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:o}),c.lastUpdateTime=o.timestamp,o}};import{createPartFromText as ti}from"@google/genai";import{context as ni,trace as oi}from"@opentelemetry/api";var ae=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new Ie((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runEphemeral(e){return d(this,null,function*(){let o=(yield new f(this.sessionService.createSession({appName:this.appName,userId:e.userId}))).id;try{yield*N(this.runAsync({userId:e.userId,sessionId:o,newMessage:e.newMessage,stateDelta:e.stateDelta,runConfig:e.runConfig}))}finally{yield new f(this.sessionService.deleteSession({appName:this.appName,userId:e.userId,sessionId:o}))}})}runAsync(e){return d(this,null,function*(){let{userId:t,sessionId:o,stateDelta:r}=e,i=fo(e.runConfig),s=e.newMessage,a=$.startSpan("invocation"),c=oi.setSpan(ni.active(),a);try{yield*N(Q(c,this,function(){return d(this,null,function*(){var m;let l=yield new f(this.sessionService.getSession({appName:this.appName,userId:t,sessionId:o}));if(!l)throw this.appName?new Error("Session not found: ".concat(o)):new Error("Session lookup failed: appName must be provided in runner constructor");if(i.supportCfc&&E(this.agent)){let x=this.agent.canonicalModel.model;if(!Ee(x))throw new Error("CFC is not supported for model: ".concat(x," in agent: ").concat(this.agent.name));Te(this.agent.codeExecutor)||(this.agent.codeExecutor=new ye)}let u=new V({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:hn(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager}),p=yield new f(this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:u}));if(p&&(s=p),s){if(!((m=s.parts)!=null&&m.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new f(this.saveArtifacts(u.invocationId,l.userId,l.id,s))),yield new f(this.sessionService.appendEvent({session:l,event:b({invocationId:u.invocationId,author:"user",actions:r?U({stateDelta:r}):void 0,content:s})}))}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let x=yield new f(this.pluginManager.runBeforeRunCallback({invocationContext:u}));if(x){let I=b({invocationId:u.invocationId,author:"model",content:x});yield new f(this.sessionService.appendEvent({session:l,event:I})),yield I}else{try{for(var v=T(u.agent.runAsync(u)),C,A,g;C=!(A=yield new f(v.next())).done;C=!1){let I=A.value;I.partial||(yield new f(this.sessionService.appendEvent({session:l,event:I})));let O=yield new f(this.pluginManager.runOnEventCallback({invocationContext:u,event:I}));O?yield O:yield I}}catch(A){g=[A]}finally{try{C&&(A=v.return)&&(yield new f(A.call(v)))}finally{if(g)throw g[0]}}yield new f(this.pluginManager.runAfterRunCallback({invocationContext:u}))}}})}))}finally{a.end()}})}async saveArtifacts(e,t,o,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c="artifact_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:o,filename:c,artifact:a}),r.parts[s]=ti("Uploaded file: ".concat(c,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let o=ri(e.events);if(o&&o.author)return t.findAgent(o.author)||t;for(let r=e.events.length-1;r>=0;r--){h.info("event:",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){h.warn("Event from an unknown agent: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!E(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function ri(n){var o,r,i,s;if(!n.length)return null;let t=(s=(i=(r=(o=n[n.length-1].content)==null?void 0:o.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=n.length-2;a>=0;a--){let c=n[a],l=w(c);if(l){for(let u of l)if(u.id===t)return c}}return null}var Ht=class extends ae{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new be,sessionService:new se,memoryService:new re})}};import{Type as $e}from"@google/genai";var Ue=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(){return this.toolContext.listArtifacts()}async deleteArtifact(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.deleteArtifact(e)}async listVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listVersions(e)}listArtifactVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listArtifactVersions(e)}getArtifactVersion(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.getArtifactVersion(e)}};var Zt=Symbol.for("google.adk.agentTool");function ii(n){return typeof n=="object"&&n!==null&&Zt in n&&n[Zt]===!0}var ko,Po,Yt=class extends(Po=q,ko=Zt,Po){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[ko]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(E(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:$e.OBJECT,properties:{request:{type:$e.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let o=E(this.agent)&&this.agent.outputSchema;t.response=o?{type:$e.OBJECT}:{type:$e.STRING}}return t}async runAsync({args:t,toolContext:o}){var A,g;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:E(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new ae({appName:this.agent.name,agent:this.agent,artifactService:new Ue(o),sessionService:new se,memoryService:new re,credentialService:o.invocationContext.credentialService}),a=await s.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:o.state.toRecord()}),c;try{for(var p=T(s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i})),m,v,C;m=!(v=await p.next()).done;m=!1){let x=v.value;x.actions.stateDelta&&o.state.update(x.actions.stateDelta),c=x}}catch(v){C=[v]}finally{try{m&&(v=p.return)&&await v.call(p)}finally{if(C)throw C[0]}}if(!((g=(A=c==null?void 0:c.content)==null?void 0:A.parts)!=null&&g.length))return"";let l=E(this.agent)&&this.agent.outputSchema,u=c.content.parts.map(x=>x.text).filter(x=>x).join("\n");return l?JSON.parse(u):u}};var Qt=Symbol.for("google.adk.baseToolset");function si(n){return typeof n=="object"&&n!==null&&Qt in n&&n[Qt]===!0}var Oo;Oo=Qt;var Wt=class{constructor(e,t){this.toolFilter=e;this.prefix=t;this[Oo]=!0}isToolSelected(e,t){return this.toolFilter?typeof this.toolFilter=="function"?this.toolFilter(e,t):Array.isArray(this.toolFilter)?this.toolFilter.includes(e.name):!1:!0}async processLlmRequest(e,t){}};var Ve=class extends q{constructor(){super({name:"exit_loop",description:"Exits the loop.\n\nCall this function only when you are instructed to do so."})}_getDeclaration(){return{name:this.name,description:this.description}}async runAsync({toolContext:e}){return e.actions.escalate=!0,e.actions.skipSummarization=!0,""}},ai=new Ve;var ze=class extends q{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(){return Promise.resolve()}async processLlmRequest({llmRequest:e}){if(e.model){if(e.config=e.config||{},e.config.tools=e.config.tools||[],jn(e.model)){if(e.config.tools.length>0)throw new Error("Google search tool can not be used with other tools in Gemini 1.x.");e.config.tools.push({googleSearchRetrieval:{}});return}if(zn(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(e.model))}}},ci=new ze;var Bo="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",Jt=class extends z{constructor(e){super(j(y({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Bo:e.description=Bo.trimStart(),e}};export{je as ActiveStreamingTool,Yt as AgentTool,pe as ApigeeLlm,To as AuthCredentialTypes,D as BaseAgent,xe as BaseCodeExecutor,$t as BaseExampleProvider,fe as BaseLlm,P as BaseLlmRequestProcessor,dt as BaseLlmResponseProcessor,ie as BasePlugin,we as BaseSessionService,q as BaseTool,Wt as BaseToolset,ye as BuiltInCodeExecutor,k as Context,ai as EXIT_LOOP,So as EventType,Ve as ExitLoopTool,z as FunctionTool,ci as GOOGLE_SEARCH,Z as Gemini,Be as GoogleLLMVariant,ze as GoogleSearchTool,be as InMemoryArtifactService,re as InMemoryMemoryService,Ge as InMemoryPolicyEngine,Ht as InMemoryRunner,se as InMemorySessionService,V as InvocationContext,J as LLMRegistry,ot as LiveRequestQueue,Ot as LlmAgent,En as LogLevel,Vt as LoggingPlugin,Jt as LongRunningFunctionTool,Mt as LoopAgent,Ft as ParallelAgent,Ie as PluginManager,Lo as PolicyOutcome,wo as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,_ as ReadonlyContext,ae as Runner,jt as SecurityPlugin,qt as SequentialAgent,S as State,kt as StreamingMode,W as ToolConfirmation,b as createEvent,U as createEventActions,qe as createSession,Xo as functionsExportedForTestingOnly,Ne as geminiInitParams,Jr as getAskUserConfirmationFunctionCalls,w as getFunctionCalls,B as getFunctionResponses,Qo as getLogger,sn as hasTrailingCodeExecutionResult,ii as isAgentTool,jo as isBaseAgent,Yr as isBaseExampleProvider,it as isBaseLlm,ut as isBaseTool,si as isBaseToolset,K as isFinalResponse,Ar as isFunctionTool,Ee as isGemini2OrAbove,E as isLlmAgent,$r as isLoopAgent,Vr as isParallelAgent,Kr as isSequentialAgent,Kt as mergeStates,Wo as setLogLevel,Yo as setLogger,Go as stringifyContent,Zr as toStructuredEvents,ei as trimTempDeltaState,ge as version,de as zodObjectToSchema};
|
|
1
8
|
/**
|
|
2
9
|
* @license
|
|
3
10
|
* Copyright 2025 Google LLC
|
|
4
11
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
12
|
*/
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
export * from "./telemetry/google_cloud.js";
|
|
13
|
-
export * from "./telemetry/setup.js";
|
|
14
|
-
export * from "./tools/mcp/mcp_session_manager.js";
|
|
15
|
-
export * from "./tools/mcp/mcp_tool.js";
|
|
16
|
-
export * from "./tools/mcp/mcp_toolset.js";
|
|
17
|
-
export {
|
|
18
|
-
DatabaseSessionService,
|
|
19
|
-
FileArtifactService,
|
|
20
|
-
GcsArtifactService,
|
|
21
|
-
getArtifactServiceFromUri,
|
|
22
|
-
getSessionServiceFromUri
|
|
23
|
-
};
|
|
13
|
+
/**
|
|
14
|
+
* @license
|
|
15
|
+
* Copyright 2026 Google LLC
|
|
16
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17
|
+
*/
|
|
18
|
+
//# sourceMappingURL=index.js.map
|