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,593 @@
|
|
|
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
|
+
"""Turn one turn's events (see turn_events.py) into `agent_events` rows, as ADK writes them."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import datetime
|
|
20
|
+
import json
|
|
21
|
+
import logging
|
|
22
|
+
import time
|
|
23
|
+
import uuid
|
|
24
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from claude_agent_sdk import ResultMessage, TextBlock, ThinkingBlock, ToolUseBlock
|
|
29
|
+
from opentelemetry import trace
|
|
30
|
+
|
|
31
|
+
from app.app_utils.bq_analytics.redaction import sanitize
|
|
32
|
+
from app.app_utils.bq_analytics.uploader import Writer
|
|
33
|
+
from app.app_utils.replies import result_error
|
|
34
|
+
from app.app_utils.turn_events import (
|
|
35
|
+
SUBAGENT_TOOLS,
|
|
36
|
+
Compaction,
|
|
37
|
+
Event,
|
|
38
|
+
ModelCallEnded,
|
|
39
|
+
ModelCallStarted,
|
|
40
|
+
SubagentEnded,
|
|
41
|
+
SubagentStarted,
|
|
42
|
+
ToolCallEnded,
|
|
43
|
+
ToolCallStarted,
|
|
44
|
+
TurnEnded,
|
|
45
|
+
TurnResult,
|
|
46
|
+
system_prompt_text,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
MAX_CONTENT_LENGTH = 500 * 1024
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AgentEventsRecorder:
|
|
53
|
+
"""Maps one turn's events (see turn_events.py) to agent_events rows."""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
out: Writer,
|
|
58
|
+
*,
|
|
59
|
+
prompt: str,
|
|
60
|
+
agent_name: Callable[[str | None], str],
|
|
61
|
+
session_id: str,
|
|
62
|
+
user_id: str,
|
|
63
|
+
model: str | None,
|
|
64
|
+
# The system prompt the model gets, recalled memories included.
|
|
65
|
+
system_prompt: Any,
|
|
66
|
+
# The agent's own system prompt.
|
|
67
|
+
instruction: Any,
|
|
68
|
+
remote_agents: dict[str, str] | None = None,
|
|
69
|
+
local_servers: set[str] | None = None,
|
|
70
|
+
) -> None:
|
|
71
|
+
self._out = out
|
|
72
|
+
self._agent_name = agent_name
|
|
73
|
+
self.agent = agent_name(None)
|
|
74
|
+
self.session_id = session_id
|
|
75
|
+
self.user_id = user_id
|
|
76
|
+
self.model = model
|
|
77
|
+
self.system_prompt = system_prompt_text(system_prompt)
|
|
78
|
+
self.remote_agents = remote_agents or {}
|
|
79
|
+
self.local_servers = local_servers or set()
|
|
80
|
+
self.invocation_id = f"e-{uuid.uuid4()}"
|
|
81
|
+
self.trace_id = self.invocation_id
|
|
82
|
+
self.invocation_span = _span_id()
|
|
83
|
+
self.agent_span = _span_id()
|
|
84
|
+
self.started = time.monotonic()
|
|
85
|
+
self.finished = False
|
|
86
|
+
self.inputs: list[dict[str, Any]] = [{"role": "user", "content": prompt}]
|
|
87
|
+
self.llm_spans: dict[str | None, str] = {}
|
|
88
|
+
self.tools: dict[str, _ToolCall] = {}
|
|
89
|
+
self.subagents: dict[str, _Subagent] = {}
|
|
90
|
+
self.result: ResultMessage | None = None
|
|
91
|
+
# The turn's OpenTelemetry span is current only once the turn runs.
|
|
92
|
+
self._held: list[dict[str, Any]] | None = []
|
|
93
|
+
text, truncated = _clip(prompt)
|
|
94
|
+
self._emit(
|
|
95
|
+
"USER_MESSAGE_RECEIVED",
|
|
96
|
+
self.invocation_span,
|
|
97
|
+
None,
|
|
98
|
+
content={"text_summary": text},
|
|
99
|
+
content_parts=_text_parts(text),
|
|
100
|
+
is_truncated=truncated,
|
|
101
|
+
)
|
|
102
|
+
self._emit("INVOCATION_STARTING", self.invocation_span, None)
|
|
103
|
+
self._emit(
|
|
104
|
+
"AGENT_STARTING",
|
|
105
|
+
self.agent_span,
|
|
106
|
+
self.invocation_span,
|
|
107
|
+
# Where v_agent_starting reads the instruction.
|
|
108
|
+
content={"text_summary": text}
|
|
109
|
+
if (text := system_prompt_text(instruction))
|
|
110
|
+
else None,
|
|
111
|
+
attributes={"model": model} if model else None,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
def handle(self, event: Event) -> None:
|
|
115
|
+
"""Record one event of the turn; never raises into the turn."""
|
|
116
|
+
if self.finished:
|
|
117
|
+
return
|
|
118
|
+
try:
|
|
119
|
+
self._handle(event)
|
|
120
|
+
except Exception:
|
|
121
|
+
logging.warning(
|
|
122
|
+
"BigQuery Agent Analytics couldn't close a turn"
|
|
123
|
+
if isinstance(event, TurnEnded)
|
|
124
|
+
else "BigQuery Agent Analytics stopped recording a turn",
|
|
125
|
+
exc_info=True,
|
|
126
|
+
)
|
|
127
|
+
self.finished = True
|
|
128
|
+
|
|
129
|
+
def _handle(self, event: Event) -> None:
|
|
130
|
+
if self._held is not None:
|
|
131
|
+
self._release_held()
|
|
132
|
+
if isinstance(event, ModelCallStarted):
|
|
133
|
+
self._llm_request(event)
|
|
134
|
+
elif isinstance(event, ModelCallEnded):
|
|
135
|
+
self._llm_response(event)
|
|
136
|
+
elif isinstance(event, ToolCallStarted):
|
|
137
|
+
self._tool_started(event)
|
|
138
|
+
elif isinstance(event, ToolCallEnded):
|
|
139
|
+
self._tool_ended(event)
|
|
140
|
+
elif isinstance(event, SubagentStarted):
|
|
141
|
+
self._subagent_started(event)
|
|
142
|
+
elif isinstance(event, SubagentEnded):
|
|
143
|
+
self._subagent_ended(event)
|
|
144
|
+
elif isinstance(event, Compaction):
|
|
145
|
+
self._emit(
|
|
146
|
+
"EVENT_COMPACTION",
|
|
147
|
+
_span_id(),
|
|
148
|
+
self.agent_span,
|
|
149
|
+
content={"end_timestamp": time.time()},
|
|
150
|
+
attributes={"trigger": event.trigger, "pre_tokens": event.pre_tokens},
|
|
151
|
+
)
|
|
152
|
+
elif isinstance(event, TurnResult):
|
|
153
|
+
self.result = event.message
|
|
154
|
+
elif isinstance(event, TurnEnded):
|
|
155
|
+
self._turn_ended(event)
|
|
156
|
+
|
|
157
|
+
def _release_held(self) -> None:
|
|
158
|
+
"""Send the opening rows, now under the turn's span when there is one."""
|
|
159
|
+
held, self._held = self._held or [], None
|
|
160
|
+
context = trace.get_current_span().get_span_context()
|
|
161
|
+
if context.is_valid:
|
|
162
|
+
# Root rows keep a NULL parent: the span's parent isn't a row.
|
|
163
|
+
ours = self.invocation_span
|
|
164
|
+
self.invocation_span = format(context.span_id, "016x")
|
|
165
|
+
self.trace_id = format(context.trace_id, "032x")
|
|
166
|
+
for row in held:
|
|
167
|
+
row["trace_id"] = self.trace_id
|
|
168
|
+
if row["span_id"] == ours:
|
|
169
|
+
row["span_id"] = self.invocation_span
|
|
170
|
+
if row["parent_span_id"] == ours:
|
|
171
|
+
row["parent_span_id"] = self.invocation_span
|
|
172
|
+
for row in held:
|
|
173
|
+
self._out.put(row)
|
|
174
|
+
|
|
175
|
+
def _llm_request(self, event: ModelCallStarted) -> None:
|
|
176
|
+
span = self.llm_spans[event.agent] = _span_id()
|
|
177
|
+
# Claude Code builds the real request; this row has only the new inputs.
|
|
178
|
+
if event.agent is None:
|
|
179
|
+
content: dict[str, Any] = {"prompt": self.inputs}
|
|
180
|
+
if self.system_prompt:
|
|
181
|
+
content["system_prompt"] = self.system_prompt
|
|
182
|
+
self._emit(
|
|
183
|
+
"LLM_REQUEST",
|
|
184
|
+
span,
|
|
185
|
+
self.agent_span,
|
|
186
|
+
content=content,
|
|
187
|
+
attributes={"model": self.model, "synthesized": True},
|
|
188
|
+
)
|
|
189
|
+
self.inputs = []
|
|
190
|
+
return
|
|
191
|
+
sub = self.subagents[event.agent]
|
|
192
|
+
self._emit(
|
|
193
|
+
"LLM_REQUEST",
|
|
194
|
+
span,
|
|
195
|
+
sub.span,
|
|
196
|
+
agent=self._agent_name(event.agent),
|
|
197
|
+
content={"prompt": sub.inputs},
|
|
198
|
+
attributes={"synthesized": True},
|
|
199
|
+
)
|
|
200
|
+
sub.inputs = []
|
|
201
|
+
|
|
202
|
+
def _llm_response(self, event: ModelCallEnded) -> None:
|
|
203
|
+
parent, agent = self._parent(event.agent)
|
|
204
|
+
usage = event.usage
|
|
205
|
+
prompt = _prompt_tokens(usage)
|
|
206
|
+
completion = int(usage.get("output_tokens") or 0)
|
|
207
|
+
response, truncated = _clip(_response_text(event.blocks))
|
|
208
|
+
thinking = "".join(
|
|
209
|
+
b.thinking for b in event.blocks if isinstance(b, ThinkingBlock)
|
|
210
|
+
)
|
|
211
|
+
latency = {"total_ms": int((time.monotonic() - event.requested_at) * 1000)}
|
|
212
|
+
if event.first_token_at is not None:
|
|
213
|
+
latency["time_to_first_token_ms"] = int(
|
|
214
|
+
(event.first_token_at - event.requested_at) * 1000
|
|
215
|
+
)
|
|
216
|
+
if event.error:
|
|
217
|
+
# The CLI puts the API's error text in the message's text blocks.
|
|
218
|
+
text = _response_text(event.blocks)
|
|
219
|
+
self._emit(
|
|
220
|
+
"LLM_ERROR",
|
|
221
|
+
self.llm_spans.pop(event.agent),
|
|
222
|
+
parent,
|
|
223
|
+
agent=agent,
|
|
224
|
+
status="ERROR",
|
|
225
|
+
error_message=f"{event.error}: {text}" if text else event.error,
|
|
226
|
+
latency_ms=latency,
|
|
227
|
+
)
|
|
228
|
+
return
|
|
229
|
+
cache_read = usage.get("cache_read_input_tokens")
|
|
230
|
+
self._emit(
|
|
231
|
+
"LLM_RESPONSE",
|
|
232
|
+
self.llm_spans.pop(event.agent),
|
|
233
|
+
parent,
|
|
234
|
+
agent=agent,
|
|
235
|
+
content={
|
|
236
|
+
"response": response,
|
|
237
|
+
"usage": {
|
|
238
|
+
"prompt": prompt,
|
|
239
|
+
"completion": completion,
|
|
240
|
+
"total": prompt + completion,
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
attributes={
|
|
244
|
+
"model_version": event.model,
|
|
245
|
+
"finish_reason": event.stop_reason,
|
|
246
|
+
"cache_type": "implicit" if cache_read else "none",
|
|
247
|
+
"usage_metadata": {
|
|
248
|
+
"prompt_token_count": prompt,
|
|
249
|
+
"candidates_token_count": completion,
|
|
250
|
+
"total_token_count": prompt + completion,
|
|
251
|
+
"cached_content_token_count": cache_read,
|
|
252
|
+
"cache_creation_input_tokens": usage.get(
|
|
253
|
+
"cache_creation_input_tokens"
|
|
254
|
+
),
|
|
255
|
+
"input_tokens": usage.get("input_tokens"),
|
|
256
|
+
},
|
|
257
|
+
**({"thinking": _clip(thinking)[0]} if thinking else {}),
|
|
258
|
+
},
|
|
259
|
+
latency_ms=latency,
|
|
260
|
+
is_truncated=truncated,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
def _tool_started(self, event: ToolCallStarted) -> None:
|
|
264
|
+
parent, agent = self._parent(event.agent)
|
|
265
|
+
span = _span_id()
|
|
266
|
+
self.tools[event.id] = _ToolCall(
|
|
267
|
+
span=span,
|
|
268
|
+
started=time.monotonic(),
|
|
269
|
+
tool=event,
|
|
270
|
+
agent=agent or self.agent,
|
|
271
|
+
)
|
|
272
|
+
self._emit(
|
|
273
|
+
"TOOL_STARTING",
|
|
274
|
+
span,
|
|
275
|
+
parent,
|
|
276
|
+
agent=agent,
|
|
277
|
+
content={
|
|
278
|
+
"tool": event.name,
|
|
279
|
+
"args": event.input,
|
|
280
|
+
"tool_origin": self._tool_origin(event.name),
|
|
281
|
+
},
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
def _tool_ended(self, event: ToolCallEnded) -> None:
|
|
285
|
+
parent, _ = self._parent(event.agent)
|
|
286
|
+
call = self.tools[event.id]
|
|
287
|
+
if event.agent is None:
|
|
288
|
+
self.inputs.append(
|
|
289
|
+
{"role": "user", "content": f"Function response: {call.tool.name}"}
|
|
290
|
+
)
|
|
291
|
+
else:
|
|
292
|
+
self.subagents[event.agent].inputs.append(
|
|
293
|
+
{"role": "user", "content": "Function response"}
|
|
294
|
+
)
|
|
295
|
+
origin = self._tool_origin(call.tool.name)
|
|
296
|
+
result = _result_content(event.content)
|
|
297
|
+
latency = {"total_ms": int((time.monotonic() - call.started) * 1000)}
|
|
298
|
+
if event.is_error:
|
|
299
|
+
self._emit(
|
|
300
|
+
"TOOL_ERROR",
|
|
301
|
+
call.span,
|
|
302
|
+
parent,
|
|
303
|
+
agent=call.agent,
|
|
304
|
+
content={
|
|
305
|
+
"tool": call.tool.name,
|
|
306
|
+
"args": call.tool.input,
|
|
307
|
+
"tool_origin": origin,
|
|
308
|
+
},
|
|
309
|
+
status="ERROR",
|
|
310
|
+
error_message=str(result)[:1000],
|
|
311
|
+
latency_ms=latency,
|
|
312
|
+
)
|
|
313
|
+
return
|
|
314
|
+
self._emit(
|
|
315
|
+
"TOOL_COMPLETED",
|
|
316
|
+
call.span,
|
|
317
|
+
parent,
|
|
318
|
+
agent=call.agent,
|
|
319
|
+
content={"tool": call.tool.name, "result": result, "tool_origin": origin},
|
|
320
|
+
latency_ms=latency,
|
|
321
|
+
)
|
|
322
|
+
if origin == "A2A":
|
|
323
|
+
self._a2a_interaction(call, parent, result, latency)
|
|
324
|
+
|
|
325
|
+
def _a2a_interaction(
|
|
326
|
+
self, call: _ToolCall, parent: str, result: Any, latency: dict[str, int]
|
|
327
|
+
) -> None:
|
|
328
|
+
server = call.tool.name.split("__")[1]
|
|
329
|
+
self._emit(
|
|
330
|
+
"A2A_INTERACTION",
|
|
331
|
+
call.span,
|
|
332
|
+
parent,
|
|
333
|
+
agent=call.agent,
|
|
334
|
+
content=result,
|
|
335
|
+
attributes={
|
|
336
|
+
"remote_agent": server,
|
|
337
|
+
"a2a_metadata": {
|
|
338
|
+
"a2a:url": self.remote_agents[server],
|
|
339
|
+
"a2a:request": call.tool.input,
|
|
340
|
+
"a2a:response": result,
|
|
341
|
+
},
|
|
342
|
+
},
|
|
343
|
+
latency_ms=latency,
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
def _subagent_started(self, event: SubagentStarted) -> None:
|
|
347
|
+
call = self.tools[event.id]
|
|
348
|
+
sub = self.subagents[event.id] = _Subagent(
|
|
349
|
+
span=_span_id(),
|
|
350
|
+
tool_span=call.span,
|
|
351
|
+
started=call.started,
|
|
352
|
+
inputs=[{"role": "user", "content": event.prompt}],
|
|
353
|
+
)
|
|
354
|
+
self._emit(
|
|
355
|
+
"AGENT_STARTING",
|
|
356
|
+
sub.span,
|
|
357
|
+
sub.tool_span,
|
|
358
|
+
agent=self._agent_name(event.id),
|
|
359
|
+
content={"text_summary": event.prompt},
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
def _subagent_ended(self, event: SubagentEnded) -> None:
|
|
363
|
+
sub = self.subagents[event.id]
|
|
364
|
+
latency = {"total_ms": int((time.monotonic() - sub.started) * 1000)}
|
|
365
|
+
self._emit(
|
|
366
|
+
"AGENT_ERROR" if event.failed else "AGENT_COMPLETED",
|
|
367
|
+
sub.span,
|
|
368
|
+
sub.tool_span,
|
|
369
|
+
agent=self._agent_name(event.id),
|
|
370
|
+
status="ERROR" if event.failed else "OK",
|
|
371
|
+
latency_ms=latency,
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
def _turn_ended(self, event: TurnEnded) -> None:
|
|
375
|
+
"""Close the turn: AGENT_RESPONSE and the COMPLETED, or ERROR, pair."""
|
|
376
|
+
self.finished = True
|
|
377
|
+
result = self.result
|
|
378
|
+
latency = {"total_ms": int((time.monotonic() - self.started) * 1000)}
|
|
379
|
+
stats = _turn_stats(result)
|
|
380
|
+
if event.failed:
|
|
381
|
+
self._close_failed(_error_detail(event.error, result), latency, stats)
|
|
382
|
+
return
|
|
383
|
+
if result is not None and result.result:
|
|
384
|
+
text, truncated = _clip(result.result)
|
|
385
|
+
self._emit(
|
|
386
|
+
"AGENT_RESPONSE",
|
|
387
|
+
self.agent_span,
|
|
388
|
+
self.invocation_span,
|
|
389
|
+
content={"response": text},
|
|
390
|
+
is_truncated=truncated,
|
|
391
|
+
)
|
|
392
|
+
self._emit(
|
|
393
|
+
"AGENT_COMPLETED",
|
|
394
|
+
self.agent_span,
|
|
395
|
+
self.invocation_span,
|
|
396
|
+
latency_ms=latency,
|
|
397
|
+
)
|
|
398
|
+
self._emit(
|
|
399
|
+
"INVOCATION_COMPLETED",
|
|
400
|
+
self.invocation_span,
|
|
401
|
+
None,
|
|
402
|
+
latency_ms=latency,
|
|
403
|
+
attributes=stats,
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
def _close_failed(
|
|
407
|
+
self, detail: str, latency: dict[str, int], stats: dict[str, Any]
|
|
408
|
+
) -> None:
|
|
409
|
+
self._emit(
|
|
410
|
+
"AGENT_ERROR",
|
|
411
|
+
self.agent_span,
|
|
412
|
+
self.invocation_span,
|
|
413
|
+
status="ERROR",
|
|
414
|
+
error_message=detail,
|
|
415
|
+
latency_ms=latency,
|
|
416
|
+
)
|
|
417
|
+
self._emit(
|
|
418
|
+
"INVOCATION_ERROR",
|
|
419
|
+
self.invocation_span,
|
|
420
|
+
None,
|
|
421
|
+
status="ERROR",
|
|
422
|
+
error_message=detail,
|
|
423
|
+
latency_ms=latency,
|
|
424
|
+
attributes=stats,
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
def _parent(self, agent: str | None) -> tuple[str, str | None]:
|
|
428
|
+
"""The span and row agent name for events of `agent`."""
|
|
429
|
+
if agent is None:
|
|
430
|
+
return self.agent_span, None
|
|
431
|
+
return self.subagents[agent].span, self._agent_name(agent)
|
|
432
|
+
|
|
433
|
+
def _tool_origin(self, name: str) -> str:
|
|
434
|
+
if name in SUBAGENT_TOOLS:
|
|
435
|
+
return "SUB_AGENT"
|
|
436
|
+
if name.startswith("mcp__"):
|
|
437
|
+
server = name.split("__")[1]
|
|
438
|
+
if server in self.remote_agents:
|
|
439
|
+
return "A2A"
|
|
440
|
+
return "LOCAL" if server in self.local_servers else "MCP"
|
|
441
|
+
return "LOCAL"
|
|
442
|
+
|
|
443
|
+
def _emit(
|
|
444
|
+
self,
|
|
445
|
+
event_type: str,
|
|
446
|
+
span_id: str,
|
|
447
|
+
parent_span_id: str | None,
|
|
448
|
+
*,
|
|
449
|
+
agent: str | None = None,
|
|
450
|
+
content: Any = None,
|
|
451
|
+
content_parts: list[dict[str, Any]] | None = None,
|
|
452
|
+
attributes: dict[str, Any] | None = None,
|
|
453
|
+
latency_ms: dict[str, int] | None = None,
|
|
454
|
+
status: str = "OK",
|
|
455
|
+
error_message: str | None = None,
|
|
456
|
+
is_truncated: bool = False,
|
|
457
|
+
) -> None:
|
|
458
|
+
# Credentials redacted and every string capped, at any depth: tool args
|
|
459
|
+
# and results, A2A payloads and prompts.
|
|
460
|
+
content, content_cut = sanitize(content, MAX_CONTENT_LENGTH)
|
|
461
|
+
attributes, attributes_cut = sanitize(attributes, MAX_CONTENT_LENGTH)
|
|
462
|
+
content_parts, parts_cut = sanitize(content_parts, MAX_CONTENT_LENGTH)
|
|
463
|
+
error_message, _ = sanitize(error_message, MAX_CONTENT_LENGTH)
|
|
464
|
+
row = {
|
|
465
|
+
"timestamp": _now(),
|
|
466
|
+
"event_id": str(uuid.uuid4()),
|
|
467
|
+
"event_type": event_type,
|
|
468
|
+
"agent": agent or self.agent,
|
|
469
|
+
"session_id": self.session_id,
|
|
470
|
+
"invocation_id": self.invocation_id,
|
|
471
|
+
"user_id": self.user_id,
|
|
472
|
+
"trace_id": self.trace_id,
|
|
473
|
+
"span_id": span_id,
|
|
474
|
+
"parent_span_id": parent_span_id,
|
|
475
|
+
"content": json.dumps(content, default=str)
|
|
476
|
+
if content is not None
|
|
477
|
+
else None,
|
|
478
|
+
"content_parts": content_parts or [],
|
|
479
|
+
"attributes": json.dumps(
|
|
480
|
+
{
|
|
481
|
+
"root_agent_name": self.agent,
|
|
482
|
+
"session_metadata": {
|
|
483
|
+
"session_id": self.session_id,
|
|
484
|
+
"user_id": self.user_id,
|
|
485
|
+
},
|
|
486
|
+
"framework": "claude_agent_sdk",
|
|
487
|
+
**(attributes or {}),
|
|
488
|
+
},
|
|
489
|
+
default=str,
|
|
490
|
+
),
|
|
491
|
+
"latency_ms": json.dumps(latency_ms) if latency_ms else None,
|
|
492
|
+
"status": status,
|
|
493
|
+
"error_message": error_message,
|
|
494
|
+
"is_truncated": is_truncated or content_cut or attributes_cut or parts_cut,
|
|
495
|
+
}
|
|
496
|
+
if self._held is not None:
|
|
497
|
+
self._held.append(row)
|
|
498
|
+
else:
|
|
499
|
+
self._out.put(row)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
@dataclass(frozen=True)
|
|
503
|
+
class _ToolCall:
|
|
504
|
+
span: str
|
|
505
|
+
started: float
|
|
506
|
+
tool: ToolCallStarted
|
|
507
|
+
agent: str
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
@dataclass
|
|
511
|
+
class _Subagent:
|
|
512
|
+
span: str
|
|
513
|
+
tool_span: str
|
|
514
|
+
started: float
|
|
515
|
+
inputs: list[dict[str, Any]]
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _span_id() -> str:
|
|
519
|
+
return uuid.uuid4().hex[:16]
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _clip(text: str) -> tuple[str, bool]:
|
|
523
|
+
if len(text) > MAX_CONTENT_LENGTH:
|
|
524
|
+
return text[:MAX_CONTENT_LENGTH] + "...[TRUNCATED]", True
|
|
525
|
+
return text, False
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _text_parts(text: str) -> list[dict[str, Any]]:
|
|
529
|
+
if not text:
|
|
530
|
+
return []
|
|
531
|
+
return [
|
|
532
|
+
{
|
|
533
|
+
"mime_type": "text/plain",
|
|
534
|
+
"text": text,
|
|
535
|
+
"part_index": 0,
|
|
536
|
+
"storage_mode": "INLINE",
|
|
537
|
+
}
|
|
538
|
+
]
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _prompt_tokens(usage: Mapping[str, Any]) -> int:
|
|
542
|
+
"""All input tokens, cached or not."""
|
|
543
|
+
return sum(
|
|
544
|
+
int(usage.get(key) or 0)
|
|
545
|
+
for key in (
|
|
546
|
+
"input_tokens",
|
|
547
|
+
"cache_read_input_tokens",
|
|
548
|
+
"cache_creation_input_tokens",
|
|
549
|
+
)
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _response_text(blocks: Sequence[Any]) -> str:
|
|
554
|
+
"""The model's text, or the tools it called when it wrote none."""
|
|
555
|
+
texts = [b.text for b in blocks if isinstance(b, TextBlock)]
|
|
556
|
+
if texts:
|
|
557
|
+
return "\n".join(texts)
|
|
558
|
+
calls = [b.name for b in blocks if isinstance(b, ToolUseBlock)]
|
|
559
|
+
return f"call: {', '.join(calls)}" if calls else ""
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _result_content(content: Any) -> Any:
|
|
563
|
+
if isinstance(content, str) or content is None:
|
|
564
|
+
return content
|
|
565
|
+
return [c.get("text") for c in content if isinstance(c, dict)]
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _turn_stats(result: ResultMessage | None) -> dict[str, Any]:
|
|
569
|
+
if result is None:
|
|
570
|
+
return {}
|
|
571
|
+
return {
|
|
572
|
+
# Covers the whole session, including resumed turns: don't sum it.
|
|
573
|
+
"session_cost_usd": result.total_cost_usd,
|
|
574
|
+
"num_turns": result.num_turns,
|
|
575
|
+
"result_subtype": result.subtype,
|
|
576
|
+
# Tool calls outside allowed_tools; each is also a TOOL_ERROR.
|
|
577
|
+
"permission_denials": result.permission_denials or None,
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _error_detail(error: BaseException | None, result: ResultMessage | None) -> str:
|
|
582
|
+
if error is not None:
|
|
583
|
+
# A cancelled turn (a client that disconnects) has no message.
|
|
584
|
+
detail = str(error) or type(error).__name__
|
|
585
|
+
elif result is not None:
|
|
586
|
+
detail = result_error(result)
|
|
587
|
+
else:
|
|
588
|
+
detail = "unknown error"
|
|
589
|
+
return detail[:1000]
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _now() -> str:
|
|
593
|
+
return datetime.datetime.now(datetime.UTC).isoformat()
|