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
@@ -28,7 +28,11 @@ from typing import Any, List, Set
28
28
 
29
29
  from pydantic import ConfigDict, Field, field_validator
30
30
 
31
- from ksadk.common.cloud_headers import build_cloud_headers, resolve_traffic_source
31
+ from ksadk.common.cloud_headers import (
32
+ build_component_headers,
33
+ resolve_component_env,
34
+ resolve_traffic_source,
35
+ )
32
36
  from ksadk.memory.adk.backends.base_ltm_backend import (
33
37
  CAP_ADD,
34
38
  CAP_DELETE,
@@ -46,6 +50,8 @@ from ksadk.memory.models import (
46
50
  map_session_state,
47
51
  )
48
52
 
53
+ from ksadk.memory.scope_ids import aicp_user_id
54
+
49
55
  logger = logging.getLogger(__name__)
50
56
 
51
57
  DEFAULT_SCENE_ID = "_sys_general"
@@ -93,6 +99,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
93
99
  secret_key: str = ""
94
100
  session_token: str = ""
95
101
  traffic_source: str = Field(default_factory=resolve_traffic_source)
102
+ component_env: str = Field(default_factory=resolve_component_env)
96
103
  region: str = "cn-beijing-6"
97
104
  endpoint: str = "aicp.api.ksyun.com"
98
105
  scheme: str = "https"
@@ -190,8 +197,10 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
190
197
  class ObservedAicpClient(aicp_module.AicpClient):
191
198
  def call(self, action, params, options=None):
192
199
  options = dict(options or {})
193
- options["CustomHeaders"] = build_cloud_headers(
194
- options.get("CustomHeaders"), traffic_source=owner.traffic_source
200
+ options["CustomHeaders"] = build_component_headers(
201
+ options.get("CustomHeaders"),
202
+ traffic_source=owner.traffic_source,
203
+ component_env=owner.component_env,
195
204
  )
196
205
  return super().call(action, params, options)
197
206
 
@@ -285,7 +294,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
285
294
  session_id = metadata.get("session_id") or kwargs.get("session_id")
286
295
  params = {
287
296
  "MemoryCollectionId": memory_collection_id,
288
- "AgentUserId": user_id,
297
+ "AgentUserId": aicp_user_id(user_id),
289
298
  "SceneId": self._effective_scene_id(),
290
299
  "DataType": "conversation",
291
300
  "Data": {"Conversation": conversation},
@@ -311,7 +320,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
311
320
  return False
312
321
  self.last_session_status = {
313
322
  "SessionId": session_id,
314
- "AgentUserId": user_id,
323
+ "AgentUserId": aicp_user_id(user_id),
315
324
  "MemoryCollectionId": memory_collection_id,
316
325
  }
317
326
 
@@ -344,7 +353,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
344
353
  self.last_error = ""
345
354
  params = {
346
355
  "MemoryCollectionId": memory_collection_id,
347
- "AgentUserId": user_id,
356
+ "AgentUserId": aicp_user_id(user_id),
348
357
  "Query": query,
349
358
  "Limit": top_k,
350
359
  "SceneId": self._effective_scene_id(),
@@ -404,7 +413,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
404
413
  memory_collection_id = self._effective_memory_collection_id()
405
414
  params = {
406
415
  "MemoryCollectionId": memory_collection_id,
407
- "AgentUserId": user_id,
416
+ "AgentUserId": aicp_user_id(user_id),
408
417
  "Query": query,
409
418
  "Limit": top_k,
410
419
  "SceneId": self._effective_scene_id(),
@@ -434,7 +443,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
434
443
  client = self._get_client()
435
444
  params: dict[str, Any] = {
436
445
  "MemoryCollectionId": self._effective_memory_collection_id(),
437
- "AgentUserId": user_id,
446
+ "AgentUserId": aicp_user_id(user_id),
438
447
  "Page": page,
439
448
  "PageSize": page_size,
440
449
  }
@@ -463,7 +472,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
463
472
  "MemoryCollectionId": self._effective_memory_collection_id(),
464
473
  "MemoryId": memory_id,
465
474
  "Content": content,
466
- "AgentUserId": user_id,
475
+ "AgentUserId": aicp_user_id(user_id),
467
476
  }
468
477
  try:
469
478
  response = client.call("UpdateMemory", params, options={"IsPostJson": True})
@@ -549,7 +558,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
549
558
  params = {
550
559
  "MemoryCollectionId": self._effective_memory_collection_id(),
551
560
  "MemoryId": memory_id,
552
- "AgentUserId": user_id,
561
+ "AgentUserId": aicp_user_id(user_id),
553
562
  }
554
563
  try:
555
564
  response = client.call("DeleteMemory", params, options={"IsPostJson": True})
@@ -821,7 +830,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
821
830
  collection = self._effective_memory_collection_id()
822
831
  for page in range(1, max_pages + 1):
823
832
  response = client.call("ListSessions", {
824
- "MemoryCollectionId": collection, "AgentUserId": user_id,
833
+ "MemoryCollectionId": collection, "AgentUserId": aicp_user_id(user_id),
825
834
  "Page": page, "PageSize": page_size,
826
835
  }, options={"IsPostJson": True})
827
836
  data = self._parse_json_response(response)
@@ -870,7 +879,7 @@ class SdkLTMBackend(BaseLongTermMemoryBackend):
870
879
  for item in items:
871
880
  if item["SessionId"] == session_id:
872
881
  if (
873
- item.get("AgentUserId", user_id) != user_id
882
+ item.get("AgentUserId", aicp_user_id(user_id)) != aicp_user_id(user_id)
874
883
  or item.get("MemoryCollectionId", collection) != collection
875
884
  ):
876
885
  return None, "MEMORY_STATUS_SCOPE_MISMATCH"
@@ -0,0 +1,49 @@
1
+ """AICP wire identity encoding, separate from persisted MemoryProvider scopes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+
8
+ SAFE_SCOPE_ID = re.compile(r"[A-Za-z0-9_-]{1,64}\Z")
9
+ SCOPE_ID_SEPARATOR = "_"
10
+ SCOPE_ID_MAX_READABLE = 60
11
+ SCOPE_ID_DIGEST_CHARS = 32
12
+
13
+
14
+ def aicp_agent_user_scope_id(*, agent_id: str, user_id: str) -> str:
15
+ """Encode Agent × User using the upstream readable/digest wire format.
16
+
17
+ This encoding belongs to the AICP boundary. Local records keep the stable
18
+ logical namespace returned by ``coordinator.agent_user_scope_id``.
19
+ """
20
+ agent = str(agent_id or "").strip()
21
+ user = str(user_id or "").strip()
22
+ if not agent and SAFE_SCOPE_ID.fullmatch(user):
23
+ return user
24
+ if agent and SCOPE_ID_SEPARATOR not in agent and SCOPE_ID_SEPARATOR not in user:
25
+ candidate = f"{agent}{SCOPE_ID_SEPARATOR}{user}"
26
+ if len(candidate) <= SCOPE_ID_MAX_READABLE and SAFE_SCOPE_ID.fullmatch(candidate):
27
+ return candidate
28
+ encoded = f"agent-user-scope/v1|{agent}|{user}".encode()
29
+ return hashlib.sha256(encoded).hexdigest()[:SCOPE_ID_DIGEST_CHARS]
30
+
31
+
32
+ def aicp_user_id(logical_id: str) -> str:
33
+ """Preserve existing valid cloud IDs and encode legacy logical namespaces.
34
+
35
+ In particular, do not rehash resource-runtime ``mp1-`` partitions or safe
36
+ caller-provided IDs: they can already own records in the cloud service.
37
+ """
38
+ value = str(logical_id or "")
39
+ if not value.strip():
40
+ raise ValueError("MEMORY_USER_ID_REQUIRED")
41
+ if SAFE_SCOPE_ID.fullmatch(value):
42
+ return value
43
+ if value.startswith("agent:"):
44
+ agent, separator, user = value[len("agent:"):].partition(":user:")
45
+ if separator:
46
+ if not agent.strip() or not user.strip():
47
+ raise ValueError("MEMORY_USER_ID_REQUIRED")
48
+ return aicp_agent_user_scope_id(agent_id=agent, user_id=user)
49
+ return aicp_agent_user_scope_id(agent_id="", user_id=value)
@@ -19,8 +19,10 @@ from pathlib import Path
19
19
  from typing import Any, Literal, Protocol, cast, runtime_checkable
20
20
 
21
21
  from ksadk.harness.config import HarnessConfig, McpToolSpec, SandboxPolicy
22
+ from ksadk.harness.native.hook_executor import HookAuthorizer
22
23
  from ksadk.harness.reasoner import HarnessReasoner, ModelGatewayHarnessReasoner
23
24
  from ksadk.harness.runtime import HarnessRuntimeAdapter
25
+ from ksadk.harness.service_runtime import HarnessServiceRuntimeAdapter, harness_service_from_env
24
26
  from ksadk.plugins.bundle import ResolvedPluginBundle
25
27
  from ksadk.plugins.contracts import CompositionProfile, PluginManifest
26
28
  from ksadk.plugins.host import PluginExecutionContext, PluginHostError
@@ -378,6 +380,8 @@ class KsADKHarnessProviderRuntime:
378
380
  user_workspace_root: Path | None = None,
379
381
  engine_selector: HarnessEngineSelector | None = None,
380
382
  native_adapter_builder: HarnessNativeAdapterBuilder | None = None,
383
+ service_hook_authorizer: HookAuthorizer | None = None,
384
+ service_hook_authorization_version: str | None = None,
381
385
  ) -> None:
382
386
  self._plugin_id = plugin_id
383
387
  self._session_service = session_service
@@ -388,6 +392,8 @@ class KsADKHarnessProviderRuntime:
388
392
  self._user_workspace_root = user_workspace_root
389
393
  self._engine_selector = engine_selector
390
394
  self._native_adapter_builder = native_adapter_builder
395
+ self._service_hook_authorizer = service_hook_authorizer
396
+ self._service_hook_authorization_version = service_hook_authorization_version
391
397
  self._ready = False
392
398
  self._disposed = False
393
399
  self._last_inventory: HarnessProviderInventory | None = None
@@ -543,8 +549,11 @@ class KsADKHarnessProviderRuntime:
543
549
  for binding in capabilities.all("memory.provider/v1")
544
550
  ),
545
551
  )
546
- engine_kind: Literal["legacy", "native"] = "legacy"
547
- if self._engine_selector is not None:
552
+ service_adapter = harness_service_from_env(instructions=prompt)
553
+ engine_kind: Literal["legacy", "native", "service"] = "legacy"
554
+ if service_adapter is not None:
555
+ engine_kind = "service"
556
+ elif self._engine_selector is not None:
548
557
  selected = self._engine_selector(engine_context)
549
558
  if inspect.isawaitable(selected):
550
559
  selected = await selected
@@ -554,17 +563,17 @@ class KsADKHarnessProviderRuntime:
554
563
  "Harness engine selection must be legacy or native",
555
564
  )
556
565
  engine_kind = selected
557
- if hook_bindings and engine_kind != "native":
566
+ if hook_bindings and engine_kind == "legacy":
558
567
  raise PluginHostError(
559
568
  "harness_hooks_native_required",
560
569
  "selected harness.hook/v1 capabilities require Native execution",
561
570
  )
562
- if any(binding.contributor for binding in context_bindings) and engine_kind != "native":
571
+ if any(binding.contributor for binding in context_bindings) and engine_kind == "legacy":
563
572
  raise PluginHostError(
564
573
  "harness_context_native_required",
565
574
  "typed Context Contributors require the selected Native execution path",
566
575
  )
567
- if engine_kind == "native":
576
+ if engine_kind in {"native", "service"}:
568
577
  inventory = replace(inventory, history_owner="native_run_ledger")
569
578
  # Only clients consuming the ephemeral callbacks may use the
570
579
  # renewable probe. Legacy/static clients retain token expiry.
@@ -573,6 +582,18 @@ class KsADKHarnessProviderRuntime:
573
582
  mcp_available=projection.runtime_available,
574
583
  mcp_runtime_credentials=projection.runtime_credentials,
575
584
  )
585
+ if service_adapter is not None:
586
+ from ksadk.plugins.providers.harness_service import (
587
+ admit_service_memory,
588
+ bind_service_resources,
589
+ )
590
+
591
+ admit_service_memory(engine_context, capabilities)
592
+ bind_service_resources(
593
+ service_adapter, engine_context, mcp_cleanup,
594
+ hook_authorizer=self._service_hook_authorizer,
595
+ hook_authorization_version=self._service_hook_authorization_version,
596
+ )
576
597
  self._last_inventory = inventory
577
598
  return KsADKHarnessActivation(
578
599
  bundle=bundle,
@@ -592,6 +613,7 @@ class KsADKHarnessProviderRuntime:
592
613
  engine_context=engine_context,
593
614
  engine_kind=engine_kind,
594
615
  native_adapter_builder=self._native_adapter_builder,
616
+ service_adapter=service_adapter,
595
617
  )
596
618
 
597
619
 
@@ -648,6 +670,10 @@ class KsADKHarnessProviderFactory:
648
670
  user_workspace_root=(Path(user_workspace_root) if user_workspace_root else None),
649
671
  engine_selector=engine_selector,
650
672
  native_adapter_builder=native_adapter_builder,
673
+ service_hook_authorizer=services.get("harness_service_hook_authorizer"),
674
+ service_hook_authorization_version=services.get(
675
+ "harness_service_hook_authorization_version"
676
+ ),
651
677
  )
652
678
  return self.runtime
653
679
 
@@ -671,8 +697,9 @@ class KsADKHarnessActivation:
671
697
  execution_policy_resolver: Any | None = None,
672
698
  user_workspace_root: Path | None = None,
673
699
  engine_context: HarnessEngineActivationContext | None = None,
674
- engine_kind: Literal["legacy", "native"] = "legacy",
700
+ engine_kind: Literal["legacy", "native", "service"] = "legacy",
675
701
  native_adapter_builder: HarnessNativeAdapterBuilder | None = None,
702
+ service_adapter: HarnessServiceRuntimeAdapter | None = None,
676
703
  ) -> None:
677
704
  self._bundle = bundle
678
705
  self._config = config
@@ -697,7 +724,7 @@ class KsADKHarnessActivation:
697
724
  self._ready = False
698
725
  self._disposed = False
699
726
  self._executors: list[RuntimeExecutor] = []
700
- self._kernel_adapter: RuntimeAdapter | None = None
727
+ self._kernel_adapter: RuntimeAdapter | None = service_adapter
701
728
  self._warmup_task: asyncio.Task[Any] | None = None
702
729
  self._warmup_error: BaseException | None = None
703
730
 
@@ -735,27 +762,37 @@ class KsADKHarnessActivation:
735
762
  "Native Harness activation requires the Scheduler runtime adapter path",
736
763
  )
737
764
  turn = HarnessTurnRequest.parse(request)
738
- context_sections = [
739
- text.strip()
740
- for source in self._context_sources
741
- if (text := await source.harness_context(self._bundle, turn)).strip()
742
- ]
743
- config = replace(
744
- self._config,
745
- prompt=_append_prompt_sections(
746
- self._config.prompt,
747
- [
748
- *[f"Skill {item.name}:\n{item.instructions}" for item in self._skills],
749
- *context_sections,
750
- ],
751
- ),
752
- )
753
- executor, launch_context = _build_direct_backend(
754
- config,
755
- agent_name=self._agent_name,
756
- workspace_root=self._workspace_root,
757
- reasoner=self._reasoner,
758
- )
765
+ config = self._config
766
+ if self._engine_kind == "service":
767
+ adapter = await self.runtime_adapter()
768
+ registry = RuntimeRegistry()
769
+ registry.register("harness", lambda _context: adapter)
770
+ executor = RuntimeExecutor(registry)
771
+ launch_context = RuntimeLaunchContext(
772
+ runtime_type="harness", project_dir=self._workspace_root,
773
+ )
774
+ else:
775
+ context_sections = [
776
+ text.strip()
777
+ for source in self._context_sources
778
+ if (text := await source.harness_context(self._bundle, turn)).strip()
779
+ ]
780
+ config = replace(
781
+ self._config,
782
+ prompt=_append_prompt_sections(
783
+ self._config.prompt,
784
+ [
785
+ *[f"Skill {item.name}:\n{item.instructions}" for item in self._skills],
786
+ *context_sections,
787
+ ],
788
+ ),
789
+ )
790
+ executor, launch_context = _build_direct_backend(
791
+ config,
792
+ agent_name=self._agent_name,
793
+ workspace_root=self._workspace_root,
794
+ reasoner=self._reasoner,
795
+ )
759
796
  self._executors.append(executor)
760
797
  preparation = await executor.prepare_start(launch_context)
761
798
  session_id, result = await invoke_runtime_conversation_once(
@@ -0,0 +1,198 @@
1
+ """Expose PluginHost-owned MCP and Skills to the independent engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ksadk._mcp_compat import tool_input_schema
6
+
7
+ import hashlib
8
+ import json
9
+ import re
10
+ from contextlib import AsyncExitStack
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from ksadk.harness.native.hook_executor import HookAuthorizer
14
+ from ksadk.harness.service_runtime import HarnessServiceRuntimeAdapter, ServiceHostTool
15
+ from ksadk.plugins.host import PluginExecutionContext, PluginHostError
16
+ from ksadk.plugins.providers.harness_contributions import McpToolSpecTransport, ProviderSkillSource
17
+ from ksadk.plugins.providers.harness_service_context import service_context_sources
18
+ from ksadk.plugins.providers.harness_service_hooks import service_hooks
19
+ from ksadk.plugins.providers.harness_service_memory import (
20
+ service_local_memory,
21
+ service_memory_verifier,
22
+ )
23
+ from ksadk.plugins.providers.platform_resources import (
24
+ PLATFORM_RESOURCE_MCP_NAME,
25
+ PLATFORM_RESOURCE_MCP_PLUGIN_ID,
26
+ PLATFORM_RESOURCE_MCP_PLUGIN_VERSION,
27
+ )
28
+ from ksadk.runtime import StartRequest
29
+ from ksadk.studio.contracts import ExecutionSpec, MemorySpec
30
+
31
+ if TYPE_CHECKING:
32
+ from ksadk.plugins.providers.harness import HarnessEngineActivationContext
33
+
34
+
35
+ def admit_service_memory(
36
+ context: HarnessEngineActivationContext, capabilities: PluginExecutionContext,
37
+ ) -> None:
38
+ """Platform memory uses its locked connector and existing worker write gate."""
39
+ policy = MemorySpec.model_validate(context.bundle.resolved_agent_spec.get("memory") or {})
40
+ if not policy.enabled or not policy.scopes or policy.provider_ref == "local-default":
41
+ return
42
+ connectors = capabilities.all("mcp.connector/v1", slot="mcp.platform-resources")
43
+ if (
44
+ policy.provider_ref.startswith("binding://")
45
+ and len(context.memory_sources) == 1 and len(connectors) == 1
46
+ ):
47
+ memory = context.memory_sources[0]
48
+ connector = connectors[0]
49
+ if (
50
+ memory.slot == "memory.primary"
51
+ and memory.plugin_id == connector.plugin_id == PLATFORM_RESOURCE_MCP_PLUGIN_ID
52
+ and memory.plugin_version == connector.plugin_version
53
+ and memory.plugin_version == PLATFORM_RESOURCE_MCP_PLUGIN_VERSION
54
+ and memory.runtime is connector.runtime
55
+ and any(spec.name == PLATFORM_RESOURCE_MCP_NAME for spec in context.config.mcp_tools)
56
+ ):
57
+ return
58
+ raise PluginHostError(
59
+ "harness_service_memory_unsupported",
60
+ "Independent Harness requires the locked platform memory connector for this activation",
61
+ )
62
+
63
+
64
+ def bind_service_resources(
65
+ adapter: HarnessServiceRuntimeAdapter,
66
+ context: HarnessEngineActivationContext,
67
+ cleanup: AsyncExitStack,
68
+ *,
69
+ hook_authorizer: HookAuthorizer | None = None,
70
+ hook_authorization_version: str | None = None,
71
+ ) -> None:
72
+ credentials = {item.name: item for item in context.mcp_runtime_credentials}
73
+ transports = []
74
+ for spec in context.config.mcp_tools:
75
+ transport = McpToolSpecTransport(spec, credential=credentials.get(spec.name))
76
+ cleanup.push_async_callback(transport.close)
77
+ transports.append((spec.name, transport))
78
+ skills = ProviderSkillSource(context.skills)
79
+ memory = service_local_memory(context)
80
+
81
+ async def check_activation() -> None:
82
+ if context.activation_available is not None and not context.activation_available():
83
+ raise RuntimeError("Harness activation is no longer available")
84
+
85
+ async def check_mcp() -> None:
86
+ await check_activation()
87
+ if context.mcp_available is not None and not await context.mcp_available():
88
+ raise RuntimeError("Harness MCP binding is no longer available")
89
+
90
+ async def list_skills(_: dict[str, Any]) -> Any:
91
+ await check_activation()
92
+ manifests = []
93
+ for ref in skills.refs:
94
+ manifest = skills.manifest(ref)
95
+ manifests.append({"ref": ref, "name": manifest.name, "summary": manifest.summary})
96
+ return manifests
97
+
98
+ async def read_skill(arguments: dict[str, Any]) -> Any:
99
+ await check_activation()
100
+ ref = arguments["ref"]
101
+ path = arguments.get("path")
102
+ if not isinstance(ref, str) or (path is not None and not isinstance(path, str)):
103
+ raise ValueError("invalid Skill resource request")
104
+ if path is None:
105
+ return skills.full_text(ref)
106
+ return skills.resource(ref, path).decode("utf-8")
107
+
108
+ async def load_tools() -> tuple[ServiceHostTool, ...]:
109
+ await check_activation()
110
+ result = memory.tools() if memory is not None else []
111
+ if skills.refs:
112
+ result.extend((
113
+ ServiceHostTool(
114
+ "ksadk_skill_list", "List Skills bound to this Agent.",
115
+ {"type": "object", "properties": {}, "additionalProperties": False},
116
+ list_skills, read_only=True,
117
+ ),
118
+ ServiceHostTool(
119
+ "ksadk_skill_read", "Read a bound Skill or one of its UTF-8 text resources.",
120
+ {"type": "object", "properties": {
121
+ "ref": {"type": "string"}, "path": {"type": "string"},
122
+ }, "required": ["ref"], "additionalProperties": False},
123
+ read_skill, read_only=True,
124
+ ),
125
+ ))
126
+ for server, transport in transports:
127
+ await check_mcp()
128
+ for definition in await transport.list_tools():
129
+ original_name = definition["name"]
130
+ canonical = json.dumps([server, definition], sort_keys=True, allow_nan=False)
131
+ digest = hashlib.sha256(canonical.encode()).hexdigest()[:20]
132
+ label = re.sub(r"[^A-Za-z0-9_]", "_", original_name)[:30]
133
+
134
+ async def call(arguments, *, bound=transport, name=original_name):
135
+ await check_mcp()
136
+ return await bound.call_tool(name, arguments)
137
+
138
+ result.append(ServiceHostTool(
139
+ f"ksadk_mcp_{label}_{digest}", definition["description"],
140
+ tool_input_schema(definition), call, deferred=True, source_name=original_name,
141
+ ))
142
+ return tuple(result)
143
+
144
+ claims = dict(context.activation_claims)
145
+ scope = {"agent_id": context.agent_name}
146
+ scope.update({key: claims[key] for key in ("user_id", "session_id") if key in claims})
147
+ if claims.get("agent_id", context.agent_name) != context.agent_name or (
148
+ "session_id" in scope and scope["session_id"] != context.activation_key
149
+ ):
150
+ raise PluginHostError(
151
+ "harness_service_activation_unbound", "Invalid Harness activation scope",
152
+ )
153
+ identity = json.dumps([
154
+ context.agent_name, context.activation_key, context.profile_digest,
155
+ context.plugin_lock_digest, context.bundle.bundle_digest, claims,
156
+ ], sort_keys=True)
157
+
158
+ async def turn_context(request: StartRequest, rows: list[dict[str, Any]]) -> list[str]:
159
+ from ksadk.plugins.providers.harness import HarnessTurnRequest
160
+
161
+ await check_activation()
162
+ turn = HarnessTurnRequest(
163
+ user_id=request.user_id, session_id=request.session_id, messages=tuple(rows),
164
+ model=request.model, request_metadata=request.metadata,
165
+ invocation_id=request.metadata.get("invocation_id") or request.metadata.get("run_id"),
166
+ )
167
+ return [
168
+ text.strip()
169
+ for binding in context.context_sources
170
+ if not binding.contributor
171
+ and (text := await binding.runtime.harness_context(context.bundle, turn)).strip()
172
+ ]
173
+
174
+ hooks, stop_limit = service_hooks(
175
+ context, cleanup, authorize=hook_authorizer,
176
+ authorization_version=hook_authorization_version,
177
+ )
178
+ execution = ExecutionSpec.model_validate(
179
+ context.bundle.resolved_agent_spec.get("execution") or {},
180
+ )
181
+ limits = execution.native_call_limits()
182
+ adapter.bind_read_only_workspace(
183
+ binding=hashlib.sha256(identity.encode()).hexdigest(),
184
+ model=context.config.model, load_tools=load_tools, context=turn_context,
185
+ scope=scope,
186
+ context_sources=(*service_context_sources(context),
187
+ *(memory.context_sources() if memory else ())),
188
+ hooks=(*hooks, *(memory.hooks() if memory else ())), stop_hook_limit=stop_limit,
189
+ tool_effects=memory.writes if memory is not None else False,
190
+ complete=memory.complete if memory and memory.flush_after else None,
191
+ verifier=service_memory_verifier(context, memory),
192
+ execution_policy={
193
+ "strategy": execution.strategy,
194
+ "maxWallMs": execution.timeout_seconds * 1000 or None,
195
+ "maxModelCalls": limits.max_model_calls,
196
+ "maxToolCalls": limits.max_tool_calls,
197
+ },
198
+ )