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
@@ -37,6 +37,13 @@ def _time(value):
37
37
  return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)
38
38
 
39
39
 
40
+ def memory_record_expiry(record):
41
+ expires = [
42
+ value for value in (_time(record.expires_at), _time(record.valid_to)) if value is not None
43
+ ]
44
+ return min(expires) if expires else None
45
+
46
+
40
47
  def admitted_memory_records(result, *, principal, scopes, top_k):
41
48
  """One host data admission for recall and explicit search projections."""
42
49
  if not isinstance(result, MemorySearchResult) or result.status not in {"ok", "not_configured"}:
@@ -54,12 +61,12 @@ def admitted_memory_records(result, *, principal, scopes, top_k):
54
61
  raise ValueError("native_memory_record_unbound")
55
62
  if record.content_hash != content_hash(record.content):
56
63
  raise ValueError("native_memory_content_mismatch")
57
- expiry = [_time(value) for value in (record.expires_at, record.valid_to) if value]
64
+ expiry = memory_record_expiry(record)
58
65
  valid_from = _time(record.valid_from)
59
66
  if (
60
67
  record.status != "active"
61
68
  or record.sensitivity == "high"
62
- or any(value <= now for value in expiry)
69
+ or (expiry is not None and expiry <= now)
63
70
  or (valid_from is not None and valid_from > now)
64
71
  ):
65
72
  continue
@@ -142,12 +149,7 @@ class StudioMemoryContextSource:
142
149
  scopes=recall.scopes,
143
150
  top_k=recall.top_k,
144
151
  ):
145
- expires = [
146
- value
147
- for value in (_time(record.expires_at), _time(record.valid_to))
148
- if value is not None
149
- ]
150
- expiry = min(expires) if expires else None
152
+ expiry = memory_record_expiry(record)
151
153
  fragments.append(
152
154
  ContextFragment(
153
155
  fragment_format="ksadk.context-fragment/v1",
@@ -877,10 +877,9 @@ class StudioNativeProductComposer:
877
877
  # Missing only in legacy sealed Builds. New Builds carry an
878
878
  # explicit object even when neither count is bounded.
879
879
  native_limits = execution.native_limits
880
- model_call_budget = (native_limits.max_model_calls if native_limits is not None
881
- else min(100, execution.max_steps))
882
- tool_call_budget = (native_limits.max_tool_calls if native_limits is not None
883
- else min(400, max(4, execution.max_steps * 4)))
880
+ call_limits = execution.native_call_limits()
881
+ model_call_budget = call_limits.max_model_calls
882
+ tool_call_budget = call_limits.max_tool_calls
884
883
  reserve_basis = (model_call_budget if native_limits is not None
885
884
  else execution.max_steps)
886
885
  workspace_port = StudioNativeWorkspacePort(
@@ -14,6 +14,7 @@ from collections.abc import Mapping
14
14
  from copy import deepcopy
15
15
  from dataclasses import replace
16
16
 
17
+ from ksadk.harness.service_runtime import harness_service_configured
17
18
  from ksadk.harness.tools import HARNESS_SANDBOX_TOOL_NAMES
18
19
  from ksadk.plugins.builtins import (
19
20
  BUILTIN_PLUGIN_VERSION,
@@ -181,7 +182,13 @@ class StudioPluginCompositionCompiler:
181
182
  config={"artifactPath": "platform-resources"},
182
183
  ))
183
184
  policy = CompositionPolicy(
184
- runtimes={"harness": RuntimePluginSelection(provider_ref=harness_ref)},
185
+ runtimes={"harness": RuntimePluginSelection(
186
+ provider_ref=harness_ref,
187
+ supported_strategies=(
188
+ frozenset({"direct", "plan-act-observe"})
189
+ if harness_service_configured() else frozenset({"direct"})
190
+ ),
191
+ )},
185
192
  providers=providers,
186
193
  session_store=_selection(
187
194
  SQLITE_SESSION_STORE_PLUGIN_ID,
@@ -8,6 +8,7 @@ from typing import Any
8
8
 
9
9
  from ksadk.harness.native.studio_admission import studio_mapping_digest
10
10
  from ksadk.harness.native_runtime import NativeRuntimeAdapter
11
+ from ksadk.harness.service_runtime import harness_service_configured
11
12
  from ksadk.plugins.host import PluginActivationSession, PluginHostError
12
13
  from ksadk.studio.errors import StudioError
13
14
  from ksadk.studio.run_service import StudioRunSpec
@@ -24,9 +25,10 @@ class StudioNativeActivationMixin:
24
25
  async def _native_activation_claims(
25
26
  self, spec: StudioRunSpec, session_id: str
26
27
  ) -> dict[str, str] | None:
27
- if (
28
+ if spec.request_config.get("provider_runtime_type") != "harness":
29
+ return None
30
+ if not harness_service_configured() and (
28
31
  self._harness_engine_selector is None
29
- or spec.request_config.get("provider_runtime_type") != "harness"
30
32
  or (self._harness_native_session_enabled is not None
31
33
  and not self._harness_native_session_enabled(spec.agent_id, session_id))
32
34
  ):
@@ -10,6 +10,7 @@ from dataclasses import dataclass
10
10
  from pathlib import Path
11
11
  from typing import Any, cast
12
12
 
13
+ from ksadk.harness.native.hook_executor import HookAuthorizer
13
14
  from ksadk.harness.reasoner import (
14
15
  HarnessReasoner,
15
16
  HarnessReasoningTurn,
@@ -818,6 +819,8 @@ class StudioPluginRuntime(StudioNativeActivationMixin):
818
819
  resource_actor_ref: str = "local-user",
819
820
  native_tenant_id: str = "local-studio",
820
821
  native_workspace_id: str | None = None,
822
+ service_hook_authorizer: HookAuthorizer | None = None,
823
+ service_hook_authorization_version: str | None = None,
821
824
  codex_local_launch_resolver: Any = None,
822
825
  runtime_executor: RuntimeExecutor | None = None,
823
826
  ) -> None:
@@ -845,6 +848,8 @@ class StudioPluginRuntime(StudioNativeActivationMixin):
845
848
  self._resource_actor_ref = resource_actor_ref
846
849
  self._native_tenant_id = native_tenant_id
847
850
  self._native_workspace_id = native_workspace_id
851
+ self._service_hook_authorizer = service_hook_authorizer
852
+ self._service_hook_authorization_version = service_hook_authorization_version
848
853
  self._codex_local_launch_resolver = codex_local_launch_resolver
849
854
  self._runtime_executor = runtime_executor
850
855
  self._legacy_bundles = LegacyBundleAdapter(legacy_harness_sources)
@@ -1182,6 +1187,10 @@ class StudioPluginRuntime(StudioNativeActivationMixin):
1182
1187
  services["harness_reasoner"] = (
1183
1188
  self._harness_reasoner or self._bound_harness_reasoner(verified)
1184
1189
  )
1190
+ services["harness_service_hook_authorizer"] = self._service_hook_authorizer
1191
+ services["harness_service_hook_authorization_version"] = (
1192
+ self._service_hook_authorization_version
1193
+ )
1185
1194
  if self._harness_engine_selector is not None:
1186
1195
  services["harness_engine_selector"] = self._harness_engine_selector
1187
1196
  services["harness_native_adapter_builder"] = (
ksadk/studio/service.py CHANGED
@@ -579,6 +579,8 @@ class StudioService(StudioSettingsMixin):
579
579
  resource_connections=self.resource_connections,
580
580
  resource_actor_ref="local-user",
581
581
  native_workspace_id=self.workspace_record.workspace_id,
582
+ service_hook_authorizer=native_harness_hook_authorizer,
583
+ service_hook_authorization_version=native_harness_hook_authorization_version,
582
584
  )
583
585
  self.run_service.plugin_runtime = self.plugin_runs
584
586
  self.scheduler_runtimes = StudioScheduledKernelRegistry(
ksadk/tracing/setup.py CHANGED
@@ -2,7 +2,7 @@
2
2
  Tracing 初始化 - 标准 OTLP 双写(Langfuse 主 + CloudMonitor 次)
3
3
 
4
4
  每个 Python Agent 进程一个 TracerProvider,挂两个 OTLP/HTTP protobuf BatchSpanProcessor,
5
- 消费同一批 ReadableSpan。仅为 CloudMonitor 克隆并补充兼容属性,不修改原始 span。
5
+ 消费同一批 ReadableSpan。导出前统一业务会话 ID,CloudMonitor 额外补充兼容属性。
6
6
 
7
7
  支持 ADK 自动插桩 via openinference-instrumentation-google-adk
8
8
  """
@@ -20,7 +20,7 @@ from typing import Any, Optional
20
20
  from urllib.parse import unquote
21
21
 
22
22
  from opentelemetry.sdk.resources import Resource
23
- from opentelemetry.sdk.trace import ReadableSpan
23
+ from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor
24
24
  from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
25
25
 
26
26
  from ksadk.tracing.exporters.inmemory_exporter import InMemoryExporter
@@ -596,8 +596,58 @@ def _build_generic_otlp_http_config() -> Optional[dict]:
596
596
  }
597
597
 
598
598
 
599
+ class _SessionIdentitySpanProcessor(SpanProcessor):
600
+ """Normalize business identity before either static or routed export queues.
601
+
602
+ Capture identity at span start: ADK may overwrite its conversation ID later,
603
+ and a child may be exported in a different batch/context from its parent.
604
+ Native ADK session objects and stored session bindings are never modified.
605
+ """
606
+
607
+ def __init__(self, processor: SpanProcessor):
608
+ self._processor = processor
609
+
610
+ def on_start(self, span, parent_context=None):
611
+ from opentelemetry import trace
612
+
613
+ from ksadk.runtime_context import get_current_invocation_context
614
+
615
+ invocation = get_current_invocation_context()
616
+ parent = trace.get_current_span(parent_context)
617
+ session_id = (
618
+ (invocation.session_id if invocation else "")
619
+ or (span.attributes or {}).get("ksadk.session_id")
620
+ or (getattr(parent, "attributes", None) or {}).get("ksadk.session_id")
621
+ )
622
+ if session_id:
623
+ span.set_attribute("ksadk.session_id", session_id)
624
+ self._processor.on_start(span, parent_context=parent_context)
625
+
626
+ def on_end(self, span):
627
+ session_id = (span.attributes or {}).get("ksadk.session_id")
628
+ if session_id:
629
+ attributes = dict(span.attributes)
630
+ attributes.update(
631
+ {
632
+ "session.id": session_id,
633
+ "gen_ai.conversation.id": session_id,
634
+ "langfuse.session.id": session_id,
635
+ }
636
+ )
637
+ if "langfuse.session_id" in attributes:
638
+ attributes["langfuse.session_id"] = session_id
639
+ span = _clone_span(span, attributes=attributes, resource=span.resource)
640
+ self._processor.on_end(span)
641
+
642
+ def shutdown(self):
643
+ self._processor.shutdown()
644
+
645
+ def force_flush(self, timeout_millis=30000):
646
+ return self._processor.force_flush(timeout_millis=timeout_millis)
647
+
648
+
599
649
  def _register_span_processor(provider: Any, processor: Any) -> None:
600
- provider.add_span_processor(processor)
650
+ provider.add_span_processor(_SessionIdentitySpanProcessor(processor))
601
651
  _managed_span_processors.append(processor)
602
652
 
603
653
 
@@ -0,0 +1,37 @@
1
+ """Lazy public API for outbound MCP tunnels.
2
+
3
+ Keeping exports lazy allows runtime configuration modules to be imported without
4
+ loading Google ADK or enabling Tunnel itself.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from importlib import import_module
10
+ from typing import Any
11
+
12
+ _EXPORTS = {
13
+ "LocalMCPService": "ksadk.tunnel.services",
14
+ "LocalAPIService": "ksadk.tunnel.services",
15
+ "APIOperation": "ksadk.tunnel.services",
16
+ "TunnelConnector": "ksadk.tunnel.connector",
17
+ "TunnelError": "ksadk.tunnel.protocol",
18
+ "TunnelLimits": "ksadk.tunnel.protocol",
19
+ "TunnelRegistry": "ksadk.tunnel.registry",
20
+ "TunnelToolset": "ksadk.tunnel.toolset",
21
+ "TunnelTools": "ksadk.tunnel.langgraph",
22
+ }
23
+
24
+ __all__ = list(_EXPORTS)
25
+
26
+
27
+ def __getattr__(name: str) -> Any:
28
+ module_name = _EXPORTS.get(name)
29
+ if module_name is None:
30
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
31
+ value = getattr(import_module(module_name), name)
32
+ globals()[name] = value
33
+ return value
34
+
35
+
36
+ def __dir__() -> list[str]:
37
+ return sorted(set(globals()) | set(_EXPORTS))
@@ -0,0 +1,384 @@
1
+ """Enterprise-side outbound connector. Only configured local tools are reachable."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import codecs
7
+ import logging
8
+ import math
9
+ import random
10
+ import ssl
11
+ from typing import Any
12
+ from urllib.parse import urlsplit, urlunsplit
13
+
14
+ # The transport, response streams and MCP client must use the same backend,
15
+ # even when both httpx packages are installed in a legacy MCP environment.
16
+ from ksadk._mcp_compat import httpx_module
17
+
18
+ httpx = httpx_module()
19
+ from websockets.exceptions import ConnectionClosed, InvalidHandshake
20
+ from websockets.legacy.client import Connect
21
+
22
+ from .protocol import (
23
+ LOCAL_ERROR_CODES,
24
+ VERSION,
25
+ TunnelError,
26
+ TunnelLimits,
27
+ decode,
28
+ encode,
29
+ identifier,
30
+ )
31
+ from .services import LocalAPIService, LocalMCPService, prepare_request, response_headers
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ class _DirectConnect(Connect):
37
+ def handle_redirect(self, uri: str) -> None:
38
+ # A gateway redirect must never forward its Authorization credential.
39
+ raise TunnelError("gateway_redirect_rejected")
40
+
41
+
42
+ class TunnelConnector:
43
+ """A reconnecting connector. Disconnected or timed-out calls are never replayed."""
44
+
45
+ def __init__(
46
+ self,
47
+ cloud_url: str,
48
+ *,
49
+ agent_id: str | None = None,
50
+ token: str,
51
+ services: list[LocalMCPService | LocalAPIService],
52
+ gateway_headers: dict[str, str] | None = None,
53
+ verify_tls: bool = True,
54
+ limits: TunnelLimits | None = None,
55
+ reconnect_min: float = 0.5,
56
+ reconnect_max: float = 30.0,
57
+ reconnect_handshake_grace: float = 120.0,
58
+ ):
59
+ parsed = urlsplit(cloud_url)
60
+ if (
61
+ parsed.scheme not in {"http", "https", "ws", "wss"}
62
+ or not parsed.hostname
63
+ or parsed.query
64
+ or parsed.fragment
65
+ or parsed.username
66
+ or parsed.password
67
+ ):
68
+ raise ValueError("cloud_url must be a base URL without credentials/query/fragment")
69
+ scheme = {"http": "ws", "https": "wss"}.get(parsed.scheme, parsed.scheme)
70
+ if not isinstance(verify_tls, bool):
71
+ raise TypeError("verify_tls must be a bool")
72
+ self._ssl_context = None
73
+ if scheme == "wss":
74
+ if verify_tls:
75
+ self._ssl_context = ssl.create_default_context()
76
+ else:
77
+ self._ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
78
+ self._ssl_context.check_hostname = False
79
+ self._ssl_context.verify_mode = ssl.CERT_NONE
80
+ self._url = urlunsplit(
81
+ (scheme, parsed.netloc, parsed.path.rstrip("/") + "/tunnel/connect", "", "")
82
+ )
83
+ self.agent_id = identifier(agent_id, "agent_id") if agent_id is not None else None
84
+ if not isinstance(token, str) or not token.strip():
85
+ raise ValueError("a non-empty tunnel token is required")
86
+ self._token = token
87
+ self._headers = dict(gateway_headers or {})
88
+ self.limits = limits or TunnelLimits()
89
+ if (
90
+ not isinstance(services, (list, tuple))
91
+ or not services
92
+ or len(services) > self.limits.max_services
93
+ or any(
94
+ not isinstance(service, (LocalMCPService, LocalAPIService)) for service in services
95
+ )
96
+ or len({s.name for s in services}) != len(services)
97
+ ):
98
+ raise ValueError("services must be non-empty, unique and within max_services")
99
+ self._services = {s.name: s for s in services}
100
+ self._descriptors = [service.descriptor() for service in services]
101
+ if any(
102
+ max(len(item.get("tools", [])), len(item.get("tool_filter") or ()))
103
+ > self.limits.max_tools
104
+ for item in self._descriptors
105
+ ):
106
+ raise ValueError("service tool count exceeds max_tools")
107
+ if (
108
+ not math.isfinite(reconnect_min)
109
+ or not math.isfinite(reconnect_max)
110
+ or not math.isfinite(reconnect_handshake_grace)
111
+ or reconnect_min <= 0
112
+ or reconnect_max < reconnect_min
113
+ or reconnect_handshake_grace < 0
114
+ ):
115
+ raise ValueError("invalid reconnect bounds")
116
+ self._reconnect_min, self._reconnect_max = reconnect_min, reconnect_max
117
+ self._handshake_grace = reconnect_handshake_grace
118
+ self._registrations = 0
119
+ self._stop = asyncio.Event()
120
+ self.connected = asyncio.Event()
121
+ self._ws: Any = None
122
+ self._running = False
123
+
124
+ async def close(self) -> None:
125
+ self._stop.set()
126
+ if self._ws is not None:
127
+ await self._ws.close()
128
+
129
+ async def run(self, *, reconnect: bool = True) -> None:
130
+ if self._running:
131
+ raise RuntimeError("connector is already running")
132
+ self._running = True
133
+ delay = self._reconnect_min
134
+ recovery_deadline = 0.0
135
+ try:
136
+ while not self._stop.is_set():
137
+ registrations = self._registrations
138
+ try:
139
+ try:
140
+ await self._run_connection()
141
+ finally:
142
+ if self._registrations != registrations:
143
+ # Begin a fixed recovery window only after a new
144
+ # successful registration. Rejected attempts never
145
+ # move its deadline, including duplicate ownership
146
+ # while an old WebSocket is still being cleaned up.
147
+ recovery_deadline = (
148
+ asyncio.get_running_loop().time() + self._handshake_grace
149
+ )
150
+ delay = self._reconnect_min
151
+ delay = self._reconnect_min
152
+ except ConnectionClosed as exc:
153
+ code = exc.rcvd.code if exc.rcvd is not None else None
154
+ if code == 4403:
155
+ raise TunnelError("unauthorized") from None
156
+ if code == 4400:
157
+ raise TunnelError("protocol_rejected") from None
158
+ if code == 4409 and not (
159
+ reconnect and asyncio.get_running_loop().time() < recovery_deadline
160
+ ):
161
+ raise TunnelError("duplicate_service") from None
162
+ if not reconnect and not self._stop.is_set():
163
+ raise TunnelError("disconnected") from None
164
+ except TunnelError as exc:
165
+ if not (
166
+ exc.code == "duplicate_service"
167
+ and reconnect
168
+ and asyncio.get_running_loop().time() < recovery_deadline
169
+ ):
170
+ raise
171
+ except InvalidHandshake as exc:
172
+ # InvalidStatusCode is a deprecated dynamic export in newer
173
+ # websockets. Its stable base works across our 12–15 range.
174
+ status = getattr(exc, "status_code", None)
175
+ recovering = (
176
+ status == 403
177
+ and reconnect
178
+ and asyncio.get_running_loop().time() < recovery_deadline
179
+ )
180
+ if status not in {429, 500, 502, 503, 504} and not recovering:
181
+ raise TunnelError("gateway_handshake_rejected") from None
182
+ if not reconnect:
183
+ raise TunnelError("gateway_unavailable") from None
184
+ except ssl.SSLCertVerificationError:
185
+ raise TunnelError("tls_verification_failed") from None
186
+ except (OSError, TimeoutError):
187
+ if not reconnect:
188
+ raise TunnelError("connection_failed") from None
189
+ if self._stop.is_set() or not reconnect:
190
+ break
191
+ logger.info("Tool tunnel disconnected; reconnecting without replaying calls")
192
+ try:
193
+ await asyncio.wait_for(self._stop.wait(), delay * random.uniform(0.8, 1.2))
194
+ except TimeoutError:
195
+ pass
196
+ delay = min(delay * 2, self._reconnect_max)
197
+ finally:
198
+ self._running = False
199
+ self.connected.clear()
200
+
201
+ async def _run_connection(self) -> None:
202
+ tasks: dict[str, asyncio.Task] = {}
203
+ send_lock = asyncio.Lock()
204
+ async with _DirectConnect(
205
+ self._url,
206
+ extra_headers=self._headers,
207
+ max_size=self.limits.max_frame_bytes,
208
+ max_queue=self.limits.max_inflight,
209
+ open_timeout=self.limits.registration_timeout,
210
+ close_timeout=self.limits.send_timeout,
211
+ ping_interval=self.limits.heartbeat_interval,
212
+ ping_timeout=self.limits.idle_timeout,
213
+ **({"ssl": self._ssl_context} if self._ssl_context is not None else {}),
214
+ ) as ws:
215
+ self._ws = ws
216
+
217
+ async def send(frame):
218
+ raw = encode(frame, self.limits)
219
+ async with asyncio.timeout(self.limits.send_timeout):
220
+ async with send_lock:
221
+ await ws.send(raw)
222
+
223
+ async def heartbeat():
224
+ while True:
225
+ await asyncio.sleep(self.limits.heartbeat_interval)
226
+ await send({"type": "heartbeat"})
227
+
228
+ heartbeat_task = None
229
+ try:
230
+ await send(
231
+ {
232
+ "type": "register",
233
+ "version": VERSION,
234
+ **({"agent_id": self.agent_id} if self.agent_id is not None else {}),
235
+ "token": self._token,
236
+ "services": self._descriptors,
237
+ }
238
+ )
239
+ async with asyncio.timeout(self.limits.registration_timeout):
240
+ try:
241
+ ack = decode(await ws.recv(), self.limits)
242
+ except (ValueError, TypeError):
243
+ raise TunnelError("invalid_registration_ack") from None
244
+ if (
245
+ set(ack) == {"type", "version", "error"}
246
+ and ack["type"] == "registration_rejected"
247
+ and ack["version"] == VERSION
248
+ and ack["error"] in ("unauthorized", "duplicate_service")
249
+ ):
250
+ raise TunnelError(ack["error"])
251
+ if (
252
+ set(ack) != {"type", "version", "connector_id"}
253
+ or ack.get("type") != "registered"
254
+ or ack.get("version") != VERSION
255
+ ):
256
+ raise TunnelError("invalid_registration_ack")
257
+ try:
258
+ identifier(ack["connector_id"], "connector id")
259
+ except ValueError:
260
+ raise TunnelError("invalid_registration_ack") from None
261
+ self.connected.set()
262
+ self._registrations += 1
263
+ heartbeat_task = asyncio.create_task(heartbeat())
264
+
265
+ def done(request_id, task):
266
+ tasks.pop(request_id, None)
267
+ if not task.cancelled():
268
+ task.exception() # receive loop observes disconnect; never leak task errors
269
+
270
+ while not self._stop.is_set():
271
+ async with asyncio.timeout(self.limits.idle_timeout):
272
+ try:
273
+ frame = decode(await ws.recv(), self.limits)
274
+ except (ValueError, TypeError):
275
+ raise TunnelError("invalid_request") from None
276
+ if frame == {"type": "heartbeat_ack"}:
277
+ continue
278
+ request_id = frame.get("id")
279
+ try:
280
+ identifier(request_id, "request id")
281
+ except ValueError:
282
+ raise TunnelError("invalid_request") from None
283
+ if frame.get("type") == "http_cancel" and set(frame) == {"type", "id"}:
284
+ if request_id in tasks:
285
+ tasks[request_id].cancel()
286
+ continue
287
+ if (
288
+ set(frame)
289
+ != {"type", "id", "server", "method", "path", "query", "headers", "body"}
290
+ or frame.get("type") != "http_request"
291
+ or request_id in tasks
292
+ ):
293
+ raise TunnelError("invalid_request")
294
+ # One admitted MCP operation may hold a GET event stream,
295
+ # notification POST and tool POST concurrently. The cloud
296
+ # bounds logical operations; this bounds their HTTP tasks.
297
+ if len(tasks) >= 3 * self.limits.max_inflight:
298
+ await send({"type": "http_error", "id": request_id, "error": "busy"})
299
+ continue
300
+ task = asyncio.create_task(self._handle(frame, send))
301
+ tasks[request_id] = task
302
+ task.add_done_callback(lambda t, rid=request_id: done(rid, t))
303
+ finally:
304
+ self.connected.clear()
305
+ self._ws = None
306
+ if heartbeat_task is not None:
307
+ heartbeat_task.cancel()
308
+ active = [*tasks.values(), *([heartbeat_task] if heartbeat_task else [])]
309
+ for task in active:
310
+ task.cancel()
311
+ await asyncio.gather(*active, return_exceptions=True)
312
+
313
+ async def _handle(self, frame: dict, send) -> None:
314
+ error = "local_service_error"
315
+ service = None
316
+ try:
317
+ async with asyncio.timeout(self.limits.request_timeout):
318
+ service = (
319
+ self._services.get(frame["server"])
320
+ if isinstance(frame["server"], str)
321
+ else None
322
+ )
323
+ if service is None:
324
+ raise TunnelError("forbidden")
325
+ request = prepare_request(service, frame)
326
+ # A client per HTTP request keeps cookies and authentication
327
+ # state isolated between local services and cloud sessions.
328
+ async with httpx.AsyncClient(
329
+ timeout=self.limits.request_timeout,
330
+ trust_env=False,
331
+ follow_redirects=False,
332
+ limits=httpx.Limits(max_connections=1, max_keepalive_connections=0),
333
+ ) as client:
334
+ async with client.stream(
335
+ request.method,
336
+ request.url,
337
+ headers=request.headers,
338
+ content=request.content,
339
+ ) as response:
340
+ await send(
341
+ {
342
+ "type": "http_response",
343
+ "id": frame["id"],
344
+ "status": response.status_code,
345
+ "headers": response_headers(response.headers),
346
+ }
347
+ )
348
+ decoder = codecs.getincrementaldecoder("utf-8")()
349
+ received = 0
350
+
351
+ async def emit(text):
352
+ # JSON escaping can cost six bytes per character.
353
+ # Split only an already received network chunk;
354
+ # never ask httpx to buffer an SSE event to a size.
355
+ step = max(1, (self.limits.max_frame_bytes - 256) // 6)
356
+ for offset in range(0, len(text), step):
357
+ await send(
358
+ {
359
+ "type": "http_chunk",
360
+ "id": frame["id"],
361
+ "data": text[offset : offset + step],
362
+ }
363
+ )
364
+
365
+ async for chunk in response.aiter_bytes():
366
+ received += len(chunk)
367
+ if received > self.limits.max_response_bytes:
368
+ raise TunnelError("frame_too_large")
369
+ await emit(decoder.decode(chunk, final=False))
370
+ await emit(decoder.decode(b"", final=True))
371
+ await send({"type": "http_end", "id": frame["id"]})
372
+ return
373
+ except asyncio.CancelledError:
374
+ raise
375
+ except TimeoutError:
376
+ error = "timeout"
377
+ except TunnelError as exc:
378
+ error = exc.code if exc.code in LOCAL_ERROR_CODES else "local_service_error"
379
+ except Exception:
380
+ # HTTP and decoding errors can contain local URLs, headers and
381
+ # payloads. Only a fixed protocol error code may reach the cloud.
382
+ if isinstance(service, LocalMCPService):
383
+ error = "local_mcp_error"
384
+ await send({"type": "http_error", "id": frame["id"], "error": error})