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,175 @@
1
+ """Project authenticated, frozen Context Contributors into the service protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import time
8
+ from dataclasses import dataclass
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from ksadk.harness.service_runtime import ServiceContextSource
12
+ from ksadk.plugins.context_contributor import (
13
+ AuthenticatedContextScope,
14
+ ContextContributorExchange,
15
+ ContextContributorRequest,
16
+ ContextContributorResponse,
17
+ )
18
+ from ksadk.plugins.contracts import plugin_lock_digest
19
+ from ksadk.plugins.host import PluginHostError
20
+ from ksadk.plugins.providers.harness_context import (
21
+ HarnessContextContributorConfiguration,
22
+ HarnessContextContributorSource,
23
+ )
24
+ from ksadk.plugins.resolver import composition_profile_digest
25
+ from ksadk.runtime import RunHandle
26
+
27
+ if TYPE_CHECKING:
28
+ from ksadk.plugins.providers.harness import HarnessEngineActivationContext
29
+
30
+
31
+ def _locked_graph(context: HarnessEngineActivationContext) -> None:
32
+ graph = context.bundle.composition
33
+ if (
34
+ context.profile_digest != graph.profile_digest
35
+ or context.profile_digest != composition_profile_digest(graph.profile)
36
+ or context.profile_digest != context.bundle.manifest.composition_profile_digest
37
+ or context.plugin_lock_digest != graph.plugin_lock_digest
38
+ or context.plugin_lock_digest != plugin_lock_digest(graph.plugin_lock)
39
+ or context.plugin_lock_digest != context.bundle.manifest.plugin_lock_digest
40
+ ):
41
+ raise PluginHostError(
42
+ "harness_service_context_unbound", "Context differs from the locked plugin graph",
43
+ )
44
+
45
+
46
+ @dataclass
47
+ class _Contributor:
48
+ context: HarnessEngineActivationContext
49
+ runtime: HarnessContextContributorSource
50
+ config: HarnessContextContributorConfiguration
51
+ scope: dict[str, str]
52
+ cached: tuple[tuple[str, int, int], float, list[dict[str, Any]]] | None = None
53
+
54
+ def check_available(self) -> None:
55
+ available = self.context.activation_available
56
+ if available is not None and not available():
57
+ raise ValueError("Harness context activation is unavailable")
58
+ _locked_graph(self.context)
59
+
60
+ async def read(self, handle: RunHandle, params: dict[str, Any]) -> list[dict[str, Any]]:
61
+ self.check_available()
62
+ remaining = params["remainingTokens"]
63
+ revision = params["goalRevision"]
64
+ if type(remaining) is not int or remaining < 0 or type(revision) is not int or revision < 0:
65
+ raise ValueError("Invalid Harness context budget or goal revision")
66
+ if handle.session_id != self.scope["session_id"]:
67
+ raise ValueError("Harness context session differs from activation")
68
+ budget = min(remaining, self.config.capabilities.max_tokens)
69
+ cache_key = (handle.run_id, revision, budget)
70
+ cache = self.cached
71
+ if cache is not None and cache[0] == cache_key and cache[1] > time.time():
72
+ return cache[2]
73
+ workspace = self.context.user_workspace_root or self.context.workspace_root
74
+ request = ContextContributorRequest(
75
+ request_format="ksadk.context-request/v1",
76
+ scope=AuthenticatedContextScope(
77
+ authenticated=True,
78
+ actor_id=self.scope["user_id"],
79
+ agent_id=self.scope["agent_id"],
80
+ session_id=handle.session_id,
81
+ turn_id=params["turnId"],
82
+ ),
83
+ invocation_id=params["operationKey"],
84
+ user_input=params["goal"],
85
+ workspace_root=str(workspace),
86
+ policy_ref=self.config.policy_ref,
87
+ remaining_budget=budget,
88
+ allowed_classifications=self.config.allowed_classifications,
89
+ metadata={
90
+ "tenant_id": self.scope["tenant_id"], "workspace_id": self.scope["workspace_id"],
91
+ "run_id": handle.run_id, "goal_revision": revision,
92
+ },
93
+ )
94
+ response = await self.runtime.harness_context_contribution(self.context.bundle, request)
95
+ if not isinstance(response, ContextContributorResponse):
96
+ raise ValueError("Invalid Harness context response")
97
+ exchange = ContextContributorExchange(
98
+ contract_format="ksadk.context-contributor/v1", capabilities=self.config.capabilities,
99
+ request=request, response=response,
100
+ )
101
+ exchange.project()
102
+ self.check_available()
103
+ if len(response.fragments) > 64 or len(response.model_dump_json()) > self.config.max_chars:
104
+ raise ValueError("Harness context response exceeded its grant")
105
+ items = []
106
+ expires = float("inf")
107
+ for fragment in response.fragments:
108
+ role = fragment.metadata.get("role")
109
+ privileged = fragment.kind == "compiled_prompt" or (
110
+ isinstance(role, str) and role in {"system", "developer"}
111
+ )
112
+ items.append({
113
+ "projection": "instructions" if privileged else "data",
114
+ "fragment": fragment.model_dump(mode="json", by_alias=True),
115
+ **({"expiresAt": int(fragment.expires_at.timestamp() * 1000)}
116
+ if fragment.expires_at else {}),
117
+ })
118
+ if fragment.expires_at is not None:
119
+ expires = min(expires, fragment.expires_at.timestamp())
120
+ if self.config.capabilities.cacheability != "none":
121
+ self.cached = (cache_key, expires, items)
122
+ return items
123
+
124
+
125
+ def service_context_sources(
126
+ context: HarnessEngineActivationContext,
127
+ ) -> tuple[ServiceContextSource, ...]:
128
+ bindings = tuple(binding for binding in context.context_sources if binding.contributor)
129
+ if not bindings:
130
+ return ()
131
+ claims = dict(context.activation_claims)
132
+ if (
133
+ any(not claims.get(key, "").strip() for key in ("tenant_id", "workspace_id", "user_id"))
134
+ or claims.get("agent_id") != context.agent_name
135
+ or claims.get("session_id") != context.activation_key
136
+ or not context.activation_key
137
+ ):
138
+ raise PluginHostError(
139
+ "harness_service_context_unbound", "Context requires authenticated activation claims",
140
+ )
141
+ _locked_graph(context)
142
+ graph = context.bundle.composition
143
+ result = []
144
+ for binding in bindings:
145
+ ref = f"plugin://{binding.plugin_id}@{binding.plugin_version}"
146
+ declarations = [item for item in graph.profile.capabilities if item.ref == ref]
147
+ offers = [
148
+ offer for entry in graph.plugin_lock.plugins for offer in entry.provides
149
+ if entry.id == binding.plugin_id and entry.version == binding.plugin_version
150
+ and offer.owner == binding.plugin_id and offer.definition == "context.contributor/v1"
151
+ and offer.slot == binding.slot
152
+ ]
153
+ if len(declarations) != 1 or len(offers) != 1 or not isinstance(
154
+ binding.runtime, HarnessContextContributorSource
155
+ ):
156
+ raise PluginHostError(
157
+ "harness_service_context_unbound", "Context source differs from the locked offer",
158
+ )
159
+ config = HarnessContextContributorConfiguration.model_validate(declarations[0].config)
160
+ caps = config.capabilities
161
+ if not caps.max_tokens:
162
+ continue
163
+ identity = json.dumps([
164
+ context.bundle.bundle_digest, context.profile_digest, context.plugin_lock_digest,
165
+ ref, binding.slot, config.model_dump(mode="json"), claims,
166
+ ], ensure_ascii=False, sort_keys=True)
167
+ source = _Contributor(context, binding.runtime, config, claims)
168
+ result.append(ServiceContextSource({
169
+ "sourceId": "ksadk-context-" + hashlib.sha256(ref.encode()).hexdigest()[:24],
170
+ "bindingDigest": "sha256:" + hashlib.sha256(identity.encode()).hexdigest(),
171
+ "maxTokens": caps.max_tokens, "maxBytes": config.max_chars,
172
+ "timeoutMs": caps.timeout_ms, "failureMode": caps.failure_mode,
173
+ "allowInstructions": caps.trust_level in {"developer", "platform"},
174
+ }, source.read))
175
+ return tuple(result)
@@ -0,0 +1,168 @@
1
+ """Bind Python Hook producers and host authorization to independent Runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from contextlib import AsyncExitStack
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ from ksadk.harness.native.hook_executor import HookAuthorizer, HookBinding, ScopedHookExecutor
11
+ from ksadk.harness.native.hook_runtime_contract import HookInvocationRequest, PreCompactSubject
12
+ from ksadk.harness.native.model import ModelToolCall
13
+ from ksadk.harness.service_runtime import ServiceHook
14
+ from ksadk.plugins.providers.harness_hooks import hook_configuration
15
+ from ksadk.runtime import RunHandle
16
+ from ksadk.studio.native_hook_registration import validate_hook_authorization_policy
17
+ from ksadk.studio.native_scope import native_scope_from_activation
18
+
19
+ if TYPE_CHECKING:
20
+ from ksadk.harness.native.hook_runtime_contract import HookDefinition
21
+ from ksadk.plugins.providers.harness import HarnessEngineActivationContext
22
+
23
+
24
+ def _tool_result(result: dict[str, Any] | None) -> dict[str, Any] | None:
25
+ if result is None:
26
+ return None
27
+ usage = result.get("resourceUsage") or {}
28
+ counters = {
29
+ "modelCalls": "model_calls", "toolCalls": "tool_calls",
30
+ "inputTokens": "input_tokens", "outputTokens": "output_tokens",
31
+ "cachedInputTokens": "cached_input_tokens", "reasoningTokens": "reasoning_tokens",
32
+ }
33
+ artifacts = []
34
+ for item in result.get("artifactRefs", []):
35
+ digest = item["digest"]
36
+ artifacts.append({
37
+ "uri": item["uri"], "content_hash": digest if ":" in digest else "sha256:" + digest,
38
+ "mime_type": item["mediaType"], "size_bytes": item["sizeBytes"],
39
+ })
40
+ return {
41
+ "status": result["status"], "content": result["content"],
42
+ "workspace_changed_paths": result.get("workspaceChangedPaths") or [],
43
+ "artifact_refs": artifacts,
44
+ "resource_usage": {
45
+ **{target: usage[key] for key, target in counters.items() if key in usage},
46
+ "child_run_ids": result.get("childRunIds") or [],
47
+ },
48
+ }
49
+
50
+
51
+ def _compaction(value: dict[str, Any] | None) -> PreCompactSubject | None:
52
+ if value is None:
53
+ return None
54
+ return PreCompactSubject.model_validate({
55
+ "source_revision": value["sourceRevision"],
56
+ "source_context_digest": value["sourceContextDigest"],
57
+ "source_message_count": value["sourceMessageCount"],
58
+ "message_refs": value["messageRefs"], "messages": value["messages"],
59
+ "retained_message_refs": value["retainedMessageRefs"],
60
+ **({"source_projection": "canonical_user"}
61
+ if value.get("sourceProjection") == "canonical_user" else {}),
62
+ })
63
+
64
+
65
+ def service_hooks(
66
+ context: HarnessEngineActivationContext,
67
+ cleanup: AsyncExitStack,
68
+ *,
69
+ authorize: HookAuthorizer | None,
70
+ authorization_version: str | None,
71
+ ) -> tuple[tuple[ServiceHook, ...], int | None]:
72
+ if not context.hook_sources:
73
+ return (), None
74
+ scope = native_scope_from_activation(context)
75
+ validate_hook_authorization_policy(authorize, authorization_version)
76
+ if context.activation_available is None or not context.activation_generation:
77
+ raise ValueError("Harness hooks require an owned PluginHost activation")
78
+ bundle = context.bundle
79
+ manifest_json = bundle.manifest.model_dump_json()
80
+ profile_json = bundle.composition.profile.model_dump_json()
81
+ lock_json = bundle.composition.plugin_lock.model_dump_json()
82
+
83
+ def available() -> bool:
84
+ return (
85
+ context.activation_available() is True
86
+ and bundle.manifest.model_dump_json() == manifest_json
87
+ and bundle.composition.profile.model_dump_json() == profile_json
88
+ and bundle.composition.plugin_lock.model_dump_json() == lock_json
89
+ )
90
+
91
+ async def admitted(request: HookInvocationRequest) -> str:
92
+ if authorize is None or not available():
93
+ return "deny"
94
+ return await authorize(request)
95
+
96
+ bindings = []
97
+ stop_limits = set()
98
+ for source in context.hook_sources:
99
+ config = hook_configuration(bundle, source)
100
+ ref = f"plugin://{source.plugin_id}@{source.plugin_version}"
101
+ identity = json.dumps([
102
+ bundle.bundle_digest, context.profile_digest, context.plugin_lock_digest,
103
+ ref, source.slot, config.model_dump(mode="json"), authorization_version,
104
+ "engine-hooks/v1",
105
+ ], sort_keys=True)
106
+ binding_digest = "sha256:" + hashlib.sha256(identity.encode()).hexdigest()
107
+ definitions = config.definitions(source_ref=ref, binding_digest=binding_digest)
108
+ if config.stop_continuation_limit is not None:
109
+ stop_limits.add(config.stop_continuation_limit)
110
+
111
+ async def callback(request, *, read=source.runtime.harness_hook):
112
+ return await read(bundle, request)
113
+
114
+ executor = ScopedHookExecutor(
115
+ scope=scope, bindings=tuple(HookBinding(item, callback, available)
116
+ for item in definitions),
117
+ authorize=admitted if authorize is not None else None,
118
+ cleanup_timeout_seconds=config.cleanup_timeout_seconds,
119
+ )
120
+ cleanup.push_async_callback(executor.aclose)
121
+
122
+ for item in definitions:
123
+ async def invoke(
124
+ handle: RunHandle, params: dict[str, Any],
125
+ *, hook: HookDefinition = item, owner: ScopedHookExecutor = executor,
126
+ ) -> dict[str, Any]:
127
+ if handle.session_id != context.activation_key:
128
+ raise ValueError("Harness Hook session differs from activation")
129
+ payload = params["input"]
130
+ call, candidate = payload["call"], payload["candidate"]
131
+ request = HookInvocationRequest(
132
+ scope=scope, run_id=handle.run_id, session_id=handle.session_id,
133
+ turn_id=params["turnId"], operation_key=params["operationKey"],
134
+ goal_revision=params["goalRevision"], goal=payload["goal"],
135
+ tool_call_count=payload["toolCallCount"],
136
+ stop_continuation_count=payload["stopContinuationCount"],
137
+ event=params["event"], definition=hook,
138
+ call=ModelToolCall(
139
+ call_id=call["callId"], name=call["name"], arguments=call["arguments"],
140
+ ) if call else None,
141
+ tool_result=_tool_result(payload["toolResult"]),
142
+ candidate_id=candidate["candidateId"] if candidate else None,
143
+ candidate_text=candidate["text"] if candidate else None,
144
+ compaction=_compaction(payload["compaction"]),
145
+ )
146
+ result = await owner.invoke(request)
147
+ output = result.output
148
+ return {
149
+ "status": result.status, "reason": result.reason,
150
+ "output": {"action": output.action,
151
+ "additionalContext": list(output.additional_context),
152
+ "updatedArguments": output.updated_arguments} if output else None,
153
+ }
154
+
155
+ bindings.append(ServiceHook({
156
+ "hookId": item.hook_id, "sourceRef": item.source_ref,
157
+ "bindingDigest": item.binding_digest,
158
+ "executionPolicyDigest": item.execution_policy_digest,
159
+ "readOnly": item.read_only, "events": list(item.events),
160
+ "timeoutMs": item.timeout_seconds * 1000, "maxInputBytes": item.max_input_bytes,
161
+ "maxOutputBytes": item.max_output_bytes, "failureMode": item.failure_mode,
162
+ **({"toolNames": list(item.tool_names)} if item.tool_names else {}),
163
+ **({"compactionSourceProjection": item.compaction_source_projection}
164
+ if item.compaction_source_projection else {}),
165
+ }, invoke))
166
+ if len(stop_limits) > 1:
167
+ raise ValueError("Conflicting Harness Stop continuation limits")
168
+ return tuple(bindings), next(iter(stop_limits), None)