"""The runtime gate question and the shared constants of the Mac decision data. Single source of truth: ``mac_laya.assistant`` (runtime), the data builders and the oracle all import the question from here, so training rows and the deployed call can never drift. The wording is byte-identical to the round-1 runtime question (assistant.decide_step and fast_lane.STEP_QUESTION); ``test_gate_question_matches_runtime`` pins that. """ from __future__ import annotations import copy VIEW_VERSION = "macjev-gate-view-v1" ORACLE_VERSION = "macjev-gate-oracle-v3" # v2: listed-parent rule 5, query_table, browser_fill_form, complete_args; # v3: observation.open_sessions (browser session open? current snapshot + controls; other modules ignored) GATE_QUESTION = { "t": "choice", "ins": "Choose the next step that best advances the original user goal with the available information.", "crit": { "execute": "Execute the proposed registered action after deterministic scope and precondition checks", "inspect": "Inspect the explicitly named app window or approved directory for more information before acting", "ask": "Ask the user to resolve missing information or ambiguity", }, } GATE_LABELS = tuple(GATE_QUESTION["crit"]) # Shadow question: asked when the planner proposes ``done``; the runtime only logs the answer. GOAL_DONE_QUESTION = { "t": "noul", "ins": "Do the observed results show that the original user goal is fully satisfied?", "crit": { "false": "No: a required output is missing or wrong, a source was changed, something unrequested was created, or a required clarification was not asked", "true": "Yes: every requested outcome is observed and nothing else was changed", }, } # Snapshot freshness used by both window controllers (runtime_windows / runtime_window_layout). SNAPSHOT_TTL_SECONDS = 120 # Input-length contract (user requirement 2026-09-24: 25,000-token inputs). Engineering max = 25,600 tokens in total # (state + question + options + readout), header (question + options) <= 2,048, never a silent cut: the view fits # the history into HISTORY_TOKEN_BUDGET with explicit markers, and a renderer that still does not fit raises # InputBudgetError (runtime: the adapter retries with the next smaller FALLBACK_BUDGETS entry and logs it). MAX_INPUT_TOKENS = 25600 HEADER_MAX_TOKENS = 2048 # Total history budget of the gate state (was ~6K in plan section 2; ~20K since the 25K requirement), explicit markers. HISTORY_TOKEN_BUDGET = 20000 # The rest of the gate state (goal, registry excerpt, open_sessions, proposed action) stays well below this; builders # drop (and count) any state above it so every row renders within MAX_INPUT_TOKENS with a full-size header. STATE_TOKEN_MAX = MAX_INPUT_TOKENS - HEADER_MAX_TOKENS # Fallback budgets tried in order when an engine still reports an input-budget error. FALLBACK_BUDGETS = (20000, 12000, 6000, 3000, 1500, 600) # Read-only observation tools: rule 4 of the oracle (execute when in scope and on intent). READ_ONLY_TOOLS = frozenset({ "list_files", "read_text", "read_office_document", "read_word_document", "read_excel_workbook", "read_powerpoint_deck", "observe_windows", "observe_window_layout", "observe_screens", "browser_observe", "ui_observe", "query_table", }) # Tool families used for quotas and reporting. FAMILY_OF_TOOL = { **{t: "files" for t in ("list_files", "read_text", "make_directory", "copy_file", "move_file", "write_text", "archive_files")}, **{t: "office" for t in ("read_office_document", "read_word_document", "read_excel_workbook", "read_powerpoint_deck", "create_word_document", "create_excel_workbook", "create_powerpoint_deck", "word_edit_copy", "excel_edit_copy", "libreoffice_save_copy", "query_table")}, **{t: "window" for t in ("observe_windows", "move_window", "resize_window", "minimize_window", "restore_window", "focus_window", "observe_window_layout", "observe_screens", "resize_layout_window", "tile_windows_side_by_side")}, **{t: "browser" for t in ("browser_open", "browser_observe", "browser_fill", "browser_select", "browser_check", "browser_click", "browser_fill_form")}, **{t: "apps" for t in ("open_app", "open_file_with_app", "media_control", "ui_observe", "ui_press", "ui_set_text", "obsidian_create_note")}, } def gate_question() -> dict: return copy.deepcopy(GATE_QUESTION) def goal_done_question() -> dict: return copy.deepcopy(GOAL_DONE_QUESTION) def runtime_contract(assistant_path=None) -> dict: """Snapshot of the gate contract as it is written in the CURRENT runtime source (read fresh). Parses ``mac_laya/assistant.py`` without importing it: the question literal inside ``Assistant.decide_step`` and the observation keys built in ``Assistant.plan``. Returns the extracted values plus sha256 digests so manifests can pin exactly what the data was built for. """ import ast import hashlib import json from pathlib import Path path = Path(assistant_path) if assistant_path else Path(__file__).resolve().parents[2] / "mac_laya" / "assistant.py" source = path.read_text() tree = ast.parse(source) question, observation_keys, history_window, question_source = None, None, None, None optional_keys: list = [] for node in ast.walk(tree): if isinstance(node, ast.FunctionDef) and node.name == "decide_step": for sub in ast.walk(node): if isinstance(sub, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "question" for t in sub.targets): question, question_source = ast.literal_eval(sub.value), "assistant.decide_step literal" if question is None and "runtime_adapter.gate_call" in ast.unparse(node): # RUNTIME_PATCH.md applied: the question comes from this module. question, question_source = copy.deepcopy(GATE_QUESTION), "macjev.mac.gate (via runtime_adapter)" if isinstance(node, ast.FunctionDef) and node.name == "plan": for sub in ast.walk(node): if isinstance(sub, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "observation" for t in sub.targets) \ and isinstance(sub.value, ast.Dict): observation_keys = [ast.literal_eval(k) for k in sub.value.keys] for value in sub.value.values: if isinstance(value, ast.Subscript) and isinstance(value.slice, ast.Slice) and value.slice.lower is not None: history_window = ast.unparse(value) # keys added conditionally, e.g. observation["open_sessions"]=sessions if isinstance(sub, ast.Assign): for t in sub.targets: if isinstance(t, ast.Subscript) and isinstance(t.value, ast.Name) and t.value.id == "observation": try: key = ast.literal_eval(t.slice) except ValueError: continue if key not in optional_keys: optional_keys.append(key) if question is None or observation_keys is None: raise RuntimeError("could not locate the gate question / observation in assistant.py; the runtime changed") state_schema = {"user_goal": "str", "observation": {**{k: "..." for k in observation_keys}, **{k: "... (optional)" for k in optional_keys}}, "proposed_action": {"tool": "str", "arguments": "object", "reason": "str (optional)"}} digest = lambda v: hashlib.sha256(json.dumps(v, ensure_ascii=False, sort_keys=True).encode()).hexdigest() # noqa: E731 return {"assistant_path": "src/mac_laya/assistant.py", "assistant_sha256": hashlib.sha256(source.encode()).hexdigest(), "question": question, "question_source": question_source, "question_sha256": digest(question), "observation_keys": observation_keys, "optional_observation_keys": optional_keys, "history_window": history_window, "state_schema": state_schema, "state_schema_sha256": digest(state_schema), "matches_macjev_gate_question": question == GATE_QUESTION}