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
ksadk/runtime/factory.py CHANGED
@@ -45,15 +45,21 @@ from ksadk.runtime.launch import RuntimeLaunchContext
45
45
  def _create_harness(context: RuntimeLaunchContext) -> RuntimeAdapter:
46
46
  """Create the managed KsADK Harness adapter from an immutable launch manifest."""
47
47
 
48
+ from ksadk.harness.service_runtime import harness_service_from_env
49
+
50
+ config = dict(context.config)
51
+ prompt = str(config.get("prompt") or config.get("base_instructions") or "").strip()
52
+ model = str(config.get("model") or "").strip()
53
+ service = harness_service_from_env(instructions=prompt, model=model or None)
54
+ if service is not None:
55
+ return service
56
+
48
57
  import re
49
58
 
50
59
  from ksadk.harness.managed_runtime import ManagedHarnessRuntimeAdapter
51
60
  from ksadk.harness.reasoner import ModelGatewayHarnessReasoner
52
61
  from ksadk.harness.spec import HarnessSpec, ModelBinding, PromptSpec
53
62
 
54
- config = dict(context.config)
55
- prompt = str(config.get("prompt") or config.get("base_instructions") or "").strip()
56
- model = str(config.get("model") or "").strip()
57
63
  if not prompt:
58
64
  raise ValueError("harness runtime requires prompt/base_instructions")
59
65
  if not model:
@@ -180,11 +186,17 @@ def _create_framework_runner(context: RuntimeLaunchContext, runtime_type: str) -
180
186
 
181
187
 
182
188
  def _create_adk(context: RuntimeLaunchContext) -> RuntimeAdapter:
183
- return ADKRuntimeAdapter(_create_framework_runner(context, "adk"))
189
+ adapter = ADKRuntimeAdapter(_create_framework_runner(context, "adk"))
190
+ if context.services.tunnel_binding is not None:
191
+ adapter.configure_tunnel(context.services.tunnel_binding)
192
+ return adapter
184
193
 
185
194
 
186
195
  def _create_langgraph(context: RuntimeLaunchContext) -> RuntimeAdapter:
187
- return LangGraphRuntimeAdapter(_create_framework_runner(context, "langgraph"))
196
+ adapter = LangGraphRuntimeAdapter(_create_framework_runner(context, "langgraph"))
197
+ if context.services.tunnel_binding is not None:
198
+ adapter.configure_tunnel(context.services.tunnel_binding)
199
+ return adapter
188
200
 
189
201
 
190
202
  def build_default_runtime_registry(
@@ -41,6 +41,11 @@ class ADKRuntimeAdapter(RunnerRuntimeAdapter):
41
41
  def __init__(self, runner: BaseRunner) -> None:
42
42
  super().__init__(runner, runtime_type="adk")
43
43
 
44
+ def configure_tunnel(self, binding) -> None:
45
+ from ksadk.tunnel.runtime import bind_runner
46
+
47
+ bind_runner(self._runner, binding)
48
+
44
49
  async def restore_run_record(self, handle: RunHandle, record: "RunRecord") -> None:
45
50
  """Rebuild private request context after native attachment has succeeded.
46
51
 
@@ -152,6 +157,11 @@ class LangGraphRuntimeAdapter(NativeLangGraphInteractionMixin, RunnerRuntimeAdap
152
157
  def __init__(self, runner: BaseRunner) -> None:
153
158
  super().__init__(runner, runtime_type="langgraph")
154
159
 
160
+ def configure_tunnel(self, binding) -> None:
161
+ from ksadk.tunnel.runtime import bind_runner
162
+
163
+ bind_runner(self._runner, binding)
164
+
155
165
  async def durable_restore(self, handle: RunHandle) -> RunHandle:
156
166
  # Recovery's adapter factory creates a cold runner, independently of
157
167
  # the deployment capability probe. Bind its saver before checking the
@@ -87,7 +87,24 @@ def fresh_checkpoint_view(config: Any, saved: Any) -> Any:
87
87
  pending = list(saved.pending_writes or [])
88
88
  if any(channel == "__interrupt__" for _, channel, _ in pending):
89
89
  return saved
90
- results = {m.tool_call_id: m for m in messages if isinstance(m, ToolMessage)}
90
+ # A custom graph can append other messages before it records a tool receipt.
91
+ # Match each receipt to the most recent preceding call with that provider ID.
92
+ call_positions = {}
93
+ results_by_call = {}
94
+ result_positions = set()
95
+ changed = False
96
+ for index, message in enumerate(messages):
97
+ if isinstance(message, AIMessage) and message.tool_calls:
98
+ for call in message.tool_calls:
99
+ call_positions[call.get("id")] = index
100
+ elif isinstance(message, ToolMessage) and message.tool_call_id in call_positions:
101
+ owner = call_positions[message.tool_call_id]
102
+ results = results_by_call.setdefault(owner, [])
103
+ results.append(message)
104
+ result_positions.add(index)
105
+ # Strict providers require the receipts immediately after their AI message.
106
+ if index != owner + len(results):
107
+ changed = True
91
108
  pending_results = {}
92
109
  updated_pending = []
93
110
  for task, channel, value in pending:
@@ -107,19 +124,23 @@ def fresh_checkpoint_view(config: Any, saved: Any) -> Any:
107
124
  updated_pending.append((task, channel, value))
108
125
 
109
126
  repaired = []
110
- changed = False
111
- for message in messages:
127
+ for index, message in enumerate(messages):
128
+ if index in result_positions:
129
+ continue # Emitted with the original call, in receipt order.
112
130
  repaired.append(message)
113
131
  if not isinstance(message, AIMessage):
114
132
  continue
133
+ results = results_by_call.get(index, ())
134
+ repaired.extend(results)
135
+ answered = {result.tool_call_id for result in results}
115
136
  for call in message.tool_calls:
116
137
  call_id = call.get("id")
117
- if not call_id or call_id in results:
138
+ if not call_id or call_id in answered:
118
139
  continue
119
- result = pending_results.get(call_id)
140
+ result = pending_results.get(call_id) if index == call_positions[call_id] else None
120
141
  if result is None:
121
142
  identity = hashlib.sha256(
122
- f"{saved.checkpoint['id']}:{call_id}".encode()
143
+ f"{saved.checkpoint['id']}:{index}:{call_id}".encode()
123
144
  ).hexdigest()
124
145
  result = ToolMessage(
125
146
  id=f"ksadk-interrupted-{identity}", tool_call_id=call_id,
@@ -135,7 +156,7 @@ def fresh_checkpoint_view(config: Any, saved: Any) -> Any:
135
156
  }},
136
157
  )
137
158
  repaired.append(result)
138
- results[call_id] = result
159
+ answered.add(call_id)
139
160
  changed = True
140
161
  if not changed:
141
162
  return saved
ksadk/runtime/launch.py CHANGED
@@ -26,6 +26,8 @@ class RuntimeServices:
26
26
  runner_factory: Callable[[Any, str], Any] | None = None
27
27
  # Process-owned dependency; never serialized into user/runtime config.
28
28
  managed_a2a_bootstrap: Any | None = None
29
+ # App-owned MCP tunnel registry and immutable deployment identity.
30
+ tunnel_binding: Any | None = None
29
31
 
30
32
 
31
33
  @dataclass(frozen=True)
ksadk/server/factory.py CHANGED
@@ -239,6 +239,7 @@ class RuntimeAppConfig:
239
239
  teams_host_factory: Any | None = None,
240
240
  a2ui_catalog_registry: Any | None = None,
241
241
  local_mcp_oauth: bool = False,
242
+ auto_tracing: bool = True,
242
243
  ) -> None:
243
244
  self.runtime_type = runtime_type
244
245
  self.route_groups: set[str] = (
@@ -260,6 +261,8 @@ class RuntimeAppConfig:
260
261
  self.a2ui_catalog_registry = a2ui_catalog_registry
261
262
  # Composition-only switch. Never populated from Agent YAML or env.
262
263
  self.local_mcp_oauth = local_mcp_oauth
264
+ # Composition-only opt-out for callers such as `ksadk run --no-trace`.
265
+ self.auto_tracing = auto_tracing
263
266
 
264
267
 
265
268
  # ---------------------------------------------------------------------------
@@ -380,6 +383,35 @@ def _is_agent_execution_path(path: str, method: str) -> bool:
380
383
  return False
381
384
 
382
385
 
386
+ def _setup_runtime_tracing() -> None:
387
+ """Initialize configured OTLP tracing before composing a Runtime app.
388
+
389
+ Unconfigured processes and application-owned providers stay untouched.
390
+ The existing setup function serializes initialization and owns exporters.
391
+ """
392
+ if os.getenv("OTEL_SDK_DISABLED", "").strip().lower() == "true":
393
+ return
394
+ if not any(os.getenv(name, "").strip() for name in (
395
+ "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
396
+ "CLOUD_MONITOR_OTLP_ENDPOINT", "CLOUD_MONITOR_OTLP_TRACES_ENDPOINT",
397
+ "CLOUD_MONITOR_OTLP_HEADERS", "CLOUD_MONITOR_OTLP_TRACES_HEADERS",
398
+ "CLOUD_MONITOR_APP_KEY",
399
+ )):
400
+ return
401
+ try:
402
+ from opentelemetry import trace
403
+
404
+ # Includes explicit SDK setup, routed tracing and OTel auto-instrumentation.
405
+ # Do not replace a user's provider or attach a second static exporter.
406
+ if not isinstance(trace.get_tracer_provider(), trace.ProxyTracerProvider):
407
+ return
408
+ from ksadk.tracing import setup_tracing
409
+
410
+ setup_tracing()
411
+ except Exception:
412
+ logger.warning("Runtime tracing initialization failed; continuing without automatic tracing", exc_info=True)
413
+
414
+
383
415
  def create_runtime_app(
384
416
  config: RuntimeAppConfig,
385
417
  configure: Optional[ConfigureApp] = None,
@@ -399,6 +431,13 @@ def create_runtime_app(
399
431
  from fastapi.middleware.cors import CORSMiddleware
400
432
  from fastapi.responses import Response
401
433
 
434
+ from ksadk.tunnel.runtime import DeferredTunnel, configure_app_tunnel
435
+
436
+ if config.auto_tracing:
437
+ _setup_runtime_tracing()
438
+
439
+ config, tunnel_binding = configure_app_tunnel(config)
440
+
402
441
  if config.a2ui_catalog_registry is not None:
403
442
  from ksadk.a2ui.registry import A2uiCatalogRegistry
404
443
 
@@ -430,6 +469,9 @@ def create_runtime_app(
430
469
  )
431
470
  from ksadk.runtime.factory import kernel_start_request_defaults
432
471
 
472
+ if tunnel_binding is not None:
473
+ await tunnel_binding.start()
474
+
433
475
  adapter_provider = _kernel_adapter_provider(config)
434
476
  from ksadk.kernel.session_storage import postgres_kernel_enabled
435
477
  if teams_host is not None:
@@ -455,6 +497,8 @@ def create_runtime_app(
455
497
  **({"before_start": teams_host.before_start} if teams_host is not None else {}),
456
498
  )
457
499
  except BaseException:
500
+ if tunnel_binding is not None:
501
+ await tunnel_binding.close()
458
502
  if teams_host is not None:
459
503
  await teams_host.close()
460
504
  _kernel_ingress.set_teams_ingress_gate(None)
@@ -490,6 +534,8 @@ def create_runtime_app(
490
534
  await state.a2a_bootstrap.start()
491
535
  yield
492
536
  finally:
537
+ if tunnel_binding is not None:
538
+ await tunnel_binding.close()
493
539
  if state.a2a_bootstrap is not None:
494
540
  await state.a2a_bootstrap.stop()
495
541
  if state.local_interactions is not None:
@@ -515,6 +561,15 @@ def create_runtime_app(
515
561
  )
516
562
  state.app = app
517
563
  app.state.runtime = state
564
+ if tunnel_binding is not None:
565
+ from ksadk.tunnel.server import mount_tunnel
566
+
567
+ if isinstance(tunnel_binding, DeferredTunnel):
568
+ from ksadk.tunnel.server import install_connector_fallback
569
+
570
+ install_connector_fallback(app, tunnel_binding)
571
+ else:
572
+ mount_tunnel(app, policies=[tunnel_binding.policy], registry=tunnel_binding.registry)
518
573
  if teams_host is not None:
519
574
  from ksadk.kernel.teams_host_http import create_teams_host_router
520
575
 
@@ -42,6 +42,7 @@ from ..invocation_identity import (
42
42
  trusted_invocation_identity_headers,
43
43
  )
44
44
  from . import dependencies as deps
45
+ from .harness_service_view import register_harness_service_view
45
46
  from .routers import health_meta_router
46
47
 
47
48
  logger = logging.getLogger(__name__)
@@ -146,6 +147,7 @@ def _register_integrated_routers(app: FastAPI, state: RuntimeAppState) -> None:
146
147
  goal-01:由模块级 ``app.include_router(...)`` 改为在 factory 的 configure
147
148
  回调里调用,普通 app 与 HarnessApp 各自装配,互不共享。
148
149
  """
150
+ register_harness_service_view(app)
149
151
  app.include_router(
150
152
  create_workspace_files_router(
151
153
  root_getter=_workspace_root_dir,
@@ -0,0 +1,38 @@
1
+ """Same-origin presentation proxy; the browser never receives service credentials."""
2
+
3
+ import httpx
4
+ from fastapi import FastAPI, HTTPException, Request, Response
5
+
6
+ from ksadk.harness.service_presentation import ENGINE_VIEW_PATH, VIEW_HASH
7
+ from ksadk.harness.service_runtime import harness_service_from_env
8
+
9
+ _VIEW_HEADERS = {
10
+ "cache-control": "private, max-age=31536000, immutable",
11
+ "content-security-policy": (
12
+ "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
13
+ "img-src data:; sandbox allow-scripts"
14
+ ),
15
+ "x-content-type-options": "nosniff",
16
+ "referrer-policy": "no-referrer",
17
+ }
18
+
19
+
20
+ def register_harness_service_view(app: FastAPI) -> None:
21
+ @app.api_route(
22
+ ENGINE_VIEW_PATH + "/{sha256}", methods=["GET", "HEAD"], include_in_schema=False
23
+ )
24
+ async def get_view(request: Request, sha256: str) -> Response:
25
+ if not VIEW_HASH.fullmatch(sha256):
26
+ raise HTTPException(status_code=404)
27
+ try:
28
+ service = harness_service_from_env()
29
+ html = await service.view_html(sha256) if service is not None else None
30
+ except (httpx.HTTPError, ValueError, RuntimeError) as error:
31
+ raise HTTPException(status_code=502, detail="Harness view unavailable") from error
32
+ if html is None:
33
+ raise HTTPException(status_code=404)
34
+ return Response(
35
+ content=b"" if request.method == "HEAD" else html,
36
+ media_type="text/html",
37
+ headers=_VIEW_HEADERS,
38
+ )
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import asyncio
6
6
  import logging
7
+ import os
7
8
  from collections.abc import Mapping
8
9
  from typing import Any
9
10
 
@@ -118,6 +119,9 @@ async def build_ui_bootstrap(request, invocation_identity, *, state, executor, l
118
119
  "Cancel": cancel_run_supported,
119
120
  },
120
121
  }
122
+ from ksadk.kernel.bootstrap import get_agent_kernel_runtime
123
+
124
+ kernel_runtime = get_agent_kernel_runtime()
121
125
  hosted_chat_transports = []
122
126
  if state.agui_agent is not None and state.agui_config is not None:
123
127
  from ksadk.agui.config import AGUI_PROTOCOL_VERSION
@@ -134,6 +138,10 @@ async def build_ui_bootstrap(request, invocation_identity, *, state, executor, l
134
138
  "Cancel": True,
135
139
  **({"SessionEventReplay": True} if (
136
140
  _kernel_ingress.kernel_route_active()
141
+ # Hosted AG-UI reads the shared Kernel log after
142
+ # Server admission; local self-admission stays off.
143
+ or (kernel_runtime is not None
144
+ and _kernel_ingress.authority_mode() == "hosted")
137
145
  or (state.local_interactions is not None
138
146
  and state.local_interactions.prepared)
139
147
  ) else {}),
@@ -147,6 +155,14 @@ async def build_ui_bootstrap(request, invocation_identity, *, state, executor, l
147
155
  and bool(getattr(state.agui_config, "preferred", False))
148
156
  else "responses"
149
157
  )
158
+ # Preference only: retain every endpoint for existing runs and interrupts.
159
+ requested_transport = os.getenv("KSADK_CHAT_PREFERRED_TRANSPORT", "").strip().lower()
160
+ if requested_transport == "responses":
161
+ preferred_transport = "responses"
162
+ elif requested_transport == "ag-ui" and any(
163
+ item["Protocol"] == "ag-ui" for item in hosted_chat_transports
164
+ ):
165
+ preferred_transport = "ag-ui"
150
166
  # Producer declaration is separate from transport availability. Consumers
151
167
  # intersect this surface with their renderer catalogue before selecting a
152
168
  # presentation profile; an older runtime has no such declaration.
@@ -169,9 +185,7 @@ async def build_ui_bootstrap(request, invocation_identity, *, state, executor, l
169
185
  ),
170
186
  ),
171
187
  ).model_dump(mode="json", by_alias=True)
172
- from ksadk.kernel.bootstrap import get_agent_kernel_runtime
173
188
  from ksadk.mcp_runtime.oauth.contract import CAPABILITY as MCP_AUTH_CAPABILITY
174
- kernel_runtime = get_agent_kernel_runtime()
175
189
  oauth_ready = bool(kernel_runtime and kernel_runtime.worker._mcp_authorization)
176
190
  return _action_response(
177
191
  "GetAgentUiBootstrap",