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.
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/METADATA +14 -9
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/RECORD +98 -68
- ksadk/__init__.py +2 -1
- ksadk/_build_provenance.json +1 -1
- ksadk/_mcp_compat.py +305 -0
- ksadk/agent.py +29 -0
- ksadk/agui/_agent_kernel.py +176 -142
- ksadk/agui/agent.py +74 -5
- ksadk/agui/hosted.py +343 -0
- ksadk/agui/request_identity.py +11 -0
- ksadk/agui/routes.py +77 -2
- ksadk/builders/code_builder.py +30 -23
- ksadk/builders/container_builder.py +5 -5
- ksadk/builders/mcp_builder.py +142 -0
- ksadk/builders/project_imports.py +66 -0
- ksadk/cli/cmd_mcp.py +1 -1
- ksadk/cli/cmd_run.py +2 -4
- ksadk/cli/cmd_web.py +8 -0
- ksadk/cli/runtime_bootstrap.py +4 -1
- ksadk/common/cloud_headers.py +33 -6
- ksadk/compat/adk_compat.py +2 -0
- ksadk/compat/adk_stream.py +35 -0
- ksadk/configs/env_registry.py +31 -0
- ksadk/conversations/projector.py +6 -0
- ksadk/conversations/runtime_observability.py +1 -0
- ksadk/detection/mcp_detector.py +80 -22
- ksadk/harness/__init__.py +3 -0
- ksadk/harness/service_presentation.py +44 -0
- ksadk/harness/service_runtime.py +1038 -0
- ksadk/interaction/providers/harness.py +9 -4
- ksadk/kernel/ingress.py +35 -25
- ksadk/kernel/worker.py +2 -2
- ksadk/kernel/worker_identity.py +15 -8
- ksadk/knowledge_base/client.py +10 -3
- ksadk/mcp_runtime/oauth/_agent.py +77 -9
- ksadk/mcp_runtime/oauth/langgraph.py +47 -15
- ksadk/mcp_runtime/oauth/local/broker.py +23 -1
- ksadk/mcp_runtime/oauth/tools.py +46 -8
- ksadk/mcp_runtime/oauth/transport.py +19 -2
- ksadk/memory/adk/backends/sdk_ltm_backend.py +21 -12
- ksadk/memory/scope_ids.py +49 -0
- ksadk/plugins/providers/harness.py +65 -28
- ksadk/plugins/providers/harness_service.py +198 -0
- ksadk/plugins/providers/harness_service_context.py +175 -0
- ksadk/plugins/providers/harness_service_hooks.py +168 -0
- ksadk/plugins/providers/harness_service_memory.py +479 -0
- ksadk/plugins/providers/platform_resources.py +2 -2
- ksadk/resource_runtime/langgraph.py +7 -3
- ksadk/resource_runtime/mcp_server.py +3 -3
- ksadk/resource_runtime/worker.py +19 -4
- ksadk/runners/_adk_canonical_stream.py +38 -10
- ksadk/runners/_adk_tunnel_history.py +96 -0
- ksadk/runners/_langgraph_canonical_stream.py +16 -0
- ksadk/runners/_langgraph_factory.py +79 -0
- ksadk/runners/_langgraph_runner_streams.py +6 -0
- ksadk/runners/_session_identity.py +8 -3
- ksadk/runners/adk_runner.py +95 -19
- ksadk/runners/langgraph_runner.py +15 -21
- ksadk/runtime/factory.py +17 -5
- ksadk/runtime/framework_adapters.py +10 -0
- ksadk/runtime/langgraph_checkpoint_view.py +28 -7
- ksadk/runtime/launch.py +2 -0
- ksadk/server/factory.py +55 -0
- ksadk/server/routes/common.py +2 -0
- ksadk/server/routes/harness_service_view.py +38 -0
- ksadk/server/routes/ui_bootstrap.py +16 -2
- ksadk/skills/mcp_server/server.py +239 -217
- ksadk/studio/contracts.py +8 -0
- ksadk/studio/mcp_runtime.py +23 -8
- ksadk/studio/native_mcp_disclosure.py +8 -6
- ksadk/studio/native_mcp_tool_port.py +3 -1
- ksadk/studio/native_memory_context.py +10 -8
- ksadk/studio/native_product.py +3 -4
- ksadk/studio/plugin_composition.py +8 -1
- ksadk/studio/plugin_native_activation.py +4 -2
- ksadk/studio/plugin_runtime.py +9 -0
- ksadk/studio/service.py +2 -0
- ksadk/tracing/setup.py +53 -3
- ksadk/tunnel/__init__.py +37 -0
- ksadk/tunnel/connector.py +384 -0
- ksadk/tunnel/discovery.py +107 -0
- ksadk/tunnel/failure.py +168 -0
- ksadk/tunnel/http_tools.py +100 -0
- ksadk/tunnel/langgraph.py +125 -0
- ksadk/tunnel/middleware.py +28 -0
- ksadk/tunnel/peers.py +872 -0
- ksadk/tunnel/protocol.py +97 -0
- ksadk/tunnel/registry.py +306 -0
- ksadk/tunnel/runtime.py +147 -0
- ksadk/tunnel/server.py +201 -0
- ksadk/tunnel/services.py +366 -0
- ksadk/tunnel/toolset.py +78 -0
- ksadk/version.py +1 -1
- ksadk_runtime_common/memory_backend/providers/mem0.py +20 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/WHEEL +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/entry_points.txt +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/licenses/LICENSE +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
"""Run-scoped local Memory ports for the independent Harness service."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import inspect
|
|
7
|
+
import json
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
from ksadk.context_engine.tokenizer import get_default_token_counter
|
|
12
|
+
from ksadk.harness.service_runtime import (
|
|
13
|
+
ServiceContextSource,
|
|
14
|
+
ServiceGoalVerifier,
|
|
15
|
+
ServiceHook,
|
|
16
|
+
ServiceHostTool,
|
|
17
|
+
)
|
|
18
|
+
from ksadk.memory.extraction import explicit_memory_target
|
|
19
|
+
from ksadk.memory.models import MemoryConflictError, MemoryRecord, MemorySearchResult
|
|
20
|
+
from ksadk.memory.policy import HARD_REJECT_LABELS, detect_sensitive_labels
|
|
21
|
+
from ksadk.plugins.builtins import LOCAL_MEMORY_PROVIDER_PLUGIN_ID
|
|
22
|
+
from ksadk.plugins.host import PluginHostError
|
|
23
|
+
from ksadk.plugins.memory_provider import (
|
|
24
|
+
MemoryFlushRequest,
|
|
25
|
+
MemoryMutationRequest,
|
|
26
|
+
MemoryPrincipal,
|
|
27
|
+
MemoryRecallRequest,
|
|
28
|
+
MemoryReceiptRequest,
|
|
29
|
+
MemoryRecordRequest,
|
|
30
|
+
MemoryUserObservation,
|
|
31
|
+
)
|
|
32
|
+
from ksadk.runtime import RunHandle
|
|
33
|
+
from ksadk.studio.contracts import ContextSpec, MemorySpec
|
|
34
|
+
from ksadk.studio.native_memory_acceptance import VERIFIER_REF, VERIFIER_VERSION
|
|
35
|
+
from ksadk.studio.native_memory_context import (
|
|
36
|
+
admitted_memory_records,
|
|
37
|
+
memory_record_expiry,
|
|
38
|
+
selected_memory_binding,
|
|
39
|
+
)
|
|
40
|
+
from ksadk.studio.native_scope import native_scope_from_activation
|
|
41
|
+
|
|
42
|
+
if TYPE_CHECKING:
|
|
43
|
+
from ksadk.plugins.providers.harness import HarnessEngineActivationContext
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _digest(value: Any) -> str:
|
|
47
|
+
encoded = json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False).encode()
|
|
48
|
+
return "sha256:" + hashlib.sha256(encoded).hexdigest()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _view(record: MemoryRecord) -> dict[str, Any]:
|
|
52
|
+
return {
|
|
53
|
+
"memory_id": record.memory_id, "content": record.content, "scope": record.scope,
|
|
54
|
+
"version": record.version, "source_event_ids": record.source_event_ids,
|
|
55
|
+
"source_session_id": record.source_session_id, "content_hash": record.content_hash,
|
|
56
|
+
"updated_at": record.updated_at, "trust_level": "untrusted",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _error(code: str) -> dict[str, Any]:
|
|
61
|
+
return {"status": "error", "content": {"code": code}}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _verification_result(status, reason, summary, refs=()):
|
|
65
|
+
return {
|
|
66
|
+
"status": status, "reason": reason, "safeSummary": summary, "evidenceRefs": list(refs),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ServiceLocalMemory:
|
|
71
|
+
def __init__(
|
|
72
|
+
self, context: HarnessEngineActivationContext, policy: MemorySpec,
|
|
73
|
+
context_policy: ContextSpec,
|
|
74
|
+
) -> None:
|
|
75
|
+
self.context = context
|
|
76
|
+
self.policy = policy
|
|
77
|
+
self.bundle = context.bundle
|
|
78
|
+
binding, ref = selected_memory_binding(context)
|
|
79
|
+
if binding.plugin_id != LOCAL_MEMORY_PROVIDER_PLUGIN_ID:
|
|
80
|
+
raise PluginHostError("harness_service_memory_unbound", "Local Memory owner is invalid")
|
|
81
|
+
self.owner = binding.runtime
|
|
82
|
+
self.provider_ref = ref
|
|
83
|
+
self.principal = MemoryPrincipal(**native_scope_from_activation(context).model_dump())
|
|
84
|
+
self.scopes = tuple(policy.scopes)
|
|
85
|
+
self.rollout = context_policy.rollout.memory_write
|
|
86
|
+
self.writes = policy.write.mode != "off" and self.rollout != "off"
|
|
87
|
+
may_flush = self.writes and "user" in self.scopes
|
|
88
|
+
self.flush_before = may_flush and policy.write.flush_before_compaction
|
|
89
|
+
self.flush_after = may_flush and policy.write.flush_after_turn
|
|
90
|
+
self.recall = bool(
|
|
91
|
+
policy.recall.enabled and policy.recall.max_tokens
|
|
92
|
+
and context_policy.contributors.memory_recall is not False
|
|
93
|
+
)
|
|
94
|
+
required = ["memory_read", "memory_search"]
|
|
95
|
+
if self.recall:
|
|
96
|
+
required.append("memory_recall")
|
|
97
|
+
if self.writes:
|
|
98
|
+
required.extend(["memory_mutate", "memory_receipt"])
|
|
99
|
+
if self.flush_before or self.flush_after:
|
|
100
|
+
required.append("memory_flush")
|
|
101
|
+
if not all(inspect.iscoroutinefunction(getattr(self.owner, method, None))
|
|
102
|
+
for method in required):
|
|
103
|
+
raise PluginHostError(
|
|
104
|
+
"harness_service_memory_unbound", "Local Memory ports are invalid",
|
|
105
|
+
)
|
|
106
|
+
self.manifest = self.bundle.manifest.model_dump_json()
|
|
107
|
+
self.profile = self.bundle.composition.profile.model_dump_json()
|
|
108
|
+
self.lock = self.bundle.composition.plugin_lock.model_dump_json()
|
|
109
|
+
self.binding = _digest([
|
|
110
|
+
self.bundle.bundle_digest, context.profile_digest, context.plugin_lock_digest, ref,
|
|
111
|
+
binding.slot, self.principal.model_dump(), policy.model_dump(), self.rollout,
|
|
112
|
+
"local-memory-service/v1",
|
|
113
|
+
])
|
|
114
|
+
|
|
115
|
+
def _available(self) -> None:
|
|
116
|
+
available = self.context.activation_available
|
|
117
|
+
if (
|
|
118
|
+
available is None or not available()
|
|
119
|
+
or self.bundle.manifest.model_dump_json() != self.manifest
|
|
120
|
+
or self.bundle.composition.profile.model_dump_json() != self.profile
|
|
121
|
+
or self.bundle.composition.plugin_lock.model_dump_json() != self.lock
|
|
122
|
+
):
|
|
123
|
+
raise ValueError("Memory activation is no longer available")
|
|
124
|
+
|
|
125
|
+
def _request(self, query: str, budget: int) -> MemoryRecallRequest:
|
|
126
|
+
return MemoryRecallRequest(
|
|
127
|
+
principal=self.principal, query=query, scopes=self.scopes,
|
|
128
|
+
top_k=self.policy.recall.top_k, max_tokens=budget,
|
|
129
|
+
min_score=self.policy.recall.min_score,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
def _records(self, result: MemorySearchResult):
|
|
133
|
+
return admitted_memory_records(
|
|
134
|
+
result, principal=self.principal, scopes=self.scopes, top_k=self.policy.recall.top_k,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def _fit(self, views: list[dict[str, Any]], budget: int) -> list[dict[str, Any]]:
|
|
138
|
+
counter = get_default_token_counter()
|
|
139
|
+
admitted = []
|
|
140
|
+
remaining = budget
|
|
141
|
+
for view in views:
|
|
142
|
+
cost = counter.count_text(json.dumps(view, ensure_ascii=False)) + 96
|
|
143
|
+
if cost <= remaining:
|
|
144
|
+
admitted.append(view)
|
|
145
|
+
remaining -= cost
|
|
146
|
+
return admitted
|
|
147
|
+
|
|
148
|
+
async def _read(self, arguments: dict[str, Any]) -> dict[str, Any]:
|
|
149
|
+
self._available()
|
|
150
|
+
request = MemoryRecordRequest(
|
|
151
|
+
principal=self.principal, scopes=self.scopes, memory_id=arguments["memory_id"],
|
|
152
|
+
)
|
|
153
|
+
record = await self.owner.memory_read(self.bundle, request)
|
|
154
|
+
self._available()
|
|
155
|
+
candidates = MemorySearchResult("ok", [record] if record else [], None, "local-default", 0,
|
|
156
|
+
"exact")
|
|
157
|
+
views = [_view(item) for item in self._records(candidates)]
|
|
158
|
+
return {"record": views[0]} if views else {"ok": False, "code": "memory_not_found_in_scope"}
|
|
159
|
+
|
|
160
|
+
async def _search(self, arguments: dict[str, Any]) -> dict[str, Any]:
|
|
161
|
+
self._available()
|
|
162
|
+
budget = self.policy.recall.max_tokens
|
|
163
|
+
request = self._request(arguments["query"], budget)
|
|
164
|
+
result = await self.owner.memory_search(self.bundle, request)
|
|
165
|
+
self._available()
|
|
166
|
+
candidates = [_view(item) for item in self._records(result)]
|
|
167
|
+
records = self._fit(candidates, budget)
|
|
168
|
+
return {"records": records, "truncated": len(records) < len(candidates)
|
|
169
|
+
or result.truncated_by_budget, "trust_level": "untrusted"}
|
|
170
|
+
|
|
171
|
+
async def _recall(self, handle: RunHandle, params: dict[str, Any]) -> list[dict[str, Any]]:
|
|
172
|
+
self._available()
|
|
173
|
+
if handle.session_id != self.context.activation_key:
|
|
174
|
+
raise ValueError("Memory recall session differs from activation")
|
|
175
|
+
budget = min(params["remainingTokens"], self.policy.recall.max_tokens)
|
|
176
|
+
if budget <= 0:
|
|
177
|
+
return []
|
|
178
|
+
result = await self.owner.memory_recall(self.bundle, self._request(params["goal"], budget))
|
|
179
|
+
self._available()
|
|
180
|
+
candidates = []
|
|
181
|
+
for record in self._records(result):
|
|
182
|
+
item = {"projection": "data", "fragment": {"kind": "recalled_memory", **_view(record)}}
|
|
183
|
+
expiry = memory_record_expiry(record)
|
|
184
|
+
if expiry is not None:
|
|
185
|
+
item["expiresAt"] = int(expiry.timestamp() * 1000)
|
|
186
|
+
candidates.append(item)
|
|
187
|
+
return self._fit(candidates, budget)
|
|
188
|
+
|
|
189
|
+
async def _mutate(self, handle: RunHandle, params: dict[str, Any]) -> dict[str, Any]:
|
|
190
|
+
self._available()
|
|
191
|
+
if handle.session_id != self.context.activation_key:
|
|
192
|
+
return _error("memory_session_unbound")
|
|
193
|
+
arguments, effect = params["arguments"], params["effect"]
|
|
194
|
+
observations = self._observations(handle, effect["observations"])
|
|
195
|
+
explicit = explicit_memory_target(effect["goal"])
|
|
196
|
+
authorized = (
|
|
197
|
+
explicit is not None and explicit[1] == arguments.get("content")
|
|
198
|
+
and {"add": "remember", "update": "correct"}.get(explicit[0]) == arguments["action"]
|
|
199
|
+
and any(
|
|
200
|
+
observation.content == effect["goal"]
|
|
201
|
+
and observation.source_event_id.startswith(f"native-message://{handle.run_id}#")
|
|
202
|
+
for observation in observations
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
if not authorized and self.rollout != "shadow" and not effect["approved"]:
|
|
206
|
+
if effect["canRequestApproval"]:
|
|
207
|
+
return {"status": "approval_required"}
|
|
208
|
+
return _error("memory_approval_required")
|
|
209
|
+
authority = "approved_call" if effect["approved"] else "candidate"
|
|
210
|
+
if authorized:
|
|
211
|
+
authority = "explicit_user"
|
|
212
|
+
receipt_request = self._receipt_request(
|
|
213
|
+
handle, effect["operationKey"], params["callId"], arguments, authority,
|
|
214
|
+
)
|
|
215
|
+
try:
|
|
216
|
+
mutation = MemoryMutationRequest(
|
|
217
|
+
**receipt_request.model_dump(), **arguments,
|
|
218
|
+
authority=authority,
|
|
219
|
+
source_session_id=handle.session_id, source_event_id=effect["sourceEventId"],
|
|
220
|
+
source_goal_revision=effect["goalRevision"],
|
|
221
|
+
source_goal_digest=_digest({"goal": effect["goal"]}),
|
|
222
|
+
source_user_observations=observations if arguments.get("scope") == "user" else (),
|
|
223
|
+
)
|
|
224
|
+
except ValueError:
|
|
225
|
+
return _error("invalid_memory_action_arguments")
|
|
226
|
+
try:
|
|
227
|
+
persisted = await self.owner.memory_receipt(self.bundle, receipt_request)
|
|
228
|
+
if persisted is not None:
|
|
229
|
+
self._available()
|
|
230
|
+
return {"status": "ok", "content": persisted}
|
|
231
|
+
result = await self.owner.memory_mutate(self.bundle, mutation)
|
|
232
|
+
except MemoryConflictError:
|
|
233
|
+
return _error("memory_version_or_identity_conflict")
|
|
234
|
+
except PluginHostError as error:
|
|
235
|
+
if error.code == "memory_write_disabled":
|
|
236
|
+
return _error("memory_write_disabled")
|
|
237
|
+
raise
|
|
238
|
+
self._available()
|
|
239
|
+
if result.get("committed") is True:
|
|
240
|
+
persisted = await self.owner.memory_receipt(self.bundle, receipt_request)
|
|
241
|
+
if persisted is None or persisted.get("committed") is not True:
|
|
242
|
+
return {"status": "uncertain"}
|
|
243
|
+
self._available()
|
|
244
|
+
return {"status": "ok", "content": persisted}
|
|
245
|
+
status = "ok" if result.get("decision") == "shadow" else "error"
|
|
246
|
+
return {"status": status, "content": result}
|
|
247
|
+
|
|
248
|
+
def _receipt_request(self, handle, operation_key, call_id, arguments, authority):
|
|
249
|
+
return MemoryReceiptRequest(
|
|
250
|
+
principal=self.principal,
|
|
251
|
+
operation_key=_digest([self.principal.model_dump(), handle.run_id, operation_key]),
|
|
252
|
+
request_digest=_digest([self.binding, handle.run_id, call_id, arguments, authority]),
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
async def _current(self, memory_id, body):
|
|
256
|
+
if not isinstance(memory_id, str):
|
|
257
|
+
return None
|
|
258
|
+
result = await self._read({"memory_id": memory_id})
|
|
259
|
+
record = result.get("record")
|
|
260
|
+
if not record or record["content"] != body:
|
|
261
|
+
return None
|
|
262
|
+
return "memory-record:" + _digest([
|
|
263
|
+
self.principal.model_dump(), memory_id, record["version"], record["content_hash"],
|
|
264
|
+
])
|
|
265
|
+
|
|
266
|
+
async def _confirm_write(self, handle, evidence, body):
|
|
267
|
+
content = evidence["content"]
|
|
268
|
+
if (
|
|
269
|
+
evidence["status"] != "ok" or not isinstance(content, dict)
|
|
270
|
+
or content.get("committed") is not True
|
|
271
|
+
):
|
|
272
|
+
return None
|
|
273
|
+
call = evidence["call"]
|
|
274
|
+
for authority in ("explicit_user", "approved_call"):
|
|
275
|
+
request = self._receipt_request(
|
|
276
|
+
handle, evidence["operationKey"], call["callId"], call["arguments"], authority,
|
|
277
|
+
)
|
|
278
|
+
try:
|
|
279
|
+
receipt = await self.owner.memory_receipt(self.bundle, request)
|
|
280
|
+
except MemoryConflictError:
|
|
281
|
+
continue
|
|
282
|
+
self._available()
|
|
283
|
+
if receipt == content:
|
|
284
|
+
return await self._current(content.get("memory_id"), body)
|
|
285
|
+
return None
|
|
286
|
+
|
|
287
|
+
async def verify_goal(self, handle, params):
|
|
288
|
+
self._available()
|
|
289
|
+
if handle.session_id != self.context.activation_key:
|
|
290
|
+
raise ValueError("Memory verification session differs from activation")
|
|
291
|
+
operation, body = explicit_memory_target(params["goal"])
|
|
292
|
+
evidence = params["evidence"]
|
|
293
|
+
if operation == "add":
|
|
294
|
+
recalled = [row["item"] for row in evidence["context"]]
|
|
295
|
+
for row in evidence["calls"]:
|
|
296
|
+
name, content = row["call"]["name"], row["content"]
|
|
297
|
+
if row["status"] != "ok" or not isinstance(content, dict):
|
|
298
|
+
continue
|
|
299
|
+
if name == "read_memory" and isinstance(content.get("record"), dict):
|
|
300
|
+
recalled.append(content["record"])
|
|
301
|
+
if name == "search_memory" and isinstance(content.get("records"), list):
|
|
302
|
+
recalled.extend(content["records"])
|
|
303
|
+
for item in recalled:
|
|
304
|
+
if item.get("content") == body:
|
|
305
|
+
if reference := await self._current(item.get("memory_id"), body):
|
|
306
|
+
return _verification_result(
|
|
307
|
+
"passed", "current_durable_fact",
|
|
308
|
+
"The exact requested fact is present in scoped durable Memory.",
|
|
309
|
+
[reference],
|
|
310
|
+
)
|
|
311
|
+
if not self.writes or self.rollout != "enabled":
|
|
312
|
+
return _verification_result(
|
|
313
|
+
"blocked", "memory_write_not_committing",
|
|
314
|
+
"This Build does not commit Memory writes.",
|
|
315
|
+
)
|
|
316
|
+
if len(body) > 8192 or HARD_REJECT_LABELS.intersection(detect_sensitive_labels(body, [])):
|
|
317
|
+
return _verification_result(
|
|
318
|
+
"blocked", "memory_fact_rejected",
|
|
319
|
+
"This fact cannot be written under Memory policy.",
|
|
320
|
+
)
|
|
321
|
+
action = {"add": "remember", "update": "correct"}[operation]
|
|
322
|
+
for row in evidence["calls"]:
|
|
323
|
+
call, content = row["call"], row["content"]
|
|
324
|
+
if (
|
|
325
|
+
call["name"] != "manage_memory" or call["arguments"].get("action") != action
|
|
326
|
+
or call["arguments"].get("content") != body
|
|
327
|
+
):
|
|
328
|
+
continue
|
|
329
|
+
if isinstance(content, dict) and content.get("code") == "policy_denied":
|
|
330
|
+
return _verification_result(
|
|
331
|
+
"blocked", "memory_approval_denied", "The requested Memory write was denied.",
|
|
332
|
+
)
|
|
333
|
+
if reference := await self._confirm_write(handle, row, body):
|
|
334
|
+
return _verification_result(
|
|
335
|
+
"passed", "current_committed_fact",
|
|
336
|
+
"The owner receipt matches the exact current scoped durable record.",
|
|
337
|
+
[reference, "engine-event:" + _digest(row["eventId"])],
|
|
338
|
+
)
|
|
339
|
+
check = _digest([self.binding, handle.run_id, params["goalRevision"], body])
|
|
340
|
+
return _verification_result(
|
|
341
|
+
"failed", "durable_fact_missing",
|
|
342
|
+
"The requested durable fact is missing. Use manage_memory and inspect its receipt. "
|
|
343
|
+
"For a correction, read the exact record and use its current version.",
|
|
344
|
+
["memory-check:" + check],
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
def _observations(
|
|
348
|
+
self, handle: RunHandle, rows: list[dict[str, Any]], *, current_only: bool = False,
|
|
349
|
+
) -> tuple[MemoryUserObservation, ...]:
|
|
350
|
+
if handle.session_id != self.context.activation_key:
|
|
351
|
+
raise ValueError("Memory observation session differs from activation")
|
|
352
|
+
observations = []
|
|
353
|
+
for row in rows:
|
|
354
|
+
run_id, event_id = row["sourceRunId"], row["sourceEventId"]
|
|
355
|
+
index = event_id.removeprefix(f"native-message://{run_id}#message=")
|
|
356
|
+
if not index.isascii() or not index.isdecimal():
|
|
357
|
+
raise ValueError("Memory observation source identity is invalid")
|
|
358
|
+
if current_only and run_id != handle.run_id:
|
|
359
|
+
raise ValueError("Completed-Turn source differs from original Run")
|
|
360
|
+
observations.append(MemoryUserObservation(
|
|
361
|
+
source_event_id=event_id, source_session_id=handle.session_id,
|
|
362
|
+
source_digest=row["sourceDigest"], content=row["content"],
|
|
363
|
+
))
|
|
364
|
+
return tuple(observations)
|
|
365
|
+
|
|
366
|
+
async def _flush(self, request: MemoryFlushRequest) -> dict[str, Any]:
|
|
367
|
+
self._available()
|
|
368
|
+
result = await self.owner.memory_flush(self.bundle, request)
|
|
369
|
+
self._available()
|
|
370
|
+
return result
|
|
371
|
+
|
|
372
|
+
async def complete(self, handle: RunHandle, params: dict[str, Any]) -> None:
|
|
373
|
+
if not self.flush_after or "manage_memory" in params["effectTools"]:
|
|
374
|
+
return
|
|
375
|
+
observations = self._observations(handle, params["observations"], current_only=True)
|
|
376
|
+
if observations:
|
|
377
|
+
await self._flush(MemoryFlushRequest(
|
|
378
|
+
principal=self.principal, trigger="completed_turn", observations=observations,
|
|
379
|
+
))
|
|
380
|
+
|
|
381
|
+
async def _pre_compact(self, handle: RunHandle, params: dict[str, Any]) -> dict[str, Any]:
|
|
382
|
+
if params["event"] != "PreCompact":
|
|
383
|
+
raise ValueError("Memory flush requires a PreCompact effect")
|
|
384
|
+
observations = self._observations(handle, params["observations"])
|
|
385
|
+
result = await self._flush(MemoryFlushRequest(
|
|
386
|
+
principal=self.principal, trigger="pre_compaction", observations=observations,
|
|
387
|
+
))
|
|
388
|
+
feedback = {
|
|
389
|
+
"memory_candidate_flush": result["status"], "proposed": result["proposed"],
|
|
390
|
+
"decisions": dict(Counter(item["decision"] for item in result["results"])),
|
|
391
|
+
"current_fact_verification": False, "trust_level": "untrusted",
|
|
392
|
+
}
|
|
393
|
+
return {"status": "ok", "reason": None, "output": {
|
|
394
|
+
"action": "continue", "updatedArguments": None,
|
|
395
|
+
"additionalContext": [json.dumps(feedback, ensure_ascii=False)],
|
|
396
|
+
}}
|
|
397
|
+
|
|
398
|
+
def hooks(self) -> tuple[ServiceHook, ...]:
|
|
399
|
+
if not self.flush_before:
|
|
400
|
+
return ()
|
|
401
|
+
return (ServiceHook({
|
|
402
|
+
"hookId": "ksadk.memory.precompact", "sourceRef": self.provider_ref,
|
|
403
|
+
"bindingDigest": self.binding,
|
|
404
|
+
"executionPolicyDigest": _digest(["ksadk-service-memory-precompact/v1", 3000]),
|
|
405
|
+
"readOnly": self.rollout == "shadow", "events": ["PreCompact"],
|
|
406
|
+
"timeoutMs": 3000, "maxInputBytes": 262144, "maxOutputBytes": 16384,
|
|
407
|
+
"failureMode": "warn", "compactionSourceProjection": "canonical_user",
|
|
408
|
+
}, self._pre_compact),)
|
|
409
|
+
|
|
410
|
+
def context_sources(self) -> tuple[ServiceContextSource, ...]:
|
|
411
|
+
if not self.recall:
|
|
412
|
+
return ()
|
|
413
|
+
return (ServiceContextSource({
|
|
414
|
+
"sourceId": "ksadk-memory-recall", "bindingDigest": self.binding,
|
|
415
|
+
"maxTokens": self.policy.recall.max_tokens, "maxBytes": 131072,
|
|
416
|
+
"timeoutMs": 3000, "failureMode": "skip", "allowInstructions": False,
|
|
417
|
+
}, self._recall),)
|
|
418
|
+
|
|
419
|
+
def tools(self) -> list[ServiceHostTool]:
|
|
420
|
+
def schema(properties, required):
|
|
421
|
+
return {"type": "object", "additionalProperties": False,
|
|
422
|
+
"properties": properties, "required": required}
|
|
423
|
+
|
|
424
|
+
identity = {"type": "string", "minLength": 1, "maxLength": 256}
|
|
425
|
+
tools = [ServiceHostTool(
|
|
426
|
+
"read_memory", "Read an exact scoped memory record and its version.",
|
|
427
|
+
schema({"memory_id": identity}, ["memory_id"]), self._read, read_only=True,
|
|
428
|
+
)]
|
|
429
|
+
if self.policy.recall.max_tokens:
|
|
430
|
+
tools.append(ServiceHostTool(
|
|
431
|
+
"search_memory", "Search this Agent's granted scopes for relevant Memory.",
|
|
432
|
+
schema({"query": {"type": "string", "minLength": 1, "maxLength": 4096}}, ["query"]),
|
|
433
|
+
self._search, read_only=True,
|
|
434
|
+
))
|
|
435
|
+
if self.writes:
|
|
436
|
+
tools.append(ServiceHostTool(
|
|
437
|
+
"manage_memory", "Remember, correct, or forget a scoped fact. Correct and forget "
|
|
438
|
+
"require the exact ID and version. Only a committed receipt proves a write.",
|
|
439
|
+
schema({
|
|
440
|
+
"action": {"type": "string", "enum": ["remember", "correct", "forget"]},
|
|
441
|
+
"scope": {"type": "string", "enum": list(self.scopes)},
|
|
442
|
+
"content": {"type": "string", "maxLength": 8192},
|
|
443
|
+
"memory_id": identity, "expected_version": {"type": "integer", "minimum": 1},
|
|
444
|
+
}, ["action", "scope"]), None, effect=self._mutate,
|
|
445
|
+
))
|
|
446
|
+
return tools
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def service_local_memory(context: HarnessEngineActivationContext) -> ServiceLocalMemory | None:
|
|
450
|
+
policy = MemorySpec.model_validate(context.bundle.resolved_agent_spec.get("memory") or {})
|
|
451
|
+
if not policy.enabled or not policy.scopes or policy.provider_ref != "local-default":
|
|
452
|
+
return None
|
|
453
|
+
context_policy = ContextSpec.model_validate(
|
|
454
|
+
context.bundle.resolved_agent_spec.get("context") or {},
|
|
455
|
+
)
|
|
456
|
+
return ServiceLocalMemory(context, policy, context_policy)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def service_memory_verifier(
|
|
460
|
+
context: HarnessEngineActivationContext, memory: ServiceLocalMemory | None,
|
|
461
|
+
) -> ServiceGoalVerifier | None:
|
|
462
|
+
policy = MemorySpec.model_validate(context.bundle.resolved_agent_spec.get("memory") or {})
|
|
463
|
+
if policy.provider_ref != "local-default":
|
|
464
|
+
return None
|
|
465
|
+
|
|
466
|
+
async def disabled(_handle, _params):
|
|
467
|
+
return _verification_result(
|
|
468
|
+
"blocked", "memory_not_enabled_in_build", "This Build has no active local Memory.",
|
|
469
|
+
)
|
|
470
|
+
|
|
471
|
+
return ServiceGoalVerifier({
|
|
472
|
+
"verifierRef": VERIFIER_REF, "verifierVersion": VERIFIER_VERSION,
|
|
473
|
+
"bindingDigest": memory.binding if memory else _digest([
|
|
474
|
+
context.bundle.bundle_digest, context.plugin_lock_digest, "disabled-local-memory",
|
|
475
|
+
]),
|
|
476
|
+
"evidenceTools": [tool.name for tool in memory.tools()] if memory else [],
|
|
477
|
+
"contextSourceId": "ksadk-memory-recall" if memory and memory.recall else None,
|
|
478
|
+
}, lambda goal: explicit_memory_target(goal) is not None,
|
|
479
|
+
memory.verify_goal if memory else disabled)
|
|
@@ -44,11 +44,11 @@ from ksadk.studio.resource_authority import (
|
|
|
44
44
|
PLATFORM_RESOURCE_MCP_PLUGIN_ID = "io.ksadk.mcp.platform-resources"
|
|
45
45
|
PLATFORM_RESOURCE_MCP_PLUGIN_VERSION = "1.0.0"
|
|
46
46
|
PLATFORM_RESOURCE_MCP_PERMISSION = "platform-resource:read"
|
|
47
|
+
PLATFORM_RESOURCE_MCP_NAME = "platform-resources"
|
|
47
48
|
PLATFORM_RESOURCE_MCP_REF = (
|
|
48
49
|
f"plugin://{PLATFORM_RESOURCE_MCP_PLUGIN_ID}@{PLATFORM_RESOURCE_MCP_PLUGIN_VERSION}"
|
|
49
50
|
)
|
|
50
51
|
_ARTIFACT_PATH = "platform-resources"
|
|
51
|
-
_CONNECTOR_NAME = "platform-resources"
|
|
52
52
|
|
|
53
53
|
ResourceWriteAuthorizerFactory = Callable[
|
|
54
54
|
[str, ResolvedPluginBundle], ResourceWriteAuthorizer | None
|
|
@@ -545,7 +545,7 @@ class PlatformResourceMCPRuntime:
|
|
|
545
545
|
aliases = {operation: operation for operation in operations}
|
|
546
546
|
token = connector.resource_bearer_token(aliases, active.leases)
|
|
547
547
|
spec = McpToolSpec(
|
|
548
|
-
name=
|
|
548
|
+
name=PLATFORM_RESOURCE_MCP_NAME,
|
|
549
549
|
url=connector.endpoint,
|
|
550
550
|
api_key=token,
|
|
551
551
|
tool_filter=operations,
|
|
@@ -6,6 +6,10 @@ state/checkpoints. This does not mutate compiled graphs or supply memory hooks.
|
|
|
6
6
|
"""
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
+
from ksadk._mcp_compat import tool_input_schema
|
|
10
|
+
|
|
11
|
+
from ksadk._mcp_compat import field
|
|
12
|
+
|
|
9
13
|
import json
|
|
10
14
|
from collections.abc import AsyncIterator, Mapping, Sequence
|
|
11
15
|
from contextlib import asynccontextmanager
|
|
@@ -48,7 +52,7 @@ async def create_bound_resource_tools(
|
|
|
48
52
|
inventory = await session.list_tools()
|
|
49
53
|
by_name = {tool.name: tool for tool in inventory.tools}
|
|
50
54
|
if (
|
|
51
|
-
inventory
|
|
55
|
+
field(inventory, "next_cursor", "nextCursor")
|
|
52
56
|
or len(by_name) != len(inventory.tools)
|
|
53
57
|
or set(by_name) != set(aliases)
|
|
54
58
|
):
|
|
@@ -67,7 +71,7 @@ async def create_bound_resource_tools(
|
|
|
67
71
|
except Exception:
|
|
68
72
|
raise ToolException("RESOURCE_MCP_CALL_FAILED") from None
|
|
69
73
|
payload = result.model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
70
|
-
if result
|
|
74
|
+
if field(result, "is_error", "isError", default=False):
|
|
71
75
|
# Preserve structured diagnostics and tell ToolNode the
|
|
72
76
|
# call failed. Never return a failed business call as success.
|
|
73
77
|
raise ToolException(json.dumps(payload, ensure_ascii=False))
|
|
@@ -80,7 +84,7 @@ async def create_bound_resource_tools(
|
|
|
80
84
|
coroutine=invoke,
|
|
81
85
|
name=name,
|
|
82
86
|
description=descriptor.description or name,
|
|
83
|
-
args_schema=descriptor
|
|
87
|
+
args_schema=tool_input_schema(descriptor),
|
|
84
88
|
infer_schema=False,
|
|
85
89
|
response_format="content_and_artifact",
|
|
86
90
|
handle_tool_error=True,
|
|
@@ -7,7 +7,7 @@ import time
|
|
|
7
7
|
from dataclasses import asdict
|
|
8
8
|
from uuid import uuid4
|
|
9
9
|
|
|
10
|
-
from
|
|
10
|
+
from ksadk._mcp_compat import MCPServer
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
def _enabled(kind: str) -> bool:
|
|
@@ -25,8 +25,8 @@ def _subject() -> str:
|
|
|
25
25
|
return value
|
|
26
26
|
|
|
27
27
|
|
|
28
|
-
def create_server() ->
|
|
29
|
-
server =
|
|
28
|
+
def create_server() -> MCPServer:
|
|
29
|
+
server = MCPServer("KsADK Platform Resources")
|
|
30
30
|
|
|
31
31
|
if _enabled("memory-instance"):
|
|
32
32
|
from ksadk.memory.service import LongTermMemoryService, format_memory_entries
|
ksadk/resource_runtime/worker.py
CHANGED
|
@@ -14,7 +14,11 @@ import httpx
|
|
|
14
14
|
from pydantic import ConfigDict, Field, SecretStr, field_validator, model_validator
|
|
15
15
|
from requests.exceptions import RequestException
|
|
16
16
|
|
|
17
|
-
from ksadk.common.cloud_headers import
|
|
17
|
+
from ksadk.common.cloud_headers import (
|
|
18
|
+
DEFAULT_TRAFFIC_SOURCE,
|
|
19
|
+
resolve_component_env,
|
|
20
|
+
resolve_traffic_source,
|
|
21
|
+
)
|
|
18
22
|
from ksadk.knowledge_base.client import KnowledgeBaseClient
|
|
19
23
|
from ksadk.memory.adk.backends.sdk_ltm_backend import SdkLTMBackend
|
|
20
24
|
from ksadk.memory.models import MemorySearchRequest
|
|
@@ -72,12 +76,13 @@ class KnowledgeWorkerBinding(ExplicitWorkerBinding):
|
|
|
72
76
|
resource_kind: ClassVar[str] = "knowledge-base"
|
|
73
77
|
|
|
74
78
|
def create_service(
|
|
75
|
-
self, *, traffic_source: str = DEFAULT_TRAFFIC_SOURCE
|
|
79
|
+
self, *, traffic_source: str = DEFAULT_TRAFFIC_SOURCE, component_env: str = ""
|
|
76
80
|
) -> BoundKnowledgeService:
|
|
77
81
|
endpoint = urlsplit(self.endpoint)
|
|
78
82
|
client = KnowledgeBaseClient(
|
|
79
83
|
dataset_id=self.config.binding.resource.id,
|
|
80
84
|
traffic_source=traffic_source,
|
|
85
|
+
component_env=component_env,
|
|
81
86
|
region=self.config.binding.resource.region,
|
|
82
87
|
endpoint=endpoint.netloc,
|
|
83
88
|
scheme=endpoint.scheme,
|
|
@@ -92,12 +97,17 @@ class MemoryWorkerBinding(ExplicitWorkerBinding):
|
|
|
92
97
|
resource_kind: ClassVar[str] = "memory-instance"
|
|
93
98
|
|
|
94
99
|
def create_provider(
|
|
95
|
-
self,
|
|
100
|
+
self,
|
|
101
|
+
identity: InvocationIdentity,
|
|
102
|
+
*,
|
|
103
|
+
traffic_source: str = DEFAULT_TRAFFIC_SOURCE,
|
|
104
|
+
component_env: str = "",
|
|
96
105
|
) -> AicpMemoryProvider:
|
|
97
106
|
endpoint = urlsplit(self.endpoint)
|
|
98
107
|
backend = SdkLTMBackend(
|
|
99
108
|
index="bound-resource",
|
|
100
109
|
traffic_source=traffic_source,
|
|
110
|
+
component_env=component_env,
|
|
101
111
|
memory_collection_id=self.config.binding.resource.id,
|
|
102
112
|
namespace=self.config.binding.resource.id,
|
|
103
113
|
agent_id=identity.agent_id,
|
|
@@ -233,6 +243,7 @@ class WorkerInitialization(PluginContractModel):
|
|
|
233
243
|
# Resolve in the trusted parent and serialize on stdin; never inherit the
|
|
234
244
|
# parent's environment or mutate global process state in a shared host.
|
|
235
245
|
traffic_source: str = Field(default_factory=resolve_traffic_source)
|
|
246
|
+
component_env: str = Field(default_factory=resolve_component_env)
|
|
236
247
|
resource_snapshot: ResourceSnapshot
|
|
237
248
|
bindings: tuple[
|
|
238
249
|
KnowledgeWorkerBinding
|
|
@@ -363,9 +374,13 @@ def main() -> int:
|
|
|
363
374
|
else binding.create_provider(
|
|
364
375
|
scopes[binding.config.binding.id].identity,
|
|
365
376
|
traffic_source=initialization.traffic_source,
|
|
377
|
+
component_env=initialization.component_env,
|
|
366
378
|
)
|
|
367
379
|
if isinstance(binding, MemoryWorkerBinding)
|
|
368
|
-
else binding.create_service(
|
|
380
|
+
else binding.create_service(
|
|
381
|
+
traffic_source=initialization.traffic_source,
|
|
382
|
+
component_env=initialization.component_env,
|
|
383
|
+
)
|
|
369
384
|
if isinstance(binding, KnowledgeWorkerBinding)
|
|
370
385
|
else binding.create_service()
|
|
371
386
|
)
|