"""Scope-relative model view of a gate call, shared by the data builders and the runtime. Replaces round-1 ``mac_laya.context.model_view`` (which collapsed every fixture path to its basename, so source and destination could become identical strings). Rules: * Paths inside ``approved_scope`` become scope-relative ("." is the scope itself); any path that stays absolute or contains ".." is, by construction, outside the approved folder. * ``list_files`` results become ``{directory, files, folders, symlinks_refused, truncated}``. * Bookkeeping that carries no decision signal (hashes, audit events, pids, recovery-draft paths, constant notes) is dropped; ``snapshot_id`` and ``window_ref`` are kept because the window and browser validators compare them. * Every history entry gets ``age_s`` (seconds since the runtime received it) when the runtime recorded ``at_unix``; window snapshots older than 120 s are stale. * The static app registry is not sent: ``registered_app_ids`` / ``window_app_aliases`` only list the apps named by the goal, the proposed action or the visible history. * The history is fitted to a token budget (gate.HISTORY_TOKEN_BUDGET, ~20K since 2026-09-24). Long strings and long lists are cut with explicit markers, and only then are the oldest results dropped (``previous_results_omitted``). Nothing is cut silently. """ from __future__ import annotations import copy import json import math import re from typing import Any, Callable from .gate import HISTORY_TOKEN_BUDGET, VIEW_VERSION DROP_KEYS = frozenset({ "sha256", "source_sha256", "native_app_event", "recovery_draft_retained", "untrusted_document_content", "observation_source", "office_application_launched", "active_parts_not_executed", "safe_to_open_in_office_not_assessed", "coordinate_space", "note", "expires_in_seconds", "execution_path", "elapsed_ms", "layout_rendered", "external_relationships_not_followed", "cached_formula_values_may_be_stale", "existing_file_overwritten", "pid", "window_id", "window_server", "verification", "at_unix", "think", "untrusted_page_content", }) LIST_KEYS = ("files", "folders", "symlinks_refused", "entries", "items", "windows", "controls", "rows", "paragraphs", "slides", "cells", "screens") STRING_MARKER = " …[gate view truncated this text: {kept} of {total} characters shown]" LIST_MARKER = "…[gate view: {more} more items not shown]" MARKER_RE = re.compile(r" …\[gate view truncated this text: (\d+) of (\d+) characters shown\]$") ACTION_TEXT_CHARS = 4000 # per argument string of the proposed action REASON_CHARS = 400 CJK = re.compile(r"[⺀-鿿가-힯豈-﫿＀-￯]") def approx_tokens(text: str) -> int: """Conservative token estimate used when no tokenizer is supplied (CJK ~1 token/char).""" cjk = len(CJK.findall(text)) return cjk + math.ceil((len(text) - cjk) / 3.2) def _registries(): # Lazy: mac_laya.assistant imports this module. from mac_laya.assistant import APPS from mac_laya.runtime_windows import WINDOW_APPS try: from mac_laya.runtime_apps import APPS as OPEN_APPS except Exception: # pragma: no cover - optional runtime module OPEN_APPS = {} return APPS, WINDOW_APPS, OPEN_APPS def mentioned(alias: str, text: str) -> bool: if not alias: return False if alias.isascii(): pattern = r"(? set[str]: apps, window_apps, open_apps = _registries() found = {bundle for alias, bundle in apps.items() if mentioned(alias, text)} found |= {bundle for bundle, aliases in window_apps.items() if any(mentioned(a, text) for a in aliases)} for bundle, app in open_apps.items(): if any(mentioned(a, text) for a in (*app.aliases, app.name.casefold())): found.add(bundle) return found def bundle_of(value: Any) -> str | None: """Bundle id for an action's bundle_id/app argument (registered or not); None if not app-like.""" if not isinstance(value, str) or not value.strip(): return None text = value.strip() if re.fullmatch(r"[A-Za-z][\w-]*(\.[\w-]+)+", text): return text apps, window_apps, open_apps = _registries() key = text.casefold() if key in apps: return apps[key] for bundle, aliases in window_apps.items(): if key in aliases: return bundle for bundle, app in open_apps.items(): if key == app.name.casefold() or key in (a.casefold() for a in app.aliases): return bundle return None def _action_bundles(action: Any) -> set[str]: out = set() if isinstance(action, dict) and isinstance(action.get("arguments"), dict): for key in ("bundle_id", "app"): bundle = bundle_of(action["arguments"].get(key)) if bundle: out.add(bundle) return out def relativize(value: Any, scope: str | None) -> Any: if scope is None: return value root = str(scope).rstrip("/") or "/" def convert(v): if isinstance(v, dict): return {k: convert(x) for k, x in v.items()} if isinstance(v, list): return [convert(x) for x in v] if isinstance(v, str): if v == root or v == root + "/": return "." if v.startswith(root + "/"): rest = v[len(root) + 1:] return rest or "." return v return convert(value) def _strip(value: Any) -> Any: if isinstance(value, dict): return {k: _strip(v) for k, v in value.items() if k not in DROP_KEYS} if isinstance(value, list): return [_strip(v) for v in value] return value def compact_listing(result: dict) -> dict: entries = result.get("entries") out = {"directory": result.get("directory", ".")} if isinstance(entries, list) and all(isinstance(e, dict) and "name" in e for e in entries): out["files"] = [e["name"] for e in entries if not e.get("is_directory") and not e.get("is_symlink_excluded")] out["folders"] = [e["name"] for e in entries if e.get("is_directory") and not e.get("is_symlink_excluded")] links = [e["name"] for e in entries if e.get("is_symlink_excluded")] if links: out["symlinks_refused"] = links else: # fast-lane listing: names only, kind unknown out["entries"] = list(entries or []) out["truncated"] = bool(result.get("truncated", False)) return out def compact_result(tool: str | None, result: Any) -> Any: if not isinstance(result, dict): return result if tool == "list_files" and "entries" in result and not ("executed" in result and result["executed"] is False): return compact_listing(result) return _strip(result) def compact_action(action: Any, *, limit_text: bool = True) -> Any: if not isinstance(action, dict): return action out = {"tool": action.get("tool"), "arguments": copy.deepcopy(action.get("arguments", {}))} if isinstance(out["arguments"], dict) and limit_text: for key, value in list(out["arguments"].items()): if isinstance(value, str) and len(value) > ACTION_TEXT_CHARS: out["arguments"][key] = cut_string(value, ACTION_TEXT_CHARS) reason = action.get("reason") if isinstance(reason, str) and reason.strip(): out["reason"] = cut_string(reason, REASON_CHARS) if len(reason) > REASON_CHARS else reason return out def cut_string(value: str, keep: int) -> str: original, total = value, len(value) match = MARKER_RE.search(value) if match: original = value[:match.start()] total = int(match.group(2)) keep = max(0, min(keep, len(original))) return original[:keep] + STRING_MARKER.format(kept=keep, total=total) def original_length(value: str) -> int: """Length of an argument string before the view cut it (the marker records it).""" match = MARKER_RE.search(value) if isinstance(value, str) else None return int(match.group(2)) if match else len(value) def history_entry(entry: Any, scope: str | None, now: float | None) -> dict: if not isinstance(entry, dict): return {"result": entry} action = entry.get("action") tool = action.get("tool") if isinstance(action, dict) else None out = {"action": relativize(compact_action(action), scope), "result": relativize(compact_result(tool, entry.get("result")), scope)} if entry.get("explicit_user_confirmation"): out["confirmed_by_user"] = True at = entry.get("at_unix") if "age_s" in entry and isinstance(entry["age_s"], (int, float)): out["age_s"] = int(entry["age_s"]) elif isinstance(at, (int, float)) and now is not None: out["age_s"] = max(0, int(round(now - at))) return out def _dumps(value: Any) -> str: return json.dumps(value, ensure_ascii=False) def _shrink_once(entries: list, count: Callable[[str], int]) -> bool: """Halve the single most expensive long string or long list; return False if nothing can shrink.""" best = None # (cost, container, key, kind) def visit(container, key, value, owner): nonlocal best if isinstance(value, str): body_len = len(value) - (len(MARKER_RE.search(value).group(0)) if MARKER_RE.search(value) else 0) if body_len > 160: cost = count(value) if best is None or cost > best[0]: best = (cost, container, key, "str", owner) elif isinstance(value, list): real = [v for v in value if not (isinstance(v, str) and v.startswith("…[gate view:"))] if len(real) > 6 and key in LIST_KEYS: cost = count(_dumps(value)) if best is None or cost > best[0]: best = (cost, container, key, "list", owner) for i, item in enumerate(value): visit(value, i, item, owner) elif isinstance(value, dict): for k, v in value.items(): visit(value, k, v, value) for entry in entries: visit(None, None, entry, entry) if best is None: return False _, container, key, kind, owner = best value = container[key] if kind == "str": match = MARKER_RE.search(value) body = value[:match.start()] if match else value container[key] = cut_string(value, max(80, len(body) // 2)) else: real = [v for v in value if not (isinstance(v, str) and v.startswith("…[gate view:"))] hidden = sum(int(re.search(r"(\d+)", v).group(1)) for v in value if isinstance(v, str) and v.startswith("…[gate view:")) keep = max(3, len(real) // 2) container[key] = real[:keep] + [LIST_MARKER.format(more=len(real) - keep + hidden)] if isinstance(container, dict) and "truncated" in container: container["truncated"] = True return True def fit_history(entries: list, budget_tokens: int, count: Callable[[str], int]) -> tuple[list, int, int]: """Return (entries, omitted_oldest, shrink_steps) whose JSON costs at most ``budget_tokens``.""" entries = copy.deepcopy(entries) omitted = steps = 0 while entries and count(_dumps(entries)) > budget_tokens: if _shrink_once(entries, count): steps += 1 continue entries.pop(0) omitted += 1 return entries, omitted, steps def gate_state(goal: str, observation: dict, action: Any, *, now: float | None = None, budget_tokens: int = HISTORY_TOKEN_BUDGET, count_tokens: Callable[[str], int] | None = None, include_registry: bool = True) -> dict: """The exact state the gate model sees for {user_goal, observation, proposed_action}.""" count = count_tokens or approx_tokens scope = observation.get("approved_scope") scope = str(scope) if scope is not None else None history = [history_entry(e, scope, now) for e in observation.get("previous_results", []) or []] history, omitted, _ = fit_history(history, budget_tokens, count) view_obs: dict = {"approved_scope": scope} if include_registry: apps, window_apps, _ = _registries() relevant = bundles_named(goal) | _action_bundles(action) for entry in observation.get("previous_results", []) or []: if isinstance(entry, dict): relevant |= _action_bundles(entry.get("action")) registered = set(apps.values()) view_obs["registered_app_ids"] = sorted(b for b in relevant if b in registered) view_obs["window_app_aliases"] = {b: list(window_apps[b]) for b in sorted(relevant) if b in window_apps} if omitted: view_obs["previous_results_omitted"] = omitted view_obs["previous_results"] = history if observation.get("open_sessions"): view_obs["open_sessions"] = relativize(_strip(observation["open_sessions"]), scope) return {"user_goal": goal, "observation": view_obs, "proposed_action": relativize(compact_action(action), scope)} def goal_done_state(goal: str, observation: dict, action: Any, **kwargs) -> dict: """Shadow 'goal satisfied?' state: same view, full (budgeted) history instead of the last four.""" return gate_state(goal, observation, action, **kwargs) def view_meta(state: dict, count_tokens: Callable[[str], int] | None = None) -> dict: count = count_tokens or approx_tokens text = _dumps(state) return {"view_version": VIEW_VERSION, "state_tokens": count(text), "history_items": len(state["observation"].get("previous_results", [])), "history_omitted": state["observation"].get("previous_results_omitted", 0), "view_truncated": "gate view" in text}