agentengine-sdk-python 0.8.7__py3-none-any.whl → 0.8.8__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.
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/METADATA +14 -9
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/RECORD +98 -68
- ksadk/__init__.py +2 -1
- ksadk/_build_provenance.json +1 -1
- ksadk/_mcp_compat.py +305 -0
- ksadk/agent.py +29 -0
- ksadk/agui/_agent_kernel.py +176 -142
- ksadk/agui/agent.py +74 -5
- ksadk/agui/hosted.py +343 -0
- ksadk/agui/request_identity.py +11 -0
- ksadk/agui/routes.py +77 -2
- ksadk/builders/code_builder.py +30 -23
- ksadk/builders/container_builder.py +5 -5
- ksadk/builders/mcp_builder.py +142 -0
- ksadk/builders/project_imports.py +66 -0
- ksadk/cli/cmd_mcp.py +1 -1
- ksadk/cli/cmd_run.py +2 -4
- ksadk/cli/cmd_web.py +8 -0
- ksadk/cli/runtime_bootstrap.py +4 -1
- ksadk/common/cloud_headers.py +33 -6
- ksadk/compat/adk_compat.py +2 -0
- ksadk/compat/adk_stream.py +35 -0
- ksadk/configs/env_registry.py +31 -0
- ksadk/conversations/projector.py +6 -0
- ksadk/conversations/runtime_observability.py +1 -0
- ksadk/detection/mcp_detector.py +80 -22
- ksadk/harness/__init__.py +3 -0
- ksadk/harness/service_presentation.py +44 -0
- ksadk/harness/service_runtime.py +1038 -0
- ksadk/interaction/providers/harness.py +9 -4
- ksadk/kernel/ingress.py +35 -25
- ksadk/kernel/worker.py +2 -2
- ksadk/kernel/worker_identity.py +15 -8
- ksadk/knowledge_base/client.py +10 -3
- ksadk/mcp_runtime/oauth/_agent.py +77 -9
- ksadk/mcp_runtime/oauth/langgraph.py +47 -15
- ksadk/mcp_runtime/oauth/local/broker.py +23 -1
- ksadk/mcp_runtime/oauth/tools.py +46 -8
- ksadk/mcp_runtime/oauth/transport.py +19 -2
- ksadk/memory/adk/backends/sdk_ltm_backend.py +21 -12
- ksadk/memory/scope_ids.py +49 -0
- ksadk/plugins/providers/harness.py +65 -28
- ksadk/plugins/providers/harness_service.py +198 -0
- ksadk/plugins/providers/harness_service_context.py +175 -0
- ksadk/plugins/providers/harness_service_hooks.py +168 -0
- ksadk/plugins/providers/harness_service_memory.py +479 -0
- ksadk/plugins/providers/platform_resources.py +2 -2
- ksadk/resource_runtime/langgraph.py +7 -3
- ksadk/resource_runtime/mcp_server.py +3 -3
- ksadk/resource_runtime/worker.py +19 -4
- ksadk/runners/_adk_canonical_stream.py +38 -10
- ksadk/runners/_adk_tunnel_history.py +96 -0
- ksadk/runners/_langgraph_canonical_stream.py +16 -0
- ksadk/runners/_langgraph_factory.py +79 -0
- ksadk/runners/_langgraph_runner_streams.py +6 -0
- ksadk/runners/_session_identity.py +8 -3
- ksadk/runners/adk_runner.py +95 -19
- ksadk/runners/langgraph_runner.py +15 -21
- ksadk/runtime/factory.py +17 -5
- ksadk/runtime/framework_adapters.py +10 -0
- ksadk/runtime/langgraph_checkpoint_view.py +28 -7
- ksadk/runtime/launch.py +2 -0
- ksadk/server/factory.py +55 -0
- ksadk/server/routes/common.py +2 -0
- ksadk/server/routes/harness_service_view.py +38 -0
- ksadk/server/routes/ui_bootstrap.py +16 -2
- ksadk/skills/mcp_server/server.py +239 -217
- ksadk/studio/contracts.py +8 -0
- ksadk/studio/mcp_runtime.py +23 -8
- ksadk/studio/native_mcp_disclosure.py +8 -6
- ksadk/studio/native_mcp_tool_port.py +3 -1
- ksadk/studio/native_memory_context.py +10 -8
- ksadk/studio/native_product.py +3 -4
- ksadk/studio/plugin_composition.py +8 -1
- ksadk/studio/plugin_native_activation.py +4 -2
- ksadk/studio/plugin_runtime.py +9 -0
- ksadk/studio/service.py +2 -0
- ksadk/tracing/setup.py +53 -3
- ksadk/tunnel/__init__.py +37 -0
- ksadk/tunnel/connector.py +384 -0
- ksadk/tunnel/discovery.py +107 -0
- ksadk/tunnel/failure.py +168 -0
- ksadk/tunnel/http_tools.py +100 -0
- ksadk/tunnel/langgraph.py +125 -0
- ksadk/tunnel/middleware.py +28 -0
- ksadk/tunnel/peers.py +872 -0
- ksadk/tunnel/protocol.py +97 -0
- ksadk/tunnel/registry.py +306 -0
- ksadk/tunnel/runtime.py +147 -0
- ksadk/tunnel/server.py +201 -0
- ksadk/tunnel/services.py +366 -0
- ksadk/tunnel/toolset.py +78 -0
- ksadk/version.py +1 -1
- ksadk_runtime_common/memory_backend/providers/mem0.py +20 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/WHEEL +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/entry_points.txt +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/licenses/LICENSE +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/top_level.txt +0 -0
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
import time
|
|
6
5
|
import logging
|
|
6
|
+
import time
|
|
7
7
|
import traceback
|
|
8
|
-
from pathlib import Path
|
|
9
8
|
from collections.abc import AsyncGenerator, AsyncIterator
|
|
9
|
+
from pathlib import Path
|
|
10
10
|
from typing import Any
|
|
11
11
|
|
|
12
12
|
from ksadk.events.adapters.adk import ADKAdapterContext, ADKEventAdapter
|
|
@@ -53,9 +53,20 @@ async def canonical_events(
|
|
|
53
53
|
last_usage: dict[str, Any] = {}
|
|
54
54
|
approval_ids: set[str] = set()
|
|
55
55
|
message_snapshots: dict[tuple[str, str], dict[str, str]] = {}
|
|
56
|
+
pending_tool_calls = set()
|
|
56
57
|
managed_descriptors = {}
|
|
57
58
|
root_transfer_target = None
|
|
58
59
|
|
|
60
|
+
def source() -> SourceRef:
|
|
61
|
+
return SourceRef(
|
|
62
|
+
framework="adk",
|
|
63
|
+
metadata={
|
|
64
|
+
"session_id": session_id,
|
|
65
|
+
**({"last_usage": last_usage} if last_usage else {}),
|
|
66
|
+
**({"usage": usage} if usage else {}),
|
|
67
|
+
},
|
|
68
|
+
)
|
|
69
|
+
|
|
59
70
|
def envelope(event_type: str, occurrence: str = "run") -> dict[str, Any]:
|
|
60
71
|
return {
|
|
61
72
|
"schema_version": 2,
|
|
@@ -72,17 +83,11 @@ async def canonical_events(
|
|
|
72
83
|
),
|
|
73
84
|
"seq": context.allocate_seq(),
|
|
74
85
|
"timestamp": time.time(),
|
|
75
|
-
"source":
|
|
76
|
-
framework="adk",
|
|
77
|
-
metadata={
|
|
78
|
-
"session_id": session_id,
|
|
79
|
-
**({"last_usage": last_usage} if last_usage else {}),
|
|
80
|
-
**({"usage": usage} if usage else {}),
|
|
81
|
-
},
|
|
82
|
-
),
|
|
86
|
+
"source": source(),
|
|
83
87
|
}
|
|
84
88
|
|
|
85
89
|
stream_failure: str | None = None
|
|
90
|
+
tunnel_outcome = None
|
|
86
91
|
stream_failure_code = "adk_stream_error"
|
|
87
92
|
yield RunStarted(**envelope("run.started"), status="running")
|
|
88
93
|
try:
|
|
@@ -101,6 +106,12 @@ async def canonical_events(
|
|
|
101
106
|
|
|
102
107
|
approval_signals = list(runner._extract_approval_signals(native_event))
|
|
103
108
|
for event in adapter.map(native_event, context):
|
|
109
|
+
if isinstance(event, ItemCompleted):
|
|
110
|
+
for part in event.snapshot.parts:
|
|
111
|
+
if isinstance(part, ToolCallContent):
|
|
112
|
+
pending_tool_calls.add((event.scope_id, part.call_id))
|
|
113
|
+
elif isinstance(part, ToolResultContent):
|
|
114
|
+
pending_tool_calls.discard((event.scope_id, part.call_id))
|
|
104
115
|
if isinstance(event, ItemCompleted) and event.item_kind in {"message", "artifact"}:
|
|
105
116
|
message_snapshots[(event.scope_id, event.item_id)] = {
|
|
106
117
|
part.part_id: part.text
|
|
@@ -176,6 +187,9 @@ async def canonical_events(
|
|
|
176
187
|
),
|
|
177
188
|
)
|
|
178
189
|
except Exception as exc: # noqa: BLE001
|
|
190
|
+
from ksadk.tunnel.failure import tunnel_failure
|
|
191
|
+
|
|
192
|
+
tunnel_outcome = tunnel_failure(exc)
|
|
179
193
|
if getattr(runner, "_managed_a2a_bootstrap", None) is not None:
|
|
180
194
|
# Keep diagnostic locations server-side. Never log exception text,
|
|
181
195
|
# source lines or local values: provider errors can embed credentials.
|
|
@@ -239,6 +253,20 @@ async def canonical_events(
|
|
|
239
253
|
reasoning_tokens=int(usage.get("reasoning_tokens") or 0),
|
|
240
254
|
)
|
|
241
255
|
|
|
256
|
+
if tunnel_outcome is not None:
|
|
257
|
+
from ksadk.tunnel.failure import failure_events
|
|
258
|
+
|
|
259
|
+
for event in failure_events(
|
|
260
|
+
tunnel_outcome,
|
|
261
|
+
run_id=run_id,
|
|
262
|
+
scope_id=root_scope_id,
|
|
263
|
+
source=source(),
|
|
264
|
+
allocate_seq=context.allocate_seq,
|
|
265
|
+
pending_calls=sorted(pending_tool_calls),
|
|
266
|
+
):
|
|
267
|
+
yield event
|
|
268
|
+
return
|
|
269
|
+
|
|
242
270
|
output_refs = context.output_refs
|
|
243
271
|
if not output_refs and managed_descriptors:
|
|
244
272
|
binding = _delegated_binding(runner._agent, root_transfer_target)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Keep a failed tunnel turn valid in ADK's own multi-turn model history."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from contextlib import aclosing
|
|
5
|
+
|
|
6
|
+
from ksadk.compat.adk_compat import Event
|
|
7
|
+
from ksadk.compat.adk_compat import genai_types as types
|
|
8
|
+
from ksadk.tunnel.failure import tunnel_failure
|
|
9
|
+
from ksadk.tunnel.protocol import TunnelError
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def preserve_tunnel_history(events, *, session_service, app_name, user_id, session_id):
|
|
15
|
+
# A resumed invocation may contain older calls. Only close calls emitted by
|
|
16
|
+
# this iterator, in this session, for which ADK did not persist a response.
|
|
17
|
+
call_events = set()
|
|
18
|
+
deferred_error = None
|
|
19
|
+
try:
|
|
20
|
+
async with aclosing(events):
|
|
21
|
+
async for event in events:
|
|
22
|
+
# Workflow-backed ADK emits an error event just before raising
|
|
23
|
+
# the original exception. Give it one iteration to propagate
|
|
24
|
+
# the typed failure; preserve ordinary error-only streams.
|
|
25
|
+
if deferred_error is not None:
|
|
26
|
+
yield deferred_error
|
|
27
|
+
deferred_error = None
|
|
28
|
+
if event.error_code in {"TunnelError", "ExceptionGroup"}:
|
|
29
|
+
deferred_error = event
|
|
30
|
+
continue
|
|
31
|
+
if not event.partial and event.get_function_calls():
|
|
32
|
+
call_events.add(event.id)
|
|
33
|
+
yield event
|
|
34
|
+
if deferred_error is not None:
|
|
35
|
+
yield deferred_error
|
|
36
|
+
except Exception as exc:
|
|
37
|
+
failure = tunnel_failure(exc)
|
|
38
|
+
if failure is not None and call_events:
|
|
39
|
+
outcome = failure
|
|
40
|
+
try:
|
|
41
|
+
session = await session_service.get_session(
|
|
42
|
+
app_name=app_name, user_id=user_id, session_id=session_id
|
|
43
|
+
)
|
|
44
|
+
if session is not None:
|
|
45
|
+
pending = _pending_calls(session, call_events)
|
|
46
|
+
outcome = failure.for_unanswered_calls(sum(map(len, pending.values())))
|
|
47
|
+
await _close_pending_calls(session_service, session, pending, outcome)
|
|
48
|
+
except Exception as storage_error:
|
|
49
|
+
# Persistence failures must not erase the user's outcome-unknown notification.
|
|
50
|
+
logger.warning(
|
|
51
|
+
"Could not persist ADK tunnel failure (%s)", type(storage_error).__name__
|
|
52
|
+
)
|
|
53
|
+
if outcome != failure:
|
|
54
|
+
raise TunnelError(outcome.result_code, indeterminate=outcome.indeterminate) from exc
|
|
55
|
+
raise
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _pending_calls(session, call_events):
|
|
59
|
+
pending = {}
|
|
60
|
+
for event in session.events:
|
|
61
|
+
if event.partial:
|
|
62
|
+
continue
|
|
63
|
+
scope = (event.invocation_id, event.branch, event.author)
|
|
64
|
+
if event.id in call_events:
|
|
65
|
+
for call in event.get_function_calls():
|
|
66
|
+
if call.id and call.id not in (event.long_running_tool_ids or ()):
|
|
67
|
+
pending.setdefault(scope, {})[call.id] = call
|
|
68
|
+
if scope in pending:
|
|
69
|
+
for response in event.get_function_responses():
|
|
70
|
+
pending[scope].pop(response.id, None)
|
|
71
|
+
return pending
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def _close_pending_calls(service, session, pending, failure):
|
|
75
|
+
for (invocation_id, branch, author), calls in pending.items():
|
|
76
|
+
if not calls:
|
|
77
|
+
continue
|
|
78
|
+
parts = [
|
|
79
|
+
types.Part(
|
|
80
|
+
function_response=types.FunctionResponse(
|
|
81
|
+
id=call.id, name=call.name, response=failure.tool_result
|
|
82
|
+
)
|
|
83
|
+
)
|
|
84
|
+
for call in calls.values()
|
|
85
|
+
]
|
|
86
|
+
origin = dict(invocation_id=invocation_id, branch=branch, author=author)
|
|
87
|
+
await service.append_event(
|
|
88
|
+
session, Event(**origin, content=types.Content(role="user", parts=parts))
|
|
89
|
+
)
|
|
90
|
+
await service.append_event(
|
|
91
|
+
session,
|
|
92
|
+
Event(
|
|
93
|
+
**origin,
|
|
94
|
+
content=types.Content(role="model", parts=[types.Part(text=failure.message)]),
|
|
95
|
+
),
|
|
96
|
+
)
|
|
@@ -430,6 +430,22 @@ class _LangGraphCanonicalStreamMixin:
|
|
|
430
430
|
if timing := extract_timing(final_state):
|
|
431
431
|
final_result_fields["timing"] = timing
|
|
432
432
|
except Exception as exc:
|
|
433
|
+
from ksadk.tunnel.failure import failure_events, tunnel_failure
|
|
434
|
+
|
|
435
|
+
if failure := tunnel_failure(exc):
|
|
436
|
+
for event in failure_events(
|
|
437
|
+
failure,
|
|
438
|
+
run_id=run_id,
|
|
439
|
+
scope_id=run_scope_id,
|
|
440
|
+
source=run_source,
|
|
441
|
+
allocate_seq=adapter_context.allocate_placeholder_seq,
|
|
442
|
+
open_items=(
|
|
443
|
+
(item.scope_id, item.item_id, item.item_kind)
|
|
444
|
+
for item in reducer.snapshot().items if item.status == "open"
|
|
445
|
+
),
|
|
446
|
+
):
|
|
447
|
+
yield event
|
|
448
|
+
return
|
|
433
449
|
from ksadk.runners._langgraph_interactions import (
|
|
434
450
|
persisted_interactions,
|
|
435
451
|
submission_progress,
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Select and bind graph factories for checkpoint and tunnel support."""
|
|
2
|
+
|
|
3
|
+
from ._langgraph_checkpoint_binding import bind_native_checkpointer
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class LangGraphFactoryMixin:
|
|
7
|
+
def _sdk_mcp_agent(self, graph=None):
|
|
8
|
+
graph = self._agent if graph is None else graph
|
|
9
|
+
builder = getattr(graph, "builder", None)
|
|
10
|
+
return vars(builder).get("_ksadk_mcp_agent") if hasattr(builder, "__dict__") else None
|
|
11
|
+
|
|
12
|
+
def _graph_factory(self, *, module=None, agent=None):
|
|
13
|
+
module = self._module if module is None else module
|
|
14
|
+
agent = self._agent if agent is None else agent
|
|
15
|
+
factory = getattr(module, "ksadk_graph_factory", None)
|
|
16
|
+
tunnel_tools = self._configured_tunnel_tools()
|
|
17
|
+
if tunnel_tools is not None:
|
|
18
|
+
return self._tunnel_graph_factory(factory, agent, tunnel_tools)
|
|
19
|
+
if callable(factory):
|
|
20
|
+
return factory
|
|
21
|
+
if self._sdk_mcp_agent(agent) is not None:
|
|
22
|
+
return lambda *, checkpointer: bind_native_checkpointer(agent, checkpointer)
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
def _configured_tunnel_tools(self):
|
|
26
|
+
binding = getattr(self, "_tunnel_binding", None)
|
|
27
|
+
if binding is None:
|
|
28
|
+
return None
|
|
29
|
+
from ksadk.tunnel.langgraph import TunnelTools
|
|
30
|
+
|
|
31
|
+
if self._tunnel_tools is None:
|
|
32
|
+
self._tunnel_tools = TunnelTools(binding.policy.agent_id, binding.registry)
|
|
33
|
+
return self._tunnel_tools
|
|
34
|
+
|
|
35
|
+
def _build_loaded_tunnel_graph(self, module, agent, managed_saver, local_saver):
|
|
36
|
+
saver = managed_saver
|
|
37
|
+
if saver is None:
|
|
38
|
+
saver = getattr(agent, "checkpointer", None)
|
|
39
|
+
if saver is None:
|
|
40
|
+
saver = local_saver
|
|
41
|
+
factory = self._graph_factory(module=module, agent=agent)
|
|
42
|
+
return factory(checkpointer=saver)
|
|
43
|
+
|
|
44
|
+
def _tunnel_graph_factory(self, factory, agent, tunnel_tools):
|
|
45
|
+
"""Require explicit integration for arbitrary compiled application graphs."""
|
|
46
|
+
import inspect
|
|
47
|
+
|
|
48
|
+
accepts_tunnel = False
|
|
49
|
+
if callable(factory):
|
|
50
|
+
params = inspect.signature(factory).parameters
|
|
51
|
+
accepts_tunnel = (
|
|
52
|
+
"tunnel_tools" in params
|
|
53
|
+
and params["tunnel_tools"].kind != inspect.Parameter.POSITIONAL_ONLY
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def build(*, checkpointer):
|
|
57
|
+
if accepts_tunnel:
|
|
58
|
+
graph = factory(checkpointer=checkpointer, tunnel_tools=tunnel_tools)
|
|
59
|
+
elif callable(factory):
|
|
60
|
+
graph = factory(checkpointer=checkpointer)
|
|
61
|
+
else:
|
|
62
|
+
graph = agent
|
|
63
|
+
from langgraph.graph.state import CompiledStateGraph
|
|
64
|
+
|
|
65
|
+
if not isinstance(graph, CompiledStateGraph):
|
|
66
|
+
raise TypeError("MCP tunnel graph factory must return CompiledStateGraph")
|
|
67
|
+
if self._sdk_mcp_agent(graph) is not None:
|
|
68
|
+
from ksadk.mcp_runtime.oauth._agent import bind_tunnel_graph
|
|
69
|
+
|
|
70
|
+
graph = bind_tunnel_graph(graph, tunnel_tools, checkpointer=checkpointer)
|
|
71
|
+
elif not accepts_tunnel:
|
|
72
|
+
raise TypeError(
|
|
73
|
+
"LangGraph MCP tunnel requires an SDK create_mcp_agent graph or "
|
|
74
|
+
"ksadk_graph_factory(*, checkpointer, tunnel_tools). Custom graphs "
|
|
75
|
+
"must explicitly bind tunnel_tools in their model and tool nodes."
|
|
76
|
+
)
|
|
77
|
+
return graph
|
|
78
|
+
|
|
79
|
+
return build
|
|
@@ -413,6 +413,12 @@ class _LangGraphStreamMixin(_LangGraphCanonicalStreamMixin):
|
|
|
413
413
|
final_output_last_usage = self._extract_last_usage(output)
|
|
414
414
|
|
|
415
415
|
except Exception as e:
|
|
416
|
+
from ksadk.tunnel.failure import tunnel_failure
|
|
417
|
+
|
|
418
|
+
if failure := tunnel_failure(e):
|
|
419
|
+
yield {"type": "text", "delta": failure.message}
|
|
420
|
+
yield {"type": "final", "output": failure.message, "metadata": failure.metadata}
|
|
421
|
+
return
|
|
416
422
|
if "Interrupt" in type(e).__name__:
|
|
417
423
|
state, error = await self._read_graph_state(config, include_subgraphs=True)
|
|
418
424
|
if state is None:
|
|
@@ -44,12 +44,17 @@ class ADKSessionIdentityMixin:
|
|
|
44
44
|
f"{owner_scope_ref}:{external_session_id}" if owner_scope_ref else external_session_id
|
|
45
45
|
)
|
|
46
46
|
|
|
47
|
+
def _adk_session_app_name(self) -> str:
|
|
48
|
+
# A user-supplied App can have a different name from its root agent.
|
|
49
|
+
app_name = getattr(getattr(self, "_runner", None), "app_name", None)
|
|
50
|
+
return app_name if isinstance(app_name, str) and app_name else self._agent.name
|
|
51
|
+
|
|
47
52
|
async def _get_adk_session(self, *, user_id: str, session_id: str) -> Any | None:
|
|
48
53
|
if self._session_service is None or not session_id:
|
|
49
54
|
return None
|
|
50
55
|
try:
|
|
51
56
|
return await self._session_service.get_session(
|
|
52
|
-
app_name=self.
|
|
57
|
+
app_name=self._adk_session_app_name(),
|
|
53
58
|
user_id=user_id,
|
|
54
59
|
session_id=session_id,
|
|
55
60
|
)
|
|
@@ -65,7 +70,7 @@ class ADKSessionIdentityMixin:
|
|
|
65
70
|
) -> Any:
|
|
66
71
|
if self._short_term_memory:
|
|
67
72
|
session = await self._short_term_memory.create_session(
|
|
68
|
-
app_name=self.
|
|
73
|
+
app_name=self._adk_session_app_name(),
|
|
69
74
|
user_id=user_id,
|
|
70
75
|
session_id=session_id,
|
|
71
76
|
)
|
|
@@ -73,7 +78,7 @@ class ADKSessionIdentityMixin:
|
|
|
73
78
|
if self._session_service is None:
|
|
74
79
|
raise RuntimeError("ADK session service is not initialized")
|
|
75
80
|
create_kwargs: dict[str, Any] = {
|
|
76
|
-
"app_name": self.
|
|
81
|
+
"app_name": self._adk_session_app_name(),
|
|
77
82
|
"user_id": user_id,
|
|
78
83
|
}
|
|
79
84
|
if session_id and preserve_requested_id:
|
ksadk/runners/adk_runner.py
CHANGED
|
@@ -124,8 +124,13 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
124
124
|
import json as _stdlib_json
|
|
125
125
|
|
|
126
126
|
from ksadk.compat.adk_compat import lite_llm_module
|
|
127
|
+
from ksadk.compat.adk_stream import (
|
|
128
|
+
normalize_tool_call_types,
|
|
129
|
+
normalize_tool_delta_types,
|
|
130
|
+
)
|
|
127
131
|
|
|
128
132
|
adk_lite_llm = lite_llm_module()
|
|
133
|
+
normalize_tool_delta_types(adk_lite_llm)
|
|
129
134
|
|
|
130
135
|
_original_fn = adk_lite_llm._message_to_generate_content_response
|
|
131
136
|
if getattr(_original_fn, "__ksadk_json_patch__", False):
|
|
@@ -148,6 +153,7 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
148
153
|
if "thought_parts" in _orig_params:
|
|
149
154
|
forward_kwargs["thought_parts"] = thought_parts
|
|
150
155
|
try:
|
|
156
|
+
normalize_tool_call_types(message)
|
|
151
157
|
result = _original_fn(message, **forward_kwargs)
|
|
152
158
|
except _stdlib_json.JSONDecodeError:
|
|
153
159
|
logger.warning(
|
|
@@ -581,8 +587,11 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
581
587
|
self._resume_disabled_reason_code = "ADK_VERSION_UNSUPPORTED"
|
|
582
588
|
|
|
583
589
|
if resumable.app is not None:
|
|
590
|
+
app = resumable.app
|
|
591
|
+
if getattr(self, "_tunnel_binding", None) is not None:
|
|
592
|
+
app = app.model_copy(update={"root_agent": self._agent})
|
|
584
593
|
runner_kwargs = dict(
|
|
585
|
-
app=
|
|
594
|
+
app=app,
|
|
586
595
|
session_service=self._session_service,
|
|
587
596
|
)
|
|
588
597
|
elif resumable.enabled:
|
|
@@ -899,6 +908,35 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
899
908
|
except Exception as exc:
|
|
900
909
|
logger.warning(f"Failed to inject MCP toolsets: {exc}")
|
|
901
910
|
|
|
911
|
+
def _inject_tunnel_toolset(self):
|
|
912
|
+
"""App-owned dynamic MCP discovery, bound to deployment identity."""
|
|
913
|
+
binding = getattr(self, "_tunnel_binding", None)
|
|
914
|
+
if binding is None:
|
|
915
|
+
return
|
|
916
|
+
from ksadk.tunnel.toolset import TunnelToolset
|
|
917
|
+
|
|
918
|
+
toolset = TunnelToolset(binding.policy.agent_id, binding.registry)
|
|
919
|
+
# Composite ADK agents (e.g. SequentialAgent) delegate to their children.
|
|
920
|
+
# Attach at the first tool-capable agent on each such execution path.
|
|
921
|
+
pending = [self._agent]
|
|
922
|
+
installed = False
|
|
923
|
+
while pending:
|
|
924
|
+
agent = pending.pop()
|
|
925
|
+
if not hasattr(agent, "tools"):
|
|
926
|
+
pending.extend(getattr(agent, "sub_agents", ()))
|
|
927
|
+
continue
|
|
928
|
+
tools = list(agent.tools or [])
|
|
929
|
+
for previous in tools:
|
|
930
|
+
if isinstance(previous, TunnelToolset) and (
|
|
931
|
+
previous._registry is not binding.registry
|
|
932
|
+
or previous.agent_id != binding.policy.agent_id
|
|
933
|
+
):
|
|
934
|
+
raise ValueError("ADK agent already belongs to another tunnel binding")
|
|
935
|
+
agent.tools = [tool for tool in tools if not isinstance(tool, TunnelToolset)] + [toolset]
|
|
936
|
+
installed = True
|
|
937
|
+
if installed:
|
|
938
|
+
self._runtime_toolsets.append(toolset)
|
|
939
|
+
|
|
902
940
|
def _inject_builtin_tools(self):
|
|
903
941
|
"""Inject ksadk built-in tools according to the runtime profile."""
|
|
904
942
|
try:
|
|
@@ -1045,6 +1083,13 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
1045
1083
|
self.detection_result.agent_variable,
|
|
1046
1084
|
)
|
|
1047
1085
|
|
|
1086
|
+
if deferred := getattr(self, "_deferred_tunnel", None):
|
|
1087
|
+
self._tunnel_binding = deferred.resolve(self._agent, self._module)
|
|
1088
|
+
if getattr(self, "_tunnel_binding", None) is not None:
|
|
1089
|
+
# ADK clone rebuilds the sub-agent tree and its parent links while
|
|
1090
|
+
# preserving existing models, callbacks and tool implementations.
|
|
1091
|
+
self._agent = self._agent.clone()
|
|
1092
|
+
|
|
1048
1093
|
# Inject safety instruction for DeepSeek/LLMs to prevent empty tool names
|
|
1049
1094
|
if hasattr(self._agent, "instruction"):
|
|
1050
1095
|
safety_prompt = "\nIMPORTANT: Do NOT output tool calls with empty names."
|
|
@@ -1092,6 +1137,7 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
1092
1137
|
self._inject_skill_runtime_tools()
|
|
1093
1138
|
self._inject_builtin_tools()
|
|
1094
1139
|
self._inject_mcp_toolsets()
|
|
1140
|
+
self._inject_tunnel_toolset()
|
|
1095
1141
|
|
|
1096
1142
|
# 初始化 Runner (使用 _build_runner 以支持 ResumabilityConfig)
|
|
1097
1143
|
self._build_runner()
|
|
@@ -1228,7 +1274,7 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
1228
1274
|
|
|
1229
1275
|
try:
|
|
1230
1276
|
session = await self._session_service.get_session(
|
|
1231
|
-
app_name=self.
|
|
1277
|
+
app_name=self._adk_session_app_name(),
|
|
1232
1278
|
user_id=user_id,
|
|
1233
1279
|
session_id=session_id,
|
|
1234
1280
|
)
|
|
@@ -1998,6 +2044,16 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
1998
2044
|
|
|
1999
2045
|
preserve_a2a_stream_identity(self._agent)
|
|
2000
2046
|
events_async = self._runner.run_async(**run_kwargs)
|
|
2047
|
+
if getattr(self, "_tunnel_binding", None) is not None:
|
|
2048
|
+
from ksadk.runners._adk_tunnel_history import preserve_tunnel_history
|
|
2049
|
+
|
|
2050
|
+
events_async = preserve_tunnel_history(
|
|
2051
|
+
events_async,
|
|
2052
|
+
session_service=self._session_service,
|
|
2053
|
+
app_name=self._adk_session_app_name(),
|
|
2054
|
+
user_id=native_user_id,
|
|
2055
|
+
session_id=session_id,
|
|
2056
|
+
)
|
|
2001
2057
|
|
|
2002
2058
|
if ksadk_invocation_id and self._resumable:
|
|
2003
2059
|
wrapped_async = self._collect_adk_invocation_id(
|
|
@@ -2049,7 +2105,11 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
2049
2105
|
# Langfuse Exporter 会读取这些 span attributes
|
|
2050
2106
|
agent_user_id, tags, _, _ = self._prepare_trace_metadata(session_id)
|
|
2051
2107
|
|
|
2052
|
-
|
|
2108
|
+
business_session_id = req_session_id or session_id
|
|
2109
|
+
span.set_attribute("ksadk.session_id", business_session_id)
|
|
2110
|
+
span.set_attribute("session.id", business_session_id)
|
|
2111
|
+
span.set_attribute("gen_ai.conversation.id", business_session_id)
|
|
2112
|
+
span.set_attribute("langfuse.session_id", business_session_id)
|
|
2053
2113
|
if agent_user_id:
|
|
2054
2114
|
span.set_attribute("langfuse.user_id", agent_user_id)
|
|
2055
2115
|
if tags:
|
|
@@ -2071,20 +2131,28 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
2071
2131
|
last_event = None
|
|
2072
2132
|
usage: dict[str, Any] = {}
|
|
2073
2133
|
last_usage: dict[str, Any] = {}
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2134
|
+
tunnel_outcome = None
|
|
2135
|
+
try:
|
|
2136
|
+
async for event in wrapped_async:
|
|
2137
|
+
events_list.append(event)
|
|
2138
|
+
last_event = event
|
|
2139
|
+
event_usage = self._extract_event_usage(event)
|
|
2140
|
+
if event_usage:
|
|
2141
|
+
usage = accumulate_usage(usage, event_usage)
|
|
2142
|
+
last_usage = event_usage # 保留最后一个非空(窗口占用=最后一次 input)
|
|
2143
|
+
if hasattr(event, "content") and event.content:
|
|
2144
|
+
if hasattr(event.content, "parts"):
|
|
2145
|
+
for part in event.content.parts:
|
|
2146
|
+
# 过滤掉思考内容 (thought=True),只保留最终答案
|
|
2147
|
+
is_thought = getattr(part, "thought", False)
|
|
2148
|
+
if hasattr(part, "text") and part.text and not is_thought:
|
|
2149
|
+
final_response += part.text
|
|
2150
|
+
except Exception as exc:
|
|
2151
|
+
from ksadk.tunnel.failure import tunnel_failure
|
|
2152
|
+
|
|
2153
|
+
tunnel_outcome = tunnel_failure(exc)
|
|
2154
|
+
if tunnel_outcome is None:
|
|
2155
|
+
raise
|
|
2088
2156
|
|
|
2089
2157
|
# Prefer the last event's text (usually the complete answer).
|
|
2090
2158
|
# When the loop aborts early (MCP error, phantom tool-call),
|
|
@@ -2095,7 +2163,9 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
2095
2163
|
is_thought = getattr(part, "thought", False)
|
|
2096
2164
|
if hasattr(part, "text") and part.text and not is_thought:
|
|
2097
2165
|
last_event_text += part.text
|
|
2098
|
-
if
|
|
2166
|
+
if tunnel_outcome is not None:
|
|
2167
|
+
final_response = tunnel_outcome.message
|
|
2168
|
+
elif last_event_text:
|
|
2099
2169
|
final_response = last_event_text
|
|
2100
2170
|
|
|
2101
2171
|
if not final_response and events_list:
|
|
@@ -2111,6 +2181,8 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
2111
2181
|
"output": final_response,
|
|
2112
2182
|
"events": events_list,
|
|
2113
2183
|
}
|
|
2184
|
+
if tunnel_outcome is not None:
|
|
2185
|
+
result["metadata"] = tunnel_outcome.metadata
|
|
2114
2186
|
if usage:
|
|
2115
2187
|
result["usage"] = usage
|
|
2116
2188
|
# last_usage = 最后一次 LLM 调用快照(input_tokens = 当前上下文窗口占用)
|
|
@@ -2169,7 +2241,11 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
2169
2241
|
# 准备 Metadata 并设置 Span Attributes
|
|
2170
2242
|
agent_user_id, tags, _, _ = self._prepare_trace_metadata(session_id)
|
|
2171
2243
|
|
|
2172
|
-
|
|
2244
|
+
business_session_id = req_session_id or session_id
|
|
2245
|
+
span.set_attribute("ksadk.session_id", business_session_id)
|
|
2246
|
+
span.set_attribute("session.id", business_session_id)
|
|
2247
|
+
span.set_attribute("gen_ai.conversation.id", business_session_id)
|
|
2248
|
+
span.set_attribute("langfuse.session_id", business_session_id)
|
|
2173
2249
|
if agent_user_id:
|
|
2174
2250
|
span.set_attribute("langfuse.user_id", agent_user_id)
|
|
2175
2251
|
if tags:
|
|
@@ -19,6 +19,7 @@ from ksadk.runners._langgraph_checkpoint_binding import (
|
|
|
19
19
|
LocalCheckpointBindingMixin,
|
|
20
20
|
bind_native_checkpointer,
|
|
21
21
|
)
|
|
22
|
+
from ksadk.runners._langgraph_factory import LangGraphFactoryMixin
|
|
22
23
|
from ksadk.runners._langgraph_fresh_turn import fresh_memory_input, fresh_user_checkpoint
|
|
23
24
|
from ksadk.runners._langgraph_output import extract_output
|
|
24
25
|
from ksadk.runners._langgraph_runner_streams import _LangGraphStreamMixin
|
|
@@ -38,7 +39,7 @@ from ksadk.sessions.db_budget import session_db_budget
|
|
|
38
39
|
|
|
39
40
|
|
|
40
41
|
class LangGraphRunner(
|
|
41
|
-
LangGraphSessionIdentityMixin, LocalCheckpointBindingMixin, _LangGraphStreamMixin, BaseRunner
|
|
42
|
+
LangGraphFactoryMixin, LangGraphSessionIdentityMixin, LocalCheckpointBindingMixin, _LangGraphStreamMixin, BaseRunner
|
|
42
43
|
):
|
|
43
44
|
"""LangGraph 框架运行时
|
|
44
45
|
|
|
@@ -65,21 +66,7 @@ class LangGraphRunner(
|
|
|
65
66
|
self._managed_checkpoint_pool: Any = None
|
|
66
67
|
self._identity_thread_bindings: dict[str, str] = {}
|
|
67
68
|
self._identity_thread_lock = asyncio.Lock()
|
|
68
|
-
|
|
69
|
-
def _sdk_mcp_agent(self, graph=None):
|
|
70
|
-
graph = self._agent if graph is None else graph
|
|
71
|
-
builder = getattr(graph, "builder", None)
|
|
72
|
-
return vars(builder).get("_ksadk_mcp_agent") if hasattr(builder, "__dict__") else None
|
|
73
|
-
|
|
74
|
-
def _graph_factory(self, *, module=None, agent=None):
|
|
75
|
-
module = self._module if module is None else module
|
|
76
|
-
agent = self._agent if agent is None else agent
|
|
77
|
-
factory = getattr(module, "ksadk_graph_factory", None)
|
|
78
|
-
if callable(factory):
|
|
79
|
-
return factory
|
|
80
|
-
if self._sdk_mcp_agent(agent) is not None:
|
|
81
|
-
return lambda *, checkpointer: bind_native_checkpointer(agent, checkpointer)
|
|
82
|
-
return None
|
|
69
|
+
self._tunnel_tools = None
|
|
83
70
|
|
|
84
71
|
def load_agent(self) -> None:
|
|
85
72
|
self._load_agent(force_reload=False)
|
|
@@ -97,18 +84,21 @@ class LangGraphRunner(
|
|
|
97
84
|
self.detection_result.agent_variable,
|
|
98
85
|
force_reload=force_reload,
|
|
99
86
|
)
|
|
87
|
+
if deferred := getattr(self, "_deferred_tunnel", None):
|
|
88
|
+
self._tunnel_binding = deferred.resolve(agent, module)
|
|
100
89
|
local_saver = getattr(self, "_sdk_local_saver", None)
|
|
101
|
-
|
|
90
|
+
has_tunnel = self._configured_tunnel_tools() is not None
|
|
91
|
+
if has_tunnel:
|
|
92
|
+
agent = self._build_loaded_tunnel_graph(module, agent, managed_saver, local_saver)
|
|
93
|
+
elif local_saver is not None and getattr(agent, "checkpointer", None) is None:
|
|
102
94
|
factory = self._graph_factory(module=module, agent=agent)
|
|
103
95
|
agent = (
|
|
104
96
|
factory(checkpointer=local_saver)
|
|
105
97
|
if callable(factory)
|
|
106
98
|
else bind_native_checkpointer(agent, local_saver)
|
|
107
99
|
)
|
|
108
|
-
if managed_saver is not None:
|
|
109
|
-
#
|
|
110
|
-
# Recompile with our existing durable saver and pool so every
|
|
111
|
-
# session retains its checkpoint and its stable thread identity.
|
|
100
|
+
if managed_saver is not None and not has_tunnel:
|
|
101
|
+
# Preserve the existing durable saver and session identity on reload.
|
|
112
102
|
factory = self._graph_factory(module=module, agent=agent)
|
|
113
103
|
if not callable(factory):
|
|
114
104
|
raise TypeError("Managed LangGraph model reload requires ksadk_graph_factory")
|
|
@@ -1379,6 +1369,10 @@ class LangGraphRunner(
|
|
|
1379
1369
|
return output
|
|
1380
1370
|
|
|
1381
1371
|
except Exception as e:
|
|
1372
|
+
from ksadk.tunnel.failure import tunnel_failure
|
|
1373
|
+
|
|
1374
|
+
if failure := tunnel_failure(e):
|
|
1375
|
+
return {"output": failure.message, "metadata": failure.metadata}
|
|
1382
1376
|
if "Interrupt" in type(e).__name__:
|
|
1383
1377
|
state, error = await self._read_graph_state(config, include_subgraphs=True)
|
|
1384
1378
|
if state is None:
|