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.
Files changed (98) hide show
  1. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/METADATA +14 -9
  2. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/RECORD +98 -68
  3. ksadk/__init__.py +2 -1
  4. ksadk/_build_provenance.json +1 -1
  5. ksadk/_mcp_compat.py +305 -0
  6. ksadk/agent.py +29 -0
  7. ksadk/agui/_agent_kernel.py +176 -142
  8. ksadk/agui/agent.py +74 -5
  9. ksadk/agui/hosted.py +343 -0
  10. ksadk/agui/request_identity.py +11 -0
  11. ksadk/agui/routes.py +77 -2
  12. ksadk/builders/code_builder.py +30 -23
  13. ksadk/builders/container_builder.py +5 -5
  14. ksadk/builders/mcp_builder.py +142 -0
  15. ksadk/builders/project_imports.py +66 -0
  16. ksadk/cli/cmd_mcp.py +1 -1
  17. ksadk/cli/cmd_run.py +2 -4
  18. ksadk/cli/cmd_web.py +8 -0
  19. ksadk/cli/runtime_bootstrap.py +4 -1
  20. ksadk/common/cloud_headers.py +33 -6
  21. ksadk/compat/adk_compat.py +2 -0
  22. ksadk/compat/adk_stream.py +35 -0
  23. ksadk/configs/env_registry.py +31 -0
  24. ksadk/conversations/projector.py +6 -0
  25. ksadk/conversations/runtime_observability.py +1 -0
  26. ksadk/detection/mcp_detector.py +80 -22
  27. ksadk/harness/__init__.py +3 -0
  28. ksadk/harness/service_presentation.py +44 -0
  29. ksadk/harness/service_runtime.py +1038 -0
  30. ksadk/interaction/providers/harness.py +9 -4
  31. ksadk/kernel/ingress.py +35 -25
  32. ksadk/kernel/worker.py +2 -2
  33. ksadk/kernel/worker_identity.py +15 -8
  34. ksadk/knowledge_base/client.py +10 -3
  35. ksadk/mcp_runtime/oauth/_agent.py +77 -9
  36. ksadk/mcp_runtime/oauth/langgraph.py +47 -15
  37. ksadk/mcp_runtime/oauth/local/broker.py +23 -1
  38. ksadk/mcp_runtime/oauth/tools.py +46 -8
  39. ksadk/mcp_runtime/oauth/transport.py +19 -2
  40. ksadk/memory/adk/backends/sdk_ltm_backend.py +21 -12
  41. ksadk/memory/scope_ids.py +49 -0
  42. ksadk/plugins/providers/harness.py +65 -28
  43. ksadk/plugins/providers/harness_service.py +198 -0
  44. ksadk/plugins/providers/harness_service_context.py +175 -0
  45. ksadk/plugins/providers/harness_service_hooks.py +168 -0
  46. ksadk/plugins/providers/harness_service_memory.py +479 -0
  47. ksadk/plugins/providers/platform_resources.py +2 -2
  48. ksadk/resource_runtime/langgraph.py +7 -3
  49. ksadk/resource_runtime/mcp_server.py +3 -3
  50. ksadk/resource_runtime/worker.py +19 -4
  51. ksadk/runners/_adk_canonical_stream.py +38 -10
  52. ksadk/runners/_adk_tunnel_history.py +96 -0
  53. ksadk/runners/_langgraph_canonical_stream.py +16 -0
  54. ksadk/runners/_langgraph_factory.py +79 -0
  55. ksadk/runners/_langgraph_runner_streams.py +6 -0
  56. ksadk/runners/_session_identity.py +8 -3
  57. ksadk/runners/adk_runner.py +95 -19
  58. ksadk/runners/langgraph_runner.py +15 -21
  59. ksadk/runtime/factory.py +17 -5
  60. ksadk/runtime/framework_adapters.py +10 -0
  61. ksadk/runtime/langgraph_checkpoint_view.py +28 -7
  62. ksadk/runtime/launch.py +2 -0
  63. ksadk/server/factory.py +55 -0
  64. ksadk/server/routes/common.py +2 -0
  65. ksadk/server/routes/harness_service_view.py +38 -0
  66. ksadk/server/routes/ui_bootstrap.py +16 -2
  67. ksadk/skills/mcp_server/server.py +239 -217
  68. ksadk/studio/contracts.py +8 -0
  69. ksadk/studio/mcp_runtime.py +23 -8
  70. ksadk/studio/native_mcp_disclosure.py +8 -6
  71. ksadk/studio/native_mcp_tool_port.py +3 -1
  72. ksadk/studio/native_memory_context.py +10 -8
  73. ksadk/studio/native_product.py +3 -4
  74. ksadk/studio/plugin_composition.py +8 -1
  75. ksadk/studio/plugin_native_activation.py +4 -2
  76. ksadk/studio/plugin_runtime.py +9 -0
  77. ksadk/studio/service.py +2 -0
  78. ksadk/tracing/setup.py +53 -3
  79. ksadk/tunnel/__init__.py +37 -0
  80. ksadk/tunnel/connector.py +384 -0
  81. ksadk/tunnel/discovery.py +107 -0
  82. ksadk/tunnel/failure.py +168 -0
  83. ksadk/tunnel/http_tools.py +100 -0
  84. ksadk/tunnel/langgraph.py +125 -0
  85. ksadk/tunnel/middleware.py +28 -0
  86. ksadk/tunnel/peers.py +872 -0
  87. ksadk/tunnel/protocol.py +97 -0
  88. ksadk/tunnel/registry.py +306 -0
  89. ksadk/tunnel/runtime.py +147 -0
  90. ksadk/tunnel/server.py +201 -0
  91. ksadk/tunnel/services.py +366 -0
  92. ksadk/tunnel/toolset.py +78 -0
  93. ksadk/version.py +1 -1
  94. ksadk_runtime_common/memory_backend/providers/mem0.py +20 -0
  95. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/WHEEL +0 -0
  96. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/entry_points.txt +0 -0
  97. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/licenses/LICENSE +0 -0
  98. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,97 @@
1
+ """Frame limits and errors for the streaming HTTP tunnel."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ LOCAL_ERROR_CODES = frozenset(
12
+ {
13
+ "busy",
14
+ "forbidden",
15
+ "invalid_request",
16
+ "local_mcp_error",
17
+ "local_service_error",
18
+ "timeout",
19
+ "frame_too_large",
20
+ "too_many_tools",
21
+ }
22
+ )
23
+
24
+ VERSION = 2
25
+ _IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z")
26
+
27
+
28
+ class TunnelError(RuntimeError):
29
+ """A sanitized tunnel failure; a failed call may already have taken effect."""
30
+
31
+ def __init__(self, code: str, *, indeterminate: bool = False):
32
+ self.code = code
33
+ self.indeterminate = indeterminate
34
+ super().__init__(f"Tool tunnel: {code}" + (" (outcome unknown)" if indeterminate else ""))
35
+
36
+
37
+ class IncompletePeerDiscovery(TunnelError):
38
+ """No services were confirmed because one or more peers were unreachable."""
39
+
40
+ def __init__(self):
41
+ super().__init__("peer_discovery_unavailable")
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class TunnelLimits:
46
+ max_frame_bytes: int = 1_048_576
47
+ max_response_bytes: int = 8_388_608
48
+ max_inflight: int = 32
49
+ max_services: int = 16
50
+ max_tools: int = 256
51
+ registration_timeout: float = 10.0
52
+ request_timeout: float = 60.0
53
+ send_timeout: float = 5.0
54
+ heartbeat_interval: float = 15.0
55
+ idle_timeout: float = 45.0
56
+
57
+ def __post_init__(self):
58
+ for name, value in vars(self).items():
59
+ if (
60
+ isinstance(value, bool)
61
+ or not isinstance(value, (int, float))
62
+ or not math.isfinite(value)
63
+ or value <= 0
64
+ or (name.startswith("max_") and not isinstance(value, int))
65
+ ):
66
+ raise ValueError(f"{name} must be finite and positive (limits require integers)")
67
+ if self.idle_timeout <= self.heartbeat_interval:
68
+ raise ValueError("idle_timeout must exceed heartbeat_interval")
69
+
70
+
71
+ def identifier(value: Any, field: str) -> str:
72
+ if not isinstance(value, str) or not _IDENTIFIER.fullmatch(value):
73
+ raise ValueError(f"{field} must be a 1-64 character identifier")
74
+ return value
75
+
76
+
77
+ def decode_request_body(body: bytes) -> str:
78
+ try:
79
+ return body.decode("utf-8")
80
+ except UnicodeDecodeError:
81
+ raise TunnelError("invalid_request") from None
82
+
83
+
84
+ def encode(frame: dict[str, Any], limits: TunnelLimits) -> str:
85
+ raw = json.dumps(frame, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
86
+ if len(raw.encode("utf-8")) > limits.max_frame_bytes:
87
+ raise TunnelError("frame_too_large")
88
+ return raw
89
+
90
+
91
+ def decode(raw: str, limits: TunnelLimits) -> dict[str, Any]:
92
+ if not isinstance(raw, str) or len(raw.encode("utf-8")) > limits.max_frame_bytes:
93
+ raise ValueError("invalid frame size or encoding")
94
+ frame = json.loads(raw, parse_constant=lambda _: (_ for _ in ()).throw(ValueError("NaN")))
95
+ if not isinstance(frame, dict):
96
+ raise ValueError("frame must be an object")
97
+ return frame
@@ -0,0 +1,306 @@
1
+ """App-owned registrations and request correlation, never a process global registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import uuid
7
+ from contextlib import nullcontext
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+ # The transport, response streams and MCP client must use the same backend,
12
+ # even when both httpx packages are installed in a legacy MCP environment.
13
+ from ksadk._mcp_compat import httpx_module
14
+
15
+ httpx = httpx_module()
16
+
17
+ from .protocol import LOCAL_ERROR_CODES, TunnelError, TunnelLimits, decode_request_body, encode
18
+
19
+
20
+ @dataclass(eq=False)
21
+ class ConnectorConnection:
22
+ agent_id: str
23
+ services: dict[str, dict]
24
+ websocket: Any = field(repr=False)
25
+ limits: TunnelLimits
26
+ connector_id: str = field(default_factory=lambda: uuid.uuid4().hex)
27
+ pending: dict[str, asyncio.Queue] = field(default_factory=dict, repr=False)
28
+ _send_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
29
+ operations: set[asyncio.Timeout] = field(default_factory=set, repr=False)
30
+ closed: bool = False
31
+ owner: dict | None = None
32
+
33
+ async def send(self, frame: dict) -> None:
34
+ raw = encode(frame, self.limits)
35
+ async with asyncio.timeout(self.limits.send_timeout):
36
+ async with self._send_lock:
37
+ await self.websocket.send_text(raw)
38
+
39
+ async def forward(self, service: str, request: httpx.Request) -> httpx.Response:
40
+ body = decode_request_body(await request.aread())
41
+ if self.closed:
42
+ raise TunnelError("disconnected")
43
+ if len(self.pending) >= 3 * self.limits.max_inflight:
44
+ raise TunnelError("busy")
45
+ request_id = uuid.uuid4().hex
46
+ queue = asyncio.Queue(maxsize=32)
47
+ self.pending[request_id] = queue
48
+ stream = ResponseStream(self, request_id, queue)
49
+ try:
50
+ await self.send(
51
+ {
52
+ "type": "http_request",
53
+ "id": request_id,
54
+ "server": service,
55
+ "method": request.method,
56
+ "path": request.url.path.strip("/"),
57
+ "query": request.url.query.decode("ascii"),
58
+ "headers": {
59
+ k: v
60
+ for k, v in request.headers.items()
61
+ if k.lower() not in {"host", "content-length", "accept-encoding"}
62
+ },
63
+ "body": body,
64
+ }
65
+ )
66
+ head = await stream.receive()
67
+ if head["type"] != "http_response":
68
+ raise TunnelError("invalid_result")
69
+ return httpx.Response(head["status"], headers=head["headers"], stream=stream)
70
+ except BaseException:
71
+ await stream.aclose()
72
+ raise
73
+
74
+ def dispatch(self, frame: dict) -> None:
75
+ if frame.get("type") not in {"http_response", "http_chunk", "http_end", "http_error"}:
76
+ raise ValueError("unexpected HTTP tunnel frame")
77
+ frame_type = frame["type"]
78
+ if frame_type == "http_response":
79
+ status, headers = frame.get("status"), frame.get("headers")
80
+ if type(status) is not int or not 100 <= status <= 599 or not isinstance(headers, dict):
81
+ raise ValueError("invalid HTTP response head")
82
+ if any(not isinstance(k, str) or not isinstance(v, str) for k, v in headers.items()):
83
+ raise ValueError("invalid HTTP response headers")
84
+ elif frame_type == "http_chunk" and not isinstance(frame.get("data"), str):
85
+ raise ValueError("invalid HTTP response chunk")
86
+ queue = self.pending.get(frame["id"])
87
+ if queue is not None:
88
+ if queue.full():
89
+ # Never let one slow response block the shared WS reader.
90
+ self.pending.pop(frame["id"])
91
+ queue.get_nowait()
92
+ queue.put_nowait({"type": "http_error"})
93
+ else:
94
+ queue.put_nowait(frame)
95
+
96
+ def fail_all(self) -> None:
97
+ self.closed = True
98
+ # Wake MCP sessions too, including a caller waiting on a parsed SSE event.
99
+ for deadline in self.operations:
100
+ if not deadline.expired():
101
+ deadline.reschedule(asyncio.get_running_loop().time())
102
+ for queue in self.pending.values():
103
+ if queue.full():
104
+ queue.get_nowait()
105
+ queue.put_nowait({"type": "http_error"})
106
+ self.pending.clear()
107
+
108
+
109
+ class ResponseStream(httpx.AsyncByteStream):
110
+ def __init__(self, connection, request_id, queue):
111
+ self.connection = connection
112
+ self.request_id = request_id
113
+ self.queue = queue
114
+ self.done = False
115
+
116
+ async def receive(self):
117
+ async with asyncio.timeout(self.connection.limits.request_timeout):
118
+ frame = await self.queue.get()
119
+ if frame["type"] == "http_error":
120
+ code = frame.get("error")
121
+ raise TunnelError(
122
+ code
123
+ if isinstance(code, str) and code in LOCAL_ERROR_CODES
124
+ else "local_service_error"
125
+ )
126
+ return frame
127
+
128
+ async def __aiter__(self):
129
+ received = 0
130
+ try:
131
+ while True:
132
+ frame = await self.receive()
133
+ if frame["type"] == "http_end":
134
+ self.done = True
135
+ return
136
+ if frame["type"] != "http_chunk":
137
+ raise TunnelError("invalid_result")
138
+ data = frame["data"].encode("utf-8")
139
+ received += len(data)
140
+ if received > self.connection.limits.max_response_bytes:
141
+ raise TunnelError("frame_too_large")
142
+ yield data
143
+ finally:
144
+ await self.aclose()
145
+
146
+ async def aclose(self):
147
+ if self.queue is None:
148
+ return
149
+ self.queue = None
150
+ self.connection.pending.pop(self.request_id, None)
151
+ if not self.done and not self.connection.closed:
152
+ try:
153
+ await self.connection.send({"type": "http_cancel", "id": self.request_id})
154
+ except Exception:
155
+ pass
156
+
157
+
158
+ class TunnelRegistry:
159
+ """One registry per runtime app; duplicates never replace a live connector."""
160
+
161
+ def __init__(self):
162
+ self._connections: dict[tuple[str, str], ConnectorConnection] = {}
163
+ self._closed = False
164
+ self.peers = None
165
+
166
+ def add(self, connection: ConnectorConnection) -> None:
167
+ if self._closed:
168
+ raise TunnelError("closed")
169
+ if any(
170
+ (connection.agent_id, service) in self._connections for service in connection.services
171
+ ):
172
+ raise TunnelError("duplicate_service")
173
+ for service in connection.services:
174
+ self._connections[connection.agent_id, service] = connection
175
+ if self.peers is not None:
176
+ connection.owner = self.peers.owner
177
+
178
+ def remove(self, connection: ConnectorConnection) -> None:
179
+ connection.fail_all()
180
+ for service in connection.services:
181
+ key = (connection.agent_id, service)
182
+ if self._connections.get(key) is connection:
183
+ self._connections.pop(key)
184
+
185
+ def connections(self, agent_id: str) -> list[tuple[str, ConnectorConnection]]:
186
+ return [
187
+ (service, conn)
188
+ for (agent, service), conn in self._connections.items()
189
+ if agent == agent_id and not conn.closed
190
+ ]
191
+
192
+ async def discover_connections(self, agent_id):
193
+ if self.peers is None or not await self.peers.start():
194
+ return self.connections(agent_id)
195
+ local = self.connections(agent_id)
196
+ for _, connection in local:
197
+ connection.owner = self.peers.owner
198
+ connections = [*local, *await self.peers.discover(agent_id, has_local=bool(local))]
199
+ aliases = {}
200
+ for service, connection in connections:
201
+ identity = (connection.connector_id, json_owner(connection.owner))
202
+ if service in aliases and aliases[service] != identity:
203
+ raise TunnelError("ambiguous_service")
204
+ aliases[service] = identity
205
+ return connections
206
+
207
+ async def list_tools(self, agent_id, service, *, connector_id=None, owner=None):
208
+ return await self._operate(agent_id, service, connector_id, None, None, owner)
209
+
210
+ async def call_tool(self, agent_id, service, name, arguments, *, connector_id=None, owner=None):
211
+ if not isinstance(name, str) or not name or not isinstance(arguments, dict):
212
+ raise TunnelError("invalid_request")
213
+ return await self._operate(agent_id, service, connector_id, name, arguments, owner)
214
+
215
+ async def _operate(self, agent_id, service, connector_id, name, arguments, owner=None):
216
+ from .http_tools import TunnelTransport, api_operation, mcp_operation
217
+
218
+ conn = self._connections.get((agent_id, service))
219
+ if self.peers is not None:
220
+ if owner is not None and owner != self.peers.owner:
221
+ conn = await self.peers.resolve(agent_id, service, connector_id, owner)
222
+ if conn.owner != owner:
223
+ raise TunnelError("disconnected")
224
+ elif owner is None and (
225
+ conn is None or (connector_id is not None and conn.connector_id != connector_id)
226
+ ):
227
+ connections = await self.discover_connections(agent_id)
228
+ conn = next(
229
+ (
230
+ candidate
231
+ for alias, candidate in connections
232
+ if alias == service
233
+ and (connector_id is None or candidate.connector_id == connector_id)
234
+ ),
235
+ None,
236
+ )
237
+ if conn is None or (connector_id is not None and connector_id != conn.connector_id):
238
+ raise TunnelError("disconnected")
239
+ if len(conn.operations) >= conn.limits.max_inflight:
240
+ raise TunnelError("busy")
241
+ deadline = asyncio.timeout(conn.limits.request_timeout)
242
+ peer_operation = None
243
+ try:
244
+ descriptor = conn.services[service]
245
+ operation = mcp_operation if descriptor["protocol"] == "mcp" else api_operation
246
+ async with deadline:
247
+ conn.operations.add(deadline)
248
+ scope = (
249
+ self.peers.operation_scope(deadline)
250
+ if self.peers is not None
251
+ else nullcontext(None)
252
+ )
253
+ with scope as peer_operation:
254
+ return await operation(
255
+ TunnelTransport(conn, service), descriptor, name, arguments
256
+ )
257
+ except TunnelError as exc:
258
+ if exc.code in {
259
+ "local_mcp_error",
260
+ "local_service_error",
261
+ "timeout",
262
+ "disconnected",
263
+ "frame_too_large",
264
+ }:
265
+ raise TunnelError(exc.code, indeterminate=name is not None) from None
266
+ raise
267
+ except TimeoutError:
268
+ code = (
269
+ peer_operation.error
270
+ if peer_operation is not None and peer_operation.error
271
+ else "disconnected" if conn.closed else "timeout"
272
+ )
273
+ raise TunnelError(
274
+ code,
275
+ indeterminate=name is not None
276
+ and code not in {"busy", "forbidden", "invalid_request"},
277
+ ) from None
278
+ except Exception:
279
+ code = (
280
+ peer_operation.error
281
+ if peer_operation is not None and peer_operation.error
282
+ else "local_service_error"
283
+ )
284
+ raise TunnelError(
285
+ code,
286
+ indeterminate=name is not None
287
+ and code not in {"busy", "forbidden", "invalid_request"},
288
+ ) from None
289
+ finally:
290
+ conn.operations.discard(deadline)
291
+
292
+ async def close(self) -> None:
293
+ self._closed = True
294
+ connections = set(self._connections.values())
295
+ self._connections.clear()
296
+ if self.peers is not None:
297
+ await self.peers.close()
298
+ for conn in connections:
299
+ conn.fail_all()
300
+ await asyncio.gather(
301
+ *(conn.websocket.close(code=1001) for conn in connections), return_exceptions=True
302
+ )
303
+
304
+
305
+ def json_owner(owner):
306
+ return (owner["address"], owner["instance_id"]) if owner is not None else None
@@ -0,0 +1,147 @@
1
+ """Deployment-owned tunnel configuration and app/runner binding."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from .registry import TunnelRegistry
10
+ from .server import TunnelAgentPolicy
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class TunnelBinding:
15
+ policy: TunnelAgentPolicy
16
+ registry: TunnelRegistry
17
+
18
+ async def start(self):
19
+ if self.registry.peers is not None:
20
+ await self.registry.peers.start()
21
+
22
+ async def close(self):
23
+ await self.registry.close()
24
+
25
+
26
+ class DeferredTunnel:
27
+ """Resolve the exported declaration on normal runner load or the first connector request."""
28
+
29
+ def __init__(self, launch):
30
+ from threading import Lock
31
+
32
+ self.launch = launch
33
+ self.binding = None
34
+ self.resolved = False
35
+ self._lock = Lock()
36
+ self.peers = None
37
+
38
+ def _peer_registry(self):
39
+ # Peer requests use only the resolved registry; they never import agents.
40
+ return self.binding.registry if self.binding is not None else None
41
+
42
+ async def start(self):
43
+ if self.peers is not None:
44
+ await self.peers.start()
45
+
46
+ def resolve(self, root, module):
47
+ from ksadk.agent import TunnelDeclaration
48
+
49
+ with self._lock:
50
+ if not self.resolved:
51
+ declaration = getattr(root, "_ksadk_tunnel_declaration", None)
52
+ if isinstance(declaration, TunnelDeclaration) and declaration.enabled:
53
+ entry = self.launch.detection.entry_point
54
+ if (
55
+ Path(module.__file__).resolve()
56
+ != (self.launch.project_dir / entry).resolve()
57
+ ):
58
+ raise ValueError("Tunnel declaration loaded from a different project")
59
+ token = os.environ.get(declaration.token_env, "")
60
+ if not token.strip():
61
+ raise ValueError(
62
+ f"Missing tunnel token in environment variable {declaration.token_env}"
63
+ )
64
+ peers = _peer_network(self._peer_registry, token=token)
65
+ self.binding = TunnelBinding(
66
+ TunnelAgentPolicy("root", token, services=None), TunnelRegistry()
67
+ )
68
+ self.peers = peers
69
+ self.binding.registry.peers = self.peers
70
+ self.resolved = True
71
+ return self.binding
72
+
73
+ def for_connector(self):
74
+ if not self.resolved:
75
+ from ksadk.runners.utils import load_agent_module
76
+
77
+ detection = self.launch.detection
78
+ root, module = load_agent_module(
79
+ str(self.launch.project_dir), detection.entry_point, detection.agent_variable
80
+ )
81
+ return self.resolve(root, module)
82
+ return self.binding
83
+
84
+ async def close(self):
85
+ if self.binding is not None:
86
+ await self.binding.registry.close()
87
+ elif self.peers is not None:
88
+ await self.peers.close()
89
+
90
+
91
+ def bind_runner(runner, binding: TunnelBinding) -> None:
92
+ """Bind before lazy runner initialization; reject cross-app registry reuse."""
93
+ if isinstance(binding, DeferredTunnel):
94
+ runner._deferred_tunnel = binding
95
+ return
96
+ current = getattr(runner, "_tunnel_binding", None)
97
+ if current is not None and current != binding:
98
+ raise ValueError("runner already belongs to another tunnel binding")
99
+ if current is None and getattr(runner, "_agent", None) is not None:
100
+ raise ValueError("MCP tunnel must be configured before runner initialization")
101
+ runner._tunnel_binding = binding
102
+
103
+
104
+ def configure_app_tunnel(config):
105
+ """Prepare per-app tunnel state without importing the agent."""
106
+ launch = config.launch_context
107
+ tunnel_binding = launch.services.tunnel_binding if launch else None
108
+ if (
109
+ launch
110
+ and launch.runtime_type in {"adk", "langgraph"}
111
+ and getattr(launch.detection, "entry_point", None)
112
+ and getattr(launch.detection, "agent_variable", None)
113
+ and tunnel_binding is None
114
+ ):
115
+ tunnel_binding = DeferredTunnel(launch)
116
+ if tunnel_binding is not None:
117
+ from dataclasses import replace
118
+
119
+ if launch.runtime_type not in {"adk", "langgraph"}:
120
+ raise ValueError("Tool tunnel requires an ADK or LangGraph RuntimeLaunchContext")
121
+ # Keep the caller's reusable config/context untouched: every app gets
122
+ # its own registry unless an explicit process-owned binding is supplied.
123
+ from copy import copy
124
+
125
+ config = copy(config)
126
+ if not isinstance(tunnel_binding, DeferredTunnel) and tunnel_binding.registry.peers is None:
127
+ tunnel_binding.registry.peers = _peer_network(
128
+ lambda: tunnel_binding.registry, token=tunnel_binding.policy.token
129
+ )
130
+ config.launch_context = replace(
131
+ launch, services=replace(launch.services, tunnel_binding=tunnel_binding)
132
+ )
133
+ if config.a2a_runtime_adapter is not None:
134
+ configure_tunnel = getattr(config.a2a_runtime_adapter, "configure_tunnel", None)
135
+ if callable(configure_tunnel):
136
+ configure_tunnel(tunnel_binding)
137
+ elif not isinstance(tunnel_binding, DeferredTunnel):
138
+ raise ValueError("A2A adapter must support the app's tool tunnel binding")
139
+
140
+ return config, tunnel_binding
141
+
142
+
143
+ def _peer_network(registry_provider, *, token):
144
+ from .peers import PeerConfig, PeerNetwork
145
+
146
+ config = PeerConfig.from_env(tunnel_token=token)
147
+ return PeerNetwork(config, registry_provider) if config is not None else None