feat: checkpoint device agent runtime milestones

This commit is contained in:
2026-07-06 17:24:03 +08:00
parent 2d4251e98e
commit 5658735bca
153 changed files with 8060 additions and 65 deletions
+13
View File
@@ -0,0 +1,13 @@
"""Per-task world-state tracking."""
from world.config import WorldConfig, load_config
from world.model import WorldModel
from world.models import WorldEvent, WorldState
__all__ = [
"WorldConfig",
"WorldEvent",
"WorldModel",
"WorldState",
"load_config",
]
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
import os
from collections.abc import Mapping
from dataclasses import dataclass
DEFAULT_HISTORY_SIZE = 10
ENABLED_ENV = "WORLD_RUNTIME_ENABLED"
HISTORY_SIZE_ENV = "WORLD_HISTORY_SIZE"
@dataclass(frozen=True)
class WorldConfig:
enabled: bool = True
history_size: int = DEFAULT_HISTORY_SIZE
def load_config(env: Mapping[str, str] | None = None) -> WorldConfig:
values = env or os.environ
return WorldConfig(
enabled=_parse_bool(values.get(ENABLED_ENV), default=True),
history_size=_parse_history_size(values.get(HISTORY_SIZE_ENV)),
)
def _parse_bool(value: str | None, *, default: bool) -> bool:
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on", "enabled"}
def _parse_history_size(value: str | None) -> int:
if value is None:
return DEFAULT_HISTORY_SIZE
try:
size = int(value)
except ValueError:
return DEFAULT_HISTORY_SIZE
return size if size > 0 else DEFAULT_HISTORY_SIZE
+111
View File
@@ -0,0 +1,111 @@
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from core.models import Scene
from semantic.models import SemanticScene
from world.config import WorldConfig, load_config
from world.models import WorldEvent, WorldState
if TYPE_CHECKING:
from runtime.executor import StepResult
from runtime.planner import PlannedStep
logger = logging.getLogger(__name__)
class WorldModel:
def __init__(self, *, config: WorldConfig | None = None) -> None:
self.config = config or load_config()
self._states: dict[str, WorldState] = {}
self._current_task_id: str | None = None
self._fallback_state = self._new_state()
@property
def state(self) -> WorldState:
if self._current_task_id is None:
return self._fallback_state
return self._states[self._current_task_id]
def start_task(self, task_id: str) -> WorldState:
self._current_task_id = task_id
return self._states.setdefault(task_id, self._new_state())
def state_for(self, task_id: str) -> WorldState | None:
return self._states.get(task_id)
def observe(
self,
scene: Scene,
semantic_scene: SemanticScene | None,
step: "PlannedStep",
result: "StepResult",
) -> None:
try:
self._update_page(semantic_scene)
self._update_app(step, result)
self._update_variables(step)
self._append_history(scene, semantic_scene, step, result)
except Exception as exc:
logger.info("world model update skipped after unexpected error: %s", exc)
def _new_state(self) -> WorldState:
return WorldState.with_history_bound(self.config.history_size)
def _update_page(self, semantic_scene: SemanticScene | None) -> None:
if semantic_scene is None:
return
page = semantic_scene.page.strip()
if page:
self.state.current_page = page
def _update_app(self, step: "PlannedStep", result: "StepResult") -> None:
if not getattr(result, "success", False):
return
action = getattr(step, "action", None)
if action not in {"launch_app", "terminate_app"}:
return
args = getattr(step, "args", {})
if not isinstance(args, dict):
logger.info("world model skipped app update: step args are not a mapping")
return
app_id = _app_identifier(args)
if not app_id:
logger.info("world model skipped app update: missing app identifier")
return
if action == "launch_app":
self.state.current_app = app_id
return
self.state.current_app = None
def _update_variables(self, step: "PlannedStep") -> None:
args = getattr(step, "args", {})
if not isinstance(args, dict) or "remember" not in args:
return
remember = args["remember"]
if not isinstance(remember, dict):
logger.info("world model skipped remember update: value is not a mapping")
return
self.state.variables.update(remember)
def _append_history(
self,
scene: Scene,
semantic_scene: SemanticScene | None,
step: "PlannedStep",
result: "StepResult",
) -> None:
self.state.history.append(
WorldEvent(
scene_summary=semantic_scene or scene,
action=str(getattr(step, "action", "unknown")),
success=bool(getattr(result, "success", False)),
)
)
def _app_identifier(args: dict[str, Any]) -> str | None:
value = args.get("bundle_id") or args.get("app_id")
return value if isinstance(value, str) and value.strip() else None
+49
View File
@@ -0,0 +1,49 @@
from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from core.models import Scene, utc_now
from semantic.models import SemanticScene
from world.config import DEFAULT_HISTORY_SIZE
@dataclass(frozen=True)
class WorldEvent:
scene_summary: SemanticScene | Scene
action: str
success: bool
timestamp: datetime = field(default_factory=utc_now)
def to_dict(self) -> dict[str, Any]:
return {
"scene_summary": self.scene_summary.to_dict(),
"action": self.action,
"success": self.success,
"timestamp": self.timestamp.isoformat(),
}
@dataclass
class WorldState:
current_app: str | None = None
current_page: str | None = None
variables: dict[str, Any] = field(default_factory=dict)
history: deque[WorldEvent] = field(
default_factory=lambda: deque(maxlen=DEFAULT_HISTORY_SIZE)
)
@classmethod
def with_history_bound(cls, history_size: int) -> "WorldState":
maxlen = history_size if history_size > 0 else DEFAULT_HISTORY_SIZE
return cls(history=deque(maxlen=maxlen))
def to_dict(self) -> dict[str, Any]:
return {
"current_app": self.current_app,
"current_page": self.current_page,
"variables": dict(self.variables),
"history": [event.to_dict() for event in self.history],
}