google-agents-cli-extensions 1.14.2__py3-none-any.whl
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.
- core/claude/README.md +35 -0
- core/claude/template/.agents/skills/agents-cli-claude/SKILL.md +106 -0
- core/claude/template/.agents/skills/agents-cli-claude/references/claude.md +386 -0
- core/claude/template/.agents/skills/agents-cli-claude/references/migrate-claude-agent.md +318 -0
- core/claude/template/.agents/skills/agents-cli-claude/references/migrate-from-aws.md +132 -0
- core/claude/template/.dockerignore +28 -0
- core/claude/template/.env +18 -0
- core/claude/template/.env.example +17 -0
- core/claude/template/.template/templateconfig.yaml +31 -0
- core/claude/template/AGENTS.md +33 -0
- core/claude/template/Dockerfile +55 -0
- core/claude/template/agent_config/README.md +9 -0
- core/claude/template/agents-cli-extension.yaml +49 -0
- core/claude/template/app/__init__.py +15 -0
- core/claude/template/app/agent.py +49 -0
- core/claude/template/app/app_utils/a2a.py +245 -0
- core/claude/template/app/app_utils/bq_analytics/__init__.py +124 -0
- core/claude/template/app/app_utils/bq_analytics/recorder.py +593 -0
- core/claude/template/app/app_utils/bq_analytics/redaction.py +209 -0
- core/claude/template/app/app_utils/bq_analytics/schema.py +394 -0
- core/claude/template/app/app_utils/bq_analytics/tables.py +104 -0
- core/claude/template/app/app_utils/bq_analytics/uploader.py +188 -0
- core/claude/template/app/app_utils/claude.py +297 -0
- core/claude/template/app/app_utils/completions.py +225 -0
- core/claude/template/app/app_utils/conversation.py +29 -0
- core/claude/template/app/app_utils/memory_bank.py +308 -0
- core/claude/template/app/app_utils/project_settings.py +91 -0
- core/claude/template/app/app_utils/reasoning_engine.py +237 -0
- core/claude/template/app/app_utils/remote_agents.py +349 -0
- core/claude/template/app/app_utils/remote_auth.py +159 -0
- core/claude/template/app/app_utils/replies.py +143 -0
- core/claude/template/app/app_utils/session_store.py +174 -0
- core/claude/template/app/app_utils/settings.py +24 -0
- core/claude/template/app/app_utils/telemetry/__init__.py +114 -0
- core/claude/template/app/app_utils/telemetry/call_counts.py +44 -0
- core/claude/template/app/app_utils/telemetry/cli_relay.py +266 -0
- core/claude/template/app/app_utils/telemetry/config.py +133 -0
- core/claude/template/app/app_utils/telemetry/logs.py +175 -0
- core/claude/template/app/app_utils/telemetry/metrics.py +270 -0
- core/claude/template/app/app_utils/telemetry/request_flush.py +104 -0
- core/claude/template/app/app_utils/telemetry/subagent_spans.py +80 -0
- core/claude/template/app/app_utils/telemetry/traces.py +166 -0
- core/claude/template/app/app_utils/turn_events.py +463 -0
- core/claude/template/app/app_utils/turn_options.py +219 -0
- core/claude/template/app/app_utils/workspaces.py +65 -0
- core/claude/template/app/fast_api_app.py +71 -0
- core/claude/template/app/feature_tools.py +27 -0
- core/claude/template/pyproject.toml +100 -0
- core/claude/template/scripts/eval_generate.py +340 -0
- core/claude/template/scripts/publish.py +66 -0
- core/claude/template/scripts/run.py +85 -0
- core/claude/template/scripts/unsupported.py +48 -0
- core/claude/template/tests/eval/datasets/basic-dataset.json +31 -0
- core/claude/template/tests/eval/eval_config.yaml +17 -0
- core/claude/template/tests/eval/response_quality.py +60 -0
- core/claude/template/tests/integration/test_server_e2e.py +168 -0
- core/claude/template/tests/load_test/.results/.placeholder +0 -0
- core/claude/template/tests/load_test/README.md +24 -0
- core/claude/template/tests/load_test/load_test.py +118 -0
- core/claude/template/tests/unit/conftest.py +63 -0
- core/claude/template/tests/unit/helpers.py +32 -0
- core/claude/template/tests/unit/test_a2a.py +432 -0
- core/claude/template/tests/unit/test_bq_analytics.py +928 -0
- core/claude/template/tests/unit/test_bq_redaction.py +89 -0
- core/claude/template/tests/unit/test_claude.py +825 -0
- core/claude/template/tests/unit/test_completions.py +369 -0
- core/claude/template/tests/unit/test_fast_api_app.py +59 -0
- core/claude/template/tests/unit/test_feature_tools.py +55 -0
- core/claude/template/tests/unit/test_memory_bank.py +625 -0
- core/claude/template/tests/unit/test_reasoning_engine.py +295 -0
- core/claude/template/tests/unit/test_remote_agents.py +517 -0
- core/claude/template/tests/unit/test_telemetry.py +991 -0
- core/claude/template/tests/unit/test_turn_events.py +309 -0
- core/claude/template/tests/unit/test_turn_options.py +394 -0
- core/claude/template/uv.lock +3029 -0
- core/langchain/README.md +54 -0
- core/langchain/template/.agents/skills/agents-cli-langchain/SKILL.md +84 -0
- core/langchain/template/.agents/skills/agents-cli-langchain/references/langchain.md +120 -0
- core/langchain/template/.agents/skills/agents-cli-langchain/references/samples.md +42 -0
- core/langchain/template/.template/templateconfig.yaml +32 -0
- core/langchain/template/AGENTS.md +35 -0
- core/langchain/template/agents-cli-extension.yaml +54 -0
- core/langchain/template/app/__init__.py +19 -0
- core/langchain/template/app/agent.py +61 -0
- core/langchain/template/app/app_utils/a2a.py +176 -0
- core/langchain/template/app/app_utils/content.py +37 -0
- core/langchain/template/app/app_utils/telemetry.py +154 -0
- core/langchain/template/app/fast_api_app.py +68 -0
- core/langchain/template/langgraph.json +7 -0
- core/langchain/template/pyproject.toml +102 -0
- core/langchain/template/scripts/_content.py +40 -0
- core/langchain/template/scripts/eval_generate.py +202 -0
- core/langchain/template/scripts/publish.py +59 -0
- core/langchain/template/scripts/run.py +59 -0
- core/langchain/template/scripts/unsupported.py +48 -0
- core/langchain/template/tests/eval/datasets/basic-dataset.json +16 -0
- core/langchain/template/tests/eval/eval_config.yaml +32 -0
- core/langchain/template/tests/eval/response_quality.py +60 -0
- core/langchain/template/tests/integration/test_server_e2e.py +173 -0
- core/langchain/template/tests/load_test/.results/.placeholder +0 -0
- core/langchain/template/tests/load_test/README.md +20 -0
- core/langchain/template/tests/load_test/load_test.py +82 -0
- core/langchain/template/uv.lock +3820 -0
- google_agents_cli_extensions-1.14.2.dist-info/METADATA +133 -0
- google_agents_cli_extensions-1.14.2.dist-info/RECORD +107 -0
- google_agents_cli_extensions-1.14.2.dist-info/WHEEL +4 -0
- google_agents_cli_extensions-1.14.2.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Prompt-response logging through OpenTelemetry's completion hook.
|
|
16
|
+
|
|
17
|
+
Enabled by OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK. A call's logged inputs
|
|
18
|
+
cover only the current turn, not earlier ones.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import functools
|
|
24
|
+
import logging
|
|
25
|
+
import os
|
|
26
|
+
from collections.abc import Callable
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from claude_agent_sdk import (
|
|
30
|
+
ClaudeAgentOptions,
|
|
31
|
+
TextBlock,
|
|
32
|
+
ThinkingBlock,
|
|
33
|
+
ToolUseBlock,
|
|
34
|
+
)
|
|
35
|
+
from opentelemetry import trace
|
|
36
|
+
from opentelemetry._logs import LogRecord
|
|
37
|
+
from opentelemetry.util.genai.completion_hook import (
|
|
38
|
+
CompletionHook,
|
|
39
|
+
load_completion_hook,
|
|
40
|
+
)
|
|
41
|
+
from opentelemetry.util.genai.types import (
|
|
42
|
+
InputMessage,
|
|
43
|
+
MessagePart,
|
|
44
|
+
OutputMessage,
|
|
45
|
+
TextPart,
|
|
46
|
+
ToolCallRequestPart,
|
|
47
|
+
ToolCallResponsePart,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
from app.app_utils import telemetry
|
|
51
|
+
from app.app_utils.telemetry.subagent_spans import SubagentSpans
|
|
52
|
+
from app.app_utils.turn_events import (
|
|
53
|
+
Event,
|
|
54
|
+
ModelCallEnded,
|
|
55
|
+
SubagentPrompt,
|
|
56
|
+
ToolCallEnded,
|
|
57
|
+
system_prompt_text,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
EVENT_NAME = "gen_ai.client.inference.operation.details"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def start_turn(
|
|
64
|
+
prompt: str,
|
|
65
|
+
options: ClaudeAgentOptions,
|
|
66
|
+
session_id: str,
|
|
67
|
+
agent_name: Callable[[str | None], str],
|
|
68
|
+
subagent_spans: SubagentSpans,
|
|
69
|
+
) -> PromptLog | None:
|
|
70
|
+
"""A recorder for one turn's model calls, or None when logging is off."""
|
|
71
|
+
if not os.environ.get("OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK"):
|
|
72
|
+
return None
|
|
73
|
+
return PromptLog(
|
|
74
|
+
_hook(),
|
|
75
|
+
trace.get_tracer(__name__),
|
|
76
|
+
prompt,
|
|
77
|
+
options,
|
|
78
|
+
session_id,
|
|
79
|
+
agent_name,
|
|
80
|
+
subagent_spans,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@functools.cache
|
|
85
|
+
def _hook() -> CompletionHook:
|
|
86
|
+
# Built once: the upload hook test-writes the bucket and starts threads.
|
|
87
|
+
return load_completion_hook()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class PromptLog:
|
|
91
|
+
"""Logs each model call of one turn, with the inputs that led to it."""
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
hook: CompletionHook,
|
|
96
|
+
tracer: trace.Tracer,
|
|
97
|
+
prompt: str,
|
|
98
|
+
options: ClaudeAgentOptions,
|
|
99
|
+
session_id: str,
|
|
100
|
+
agent_name: Callable[[str | None], str],
|
|
101
|
+
subagent_spans: SubagentSpans,
|
|
102
|
+
) -> None:
|
|
103
|
+
self._hook = hook
|
|
104
|
+
self._tracer = tracer
|
|
105
|
+
self._system = _system_instruction(options.system_prompt)
|
|
106
|
+
self._attributes = {
|
|
107
|
+
"gen_ai.operation.name": "chat",
|
|
108
|
+
"gen_ai.provider.name": "gcp.vertex_ai",
|
|
109
|
+
# OpenTelemetry's conversation is the Claude session.
|
|
110
|
+
"gen_ai.conversation.id": session_id,
|
|
111
|
+
}
|
|
112
|
+
# Per agent: the messages of earlier calls, and those since the last call.
|
|
113
|
+
self._history: dict[str | None, list[InputMessage]] = {}
|
|
114
|
+
self._new: dict[str | None, list[InputMessage]] = {
|
|
115
|
+
None: [InputMessage(role="user", parts=[TextPart(content=prompt)])]
|
|
116
|
+
}
|
|
117
|
+
# Per agent: the SDK message the last tool result in _new came in.
|
|
118
|
+
self._results_from: dict[str | None, int] = {}
|
|
119
|
+
self._agent_name = agent_name
|
|
120
|
+
self._subagent_spans = subagent_spans
|
|
121
|
+
|
|
122
|
+
def handle(self, event: Event) -> None:
|
|
123
|
+
try:
|
|
124
|
+
if isinstance(event, ModelCallEnded):
|
|
125
|
+
self._log(event)
|
|
126
|
+
elif isinstance(event, ToolCallEnded):
|
|
127
|
+
self._add_result(event)
|
|
128
|
+
elif isinstance(event, SubagentPrompt):
|
|
129
|
+
self._new.setdefault(event.agent, []).append(
|
|
130
|
+
InputMessage(role="user", parts=[TextPart(content=event.text)])
|
|
131
|
+
)
|
|
132
|
+
except Exception: # logging must never fail a turn
|
|
133
|
+
logging.warning("Couldn't log a model call", exc_info=True)
|
|
134
|
+
|
|
135
|
+
def _add_result(self, event: ToolCallEnded) -> None:
|
|
136
|
+
part = ToolCallResponsePart(
|
|
137
|
+
response=_response(event.content, event.is_error), id=event.id
|
|
138
|
+
)
|
|
139
|
+
new = self._new.setdefault(event.agent, [])
|
|
140
|
+
if new and self._results_from.get(event.agent) == event.message_index:
|
|
141
|
+
new[-1].parts.append(part)
|
|
142
|
+
else:
|
|
143
|
+
new.append(InputMessage(role="tool", parts=[part]))
|
|
144
|
+
self._results_from[event.agent] = event.message_index
|
|
145
|
+
|
|
146
|
+
def _log(self, event: ModelCallEnded) -> None:
|
|
147
|
+
agent = event.agent
|
|
148
|
+
history = self._history.setdefault(agent, [])
|
|
149
|
+
history.extend(self._new.pop(agent, []))
|
|
150
|
+
self._results_from.pop(agent, None)
|
|
151
|
+
inputs = list(history)
|
|
152
|
+
parts = _parts(event.blocks)
|
|
153
|
+
history.append(InputMessage(role="assistant", parts=parts))
|
|
154
|
+
|
|
155
|
+
subagent = (
|
|
156
|
+
self._subagent_spans.subagent_span(agent) if agent is not None else None
|
|
157
|
+
)
|
|
158
|
+
span = self._tracer.start_span(
|
|
159
|
+
f"chat {event.model}",
|
|
160
|
+
context=trace.set_span_in_context(subagent)
|
|
161
|
+
if subagent is not None
|
|
162
|
+
else None,
|
|
163
|
+
kind=trace.SpanKind.CLIENT,
|
|
164
|
+
start_time=event.started_ns,
|
|
165
|
+
)
|
|
166
|
+
attributes: dict[str, Any] = {
|
|
167
|
+
**self._attributes,
|
|
168
|
+
"gen_ai.request.model": event.model,
|
|
169
|
+
"gen_ai.response.model": event.model,
|
|
170
|
+
"gen_ai.agent.name": self._agent_name(agent),
|
|
171
|
+
}
|
|
172
|
+
if event.stop_reason:
|
|
173
|
+
attributes["gen_ai.response.finish_reasons"] = [event.stop_reason]
|
|
174
|
+
for key in ("input_tokens", "output_tokens"):
|
|
175
|
+
if event.usage.get(key) is not None:
|
|
176
|
+
attributes[f"gen_ai.usage.{key}"] = event.usage[key]
|
|
177
|
+
if event.error:
|
|
178
|
+
attributes["error.type"] = event.error
|
|
179
|
+
span.set_status(trace.Status(trace.StatusCode.ERROR, event.error))
|
|
180
|
+
try:
|
|
181
|
+
span.set_attributes(attributes)
|
|
182
|
+
record = LogRecord(
|
|
183
|
+
attributes={"event.name": EVENT_NAME, **attributes},
|
|
184
|
+
context=trace.set_span_in_context(span),
|
|
185
|
+
)
|
|
186
|
+
self._hook.on_completion(
|
|
187
|
+
inputs=inputs,
|
|
188
|
+
outputs=[OutputMessage(role="assistant", parts=parts)],
|
|
189
|
+
system_instruction=self._system if agent is None else [],
|
|
190
|
+
span=span,
|
|
191
|
+
log_record=record,
|
|
192
|
+
)
|
|
193
|
+
telemetry.emit_event(record)
|
|
194
|
+
finally:
|
|
195
|
+
span.end()
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _parts(blocks: tuple[Any, ...]) -> list[MessagePart]:
|
|
199
|
+
parts: list[MessagePart] = []
|
|
200
|
+
for block in blocks:
|
|
201
|
+
if isinstance(block, TextBlock):
|
|
202
|
+
parts.append(TextPart(content=block.text))
|
|
203
|
+
elif isinstance(block, ThinkingBlock):
|
|
204
|
+
# As text: the Console's message viewer rejects "reasoning" parts.
|
|
205
|
+
parts.append(TextPart(content=block.thinking))
|
|
206
|
+
elif isinstance(block, ToolUseBlock):
|
|
207
|
+
parts.append(
|
|
208
|
+
ToolCallRequestPart(arguments=block.input, name=block.name, id=block.id)
|
|
209
|
+
)
|
|
210
|
+
return parts
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _response(content: Any, is_error: bool) -> dict[str, Any]:
|
|
214
|
+
"""A tool result as an object: the Console's viewer rejects other shapes."""
|
|
215
|
+
if isinstance(content, list) and all(
|
|
216
|
+
isinstance(item, dict) and item.get("type") == "text" for item in content
|
|
217
|
+
):
|
|
218
|
+
content = "".join(item.get("text", "") for item in content)
|
|
219
|
+
return {"error" if is_error else "result": content}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _system_instruction(system_prompt: Any) -> list[MessagePart]:
|
|
223
|
+
"""The system prompt the model got; with a preset, only what it appends."""
|
|
224
|
+
text = system_prompt_text(system_prompt)
|
|
225
|
+
return [TextPart(content=text)] if text else []
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""The conversation and user of the turn that is running."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from contextvars import ContextVar
|
|
20
|
+
|
|
21
|
+
# The running turn's conversation, scoped to the caller. Tools can key
|
|
22
|
+
# per-conversation state on it.
|
|
23
|
+
current_conversation: ContextVar[str | None] = ContextVar(
|
|
24
|
+
"current_conversation", default=None
|
|
25
|
+
)
|
|
26
|
+
# The running turn's user: the authenticated caller, else one named after the
|
|
27
|
+
# conversation. Tools can key per-user state on it. Unset outside a turn, where
|
|
28
|
+
# get() raises LookupError.
|
|
29
|
+
current_user: ContextVar[str] = ContextVar("current_user")
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Long-term memory of each user, in Memory Bank, as ADK's memory tools keep it.
|
|
16
|
+
|
|
17
|
+
Enabled when MEMORY_BANK_ENABLED is true. Each turn:
|
|
18
|
+
|
|
19
|
+
- `recall` adds the user's memories that match the prompt to the system prompt
|
|
20
|
+
(ADK's PreloadMemoryTool);
|
|
21
|
+
- `start_turn` records the main agent's events and, when the turn succeeds,
|
|
22
|
+
sends them to Memory Bank in the background, which extracts memories from them;
|
|
23
|
+
- the `search_memory` tool lets the model search the memories (ADK's
|
|
24
|
+
LoadMemoryTool).
|
|
25
|
+
|
|
26
|
+
Memories are scoped to the agent's name and the user. On Agent Runtime they live
|
|
27
|
+
in the agent's own engine. Elsewhere, in the engine named MEMORY_BANK_ENGINE_NAME
|
|
28
|
+
(default: the agent's name), which is created when missing.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import asyncio
|
|
34
|
+
import datetime
|
|
35
|
+
import logging
|
|
36
|
+
import os
|
|
37
|
+
import threading
|
|
38
|
+
import uuid
|
|
39
|
+
from typing import Any
|
|
40
|
+
|
|
41
|
+
import anyio
|
|
42
|
+
from claude_agent_sdk import (
|
|
43
|
+
McpServerConfig,
|
|
44
|
+
TextBlock,
|
|
45
|
+
ToolResultBlock,
|
|
46
|
+
ToolUseBlock,
|
|
47
|
+
create_sdk_mcp_server,
|
|
48
|
+
tool,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
from app.app_utils.conversation import current_user
|
|
52
|
+
from app.app_utils.replies import tool_result_text
|
|
53
|
+
from app.app_utils.telemetry.config import agent_name
|
|
54
|
+
from app.app_utils.turn_events import Event, ModelCallEnded, ToolCallEnded, TurnEnded
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"allowed_tools",
|
|
58
|
+
"enabled",
|
|
59
|
+
"flush",
|
|
60
|
+
"mcp_servers",
|
|
61
|
+
"recall",
|
|
62
|
+
"search_memory",
|
|
63
|
+
"start_turn",
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
_PAST_CONVERSATIONS = """The following content is from your previous conversations with the user.
|
|
67
|
+
They may be useful for answering the user's current query.
|
|
68
|
+
<PAST_CONVERSATIONS>
|
|
69
|
+
{}
|
|
70
|
+
</PAST_CONVERSATIONS>
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
_engine_name: str | None = None
|
|
74
|
+
_engine_lock = threading.Lock()
|
|
75
|
+
# Strong references, so running ingests aren't garbage collected.
|
|
76
|
+
_pending: set[asyncio.Task[None]] = set()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def enabled() -> bool:
|
|
80
|
+
"""Whether MEMORY_BANK_ENABLED turns memory on."""
|
|
81
|
+
return os.environ.get("MEMORY_BANK_ENABLED", "").lower() in ("true", "1")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@tool(
|
|
85
|
+
"search_memory",
|
|
86
|
+
"Search your memories of earlier conversations with the user. Call it when "
|
|
87
|
+
"the user's request may depend on something they told you before.",
|
|
88
|
+
{"query": str},
|
|
89
|
+
)
|
|
90
|
+
async def search_memory(args: dict[str, Any]) -> dict[str, Any]:
|
|
91
|
+
lines = await _search(args["query"], current_user.get())
|
|
92
|
+
text = "\n".join(lines) if lines else "No memories found."
|
|
93
|
+
return {"content": [{"type": "text", "text": text}]}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
_server = create_sdk_mcp_server(name="memory", tools=[search_memory])
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def mcp_servers() -> dict[str, McpServerConfig]:
|
|
100
|
+
"""The memory tool's server, keyed by name."""
|
|
101
|
+
return {"memory": _server}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def allowed_tools() -> list[str]:
|
|
105
|
+
"""The memory tool's allow rule."""
|
|
106
|
+
return ["mcp__memory__search_memory"]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def recall(system_prompt: Any, prompt: str, user_id: str) -> Any:
|
|
110
|
+
"""`system_prompt` with the user's memories that match `prompt` added.
|
|
111
|
+
|
|
112
|
+
Without memories, or when they can't be read, it is returned unchanged.
|
|
113
|
+
"""
|
|
114
|
+
if not enabled():
|
|
115
|
+
return system_prompt
|
|
116
|
+
try:
|
|
117
|
+
lines = await _search(prompt, user_id)
|
|
118
|
+
except Exception as e: # memory must never stop the agent
|
|
119
|
+
logging.warning("Couldn't recall the user's memories: %s", e)
|
|
120
|
+
return system_prompt
|
|
121
|
+
if not lines:
|
|
122
|
+
return system_prompt
|
|
123
|
+
return _with_memories(system_prompt, _PAST_CONVERSATIONS.format("\n".join(lines)))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def start_turn(prompt: str, session_id: str, user_id: str) -> MemoryIngest | None:
|
|
127
|
+
"""A recorder that sends one turn to Memory Bank, or None when memory is off."""
|
|
128
|
+
if not enabled():
|
|
129
|
+
return None
|
|
130
|
+
return MemoryIngest(prompt, session_id, user_id)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
async def flush() -> None:
|
|
134
|
+
"""Wait until the turns' pending ingests are sent."""
|
|
135
|
+
# shortcut: waits for every turn's pending ingest, not only the caller's;
|
|
136
|
+
# track them per turn if a turn shouldn't wait on another one's.
|
|
137
|
+
if _pending:
|
|
138
|
+
await asyncio.wait(set(_pending))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class MemoryIngest:
|
|
142
|
+
"""Collects one turn's main-agent events, and sends them if the turn succeeds."""
|
|
143
|
+
|
|
144
|
+
def __init__(self, prompt: str, session_id: str, user_id: str) -> None:
|
|
145
|
+
self._session_id = session_id
|
|
146
|
+
self._user_id = user_id
|
|
147
|
+
self._turn = uuid.uuid4().hex
|
|
148
|
+
self._tool_names: dict[str, str] = {}
|
|
149
|
+
self._events: list[dict[str, Any]] = []
|
|
150
|
+
self._add("user", [{"text": prompt}])
|
|
151
|
+
|
|
152
|
+
def handle(self, event: Event) -> None:
|
|
153
|
+
# Subagents' events are left out: the main agent's tool call and its
|
|
154
|
+
# result stand for a subagent's work.
|
|
155
|
+
if isinstance(event, ModelCallEnded) and event.agent is None:
|
|
156
|
+
self._add("model", self._model_parts(event.blocks))
|
|
157
|
+
elif isinstance(event, ToolCallEnded) and event.agent is None:
|
|
158
|
+
block = ToolResultBlock(
|
|
159
|
+
tool_use_id=event.id, content=event.content, is_error=event.is_error
|
|
160
|
+
)
|
|
161
|
+
response = {
|
|
162
|
+
"id": event.id,
|
|
163
|
+
"name": self._tool_names.get(event.id, ""),
|
|
164
|
+
"response": {
|
|
165
|
+
"error" if event.is_error else "result": tool_result_text(block)
|
|
166
|
+
},
|
|
167
|
+
}
|
|
168
|
+
self._add("user", [{"function_response": response}])
|
|
169
|
+
elif isinstance(event, TurnEnded) and not event.failed:
|
|
170
|
+
task = asyncio.create_task(
|
|
171
|
+
_ingest(self._session_id, self._user_id, self._events)
|
|
172
|
+
)
|
|
173
|
+
_pending.add(task)
|
|
174
|
+
task.add_done_callback(_pending.discard)
|
|
175
|
+
|
|
176
|
+
def _model_parts(self, blocks: tuple[Any, ...]) -> list[dict[str, Any]]:
|
|
177
|
+
parts: list[dict[str, Any]] = []
|
|
178
|
+
for block in blocks:
|
|
179
|
+
if isinstance(block, TextBlock) and block.text:
|
|
180
|
+
parts.append({"text": block.text})
|
|
181
|
+
elif isinstance(block, ToolUseBlock):
|
|
182
|
+
self._tool_names[block.id] = block.name
|
|
183
|
+
call = {"id": block.id, "name": block.name, "args": block.input}
|
|
184
|
+
parts.append({"function_call": call})
|
|
185
|
+
return parts
|
|
186
|
+
|
|
187
|
+
def _add(self, role: str, parts: list[dict[str, Any]]) -> None:
|
|
188
|
+
if not parts:
|
|
189
|
+
return
|
|
190
|
+
self._events.append(
|
|
191
|
+
{
|
|
192
|
+
"content": {"role": role, "parts": parts},
|
|
193
|
+
"event_id": f"{self._turn}-{len(self._events)}",
|
|
194
|
+
"event_time": datetime.datetime.now(datetime.UTC),
|
|
195
|
+
}
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
async def _ingest(session_id: str, user_id: str, events: list[dict[str, Any]]) -> None:
|
|
200
|
+
try:
|
|
201
|
+
async with _client().aio as client:
|
|
202
|
+
await client.memory_banks.ingest_events(
|
|
203
|
+
name=await _engine(),
|
|
204
|
+
scope=_scope(user_id),
|
|
205
|
+
stream_id=session_id,
|
|
206
|
+
direct_contents_source={"events": events},
|
|
207
|
+
)
|
|
208
|
+
except Exception as e: # memory must never stop the agent
|
|
209
|
+
logging.warning("Couldn't send the turn to Memory Bank: %s", e)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
async def _search(query: str, user_id: str) -> list[str]:
|
|
213
|
+
"""The user's memories that match `query`, as ADK's memory tools show them."""
|
|
214
|
+
lines: list[str] = []
|
|
215
|
+
async with _client().aio as client:
|
|
216
|
+
retrieved = await client.memory_banks.memories.retrieve(
|
|
217
|
+
name=await _engine(),
|
|
218
|
+
scope=_scope(user_id),
|
|
219
|
+
similarity_search_params={"search_query": query},
|
|
220
|
+
)
|
|
221
|
+
async for item in retrieved:
|
|
222
|
+
memory = item.memory
|
|
223
|
+
if memory is None or not memory.fact:
|
|
224
|
+
continue
|
|
225
|
+
if memory.update_time:
|
|
226
|
+
lines.append(f"Time: {memory.update_time.isoformat()}")
|
|
227
|
+
# Memory Bank's memories are the user's, so ADK shows each as "user: <fact>".
|
|
228
|
+
lines.append(f"user: {memory.fact}")
|
|
229
|
+
return lines
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _with_memories(system_prompt: Any, memories: str) -> Any:
|
|
233
|
+
"""`system_prompt` with `memories` appended, rebuilt on every request.
|
|
234
|
+
|
|
235
|
+
snapshot=False makes the CLI send this turn's memories, not the system
|
|
236
|
+
prompt the session recorded on its first request.
|
|
237
|
+
"""
|
|
238
|
+
if system_prompt is None:
|
|
239
|
+
# The SDK sends no system prompt as an empty custom one.
|
|
240
|
+
return {"type": "custom", "prompt": memories, "snapshot": False}
|
|
241
|
+
if isinstance(system_prompt, str):
|
|
242
|
+
return {
|
|
243
|
+
"type": "custom",
|
|
244
|
+
"prompt": _joined(system_prompt, memories),
|
|
245
|
+
"snapshot": False,
|
|
246
|
+
}
|
|
247
|
+
if system_prompt.get("type") == "preset":
|
|
248
|
+
append = _joined(system_prompt.get("append", ""), memories)
|
|
249
|
+
return {**system_prompt, "append": append, "snapshot": False}
|
|
250
|
+
if system_prompt.get("type") == "custom":
|
|
251
|
+
prompt = _joined(system_prompt["prompt"], memories)
|
|
252
|
+
return {**system_prompt, "prompt": prompt, "snapshot": False}
|
|
253
|
+
logging.warning(
|
|
254
|
+
"Memories are not added to a system prompt file; use a string system "
|
|
255
|
+
"prompt to get them."
|
|
256
|
+
)
|
|
257
|
+
return system_prompt
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _joined(text: str, memories: str) -> str:
|
|
261
|
+
return f"{text}\n\n{memories}" if text else memories
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _scope(user_id: str) -> dict[str, str]:
|
|
265
|
+
return {"app_name": agent_name(), "user_id": user_id}
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _client() -> Any:
|
|
269
|
+
"""A client per call: its async client is bound to the event loop it first ran in."""
|
|
270
|
+
import agentplatform
|
|
271
|
+
|
|
272
|
+
return agentplatform.Client(location=_location())
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _location() -> str:
|
|
276
|
+
"""The engine's region; Agent Runtime doesn't support "global"."""
|
|
277
|
+
if location := os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_LOCATION"):
|
|
278
|
+
return location
|
|
279
|
+
location = os.environ.get("GOOGLE_CLOUD_LOCATION")
|
|
280
|
+
if location and location != "global":
|
|
281
|
+
return location
|
|
282
|
+
# `scaffold create --region` rewrites this default to the project's region.
|
|
283
|
+
return "us-east1"
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
async def _engine() -> str:
|
|
287
|
+
"""The engine whose Memory Bank holds the memories, resolved once per process."""
|
|
288
|
+
return await anyio.to_thread.run_sync(_resolve_engine)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _resolve_engine() -> str:
|
|
292
|
+
global _engine_name
|
|
293
|
+
with _engine_lock:
|
|
294
|
+
if _engine_name is None:
|
|
295
|
+
_engine_name = _find_or_create_engine()
|
|
296
|
+
return _engine_name
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _find_or_create_engine() -> str:
|
|
300
|
+
if engine_id := os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ID"):
|
|
301
|
+
return f"reasoningEngines/{engine_id}"
|
|
302
|
+
name = os.environ.get("MEMORY_BANK_ENGINE_NAME") or agent_name()
|
|
303
|
+
client = _client()
|
|
304
|
+
found = list(client.runtimes.list(config={"filter": f"display_name={name}"}))
|
|
305
|
+
if found:
|
|
306
|
+
return found[0].api_resource.name
|
|
307
|
+
logging.info("Creating Agent Runtime %r for Memory Bank", name)
|
|
308
|
+
return client.runtimes.create(config={"display_name": name}).api_resource.name
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""The served agent's Claude Code settings: CLAUDE.md, .claude/ and .mcp.json.
|
|
16
|
+
|
|
17
|
+
They live in agent_config/, not at the project root, so the developer's own
|
|
18
|
+
Claude Code setup (permission rules, hooks, notes) never reaches the served agent.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
import shutil
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
from app.app_utils import workspaces
|
|
28
|
+
|
|
29
|
+
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
|
30
|
+
AGENT_CONFIG_DIR = PROJECT_ROOT / "agent_config"
|
|
31
|
+
|
|
32
|
+
_FILES = ("CLAUDE.md", "CLAUDE.local.md", ".mcp.json")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def copy_project_settings(workspace: Path) -> bool:
|
|
36
|
+
"""Copy agent_config/'s CLAUDE.md, .claude/ and .mcp.json into `workspace`.
|
|
37
|
+
|
|
38
|
+
Returns whether there are settings to load there.
|
|
39
|
+
"""
|
|
40
|
+
config = AGENT_CONFIG_DIR
|
|
41
|
+
if workspace.resolve() == config.resolve():
|
|
42
|
+
return (config / ".claude").is_dir() or any(
|
|
43
|
+
(config / name).is_file() for name in _FILES
|
|
44
|
+
)
|
|
45
|
+
if not workspace.resolve().is_relative_to(workspaces.WORKSPACES.resolve()):
|
|
46
|
+
# A root_agent cwd of its own, such as the project root or a repo the
|
|
47
|
+
# agent works on: its files are not ours to replace or delete.
|
|
48
|
+
return False
|
|
49
|
+
# Replace, don't merge: settings the agent wrote into its workspace on an
|
|
50
|
+
# earlier turn (hooks, MCP servers) must not load on the next one.
|
|
51
|
+
shutil.rmtree(workspace / ".claude", ignore_errors=True)
|
|
52
|
+
found = False
|
|
53
|
+
if (config / ".claude").is_dir():
|
|
54
|
+
shutil.copytree(config / ".claude", workspace / ".claude")
|
|
55
|
+
found = True
|
|
56
|
+
for name in _FILES:
|
|
57
|
+
if (config / name).is_file():
|
|
58
|
+
shutil.copy2(config / name, workspace / name)
|
|
59
|
+
found = True
|
|
60
|
+
else:
|
|
61
|
+
(workspace / name).unlink(missing_ok=True)
|
|
62
|
+
return found
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def settings_allow_rules(setting_sources: list[str]) -> list[str]:
|
|
66
|
+
"""The permissions.allow rules from agent_config/'s settings the CLI loads.
|
|
67
|
+
|
|
68
|
+
The CLI ignores them in an untrusted directory, which every workspace is,
|
|
69
|
+
so they are passed as allowed_tools instead. They are read from
|
|
70
|
+
agent_config/, never from the workspace copy, which the agent can write to.
|
|
71
|
+
"""
|
|
72
|
+
rules: list[str] = []
|
|
73
|
+
for source, name in (
|
|
74
|
+
("project", "settings.json"),
|
|
75
|
+
("local", "settings.local.json"),
|
|
76
|
+
):
|
|
77
|
+
path = AGENT_CONFIG_DIR / ".claude" / name
|
|
78
|
+
if source not in setting_sources or not path.is_file():
|
|
79
|
+
continue
|
|
80
|
+
try:
|
|
81
|
+
settings = json.loads(path.read_text())
|
|
82
|
+
except ValueError:
|
|
83
|
+
# The CLI reports a malformed settings file itself.
|
|
84
|
+
continue
|
|
85
|
+
permissions = (
|
|
86
|
+
settings.get("permissions") if isinstance(settings, dict) else None
|
|
87
|
+
)
|
|
88
|
+
allow = permissions.get("allow") if isinstance(permissions, dict) else None
|
|
89
|
+
if isinstance(allow, list):
|
|
90
|
+
rules.extend(rule for rule in allow if isinstance(rule, str))
|
|
91
|
+
return rules
|