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,463 @@
|
|
|
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
|
+
"""Group one turn's SDK messages into model calls, tool calls and subagent runs.
|
|
16
|
+
|
|
17
|
+
BigQuery Agent Analytics, prompt-response logging and the call-count metrics all
|
|
18
|
+
read a turn through this parser. Every turn ends with one TurnEnded event, even
|
|
19
|
+
when the parser stopped reading the turn's messages. It handles the CLI's message
|
|
20
|
+
quirks once:
|
|
21
|
+
|
|
22
|
+
- one AssistantMessage per content block of a model call, all with its message_id;
|
|
23
|
+
- the final usage and stop reason arrive later, in a message_delta stream event;
|
|
24
|
+
- tool results can arrive before message_stop;
|
|
25
|
+
- subagent messages carry parent_tool_use_id and interleave with the main agent's;
|
|
26
|
+
- a background subagent ends at its task_notification, not at its tool result.
|
|
27
|
+
|
|
28
|
+
An agent is None for the main agent, else the id of the tool call that started
|
|
29
|
+
the subagent. `TurnParser.agent_name` names either.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import logging
|
|
35
|
+
import time
|
|
36
|
+
from collections.abc import Mapping
|
|
37
|
+
from dataclasses import dataclass, field
|
|
38
|
+
from typing import Any
|
|
39
|
+
|
|
40
|
+
from claude_agent_sdk import (
|
|
41
|
+
AssistantMessage,
|
|
42
|
+
ResultMessage,
|
|
43
|
+
StreamEvent,
|
|
44
|
+
SystemMessage,
|
|
45
|
+
ToolResultBlock,
|
|
46
|
+
ToolUseBlock,
|
|
47
|
+
UserMessage,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# "Task" in older Claude Code CLI versions.
|
|
51
|
+
SUBAGENT_TOOLS = ("Agent", "Task")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class ModelCallStarted:
|
|
56
|
+
agent: str | None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class ModelCallEnded:
|
|
61
|
+
agent: str | None
|
|
62
|
+
blocks: tuple[Any, ...]
|
|
63
|
+
usage: Mapping[str, Any]
|
|
64
|
+
model: str | None
|
|
65
|
+
stop_reason: str | None
|
|
66
|
+
# time.monotonic() of the last send to the model.
|
|
67
|
+
requested_at: float
|
|
68
|
+
first_token_at: float | None
|
|
69
|
+
# time.time_ns() when the call started.
|
|
70
|
+
started_ns: int
|
|
71
|
+
# Why the call failed (AssistantMessage.error, e.g. "rate_limit"), or None.
|
|
72
|
+
error: str | None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class ToolCallStarted:
|
|
77
|
+
agent: str | None
|
|
78
|
+
id: str
|
|
79
|
+
name: str
|
|
80
|
+
input: Any
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class ToolCallEnded:
|
|
85
|
+
agent: str | None
|
|
86
|
+
id: str
|
|
87
|
+
content: Any
|
|
88
|
+
is_error: bool
|
|
89
|
+
# Which SDK message delivered the result: results from one message belong together.
|
|
90
|
+
message_index: int
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class SubagentStarted:
|
|
95
|
+
id: str
|
|
96
|
+
prompt: str | None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass(frozen=True)
|
|
100
|
+
class SubagentEnded:
|
|
101
|
+
id: str
|
|
102
|
+
failed: bool
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass(frozen=True)
|
|
106
|
+
class SubagentPrompt:
|
|
107
|
+
agent: str
|
|
108
|
+
text: str
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class Compaction:
|
|
113
|
+
trigger: Any
|
|
114
|
+
pre_tokens: Any
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class TurnResult:
|
|
119
|
+
message: ResultMessage
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True)
|
|
123
|
+
class TurnEnded:
|
|
124
|
+
failed: bool
|
|
125
|
+
# None when the turn ended without an exception, or ended at its result.
|
|
126
|
+
error: BaseException | None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
Event = (
|
|
130
|
+
ModelCallStarted
|
|
131
|
+
| ModelCallEnded
|
|
132
|
+
| ToolCallStarted
|
|
133
|
+
| ToolCallEnded
|
|
134
|
+
| SubagentStarted
|
|
135
|
+
| SubagentEnded
|
|
136
|
+
| SubagentPrompt
|
|
137
|
+
| Compaction
|
|
138
|
+
| TurnResult
|
|
139
|
+
| TurnEnded
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass
|
|
144
|
+
class _Call:
|
|
145
|
+
agent: str | None
|
|
146
|
+
requested_at: float
|
|
147
|
+
started_ns: int = field(default_factory=time.time_ns)
|
|
148
|
+
seen: bool = False
|
|
149
|
+
message_id: str | None = None
|
|
150
|
+
blocks: list[Any] = field(default_factory=list)
|
|
151
|
+
message_usage: dict[str, Any] = field(default_factory=dict)
|
|
152
|
+
stream_usage: dict[str, Any] = field(default_factory=dict)
|
|
153
|
+
model: str | None = None
|
|
154
|
+
stop_reason: str | None = None
|
|
155
|
+
stream_stop_reason: str | None = None
|
|
156
|
+
first_token_at: float | None = None
|
|
157
|
+
error: str | None = None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@dataclass
|
|
161
|
+
class _Subagent:
|
|
162
|
+
prompt: str | None
|
|
163
|
+
boundary: float = field(default_factory=time.monotonic)
|
|
164
|
+
started: bool = False
|
|
165
|
+
call: _Call | None = None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class TurnParser:
|
|
169
|
+
"""Turns one turn's SDK messages into events; never raises."""
|
|
170
|
+
|
|
171
|
+
def __init__(self, main_agent: str) -> None:
|
|
172
|
+
self.result: ResultMessage | None = None
|
|
173
|
+
self._main_agent = main_agent
|
|
174
|
+
self._names: dict[str, str] = {}
|
|
175
|
+
self._tools: dict[str, ToolCallStarted] = {}
|
|
176
|
+
self._subagents: dict[str, _Subagent] = {}
|
|
177
|
+
# Subagents run as background tasks: they end at their task_notification.
|
|
178
|
+
self._tasks: set[str] = set()
|
|
179
|
+
self._call: _Call | None = None
|
|
180
|
+
self._streaming = False
|
|
181
|
+
# Messages that arrive while the main agent's call streams wait for its end.
|
|
182
|
+
self._held: list[tuple[int, Any]] = []
|
|
183
|
+
self._boundary = time.monotonic()
|
|
184
|
+
self._index = 0
|
|
185
|
+
self._broken = False
|
|
186
|
+
|
|
187
|
+
def agent_name(self, agent: str | None) -> str:
|
|
188
|
+
"""The display name of `agent`: the main agent, or a subagent."""
|
|
189
|
+
if agent is None:
|
|
190
|
+
return self._main_agent
|
|
191
|
+
return self._names.get(agent, "subagent")
|
|
192
|
+
|
|
193
|
+
def feed(self, message: Any) -> list[Event]:
|
|
194
|
+
"""The events this message completes, in order."""
|
|
195
|
+
self._index += 1
|
|
196
|
+
return self._guard(self._feed, self._index, message)
|
|
197
|
+
|
|
198
|
+
def finish(self, error: BaseException | None = None) -> list[Event]:
|
|
199
|
+
"""Close what is still open when the stream ends, then end the turn."""
|
|
200
|
+
out = self._guard(self._end_stream)
|
|
201
|
+
if isinstance(error, GeneratorExit) and self.result is not None:
|
|
202
|
+
# The caller stopped reading at the result: that is how the turn ended.
|
|
203
|
+
error = None
|
|
204
|
+
failed = error is not None or (self.result is not None and self.result.is_error)
|
|
205
|
+
out += self._guard(self._end_subagents, failed)
|
|
206
|
+
out.append(TurnEnded(failed, error))
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
def _guard(self, step: Any, *args: Any) -> list[Event]:
|
|
210
|
+
if self._broken:
|
|
211
|
+
return []
|
|
212
|
+
out: list[Event] = []
|
|
213
|
+
try:
|
|
214
|
+
step(*args, out)
|
|
215
|
+
except Exception:
|
|
216
|
+
logging.warning("Stopped reading the turn's messages", exc_info=True)
|
|
217
|
+
self._broken = True
|
|
218
|
+
return out
|
|
219
|
+
|
|
220
|
+
def _feed(self, index: int, message: Any, out: list[Event]) -> None:
|
|
221
|
+
if self._streaming and not isinstance(message, StreamEvent):
|
|
222
|
+
if not isinstance(message, AssistantMessage) or message.parent_tool_use_id:
|
|
223
|
+
self._held.append((index, message))
|
|
224
|
+
return
|
|
225
|
+
if isinstance(message, SystemMessage):
|
|
226
|
+
self._system(message, out)
|
|
227
|
+
elif isinstance(message, StreamEvent):
|
|
228
|
+
self._stream(message, out)
|
|
229
|
+
elif isinstance(message, (AssistantMessage, UserMessage)):
|
|
230
|
+
if message.parent_tool_use_id:
|
|
231
|
+
self._subagent_message(index, message, out)
|
|
232
|
+
elif isinstance(message, AssistantMessage):
|
|
233
|
+
if self._call is None:
|
|
234
|
+
self._call = self._start_call(None, self._boundary, out)
|
|
235
|
+
self._call = self._add_message(self._call, message)
|
|
236
|
+
else:
|
|
237
|
+
self._end_main_call(out)
|
|
238
|
+
self._boundary = time.monotonic()
|
|
239
|
+
self._tool_results(index, message, out)
|
|
240
|
+
elif isinstance(message, ResultMessage):
|
|
241
|
+
self._end_main_call(out)
|
|
242
|
+
self.result = message
|
|
243
|
+
out.append(TurnResult(message))
|
|
244
|
+
|
|
245
|
+
def _system(self, message: SystemMessage, out: list[Event]) -> None:
|
|
246
|
+
data = message.data if isinstance(message.data, dict) else {}
|
|
247
|
+
tool_use_id = str(data.get("tool_use_id") or "")
|
|
248
|
+
if message.subtype == "init":
|
|
249
|
+
self._boundary = time.monotonic()
|
|
250
|
+
elif message.subtype == "task_started":
|
|
251
|
+
# Can arrive before its tool call; the subagent starts with it.
|
|
252
|
+
self._tasks.add(tool_use_id)
|
|
253
|
+
sub = self._subagents.get(tool_use_id)
|
|
254
|
+
if sub is not None:
|
|
255
|
+
sub = self._start_subagent(tool_use_id, sub, out)
|
|
256
|
+
elif message.subtype == "task_notification":
|
|
257
|
+
sub = self._subagents.pop(tool_use_id, None)
|
|
258
|
+
if sub is not None:
|
|
259
|
+
failed = data.get("status") != "completed"
|
|
260
|
+
self._end_subagent(tool_use_id, sub, failed, out)
|
|
261
|
+
elif message.subtype == "compact_boundary":
|
|
262
|
+
metadata = data.get("compact_metadata") or {}
|
|
263
|
+
out.append(Compaction(metadata.get("trigger"), metadata.get("pre_tokens")))
|
|
264
|
+
|
|
265
|
+
def _stream(self, message: StreamEvent, out: list[Event]) -> None:
|
|
266
|
+
# Only the main agent's calls are streamed.
|
|
267
|
+
if message.parent_tool_use_id:
|
|
268
|
+
return
|
|
269
|
+
event = message.event
|
|
270
|
+
kind = event.get("type")
|
|
271
|
+
if kind == "message_start" and self._call is None:
|
|
272
|
+
self._call = self._start_call(None, self._boundary, out)
|
|
273
|
+
self._streaming = True
|
|
274
|
+
usage = (event.get("message") or {}).get("usage") or {}
|
|
275
|
+
self._call.stream_usage = dict(usage)
|
|
276
|
+
elif kind == "message_stop":
|
|
277
|
+
self._streaming = False
|
|
278
|
+
self._end_main_call(out)
|
|
279
|
+
held, self._held = self._held, []
|
|
280
|
+
for index, held_message in held:
|
|
281
|
+
self._feed(index, held_message, out)
|
|
282
|
+
elif self._call is None:
|
|
283
|
+
return
|
|
284
|
+
elif kind == "content_block_delta" and self._call.first_token_at is None:
|
|
285
|
+
self._call.first_token_at = time.monotonic()
|
|
286
|
+
elif kind == "message_delta":
|
|
287
|
+
usage = event.get("usage") or {}
|
|
288
|
+
self._call.stream_usage.update(
|
|
289
|
+
{k: v for k, v in usage.items() if v is not None}
|
|
290
|
+
)
|
|
291
|
+
self._call.stream_stop_reason = (event.get("delta") or {}).get(
|
|
292
|
+
"stop_reason"
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
def _subagent_message(
|
|
296
|
+
self, index: int, message: AssistantMessage | UserMessage, out: list[Event]
|
|
297
|
+
) -> None:
|
|
298
|
+
agent = message.parent_tool_use_id or ""
|
|
299
|
+
sub = self._subagents.get(agent)
|
|
300
|
+
if sub is None:
|
|
301
|
+
return
|
|
302
|
+
sub = self._start_subagent(agent, sub, out)
|
|
303
|
+
if isinstance(message, AssistantMessage):
|
|
304
|
+
if sub.call is not None and sub.call.message_id not in (
|
|
305
|
+
None,
|
|
306
|
+
message.message_id,
|
|
307
|
+
):
|
|
308
|
+
sub = self._end_subagent_call(sub, out)
|
|
309
|
+
if sub.call is None:
|
|
310
|
+
sub.call = self._start_call(agent, sub.boundary, out)
|
|
311
|
+
sub.call = self._add_message(sub.call, message)
|
|
312
|
+
return
|
|
313
|
+
sub = self._end_subagent_call(sub, out)
|
|
314
|
+
if isinstance(message.content, str):
|
|
315
|
+
out.append(SubagentPrompt(agent, message.content))
|
|
316
|
+
self._tool_results(index, message, out)
|
|
317
|
+
|
|
318
|
+
def _start_call(
|
|
319
|
+
self, agent: str | None, requested_at: float, out: list[Event]
|
|
320
|
+
) -> _Call:
|
|
321
|
+
out.append(ModelCallStarted(agent))
|
|
322
|
+
return _Call(agent, requested_at)
|
|
323
|
+
|
|
324
|
+
def _add_message(self, call: _Call, message: AssistantMessage) -> _Call:
|
|
325
|
+
call.seen = True
|
|
326
|
+
call.message_id = message.message_id
|
|
327
|
+
call.blocks.extend(message.content)
|
|
328
|
+
call.message_usage = dict(message.usage or {})
|
|
329
|
+
call.model = message.model
|
|
330
|
+
call.stop_reason = message.stop_reason
|
|
331
|
+
call.error = message.error or call.error
|
|
332
|
+
for block in message.content:
|
|
333
|
+
if isinstance(block, ToolUseBlock) and block.name in SUBAGENT_TOOLS:
|
|
334
|
+
# Named as soon as the call is seen, not when it ends: its
|
|
335
|
+
# subagent's span is claimed while the call is still open.
|
|
336
|
+
self._names[block.id] = subagent_name(block.input)
|
|
337
|
+
return call
|
|
338
|
+
|
|
339
|
+
def _end_main_call(self, out: list[Event]) -> None:
|
|
340
|
+
call, self._call = self._call, None
|
|
341
|
+
if call is not None:
|
|
342
|
+
self._end_call(call, out)
|
|
343
|
+
|
|
344
|
+
def _end_subagent_call(self, sub: _Subagent, out: list[Event]) -> _Subagent:
|
|
345
|
+
call, sub.call = sub.call, None
|
|
346
|
+
if call is not None:
|
|
347
|
+
self._end_call(call, out)
|
|
348
|
+
sub.boundary = time.monotonic()
|
|
349
|
+
return sub
|
|
350
|
+
|
|
351
|
+
def _end_call(self, call: _Call, out: list[Event]) -> None:
|
|
352
|
+
if not call.seen:
|
|
353
|
+
return
|
|
354
|
+
agent = call.agent
|
|
355
|
+
out.append(
|
|
356
|
+
ModelCallEnded(
|
|
357
|
+
agent=agent,
|
|
358
|
+
blocks=tuple(call.blocks),
|
|
359
|
+
usage={**call.message_usage, **call.stream_usage},
|
|
360
|
+
model=call.model,
|
|
361
|
+
stop_reason=call.stream_stop_reason or call.stop_reason,
|
|
362
|
+
requested_at=call.requested_at,
|
|
363
|
+
first_token_at=call.first_token_at,
|
|
364
|
+
started_ns=call.started_ns,
|
|
365
|
+
error=call.error,
|
|
366
|
+
)
|
|
367
|
+
)
|
|
368
|
+
for block in call.blocks:
|
|
369
|
+
if not isinstance(block, ToolUseBlock):
|
|
370
|
+
continue
|
|
371
|
+
started = ToolCallStarted(agent, block.id, block.name, block.input)
|
|
372
|
+
self._tools[block.id] = started
|
|
373
|
+
out.append(started)
|
|
374
|
+
if block.name in SUBAGENT_TOOLS:
|
|
375
|
+
prompt = (
|
|
376
|
+
block.input.get("prompt") if isinstance(block.input, dict) else None
|
|
377
|
+
)
|
|
378
|
+
sub = _Subagent(prompt)
|
|
379
|
+
self._subagents[block.id] = sub
|
|
380
|
+
if block.id in self._tasks: # its task_started came first
|
|
381
|
+
self._start_subagent(block.id, sub, out)
|
|
382
|
+
|
|
383
|
+
def _tool_results(self, index: int, message: UserMessage, out: list[Event]) -> None:
|
|
384
|
+
if not isinstance(message.content, list):
|
|
385
|
+
return
|
|
386
|
+
for block in message.content:
|
|
387
|
+
if not isinstance(block, ToolResultBlock):
|
|
388
|
+
continue
|
|
389
|
+
started = self._tools.pop(block.tool_use_id, None)
|
|
390
|
+
if started is None:
|
|
391
|
+
continue
|
|
392
|
+
sub = self._subagents.get(block.tool_use_id)
|
|
393
|
+
# A subagent that hasn't sent anything yet runs in the background:
|
|
394
|
+
# its result only says it started.
|
|
395
|
+
if (
|
|
396
|
+
sub is not None
|
|
397
|
+
and block.tool_use_id not in self._tasks
|
|
398
|
+
and (sub.started or block.is_error)
|
|
399
|
+
):
|
|
400
|
+
del self._subagents[block.tool_use_id]
|
|
401
|
+
self._end_subagent(block.tool_use_id, sub, bool(block.is_error), out)
|
|
402
|
+
out.append(
|
|
403
|
+
ToolCallEnded(
|
|
404
|
+
agent=started.agent,
|
|
405
|
+
id=started.id,
|
|
406
|
+
content=block.content,
|
|
407
|
+
is_error=bool(block.is_error),
|
|
408
|
+
message_index=index,
|
|
409
|
+
)
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
def _start_subagent(
|
|
413
|
+
self, tool_use_id: str, sub: _Subagent, out: list[Event]
|
|
414
|
+
) -> _Subagent:
|
|
415
|
+
if not sub.started:
|
|
416
|
+
sub.started = True
|
|
417
|
+
out.append(SubagentStarted(tool_use_id, sub.prompt))
|
|
418
|
+
return sub
|
|
419
|
+
|
|
420
|
+
def _end_subagent(
|
|
421
|
+
self, tool_use_id: str, sub: _Subagent, failed: bool, out: list[Event]
|
|
422
|
+
) -> None:
|
|
423
|
+
sub = self._start_subagent(tool_use_id, sub, out)
|
|
424
|
+
self._end_subagent_call(sub, out)
|
|
425
|
+
out.append(SubagentEnded(tool_use_id, failed))
|
|
426
|
+
|
|
427
|
+
def _end_stream(self, out: list[Event]) -> None:
|
|
428
|
+
if self._streaming or self._held:
|
|
429
|
+
self._streaming = False
|
|
430
|
+
held, self._held = self._held, []
|
|
431
|
+
self._end_main_call(out)
|
|
432
|
+
for index, message in held:
|
|
433
|
+
self._feed(index, message, out)
|
|
434
|
+
self._end_main_call(out)
|
|
435
|
+
|
|
436
|
+
def _end_subagents(self, failed: bool, out: list[Event]) -> None:
|
|
437
|
+
# Background subagents whose task never reported back end with the turn.
|
|
438
|
+
for tool_use_id, sub in list(self._subagents.items()):
|
|
439
|
+
self._end_subagent(tool_use_id, sub, failed, out)
|
|
440
|
+
self._subagents.clear()
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def subagent_name(tool_input: Any) -> str:
|
|
444
|
+
"""The name of the subagent an Agent tool call with `tool_input` starts."""
|
|
445
|
+
if isinstance(tool_input, dict) and tool_input.get("subagent_type"):
|
|
446
|
+
return str(tool_input["subagent_type"])
|
|
447
|
+
return "subagent"
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def system_prompt_text(system_prompt: Any) -> str:
|
|
451
|
+
"""The text of a `ClaudeAgentOptions.system_prompt`, or "" when it has none.
|
|
452
|
+
|
|
453
|
+
A preset's own prompt is the CLI's, so only what it appends counts; a system
|
|
454
|
+
prompt file isn't read.
|
|
455
|
+
"""
|
|
456
|
+
if isinstance(system_prompt, str):
|
|
457
|
+
return system_prompt
|
|
458
|
+
if isinstance(system_prompt, dict):
|
|
459
|
+
if system_prompt.get("type") == "preset":
|
|
460
|
+
return system_prompt.get("append", "")
|
|
461
|
+
if system_prompt.get("type") == "custom":
|
|
462
|
+
return system_prompt.get("prompt", "")
|
|
463
|
+
return ""
|
|
@@ -0,0 +1,219 @@
|
|
|
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
|
+
"""`root_agent`'s options for one served turn: its session, workspace and defaults."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import dataclasses
|
|
20
|
+
import functools
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import uuid
|
|
24
|
+
from collections.abc import Mapping
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import claude_agent_sdk
|
|
29
|
+
from claude_agent_sdk import ClaudeAgentOptions
|
|
30
|
+
|
|
31
|
+
from app.app_utils import settings, workspaces
|
|
32
|
+
from app.app_utils.project_settings import (
|
|
33
|
+
copy_project_settings,
|
|
34
|
+
settings_allow_rules,
|
|
35
|
+
)
|
|
36
|
+
from app.app_utils.telemetry import cli_telemetry_env
|
|
37
|
+
|
|
38
|
+
# Claude session ids must be UUIDs; other conversation ids map to one derived from them.
|
|
39
|
+
# Never change it: transcripts are stored under the derived ids, so a new namespace
|
|
40
|
+
# would leave existing conversations unresumable.
|
|
41
|
+
_SESSION_NAMESPACE = uuid.UUID("5b0e7f2a-3c4d-4e8f-9a1b-2c3d4e5f6a7b")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def turn_options(
|
|
45
|
+
options: ClaudeAgentOptions,
|
|
46
|
+
conversation_id: str,
|
|
47
|
+
user_id: str | None = None,
|
|
48
|
+
) -> ClaudeAgentOptions:
|
|
49
|
+
"""`options` for one turn of a served agent.
|
|
50
|
+
|
|
51
|
+
Starts or resumes the session for `conversation_id`, scoped to `user_id`.
|
|
52
|
+
Defaults apply only where `root_agent` leaves a field unset.
|
|
53
|
+
"""
|
|
54
|
+
session_store = _session_store(options)
|
|
55
|
+
session_id = session_id_for(conversation_id)
|
|
56
|
+
cwd = Path(options.cwd) if options.cwd else _workspace_for(session_id, user_id)
|
|
57
|
+
session_fields = await _session_fields(session_store, session_id, cwd)
|
|
58
|
+
|
|
59
|
+
# No await from here until stream_turn claims the workspace, so it can't be
|
|
60
|
+
# evicted first.
|
|
61
|
+
cwd.mkdir(parents=True, exist_ok=True)
|
|
62
|
+
|
|
63
|
+
setting_sources = _setting_sources(options, cwd)
|
|
64
|
+
return dataclasses.replace(
|
|
65
|
+
options,
|
|
66
|
+
include_partial_messages=True,
|
|
67
|
+
# Remote prompts must not read local files ("@/path") or run slash commands.
|
|
68
|
+
verbatim_prompts=True,
|
|
69
|
+
cwd=str(cwd),
|
|
70
|
+
setting_sources=setting_sources,
|
|
71
|
+
allowed_tools=list(
|
|
72
|
+
dict.fromkeys(
|
|
73
|
+
[*options.allowed_tools, *settings_allow_rules(setting_sources)]
|
|
74
|
+
)
|
|
75
|
+
),
|
|
76
|
+
session_store=session_store,
|
|
77
|
+
# No one can answer permission prompts on a server: deny tools not in
|
|
78
|
+
# allowed_tools, unless the agent has its own can_use_tool callback.
|
|
79
|
+
permission_mode=options.permission_mode
|
|
80
|
+
or (None if options.can_use_tool else "dontAsk"),
|
|
81
|
+
env={
|
|
82
|
+
# Auto memory loads even with setting_sources=[].
|
|
83
|
+
"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1",
|
|
84
|
+
# Behind ToolSearch, the model often misses the tool it needs.
|
|
85
|
+
"ENABLE_TOOL_SEARCH": "false",
|
|
86
|
+
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
|
|
87
|
+
# The CLI and every tool it runs inherit the server's environment;
|
|
88
|
+
# the Cloud SQL password is read by the server, not them.
|
|
89
|
+
"DB_PASS": "",
|
|
90
|
+
**(
|
|
91
|
+
{"CLAUDE_CODE_SIMPLE": "1"}
|
|
92
|
+
if _is_bare(options, setting_sources)
|
|
93
|
+
else {}
|
|
94
|
+
),
|
|
95
|
+
**cli_telemetry_env(),
|
|
96
|
+
**options.env,
|
|
97
|
+
**_traffic_tag_env(options.env),
|
|
98
|
+
# After options.env, so model calls always go to Gemini platform.
|
|
99
|
+
"CLAUDE_CODE_USE_VERTEX": "1",
|
|
100
|
+
"ANTHROPIC_API_KEY": "",
|
|
101
|
+
"ANTHROPIC_AUTH_TOKEN": "",
|
|
102
|
+
},
|
|
103
|
+
stderr=options.stderr or _log_cli_stderr,
|
|
104
|
+
**session_fields,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def session_id_for(conversation_id: str) -> str:
|
|
109
|
+
"""The Claude session id for a conversation; a canonical UUID is used as is."""
|
|
110
|
+
try:
|
|
111
|
+
if str(uuid.UUID(conversation_id)) == conversation_id:
|
|
112
|
+
return conversation_id
|
|
113
|
+
except ValueError:
|
|
114
|
+
pass
|
|
115
|
+
return str(uuid.uuid5(_SESSION_NAMESPACE, conversation_id))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _session_store(options: ClaudeAgentOptions) -> Any:
|
|
119
|
+
"""The agent's own store, else the Cloud SQL store when it is configured."""
|
|
120
|
+
if options.session_store is not None:
|
|
121
|
+
return options.session_store
|
|
122
|
+
return _cloud_sql_store()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@functools.cache
|
|
126
|
+
def _cloud_sql_store() -> Any:
|
|
127
|
+
"""The Cloud SQL session store, or None when it isn't configured."""
|
|
128
|
+
from app.app_utils.session_store import PostgresSessionStore
|
|
129
|
+
|
|
130
|
+
return PostgresSessionStore.from_env()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _workspace_for(session_id: str, user_id: str | None) -> Path:
|
|
134
|
+
"""The conversation's workspace."""
|
|
135
|
+
if user_id is not None:
|
|
136
|
+
# A workspace per (caller, conversation) keeps callers apart. Hex, so
|
|
137
|
+
# no conversation id can collide with a caller's workspace name.
|
|
138
|
+
name = uuid.uuid5(_SESSION_NAMESPACE, f"{session_id}{user_id}").hex
|
|
139
|
+
else:
|
|
140
|
+
name = session_id
|
|
141
|
+
return workspaces.WORKSPACES / settings.AGENT_NAME / name
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
async def _session_fields(
|
|
145
|
+
session_store: Any, session_id: str, cwd: Path
|
|
146
|
+
) -> dict[str, Any]:
|
|
147
|
+
"""The options that resume the session if it has a transcript, else start it."""
|
|
148
|
+
if await _session_exists(session_store, session_id, cwd):
|
|
149
|
+
return {"resume": session_id}
|
|
150
|
+
return {"session_id": session_id}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
async def _session_exists(session_store: Any, session_id: str, cwd: Path) -> bool:
|
|
154
|
+
"""Whether the session has a transcript to resume, without reading it."""
|
|
155
|
+
transcript = workspaces.transcripts_dir(cwd) / f"{session_id}.jsonl"
|
|
156
|
+
if transcript.is_file() and transcript.stat().st_size > 0:
|
|
157
|
+
return True
|
|
158
|
+
if session_store is None:
|
|
159
|
+
return False
|
|
160
|
+
key = {
|
|
161
|
+
"project_key": claude_agent_sdk.project_key_for_directory(cwd),
|
|
162
|
+
"session_id": session_id,
|
|
163
|
+
}
|
|
164
|
+
if hasattr(session_store, "exists"):
|
|
165
|
+
return await session_store.exists(key)
|
|
166
|
+
return await session_store.load(key) is not None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _setting_sources(options: ClaudeAgentOptions, cwd: Path) -> list[str]:
|
|
170
|
+
"""The setting sources the CLI loads, after copying project settings to `cwd`."""
|
|
171
|
+
setting_sources = options.setting_sources
|
|
172
|
+
wants_project = setting_sources is None or bool(
|
|
173
|
+
{"project", "local"} & set(setting_sources)
|
|
174
|
+
)
|
|
175
|
+
copied = copy_project_settings(cwd) if wants_project else False
|
|
176
|
+
if setting_sources is None:
|
|
177
|
+
# Unset, the CLI would also load parent directories and ~/.claude.
|
|
178
|
+
return ["project"] if copied else []
|
|
179
|
+
return setting_sources
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _is_bare(options: ClaudeAgentOptions, setting_sources: list[str]) -> bool:
|
|
183
|
+
"""Whether the turn can run in the CLI's bare mode.
|
|
184
|
+
|
|
185
|
+
Bare mode drops the CLI's per-prompt reminders, which can make the model
|
|
186
|
+
treat user instructions as prompt injection. It also disables settings,
|
|
187
|
+
skills, plugins and hooks.
|
|
188
|
+
"""
|
|
189
|
+
return (
|
|
190
|
+
options.tools == []
|
|
191
|
+
and not setting_sources
|
|
192
|
+
and options.skills is None
|
|
193
|
+
and not options.plugins
|
|
194
|
+
and not options.hooks
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _traffic_tag_env(env: Mapping[str, str]) -> dict[str, str]:
|
|
199
|
+
"""Adds the agents-cli tag to the headers the CLI sends on model calls.
|
|
200
|
+
|
|
201
|
+
Gemini platform attributes model calls to a tool by their x-goog-api-client
|
|
202
|
+
header, and the Anthropic client sends none. Headers the agent or the
|
|
203
|
+
server already sets are kept.
|
|
204
|
+
"""
|
|
205
|
+
# The CLI's own environment: the agent's env wins over the server's.
|
|
206
|
+
cli_env = {**os.environ, **env}
|
|
207
|
+
opt_out = cli_env.get("AGENTS_CLI_TELEMETRY", "").strip().lower()
|
|
208
|
+
if cli_env.get("DO_NOT_TRACK") or opt_out in ("0", "false", "no", "off"):
|
|
209
|
+
return {}
|
|
210
|
+
tag = (
|
|
211
|
+
"x-goog-api-client: "
|
|
212
|
+
f"agents-cli-app/{settings.AGENTS_CLI_VERSION}+claude-agent-sdk"
|
|
213
|
+
)
|
|
214
|
+
own = cli_env.get("ANTHROPIC_CUSTOM_HEADERS")
|
|
215
|
+
return {"ANTHROPIC_CUSTOM_HEADERS": f"{own}\n{tag}" if own else tag}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _log_cli_stderr(line: str) -> None:
|
|
219
|
+
logging.getLogger("claude_cli").warning(line.rstrip())
|