Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions ksadk/cli/cmd_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@

from ksadk.cli.error_utils import ensure_json_output_supported, print_exception
from ksadk.cli.local_runtime import reexec_with_project_venv_if_needed
from ksadk.cli.runtime_bootstrap import create_runtime_web_app
from ksadk.cli.runtime_bootstrap import (
create_local_runtime_composition,
create_runtime_web_app,
)
from ksadk.cli.ui import (
print_error,
print_info,
Expand Down Expand Up @@ -207,11 +210,25 @@ def _run_custom(
print_warn(f"Tracing 初始化失败: {e}")

if interactive:
del show_thinking, no_stream, no_alt_screen
print_error(
"RuntimeAdapter TUI 尚未接通;请使用 `ksadk web` 或不带 --interactive 启动"
from ksadk.tui.runtime_runner import CanonicalRuntimeRunner, run_runtime_tui

try:
composition = create_local_runtime_composition(result, agent_path)
runner = CanonicalRuntimeRunner(
composition,
agent_id=str(result.name),
)
except Exception as e:
print_exception("RuntimeAdapter 初始化失败", e)
raise SystemExit(1)
run_runtime_tui(
runner,
show_thinking=show_thinking,
no_stream=no_stream,
project_dir=str(agent_path),
no_alt_screen=no_alt_screen,
)
raise SystemExit(2)
return

try:
runtime_app = create_runtime_web_app(result, agent_path, auto_tracing=not no_trace)
Expand Down
48 changes: 39 additions & 9 deletions ksadk/cli/runtime_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -33,10 +34,20 @@ def _managed_a2a_card() -> Any:
return build_managed_a2a_card_if_configured()


def create_runtime_web_app(
detection: Any, agent_path: Path, *, auto_tracing: bool = True,
) -> FastAPI:
"""Compose one detected project around the canonical RuntimeExecutor."""
@dataclass
class LocalRuntimeComposition:
"""Framework-neutral Runtime objects shared by local CLI frontends."""

launch_context: RuntimeLaunchContext
executor: RuntimeExecutor
managed_a2a: Any = None
managed_a2a_adapter: Any = None


def create_local_runtime_composition(
detection: Any, agent_path: Path,
) -> LocalRuntimeComposition:
"""Build the canonical Runtime boundary without creating an HTTP app."""

config = dict(getattr(detection, "raw_config", None) or {})
managed_runtime = os.getenv("AGENTENGINE_MANAGED_RUNTIME") == "1"
Expand Down Expand Up @@ -82,18 +93,37 @@ def create_runtime_web_app(
):
executor.configure_managed_a2a(managed_a2a)
adapter = executor.create_adapter(context)
return LocalRuntimeComposition(
launch_context=context,
executor=executor,
managed_a2a=managed_a2a,
managed_a2a_adapter=adapter,
)


def create_runtime_web_app(
detection: Any, agent_path: Path, *, auto_tracing: bool = True,
) -> FastAPI:
"""Compose one detected project around the canonical RuntimeExecutor."""

composition = create_local_runtime_composition(detection, agent_path)
managed_runtime = os.getenv("AGENTENGINE_MANAGED_RUNTIME") == "1"
return create_runtime_app(
RuntimeAppConfig(
runtime_executor=executor,
launch_context=context,
runtime_executor=composition.executor,
launch_context=composition.launch_context,
agui=agui_config_for_detection(detection),
a2a=managed_a2a,
a2a_runtime_adapter=adapter,
a2a=composition.managed_a2a,
a2a_runtime_adapter=composition.managed_a2a_adapter,
local_mcp_oauth=not managed_runtime,
auto_tracing=auto_tracing,
),
configure_runtime_app,
)


__all__ = ["create_runtime_web_app"]
__all__ = [
"LocalRuntimeComposition",
"create_local_runtime_composition",
"create_runtime_web_app",
]
58 changes: 52 additions & 6 deletions ksadk/runtime/conversation_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,14 +557,43 @@ def _validate_event_scope(
@transient_skill_connection
async def iter_runtime_conversation_semantic_events(
**kwargs: Any,
) -> AsyncIterator[dict[str, Any]]:
"""Own the canonical source and its semantic projector for one turn."""

include_control_events = bool(kwargs.pop("_include_control_events", False))
execution_context: dict[str, str] = {}
source_events = iter_runtime_conversation_events(
**kwargs, _execution_context=execution_context
)
projector = _project_runtime_conversation_semantic_events(
source_events,
execution_context=execution_context,
include_control_events=include_control_events,
**kwargs,
)
try:
async for event in projector:
yield event
finally:
try:
await projector.aclose()
finally:
await source_events.aclose()


async def _project_runtime_conversation_semantic_events(
source_events: AsyncIterator[RuntimeEvent],
*,
execution_context: dict[str, str],
include_control_events: bool = False,
**kwargs: Any,
) -> AsyncIterator[dict[str, Any]]:
"""Project canonical RuntimeEvents into the transport-neutral serializer input."""

reducer = StreamReducer()
emitted_text = ""
reasoning_parts: dict[tuple[str, str, str], str] = {}
approval: dict[str, Any] | None = None
execution_context: dict[str, str] = {}
# (scope_id, call_id) → tool_name:不同子运行可复用原生 call_id。
# (ToolResultContent 不带 name,前端靠 name 关联 call/result)。
_tool_name_by_call_id: dict[tuple[str, str], str] = {}
Expand All @@ -573,9 +602,7 @@ async def iter_runtime_conversation_semantic_events(
# ItemCompleted.snapshot 都带(需去重);LangGraph/ADK 的 ItemStarted.initial=None,
# ToolCallContent 只出现在 ItemCompleted.snapshot(需在 Completed 补发,不能跳过)。
_emitted_tool_call_ids: set[tuple[str, str]] = set()
async for event in iter_runtime_conversation_events(
**kwargs, _execution_context=execution_context
):
async for event in source_events:
patch = reducer.apply(event)
if not patch.applied:
continue
Expand All @@ -602,11 +629,14 @@ async def iter_runtime_conversation_semantic_events(
}
emitted_text = current
if isinstance(event, RunStarted):
yield {
started = {
"type": "started",
"session_id": execution_context.get("session_id", ""),
"metadata": dict(event.source.metadata),
}
if include_control_events:
started["run_id"] = event.run_id
yield started
elif isinstance(event, (ContextCompactionStarted, ContextCompactionCompleted)):
semantic = {"type": "compaction", "trigger": event.trigger}
# Distinguish start vs done for SSE projection (response.compaction.start/done)
Expand Down Expand Up @@ -677,6 +707,15 @@ async def iter_runtime_conversation_semantic_events(
"run_id": part.call_id,
}
elif isinstance(event, InteractionRequested):
if include_control_events:
yield {
"type": "interaction",
"run_id": event.run_id,
"session_id": execution_context.get("session_id", ""),
"interaction_id": event.interaction_id,
"interaction_kind": event.interaction_kind,
"request": event.request.model_dump(mode="json", by_alias=True),
}
if event.interaction_kind == "approval" and event.request.request_type == "approval":
detail = event.request.detail
approval = dict(detail) if isinstance(detail, Mapping) else {}
Expand All @@ -687,7 +726,7 @@ async def iter_runtime_conversation_semantic_events(
approval.setdefault("call_id", event.request.call_id)
approval.setdefault("kind", event.request.kind)
elif isinstance(event, RunInterrupted):
yield {
interrupted = {
"type": "interrupt",
"interrupt_info": approval
or {
Expand All @@ -697,6 +736,13 @@ async def iter_runtime_conversation_semantic_events(
},
"session_id": execution_context.get("session_id", ""),
}
if include_control_events:
interrupted.update(
run_id=event.run_id,
interaction_id=event.interaction_id,
continuation_id=event.continuation_id,
)
yield interrupted
elif isinstance(event, RunFailed):
usage = execution_context.get("terminal_usage") or reducer.usage_snapshot()
metrics = event.source.metadata.get("metrics")
Expand Down
36 changes: 26 additions & 10 deletions ksadk/tui/loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,10 @@ async def render_stream(
chunk_type = str(chunk.get("type") or "text")

if chunk_type == "thinking":
delta = chunk.get("delta") or ""
if delta:
full_thinking += str(delta)
delta = str(chunk.get("delta") or "")
replace = bool(chunk.get("replace") or chunk.get("operation") == "replace")
if delta or replace:
full_thinking = delta if replace else full_thinking + delta
saw_content = True
await r.on_thinking(full_thinking)
continue
Expand Down Expand Up @@ -252,8 +253,9 @@ async def render_stream(
await r.on_usage(chunk_usage)
saw_content = True
continue
if delta:
full_response += delta
replace = bool(chunk.get("replace") or chunk.get("operation") == "replace")
if delta or replace:
full_response = delta if replace else full_response + delta
saw_content = True
await r.on_text(full_response)
except InterruptPending:
Expand Down Expand Up @@ -354,10 +356,12 @@ def __init__(
assistant_entry: TranscriptEntry | None = None,
*,
show_thinking: bool = False,
stream_updates: bool = True,
) -> None:
self.loop = loop
self.assistant_entry = assistant_entry
self.show_thinking = show_thinking
self.stream_updates = stream_updates
self._tool_entries: list[TranscriptEntry] = []
self._ordered_entries: list[TranscriptEntry] = []
self._tool_entries_by_key: dict[str, TranscriptEntry] = {}
Expand Down Expand Up @@ -400,7 +404,8 @@ async def on_text(self, full_text: str) -> None:
self._ordered_entries.append(self._active_text_entry)
self._active_text_entry.content += delta
self._last_full_text = full_text
self.loop._set_streaming(self._compose_streaming())
if self.stream_updates:
self.loop._set_streaming(self._compose_streaming())

async def on_thinking(self, full_thinking: str) -> None:
if self.loop is not None and self.assistant_entry is not None:
Expand Down Expand Up @@ -432,7 +437,8 @@ async def on_tool_call(
entry = existing
entry._tool_call_id = merge_key # type: ignore[attr-defined]
# tool 行立即进动态区(就地在文本流里显示),不中途落定避免时序错乱。
self.loop._set_streaming(self._compose_streaming())
if self.stream_updates:
self.loop._set_streaming(self._compose_streaming())

async def on_usage(self, usage: dict) -> None:
if self.loop is not None and self.assistant_entry is not None:
Expand Down Expand Up @@ -491,11 +497,13 @@ def __init__(
runner,
*,
show_thinking: bool = False,
no_stream: bool = False,
project_dir: str = ".",
no_alt_screen: bool = False,
) -> None:
self.runner = runner
self.show_thinking = show_thinking
self.no_stream = no_stream
self.project_dir = Path(project_dir).resolve()
self._no_alt_screen = no_alt_screen
self.session_id = str(getattr(runner, "session_id", None) or uuid.uuid4().hex[:8])
Expand Down Expand Up @@ -992,6 +1000,7 @@ async def _run_turn_async(
self,
assistant_entry,
show_thinking=self.show_thinking,
stream_updates=not self.no_stream,
)
try:
response, usage = await render_stream(self.runner, input_data, renderer=renderer)
Expand Down Expand Up @@ -1911,15 +1920,22 @@ def _clean(match: "re.Match[str]") -> str:


def run_tui(
runner, *, show_thinking: bool = False, project_dir: str = ".", no_alt_screen: bool = False
runner,
*,
show_thinking: bool = False,
no_stream: bool = False,
project_dir: str = ".",
no_alt_screen: bool = False,
) -> None:
"""TUI 入口:被 cmd_invoke._invoke_tui / cmd_run._run_custom 调用。
"""Legacy Runner/RemoteRunner TUI 入口。

``no_alt_screen`` 作为兼容参数保留;TUI 现在默认使用 Codex-style inline viewport。
本地 RuntimeAdapter 项目使用 ``ksadk.tui.runtime_runner.run_runtime_tui``。
``no_alt_screen`` 作为兼容参数保留;TUI 默认使用 inline viewport。
"""
InteractionLoop(
runner,
show_thinking=show_thinking,
no_stream=no_stream,
project_dir=project_dir,
no_alt_screen=no_alt_screen,
).run()
Loading
Loading