File size: 88,288 Bytes
72c7148 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 | """State simulator for the Mac gate: fixtures, correct plans, executed histories and perturbations.
One *episode* = a goal (family x language x wording), a fixture in a fresh temporary folder, and
the correct plan for the goal. File tools and Office reads are executed for real with the
runtime's own ``FileScope`` / ``office_reader`` on that folder (so results carry the runtime's exact
shapes); native-app tools (Office creation, windows, browser, app opening) return synthesised
results with the runtime's key names. The temporary path is then rewritten to a realistic
approved folder (e.g. ``/Users/mei/Documents/Q3``) so the view sees what the product would see.
``gate_candidates(episode)`` yields raw runtime-shaped (observation, proposed_action) pairs for
every plan step under a menu of *situations* (clean history, skipped observation, stale or
consumed snapshot, collision, missing source, wrong / outside path, off-intent tool,
unregistered tool or app, noisy / long history, truncated listing). Labels are NOT decided
here: the builder passes the view state to ``oracle.decide``.
"""
from __future__ import annotations
import copy
import hashlib
import json
import posixpath
import random
import shutil
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from . import wording as W
AREA_OF_FAMILY = {
**{f: "files" for f in ("copy", "move", "write", "archive", "copy_archive", "organize", "read_text", "list")},
**{f: "office" for f in ("word_create", "excel_create", "slides_create", "office_read", "office_read_app",
"office_transform", "excel_to_word", "libreoffice_copy")},
**{f: "window" for f in ("window_single", "window_layout", "window_resize_layout", "window_observe")},
**{f: "apps" for f in ("open_app", "open_file", "browser_form")},
}
FAMILIES = tuple(AREA_OF_FAMILY)
# App hold-outs (never in train): dev "unseen app" group and test "unseen app" group.
WINDOW_APP_POOL = { # display name -> bundle
"TextEdit": "com.apple.TextEdit", "Preview": "com.apple.Preview", "Finder": "com.apple.finder",
"Chrome": "com.google.Chrome", "Word": "com.microsoft.Word", "Excel": "com.microsoft.Excel",
"PowerPoint": "com.microsoft.Powerpoint", "Firefox": "org.mozilla.firefox", "LibreOffice": "org.libreoffice.script",
"Obsidian": "md.obsidian", "Safari": "com.apple.Safari", "VS Code": "com.microsoft.VSCode",
"VLC": "org.videolan.vlc", "Calculator": "com.apple.calculator",
}
ZH_APP_NAME = {"TextEdit": "文本编辑", "Preview": "预览", "Finder": "访达", "Chrome": "Chrome", "Firefox": "火狐",
"Calculator": "计算器"}
DEV_APPS = frozenset({"Safari", "VS Code"})
TEST_APPS = frozenset({"VLC", "Calculator"})
OPEN_FILE_APPS = {"Preview": (".pdf", ".png", ".jpg"), "TextEdit": (".txt", ".md", ".rtf"), "VLC": (".mp3", ".mp4", ".wav"),
"Word": (".docx",), "Excel": (".xlsx",), "PowerPoint": (".pptx",)}
UNREGISTERED_TOOLS = ("delete_file", "run_shell", "send_email", "rename_file", "upload_file", "execute_script",
"empty_trash", "download_url", "overwrite_file", "click_screen")
UNREGISTERED_BUNDLES = ("com.spotify.client", "com.tinyspeck.slackmacgap", "us.zoom.xos", "com.apple.Terminal",
"com.apple.mail", "com.apple.Music", "com.tencent.xinWeChat")
USERS = ("mei", "alex", "chen", "sam", "li.na", "jordan", "wang", "priya", "tom", "zhao", "lena", "kai")
PLACES = ("Documents", "Desktop", "Downloads", "Projects", "Work", "文档", "工作")
PROJECTS = ("Q3", "invoices", "trip-2026", "thesis", "client_acme", "报销", "课程资料", "handover", "release-notes",
"年度总结", "grant", "household", "photos-sorted", "lab", "季度复盘", "hiring")
STEMS = {"en": ("notes", "report", "budget", "invoice", "draft", "summary", "plan", "minutes", "todo", "agenda", "memo",
"log", "letter", "contacts", "inventory", "schedule", "outline", "checklist", "ideas", "readme",
"quote", "roster", "feedback", "timeline", "receipts", "brief"),
"zh": ("笔记", "报告", "预算", "发票", "草稿", "总结", "计划", "会议纪要", "待办", "议程", "备忘", "日志",
"信件", "通讯录", "库存", "日程", "提纲", "清单", "想法", "说明", "报价", "名单", "反馈", "时间线")}
FOLDERS = {"en": ("archive", "backup", "shared", "old", "final", "inbox", "exports", "2025", "clients", "misc"),
"zh": ("归档", "备份", "共享", "旧文件", "定稿", "收件", "导出", "客户", "杂项", "资料")}
TEXTS = {"en": ("Meeting moved to Thursday 10am.", "Remember to renew the parking permit.", "Totals checked twice; ok.",
"Ship the draft to Dana by Friday.", "Call the landlord about the heater.", "Budget line 4 needs review."),
"zh": ("会议改到周四上午十点。", "记得续办停车证。", "合计已复核两遍,无误。", "周五前把草稿发给王老师。",
"联系房东修暖气。", "预算第四行需要复查。")}
TITLES = {"en": ("Overview", "Goals", "Timeline", "Risks", "Budget", "Next steps", "Results", "Team"),
"zh": ("概览", "目标", "时间表", "风险", "预算", "下一步", "结果", "团队")}
WINDOW_TITLES = ("notes.txt", "Quarterly plan", "draft-v2.md", "Untitled", "summary.docx", "Inbox", "photo_12.png",
"budget.xlsx", "README.md", "会议纪要.txt", "旅行计划", "slides.pptx")
FIELDS = (("name", "Name", "Chen Li"), ("email", "Email", "sam@example.org"), ("city", "City", "Hangzhou"),
("qty", "Quantity", "12"), ("note", "Note", "Leave at the door"), ("phone", "Phone", "555-0142"))
def _hex(rng: random.Random, n: int = 10) -> str:
return "".join(rng.choice("0123456789abcdef") for _ in range(n))
@dataclass
class Episode:
family: str
lang: str
widx: int
goal: str
scope: str
files: dict # rel -> bytes (file) | None (dir) | "symlink"
plan: list # correct actions, in order
app: str | None = None # display name of the app the goal is about (hold-out unit)
windows: list = field(default_factory=list)
spec: dict | None = None # acceptance-style row for the goal-done verifier
seed: int = 0
info: dict = field(default_factory=dict)
@property
def area(self) -> str:
return AREA_OF_FAMILY[self.family]
# ------------------------------------------------------------------ episode factories
def _scope(rng):
return f"/Users/{rng.choice(USERS)}/{rng.choice(PLACES)}/{rng.choice(PROJECTS)}"
NAME_SEPS = ("_", "-", "")
NAME_SUFFIXES = ("", "v2", "final", "2026", "old", "a", "b", "03", "copy", "new", "1", "2")
DIR_SUFFIXES = ("", "_new", "-2026", "_old", "2")
def _name(rng, lang, ext, used):
for _ in range(50):
stem = rng.choice(STEMS[lang if rng.random() < .8 else "en"])
if rng.random() < .5:
stem += rng.choice(NAME_SEPS) + rng.choice(NAME_SUFFIXES[1:])
name = stem + ext
if name not in used:
used.add(name)
return name
name = f"file_{_hex(rng, 4)}{ext}"
used.add(name)
return name
def _text(rng, lang):
return rng.choice(TEXTS[lang]) + f" #{_hex(rng, 4)}"
def _distractors(rng, lang, files, used, n=None):
n = rng.randint(0, 6) if n is None else n
for _ in range(n):
ext = rng.choice((".txt", ".md", ".csv", ".pdf", ".png", ".docx", ".xlsx"))
files[_name(rng, lang, ext, used)] = f"distractor {_hex(rng, 6)}\n".encode()
if rng.random() < .35:
folder = rng.choice(FOLDERS[lang])
files[folder] = None
for _ in range(rng.randint(0, 3)):
files[folder + "/" + _name(rng, lang, ".txt", set())] = b"old\n"
def _office_bytes(ext, rng, lang, paragraphs=None, rows=None):
from mac_laya.fixture_office import docx_bytes, xlsx_bytes
if ext == ".docx":
return docx_bytes(paragraphs or [_text(rng, lang) for _ in range(rng.randint(2, 5))])
return xlsx_bytes(rows or [["Item", "Qty"], ["pens", 4], ["paper", 2]])
def _goal(family, lang, widx, **slots):
return W.goal_template(family, lang, widx).format(**slots)
def reason_for(tool, arguments, lang, rng, bank_share: float = 0.0):
"""A reason sentence consistent with ``tool`` and its (final) arguments. With ``bank_share`` (train only),
that share of reasons comes from the teacher-paraphrased reason bank of the same tool, when it has any."""
reasons = W.REASONS.get(tool, {}).get(lang) or W.GENERIC_REASONS[lang]
if bank_share > 0 and rng.random() < bank_share:
reasons = W.reason_bank().get(f"{tool}:{lang}") or reasons
arguments = arguments if isinstance(arguments, dict) else {}
fmt = {k: (v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)) for k, v in arguments.items()}
fmt.setdefault("target", next((v for v in fmt.values() if isinstance(v, str) and v), ""))
if "directory" in fmt:
fmt.setdefault("dir", fmt["directory"]) # list_files templates say {dir}
try:
return rng.choice(reasons).format(**fmt)
except (KeyError, IndexError):
return rng.choice(W.GENERIC_REASONS[lang])
def _act(tool, lang, rng, **arguments):
return {"tool": tool, "arguments": arguments, "reason": reason_for(tool, arguments, lang, rng)}
def _list(lang, rng, directory="."):
return _act("list_files", lang, rng, directory=directory, dir=directory)
def _fix_args(action):
"""Drop the formatting helpers (dir=...) that are not tool arguments."""
from mac_laya.assistant import CATALOGUE
spec = CATALOGUE.get(action["tool"])
if spec:
action["arguments"] = {k: v for k, v in action["arguments"].items() if k in spec["arguments"]}
return action
# share of office_transform / excel_to_word episodes that read their source with query_table (the planner's newer
# tool) instead of the Office reader; raised from .5 (to .9 / .95) in the 2026-09-24 review so the long-history counterexamples
# (which enlarged the Office-creation cells) do not push query_table below 100 train rows
QUERY_TABLE_SHARE = .9
QUERY_TABLE_SHARE_XLSX = .95 # excel_to_word; read_excel_workbook / read_office_document stay covered by office_read(_app)
def make_episode(family: str, lang: str, widx: int, seed: int, app: str | None = None) -> Episode:
rng = random.Random(seed)
used: set = set()
files: dict = {}
scope = _scope(rng)
plan: list = []
spec = None
windows: list = []
info: dict = {}
L = lambda: _list(lang, rng) # noqa: E731
if family in ("copy", "move", "write", "archive", "copy_archive", "organize", "read_text", "list"):
ext = rng.choice((".txt", ".md", ".csv"))
if family == "copy":
src, dst = _name(rng, lang, ext, used), _name(rng, lang, ext, used)
files[src] = _text(rng, lang).encode()
goal = _goal(family, lang, widx, src=src, dst=dst)
plan = [L(), _act("copy_file", lang, rng, source=src, destination=dst)]
spec = {"preserve": [src], "assertions": [{"kind": "file_text", "path": dst, "text": files[src].decode()}]}
info = {"sources": [src], "dests": [dst]}
elif family == "move":
src, dst = _name(rng, lang, ext, used), _name(rng, lang, ext, used)
files[src] = _text(rng, lang).encode()
goal = _goal(family, lang, widx, src=src, dst=dst)
plan = [L(), _act("move_file", lang, rng, source=src, destination=dst)]
spec = {"preserve": [], "assertions": [{"kind": "file_text", "path": dst, "text": files[src].decode()},
{"kind": "absent", "path": src}]}
info = {"sources": [src], "dests": [dst]}
elif family == "write":
dst, text = _name(rng, lang, ext, used), _text(rng, lang)
goal = _goal(family, lang, widx, dst=dst, text=text)
plan = [L(), _act("write_text", lang, rng, path=dst, text=text)]
spec = {"preserve": [], "assertions": [{"kind": "file_text", "path": dst, "text": text}]}
info = {"sources": [], "dests": [dst]}
elif family == "archive":
a, b, z = _name(rng, lang, ext, used), _name(rng, lang, ".txt", used), _name(rng, lang, ".zip", used)
files[a], files[b] = _text(rng, lang).encode(), _text(rng, lang).encode()
goal = _goal(family, lang, widx, a=a, b=b, zip=z)
plan = [L(), _act("archive_files", lang, rng, paths=[a, b], destination=z)]
spec = {"preserve": [a, b], "assertions": [{"kind": "zip_exact_text_members", "path": z,
"members": {a: files[a].decode(), b: files[b].decode()}}]}
info = {"sources": [a, b], "dests": [z]}
elif family == "copy_archive":
src, mid, b, z = (_name(rng, lang, ext, used), _name(rng, lang, ext, used), _name(rng, lang, ".txt", used),
_name(rng, lang, ".zip", used))
files[src], files[b] = _text(rng, lang).encode(), _text(rng, lang).encode()
goal = _goal(family, lang, widx, src=src, mid=mid, b=b, zip=z)
plan = [L(), _act("copy_file", lang, rng, source=src, destination=mid),
_act("archive_files", lang, rng, paths=[mid, b], destination=z)]
spec = {"preserve": [src, b], "assertions": [
{"kind": "file_text", "path": mid, "text": files[src].decode()},
{"kind": "zip_exact_text_members", "path": z, "members": {mid: files[src].decode(), b: files[b].decode()}}]}
info = {"sources": [src, b], "dests": [mid, z]}
elif family == "organize":
src = _name(rng, lang, ext, used)
folder = rng.choice(FOLDERS[lang]) + rng.choice(("", "_new", "-2026"))
final = _name(rng, lang, ext, used)
files[src] = _text(rng, lang).encode()
goal = _goal(family, lang, widx, dir=folder, src=src, src_name=src, final=final)
plan = [L(), _act("make_directory", lang, rng, path=folder),
_act("copy_file", lang, rng, source=src, destination=f"{folder}/{src}"),
_act("move_file", lang, rng, source=f"{folder}/{src}", destination=f"{folder}/{final}")]
spec = {"preserve": [src], "assertions": [{"kind": "file_text", "path": f"{folder}/{final}", "text": files[src].decode()},
{"kind": "absent", "path": f"{folder}/{src}"}]}
info = {"sources": [src], "dests": [folder, f"{folder}/{final}"]}
elif family == "read_text":
src = _name(rng, lang, ext, used)
files[src] = (_text(rng, lang) + "\n") * rng.choice((1, 1, 3, 40, 400))
files[src] = files[src].encode() if isinstance(files[src], str) else files[src]
goal = _goal(family, lang, widx, src=src)
plan = [L(), _act("read_text", lang, rng, path=src)]
info = {"sources": [src], "dests": []}
else: # list
folder = rng.choice(FOLDERS[lang])
files[folder] = None
for _ in range(rng.choice((1, 3, 8, 30, 120))):
files[folder + "/" + _name(rng, lang, rng.choice((".txt", ".pdf", ".png")), used)] = b"x\n"
goal = _goal(family, lang, widx, dir=folder)
plan = [_act("list_files", lang, rng, directory=folder, dir=folder)]
info = {"sources": [], "dests": [], "dir": folder}
_distractors(rng, lang, files, used)
elif family in ("word_create", "excel_create", "slides_create"):
if family == "word_create":
dst, text = _name(rng, lang, ".docx", used), _text(rng, lang)
goal = _goal(family, lang, widx, dst=dst, text=text)
plan = [L(), _act("create_word_document", lang, rng, destination=dst, text=text)]
spec = {"preserve": [], "assertions": [{"kind": "word_text", "path": dst, "content": text}]}
elif family == "excel_create":
dst = _name(rng, lang, ".xlsx", used)
rows = [["Item", "Qty"]] + [[rng.choice(("pens", "paper", "tape", "ink", "纸", "笔")), rng.randint(1, 40)]
for _ in range(rng.randint(1, 4))]
goal = _goal(family, lang, widx, dst=dst, rows=json.dumps(rows, ensure_ascii=False))
plan = [L(), _act("create_excel_workbook", lang, rng, destination=dst, rows=rows)]
spec = {"preserve": [], "assertions": [{"kind": "excel_values", "path": dst, "content": rows}]}
else:
dst = _name(rng, lang, ".pptx", used)
titles = rng.sample(TITLES[lang], rng.randint(1, 4))
goal = _goal(family, lang, widx, dst=dst, titles=json.dumps(titles, ensure_ascii=False))
plan = [L(), _act("create_powerpoint_deck", lang, rng, destination=dst, titles=titles)]
info = {"sources": [], "dests": [dst]}
_distractors(rng, lang, files, used)
elif family in ("office_read", "office_read_app", "office_transform", "excel_to_word", "libreoffice_copy"):
if family == "office_read":
ext = rng.choice((".docx", ".xlsx"))
src = _name(rng, lang, ext, used)
files[src] = _office_bytes(ext, rng, lang)
goal = _goal(family, lang, widx, src=src)
plan = [L(), _act("read_office_document", lang, rng, path=src, section="", offset=0, limit=20)]
info = {"sources": [src], "dests": []}
elif family == "office_read_app":
app = app or rng.choice(("Word", "Excel", "PowerPoint"))
ext = {"Word": ".docx", "Excel": ".xlsx", "PowerPoint": ".pptx"}[app]
src = _name(rng, lang, ext, used)
files[src] = _office_bytes(ext, rng, lang) if ext != ".pptx" else b"PK-placeholder-pptx"
tool = {"Word": "read_word_document", "Excel": "read_excel_workbook", "PowerPoint": "read_powerpoint_deck"}[app]
goal = _goal(family, lang, widx, src=src, appname=app)
plan = [L(), _act(tool, lang, rng, path=src)]
info = {"sources": [src], "dests": []}
elif family == "office_transform":
src, dst = _name(rng, lang, ".docx", used), _name(rng, lang, ".docx", used)
paragraphs = [_text(rng, lang) for _ in range(rng.randint(2, 4))]
files[src] = _office_bytes(".docx", rng, lang, paragraphs=paragraphs)
goal = _goal(family, lang, widx, src=src, dst=dst)
read = (_act("query_table", lang, rng, source=src, where={}, order_by="row", descending=True, derive={})
if rng.random() < QUERY_TABLE_SHARE else _act("read_office_document", lang, rng, path=src, section="", offset=0, limit=20))
plan = [L(), read, _act("create_word_document", lang, rng, destination=dst, text="\n".join(reversed(paragraphs)))]
spec = {"preserve": [src], "assertions": [{"kind": "word_text", "path": dst, "content": "\n".join(reversed(paragraphs))}]}
info = {"sources": [src], "dests": [dst]}
elif family == "excel_to_word":
src, dst = _name(rng, lang, ".xlsx", used), _name(rng, lang, ".docx", used)
col = rng.choice(("Item", "Name", "City"))
values = [rng.choice(("pens", "Hangzhou", "Oslo", "Chen", "ink", "Lima")) + str(i) for i in range(rng.randint(2, 4))]
files[src] = _office_bytes(".xlsx", rng, lang, rows=[[col, "Qty"]] + [[v, i] for i, v in enumerate(values)])
goal = _goal(family, lang, widx, src=src, dst=dst, col=col)
read = (_act("query_table", lang, rng, source=src, where={}, order_by="", descending=False, derive={})
if rng.random() < QUERY_TABLE_SHARE_XLSX else _act("read_excel_workbook", lang, rng, path=src))
plan = [L(), read,
_act("create_word_document", lang, rng, destination=dst, text="\n".join(values))]
spec = {"preserve": [src], "assertions": [{"kind": "word_text", "path": dst, "content": "\n".join(values)}]}
info = {"sources": [src], "dests": [dst]}
else:
src, dst = _name(rng, lang, rng.choice((".docx", ".odt", ".rtf")), used), _name(rng, lang, ".docx", used)
files[src] = _office_bytes(".docx", rng, lang) if src.endswith(".docx") else b"{\\rtf1 placeholder}"
goal = _goal(family, lang, widx, src=src, dst=dst)
plan = [L(), _act("libreoffice_save_copy", lang, rng, source=src, destination=dst)]
info = {"sources": [src], "dests": [dst]}
_distractors(rng, lang, files, used)
elif family in ("window_single", "window_layout", "window_resize_layout", "window_observe"):
app = app or rng.choice([a for a in WINDOW_APP_POOL if a not in DEV_APPS | TEST_APPS])
bundle = WINDOW_APP_POOL[app]
appname = ZH_APP_NAME.get(app, app) if lang == "zh" and rng.random() < .6 else app
titles = rng.sample(WINDOW_TITLES, rng.randint(2, 5))
windows = [{"window_ref": f"w{_hex(rng, 6)}", "title": t, "position": [rng.randint(0, 900), rng.randint(25, 500)],
"size": [rng.randint(300, 1200), rng.randint(200, 800)], "minimized": rng.random() < .15} for t in titles]
target = windows[0]
if family == "window_single":
tool = rng.choice(("move_window", "resize_window", "minimize_window", "restore_window", "focus_window"))
verb_en, verb_lower, verb_past, verb_zh, extra_en, extra_zh = W.WINDOW_VERBS[tool]
x, y, w_, h_ = rng.randint(0, 800), rng.randint(30, 500), rng.randint(400, 1400), rng.randint(300, 900)
slots = dict(appname=appname, title=target["title"], verb_en=verb_en, verb_lower=verb_lower, verb_past=verb_past,
verb_zh=verb_zh, extra_en=extra_en.format(x=x, y=y, w=w_, h=h_),
extra_zh=extra_zh.format(x=x, y=y, w=w_, h=h_))
goal = _goal(family, lang, widx, **slots)
args = dict(bundle_id=bundle, window_ref=target["window_ref"], snapshot_id="$SNAP")
if tool == "move_window":
args["value"] = [x, y]
if tool == "resize_window":
args["value"] = [w_, h_]
plan = [_act("observe_windows", lang, rng, bundle_id=bundle), _act(tool, lang, rng, **args)]
elif family == "window_layout":
left, right = windows[0], windows[1]
goal = _goal(family, lang, widx, appname=appname, left=left["title"], right=right["title"])
plan = [_act("observe_window_layout", lang, rng, bundle_id=bundle),
_act("tile_windows_side_by_side", lang, rng, bundle_id=bundle, left_window_ref=left["window_ref"],
right_window_ref=right["window_ref"], snapshot_id="$SNAP")]
elif family == "window_resize_layout":
w_, h_ = rng.randint(400, 1400), rng.randint(300, 900)
goal = _goal(family, lang, widx, appname=appname, title=target["title"], w=w_, h=h_)
plan = [_act("observe_window_layout", lang, rng, bundle_id=bundle),
_act("resize_layout_window", lang, rng, bundle_id=bundle, window_ref=target["window_ref"],
snapshot_id="$SNAP", value=[w_, h_])]
else:
goal = _goal(family, lang, widx, appname=appname)
plan = [_act("observe_windows", lang, rng, bundle_id=bundle)]
info = {"bundle": bundle}
_distractors(rng, lang, files, used, n=rng.randint(0, 2))
elif family == "open_app":
app = app or rng.choice([a for a in WINDOW_APP_POOL if a not in DEV_APPS | TEST_APPS])
from mac_laya.assistant import APPS
bundle = WINDOW_APP_POOL[app]
if bundle not in set(APPS.values()):
raise ValueError(f"{app} is not a registered open_app target")
appname = ZH_APP_NAME.get(app, app) if lang == "zh" and rng.random() < .6 else app
goal = _goal(family, lang, widx, appname=appname)
plan = [_act("open_app", lang, rng, bundle_id=bundle)]
info = {"bundle": bundle}
elif family == "open_file":
app = app or rng.choice([a for a in OPEN_FILE_APPS if a not in DEV_APPS | TEST_APPS])
ext = rng.choice(OPEN_FILE_APPS[app])
src = _name(rng, lang, ext, used)
files[src] = _office_bytes(ext, rng, lang) if ext in (".docx", ".xlsx") else b"binary placeholder\n"
appname = ZH_APP_NAME.get(app, app) if lang == "zh" and rng.random() < .5 else app
goal = _goal(family, lang, widx, src=src, appname=appname)
plan = [L(), _act("open_file_with_app", lang, rng, path=src, app=app)]
info = {"sources": [src], "dests": []}
_distractors(rng, lang, files, used)
elif family == "browser_form":
app = app or "Chrome"
appname = ZH_APP_NAME.get(app, app) if lang == "zh" and rng.random() < .5 else app
field_id, label, value = rng.choice(FIELDS)
mode = rng.choice(("submit", "nosubmit", "plain"))
submit_en = {"submit": " and then submit the form", "nosubmit": ", but do not submit it", "plain": ""}[mode]
submit_zh = {"submit": ",然后提交表单", "nosubmit": ",但不要提交", "plain": ""}[mode]
goal = _goal(family, lang, widx, appname=appname, field=label, value=value, submit_en=submit_en, submit_zh=submit_zh)
key = "firefox" if app == "Firefox" else "chrome"
plan = [_act("browser_observe", lang, rng, app=key),
(_act("browser_fill_form", lang, rng, app=key, fields={field_id: value}, snapshot_id="$SNAP") if rng.random() < .6
else _act("browser_fill", lang, rng, app=key, target=field_id, value=value, snapshot_id="$SNAP"))]
if mode != "plain":
plan.append(_act("browser_click", lang, rng, app=key, target="submit", snapshot_id="$SNAP"))
info = {"field": field_id, "mode": mode, "browser": key,
"controls": [{"id": f[0], "kind": "text", "label": f[1], "value": ""} for f in FIELDS]
+ [{"id": "submit", "kind": "button", "label": "Submit"}, {"id": "reset", "kind": "button", "label": "Reset"}]}
else:
raise ValueError(family)
plan = [_fix_args(a) for a in plan]
row_spec = {"family": family, "expected": spec} if spec else None
return Episode(family, lang, widx, goal, scope, files, plan, app, windows, row_spec, seed, info)
# ------------------------------------------------------------------ execution
class Runner:
"""Executes actions on a real temporary fixture (file tools, Office reads) or synthesises results."""
def __init__(self, ep: Episode, rng: random.Random, files: dict | None = None):
self.ep, self.rng = ep, rng
self.base = Path(tempfile.mkdtemp(prefix="macjev-sim-")).resolve()
self.root = self.base / "scope"
self.root.mkdir()
outside = self.base / "outside"
outside.mkdir()
(outside / "t.txt").write_text("outside")
for rel, content in sorted((files if files is not None else ep.files).items(), key=lambda kv: kv[0].count("/")):
path = self.root / rel
path.parent.mkdir(parents=True, exist_ok=True)
if content is None:
path.mkdir(exist_ok=True)
elif content == "symlink":
path.symlink_to(outside / "t.txt")
else:
path.write_bytes(content)
self.snap = {} # bundle/app -> current snapshot id
self.phantom = [] # extra names shown by a >100-entry listing of the scope root
self.phantom_dirs = {} # resolved sub-folder path -> extra names (big folders listed like FileScope, not written)
self.clock = 0.0
# Isolated browser sessions this run opened (runtime_browser keeps them in ctx.sessions["browser:<app>"]):
# app -> {"url", "title", "snapshots": [ids, oldest first], "values": {control id: value}}
self.browser = {}
self.extra_sessions = {} # other modules' open_sessions summaries (label-neutral: no validator reads them)
def close(self):
shutil.rmtree(self.base, ignore_errors=True)
def _rewrite(self, value):
raw = str(self.root)
def conv(v):
if isinstance(v, dict):
return {k: conv(x) for k, x in v.items()}
if isinstance(v, list):
return [conv(x) for x in v]
if isinstance(v, str) and raw in v:
return v.replace(raw, self.ep.scope)
return v
return conv(value)
def resolve_placeholders(self, action):
action = copy.deepcopy(action)
args = action.get("arguments", {})
if isinstance(args, dict) and args.get("snapshot_id") == "$SNAP":
key = args.get("bundle_id") or args.get("app")
args["snapshot_id"] = self.snap.get(key) or f"s{_hex(self.rng, 12)}"
return action
def run(self, action) -> dict:
from mac_laya.office_reader import read_office
from mac_laya.scoped_files import FileScope
tool, args = action["tool"], action.get("arguments", {})
if isinstance(args, dict): # absolute paths inside the approved folder -> the temporary fixture
args = {k: (str(self.root) + v[len(self.ep.scope):] if isinstance(v, str) and (v == self.ep.scope or v.startswith(self.ep.scope + "/"))
else [str(self.root) + x[len(self.ep.scope):] if isinstance(x, str) and x.startswith(self.ep.scope + "/") else x for x in v]
if isinstance(v, list) else v) for k, v in args.items()}
else:
return {"executed": False, "error": "ValueError", "message": "Unknown or missing tool argument"}
rng = self.rng
try:
if tool in ("list_files", "read_text", "make_directory", "copy_file", "move_file", "write_text", "archive_files"):
args2 = dict(args)
if tool == "list_files" and args2.get("directory") in (".", self.ep.scope):
args2["directory"] = str(self.root)
result = FileScope(self.root).execute(tool, args2)
extra = (self.phantom if tool == "list_files" and self.phantom and Path(result["directory"]) == self.root
else self.phantom_dirs.get(str(Path(result["directory"]))) if tool == "list_files" else None)
if extra:
# A folder with more than 100 entries, listed exactly as FileScope does (sorted, first 100),
# without writing hundreds of files to disk.
entries = {e["name"]: e for e in result["entries"]}
for name in extra:
entries.setdefault(name, {"name": name, "is_directory": False, "is_symlink_excluded": False,
"bytes": 2048})
names = sorted(entries)
result = {**result, "entries": [entries[n] for n in names[:100]], "truncated": len(names) > 100}
return self._rewrite(result)
if tool == "read_office_document":
return self._rewrite(read_office(args, self.root))
if tool == "query_table":
from mac_laya import runtime_data
from mac_laya.runtime_context import RuntimeContext
return self._rewrite(runtime_data.execute(tool, dict(args), RuntimeContext(self.root, self.ep.goal)))
if tool in ("create_word_document", "create_excel_workbook", "create_powerpoint_deck"):
from mac_laya.scoped_files import resolve_path
dest = resolve_path(args["destination"], self.root)
if dest.exists() or not dest.parent.is_dir():
raise ValueError("Office destination must be new and its parent must already exist")
data = self._office_file(tool, args)
dest.write_bytes(data)
return self._rewrite({"destination": str(dest), "verified": True, "sha256": hashlib.sha256(data).hexdigest(),
"native_office_application_used": True})
if tool in ("read_word_document", "read_excel_workbook", "read_powerpoint_deck"):
path = self.root / args["path"]
if not path.is_file():
raise FileNotFoundError(args["path"])
if tool == "read_word_document":
return {"path": self.ep.scope + "/" + args["path"], "paragraphs": [_text(rng, self.ep.lang) for _ in range(3)],
"app_paragraph_count": 3}
if tool == "read_excel_workbook":
return {"path": self.ep.scope + "/" + args["path"], "worksheet": "Sheet1", "worksheet_count": 1,
"used_range": "$A$1:$B$4", "read_range": "A1:B4",
"values": [["Item", "Qty"], ["pens", 4], ["paper", 2], ["ink", 1]]}
return {"path": self.ep.scope + "/" + args["path"],
"slides": [{"slide_index": i, "shape_texts": [t], "title": t} for i, t in enumerate(TITLES[self.ep.lang][:3])]}
if tool == "libreoffice_save_copy":
dest = self.root / args["destination"]
if dest.exists():
raise FileExistsError(args["destination"])
dest.write_bytes(b"docx copy")
return {"destination": self.ep.scope + "/" + args["destination"], "verified": True, "sha256": _hex(rng, 64),
"source_sha256": _hex(rng, 64)}
if tool in ("observe_windows", "observe_window_layout"):
sid = f"s{_hex(rng, 12)}"
self.snap[args["bundle_id"]] = sid
windows = [dict(w) for w in self.ep.windows]
if tool == "observe_windows":
return {"bundle_id": args["bundle_id"], "running": True, "snapshot_id": sid, "windows": windows}
for w in windows:
w["document_in_approved_folder"] = w["title"] if "." in w["title"] and rng.random() < .5 else None
return {"bundle_id": args["bundle_id"], "running": True, "snapshot_id": sid, "windows": windows,
"screens": [{"index": 0, "primary": True, "frame": [0, 0, 1728, 1117], "visible_frame": [0, 25, 1728, 1050]}]}
if tool in ("move_window", "resize_window", "minimize_window", "restore_window", "focus_window"):
self.snap.pop(args["bundle_id"], None)
return {"verified": True, "window_ref": args["window_ref"], "command": tool.removesuffix("_window")}
if tool in ("resize_layout_window", "tile_windows_side_by_side"):
self.snap.pop(args["bundle_id"], None)
return {"verified": True, "bundle_id": args["bundle_id"], "steps": 1 if tool == "resize_layout_window" else 2}
if tool == "browser_open":
app = args.get("app")
if app not in BROWSER_NAMES:
raise ValueError("Unknown browser app")
session = self.browser.setdefault(app, {"url": args.get("url") or PAGE_URL, "title": PAGE_TITLE,
"snapshots": [], "values": {}})
sid = self._browser_snapshot(app)
return {"app": app, "snapshot_id": sid, "observation": self.page(app)}
if tool in BROWSER_SESSION_TOOLS and args.get("app") in BROWSER_NAMES and args.get("app") not in self.browser:
# runtime_browser._session: every browser tool but browser_open needs an open isolated session
raise ValueError(f"No isolated {BROWSER_NAMES[args['app']]} session is open; use browser_open first")
if tool == "browser_observe":
sid = self._browser_snapshot(args["app"])
return {"app": args["app"], "snapshot_id": sid, "observation": self.page(args["app"])}
if tool in ("browser_fill", "browser_click", "browser_fill_form"):
values = self.browser[args["app"]]["values"]
if tool == "browser_fill":
values[args["target"]] = args.get("value")
elif tool == "browser_fill_form":
values.update({str(k).lstrip("#"): v for k, v in dict(args["fields"]).items()})
sid = self._browser_snapshot(args["app"])
changed = ({"id": args["target"], "value": args.get("value")} if tool == "browser_fill" else
{"fields": dict(args["fields"])} if tool == "browser_fill_form" else {"clicked": args["target"]})
return {"app": args["app"], "snapshot_id": sid, "changed": changed}
if tool == "open_app":
return {"opened": True, "frontmost_matches": True, "bundle_id": args["bundle_id"]}
if tool == "open_file_with_app":
return {"verified": True, "app": args["app"], "path": self.ep.scope + "/" + args["path"]}
return {"executed": False, "error": "ValueError", "message": "Unknown or missing tool argument"}
except Exception as error: # a failed step: nothing changed; runtime reports it like this
return {"executed": False, "error": type(error).__name__, "message": self._rewrite(str(error))}
def _browser_snapshot(self, app: str) -> str:
sid = f"p{_hex(self.rng, 12)}"
self.snap[app] = sid
self.browser[app]["snapshots"].append(sid)
return sid
def page(self, app: str) -> dict:
"""The page view (runtime_browser.present shape) with the values typed so far."""
values = self.browser.get(app, {}).get("values", {})
controls = []
for control in copy.deepcopy(self.ep.info.get("controls", [])):
if control.get("kind") != "button":
control["value"] = values.get(control["id"], control.get("value", ""))
controls.append(control)
return {"title": PAGE_TITLE, "url": PAGE_URL, "controls": controls}
def describe_sessions(self) -> dict:
"""observation["open_sessions"] as assistant.session_summary() builds it: {module name: describe_sessions(ctx)}
for every runtime module that reports something (omitted when nothing is open)."""
out = {}
browsers = []
for app, session in self.browser.items():
entry = {"app": app, "url": session["url"], "title": session["title"],
"current_snapshot_id": session["snapshots"][-1] if session["snapshots"] else None}
view = self.page(app)
entry.update({"tables": [], "controls": view["controls"], "texts": {}})
browsers.append(entry)
if browsers:
out["runtime_browser"] = browsers
for module in SESSION_MODULE_ORDER:
if self.extra_sessions.get(module):
out[module] = copy.deepcopy(self.extra_sessions[module])
return out
def _office_file(self, tool, args):
from mac_laya.fixture_office import docx_bytes, xlsx_bytes
if tool == "create_word_document":
return docx_bytes(str(args["text"]).split("\n"))
if tool == "create_excel_workbook":
return xlsx_bytes(args["rows"])
return b"pptx placeholder"
# ------------------------------------------------------------------ open sessions
PAGE_URL, PAGE_TITLE = "http://127.0.0.1/test/form", "Order form (test page)"
BROWSER_NAMES = {"chrome": "Google Chrome", "firefox": "Firefox"}
BROWSER_SESSION_TOOLS = ("browser_observe", "browser_fill", "browser_select", "browser_check", "browser_click", "browser_fill_form")
# module order of assistant.LOADED_MODULES for the modules that implement describe_sessions
SESSION_MODULE_ORDER = ("runtime_libreoffice", "runtime_obsidian", "runtime_apps", "runtime_ui") # assistant.RUNTIME_MODULES order
VAULTS = ("Notes", "Research", "journal", "工作笔记", "vault-2026")
UI_APPS = {"Notes": "com.apple.Notes", "Reminders": "com.apple.reminders", "TextEdit": "com.apple.TextEdit",
"Finder": "com.apple.finder", "Preview": "com.apple.Preview"}
SESSION_SHARE = 0.35 # candidates that also show other modules' sessions (label-neutral distractors)
def distractor_sessions(rng: random.Random, lang: str) -> dict:
"""Other runtime modules' session summaries, exactly in their describe_sessions() shapes. None of them is
read by a validator of a supported tool (LibreOffice / Obsidian / opened-file / UI sessions only matter for
closing and for their own tools), so they never change a label; they are there so the model learns that.
Held-out (dev/test) apps never appear."""
held = DEV_APPS | TEST_APPS
out = {}
for module in rng.sample(SESSION_MODULE_ORDER, rng.randint(1, 2)):
if module == "runtime_apps":
from mac_laya.runtime_apps import APPS as OPEN_APPS
names = {a.name: a for a in OPEN_APPS.values()}
pool = [(OPEN_FILE_APP_NAME.get(n, n), n) for n in names if OPEN_FILE_APP_NAME.get(n, n) not in held]
entries = []
for _ in range(rng.randint(1, 2)):
short, name = rng.choice(pool)
ext = rng.choice(OPEN_FILE_APPS.get(short, (".txt",)))
entries.append({"app": name, "file": _name(rng, lang, ext, set())})
out[module] = entries
elif module == "runtime_libreoffice":
out[module] = {"app": "LibreOffice", "isolated_profile": True, "running": rng.random() < .8}
elif module == "runtime_obsidian":
out[module] = {"app": "Obsidian", "isolated_profile": True, "vault": rng.choice(VAULTS), "running": rng.random() < .8}
else:
app = rng.choice(sorted(UI_APPS))
out[module] = [{"app": app, "bundle_id": UI_APPS[app], "window": rng.choice(WINDOW_TITLES),
"current_snapshot_id": f"u{_hex(rng, 12)}", "expires_in_seconds": rng.randint(5, 115)}]
return out
OPEN_FILE_APP_NAME = {"Microsoft Word": "Word", "Microsoft Excel": "Excel", "Microsoft PowerPoint": "PowerPoint"}
# ------------------------------------------------------------------ gate candidates
SITUATIONS = ("clean", "skip_obs", "stale", "consumed", "collision", "missing_src", "wrong_path", "outside",
"off_intent", "unregistered", "noise", "shifted", "truncated_listing", "symlink", "wrong_app", "no_submit",
"long_history")
LONG_LINES = {"en": ("Quarterly notes: revenue flat, costs down 3%, hiring paused until March.",
"Action items: renew the licence, archive the 2024 invoices, check the backup drive.",
"Customer feedback was mostly positive; two complaints about late delivery."),
"zh": ("季度记录:收入持平,成本下降百分之三,招聘暂停到三月。", "待办事项:续签许可证,归档二〇二四年的发票,检查备份硬盘。",
"客户反馈大多正面,有两条关于延迟交付的投诉。")}
# ------------------------------------------------------------------ very long observation states (25K requirement)
# User requirement 2026-09-24: the gate must read 25,000-token inputs (engineering max 25,600 tokens in total). The
# 'xl_history' modifier adds several earlier results that are long IN THE RUNTIME'S OWN SHAPES: list_files of big
# sub-folders (FileScope lists the first 100 sorted names and sets "truncated": true), read_text of long notes
# (FileScope returns text[:12000] and "truncated"), read_office_document pages (office_reader.page: <= 50 items,
# 3,000 characters per item, 12,000 per page, "content_truncated" / "page_has_more"), in English and Chinese. The view
# then fits them into gate.HISTORY_TOKEN_BUDGET (~20K) with its explicit markers. They are reads of OTHER folders and
# files (never the episode's own sources, outputs or their folders), so the base situation's rule evidence -- and
# therefore the oracle label -- is unchanged by the length; the builder balances labels within the long rows too.
XL_TARGETS = ((7600, 11600), (11600, 15600), (15600, 22500)) # history tokens added (strata; the view cuts > budget)
XL_TARGET_WEIGHTS = (1.0, 1.0, 1.6) # the top stratum loses rows to the view's halving cut (> budget -> ~15-17K)
XL_MAX_ENTRIES = 11 # assistant.max_steps = 12: at most 11 earlier results before the proposed step
XL_STEP_SHARE = 1.0 # steps that get an xl variant of one of their situations (a second one: XL_SECOND)
XL_SECOND = .5
XL_OTHER_LANG = .3 # share of long documents written in the other language (en <-> zh)
XL_WORDS = {"en": ("invoice", "shipment", "renewal", "backup", "contract", "survey", "workshop", "deadline", "budget line",
"vendor", "migration", "audit", "handover", "prototype", "travel claim", "rota", "lab result"),
"zh": ("发票", "发货", "续约", "备份", "合同", "问卷", "工作坊", "截止日期", "预算科目", "供应商", "迁移", "审计",
"交接", "原型", "差旅报销", "排班", "化验结果")}
XL_PEOPLE = {"en": ("Dana", "Priya", "Tom", "Lena", "Jordan", "Kai", "Sam", "Alex"),
"zh": ("王老师", "李娜", "陈晨", "赵磊", "张敏", "刘洋", "周婷", "孙浩")}
XL_CITIES = ("Hangzhou", "Oslo", "Lima", "Sydney", "Porto", "Nairobi", "杭州", "成都", "深圳")
def _xl_line(rng, lang) -> str:
w = lambda: rng.choice(XL_WORDS[lang]) # noqa: E731
p = lambda: rng.choice(XL_PEOPLE[lang]) # noqa: E731
date = f"2026-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}"
kind = rng.random()
if lang == "zh":
if kind < .25:
return f"{date} {p()}:{w()}已处理,{w()}还差{rng.randint(2, 40)}项,下周{rng.choice('一二三四五')}前再确认。"
if kind < .45:
return f"- [ ] {w()}(负责人:{p()},截止 {date})"
if kind < .65:
return f"{w()},{rng.randint(1, 300)},{rng.randint(5, 9999)}.{rng.randint(0, 99):02d},{rng.choice(XL_CITIES)}"
if kind < .75:
return "## " + rng.choice(TITLES["zh"])
return rng.choice(LONG_LINES["zh"] + TEXTS["zh"]) + f"({w()},编号 {_hex(rng, 5)})"
if kind < .25:
return f"{date} {p()}: the {w()} is done, {rng.randint(2, 40)} {w()} items still open, confirm by {rng.choice(('Mon', 'Tue', 'Wed', 'Thu', 'Fri'))}."
if kind < .45:
return f"- [ ] {w()} (owner: {p()}, due {date})"
if kind < .65:
return f"{w()},{rng.randint(1, 300)},{rng.randint(5, 9999)}.{rng.randint(0, 99):02d},{rng.choice(XL_CITIES)}"
if kind < .75:
return "## " + rng.choice(TITLES["en"])
return rng.choice(LONG_LINES["en"] + TEXTS["en"]) + f" ({w()}, ref {_hex(rng, 5)})"
def _xl_text(rng, lang, n_chars: int) -> str:
lines, size = [], 0
while size < n_chars:
line = _xl_line(rng, lang)
lines.append(line)
size += len(line) + 1
return "\n".join(lines)
def _xl_name(rng, lang, ext) -> str:
stem = rng.choice(STEMS[lang if rng.random() < .8 else "en"])
return f"{stem}{rng.choice(NAME_SEPS)}{rng.choice(('2025', '2026', 'q1', 'q2', 'q3', 'q4', 'old', 'full', 'all'))}_{_hex(rng, 3)}{ext}"
def _xl_folder(runner: Runner, rng, lang, protect) -> Path:
for _ in range(20):
name = rng.choice(FOLDERS[lang]) + rng.choice(("", "_", "-")) + rng.choice(("2024", "2025", "all", "big", "scans", "export"))
path = runner.root / name
if name not in protect and not path.exists():
path.mkdir()
return path
path = runner.root / f"xl_{_hex(rng, 6)}"
path.mkdir()
return path
def xl_entries(runner: Runner, rng, target_tokens: int, room: int, count_tokens=None, now: float = 0.0) -> list:
"""Long earlier results in the runtime's shapes (see XL_TARGETS) until about ``target_tokens`` view tokens.
Returns [action, result, at_unix] triples; never touches the episode's own sources, outputs or their folders."""
from . import view as V
count = count_tokens or V.approx_tokens
ep = runner.ep
protect = set()
for rel in list(ep.info.get("sources", [])) + list(ep.info.get("dests", [])) + [ep.info.get("dir")]:
if isinstance(rel, str):
protect.add(rel)
protect.update(_ancestors(rel))
out, total = [], 0
while total < target_tokens and len(out) < room:
lang = ep.lang if rng.random() >= XL_OTHER_LANG else ("zh" if ep.lang == "en" else "en")
remaining = target_tokens - total
# characters per Qwen3.5 token of _xl_text (measured: en ~2.5, zh ~1.3); sizes the last entries so the
# length strata of XL_TARGETS are actually reached instead of overshooting by one 9K-token Chinese read
ratio = 1.3 if lang == "zh" else 2.5
kind = rng.random() if remaining > 2500 else rng.choice((.1, .1, .5))
if kind < .28:
folder = _xl_folder(runner, rng, lang, protect)
for _ in range(rng.randint(0, 4)):
(folder / _xl_name(rng, lang, rng.choice((".txt", ".md")))).write_bytes(b"x\n")
ext = rng.choice((".pdf", ".jpg", ".png", ".docx", ".xlsx", ".txt", ".mp3"))
runner.phantom_dirs[str(folder)] = sorted({_xl_name(rng, lang if rng.random() < .8 else "en", ext if rng.random() < .7 else
rng.choice((".pdf", ".txt", ".png")))
for _ in range(rng.randint(101, 420))})
action = _fix_args(_list(lang, rng, folder.name))
elif kind < .72:
folder = runner.root if rng.random() < .5 else _xl_folder(runner, rng, lang, protect)
name = _xl_name(rng, lang, rng.choice((".md", ".txt", ".log", ".csv")))
natural = rng.choice((rng.randint(2500, 11000), rng.randint(12500, 60000)))
size = natural if natural > 12000 and remaining * ratio > 12000 else int(min(natural, max(1200, remaining * ratio)))
(folder / name).write_text(_xl_text(rng, lang, size))
action = _fix_args(_act("read_text", lang, rng, path=str((folder / name).relative_to(runner.root))))
else:
folder = runner.root if rng.random() < .5 else _xl_folder(runner, rng, lang, protect)
name = _xl_name(rng, lang, ".docx")
per = max(1, min(12, int(remaining * ratio / 40 / 110))) # ~40 paragraphs a page, ~110 chars a line
paragraphs = [" ".join(_xl_line(rng, lang) for _ in range(rng.randint(1, per))) for _ in range(rng.randint(25, 90))]
from mac_laya.fixture_office import docx_bytes
(folder / name).write_bytes(docx_bytes(paragraphs))
action = _fix_args(_act("read_office_document", lang, rng, path=str((folder / name).relative_to(runner.root)),
section="", offset=rng.choice((0, 0, 0, 10, 20)), limit=rng.choice((20, 30, 40, 50))))
result = runner.run(action)
at = now - rng.randint(20, 900)
entry = runtime_entry(action, result, at)
total += count(json.dumps(V.history_entry(entry, ep.scope, now), ensure_ascii=False))
out.append([action, result, at])
return out
# ------------------------------------------------------------------ read steps without history (review 2026-09-24)
# The read|no_history cell was 84% execute (cap .75): the only no-history 'ask' reads were outside paths. These are
# the other runtime-refused reads a gate sees WITHOUT any history (labels still come from the oracle): a file type the
# reader cannot open (office_reader / runtime_office_apps / runtime_data), an Office-app read the goal does not imply
# (runtime_office_apps.validate INTENT), and query_table on a browser page when no isolated page is open.
WRONG_TYPE = {"read_office_document": (".pdf", ".odt", ".txt", ".csv", ".rtf", ".doc", ".xls", ".pages"),
"read_word_document": (".xlsx", ".pdf", ".doc", ".odt", ".txt"),
"read_excel_workbook": (".csv", ".docx", ".xls", ".numbers", ".pdf"),
"read_powerpoint_deck": (".key", ".pdf", ".docx", ".ppt"),
"query_table": (".csv", ".pdf", ".txt", ".pptx", ".xls", ".numbers")}
APP_READER = {".docx": "read_word_document", ".xlsx": "read_excel_workbook", ".pptx": "read_powerpoint_deck"}
READ_STEP_TOOLS = ("read_text", "read_office_document", "read_word_document", "read_excel_workbook", "read_powerpoint_deck",
"query_table")
READ_NO_HISTORY = {"skip_obs+outside": .6, "skip_obs+wrong_type": .7, "skip_obs+app_reader": .6, "skip_obs+browser_source": .6}
def _noise_entries(runner: Runner, rng, lang, n):
"""Earlier observations that do not show this step's own files, shaped like real repeated observations: mostly
SUCCESSFUL listings of sub-folders and reads of other files (v2 noise failed ~70% of the time, so the shape of the
first history result -- an error vs a listing -- predicted 'inspect' for mutations: layout shortcut), plus some
failed reads of absent names and tools refused as unavailable. Never reads or lists the episode's own sources,
outputs or their folders."""
protect = set()
for rel in list(runner.ep.info.get("sources", [])) + list(runner.ep.info.get("dests", [])) + [runner.ep.info.get("dir")]:
if isinstance(rel, str):
protect.add(rel)
protect.update(ancestor for ancestor in _ancestors(rel))
out = []
for _ in range(n):
kind = rng.random()
if kind < .45:
folder = _noise_folder(runner, rng, lang, protect)
action = _fix_args(_list(lang, rng, folder))
elif kind < .8:
action = _fix_args(_act("read_text", lang, rng, path=_noise_file(runner, rng, lang, protect)))
elif kind < .9:
name = _name(rng, lang, ".txt", set(protect))
action = _fix_args(_act("read_text", lang, rng, path=name))
else:
tool = rng.choice(UNREGISTERED_TOOLS)
arguments = {"path": _name(rng, lang, ".txt", set())}
action = {"tool": tool, "arguments": arguments, "reason": reason_for(tool, arguments, lang, rng)}
out.append((action, {"executed": False, "refused": "tool_unavailable_for_this_request",
"message": f"{action['tool']!r} is not available for this request; choose one of the listed TOOLS"}))
continue
out.append((action, runner.run(action)))
return out
def _ancestors(rel: str) -> list:
parts = rel.split("/")
return ["/".join(parts[:i]) for i in range(1, len(parts))]
def _noise_folder(runner: Runner, rng, lang, protect) -> str:
"""An existing sub-folder that is not the episode's own (created on the fly, with a few files, if none)."""
existing = sorted(str(p.relative_to(runner.root)) for p in runner.root.iterdir()
if p.is_dir() and not p.is_symlink() and p.name not in protect and not p.name.endswith("_all"))
if existing and rng.random() < .6:
return rng.choice(existing)
for _ in range(20):
name = rng.choice(FOLDERS[lang]) + rng.choice(DIR_SUFFIXES)
path = runner.root / name
if name not in protect and not path.is_symlink() and (path.is_dir() or not path.exists()):
break
else:
return rng.choice(existing) if existing else rng.choice(FOLDERS[lang])
path.mkdir(exist_ok=True)
for _ in range(rng.randint(0, 3)):
(path / _name(rng, lang, rng.choice((".txt", ".md", ".pdf")), set())).write_bytes(b"old\n")
return name
def _noise_file(runner: Runner, rng, lang, protect) -> str:
"""Another existing text file in the folder (a distractor), or one inside a noise sub-folder."""
files = sorted(str(p.relative_to(runner.root)) for p in runner.root.rglob("*")
if p.is_file() and not p.is_symlink() and p.suffix in (".txt", ".md", ".csv")
and str(p.relative_to(runner.root)) not in protect and "_all/" not in str(p.relative_to(runner.root)))
if files and rng.random() < .7:
return rng.choice(files)
folder = _noise_folder(runner, rng, lang, protect)
if not (runner.root / folder).is_dir():
return rng.choice(files) if files else _name(rng, lang, ".txt", set(protect))
name = f"{folder}/{_name(rng, lang, rng.choice(('.txt', '.md')), set())}"
if not (runner.root / name).exists():
(runner.root / name).write_text(_text(rng, lang))
return name
def _perturb_path(value, rng, lang, mode, scope):
"""A wrong path: outside the scope, or a near-miss / unrelated name (never a case-only change,
which macOS treats as the same file)."""
if not isinstance(value, str) or value == "":
return None
if value == ".":
# the scope itself (list_files "."): outside -> a parent / another folder; wrong -> a folder or file name
if mode == "outside":
return rng.choice(("..", f"../{rng.choice(FOLDERS[lang])}", f"/Users/{rng.choice(USERS)}/Desktop", "/tmp",
f"{scope}/..", "/Volumes/USB", f"{scope}-old"))
return rng.choice(FOLDERS[lang]) + rng.choice(DIR_SUFFIXES)
if mode == "outside":
return rng.choice((f"../{value}", f"/Users/{rng.choice(USERS)}/Desktop/{value}", "/etc/hosts", f"{scope}/../{value}",
f"/tmp/{value}", f"/Volumes/USB/{value}", f"{scope}-old/{value}"))
head, _, base = value.rpartition("/")
stem, dot, ext = base.rpartition(".")
if not dot:
root = next((base[:-len(t)] for t in sorted(DIR_SUFFIXES[1:], key=len, reverse=True)
if base.endswith(t) and len(base) > len(t)), base)
options = [root + rng.choice(DIR_SUFFIXES), rng.choice(FOLDERS[lang]) + rng.choice(DIR_SUFFIXES),
rng.choice(FOLDERS[lang])]
else:
root = stem
tails = sorted({sep + suffix for sep in NAME_SEPS for suffix in NAME_SUFFIXES[1:]}, key=len, reverse=True)
for tail in tails: # strip a legitimate suffix (longest first), then add a different one
if stem.endswith(tail) and len(stem) > len(tail):
root = stem[:-len(tail)]
break
root = root.rstrip("_-") or stem
options = [f"{root}{rng.choice(NAME_SEPS)}{rng.choice(NAME_SUFFIXES[1:])}.{ext}", f"{root}.{ext}",
_name(rng, lang, "." + ext, {base})]
for _ in range(20):
new = rng.choice(options)
if new.casefold() != base.casefold():
return (head + "/" if head else "") + new
return None
OFF_INTENT = {"copy_file": ("move_file", "archive_files"), "move_file": ("copy_file",), "write_text": ("create_word_document",),
"archive_files": ("move_file",), "create_word_document": ("write_text",), "create_excel_workbook": ("write_text",),
"create_powerpoint_deck": ("write_text",), "read_text": ("move_file", "write_text"),
"read_office_document": ("write_text", "move_file"), "make_directory": ("move_file",),
"list_files": ("make_directory",), "open_file_with_app": ("open_app",)}
# Compound situations (review 2026-09-24, G1 "layout predicts the label"): a history modifier combined with a
# proposal modifier, so that within every (tool family x history present) cell the labels are as mixed as the
# rules allow (e.g. a wrong or outside path with NO history is still "ask"; an unrelated history is "inspect").
COMBO_HISTORY = ("skip_obs", "unrelated", "root_listed", "noise")
LONG_COMBO_SHARE = .2 # compound situations that also carry long earlier results (length is not a label cue)
COMBO_PROPOSAL = ("wrong_path", "outside", "off_intent", "unregistered", "wrong_app", "symlink", "collision", "missing_src")
BROWSER_SITUATIONS = ("no_session", "other_session", "old_snapshot")
READ_ONLY_TOOL_NAMES = {"list_files", "read_text", "read_office_document", "read_word_document", "read_excel_workbook",
"read_powerpoint_deck", "query_table", "observe_windows", "observe_window_layout", "browser_observe"}
OBSERVING = {"list_files", "read_text", "read_office_document", "read_excel_workbook", "read_word_document",
"read_powerpoint_deck", "query_table", "observe_windows", "observe_window_layout", "browser_observe", "browser_open"}
def gate_candidates(ep: Episode, rng: random.Random, per_step: int = 3, reason_bank_share: float = 0.0,
count_tokens=None, xl_share: float = XL_STEP_SHARE):
"""Yield (situation, step_index, raw_observation, proposed_action, now) tuples. A situation is one name
from SITUATIONS or 'history+proposal' (COMBO_*), optionally '+xl_history' (very long earlier results; token
targets are measured with ``count_tokens`` when given, else view.approx_tokens)."""
out = []
pool = SITUATIONS + (BROWSER_SITUATIONS if ep.family == "browser_form" else ())
for k in range(len(ep.plan)):
situations = rng.sample(pool, min(per_step, len(pool)))
if "clean" not in situations and rng.random() < .5:
situations[0] = "clean"
if k > 0 and "skip_obs" not in situations and rng.random() < .5:
situations[-1] = "skip_obs"
if "long_history" not in situations and rng.random() < .2:
situations.append("long_history")
# compound situations: more of them for the steps whose (tool family x history) cells are otherwise
# one-sided (read-only observations are execute unless a path/app is wrong; Office creation and window
# actions without history are inspect unless a path/app is wrong)
tool = ep.plan[k]["tool"]
one_sided = tool in READ_ONLY_TOOL_NAMES or tool.startswith(("create_", "observe_")) or tool.endswith("_window") \
or tool in ("tile_windows_side_by_side", "open_app")
for _ in range(4 if one_sided else 2):
if rng.random() < .7:
combo = rng.choice(COMBO_HISTORY) + "+" + rng.choice(COMBO_PROPOSAL)
if rng.random() < LONG_COMBO_SHARE:
combo += "+long_history"
situations.append(combo)
# long earlier results must not mean "execute" (adversarial review 2026-09-24: v3 long_history rows were
# 1492/1501 execute, so the state's token length alone predicted the label): they also sit next to a history
# that does not show this step's sources, or under a proposal modifier. They are token-expensive, so the
# builder caps the share of long rows it selects (builders.mac_gate.LONG_SHARE_CAP).
if rng.random() < LONG_COMBO_SHARE:
situations.append(rng.choice(("skip_obs", "unrelated")) + "+long_history")
if ep.family == "browser_form" and tool != "browser_observe":
situations += [s for s in ("old_snapshot", "consumed") if s not in situations and rng.random() < .6]
if tool in READ_STEP_TOOLS and k > 0:
# reads WITHOUT history that the runtime refuses (review 2026-09-24: read|no_history was 84% execute)
situations += [s for s, p in READ_NO_HISTORY.items() if rng.random() < p]
if rng.random() < xl_share:
# the same situations with very long earlier results (25K requirement): length never decides the label
base = [s for s in situations if "shifted" not in s and "xl_history" not in s]
if base:
for pick in rng.sample(base, min(len(base), 2 if rng.random() < XL_SECOND else 1)):
situations.append(pick + "+xl_history")
for situation in situations:
item = _candidate(ep, rng, k, situation, reason_bank_share, count_tokens)
if item is not None:
out.append((situation, k, *item))
return out
def _candidate(ep: Episode, rng: random.Random, k: int, situation: str, reason_bank_share: float = 0.0,
count_tokens=None):
parts = set(situation.split("+"))
if "xl_history" in parts and "shifted" in parts:
return None # the round-1 last-four window cannot carry a long history
files = dict(ep.files)
target = ep.plan[k]
tool = target["tool"]
args = target.get("arguments", {})
sources = list(ep.info.get("sources", []))
dests = list(ep.info.get("dests", []))
if "collision" in parts:
cand = [d for d in dests if d in (args.get("destination"), args.get("path"))]
if not cand or any(r.startswith(cand[0] + "/") for r in files):
return None # (a distractor folder of that name already exists: not a file collision)
files[cand[0]] = b"already here\n"
if "missing_src" in parts:
cand = [s for s in sources if s in json.dumps(args, ensure_ascii=False)]
if not cand:
return None
files.pop(cand[0], None)
phantom = []
long_files = []
if "long_history" in parts:
# Long earlier results (a read of a long text, a big sub-folder listing) that the view must fit into
# its token budget with explicit truncation markers; the full history is kept (patched runtime).
for _ in range(rng.randint(1, 3)):
name = f"{rng.choice(STEMS[ep.lang])}_{_hex(rng, 3)}.md"
lines = [rng.choice(LONG_LINES[ep.lang if rng.random() < .8 else "en"]) for _ in range(rng.randint(60, 420))]
files[name] = "\n".join(lines).encode()
long_files.append(name)
if "truncated_listing" in parts:
if not any(isinstance(v, str) and "." in v for v in args.values()):
return None
phantom = [f"{rng.choice(('scan', 'IMG', 'page', '扫描'))}_{i:04d}.{rng.choice(('png', 'jpg', 'pdf'))}"
for i in range(rng.randint(101 - len(files), 160))]
if "symlink" in parts:
paths = [v for key, v in args.items() if key in ("source", "path", "destination", "directory")
and isinstance(v, str) and v != "."]
if not paths:
return None
for rel in [r for r in files if r.startswith(paths[0] + "/")]:
files.pop(rel) # a symlinked folder has no real children
files[paths[0]] = "symlink"
browser = ep.family == "browser_form"
if not browser and parts & set(BROWSER_SITUATIONS):
return None
runner = Runner(ep, rng, files)
runner.phantom = phantom
try:
now = 1_790_000_000.0 + rng.randint(0, 10_000_000)
history = [] # (action, result, age)
t = now - rng.randint(20, 90) * max(1, k)
if browser:
key = ep.info["browser"]
if "other_session" in parts:
key = "firefox" if key == "chrome" else "chrome"
if "no_session" not in parts:
# the page was opened earlier in this task (browser_open is a confirmed mutation)
action = _fix_args(_act("browser_open", ep.lang, rng, app=key, url=PAGE_URL))
result = runner.run(action)
if rng.random() < .7:
history.append([action, result, t - rng.randint(5, 60)])
for j in range(k):
action = runner.resolve_placeholders(ep.plan[j])
result = runner.run(action)
history.append([action, result, t])
t += rng.randint(3, 40)
if "root_listed" in parts and not any(h[0]["tool"] == "list_files" and h[0]["arguments"].get("directory") == "."
for h in history):
# the planner listed the approved folder earlier (only added when the history has no such listing, so
# the history length does not differ from the clean case)
action = _fix_args(_list(ep.lang, rng))
history.insert(0, [action, runner.run(action), now - rng.randint(20, 300)])
if "noise" in parts:
# the patched runtime sends the FULL history (up to max_steps=12 entries), not the last four
noise = _noise_entries(runner, rng, ep.lang, rng.choice((1, 1, 2, 2, 3, 4, 6, 8)))
for action, result in noise:
history.insert(rng.randint(0, len(history)), [action, result, now - rng.randint(5, 300)])
if "shifted" in parts:
# Round-1 runtime window: only the last four results are passed, so an early observation
# can drop out of the visible history.
noise = _noise_entries(runner, rng, ep.lang, rng.randint(2, 4))
history.extend([a, r, now - rng.randint(5, 60)] for a, r in noise)
history = history[-4:]
if "skip_obs" in parts or "unrelated" in parts:
if "skip_obs" in parts and not any(h[0]["tool"] in OBSERVING for h in history):
return None
history = [h for h in history if h[0]["tool"] not in OBSERVING]
if "unrelated" in parts:
# a history that is present but does not show what this step needs (other folders, other files,
# refused tools): mutations stay "inspect", window/browser steps depend on the session state
for action, result in _noise_entries(runner, rng, ep.lang, rng.choice((1, 1, 1, 2, 2, 3, 4, 6))):
history.insert(rng.randint(0, len(history)), [action, result, now - rng.randint(5, 300)])
if "long_history" in parts:
if not long_files:
return None
extra = []
for name in long_files:
action = _fix_args(_act("read_text", ep.lang, rng, path=name))
extra.append([action, runner.run(action), now - rng.randint(30, 400)])
if rng.random() < .5:
folder = rng.choice(FOLDERS[ep.lang]) + "_all"
big = {f"{folder}/{rng.choice(('scan', 'IMG', 'doc'))}_{i:03d}.{rng.choice(('png', 'pdf', 'txt'))}": b"x" for i in range(rng.randint(40, 99))}
for rel in big:
(runner.root / rel).parent.mkdir(parents=True, exist_ok=True)
(runner.root / rel).write_bytes(b"x")
action = _fix_args(_list(ep.lang, rng, folder))
extra.append([action, runner.run(action), now - rng.randint(30, 400)])
history = extra + history # (after skip_obs / unrelated: those filters must not remove them)
if "xl_history" in parts:
room = XL_MAX_ENTRIES - len(history)
if room < 1:
return None
low, high = rng.choices(XL_TARGETS, weights=XL_TARGET_WEIGHTS)[0]
extra = xl_entries(runner, rng, rng.randint(low, high), room, count_tokens, now)
for entry in extra: # interleaved; the plan's own results keep their order
history.insert(rng.randint(0, len(history)), entry)
proposal = runner.resolve_placeholders(target)
# ages: stale snapshots are older than 120 s
ages = []
for h in history:
ages.append(max(1, int(now - h[2])))
if ages:
base_age = rng.randint(2, 100)
ages = [base_age + (len(ages) - 1 - i) * rng.randint(2, 15) for i in range(len(ages))]
if "stale" in parts:
snaps = [i for i, h in enumerate(history) if h[0]["tool"] in ("observe_windows", "observe_window_layout")]
if not snaps:
return None
for i in range(0, snaps[-1] + 1):
ages[i] = max(ages[i], rng.randint(125, 3600))
if "consumed" in parts:
if tool not in ("move_window", "resize_window", "minimize_window", "restore_window", "focus_window",
"resize_layout_window", "tile_windows_side_by_side", "browser_fill", "browser_click",
"browser_fill_form"):
return None
old = copy.deepcopy(proposal)
prev = runner.run(proposal) # the same action already ran; the snapshot is used up
history.append([old, prev, now - 3])
ages.append(rng.randint(3, 30))
pargs = proposal.get("arguments", {})
if "old_snapshot" in parts:
# a browser action that carries an earlier page snapshot_id (the page changed since)
snaps = runner.browser.get(pargs.get("app"), {}).get("snapshots", [])
if "snapshot_id" not in pargs or len(snaps) < 2:
return None
pargs["snapshot_id"] = rng.choice(snaps[:-1])
if parts & {"wrong_path", "outside"}:
mode = "outside" if "outside" in parts else "wrong_path"
keys = [key for key in ("source", "path", "destination", "directory") if isinstance(pargs.get(key), str)]
if tool == "archive_files":
keys = ["paths"] if mode == "wrong_path" else ["destination"]
if not keys:
return None
key = rng.choice(keys)
original = pargs[key][0] if key == "paths" else pargs[key]
if key == "directory" and original == "." and mode == "wrong_path" and rng.random() < .4:
names = [n for n in files if "/" not in n and files[n] not in (None, "symlink")]
changed = rng.choice(names) if names else None # a file where a folder is expected
else:
changed = _perturb_path(original, rng, ep.lang, mode, ep.scope)
if changed is None:
return None
if key == "paths":
pargs["paths"] = [changed] + pargs["paths"][1:]
else:
pargs[key] = changed
if "wrong_type" in parts:
key = "source" if tool == "query_table" else "path"
if tool not in WRONG_TYPE or not isinstance(pargs.get(key), str):
return None
stem, ext = posixpath.splitext(pargs[key])
pargs[key] = stem + rng.choice([e for e in WRONG_TYPE[tool] if e != ext.lower()])
if "app_reader" in parts:
path = pargs.get("path") if tool == "read_office_document" else pargs.get("source") if tool == "query_table" else None
new_tool = APP_READER.get(posixpath.splitext(path)[1].lower()) if isinstance(path, str) else None
if new_tool is None:
return None
proposal = {"tool": new_tool, "arguments": {"path": path}}
pargs = proposal["arguments"]
if "browser_source" in parts:
if tool != "query_table":
return None
pargs["source"] = rng.choice(("chrome", "firefox", "Google Chrome", "chrome"))
if "off_intent" in parts:
if tool not in OFF_INTENT:
return None
new = rng.choice(OFF_INTENT[tool])
proposal = _retool(proposal, new, ep, rng)
if "unregistered" in parts:
if "bundle_id" in pargs and rng.random() < .6:
pargs["bundle_id"] = rng.choice(UNREGISTERED_BUNDLES)
else:
proposal = {"tool": rng.choice(UNREGISTERED_TOOLS), "arguments": copy.deepcopy(pargs)}
if "wrong_app" in parts:
# the substituted (wrong) app is never a held-out dev/test app: otherwise every train row that shows
# Calculator/VLC/Safari/VS Code is an 'ask' (data audit 2026-09-24: 198 train rows, 100% ask), which
# teaches "held-out app -> ask" and biases the unseen_app dev/test groups
held = DEV_APPS | TEST_APPS
if "bundle_id" in pargs:
others = [b for a, b in WINDOW_APP_POOL.items() if b != pargs["bundle_id"] and a not in held]
pargs["bundle_id"] = rng.choice(others)
elif tool == "open_file_with_app":
pargs["app"] = rng.choice([a for a in OPEN_FILE_APPS if a != pargs["app"] and a not in held])
elif "app" in pargs:
pargs["app"] = "firefox" if pargs["app"] == "chrome" else "chrome"
else:
return None
if "no_submit" in parts:
if ep.family != "browser_form" or tool != "browser_click":
return None
if rng.random() < SESSION_SHARE:
runner.extra_sessions = distractor_sessions(rng, ep.lang)
raw_history = [runtime_entry(action, result, now - age) for (action, result, _), age in zip(history, ages)]
proposal = finalize_reasons(proposal, raw_history, ep.lang, rng, reason_bank_share)
observation = raw_observation(ep.scope, raw_history, runner.describe_sessions())
return observation, proposal, now
finally:
runner.close()
REASON_SHARE = 0.15 # share of rows whose actions carry a planner "reason" (the runtime planner emits none)
def runtime_entry(action: dict, result: Any, at_unix: float) -> dict:
"""A history entry shaped like assistant.plan() records it: mutating tools only run after the user's
one-use confirmation, so their entries carry ``explicit_user_confirmation`` (view: ``confirmed_by_user``)."""
from mac_laya.assistant import MUTATIONS
entry = {"action": action, "result": result, "at_unix": at_unix}
if action.get("tool") in MUTATIONS:
entry["explicit_user_confirmation"] = True
return entry
def finalize_reasons(proposal: dict, raw_history: list, lang: str, rng: random.Random, bank_share: float = 0.0) -> dict:
"""Reasons as the runtime would show them. The local planner returns only {tool, arguments}; in
REASON_SHARE of rows a reason is kept, always regenerated from the FINAL tool and arguments (so a
perturbed path, app or tool never leaves a mismatching reason behind). With ``bank_share`` > 0 (train
only) that share of the regenerated reasons is drawn from the teacher-paraphrased reason bank
(``mac_goal_paraphrase`` kind=reason, same tool, same placeholders)."""
proposal = copy.deepcopy(proposal)
keep = rng.random() < REASON_SHARE
for entry in raw_history:
action = entry["action"]
if keep:
action["reason"] = reason_for(action.get("tool"), action.get("arguments"), lang, rng, bank_share)
else:
action.pop("reason", None)
if keep:
proposal["reason"] = reason_for(proposal.get("tool"), proposal.get("arguments"), lang, rng, bank_share)
else:
proposal.pop("reason", None)
return proposal
def _retool(proposal, new, ep, rng):
args = proposal.get("arguments", {})
first = next((v for v in args.values() if isinstance(v, str)), "x.txt")
if isinstance(args.get("paths"), list):
first = args["paths"][0]
if new == "move_file":
a = {"source": args.get("source", first), "destination": args.get("destination", _name(rng, ep.lang, ".txt", set()))}
elif new == "copy_file":
a = {"source": args.get("source", first), "destination": args.get("destination", _name(rng, ep.lang, ".txt", set()))}
elif new == "archive_files":
a = {"paths": [args.get("source", first)], "destination": _name(rng, ep.lang, ".zip", set())}
elif new == "write_text":
a = {"path": args.get("destination", args.get("path", first)), "text": args.get("text", _text(rng, ep.lang))}
if isinstance(a["text"], list):
a["text"] = json.dumps(a["text"], ensure_ascii=False)
elif new == "create_word_document":
a = {"destination": args.get("path", first).rsplit(".", 1)[0] + ".docx", "text": args.get("text", _text(rng, ep.lang))}
elif new == "make_directory":
a = {"path": rng.choice(FOLDERS[ep.lang]) + "_new"}
elif new == "open_app":
from mac_laya.runtime_apps import resolve_app
a = {"bundle_id": resolve_app(args.get("app")) or "com.apple.Preview"}
else:
a = dict(args)
return {"tool": new, "arguments": a, "reason": reason_for(new, a, ep.lang, rng)}
def raw_observation(scope: str, history: list, sessions: dict | None = None) -> dict:
"""What assistant.plan() builds (before the view): the full registry, all window aliases, history, and
``open_sessions`` only when some runtime module reports an open session (``if sessions: ...``)."""
from mac_laya.assistant import APPS
from mac_laya.runtime_windows import WINDOW_APPS
observation = {"approved_scope": scope, "registered_app_ids": sorted(set(APPS.values())), "window_app_aliases": WINDOW_APPS,
"previous_results": history}
if sessions:
observation["open_sessions"] = sessions
return observation
# ------------------------------------------------------------------ goal-done states
def goal_done_candidates(ep: Episode, rng: random.Random):
"""Yield (variant, raw_observation, fixture_root_check) for the goal-done shadow question.
Variants: full correct plan, a strict prefix (missing output), a destructive variant (move instead of
copy), a wrong-content variant, and an extra-output variant. Each is executed on a fresh fixture;
the label comes from the runtime's independent verifiers on the resulting folder.
"""
from mac_laya.system_file_verifier import FILE_FAMILIES, snapshot, verify_files
if ep.spec is None:
return []
out = []
variants = ["full", "prefix", "extra", "wrong_content", "destructive"]
for variant in rng.sample(variants, 3):
plan = [copy.deepcopy(a) for a in ep.plan]
if variant == "prefix":
if len(plan) < 2:
continue
plan = plan[:rng.randint(1, len(plan) - 1)]
elif variant == "extra":
taken = set(ep.files) | set(ep.info.get("dests", []))
plan.append(_fix_args(_act("write_text", ep.lang, rng, path=_name(rng, ep.lang, ".txt", taken), text=_text(rng, ep.lang))))
elif variant == "wrong_content":
last = plan[-1]
if last["tool"] in ("write_text", "create_word_document"):
last["arguments"]["text"] = _wrong_text(last["arguments"]["text"], ep.lang, rng)
elif last["tool"] == "create_excel_workbook":
rows = [list(r) for r in last["arguments"]["rows"]]
if len(rows) > 2 and rng.random() < .5:
rows.pop(rng.randrange(1, len(rows)))
else:
i = rng.randrange(1, len(rows)) if len(rows) > 1 else 0
rows[i][-1] = (rows[i][-1] + rng.randint(1, 9)) if isinstance(rows[i][-1], int) else rows[i][-1] + "s"
last["arguments"]["rows"] = rows
else:
continue
elif variant == "destructive":
idx = [i for i, a in enumerate(plan) if a["tool"] == "copy_file"]
if not idx:
continue
a = plan[idx[0]]
plan[idx[0]] = {"tool": "move_file", "arguments": dict(a["arguments"]), "reason": a.get("reason", "")}
runner = Runner(ep, rng)
try:
before = snapshot(runner.root)
now = 1_790_000_000.0 + rng.randint(0, 10_000_000)
history, events = [], []
for j, action in enumerate(plan):
action = runner.resolve_placeholders(action)
result = runner.run(action)
history.append(runtime_entry(action, result, now - 10 * (len(plan) - j)))
real = {**result}
if "destination" in real and isinstance(real["destination"], str):
real["destination"] = real["destination"].replace(ep.scope, str(runner.root))
events.append({"actor": "real_tool_executor", "action": action, "result": real})
history = _with_readonly_noise(history, runner, ep, rng, now)
row = {**ep.spec, "family": ep.family}
if ep.family in FILE_FAMILIES:
verdict = verify_files(row, runner.root, before, {})
else:
verdict = _verify_office(row, runner.root, before, events)
done = {"tool": "done", "arguments": {"summary": "Finished." if ep.lang == "en" else "已完成。"},
"reason": "The goal looks satisfied." if ep.lang == "en" else "目标看起来已完成。"}
done = finalize_reasons(done, history, ep.lang, rng)
out.append((variant, raw_observation(ep.scope, history), done, now, verdict))
finally:
runner.close()
return out
def _with_readonly_noise(history: list, runner: Runner, ep: Episode, rng: random.Random, now: float) -> list:
"""Real planner histories repeat observations: in 60% of goal-done rows (every variant) 1-2 read-only
steps (a listing of the folder, a read of an input or output) are inserted at random positions. They change
nothing, so the verifier's verdict is unchanged, but the history length / tool sequence no longer gives
the label away (family + history length predicted 87% of dev labels before)."""
if rng.random() >= .6:
return history
names = [n for n in ep.info.get("sources", []) + ep.info.get("dests", []) if isinstance(n, str) and "." in n]
mutations = [a for a in ep.plan if a["tool"] in ("copy_file", "move_file", "write_text", "archive_files",
"create_word_document", "create_excel_workbook")]
out = list(history)
for _ in range(rng.randint(1, 2)):
roll = rng.random()
if mutations and roll < .3:
# a step the runtime refused before running it (validate_mutation): nothing changed, no confirmation
# (assistant.validate_mutation: an argument missing -> ValueError, recorded as refused)
action = copy.deepcopy(rng.choice(mutations))
action["arguments"].pop(rng.choice(sorted(action["arguments"])))
entry = {"action": action, "result": {"executed": False, "refused": "ValueError",
"message": "Unknown or missing tool argument"}, "at_unix": 0.0}
elif names and roll < .65:
action = _fix_args(_act("read_text", ep.lang, rng, path=rng.choice(names)))
entry = runtime_entry(action, runner.run(action), 0.0)
else:
action = _fix_args(_list(ep.lang, rng))
entry = runtime_entry(action, runner.run(action), 0.0)
out.insert(rng.randint(1, len(out)), entry)
for j, entry in enumerate(out):
entry["at_unix"] = now - 10 * (len(out) - j)
return out
def _wrong_text(text: str, lang: str, rng: random.Random) -> str:
"""A plausible but wrong version of the requested text: a line dropped, another sentence swapped in, or
the tag changed. No marker word ("edited", "draft", ...) that a model could key on."""
lines = text.split("\n")
options = ["swap"]
if len(lines) > 1:
options.append("drop")
if "#" in lines[-1]:
options.append("tag")
mode = rng.choice(options)
if mode == "drop":
lines.pop(rng.randrange(len(lines)))
elif mode == "tag":
head, _, tag = lines[-1].rpartition("#")
lines[-1] = head + "#" + "".join(rng.choice("0123456789abcdef") for _ in tag)
else:
i = rng.randrange(len(lines))
other = [t for t in TEXTS[lang] if not lines[i].startswith(t)]
lines[i] = rng.choice(other) + f" #{_hex(rng, 4)}"
out = "\n".join(lines)
return out if out != text else out + "\n" + rng.choice(TEXTS[lang])
def _verify_office(row, root, before, events):
from mac_laya.system_office_verifier import OFFICE_FAMILIES, verify_office
if row["family"] in OFFICE_FAMILIES:
return verify_office(row, root, before, events)
# office_transform / excel_to_word: same predicate as word_create on the named output.
proxy = {**row, "family": "word_create"}
return verify_office(proxy, root, before, events)
def stable_seed(*parts) -> int:
return int(hashlib.sha256("|".join(map(str, parts)).encode()).hexdigest()[:12], 16)
|