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,159 @@
|
|
|
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
|
+
"""How `remote_agent` authenticates to a remote agent.
|
|
16
|
+
|
|
17
|
+
Which host gets which Google token, over which TLS connection, and how the
|
|
18
|
+
token is kept to the host it was meant for.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import ssl
|
|
24
|
+
from collections.abc import Generator, Mapping
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
import httpx
|
|
28
|
+
from a2a.types import AgentCard
|
|
29
|
+
|
|
30
|
+
_AGENT_RUNTIME_HOST_SUFFIX = "-aiplatform.googleapis.com"
|
|
31
|
+
_CLOUD_RUN_HOST_SUFFIX = ".run.app"
|
|
32
|
+
_CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def is_agent_runtime(url: str) -> bool:
|
|
36
|
+
"""Whether `url` is an Agent Runtime endpoint, matched on the host.
|
|
37
|
+
|
|
38
|
+
The access token sent there is good for any Google Cloud API.
|
|
39
|
+
"""
|
|
40
|
+
parsed = httpx.URL(url)
|
|
41
|
+
return (
|
|
42
|
+
parsed.scheme == "https"
|
|
43
|
+
and parsed.host.endswith(_AGENT_RUNTIME_HOST_SUFFIX)
|
|
44
|
+
and "/reasoningEngines/" in parsed.path
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def is_cloud_run(url: str) -> bool:
|
|
49
|
+
"""Whether `url` is at a Cloud Run service's own `*.run.app` host."""
|
|
50
|
+
parsed = httpx.URL(url)
|
|
51
|
+
return parsed.scheme == "https" and parsed.host.endswith(_CLOUD_RUN_HOST_SUFFIX)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def mtls_target(url: str) -> tuple[str, ssl.SSLContext | bool]:
|
|
55
|
+
"""Where to send an Agent Runtime request, and how to verify TLS there.
|
|
56
|
+
|
|
57
|
+
Tokens bound to an Agent Identity certificate need mTLS at the
|
|
58
|
+
mtls.googleapis.com host. Call this per request to pick up a rotated cert.
|
|
59
|
+
"""
|
|
60
|
+
from google.auth.transport import mtls
|
|
61
|
+
|
|
62
|
+
context = mtls.get_default_ssl_context()
|
|
63
|
+
if context is None:
|
|
64
|
+
return url, True
|
|
65
|
+
return _mtls_url(url), context
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _mtls_url(url: str) -> str:
|
|
69
|
+
"""`url` at its API's mTLS host, e.g. us-central1-aiplatform.mtls.googleapis.com."""
|
|
70
|
+
parsed = httpx.URL(url)
|
|
71
|
+
host = parsed.host.removesuffix(".googleapis.com") + ".mtls.googleapis.com"
|
|
72
|
+
return str(parsed.copy_with(host=host))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def cloud_credentials() -> Any:
|
|
76
|
+
"""Application Default Credentials for Google Cloud APIs."""
|
|
77
|
+
import google.auth
|
|
78
|
+
|
|
79
|
+
credentials, _ = google.auth.default(scopes=[_CLOUD_PLATFORM_SCOPE])
|
|
80
|
+
return credentials
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def access_token(credentials: Any) -> str:
|
|
84
|
+
"""A current OAuth access token from `credentials`, refreshed when expired."""
|
|
85
|
+
from google.auth.transport.requests import Request
|
|
86
|
+
|
|
87
|
+
if not credentials.valid: # also false within a few minutes of expiry
|
|
88
|
+
credentials.refresh(Request())
|
|
89
|
+
return credentials.token
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def id_token(audience: str, bind: bool = True) -> tuple[str, bool]:
|
|
93
|
+
"""A Google ID token for `audience`, and whether it's the user's unbound one."""
|
|
94
|
+
import google.auth
|
|
95
|
+
import google.oauth2.credentials
|
|
96
|
+
import google.oauth2.id_token
|
|
97
|
+
from google.auth import compute_engine, impersonated_credentials
|
|
98
|
+
from google.auth.transport.requests import Request
|
|
99
|
+
|
|
100
|
+
request = Request()
|
|
101
|
+
# Resolved like ADC, so a developer's login wins over a VM's metadata server.
|
|
102
|
+
credentials, _ = google.auth.default()
|
|
103
|
+
if isinstance(credentials, google.oauth2.credentials.Credentials):
|
|
104
|
+
# User credentials' own ID token is for gcloud's client, not `audience`:
|
|
105
|
+
# whoever receives it can call any Cloud Run service the user can.
|
|
106
|
+
credentials.refresh(request)
|
|
107
|
+
return credentials.id_token, True
|
|
108
|
+
if isinstance(credentials, impersonated_credentials.Credentials):
|
|
109
|
+
token = impersonated_credentials.IDTokenCredentials(
|
|
110
|
+
credentials, target_audience=audience, include_email=True
|
|
111
|
+
)
|
|
112
|
+
token.refresh(request)
|
|
113
|
+
return token.token, False
|
|
114
|
+
if isinstance(credentials, compute_engine.Credentials):
|
|
115
|
+
# With Agent Identity the token is bound to the agent's certificate,
|
|
116
|
+
# which Cloud Run rejects with 401; callers to Cloud Run pass bind=False.
|
|
117
|
+
token = compute_engine.IDTokenCredentials(
|
|
118
|
+
request,
|
|
119
|
+
audience,
|
|
120
|
+
use_metadata_identity_endpoint=True,
|
|
121
|
+
bind_id_token=bind,
|
|
122
|
+
)
|
|
123
|
+
token.refresh(request)
|
|
124
|
+
return token.token, False
|
|
125
|
+
# A service account key.
|
|
126
|
+
return google.oauth2.id_token.fetch_id_token(request, audience), False
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def origin(url: str | httpx.URL) -> httpx.URL:
|
|
130
|
+
"""The scheme, host and port of `url`."""
|
|
131
|
+
# httpx.URL normalizes case and drops a default port.
|
|
132
|
+
url = httpx.URL(url)
|
|
133
|
+
return httpx.URL(scheme=url.scheme, host=url.host, port=url.port)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class PinnedHeaders(httpx.Auth):
|
|
137
|
+
"""Add `headers` only to requests for `origin`, so credentials stay there."""
|
|
138
|
+
|
|
139
|
+
def __init__(self, headers: Mapping[str, str], origin: httpx.URL) -> None:
|
|
140
|
+
self._headers = dict(headers)
|
|
141
|
+
self._origin = origin
|
|
142
|
+
|
|
143
|
+
def auth_flow(
|
|
144
|
+
self, request: httpx.Request
|
|
145
|
+
) -> Generator[httpx.Request, httpx.Response]:
|
|
146
|
+
if origin(request.url) == self._origin:
|
|
147
|
+
# No traceparent: the remote agent records its own trace.
|
|
148
|
+
request.headers.update(self._headers)
|
|
149
|
+
yield request
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def pin_to_origin(card: AgentCard, url: str) -> None:
|
|
153
|
+
"""Point the card's endpoints at `url`'s origin, so it can't redirect the token."""
|
|
154
|
+
target = httpx.URL(url)
|
|
155
|
+
for interface in card.supported_interfaces:
|
|
156
|
+
declared = httpx.URL(interface.url)
|
|
157
|
+
interface.url = str(
|
|
158
|
+
target.copy_with(path=declared.path or target.path, query=declared.query)
|
|
159
|
+
)
|
|
@@ -0,0 +1,143 @@
|
|
|
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
|
+
"""Read a turn's reply and tool calls out of the SDK messages it streams."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import dataclasses
|
|
20
|
+
import logging
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from claude_agent_sdk import (
|
|
24
|
+
AssistantMessage,
|
|
25
|
+
Message,
|
|
26
|
+
ResultMessage,
|
|
27
|
+
StreamEvent,
|
|
28
|
+
TextBlock,
|
|
29
|
+
ToolResultBlock,
|
|
30
|
+
ToolUseBlock,
|
|
31
|
+
UserMessage,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
from app.app_utils.telemetry.config import capture_content
|
|
35
|
+
from app.app_utils.turn_events import subagent_name
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclasses.dataclass
|
|
39
|
+
class TurnReply:
|
|
40
|
+
"""What one turn produced: the reply, its tool calls, and the run stats."""
|
|
41
|
+
|
|
42
|
+
text: str = ""
|
|
43
|
+
session_id: str | None = None
|
|
44
|
+
tool_calls: list[dict[str, Any]] = dataclasses.field(default_factory=list)
|
|
45
|
+
result: ResultMessage | None = None
|
|
46
|
+
subagent_calls: list[dict[str, Any]] = dataclasses.field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AgentError(RuntimeError):
|
|
50
|
+
"""The turn failed, or couldn't start: a preflight check found a problem."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def record(reply: TurnReply, message: Message) -> TurnReply:
|
|
54
|
+
"""Fold one SDK message into `reply` and return it.
|
|
55
|
+
|
|
56
|
+
Raises:
|
|
57
|
+
AgentError: `message` is an error result.
|
|
58
|
+
"""
|
|
59
|
+
if isinstance(message, AssistantMessage):
|
|
60
|
+
# Fallback for results without a reply.
|
|
61
|
+
reply.text = last_text(message) or reply.text
|
|
62
|
+
parent = message.parent_tool_use_id
|
|
63
|
+
for block in message.content:
|
|
64
|
+
if not isinstance(block, ToolUseBlock):
|
|
65
|
+
continue
|
|
66
|
+
call = {"id": block.id, "name": block.name, "args": block.input}
|
|
67
|
+
if parent:
|
|
68
|
+
call.update(agent=_subagent_name(reply, parent), parent=parent)
|
|
69
|
+
reply.subagent_calls.append(call)
|
|
70
|
+
else:
|
|
71
|
+
reply.tool_calls.append(call)
|
|
72
|
+
elif isinstance(message, UserMessage) and isinstance(message.content, list):
|
|
73
|
+
results = {
|
|
74
|
+
b.tool_use_id: b for b in message.content if isinstance(b, ToolResultBlock)
|
|
75
|
+
}
|
|
76
|
+
for call in reply.tool_calls + reply.subagent_calls:
|
|
77
|
+
if call["id"] in results and "result" not in call:
|
|
78
|
+
call["result"] = tool_result_text(results[call["id"]])
|
|
79
|
+
elif isinstance(message, ResultMessage):
|
|
80
|
+
reply.result = message
|
|
81
|
+
reply.session_id = message.session_id
|
|
82
|
+
# A denied tool call doesn't fail the turn. Its arguments are logged only
|
|
83
|
+
# with content capture on.
|
|
84
|
+
for denial in message.permission_denials or []:
|
|
85
|
+
if not capture_content() and isinstance(denial, dict):
|
|
86
|
+
denial = denial.get("tool_name")
|
|
87
|
+
logging.warning("Claude agent was denied a tool call: %s", denial)
|
|
88
|
+
if message.is_error:
|
|
89
|
+
raise AgentError(f"Claude agent turn failed: {result_error(message)}")
|
|
90
|
+
reply.text = message.result or reply.text
|
|
91
|
+
return reply
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _subagent_name(reply: TurnReply, parent: str) -> str:
|
|
95
|
+
"""The subagent the `parent` call delegated to, named as in BigQuery rows."""
|
|
96
|
+
for call in reply.tool_calls + reply.subagent_calls:
|
|
97
|
+
if call["id"] == parent:
|
|
98
|
+
return subagent_name(call["args"])
|
|
99
|
+
return "subagent"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def result_error(result: ResultMessage) -> str:
|
|
103
|
+
"""What went wrong, from an error result."""
|
|
104
|
+
return result.result or ", ".join(result.errors or []) or result.subtype
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def tool_result_text(block: ToolResultBlock) -> str:
|
|
108
|
+
"""Flatten a tool result's content (a string or MCP content blocks)."""
|
|
109
|
+
content = block.content
|
|
110
|
+
if isinstance(content, str):
|
|
111
|
+
return content
|
|
112
|
+
if isinstance(content, list):
|
|
113
|
+
return "".join(
|
|
114
|
+
str(item.get("text", "")) for item in content if isinstance(item, dict)
|
|
115
|
+
)
|
|
116
|
+
return ""
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def last_text(message: Message) -> str:
|
|
120
|
+
"""Text of a top-level assistant message, or ""."""
|
|
121
|
+
if not isinstance(message, AssistantMessage) or message.parent_tool_use_id:
|
|
122
|
+
return ""
|
|
123
|
+
return "".join(b.text for b in message.content if isinstance(b, TextBlock))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def text_delta(message: Message) -> str:
|
|
127
|
+
"""The text a partial-message stream event adds, or ""."""
|
|
128
|
+
if not isinstance(message, StreamEvent) or message.parent_tool_use_id:
|
|
129
|
+
return ""
|
|
130
|
+
event = message.event
|
|
131
|
+
if event.get("type") != "content_block_delta":
|
|
132
|
+
return ""
|
|
133
|
+
delta = event.get("delta") or {}
|
|
134
|
+
return delta.get("text", "") if delta.get("type") == "text_delta" else ""
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def starts_block(message: Message, kind: str) -> bool:
|
|
138
|
+
"""Whether a partial-message stream event opens a top-level `kind` block."""
|
|
139
|
+
if not isinstance(message, StreamEvent) or message.parent_tool_use_id:
|
|
140
|
+
return False
|
|
141
|
+
event = message.event
|
|
142
|
+
block = event.get("content_block") or {}
|
|
143
|
+
return event.get("type") == "content_block_start" and block.get("type") == kind
|
|
@@ -0,0 +1,174 @@
|
|
|
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
|
+
"""Keep Claude session transcripts in Cloud SQL, so any instance can resume them.
|
|
16
|
+
|
|
17
|
+
Adapted from the Claude Agent SDK's reference Postgres adapter.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import re
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import asyncpg
|
|
29
|
+
from claude_agent_sdk import SessionKey, SessionListSubkeysKey, SessionStoreEntry
|
|
30
|
+
|
|
31
|
+
# The table name is interpolated into SQL (identifiers can't be parameters).
|
|
32
|
+
_IDENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
33
|
+
|
|
34
|
+
# Per instance; Cloud SQL's connection limit is shared by all instances.
|
|
35
|
+
POOL_SIZE = 5
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class PostgresSessionStore:
|
|
39
|
+
"""A `SessionStore` over a Postgres table, created on first use.
|
|
40
|
+
|
|
41
|
+
One row per transcript entry; the main transcript has `subpath = ''`.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
table: str = "claude_session_store",
|
|
47
|
+
**connect: Any,
|
|
48
|
+
) -> None:
|
|
49
|
+
"""`connect` is passed to `asyncpg.create_pool` (host, user, ...)."""
|
|
50
|
+
if not _IDENT_RE.match(table):
|
|
51
|
+
raise ValueError(f"table {table!r} must match [A-Za-z_][A-Za-z0-9_]*")
|
|
52
|
+
self._table = table
|
|
53
|
+
self._connect = connect
|
|
54
|
+
self._pool: asyncpg.Pool | None = None
|
|
55
|
+
self._pool_loop: asyncio.AbstractEventLoop | None = None
|
|
56
|
+
self._lock = asyncio.Lock()
|
|
57
|
+
self._lock_loop: asyncio.AbstractEventLoop | None = None
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_env(cls) -> PostgresSessionStore | None:
|
|
61
|
+
"""A store for the Cloud SQL instance in the environment, or None."""
|
|
62
|
+
instance = os.environ.get("INSTANCE_CONNECTION_NAME")
|
|
63
|
+
password = os.environ.get("DB_PASS")
|
|
64
|
+
user = os.environ.get("DB_USER")
|
|
65
|
+
database = os.environ.get("DB_NAME", "postgres")
|
|
66
|
+
if not instance or not password:
|
|
67
|
+
return None
|
|
68
|
+
return cls(
|
|
69
|
+
host=f"/cloudsql/{instance}",
|
|
70
|
+
user=user or "postgres",
|
|
71
|
+
password=password,
|
|
72
|
+
database=database,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
async def _get_pool(self) -> asyncpg.Pool:
|
|
76
|
+
# A pool belongs to the event loop that created it, so a new loop
|
|
77
|
+
# (e.g. `anyio.run` per turn) gets a new pool.
|
|
78
|
+
loop = asyncio.get_running_loop()
|
|
79
|
+
if self._pool is not None and self._pool_loop is loop:
|
|
80
|
+
return self._pool
|
|
81
|
+
if self._lock_loop is not loop:
|
|
82
|
+
self._lock, self._lock_loop = asyncio.Lock(), loop
|
|
83
|
+
async with self._lock:
|
|
84
|
+
if self._pool is not None and self._pool_loop is loop:
|
|
85
|
+
return self._pool
|
|
86
|
+
if self._pool is not None:
|
|
87
|
+
# Its loop is gone, so it can't be closed gracefully.
|
|
88
|
+
self._pool.terminate()
|
|
89
|
+
pool = await asyncpg.create_pool(
|
|
90
|
+
min_size=1, max_size=POOL_SIZE, **self._connect
|
|
91
|
+
)
|
|
92
|
+
async with pool.acquire() as conn, conn.transaction():
|
|
93
|
+
# Serializes instances that start at once: concurrent
|
|
94
|
+
# CREATE TABLE IF NOT EXISTS can still collide in Postgres.
|
|
95
|
+
await conn.execute(
|
|
96
|
+
"SELECT pg_advisory_xact_lock(hashtext($1))", self._table
|
|
97
|
+
)
|
|
98
|
+
await conn.execute(
|
|
99
|
+
f"""
|
|
100
|
+
CREATE TABLE IF NOT EXISTS {self._table} (
|
|
101
|
+
project_key text NOT NULL,
|
|
102
|
+
session_id text NOT NULL,
|
|
103
|
+
subpath text NOT NULL DEFAULT '',
|
|
104
|
+
seq bigserial,
|
|
105
|
+
entry jsonb NOT NULL,
|
|
106
|
+
mtime bigint NOT NULL,
|
|
107
|
+
PRIMARY KEY (project_key, session_id, subpath, seq)
|
|
108
|
+
)
|
|
109
|
+
"""
|
|
110
|
+
)
|
|
111
|
+
self._pool, self._pool_loop = pool, loop
|
|
112
|
+
return pool
|
|
113
|
+
|
|
114
|
+
async def append(self, key: SessionKey, entries: list[SessionStoreEntry]) -> None:
|
|
115
|
+
if not entries:
|
|
116
|
+
return
|
|
117
|
+
pool = await self._get_pool()
|
|
118
|
+
# One multi-row INSERT per batch: atomic, and in batch order.
|
|
119
|
+
await pool.execute(
|
|
120
|
+
f"""
|
|
121
|
+
INSERT INTO {self._table} (project_key, session_id, subpath, entry, mtime)
|
|
122
|
+
SELECT $1, $2, $3, e,
|
|
123
|
+
(EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint
|
|
124
|
+
FROM unnest($4::jsonb[]) WITH ORDINALITY AS t(e, ord)
|
|
125
|
+
ORDER BY ord
|
|
126
|
+
""",
|
|
127
|
+
key["project_key"],
|
|
128
|
+
key["session_id"],
|
|
129
|
+
key.get("subpath") or "",
|
|
130
|
+
[json.dumps(e) for e in entries],
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
async def load(self, key: SessionKey) -> list[SessionStoreEntry] | None:
|
|
134
|
+
pool = await self._get_pool()
|
|
135
|
+
rows = await pool.fetch(
|
|
136
|
+
f"""
|
|
137
|
+
SELECT entry FROM {self._table}
|
|
138
|
+
WHERE project_key = $1 AND session_id = $2 AND subpath = $3
|
|
139
|
+
ORDER BY seq
|
|
140
|
+
""",
|
|
141
|
+
key["project_key"],
|
|
142
|
+
key["session_id"],
|
|
143
|
+
key.get("subpath") or "",
|
|
144
|
+
)
|
|
145
|
+
# jsonb reorders object keys; the SessionStore contract allows that.
|
|
146
|
+
return [json.loads(row["entry"]) for row in rows] or None
|
|
147
|
+
|
|
148
|
+
async def list_subkeys(self, key: SessionListSubkeysKey) -> list[str]:
|
|
149
|
+
"""Subagent transcripts of a session, so they are restored on resume."""
|
|
150
|
+
pool = await self._get_pool()
|
|
151
|
+
rows = await pool.fetch(
|
|
152
|
+
f"""
|
|
153
|
+
SELECT DISTINCT subpath FROM {self._table}
|
|
154
|
+
WHERE project_key = $1 AND session_id = $2 AND subpath <> ''
|
|
155
|
+
""",
|
|
156
|
+
key["project_key"],
|
|
157
|
+
key["session_id"],
|
|
158
|
+
)
|
|
159
|
+
return [row["subpath"] for row in rows]
|
|
160
|
+
|
|
161
|
+
async def exists(self, key: SessionKey) -> bool:
|
|
162
|
+
"""Whether the key has a transcript, without loading it."""
|
|
163
|
+
pool = await self._get_pool()
|
|
164
|
+
return await pool.fetchval(
|
|
165
|
+
f"""
|
|
166
|
+
SELECT EXISTS (
|
|
167
|
+
SELECT 1 FROM {self._table}
|
|
168
|
+
WHERE project_key = $1 AND session_id = $2 AND subpath = $3
|
|
169
|
+
)
|
|
170
|
+
""",
|
|
171
|
+
key["project_key"],
|
|
172
|
+
key["session_id"],
|
|
173
|
+
key.get("subpath") or "",
|
|
174
|
+
)
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
"""Project settings."""
|
|
16
|
+
|
|
17
|
+
# The agent's name in traces and analytics. Keep in sync with
|
|
18
|
+
# create_params.root_agent_name in agents-cli-manifest.yaml.
|
|
19
|
+
AGENT_NAME: str = "{{cookiecutter.root_agent_name}}"
|
|
20
|
+
|
|
21
|
+
# The agents-cli version that created this project. Model calls send it in the
|
|
22
|
+
# x-goog-api-client header so Google can count traffic from agents-cli projects;
|
|
23
|
+
# set DO_NOT_TRACK=1 or AGENTS_CLI_TELEMETRY=0 to stop sending it.
|
|
24
|
+
AGENTS_CLI_VERSION: str = "{{cookiecutter.package_version}}"
|
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
"""OpenTelemetry setup: traces, logs and metrics to Google Cloud over OTLP.
|
|
16
|
+
|
|
17
|
+
Without GCP credentials, only the instrumentation runs. Each signal lives in
|
|
18
|
+
its own module; setup_telemetry() wires them together.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
import os
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from dotenv import load_dotenv
|
|
28
|
+
|
|
29
|
+
from app.app_utils.telemetry import (
|
|
30
|
+
cli_relay,
|
|
31
|
+
config,
|
|
32
|
+
logs,
|
|
33
|
+
metrics,
|
|
34
|
+
request_flush,
|
|
35
|
+
traces,
|
|
36
|
+
)
|
|
37
|
+
from app.app_utils.telemetry.cli_relay import cli_telemetry_env
|
|
38
|
+
from app.app_utils.telemetry.logs import emit_event
|
|
39
|
+
from app.app_utils.telemetry.request_flush import FlushTelemetryMiddleware
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"FASTAPI_TELEMETRY",
|
|
43
|
+
"FlushTelemetryMiddleware",
|
|
44
|
+
"cli_telemetry_env",
|
|
45
|
+
"emit_event",
|
|
46
|
+
"setup_telemetry",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
# Off so every request starts its own trace instead of continuing traceparent.
|
|
50
|
+
FASTAPI_TELEMETRY = {"tracing": False, "metrics": False, "logs": False}
|
|
51
|
+
|
|
52
|
+
_initialized = False
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def setup_telemetry() -> None:
|
|
56
|
+
"""Configure trace export and instrumentation (idempotent)."""
|
|
57
|
+
global _initialized
|
|
58
|
+
if _initialized:
|
|
59
|
+
return
|
|
60
|
+
_initialized = True
|
|
61
|
+
# Runs at import, before anything else loads .env.
|
|
62
|
+
load_dotenv()
|
|
63
|
+
|
|
64
|
+
exporting = False
|
|
65
|
+
if not config.cloud_export_enabled():
|
|
66
|
+
logging.info(
|
|
67
|
+
"Cloud telemetry export disabled by "
|
|
68
|
+
"GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY."
|
|
69
|
+
)
|
|
70
|
+
else:
|
|
71
|
+
try:
|
|
72
|
+
_setup_cloud_exporters()
|
|
73
|
+
exporting = True
|
|
74
|
+
except Exception as e: # no GCP creds (local dev)
|
|
75
|
+
logging.warning("Cloud telemetry export not configured: %s", e)
|
|
76
|
+
if not exporting:
|
|
77
|
+
# OpenInference fails the turn when it ends a non-recording span with
|
|
78
|
+
# gen_ai.* attributes on.
|
|
79
|
+
os.environ.setdefault("OPENINFERENCE_ENABLE_GENAI_SEMCONV", "false")
|
|
80
|
+
traces.install_instrumentation()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _setup_cloud_exporters() -> None:
|
|
84
|
+
"""Export traces (the server's and the CLI's), logs and metrics to Cloud."""
|
|
85
|
+
from opentelemetry import trace
|
|
86
|
+
|
|
87
|
+
credentials, project_id = _default_credentials()
|
|
88
|
+
resource = config.build_resource(project_id)
|
|
89
|
+
|
|
90
|
+
tracer_provider = traces.setup_cloud_tracing(credentials, resource, project_id)
|
|
91
|
+
tracer_provider.add_span_processor(metrics.MetricsProcessor())
|
|
92
|
+
trace.set_tracer_provider(tracer_provider)
|
|
93
|
+
|
|
94
|
+
logger_provider = logs.setup_cloud_logging(credentials, resource, project_id)
|
|
95
|
+
reader = metrics.setup_cloud_metrics(credentials, resource)
|
|
96
|
+
if reader is not None:
|
|
97
|
+
request_flush.enable_request_flush(tracer_provider, logger_provider, reader)
|
|
98
|
+
|
|
99
|
+
cli_relay.enable_cli_export(credentials, project_id)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _default_credentials() -> tuple[Any, str]:
|
|
103
|
+
"""Application Default Credentials, and the project to export to."""
|
|
104
|
+
import google.auth
|
|
105
|
+
|
|
106
|
+
credentials, adc_project = google.auth.default(
|
|
107
|
+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
|
|
108
|
+
)
|
|
109
|
+
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT") or adc_project
|
|
110
|
+
if not project_id:
|
|
111
|
+
raise RuntimeError(
|
|
112
|
+
"no Google Cloud project; set GOOGLE_CLOUD_PROJECT to export traces"
|
|
113
|
+
)
|
|
114
|
+
return credentials, project_id
|
|
@@ -0,0 +1,44 @@
|
|
|
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
|
+
|
|
16
|
+
"""Records gen_ai.invoke_agent.inference_calls and .tool_calls for one turn."""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
|
|
22
|
+
from app.app_utils.telemetry import metrics
|
|
23
|
+
from app.app_utils.turn_events import Event, ModelCallEnded, ToolCallStarted, TurnEnded
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CallCounts:
|
|
27
|
+
"""Counts one turn's model and tool calls per agent, and records them at its end."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, agent_name: Callable[[str | None], str]) -> None:
|
|
30
|
+
self._agent_name = agent_name
|
|
31
|
+
# The main agent always gets a point, even with no calls.
|
|
32
|
+
self._model_calls: dict[str | None, int] = {None: 0}
|
|
33
|
+
self._tool_calls: dict[str | None, int] = {None: 0}
|
|
34
|
+
|
|
35
|
+
def handle(self, event: Event) -> None:
|
|
36
|
+
if isinstance(event, ModelCallEnded):
|
|
37
|
+
self._model_calls[event.agent] = self._model_calls.get(event.agent, 0) + 1
|
|
38
|
+
elif isinstance(event, ToolCallStarted):
|
|
39
|
+
self._tool_calls[event.agent] = self._tool_calls.get(event.agent, 0) + 1
|
|
40
|
+
elif isinstance(event, TurnEnded):
|
|
41
|
+
metrics.record_call_counts(
|
|
42
|
+
(self._agent_name(agent), model_calls, self._tool_calls.get(agent, 0))
|
|
43
|
+
for agent, model_calls in self._model_calls.items()
|
|
44
|
+
)
|