feat(runtime): add user-controlled turn recovery
This commit is contained in:
1 parent
ffa58aa5ef
commit
12029f8812
60 files changed
+4027
-169
No files matched your search
@@ -69,6 +69,7 @@ def build_gateway_services(
|
||||
mcp_runtime_status: Callable[[], Mapping[str, str]] | None = None,
|
||||
mcp_reload: Callable[[], Awaitable[dict[str, Any]]] | None = None,
|
||||
skill_state_action: Callable[[set[str]], None] | None = None,
|
||||
recovery_action: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] | None = None,
|
||||
logger: Any = default_logger,
|
||||
) -> GatewayServices:
|
||||
settings = WebUISettingsServices.create(
|
||||
@@ -131,6 +132,7 @@ def build_gateway_services(
|
||||
mcp_runtime_status=mcp_runtime_status,
|
||||
mcp_reload=mcp_reload,
|
||||
skill_state_action=skill_state_action,
|
||||
recovery_action=recovery_action,
|
||||
log=logger,
|
||||
)
|
||||
return GatewayServices(
|
||||
|
||||
@@ -31,8 +31,9 @@ from nanobot.session.manager import (
|
||||
_metadata_title, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
from nanobot.session.model_selection import model_preset_from_metadata
|
||||
from nanobot.session.recovery import recovery_state_from_metadata
|
||||
|
||||
_INDEX_VERSION = 7
|
||||
_INDEX_VERSION = 8
|
||||
_INDEX_FILENAME = ".webui_session_index.json"
|
||||
_MODEL_PRESET_FIELD = "model_preset"
|
||||
_ROW_SOURCE_FIELD = "_source"
|
||||
@@ -245,6 +246,7 @@ def _public_row(sessions_dir: Path, webui_dir: Path, row: dict[str, Any]) -> dic
|
||||
"title": row.get("title", ""),
|
||||
"preview": row.get("preview", ""),
|
||||
_MODEL_PRESET_FIELD: row.get(_MODEL_PRESET_FIELD),
|
||||
"recovery_state": row.get("recovery_state"),
|
||||
_WORKSPACE_SCOPE_PRESENT_FIELD: row.get(_WORKSPACE_SCOPE_PRESENT_FIELD, False),
|
||||
_WORKSPACE_SCOPE_VALUE_FIELD: row.get(_WORKSPACE_SCOPE_VALUE_FIELD),
|
||||
"path": str(path),
|
||||
@@ -485,6 +487,7 @@ def _indexed_row_for_session(session: Session, path: Path, webui_dir: Path) -> d
|
||||
"title": _metadata_title(session.metadata),
|
||||
"preview": _preview_from_messages(session.messages),
|
||||
_MODEL_PRESET_FIELD: model_preset_from_metadata(session.metadata),
|
||||
"recovery_state": recovery_state_from_metadata(session.metadata),
|
||||
**_indexed_workspace_scope_fields(session.metadata),
|
||||
_ROW_SOURCE_FIELD: _SESSION_SOURCE,
|
||||
"file": path.name,
|
||||
@@ -601,6 +604,7 @@ def _scan_transcript_row(
|
||||
"title": "",
|
||||
"preview": preview or fallback_preview,
|
||||
_MODEL_PRESET_FIELD: None,
|
||||
"recovery_state": None,
|
||||
**_indexed_workspace_scope_fields({}),
|
||||
_ROW_SOURCE_FIELD: _TRANSCRIPT_SOURCE,
|
||||
"file": stem,
|
||||
@@ -687,6 +691,7 @@ def _scan_session_row(
|
||||
"title": _metadata_title(metadata),
|
||||
"preview": preview or fallback_preview,
|
||||
_MODEL_PRESET_FIELD: model_preset_from_metadata(metadata),
|
||||
"recovery_state": recovery_state_from_metadata(metadata),
|
||||
**_indexed_workspace_scope_fields(metadata),
|
||||
_ROW_SOURCE_FIELD: _SESSION_SOURCE,
|
||||
"file": path.name,
|
||||
|
||||
@@ -2541,6 +2541,19 @@ def has_pending_tool_calls(
|
||||
return False
|
||||
|
||||
|
||||
def has_unfinished_transcript_tail(session_key: str) -> bool:
|
||||
"""Return whether the active transcript ends in an unfinished turn.
|
||||
|
||||
Recovery runs at gateway startup and only needs the newest, still-active
|
||||
turn. Completed turns are rotated into immutable segment files, so reading
|
||||
every historical segment here would make restart cost grow with the full
|
||||
conversation history.
|
||||
"""
|
||||
return has_pending_tool_calls(
|
||||
_read_transcript_file(webui_transcript_path(session_key))
|
||||
)
|
||||
|
||||
|
||||
def completed_turn_ids(lines: list[dict[str, Any]]) -> list[str]:
|
||||
"""Return stable identities for turns with an explicitly persisted completion."""
|
||||
completed: list[str] = []
|
||||
|
||||
@@ -29,6 +29,7 @@ from nanobot.cron.session_turns import is_bound_cron_job
|
||||
from nanobot.cron.types import CronJob, CronSchedule
|
||||
from nanobot.security.workspace_access import WorkspaceScope
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import RecoveryActionError
|
||||
from nanobot.session.session_handles import (
|
||||
SessionHandleResolver,
|
||||
)
|
||||
@@ -145,6 +146,8 @@ _WEBUI_MUTATION_PATHS = {
|
||||
"skill.delete": "/api/webui/skills/delete",
|
||||
"sidebar.update": "/api/webui/sidebar-state/update",
|
||||
"workspace.pick_folder": "/api/workspaces/pick-folder",
|
||||
"recovery.continue": "/api/webui/recovery/continue",
|
||||
"recovery.dismiss": "/api/webui/recovery/dismiss",
|
||||
"settings.agent.update": "/api/settings/update",
|
||||
"settings.model_configuration.create": "/api/settings/model-configurations/create",
|
||||
"settings.model_configuration.update": "/api/settings/model-configurations/update",
|
||||
@@ -323,6 +326,9 @@ class GatewayHTTPHandler:
|
||||
mcp_runtime_status: Callable[[], Mapping[str, str]] | None = None,
|
||||
mcp_reload: Callable[[], Awaitable[dict[str, Any]]] | None = None,
|
||||
skill_state_action: Callable[[set[str]], None] | None = None,
|
||||
recovery_action: (
|
||||
Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] | None
|
||||
) = None,
|
||||
log: Any = logger,
|
||||
) -> None:
|
||||
self.config = config
|
||||
@@ -340,6 +346,7 @@ class GatewayHTTPHandler:
|
||||
disabled_skills if disabled_skills is not None else set()
|
||||
)
|
||||
self.skill_state_action = skill_state_action
|
||||
self.recovery_action = recovery_action
|
||||
self._skill_install_lock = asyncio.Lock()
|
||||
self._folder_picker_lock = asyncio.Lock()
|
||||
self.cron_service = cron_service
|
||||
@@ -454,6 +461,8 @@ class GatewayHTTPHandler:
|
||||
return True
|
||||
if re.match(r"^/api/webui/automations/(enable|disable|delete|run|update)$", path):
|
||||
return True
|
||||
if path in {"/api/webui/recovery/continue", "/api/webui/recovery/dismiss"}:
|
||||
return True
|
||||
return path in {
|
||||
"/api/webui/skills/install",
|
||||
"/api/webui/skills/update",
|
||||
@@ -507,6 +516,11 @@ class GatewayHTTPHandler:
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
# Recovery routes
|
||||
response = await self._dispatch_recovery_route(request, got)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
# Session routes
|
||||
response = await self._dispatch_session_routes(request, got)
|
||||
if response is not None:
|
||||
@@ -700,6 +714,27 @@ class GatewayHTTPHandler:
|
||||
|
||||
return None
|
||||
|
||||
async def _dispatch_recovery_route(
|
||||
self,
|
||||
request: WsRequest,
|
||||
path: str,
|
||||
) -> Response | None:
|
||||
match = re.fullmatch(r"/api/webui/recovery/(continue|dismiss)", path)
|
||||
if match is None:
|
||||
return None
|
||||
if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False):
|
||||
return _http_error(405, "WebUI recovery actions require an authenticated WebSocket")
|
||||
if self.recovery_action is None:
|
||||
return _http_error(503, "WebUI recovery is unavailable")
|
||||
payload = _mutation_payload(request)
|
||||
if payload is None:
|
||||
return _http_error(400, "invalid recovery payload")
|
||||
try:
|
||||
result = await self.recovery_action(match.group(1), payload)
|
||||
except RecoveryActionError as exc:
|
||||
return _http_error(exc.status, str(exc))
|
||||
return _http_json_response(result)
|
||||
|
||||
async def _handle_session_context_get(self, request: WsRequest, key: str) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
@@ -746,6 +781,10 @@ class GatewayHTTPHandler:
|
||||
for k, v in s.items()
|
||||
if k != "path" and k not in WEBUI_SESSION_INDEX_INTERNAL_FIELDS
|
||||
}
|
||||
# Keep the additive recovery field absent for ordinary sessions so
|
||||
# older clients and compact list responses stay unchanged.
|
||||
if row.get("recovery_state") is None:
|
||||
row.pop("recovery_state", None)
|
||||
chat_id = key.split(":", 1)[1]
|
||||
started_at = websocket_turn_wall_started_at(chat_id)
|
||||
if started_at is not None:
|
||||
|
||||
Reference in new issue
Block a user