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
ksadk/agui/hosted.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
"""Prepare platform Actions and observe their admitted tasks; never execute a graph."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
from uuid import UUID
|
|
10
|
+
|
|
11
|
+
from fastapi import HTTPException
|
|
12
|
+
|
|
13
|
+
from ksadk.agui._agent_kernel import public_interrupt
|
|
14
|
+
from ksadk.agui._agent_resume import AguiRootNullUnsupported
|
|
15
|
+
from ksadk.agui._agent_types import _PendingInterrupt, _ThreadRun
|
|
16
|
+
from ksadk.interaction.form_values import normalize_form_answer
|
|
17
|
+
from ksadk.kernel.execution_grants import execution_grant_run_id
|
|
18
|
+
from ksadk.mcp_runtime.oauth.contract import CAPABILITY
|
|
19
|
+
from ksadk.runtime.adapter import RunHandle
|
|
20
|
+
|
|
21
|
+
PREPARE_PATH = "/agentengine/internal/agui/prepare"
|
|
22
|
+
ADMISSION_HEADER = "X-AgentEngine-AGUI-Admission"
|
|
23
|
+
VERSION_HEADER = "X-KsADK-AGUI-Preparation"
|
|
24
|
+
SCHEMA = "ksadk.agui.preparation/v1"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def request_digest(input):
|
|
28
|
+
return hashlib.sha256(
|
|
29
|
+
json.dumps(
|
|
30
|
+
input.model_dump(mode="json", by_alias=True),
|
|
31
|
+
sort_keys=True,
|
|
32
|
+
separators=(",", ":"),
|
|
33
|
+
ensure_ascii=False,
|
|
34
|
+
allow_nan=False,
|
|
35
|
+
).encode()
|
|
36
|
+
).hexdigest()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def enqueue_idempotency(run_id):
|
|
40
|
+
return "agui.enqueue:" + hashlib.sha256(run_id.encode()).hexdigest()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def resume_idempotency(run_id, interaction_id):
|
|
44
|
+
return (
|
|
45
|
+
"agui.resume:"
|
|
46
|
+
+ hashlib.sha256(
|
|
47
|
+
json.dumps(
|
|
48
|
+
[run_id, interaction_id],
|
|
49
|
+
separators=(",", ":"),
|
|
50
|
+
ensure_ascii=False,
|
|
51
|
+
).encode()
|
|
52
|
+
).hexdigest()
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def hosted_runtime():
|
|
57
|
+
from ksadk.kernel.bootstrap import get_agent_kernel_runtime
|
|
58
|
+
from ksadk.kernel.ingress import authority_mode
|
|
59
|
+
|
|
60
|
+
runtime = get_agent_kernel_runtime()
|
|
61
|
+
if runtime is None or authority_mode() != "hosted":
|
|
62
|
+
raise HTTPException(409, "Hosted AG-UI task admission is unavailable")
|
|
63
|
+
return runtime
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def interaction(runtime, session_id, interaction_id, tenant_id):
|
|
67
|
+
return await runtime.kernel_store.read_public_interaction(
|
|
68
|
+
interaction_id,
|
|
69
|
+
tenant_id=tenant_id,
|
|
70
|
+
agent_instance_id=runtime.config.agent_instance_id,
|
|
71
|
+
session_id=session_id,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def decision(entry, record):
|
|
76
|
+
from ksadk.agui._agent_helpers import approval_decision_for_audit
|
|
77
|
+
|
|
78
|
+
if entry.status == "cancelled":
|
|
79
|
+
return "cancel", None
|
|
80
|
+
if "payload" not in entry.model_fields_set:
|
|
81
|
+
raise HTTPException(422, "An explicit answer is required")
|
|
82
|
+
if entry.payload is None:
|
|
83
|
+
raise AguiRootNullUnsupported()
|
|
84
|
+
if record["kind"] == "approval":
|
|
85
|
+
action = (
|
|
86
|
+
"approve"
|
|
87
|
+
if approval_decision_for_audit(entry.status, entry.payload) == "approved"
|
|
88
|
+
else "reject"
|
|
89
|
+
)
|
|
90
|
+
else:
|
|
91
|
+
normalize_form_answer(record["request_schema"], entry.payload)
|
|
92
|
+
action = "submit"
|
|
93
|
+
return action, entry.payload
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
async def resume_records(runtime, input, tenant_id):
|
|
97
|
+
entries = input.resume or []
|
|
98
|
+
if len(entries) > 16:
|
|
99
|
+
raise HTTPException(422, "At most 16 answers may be submitted together")
|
|
100
|
+
if len({entry.interrupt_id for entry in entries}) != len(entries):
|
|
101
|
+
raise HTTPException(422, "Duplicate interruptId")
|
|
102
|
+
records = [
|
|
103
|
+
await interaction(runtime, input.thread_id, entry.interrupt_id, tenant_id)
|
|
104
|
+
for entry in entries
|
|
105
|
+
]
|
|
106
|
+
if not records or any(record is None for record in records):
|
|
107
|
+
raise HTTPException(404, "Interaction not found")
|
|
108
|
+
if len({record["run_id"] for record in records}) != 1:
|
|
109
|
+
raise HTTPException(422, "A resume batch must address one original run")
|
|
110
|
+
terminal = [
|
|
111
|
+
record for record in records if record["status"] in {"resolved", "cancelled", "expired"}
|
|
112
|
+
]
|
|
113
|
+
if any(r["status"] == "expired" for r in terminal):
|
|
114
|
+
raise HTTPException(409, "Interaction is already terminal")
|
|
115
|
+
# Validate the complete batch before admitting its first command.
|
|
116
|
+
for entry, record in zip(entries, records):
|
|
117
|
+
decision(entry, record)
|
|
118
|
+
return records, len(terminal) == len(records)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def matches_answer(command, *, agent, runtime, input, tenant_id, entry, record):
|
|
122
|
+
action, response = decision(entry, record)
|
|
123
|
+
return (
|
|
124
|
+
command.command_type == "submit_interaction"
|
|
125
|
+
and command.tenant_id == tenant_id
|
|
126
|
+
and command.agent_instance_id == runtime.config.agent_instance_id
|
|
127
|
+
and command.session_id == input.thread_id
|
|
128
|
+
and command.payload.get("invocation_identity") == agent._identity.to_payload()
|
|
129
|
+
and command.idempotency_key == resume_idempotency(input.run_id, entry.interrupt_id)
|
|
130
|
+
and command.payload.get("run_id") == record["run_id"]
|
|
131
|
+
and command.payload.get("interaction_id") == entry.interrupt_id
|
|
132
|
+
and command.payload.get("action") == action
|
|
133
|
+
and command.payload.get("response") == response
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
async def prepare(agent, input, *, tenant_id):
|
|
138
|
+
from ksadk.agui.config import AGUI_PROTOCOL_VERSION
|
|
139
|
+
|
|
140
|
+
if input.protocol_version not in {None, AGUI_PROTOCOL_VERSION, "1.0.0"}:
|
|
141
|
+
raise HTTPException(422, "Unsupported AG-UI protocol version")
|
|
142
|
+
runtime = hosted_runtime()
|
|
143
|
+
if not isinstance(tenant_id, str) or not tenant_id.strip():
|
|
144
|
+
raise HTTPException(401, "Verified platform account is required")
|
|
145
|
+
if agent._identity.is_empty or agent._session is None:
|
|
146
|
+
raise HTTPException(401, "Verified session identity is required")
|
|
147
|
+
actions = []
|
|
148
|
+
if input.resume:
|
|
149
|
+
records, readonly = await resume_records(runtime, input, tenant_id)
|
|
150
|
+
revisions = []
|
|
151
|
+
# Reuse the original admitted command on retries, including its revision.
|
|
152
|
+
# A worker may have consumed one answer while another submission failed.
|
|
153
|
+
# Validate the whole batch before Gateway submits any further answers.
|
|
154
|
+
for entry, record in zip(input.resume, records):
|
|
155
|
+
message = await runtime.kernel_store.load_by_idempotency(
|
|
156
|
+
input.thread_id, resume_idempotency(input.run_id, entry.interrupt_id)
|
|
157
|
+
)
|
|
158
|
+
if message is not None:
|
|
159
|
+
if not matches_answer(message.command, agent=agent, runtime=runtime,
|
|
160
|
+
input=input, tenant_id=tenant_id, entry=entry, record=record):
|
|
161
|
+
raise HTTPException(409, "Answer differs from the admitted submission")
|
|
162
|
+
revisions.append(message.command.payload["expected_revision"])
|
|
163
|
+
else:
|
|
164
|
+
if not readonly and record["status"] != "pending":
|
|
165
|
+
raise HTTPException(409, "Interaction was completed by another submission")
|
|
166
|
+
revisions.append(record["revision"])
|
|
167
|
+
if not readonly:
|
|
168
|
+
for entry, record, revision in zip(input.resume, records, revisions):
|
|
169
|
+
action, response = decision(entry, record)
|
|
170
|
+
actions.append(
|
|
171
|
+
{
|
|
172
|
+
"action": "SubmitInteraction",
|
|
173
|
+
"body": {
|
|
174
|
+
"RunId": record["run_id"],
|
|
175
|
+
"InteractionId": entry.interrupt_id,
|
|
176
|
+
"ExpectedRevision": revision,
|
|
177
|
+
"InteractionAction": action,
|
|
178
|
+
"Response": response,
|
|
179
|
+
"IdempotencyKey": resume_idempotency(input.run_id, entry.interrupt_id),
|
|
180
|
+
},
|
|
181
|
+
}
|
|
182
|
+
)
|
|
183
|
+
else:
|
|
184
|
+
forwarded = input.forwarded_props or {}
|
|
185
|
+
actions.append(
|
|
186
|
+
{
|
|
187
|
+
"action": "RunAgent",
|
|
188
|
+
"body": {
|
|
189
|
+
"InvocationId": input.run_id,
|
|
190
|
+
"Background": True,
|
|
191
|
+
"Stream": False,
|
|
192
|
+
"Messages": [
|
|
193
|
+
{
|
|
194
|
+
"role": "user",
|
|
195
|
+
"content": agent._json_safe(agent._latest_user_input(input)),
|
|
196
|
+
}
|
|
197
|
+
],
|
|
198
|
+
"Model": forwarded.get("model"),
|
|
199
|
+
"ModelMetadata": forwarded.get("modelMetadata"),
|
|
200
|
+
"ModelOptions": forwarded.get("modelOptions"),
|
|
201
|
+
"Metadata": {
|
|
202
|
+
"agentengine": {"tool_approval_mode": forwarded.get("toolApprovalMode")}
|
|
203
|
+
},
|
|
204
|
+
"Extensions": {
|
|
205
|
+
"mcp.authorization": CAPABILITY,
|
|
206
|
+
"ksadk.agui": {
|
|
207
|
+
"schema": "ksadk.agui/v1",
|
|
208
|
+
"request_digest": request_digest(input),
|
|
209
|
+
"options": agent._request_config(input)["ag-ui"],
|
|
210
|
+
},
|
|
211
|
+
},
|
|
212
|
+
},
|
|
213
|
+
}
|
|
214
|
+
)
|
|
215
|
+
for item in actions:
|
|
216
|
+
item["body"].update(AgentId=agent._session.agent_id, SessionId=input.thread_id)
|
|
217
|
+
return {
|
|
218
|
+
"schema": SCHEMA,
|
|
219
|
+
"agent_id": agent._session.agent_id,
|
|
220
|
+
"session_id": input.thread_id,
|
|
221
|
+
"tenant_id": tenant_id,
|
|
222
|
+
"request_digest": request_digest(input),
|
|
223
|
+
"actions": actions,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@dataclass
|
|
228
|
+
class KernelStream:
|
|
229
|
+
target_run: str
|
|
230
|
+
run: Any
|
|
231
|
+
events: Any
|
|
232
|
+
read_interaction: Any
|
|
233
|
+
readonly: bool = False
|
|
234
|
+
command_ids: set[str] = field(default_factory=set)
|
|
235
|
+
submissions: dict[str, str] = field(default_factory=dict)
|
|
236
|
+
unconsumed: set[str] = field(default_factory=set)
|
|
237
|
+
ready: list = field(default_factory=list)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
async def observe(agent, input, admission):
|
|
241
|
+
"""Authorize the read against persisted Server-admitted commands, not header claims."""
|
|
242
|
+
runtime = hosted_runtime()
|
|
243
|
+
if (
|
|
244
|
+
not isinstance(admission, dict)
|
|
245
|
+
or admission.get("schema") != SCHEMA
|
|
246
|
+
or admission.get("request_digest") != request_digest(input)
|
|
247
|
+
or not isinstance(admission.get("receipts"), list)
|
|
248
|
+
or not isinstance(admission.get("tenant_id"), str)
|
|
249
|
+
or not admission["tenant_id"].strip()
|
|
250
|
+
):
|
|
251
|
+
raise HTTPException(403, "Invalid AG-UI admission binding")
|
|
252
|
+
receipts = admission["receipts"]
|
|
253
|
+
if not receipts:
|
|
254
|
+
# No persisted command is available to bind this read-only replay.
|
|
255
|
+
# Revalidate the session owner before exposing any interaction/events.
|
|
256
|
+
if agent._identity.is_empty:
|
|
257
|
+
raise HTTPException(401, "Verified session identity is required")
|
|
258
|
+
await agent._authorize_session(input)
|
|
259
|
+
tenant_id = admission["tenant_id"]
|
|
260
|
+
records, readonly = (
|
|
261
|
+
await resume_records(runtime, input, tenant_id) if input.resume else ([], False)
|
|
262
|
+
)
|
|
263
|
+
if (
|
|
264
|
+
len(receipts) > 16
|
|
265
|
+
or (not receipts and not readonly)
|
|
266
|
+
or (receipts and len(receipts) != len(input.resume or [None]))
|
|
267
|
+
):
|
|
268
|
+
raise HTTPException(403, "Invalid AG-UI receipt count")
|
|
269
|
+
target = records[0]["run_id"] if records else None
|
|
270
|
+
command_ids, submissions = set(), {}
|
|
271
|
+
cursors = []
|
|
272
|
+
for index, receipt in enumerate(receipts):
|
|
273
|
+
if not isinstance(receipt, dict) or any(
|
|
274
|
+
not isinstance(receipt.get(key), str) or not receipt[key]
|
|
275
|
+
for key in ("MessageId", "CommandId")
|
|
276
|
+
):
|
|
277
|
+
raise HTTPException(403, "Invalid AG-UI receipt")
|
|
278
|
+
try:
|
|
279
|
+
UUID(receipt["MessageId"])
|
|
280
|
+
UUID(receipt["CommandId"])
|
|
281
|
+
except ValueError:
|
|
282
|
+
raise HTTPException(403, "Invalid AG-UI receipt") from None
|
|
283
|
+
message = await runtime.kernel_store.load_message(str(receipt.get("MessageId") or ""))
|
|
284
|
+
command = message.command if message is not None else None
|
|
285
|
+
if (
|
|
286
|
+
command is None
|
|
287
|
+
or str(command.command_id) != receipt.get("CommandId")
|
|
288
|
+
or command.agent_instance_id != runtime.config.agent_instance_id
|
|
289
|
+
# The Session storage partition may be "default"; it is not the
|
|
290
|
+
# platform tenant signed into the admitted command.
|
|
291
|
+
or command.tenant_id != tenant_id
|
|
292
|
+
or command.session_id != input.thread_id
|
|
293
|
+
or command.payload.get("invocation_identity") != agent._identity.to_payload()
|
|
294
|
+
):
|
|
295
|
+
raise HTTPException(403, "AG-UI command owner mismatch")
|
|
296
|
+
if input.resume:
|
|
297
|
+
entry = input.resume[index]
|
|
298
|
+
if not matches_answer(command, agent=agent, runtime=runtime, input=input,
|
|
299
|
+
tenant_id=tenant_id, entry=entry, record=records[index]):
|
|
300
|
+
raise HTTPException(403, "AG-UI answer binding mismatch")
|
|
301
|
+
submissions[str(command.command_id)] = entry.interrupt_id
|
|
302
|
+
else:
|
|
303
|
+
options = (command.payload.get("runtime_options") or {}).get("ag-ui") or {}
|
|
304
|
+
if (
|
|
305
|
+
command.command_type != "enqueue"
|
|
306
|
+
or command.source.kind != "agui"
|
|
307
|
+
or command.idempotency_key != enqueue_idempotency(input.run_id)
|
|
308
|
+
or options.get("request_digest") != request_digest(input)
|
|
309
|
+
):
|
|
310
|
+
raise HTTPException(403, "AG-UI request binding mismatch")
|
|
311
|
+
target = execution_grant_run_id(command)
|
|
312
|
+
command_ids.add(str(command.command_id))
|
|
313
|
+
cursors.append(message.accepted_seq)
|
|
314
|
+
if not target:
|
|
315
|
+
raise HTTPException(403, "AG-UI original run is missing")
|
|
316
|
+
run = _ThreadRun(RunHandle(run_id=target, session_id=input.thread_id, runtime_type="ksadk"))
|
|
317
|
+
for record in records:
|
|
318
|
+
if record["status"] == "pending":
|
|
319
|
+
interrupt = public_interrupt(record)
|
|
320
|
+
run.pending[interrupt.id] = _PendingInterrupt(interrupt, "", record["kind"])
|
|
321
|
+
|
|
322
|
+
async def events():
|
|
323
|
+
# Same admitted, read-only observer used by managed A2A. The immutable
|
|
324
|
+
# command and session owner above authorize this internal store read;
|
|
325
|
+
# all mutations still require the existing Server-issued permits.
|
|
326
|
+
subscribe = getattr(
|
|
327
|
+
runtime.session_events, "subscribe_recovering", runtime.session_events.subscribe
|
|
328
|
+
)
|
|
329
|
+
async for envelope in subscribe(input.thread_id, min(cursors, default=0)):
|
|
330
|
+
if envelope.session_id != input.thread_id:
|
|
331
|
+
raise PermissionError("AG-UI event session mismatch")
|
|
332
|
+
yield envelope.seq, envelope
|
|
333
|
+
|
|
334
|
+
return KernelStream(
|
|
335
|
+
target,
|
|
336
|
+
run,
|
|
337
|
+
events(),
|
|
338
|
+
lambda key: interaction(runtime, input.thread_id, key, tenant_id),
|
|
339
|
+
readonly=not receipts,
|
|
340
|
+
command_ids=command_ids,
|
|
341
|
+
submissions=submissions,
|
|
342
|
+
unconsumed={entry.interrupt_id for entry in input.resume or []} if receipts else set(),
|
|
343
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Request-scoped identity supplied by the Runtime's private HTTP carrier."""
|
|
2
|
+
|
|
3
|
+
from contextvars import ContextVar
|
|
4
|
+
|
|
5
|
+
from ksadk.runtime_context import PlatformIdentityContext
|
|
6
|
+
|
|
7
|
+
agui_request_identity: ContextVar[PlatformIdentityContext | None] = ContextVar(
|
|
8
|
+
"agui_request_identity", default=None
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
agui_admission: ContextVar[dict | None] = ContextVar("agui_admission", default=None)
|
ksadk/agui/routes.py
CHANGED
|
@@ -5,7 +5,8 @@ from __future__ import annotations
|
|
|
5
5
|
from importlib import import_module
|
|
6
6
|
from typing import Any, Callable, cast
|
|
7
7
|
|
|
8
|
-
from fastapi import FastAPI
|
|
8
|
+
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request
|
|
9
|
+
from fastapi.responses import JSONResponse
|
|
9
10
|
|
|
10
11
|
from ksadk.agui.agent import KsadkAGUIAgent
|
|
11
12
|
from ksadk.agui.config import AGUIConfig, require_agui_dependencies
|
|
@@ -42,7 +43,81 @@ def add_ksadk_agui_endpoint(
|
|
|
42
43
|
session_service_factory=session_service_factory,
|
|
43
44
|
local_kernel_provider=local_kernel_provider,
|
|
44
45
|
)
|
|
45
|
-
|
|
46
|
+
from ksadk.agui.hosted import ADMISSION_HEADER, PREPARE_PATH, VERSION_HEADER
|
|
47
|
+
from ksadk.agui.request_identity import agui_admission, agui_request_identity
|
|
48
|
+
from ksadk.server.invocation_identity import resolve_trusted_invocation_identity
|
|
49
|
+
|
|
50
|
+
async def identity_scope(
|
|
51
|
+
request: Request, identity=Depends(resolve_trusted_invocation_identity)
|
|
52
|
+
):
|
|
53
|
+
import json
|
|
54
|
+
|
|
55
|
+
raw = request.headers.get(ADMISSION_HEADER)
|
|
56
|
+
admission = None
|
|
57
|
+
if raw is not None:
|
|
58
|
+
try:
|
|
59
|
+
if len(raw) > 65536:
|
|
60
|
+
raise ValueError("oversized admission")
|
|
61
|
+
admission = json.loads(raw)
|
|
62
|
+
if not isinstance(admission, dict):
|
|
63
|
+
raise ValueError("invalid admission")
|
|
64
|
+
except ValueError:
|
|
65
|
+
raise HTTPException(403, "Invalid AG-UI admission") from None
|
|
66
|
+
token = agui_request_identity.set(identity)
|
|
67
|
+
receipt_token = agui_admission.set(admission)
|
|
68
|
+
try:
|
|
69
|
+
yield
|
|
70
|
+
finally:
|
|
71
|
+
agui_admission.reset(receipt_token)
|
|
72
|
+
agui_request_identity.reset(token)
|
|
73
|
+
|
|
74
|
+
router = APIRouter(dependencies=[Depends(identity_scope)])
|
|
75
|
+
_fastapi_endpoint_helper()(router, cast(Any, agent), path=config.path)
|
|
76
|
+
app.include_router(router)
|
|
77
|
+
|
|
78
|
+
@app.post(PREPARE_PATH, include_in_schema=False)
|
|
79
|
+
async def prepare_hosted_agui(
|
|
80
|
+
request: Request, identity=Depends(resolve_trusted_invocation_identity)
|
|
81
|
+
):
|
|
82
|
+
from ag_ui.core import RunAgentInput
|
|
83
|
+
from pydantic import ValidationError
|
|
84
|
+
|
|
85
|
+
from ksadk.agui._agent_resume import AguiRootNullUnsupported
|
|
86
|
+
from ksadk.agui.hosted import prepare
|
|
87
|
+
from ksadk.interaction.schema import InputValidationError
|
|
88
|
+
from ksadk.kernel.bootstrap import get_agent_kernel_runtime
|
|
89
|
+
from ksadk.kernel.ingress import authority_mode
|
|
90
|
+
|
|
91
|
+
# This read-only preparation never submits a command. Non-LangGraph
|
|
92
|
+
# runtimes keep their existing native AG-UI route.
|
|
93
|
+
if (
|
|
94
|
+
config.runtime_type != "langgraph"
|
|
95
|
+
or get_agent_kernel_runtime() is None
|
|
96
|
+
or authority_mode() != "hosted"
|
|
97
|
+
):
|
|
98
|
+
return JSONResponse({"detail": "Unsupported AG-UI runtime"}, status_code=404)
|
|
99
|
+
headers = {VERSION_HEADER: "1"}
|
|
100
|
+
try:
|
|
101
|
+
tenant_id = request.headers.get("x-auth-account-id", "").strip()
|
|
102
|
+
if identity.is_empty or not tenant_id:
|
|
103
|
+
raise HTTPException(401, "Verified platform account and identity are required")
|
|
104
|
+
input = RunAgentInput.model_validate(await request.json())
|
|
105
|
+
bound = agent.clone()
|
|
106
|
+
bound._identity = identity
|
|
107
|
+
await bound._authorize_session(input)
|
|
108
|
+
return JSONResponse(
|
|
109
|
+
await prepare(bound, input, tenant_id=tenant_id),
|
|
110
|
+
headers=headers,
|
|
111
|
+
)
|
|
112
|
+
except HTTPException as exc:
|
|
113
|
+
return JSONResponse(
|
|
114
|
+
{"detail": exc.detail}, status_code=exc.status_code, headers=headers
|
|
115
|
+
)
|
|
116
|
+
except (ValidationError, ValueError, InputValidationError, AguiRootNullUnsupported):
|
|
117
|
+
return JSONResponse(
|
|
118
|
+
{"detail": "Invalid AG-UI request or answer"}, status_code=422, headers=headers
|
|
119
|
+
)
|
|
120
|
+
|
|
46
121
|
return agent
|
|
47
122
|
|
|
48
123
|
|
ksadk/builders/code_builder.py
CHANGED
|
@@ -289,6 +289,7 @@ class CodeBuilder(BaseBuilder):
|
|
|
289
289
|
".md",
|
|
290
290
|
".html",
|
|
291
291
|
".js",
|
|
292
|
+
".mjs",
|
|
292
293
|
".css",
|
|
293
294
|
".svg",
|
|
294
295
|
".ico",
|
|
@@ -302,6 +303,10 @@ class CodeBuilder(BaseBuilder):
|
|
|
302
303
|
".ttf",
|
|
303
304
|
".map",
|
|
304
305
|
}
|
|
306
|
+
# The shared runtime selects the actual MCP HTTP backend and supports both
|
|
307
|
+
# SDK generations; deployment must not contradict a supported MCP 2.x pin.
|
|
308
|
+
TUNNEL_MCP_REQUIREMENT = "mcp>=1.26.0"
|
|
309
|
+
TUNNEL_WEBSOCKETS_REQUIREMENT = "websockets>=12.0,<16.0"
|
|
305
310
|
BUNDLED_KSADK_CORE_RUNTIME_REQUIREMENTS = (
|
|
306
311
|
"a2a-sdk[fastapi]==1.1.0",
|
|
307
312
|
# Shared Runtime imports the official validator even for non-UI Agents.
|
|
@@ -322,14 +327,16 @@ class CodeBuilder(BaseBuilder):
|
|
|
322
327
|
"kingsoftcloud-sdk-python>=1.5.8.94",
|
|
323
328
|
"cryptography>=44.0.0",
|
|
324
329
|
"rfc8785==0.1.4",
|
|
325
|
-
|
|
330
|
+
TUNNEL_WEBSOCKETS_REQUIREMENT,
|
|
326
331
|
"qrcode>=7.4.0",
|
|
327
332
|
"rfc8785>=0.1.4",
|
|
328
333
|
)
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
334
|
+
# 装进**用户项目**的 MCP runtime 依赖。
|
|
335
|
+
#
|
|
336
|
+
# 2026-11-18:`mcp>=1.1.0` → `>=2.3.0`,并移除 `langchain-mcp-adapters`
|
|
337
|
+
# (它 pin `mcp<2.0.0`,会把用户项目拉回 mcp 1.x,与 ksadk 自身要求的
|
|
338
|
+
# mcp>=2.3.0 冲突)。用户需要 LangChain 工具适配时自行安装。
|
|
339
|
+
BUNDLED_KSADK_MCP_RUNTIME_REQUIREMENTS = ("mcp>=2.3.0",)
|
|
333
340
|
BUNDLED_KSADK_POSTGRES_SESSION_REQUIREMENTS = (
|
|
334
341
|
"asyncpg>=0.30.0,<1.0.0",
|
|
335
342
|
"greenlet>=1.0.0",
|
|
@@ -661,6 +668,10 @@ class CodeBuilder(BaseBuilder):
|
|
|
661
668
|
requirements.extend(self.BUNDLED_KSADK_ATTACHMENT_OCR_RUNTIME_REQUIREMENTS)
|
|
662
669
|
if framework == "langgraph" or self._mcp_runtime_enabled():
|
|
663
670
|
requirements.extend(self.BUNDLED_KSADK_MCP_RUNTIME_REQUIREMENTS)
|
|
671
|
+
# Preserve the default for imported/re-exported factories. Explicit
|
|
672
|
+
# tunnel declarations also retain their protocol bounds after user pins.
|
|
673
|
+
if self._project_imports_any({"ksadk.Agent", "ksadk.agent"}):
|
|
674
|
+
requirements.append(self.TUNNEL_MCP_REQUIREMENT)
|
|
664
675
|
# A managed LangGraph runtime receives its Session store at deployment,
|
|
665
676
|
# including when the developer builds a standalone ZIP or image offline.
|
|
666
677
|
if framework == "langgraph" or self._postgres_session_runtime_enabled():
|
|
@@ -689,6 +700,13 @@ class CodeBuilder(BaseBuilder):
|
|
|
689
700
|
return True
|
|
690
701
|
return self._project_imports_any({"mcp", "langchain_mcp_adapters"})
|
|
691
702
|
|
|
703
|
+
def _tunnel_runtime_requirements(self) -> tuple[str, ...]:
|
|
704
|
+
from .project_imports import uses_tunnel
|
|
705
|
+
|
|
706
|
+
if any(uses_tunnel(path) for path in self._iter_project_py_files()):
|
|
707
|
+
return (self.TUNNEL_MCP_REQUIREMENT, self.TUNNEL_WEBSOCKETS_REQUIREMENT)
|
|
708
|
+
return ()
|
|
709
|
+
|
|
692
710
|
def _postgres_session_runtime_enabled(self) -> bool:
|
|
693
711
|
if self._env_flag_enabled("KSADK_BUILD_ENABLE_POSTGRES_SESSION"):
|
|
694
712
|
return True
|
|
@@ -756,24 +774,10 @@ class CodeBuilder(BaseBuilder):
|
|
|
756
774
|
return normalized.startswith(("postgres://", "postgresql://", "postgresql+asyncpg://"))
|
|
757
775
|
|
|
758
776
|
def _project_imports_any(self, module_names: set[str]) -> bool:
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
|
|
764
|
-
except (OSError, SyntaxError, UnicodeDecodeError):
|
|
765
|
-
continue
|
|
766
|
-
for node in ast.walk(tree):
|
|
767
|
-
if isinstance(node, ast.Import):
|
|
768
|
-
for alias in node.names:
|
|
769
|
-
root = alias.name.split(".", 1)[0]
|
|
770
|
-
if root in module_names:
|
|
771
|
-
return True
|
|
772
|
-
elif isinstance(node, ast.ImportFrom) and node.module:
|
|
773
|
-
root = node.module.split(".", 1)[0]
|
|
774
|
-
if root in module_names:
|
|
775
|
-
return True
|
|
776
|
-
return False
|
|
777
|
+
from .project_imports import imports_any
|
|
778
|
+
|
|
779
|
+
return any(imports_any(path, module_names) for path in self._iter_project_py_files()
|
|
780
|
+
if not self._should_skip_project_file(path))
|
|
777
781
|
|
|
778
782
|
def _iter_project_py_files(self):
|
|
779
783
|
for path in self._iter_project_files():
|
|
@@ -1055,9 +1059,11 @@ class CodeBuilder(BaseBuilder):
|
|
|
1055
1059
|
return requirements_path
|
|
1056
1060
|
|
|
1057
1061
|
def _build_requirements_list(self, detection_result) -> List[str]:
|
|
1062
|
+
tunnel_requirements = self._tunnel_runtime_requirements()
|
|
1058
1063
|
final_deps = merge_requirement_lists(
|
|
1059
1064
|
self._get_base_requirements(detection_result),
|
|
1060
1065
|
self._bundled_runtime_requirements(detection_result),
|
|
1066
|
+
tunnel_requirements,
|
|
1061
1067
|
)
|
|
1062
1068
|
|
|
1063
1069
|
extra_requirements: tuple[str, ...] = ()
|
|
@@ -1079,6 +1085,7 @@ class CodeBuilder(BaseBuilder):
|
|
|
1079
1085
|
for requirement in (
|
|
1080
1086
|
*code_requirements_for_framework(detection_result.type.value),
|
|
1081
1087
|
*extra_requirements,
|
|
1088
|
+
*tunnel_requirements,
|
|
1082
1089
|
):
|
|
1083
1090
|
if requirement not in final_deps:
|
|
1084
1091
|
final_deps.append(requirement)
|
|
@@ -417,11 +417,12 @@ CMD ["python", "entrypoint.py"]
|
|
|
417
417
|
framework = detection_result.type.value
|
|
418
418
|
base_deps += requirements_for_framework(framework)
|
|
419
419
|
|
|
420
|
+
bundled_builder = CodeBuilder(project_path or self.project_dir)
|
|
421
|
+
tunnel_requirements = bundled_builder._tunnel_runtime_requirements()
|
|
420
422
|
base_deps = merge_requirement_lists(
|
|
421
423
|
base_deps,
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
),
|
|
424
|
+
bundled_builder._bundled_runtime_requirements(detection_result),
|
|
425
|
+
tunnel_requirements,
|
|
425
426
|
)
|
|
426
427
|
|
|
427
428
|
# 合并用户 requirements.txt (如果存在)
|
|
@@ -431,7 +432,6 @@ CMD ["python", "entrypoint.py"]
|
|
|
431
432
|
if user_requirements.exists():
|
|
432
433
|
user_content = user_requirements.read_text()
|
|
433
434
|
parsed_user_requirements = parse_requirements_text(user_content)
|
|
434
|
-
bundled_builder = CodeBuilder(project_path or self.project_dir)
|
|
435
435
|
extra_requirements = bundled_builder._bundled_ksadk_extra_requirements(
|
|
436
436
|
parsed_user_requirements,
|
|
437
437
|
)
|
|
@@ -451,7 +451,7 @@ CMD ["python", "entrypoint.py"]
|
|
|
451
451
|
if LANGGRAPH_REQUIREMENT in requirements_for_framework(framework)
|
|
452
452
|
else ()
|
|
453
453
|
)
|
|
454
|
-
for requirement in (*pinned_framework, *extra_requirements):
|
|
454
|
+
for requirement in (*pinned_framework, *extra_requirements, *tunnel_requirements):
|
|
455
455
|
if requirement not in base_deps:
|
|
456
456
|
base_deps.append(requirement)
|
|
457
457
|
|