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.
Files changed (107) hide show
  1. core/claude/README.md +35 -0
  2. core/claude/template/.agents/skills/agents-cli-claude/SKILL.md +106 -0
  3. core/claude/template/.agents/skills/agents-cli-claude/references/claude.md +386 -0
  4. core/claude/template/.agents/skills/agents-cli-claude/references/migrate-claude-agent.md +318 -0
  5. core/claude/template/.agents/skills/agents-cli-claude/references/migrate-from-aws.md +132 -0
  6. core/claude/template/.dockerignore +28 -0
  7. core/claude/template/.env +18 -0
  8. core/claude/template/.env.example +17 -0
  9. core/claude/template/.template/templateconfig.yaml +31 -0
  10. core/claude/template/AGENTS.md +33 -0
  11. core/claude/template/Dockerfile +55 -0
  12. core/claude/template/agent_config/README.md +9 -0
  13. core/claude/template/agents-cli-extension.yaml +49 -0
  14. core/claude/template/app/__init__.py +15 -0
  15. core/claude/template/app/agent.py +49 -0
  16. core/claude/template/app/app_utils/a2a.py +245 -0
  17. core/claude/template/app/app_utils/bq_analytics/__init__.py +124 -0
  18. core/claude/template/app/app_utils/bq_analytics/recorder.py +593 -0
  19. core/claude/template/app/app_utils/bq_analytics/redaction.py +209 -0
  20. core/claude/template/app/app_utils/bq_analytics/schema.py +394 -0
  21. core/claude/template/app/app_utils/bq_analytics/tables.py +104 -0
  22. core/claude/template/app/app_utils/bq_analytics/uploader.py +188 -0
  23. core/claude/template/app/app_utils/claude.py +297 -0
  24. core/claude/template/app/app_utils/completions.py +225 -0
  25. core/claude/template/app/app_utils/conversation.py +29 -0
  26. core/claude/template/app/app_utils/memory_bank.py +308 -0
  27. core/claude/template/app/app_utils/project_settings.py +91 -0
  28. core/claude/template/app/app_utils/reasoning_engine.py +237 -0
  29. core/claude/template/app/app_utils/remote_agents.py +349 -0
  30. core/claude/template/app/app_utils/remote_auth.py +159 -0
  31. core/claude/template/app/app_utils/replies.py +143 -0
  32. core/claude/template/app/app_utils/session_store.py +174 -0
  33. core/claude/template/app/app_utils/settings.py +24 -0
  34. core/claude/template/app/app_utils/telemetry/__init__.py +114 -0
  35. core/claude/template/app/app_utils/telemetry/call_counts.py +44 -0
  36. core/claude/template/app/app_utils/telemetry/cli_relay.py +266 -0
  37. core/claude/template/app/app_utils/telemetry/config.py +133 -0
  38. core/claude/template/app/app_utils/telemetry/logs.py +175 -0
  39. core/claude/template/app/app_utils/telemetry/metrics.py +270 -0
  40. core/claude/template/app/app_utils/telemetry/request_flush.py +104 -0
  41. core/claude/template/app/app_utils/telemetry/subagent_spans.py +80 -0
  42. core/claude/template/app/app_utils/telemetry/traces.py +166 -0
  43. core/claude/template/app/app_utils/turn_events.py +463 -0
  44. core/claude/template/app/app_utils/turn_options.py +219 -0
  45. core/claude/template/app/app_utils/workspaces.py +65 -0
  46. core/claude/template/app/fast_api_app.py +71 -0
  47. core/claude/template/app/feature_tools.py +27 -0
  48. core/claude/template/pyproject.toml +100 -0
  49. core/claude/template/scripts/eval_generate.py +340 -0
  50. core/claude/template/scripts/publish.py +66 -0
  51. core/claude/template/scripts/run.py +85 -0
  52. core/claude/template/scripts/unsupported.py +48 -0
  53. core/claude/template/tests/eval/datasets/basic-dataset.json +31 -0
  54. core/claude/template/tests/eval/eval_config.yaml +17 -0
  55. core/claude/template/tests/eval/response_quality.py +60 -0
  56. core/claude/template/tests/integration/test_server_e2e.py +168 -0
  57. core/claude/template/tests/load_test/.results/.placeholder +0 -0
  58. core/claude/template/tests/load_test/README.md +24 -0
  59. core/claude/template/tests/load_test/load_test.py +118 -0
  60. core/claude/template/tests/unit/conftest.py +63 -0
  61. core/claude/template/tests/unit/helpers.py +32 -0
  62. core/claude/template/tests/unit/test_a2a.py +432 -0
  63. core/claude/template/tests/unit/test_bq_analytics.py +928 -0
  64. core/claude/template/tests/unit/test_bq_redaction.py +89 -0
  65. core/claude/template/tests/unit/test_claude.py +825 -0
  66. core/claude/template/tests/unit/test_completions.py +369 -0
  67. core/claude/template/tests/unit/test_fast_api_app.py +59 -0
  68. core/claude/template/tests/unit/test_feature_tools.py +55 -0
  69. core/claude/template/tests/unit/test_memory_bank.py +625 -0
  70. core/claude/template/tests/unit/test_reasoning_engine.py +295 -0
  71. core/claude/template/tests/unit/test_remote_agents.py +517 -0
  72. core/claude/template/tests/unit/test_telemetry.py +991 -0
  73. core/claude/template/tests/unit/test_turn_events.py +309 -0
  74. core/claude/template/tests/unit/test_turn_options.py +394 -0
  75. core/claude/template/uv.lock +3029 -0
  76. core/langchain/README.md +54 -0
  77. core/langchain/template/.agents/skills/agents-cli-langchain/SKILL.md +84 -0
  78. core/langchain/template/.agents/skills/agents-cli-langchain/references/langchain.md +120 -0
  79. core/langchain/template/.agents/skills/agents-cli-langchain/references/samples.md +42 -0
  80. core/langchain/template/.template/templateconfig.yaml +32 -0
  81. core/langchain/template/AGENTS.md +35 -0
  82. core/langchain/template/agents-cli-extension.yaml +54 -0
  83. core/langchain/template/app/__init__.py +19 -0
  84. core/langchain/template/app/agent.py +61 -0
  85. core/langchain/template/app/app_utils/a2a.py +176 -0
  86. core/langchain/template/app/app_utils/content.py +37 -0
  87. core/langchain/template/app/app_utils/telemetry.py +154 -0
  88. core/langchain/template/app/fast_api_app.py +68 -0
  89. core/langchain/template/langgraph.json +7 -0
  90. core/langchain/template/pyproject.toml +102 -0
  91. core/langchain/template/scripts/_content.py +40 -0
  92. core/langchain/template/scripts/eval_generate.py +202 -0
  93. core/langchain/template/scripts/publish.py +59 -0
  94. core/langchain/template/scripts/run.py +59 -0
  95. core/langchain/template/scripts/unsupported.py +48 -0
  96. core/langchain/template/tests/eval/datasets/basic-dataset.json +16 -0
  97. core/langchain/template/tests/eval/eval_config.yaml +32 -0
  98. core/langchain/template/tests/eval/response_quality.py +60 -0
  99. core/langchain/template/tests/integration/test_server_e2e.py +173 -0
  100. core/langchain/template/tests/load_test/.results/.placeholder +0 -0
  101. core/langchain/template/tests/load_test/README.md +20 -0
  102. core/langchain/template/tests/load_test/load_test.py +82 -0
  103. core/langchain/template/uv.lock +3820 -0
  104. google_agents_cli_extensions-1.14.2.dist-info/METADATA +133 -0
  105. google_agents_cli_extensions-1.14.2.dist-info/RECORD +107 -0
  106. google_agents_cli_extensions-1.14.2.dist-info/WHEEL +4 -0
  107. google_agents_cli_extensions-1.14.2.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,49 @@
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
+ # yaml-language-server: $schema=https://raw.githubusercontent.com/google/agents-cli/main/schemas/agents-cli-extension-v1alpha1.schema.json
16
+
17
+ schema: agents-cli-extension/v1alpha1
18
+ name: claude
19
+ description: Run Claude Agent SDK agents through the agents-cli lifecycle.
20
+
21
+ requires:
22
+ agents_cli: ">=1.14,<2"
23
+
24
+ commands:
25
+ override:
26
+ run:
27
+ run: ["uv", "run", "python", "scripts/run.py"]
28
+ description: Run the agent with a single prompt, in process.
29
+
30
+ # Old command name, so older CLIs apply it too; newer ones map it to `publish gemini`.
31
+ publish.gemini-enterprise:
32
+ run: ["uv", "run", "--with", "pyyaml", "python", "scripts/publish.py"]
33
+ description: Register over A2A; refuse on Agent Runtime, which needs ADK.
34
+
35
+ eval.generate:
36
+ run: ["uv", "run", "--with", "pyyaml", "python", "scripts/eval_generate.py"]
37
+ description: Generate eval traces from the agent (EvaluationDataset shape).
38
+
39
+ playground:
40
+ run: ["uv", "run", "python", "scripts/unsupported.py", "playground"]
41
+ description: Unsupported for Claude agents (the SDK has no local dev UI).
42
+
43
+ eval.dataset:
44
+ run: ["uv", "run", "python", "scripts/unsupported.py", "eval dataset"]
45
+ description: Unsupported for Claude agents (needs an ADK agent to introspect).
46
+
47
+ eval.optimize:
48
+ run: ["uv", "run", "python", "scripts/unsupported.py", "eval optimize"]
49
+ description: Unsupported for Claude agents (needs an ADK agent to introspect).
@@ -0,0 +1,15 @@
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
+ # https://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
+ """Claude Agent SDK agent package."""
@@ -0,0 +1,49 @@
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
+ # https://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
+ """Claude Agent SDK agent: a weather assistant with one custom tool.
16
+
17
+ Uses Claude on Gemini platform with Application Default Credentials; the model
18
+ must be enabled in Model Garden.
19
+ """
20
+
21
+ from typing import Any
22
+
23
+ from claude_agent_sdk import ClaudeAgentOptions, create_sdk_mcp_server, tool
24
+
25
+ from app.feature_tools import FEATURE_MCP_SERVERS, FEATURE_TOOLS
26
+
27
+
28
+ @tool("get_weather", "Get the current weather for a city.", {"city": str})
29
+ async def get_weather(args: dict[str, Any]) -> dict[str, Any]:
30
+ city = args["city"]
31
+ if "sf" in city.lower() or "san francisco" in city.lower():
32
+ forecast = "It's 60 degrees and foggy."
33
+ else:
34
+ forecast = "It's 90 degrees and sunny."
35
+ return {"content": [{"type": "text", "text": forecast}]}
36
+
37
+
38
+ weather_server = create_sdk_mcp_server(name="weather", tools=[get_weather])
39
+
40
+ root_agent = ClaudeAgentOptions(
41
+ model="claude-haiku-4-5",
42
+ # The CLI prepends "You are Claude Code...": give the agent its own name.
43
+ system_prompt="You are Skye, a helpful assistant. Use get_weather for weather questions.",
44
+ mcp_servers={"weather": weather_server, **FEATURE_MCP_SERVERS},
45
+ # No built-in Claude Code tools (Bash, Read, Write, ...); allow only these.
46
+ tools=[],
47
+ allowed_tools=["mcp__weather__get_weather", *FEATURE_TOOLS],
48
+ max_turns=10,
49
+ )
@@ -0,0 +1,245 @@
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
+ # https://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
+ """A2A protocol layer: the executor, the agent card, and the routes."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import logging
21
+ import os
22
+ import uuid
23
+ from contextlib import aclosing
24
+
25
+ from a2a.helpers import new_task_from_user_message
26
+ from a2a.server.agent_execution import AgentExecutor, RequestContext
27
+ from a2a.server.events import EventQueue
28
+ from a2a.server.request_handlers import DefaultRequestHandler
29
+ from a2a.server.routes import (
30
+ add_a2a_routes_to_fastapi,
31
+ create_agent_card_routes,
32
+ create_jsonrpc_routes,
33
+ )
34
+ from a2a.server.tasks import InMemoryTaskStore, TaskUpdater
35
+ from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill, Part
36
+ from a2a.utils.constants import (
37
+ AGENT_CARD_WELL_KNOWN_PATH,
38
+ PROTOCOL_VERSION_0_3,
39
+ PROTOCOL_VERSION_1_0,
40
+ )
41
+ from claude_agent_sdk import Message
42
+ from fastapi import FastAPI
43
+ from opentelemetry import trace
44
+
45
+ from app.agent import root_agent
46
+ from app.app_utils import memory_bank
47
+ from app.app_utils.claude import stream_turn
48
+ from app.app_utils.replies import TurnReply, record, starts_block, text_delta
49
+ from app.app_utils.telemetry.config import on_agent_runtime
50
+
51
+ # Matches the `agents-cli run --mode a2a --app-name` default.
52
+ _A2A_NAME = os.environ.get("A2A_NAME", "app")
53
+ _A2A_RPC_PATH = f"/a2a/{_A2A_NAME}"
54
+
55
+
56
+ def add_a2a_routes(app: FastAPI) -> None:
57
+ """Mount the JSON-RPC endpoint and the agent card on the app."""
58
+ agent_card = _agent_card()
59
+ request_handler = DefaultRequestHandler(
60
+ agent_executor=ClaudeAgentExecutor(),
61
+ task_store=InMemoryTaskStore(),
62
+ agent_card=agent_card,
63
+ )
64
+ add_a2a_routes_to_fastapi(
65
+ app,
66
+ agent_card_routes=create_agent_card_routes(
67
+ agent_card, card_url=f"{_A2A_RPC_PATH}{AGENT_CARD_WELL_KNOWN_PATH}"
68
+ ),
69
+ jsonrpc_routes=create_jsonrpc_routes(
70
+ request_handler, rpc_url=_A2A_RPC_PATH, enable_v0_3_compat=True
71
+ ),
72
+ )
73
+
74
+
75
+ class ClaudeAgentExecutor(AgentExecutor):
76
+ """Bridge the A2A request lifecycle to a Claude Agent SDK turn."""
77
+
78
+ async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
79
+ task = context.current_task
80
+ if task is None:
81
+ # The Task must be queued before any status update.
82
+ task = new_task_from_user_message(context.message)
83
+ await event_queue.enqueue_event(task)
84
+ updater = TaskUpdater(event_queue, task.id, task.context_id)
85
+ await updater.start_work()
86
+
87
+ structured = root_agent.output_format is not None
88
+ artifact = _ResponseArtifact(updater, stream_text=not structured)
89
+ reply = TurnReply()
90
+ turn_span = trace.INVALID_SPAN
91
+ try:
92
+ async with aclosing(
93
+ stream_turn(
94
+ context.get_user_input(),
95
+ root_agent,
96
+ task.context_id,
97
+ # As ADK names unauthenticated callers.
98
+ _caller(context) or f"A2A_USER_{task.context_id}",
99
+ )
100
+ ) as stream:
101
+ async for message in stream:
102
+ turn_span = trace.get_current_span()
103
+ await artifact.add(message)
104
+ reply = record(reply, message)
105
+ except Exception as e:
106
+ # Log under the ended turn span so the record links to its trace.
107
+ with trace.use_span(turn_span):
108
+ logging.exception("Claude agent turn failed")
109
+ await updater.failed(
110
+ updater.new_agent_message([Part(text=f"Agent error: {e}")])
111
+ )
112
+ return
113
+
114
+ await artifact.finish(_final_reply(reply, artifact.answer, structured))
115
+ if on_agent_runtime():
116
+ # Agent Runtime throttles the CPU once the response ends.
117
+ await memory_bank.flush()
118
+ await updater.complete()
119
+
120
+ async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
121
+ await TaskUpdater(event_queue, context.task_id, context.context_id).cancel()
122
+
123
+
124
+ class _ResponseArtifact:
125
+ """The "response" artifact a turn's text deltas stream into."""
126
+
127
+ def __init__(self, updater: TaskUpdater, *, stream_text: bool) -> None:
128
+ self._updater = updater
129
+ self._stream_text = stream_text
130
+ self._id = uuid.uuid4().hex
131
+ self._started = False
132
+ self._separator = ""
133
+ self._answer: list[str] = []
134
+
135
+ @property
136
+ def answer(self) -> str:
137
+ """The text streamed since the last tool call."""
138
+ return "".join(self._answer)
139
+
140
+ async def add(self, message: Message) -> None:
141
+ """Stream the text `message` adds, separating text blocks with a blank line."""
142
+ if self._started and starts_block(message, "text"):
143
+ self._separator = "\n\n"
144
+ if starts_block(message, "tool_use"):
145
+ self._answer = []
146
+ if not self._stream_text or not (text := text_delta(message)):
147
+ return
148
+ await self._updater.add_artifact(
149
+ [Part(text=self._separator + text)],
150
+ artifact_id=self._id,
151
+ name="response",
152
+ append=self._started,
153
+ last_chunk=False,
154
+ )
155
+ self._started = True
156
+ self._answer.append((self._separator if self._answer else "") + text)
157
+ self._separator = ""
158
+
159
+ async def finish(self, reply: str) -> None:
160
+ """Send `reply` as the last chunk, replacing the streamed ones.
161
+
162
+ Some clients keep only the last chunk, so it carries the whole reply.
163
+ """
164
+ if reply:
165
+ await self._updater.add_artifact(
166
+ [Part(text=reply)],
167
+ artifact_id=self._id,
168
+ name="response",
169
+ append=False,
170
+ last_chunk=True,
171
+ )
172
+
173
+
174
+ def _final_reply(reply: TurnReply, answer: str, structured: bool) -> str:
175
+ """The reply a caller gets once the turn has finished.
176
+
177
+ With `output_format` set, it's the structured output as JSON. Otherwise it's
178
+ `answer`, the text streamed after the last tool call, so the model's narration
179
+ before a tool call is dropped; a turn that streamed no text falls back to the
180
+ turn's reply.
181
+ """
182
+ if structured and reply.result and reply.result.structured_output is not None:
183
+ return json.dumps(reply.result.structured_output)
184
+ return answer or reply.text
185
+
186
+
187
+ def _agent_card() -> AgentCard:
188
+ rpc_url = f"{advertised_base_url()}{_A2A_RPC_PATH}"
189
+ return AgentCard(
190
+ name=_A2A_NAME,
191
+ description="A Claude Agent SDK agent served over the A2A protocol.",
192
+ supported_interfaces=[
193
+ AgentInterface(
194
+ url=rpc_url,
195
+ protocol_binding="JSONRPC",
196
+ protocol_version=PROTOCOL_VERSION_1_0,
197
+ ),
198
+ # Gemini's registration validator still requires the 0.3 card shape.
199
+ AgentInterface(
200
+ url=rpc_url,
201
+ protocol_binding="JSONRPC",
202
+ protocol_version=PROTOCOL_VERSION_0_3,
203
+ ),
204
+ ],
205
+ version=os.environ.get("AGENT_VERSION", "0.1.0"),
206
+ default_input_modes=["text/plain"],
207
+ default_output_modes=["text/plain"],
208
+ capabilities=AgentCapabilities(streaming=True),
209
+ skills=[
210
+ AgentSkill(
211
+ id="chat",
212
+ name="chat",
213
+ description="Hold a conversation with the agent.",
214
+ tags=["chat", "claude"],
215
+ )
216
+ ],
217
+ )
218
+
219
+
220
+ def advertised_base_url() -> str:
221
+ """Base URL for the agent card."""
222
+ if app_url := os.environ.get("APP_URL"):
223
+ return app_url
224
+ # APP_URL can be unset on a first Agent Runtime deploy.
225
+ engine_id = os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ID")
226
+ location = os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_LOCATION")
227
+ project = os.environ.get("GOOGLE_CLOUD_PROJECT")
228
+ if engine_id and location and project:
229
+ return (
230
+ f"https://{location}-aiplatform.googleapis.com/reasoningEngines/v1"
231
+ f"/projects/{project}/locations/{location}"
232
+ f"/reasoningEngines/{engine_id}/api"
233
+ )
234
+ host = os.environ.get("HOST", "127.0.0.1")
235
+ if host in ("0.0.0.0", "::", ""):
236
+ host = "127.0.0.1"
237
+ return f"http://{host}:{os.environ.get('PORT', '8080')}"
238
+
239
+
240
+ def _caller(context: RequestContext) -> str | None:
241
+ """The authenticated caller's name; unauthenticated names are ignored."""
242
+ user = context.call_context.user if context.call_context else None
243
+ if user and user.user_name and user.is_authenticated:
244
+ return user.user_name
245
+ return None
@@ -0,0 +1,124 @@
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
+ """Write each turn's events to BigQuery Agent Analytics (`agent_events`).
16
+
17
+ Enabled when BQ_ANALYTICS_DATASET_ID is set. Rows are written on a background
18
+ thread, so a turn never waits on BigQuery.
19
+
20
+ - recorder.py turns a turn's events into rows.
21
+ - uploader.py streams the rows to BigQuery; tables.py creates the table and views.
22
+ - schema.py is ADK's table schema and view definitions.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ import os
29
+ import threading
30
+ from collections.abc import Callable
31
+ from typing import Any
32
+
33
+ from app.app_utils.bq_analytics.recorder import AgentEventsRecorder
34
+ from app.app_utils.bq_analytics.uploader import Writer
35
+ from app.app_utils.remote_agents import remote_agent_url
36
+
37
+ __all__ = ["flush", "start_turn", "writer"]
38
+
39
+ _writer: Writer | None = None
40
+ _writer_failed = False
41
+ _writer_lock = threading.Lock()
42
+
43
+
44
+ def writer() -> Writer | None:
45
+ """The process's writer, or None when BQ_ANALYTICS_DATASET_ID is unset."""
46
+ global _writer, _writer_failed
47
+ dataset = os.environ.get("BQ_ANALYTICS_DATASET_ID")
48
+ if not dataset or _writer_failed:
49
+ return None
50
+ with _writer_lock:
51
+ if _writer is None and not _writer_failed:
52
+ try:
53
+ _writer = Writer(_project(), dataset)
54
+ except Exception as e: # analytics must never stop the agent
55
+ logging.warning(
56
+ "BigQuery Agent Analytics is off: %s. It needs Google Cloud "
57
+ "credentials and a project (GOOGLE_CLOUD_PROJECT).",
58
+ e,
59
+ )
60
+ _writer_failed = True
61
+ return _writer
62
+
63
+
64
+ def flush(timeout: float) -> None:
65
+ """Wait for queued rows, when the writer is running."""
66
+ if _writer is not None:
67
+ _writer.flush(timeout)
68
+
69
+
70
+ def start_turn(
71
+ prompt: str,
72
+ options: Any,
73
+ session_id: str,
74
+ conversation_id: str,
75
+ user_id: str | None,
76
+ agent_name: Callable[[str | None], str],
77
+ *,
78
+ instruction: Any,
79
+ ) -> AgentEventsRecorder | None:
80
+ """A recorder for one turn run with `options`, or None when analytics is off.
81
+
82
+ Args:
83
+ instruction: The agent's own system prompt, without recalled memories.
84
+ """
85
+ out = writer()
86
+ if out is None:
87
+ return None
88
+ servers = options.mcp_servers if isinstance(options.mcp_servers, dict) else {}
89
+ remote = {
90
+ name: url
91
+ for name, config in servers.items()
92
+ if isinstance(config, dict) and (url := remote_agent_url(config)) is not None
93
+ }
94
+ # In-process @tool servers count as the agent's own (LOCAL) tools.
95
+ local = {
96
+ name
97
+ for name, config in servers.items()
98
+ if isinstance(config, dict)
99
+ and config.get("type") == "sdk"
100
+ and name not in remote
101
+ }
102
+ return AgentEventsRecorder(
103
+ out,
104
+ prompt=prompt,
105
+ agent_name=agent_name,
106
+ session_id=session_id,
107
+ user_id=user_id or f"A2A_USER_{conversation_id}",
108
+ model=options.model,
109
+ system_prompt=options.system_prompt,
110
+ instruction=instruction,
111
+ remote_agents=remote,
112
+ local_servers=local,
113
+ )
114
+
115
+
116
+ def _project() -> str:
117
+ project = os.environ.get("GOOGLE_CLOUD_PROJECT")
118
+ if not project:
119
+ import google.auth
120
+
121
+ _, project = google.auth.default()
122
+ if not project:
123
+ raise ValueError("no Google Cloud project found")
124
+ return project