refactor: remove expired write_stdin compatibility

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-20 13:22:41 +08:00
1 parent 0f3cabb16d
commit 3d4200ff0d
4 files changed
+1 -218

No files matched your search

-110
View File
@@ -92,111 +92,6 @@ def _archive_offset(data: dict[str, Any]) -> int:
return 0
# TODO(0.3.2): Remove the write_stdin replay migration after 0.3.1.
def _migrate_legacy_exec_arguments(container: dict[str, Any]) -> bool:
raw_arguments = cast(object, container.get("arguments"))
encoded = isinstance(raw_arguments, str)
if encoded:
try:
decoded: object = json.loads(raw_arguments)
except json.JSONDecodeError:
return False
else:
decoded = raw_arguments
if not isinstance(decoded, dict):
return False
arguments = cast(dict[str, Any], decoded)
changed = False
if "chars" in arguments:
if "input" not in arguments:
arguments["input"] = arguments["chars"]
arguments.pop("chars")
changed = True
wait_key = (
"wait_timeout_ms"
if arguments.get("wait_for") or arguments.get("until_exit")
else "yield_time_ms"
)
if "timeout_ms" not in arguments and wait_key in arguments:
arguments["timeout_ms"] = arguments[wait_key]
for key in ("yield_time_ms", "wait_timeout_ms", "max_output_chars", "max_output_tokens"):
if key in arguments:
arguments.pop(key)
changed = True
if changed:
container["arguments"] = (
json.dumps(arguments, ensure_ascii=False, separators=(",", ":"))
if encoded
else arguments
)
return changed
def _migrate_legacy_exec_tool_call(value: object) -> bool:
if not isinstance(value, dict):
return False
tool_call = cast(dict[str, Any], value)
function_value = cast(object, tool_call.get("function"))
function = (
cast(dict[str, Any], function_value)
if isinstance(function_value, dict)
else tool_call
)
name = function.get("name")
if name not in {"write_stdin", "exec_session"}:
return False
changed = name == "write_stdin"
if changed:
function["name"] = "exec_session"
return _migrate_legacy_exec_arguments(function) or changed
def _migrate_legacy_exec_message(message: dict[str, Any]) -> bool:
changed = False
if message.get("name") == "write_stdin":
message["name"] = "exec_session"
changed = True
tool_calls = cast(object, message.get("tool_calls"))
if isinstance(tool_calls, list):
for tool_call in cast(list[object], tool_calls):
changed = _migrate_legacy_exec_tool_call(tool_call) or changed
return changed
def _migrate_legacy_exec_session_records(
messages: list[dict[str, Any]],
metadata: dict[str, Any],
) -> bool:
changed = False
for message in messages:
changed = _migrate_legacy_exec_message(message) or changed
checkpoint_value = cast(object, metadata.get(_RUNTIME_CHECKPOINT_KEY))
if not isinstance(checkpoint_value, dict):
return changed
checkpoint = cast(dict[str, Any], checkpoint_value)
assistant = cast(object, checkpoint.get("assistant_message"))
if isinstance(assistant, dict):
changed = _migrate_legacy_exec_message(cast(dict[str, Any], assistant)) or changed
pending = cast(object, checkpoint.get("pending_tool_calls"))
if isinstance(pending, list):
for tool_call in cast(list[object], pending):
changed = _migrate_legacy_exec_tool_call(tool_call) or changed
completed = cast(object, checkpoint.get("completed_tool_results"))
if isinstance(completed, list):
for result in cast(list[object], completed):
if isinstance(result, dict):
result_data = cast(dict[str, Any], result)
if result_data.get("name") == "write_stdin":
result_data["name"] = "exec_session"
changed = True
return changed
def _is_provider_state_record_line(line: str) -> bool:
"""Recognize the canonical private record without decoding its opaque payload."""
return _PROVIDER_STATE_RECORD_PREFIX_RE.match(line) is not None
@@ -1100,8 +995,6 @@ class JsonlSessionStore:
provider_state=provider_state,
)
self._overlay_runtime_checkpoint_unlocked(session, path)
if _migrate_legacy_exec_session_records(session.messages, session.metadata):
session.provider_state = None
return session
except _SESSION_DATA_ERRORS as e:
logger.warning("Failed to load session {}: {}", key, e)
@@ -1192,8 +1085,6 @@ class JsonlSessionStore:
provider_state=provider_state,
)
self._overlay_runtime_checkpoint_unlocked(session, path)
if _migrate_legacy_exec_session_records(session.messages, session.metadata):
session.provider_state = None
return session
except _SESSION_DATA_ERRORS as e:
logger.warning("Repair failed for session {}: {}", key, e)
@@ -1471,7 +1362,6 @@ class JsonlSessionStore:
continue
else:
messages.append(data)
_migrate_legacy_exec_session_records(messages, metadata)
return {
"key": stored_key or key,
"created_at": created_at,
-103
View File
@@ -1,4 +1,3 @@
import json
from unittest.mock import MagicMock
from nanobot.providers.base import ProviderConversationState
@@ -159,108 +158,6 @@ def test_runtime_checkpoint_does_not_rewrite_long_session(tmp_path) -> None:
assert restored.provider_state.payload == {"response_id": "private-response"}
def test_load_migrates_legacy_write_stdin_history(tmp_path) -> None:
manager = SessionManager(tmp_path)
session = manager.get_or_create("websocket:legacy-exec")
session.messages = [
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call-1",
"type": "function",
"function": {
"name": "write_stdin",
"arguments": json.dumps(
{
"session_id": "abc",
"chars": "yes\n",
"wait_for": "ready",
"wait_timeout_ms": 5000,
"yield_time_ms": 0,
"max_output_tokens": 1000,
}
),
},
}
],
},
{
"role": "tool",
"tool_call_id": "call-1",
"name": "write_stdin",
"content": "ready",
},
]
session.provider_state = ProviderConversationState(
kind="openai_responses",
provider="openai:test",
model="test-model",
version=1,
payload={"response_id": "legacy-response"},
)
manager.save(session)
restored = SessionManager(tmp_path).get_or_create(session.key)
function = restored.messages[0]["tool_calls"][0]["function"]
arguments = json.loads(function["arguments"])
assert function["name"] == "exec_session"
assert arguments == {
"session_id": "abc",
"wait_for": "ready",
"input": "yes\n",
"timeout_ms": 5000,
}
assert restored.messages[1]["name"] == "exec_session"
assert restored.provider_state is None
def test_load_migrates_legacy_write_stdin_runtime_checkpoint(tmp_path) -> None:
manager = SessionManager(tmp_path)
session = manager.get_or_create("websocket:legacy-checkpoint")
session.add_message("user", "continue")
manager.save(session)
legacy_call = {
"id": "call-1",
"type": "function",
"function": {
"name": "write_stdin",
"arguments": {"session_id": "abc", "chars": "", "yield_time_ms": 1000},
},
}
session.metadata["runtime_checkpoint"] = {
"phase": "awaiting_tools",
"assistant_message": {
"role": "assistant",
"content": "",
"tool_calls": [legacy_call],
},
"completed_tool_results": [],
"pending_tool_calls": [legacy_call],
}
session.provider_state = ProviderConversationState(
kind="openai_responses",
provider="openai:test",
model="test-model",
version=1,
payload={"response_id": "legacy-response"},
)
manager.save_runtime_checkpoint(session)
restored = SessionManager(tmp_path).get_or_create(session.key)
checkpoint = restored.metadata["runtime_checkpoint"]
pending_function = checkpoint["pending_tool_calls"][0]["function"]
assert pending_function == {
"name": "exec_session",
"arguments": {"session_id": "abc", "input": "", "timeout_ms": 1000},
}
assert checkpoint["assistant_message"]["tool_calls"][0]["function"] == pending_function
assert restored.provider_state is None
def test_completed_session_supersedes_stale_checkpoint(tmp_path) -> None:
manager = SessionManager(tmp_path)
session = manager.get_or_create("websocket:completed")
@@ -240,9 +240,7 @@ function activityLabel(
return statusCopy(status, "Starting long task", "Started long task", "Could not start long task");
case "update_goal":
return statusCopy(status, "Updating long task", "Updated long task", "Could not update long task");
// TODO(0.3.2): Remove write_stdin display compatibility after 0.3.1.
case "exec_session":
case "write_stdin":
return statusCopy(status, "Continuing command", "Continued command", "Could not continue command");
case "list_exec_sessions":
return statusCopy(status, "Checking running commands", "Checked running commands", "Could not check running commands");
@@ -293,9 +291,7 @@ function activityDetail(items: GenericToolRunItem[], family: ToolFamily, name: s
return safeText(fieldValue(trace, "ui_summary"));
case "update_goal":
return safeText(fieldValue(trace, "action"));
// TODO(0.3.2): Remove write_stdin display compatibility after 0.3.1.
case "exec_session":
case "write_stdin":
return compactIdentifier(fieldValue(trace, "session_id"));
case "screenshot":
case "capture_screenshot":
+1 -1
View File
@@ -30,7 +30,7 @@ describe("generic tool activity semantics", () => {
['create_goal({"objective":"private objective","ui_summary":"Benchmark memory"})', "Started long task", "Benchmark memory"],
['update_goal({"action":"complete","recap":"private recap"})', "Updated long task", "complete"],
['exec_session({"session_id":"session-1234567890-secret","until_exit":true})', "Continued command", "session…ecret"],
['write_stdin({"session_id":"legacy-1234567890-secret","chars":"private input"})', "Continued command", "legacy-…ecret"],
['write_stdin({"session_id":"legacy-1234567890-secret","chars":"private input"})', "Completed Write stdin", ""],
['list_exec_sessions({})', "Checked running commands", ""],
['screenshot({"path":"artifacts/home.png"})', "Captured screenshot", ""],
['third_party_sync({"token":"secret","payload":"private payload"})', "Completed Third party sync", ""],