REA computer-use environment, v0.1.0
Browse filesFiles changed (18)
- README.mdAdded+110
- bundle/README.mdAdded+47
- bundle/artifacts/add-quiz-note-check/verify.pyAdded+561
- bundle/envs/xournalpp/SKILL.mdAdded+10
- bundle/envs/xournalpp/env.tomlAdded+4
- bundle/envs/xournalpp/seed/.config/xournalpp/palette.gplAdded+14
- bundle/envs/xournalpp/seed/.config/xournalpp/settings.xmlAdded+175
- bundle/envs/xournalpp/seed/Documents/biology-notes.xoppAdded
- bundle/envs/xournalpp/xournalpp_app.pyAdded+903
- bundle/evals/xournalpp.tomlAdded+1
- bundle/tasks/add-quiz-note.jsonAdded+9
- bundle/tasks/smoke.jsonAdded+7
- media/hero.gifAdded
- media/solve-1.mp4Added+3
- media/solve-2.mp4Added+3
- media/solve-3.mp4Added+3
- media/witness.mp4Added+3
- results.jsonAdded+114
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110---license: apache-2.0pretty_name: Xournal++ computer-use environment from a one-line request (REA)tags:- computer-use- cua- gui-agent- rl-environment- agentenv- desktop- linux- rea- notes- handwriting- pdf-annotation- from-request---
# Xournal++: a computer-use environment built from a one-line request

**The real Xournal++ 1.2 handwriting notebook running on an Ubuntu 24.04 desktop, as an [agentenv](https://pypi.org/project/agentenv-framework/) computer environment. An agent completes the task only through screenshots, mouse and keyboard, and a verifier grades the saved files with no model.**
Claude Code built this environment from a one-line request in about 18 minutes, with only REA's build skill and MCP tools; [How it was made](#how-it-was-made) has the request and the steps. Xournal++ opens a one-page notebook, `Documents/biology-notes.xopp`, at launch: a lined page with three typed notes, Cell Biology - Week 3, Mitochondria make ATP and Ribosomes build proteins. The agent has to add a text note that says "Quiz on Friday: bring a calculator" and save. It sees only the screen and acts only with the mouse and keyboard.
## Watch
- Agent runs (Claude Code with Claude Sonnet 5.5): [run 1](media/solve-1.mp4), [run 2](media/solve-2.mp4), [run 3](media/solve-3.mp4)- Witness, which proves the task can be done through the computer: [witness.mp4](media/witness.mp4)
Each video is the computer's own screen recording at 10 frames per second.
## The task
> In Xournal++, add a text note that says "Quiz on Friday: bring a calculator" to the Cell Biology notebook page in Documents/biology-notes.xopp, and save it.
`bundle/artifacts/add-quiz-note-check/verify.py` reads the app's files through the computer's `data/get` view and passes only if every check holds:
| Check | Kind | File || --- | --- | --- || `note-text` | `text_contains` | `Documents/biology-notes.xopp` || `one-new-note` | `member_count` | `Documents/biology-notes.xopp` || `notes-kept` | `text_contains` | `Documents/biology-notes.xopp` |
An `.xopp` file is gzip-compressed XML, and REA reads the XML inside. Each typed note is a `text` element in the page's layer. The checks read the layer: its text must contain "Quiz on Friday: bring a calculator" and, with the notes' text run together, still contain the three original notes in order, and the layer must hold exactly four text notes (`member_count`), so the new text has to be a note of its own rather than added to an existing one. REA's draft suggested a check on the page's preview image, which Xournal++ redraws on every save, and one on the layer's whole text; Claude Code discarded the first, split the second into the new-note and kept-notes checks, and added the count.
## Results
3 of 3 runs passed, about $0.56 per run.
| Run | Outcome | Turns | Cost | Video || --- | --- | --- | --- | --- || 1 | passed | 10 | $0.72 | [video](media/solve-1.mp4) || 2 | passed | 10 | $0.49 | [video](media/solve-2.mp4) || 3 | passed | 9 | $0.46 | [video](media/solve-3.mp4) |
## Run it
You need Docker. `agentenv-framework` builds the computer: Ubuntu 24.04 with the app installed from Ubuntu's archive (`xournalpp` 1.2.2, with `librsvg2-common`).
```bashpip install agentenv-framework==0.9.1431hf download earakely-scale/XournalppFromRequestComputerEnv-REA --repo-type dataset --local-dir xournalpp-requestagent-env run xournalpp-request/bundle --task add-quiz-note --agent claude-code --model <model>```
The agent needs a model provider configured for agentenv. `--task smoke` only boots the computer, with no agent. `bundle/README.md` describes the bundle in detail.
## How it was made
Claude Code built this environment from a one-line request, given only [REA](https://github.com/morluto/rea)'s build skill and REA's MCP tools:
> Build me a Xournal++ environment where the agent adds a text note to a small notebook page and saves it.
It asked only the skill's upfront questions, wrote no app-specific scripts, and finished in about 18 minutes. The steps were REA's usual ones:
1. **Capture.** REA launched Xournal++ on a Linux desktop and recorded its package, windows and opened files while the edit was made. It also recorded the app's state folders before and after.2. **Export.** REA turned the capture into an agentenv `computer_app`. It installs the app, seeds the starting files, starts the app, and waits for its main window. It also serves typed views of the app's files for verifiers.3. **Task.** The task's checks were validated against the capture: they fail on the starting state and pass on the captured end state.4. **Witness.** In a fresh computer, the note was added through computer actions alone, and the checks were read at four stages. They held on the first try:
| Stage | Checks || --- | --- || `seed` | fail, as expected: the layer holds three notes, none of them the quiz note || `after_edit` | pass || `near_miss` | fail, as expected: the note was changed to "Quiz on Friday: bring a calculater" || `after_reset` | fail, as expected: `data/reset` restored the seed |
The agent runs came after the build: Claude Code with Claude Sonnet 5.5 (`--model anthropic/claude-sonnet-5-5 --no-emulate`, on an amd64 host) solved the task 3 times, each run recorded.
## What's inside
```bundle/ the agentenv bundle: envs/ (app module, seed files), tasks/, artifacts/ (verifier), evals/media/ witness and agent-run recordings (MP4) with short GIF previewsresults.json the runs above, with each check's result```
## Limits
- The checks expect the notebook to keep one page with one layer: a note added on a new page or in a new layer makes their pointers match two and fail.- The note must contain the sentence exactly as written, though words around it still pass; where it sits on the page is not checked.- The bundle installs `librsvg2-common`, the SVG image loader Xournal++'s icons need, beside the app as an extra package. The build asked for it up front.- The computer installs whatever `xournalpp` Ubuntu 24.04's archive holds at build time (1.2.2 for these runs); it is not pinned.- Three runs is a small sample: the solve rate shows the task is solvable, not how hard it is.
## Licences
The bundle code, the task and the synthetic seed files are Apache-2.0. Xournal++ itself is not included: the computer installs it from Ubuntu's archive (`xournalpp` 1.2.2, with `librsvg2-common`) at build time, under its own licence (GPL-2.0-or-later).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Xournal++ computer app
Exported by REA's `export-desktop-application` from a capture of the `xournalpp` package(capture Evidence `ev_ae6b6473d4c3536078503ae95cc6b6ff3e22d29881d18f518b21b338a9e6142b`). It was checked against agentenv-framework0.9.1431.
- `envs/xournalpp/` is a computer app on the `ubuntu-24.04` base with the `reference` driver, for `amd64` and `arm64`. It installs `xournalpp` from the distribution archive, launches `sh -c cd "$HOME" 2>/dev/null; exec 'xournalpp' "$HOME"/'Documents/biology-notes.xopp'` at boot and is ready when a window of class `Com.github.xournalpp.xournalpp` appears.- Installed beside the app because the export was asked for them with `--extra-package`, as a build computer asks for the packages its request named: `librsvg2-common`.- At launch the app opens `~/Documents/biology-notes.xopp`, the seed's one document.- Owned paths: `~/.config/xournalpp`, `~/Documents`. `data/get` returns their files and a typed JSON view of each; `data/reset` restores the seed.- Seed: 3 file(s) made for the task, as saved at checkpoint `seed`. Text files and dconf keys spell the capture host's name as `localhost`, `user@host` as `user@localhost` and the home as `/home/user`, which the computer respells to its own at boot. Rewritten: `envs/xournalpp/seed/Documents/biology-notes.xopp`.- `tasks/smoke.json` deploys the app.
Run the task with `agent-env run <this folder>`, or only the deploy with `--task smoke`.
The seed was made for this task, not taken from a user's own data; read `envs/xournalpp/seed/` before publishing the bundle.
## Task `add-quiz-note`
`tasks/add-quiz-note.json` deploys the app, has the agent work through the computer from the prompt below, and gradesthe outcome with `artifacts/add-quiz-note-check/verify.py`, which reads the app's `data/get` views and needsno model. It grades once the app's files have held for 3 s, so a save the app makes on its own within thattime of the agent stopping counts; each result's `settled` is false when they were still changing 15 s after thefirst read. `evals/xournalpp.toml` names it, so a run of the bundle runs it.
> In Xournal++, add a text note that says "Quiz on Friday: bring a calculator" to the Cell Biology notebook page in Documents/biology-notes.xopp, and save it.
Checks, each of which must pass:
- `note-text`: `{"kind":"text_contains","file":"Documents/biology-notes.xopp","pointer":"/root/children/[name=page]/children/[name=layer]","value":"Quiz on Friday: bring a calculator"}`- `one-new-note`: `{"kind":"member_count","file":"Documents/biology-notes.xopp","pointer":"/root/children/[name=page]/children/[name=layer]/children","matching":"[name=text]","equals":4}`- `notes-kept`: `{"kind":"text_contains","file":"Documents/biology-notes.xopp","pointer":"/root/children/[name=page]/children/[name=layer]","value":"Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins"}`
REA kept the task because its checks fail on the seed (`note-text`, `one-new-note`) and allpass on the captured end state.
To measure a solve rate, run the task k times (3 by default) with the agent and model to measure, and count the runswhose summary line says `passed`; a run that says `failed` did not finish and is run again rather than counted:
agent-env run <this folder> --task add-quiz-note --agent claude-code --model MODEL123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561"""Checks of the task add-quiz-note against the xournalpp app's state, exported by REA from a desktop application capture.
It reads the app's data/get through the computer, takes the typed views of its files and evaluates each check: nomodel, no code from the task. It grades once the app's files settle, since an app can save a few seconds after thelast change: each result's settled says whether they had held for SETTLE_WINDOW_S, or had not by SETTLE_BOUND_S andthe last completed read was graded, and read_cut whether a read still running at SETTLE_BOUND_S was cut. A failure toreach the app raises, so the run fails rather than scoring the agent."""import asyncioimport hashlibimport jsonimport mathimport reimport time
from agentenv_protocol import client as protocolfrom agentenv_protocol.types import RPC_PATH
APP = "xournalpp"CHECKS = [ {"id": "note-text", "kind": "text_contains", "file": "Documents/biology-notes.xopp", "pointer": "/root/children/[name=page]/children/[name=layer]", "value": "Quiz on Friday: bring a calculator"}, {"id": "one-new-note", "kind": "member_count", "file": "Documents/biology-notes.xopp", "pointer": "/root/children/[name=page]/children/[name=layer]/children", "matching": "[name=text]", "equals": 4}, {"id": "notes-kept", "kind": "text_contains", "file": "Documents/biology-notes.xopp", "pointer": "/root/children/[name=page]/children/[name=layer]", "value": "Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins"},]#: The app's data/get is read this often until its files settle.SETTLE_INTERVAL_S = 0.5#: How long each file's bytes must hold, from the read that returned them, before the views are graded.SETTLE_WINDOW_S = 3.0#: After the first read began: no read starts then or later, one still running is cut, and the last completed read is#: graded though the files are still changing.SETTLE_BOUND_S = 15.0#: Where a data/get file part names its path in the home.DATA_OBJECTS = "urn:agentenv:data-objects/v1"
MISSING = object()INDEX = re.compile(r"0|[1-9][0-9]*")VIEW_FORMATS = ("text", "json", "keyfile", "xml")NUMERAL = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")WHITESPACE_RUN = re.compile(r"[ \t\r\n]+")
def _shown(value) -> str: text = json.dumps(value, ensure_ascii=False, separators=(",", ":")) return text if len(text) <= 200 else text[:200] + "…"
def _same(actual, expected) -> bool: """JSON equality: numbers by value but never a boolean for a number, objects by their keys, arrays in order.""" if isinstance(expected, list): return (isinstance(actual, list) and len(actual) == len(expected) and all(_same(item, wanted) for item, wanted in zip(actual, expected))) if isinstance(expected, dict): return (isinstance(actual, dict) and len(actual) == len(expected) and all(key in actual and _same(actual[key], value) for key, value in expected.items())) if isinstance(expected, bool) or isinstance(actual, bool): return isinstance(expected, bool) and isinstance(actual, bool) and actual == expected if isinstance(expected, (int, float)): return isinstance(actual, (int, float)) and actual == expected return type(actual) is type(expected) and actual == expected
def _is_element(value) -> bool: return (isinstance(value, dict) and isinstance(value.get("name"), str) and isinstance(value.get("attributes"), dict) and isinstance(value.get("children"), list))
def _element_text(element, attribute=None) -> str: """An element's text as XPath's string() reads it from what the view keeps: every text node among its children and its descendants', in document order. With attribute, the values of that attribute on it and its descendants instead, in document order, and no text node.""" parts, pending = [], [element] while pending: node = pending.pop() if isinstance(node, str): if attribute is None: parts.append(node) elif _is_element(node): if attribute is not None and isinstance(node["attributes"].get(attribute), str): parts.append(node["attributes"][attribute]) pending.extend(reversed(node["children"])) return "".join(parts)
def _bracketed(token: str) -> bool: return len(token) >= 2 and token.startswith("[") and token.endswith("]")
def _selector(token: str): """A selector's conditions, [KEY=VALUE], [@KEY=VALUE] or [>KEY=VALUE] one or more times, or None when the token is not one.""" if not _bracketed(token): return None conditions = [] for part in token[1:-1].split("]["): key, equals, value = part.partition("=") prefix = key[:1] if key[:1] in ("@", ">") else "" name = key[len(prefix):] if not equals or not name: return None conditions.append((prefix, name, value)) return conditions
def _has_child_text(member, key: str, value: str) -> bool: """Whether an element has a child element named key whose text, its whitespace collapsed, is value.""" return _is_element(member) and any( _is_element(child) and child["name"] == key and _collapse_whitespace(_element_text(child)) == value for child in member["children"])
def _selects(member, conditions) -> bool: """Whether an array member meets every condition; selectors compare strings only.""" if not isinstance(member, dict): return False for prefix, key, value in conditions: if prefix == ">": if not _has_child_text(member, key, value): return False continue fields = member.get("attributes") if prefix == "@" else member if not isinstance(fields, dict) or not isinstance(fields.get(key), str) or fields[key] != value: return False return True
def _step(items: list, token: str, last: bool): """One step into an array, by index or by a selector that must match one member, or none when it is the last.""" if INDEX.fullmatch(token): return ("member", items[int(token)]) if int(token) < len(items) else ("none", None) conditions = _selector(token) if conditions is None: return ("unresolved", f"{token} is not a selector of the form [KEY=VALUE]") if _bracketed(token) else ( "none", None) matched = [item for item in items if _selects(item, conditions)] if len(matched) == 1: return "member", matched[0] if len(matched) > 1: return "unresolved", f"{token} matches {len(matched)} members, not one" return ("none" if last else "unresolved"), f"{token} matches no member"
def _locate(view, pointer: str): """Where a pointer leads: ("value", value), ("none", why or None) or ("unresolved", problem), with the pointers to the arrays a selector searched on the way.""" current, searched = view, [] segments = pointer[1:].split("/") for position, segment in enumerate(segments): token = segment.replace("~1", "/").replace("~0", "~") if isinstance(current, list): if not INDEX.fullmatch(token) and _selector(token) is not None: searched.append("".join("/" + part for part in segments[:position])) kind, found = _step(current, token, position == len(segments) - 1) if kind != "member": return kind, found, searched current = found elif isinstance(current, dict) and token in current: current = current[token] else: return "none", None, searched return "value", current, searched
def _number(value): """A number, or a numeral string read as one; None for anything else, a boolean, or a numeral past the doubles.""" if isinstance(value, bool): return None if isinstance(value, (int, float)): return value if not isinstance(value, str) or not NUMERAL.fullmatch(value): return None number = float(value) return number if math.isfinite(number) else None
def _entry_leaves_out(entry) -> bool: return isinstance(entry, dict) and (isinstance(entry.get("view_error"), str) or ( entry.get("format") in ("text", "xml") and isinstance(entry.get("view"), dict) and entry["view"].get("truncated") is True))
def _viewless_entry(view, pointer: str): """The name of the entry whose view a pointer goes into when it has none, so its null is no JSON value, and why: binary, unread, or of a format without a view; None when it has one.""" parts = pointer[1:].split("/") if len(parts) < 3 or parts[0] != "entries" or parts[2] != "view": return None kind, item, _ = _locate(view, "/entries/" + parts[1]) if kind != "value" or not isinstance(item, dict): return None if isinstance(item.get("view_error"), str): reason = f"has no view: {item['view_error']}" elif item.get("format") == "binary": reason = "is binary and has no view" elif item.get("format") not in VIEW_FORMATS: reason = "has no view" else: return None return (item["name"] if isinstance(item.get("name"), str) else ""), reason
def _array_leaves_out(form, view, array: str) -> bool: """Whether an array a selector searched may lack members: in a zip the listing or its entry's view, else the view's own truncation.""" if form != "zip": return _truncated(form, view) if array == "/entries": return isinstance(view, dict) and view.get("truncated") is True return _zip_leaves_out(view, array)
def _zip_leaves_out(view, pointer: str) -> bool: """Whether a zip view leaves out what a pointer reaches: for a pointer into one listed entry, only that entry.""" if not isinstance(view, dict): return False parts = pointer[1:].split("/") if parts[0] == "entries" and len(parts) > 1: kind, entry, _ = _locate(view, "/entries/" + parts[1]) return _entry_leaves_out(entry) if kind == "value" else view.get("truncated") is True entries = view.get("entries") if isinstance(view.get("entries"), list) else [] return view.get("truncated") is True or any(_entry_leaves_out(entry) for entry in entries)
def _truncated(form, view) -> bool: if not isinstance(view, dict): return False if form in ("text", "xml"): return view.get("truncated") is True if form != "sqlite": return False tables = view.get("tables") return view.get("tables_truncated") is True or any( isinstance(table, dict) and (table.get("truncated") is True or isinstance(table.get("error"), str)) for table in (tables.values() if isinstance(tables, dict) else []))
def _view_of(check, entry, form): """The view, whether it is truncated, and why the check cannot read it; an absent file reads as empty.""" if entry is None: return None, False, None if isinstance(entry.get("error"), str): return None, False, f"{check['file']} has no view: {entry['error']}" if entry.get("format") in (None, "binary"): return None, False, f"{check['file']} is binary and has no view" if form is not None and entry.get("format") != form: return None, False, f"{check['file']} is read as {entry.get('format')}, not {form}" return entry.get("view"), _truncated(entry.get("format"), entry.get("view")), None
def _undecided(check): return False, f"the view of {check['file']} is truncated, so what it leaves out is unknown"
def _compared(check, n: int, what: str): operator = next(key for key in ("equals", "at_least", "at_most") if check.get(key) is not None) expected = check[operator] met = n == expected if operator == "equals" else n >= expected if operator == "at_least" else n <= expected return met, f"{n} {what}, expected {operator.replace('_', ' ')} {expected}"
def _lines(check, entry): view, truncated, problem = _view_of(check, entry, "text") if problem is not None: return False, problem lines = view.get("lines") if isinstance(view, dict) and isinstance(view.get("lines"), list) else [] lines = [line for line in lines if isinstance(line, str)] file = check["file"] if check["kind"] == "lines_present": missing = next((line for line in check["lines"] if line not in lines), None) return (True, f"{file} has the line(s) {_shown(check['lines'])}") if missing is None else ( False, f"{file} has no line {_shown(missing)}") if truncated: return _undecided(check) if check["kind"] == "lines_absent": found = next((line for line in check["lines"] if line in lines), None) return (True, f"{file} has none of the lines {_shown(check['lines'])}") if found is None else ( False, f"{file} still has the line {_shown(found)}") if check.get("contains") is not None: n = sum(1 for line in lines if check["contains"] in line) return _compared(check, n, f"line(s) of {file} contain {_shown(check['contains'])}") n = sum(1 for line in lines if line == check["exact"]) return _compared(check, n, f"line(s) of {file} match {_shown(check['exact'])}")
def _near(at: str, found, expected, tolerance): """A value compared within a tolerance: numbers, and numeral strings, by their difference.""" number = _number(found) within = f"within {_shown(tolerance)} of {_shown(expected)}" if number is None: return False, f"{at} is {_shown(found)}, not a number" if abs(number - expected) <= tolerance: return True, f"{at} is {_shown(found)}, {within}" return False, f"{at} is {_shown(found)}, not {within}"
def _value(check, entry): view, truncated, problem = _view_of(check, entry, None) if problem is not None: return False, problem kind, found, searched = ("none", None, []) if entry is None else _locate(view, check["pointer"]) at = f"{check['file']} at {check['pointer']}" viewless = _viewless_entry(view, check["pointer"]) if entry is not None and entry.get("format") == "zip" else None if viewless is not None: return False, f"{check['file']} entry {viewless[0]} {viewless[1]}" # A selector tells one member from several only in an array the view holds whole. if any(_array_leaves_out(entry.get("format"), view, array) for array in searched): return _undecided(check) if kind == "unresolved": return False, f"{at}: {found}" if entry is not None and entry.get("format") == "zip": truncated = _zip_leaves_out(view, check["pointer"]) if check["kind"] == "value_equals" and isinstance(check["value"], (dict, list)) and truncated: return _undecided(check) if check["kind"] == "value_equals": if kind == "none": return False, f"{at} has no value" if found is None else f"{at}: {found}" expected = check["value"] if check.get("tolerance") is not None and isinstance(expected, (int, float)) and not isinstance(expected, bool): return _near(at, found, expected, check["tolerance"]) if _same(found, check["value"]): return True, f"{at} is {_shown(check['value'])}" return False, f"{at} is {_shown(found)}, not {_shown(check['value'])}" if truncated: return _undecided(check) return (True, f"{at} has no value") if kind == "none" else (False, f"{at} is {_shown(found)}")
def _collapse_whitespace(text: str) -> str: """Each run of XML whitespace (space, tab, CR, LF) made one space, none at either end, as normalize-space().""" return WHITESPACE_RUN.sub(" ", text).strip(" ")
def _text_at(view, pointer: str) -> bool: """Whether a string a pointer reaches is text of the document: a member of an element's children (a text node) or attributes (an attribute's value), rather than an element's name or a field of the DOCTYPE.""" segments = pointer.split("/") if len(segments) < 3 or segments[-2] not in ("children", "attributes"): return False kind, owner, _ = _locate(view, "/".join(segments[:-2])) return kind == "value" and _is_element(owner)
def _not_xml_entry(check, view): """Why a text check's pointer into an archive goes into no XML entry's view, or None when it does or names an entry not listed.""" parts = check["pointer"].split("/") if len(parts) < 4 or parts[3] != "view": return f"{check['file']} at {check['pointer']} does not point into an entry's view" if parts[1] != "entries": return None kind, item, _ = _locate(view, "/entries/" + parts[2]) if kind != "value" or not isinstance(item, dict) or item.get("format") == "xml": return None # An entry without a view failed before this, so its format is one with a view. name, form = (value if isinstance(value, str) else "" for value in (item.get("name"), item.get("format"))) return f"{check['file']} entry {name} is read as {form}, not xml"
def _whole_text(check, entry): """An element's whole text, or a text node's, compared with the value or searched for it.""" view, truncated, problem = _view_of(check, entry, None) if problem is not None: return False, problem at = f"{check['file']} at {check['pointer']}" if entry is None: return False, f"{at} has no value" form = entry.get("format") if form not in ("xml", "zip"): return False, f"{check['file']} is read as {form}, not xml" kind, found, searched = _locate(view, check["pointer"]) viewless = _viewless_entry(view, check["pointer"]) if form == "zip" else None if viewless is not None: return False, f"{check['file']} entry {viewless[0]} {viewless[1]}" if any(_array_leaves_out(form, view, array) for array in searched): return _undecided(check) problem = _not_xml_entry(check, view) if form == "zip" else None if problem is not None: return False, problem if kind == "unresolved": return False, f"{at}: {found}" if kind == "none": return False, f"{at} has no value" if found is None else f"{at}: {found}" # Only an element has attributes of its own and of its descendants to join. attribute = check.get("text_attribute") if not ((attribute is None and _text_at(view, check["pointer"])) if isinstance(found, str) else _is_element(found)): what = "an element, a text node or an attribute value" if attribute is None else "an element" return False, f"{at} is {_shown(found)}, not {what}" # A text node is whole. An element's text in a cut view may lack what the cut dropped from its middle. if form == "zip": truncated = _zip_leaves_out(view, check["pointer"]) if not isinstance(found, str) and truncated: return _undecided(check) return _compared_text(check, at, _element_text(found, attribute))
def _compared_text(check, at: str, found: str): """A text found at a pointer compared with the check's value or searched for it, both collapsed when it asks.""" collapse = check.get("normalize_whitespace") is True text = _collapse_whitespace(found) if collapse else found value = _collapse_whitespace(check["value"]) if collapse else check["value"] attribute = check.get("text_attribute") read = "" if attribute is None else f" in its {attribute} values" how = read + (" with whitespace collapsed" if collapse else "") if check["kind"] == "text_equals": if text == value: return True, f"{at} has the text {_shown(value)}{how}" return False, f"{at} has the text {_shown(text)}{how}, not {_shown(value)}" if value in text: return True, f"{at} has text containing {_shown(value)}{how}" return False, f"{at} has the text {_shown(text)}{how}, without {_shown(value)}"
def _members(check, entry): """How many members of the array at a pointer, or of those a selector matches, compared with the expected number.""" matching, pointer = check.get("matching"), check["pointer"] view, truncated, problem = _view_of(check, entry, None) if problem is not None: return False, problem form = None if entry is None else entry.get("format") # The empty pointer names the whole view, as a JSON file whose top level is an array. kind, found, searched = (("none", None, []) if entry is None else ("value", view, []) if pointer == "" else _locate(view, pointer)) at = check["file"] if pointer == "" else f"{check['file']} at {pointer}" viewless = _viewless_entry(view, pointer) if form == "zip" else None if viewless is not None: return False, f"{check['file']} entry {viewless[0]} {viewless[1]}" if any(_array_leaves_out(form, view, array) for array in searched): return _undecided(check) if kind == "unresolved": return False, f"{at}: {found}" if kind == "none": return False, f"{at} has no value" if found is None else f"{at}: {found}" if not isinstance(found, list): return False, f"{at} is {_shown(found)}, not an array" # A count is decided only on an array the view holds whole. if _array_leaves_out(form, view, pointer): return _undecided(check) # The parser refuses a matching that is no selector. conditions = None if matching is None else _selector(matching) n = len(found) if matching is None else sum(1 for item in found if conditions and _selects(item, conditions)) return _compared(check, n, f"member(s) of {at}" + ("" if matching is None else f" matching {matching}"))
def _rows(check, entry): view, _, problem = _view_of(check, entry, "sqlite") if problem is not None: return False, problem view = view if isinstance(view, dict) else {} tables = view.get("tables") if isinstance(view.get("tables"), dict) else {} table = tables[check["table"]] if check["table"] in tables else MISSING name = f"{check['file']} table {check['table']}" if table is MISSING and view.get("tables_truncated") is True: return _undecided(check) table = table if isinstance(table, dict) else {} if isinstance(table.get("error"), str): return False, f"{name} could not be read: {table['error']}" columns = table.get("columns") if isinstance(table.get("columns"), list) else [] rows = table.get("rows") if isinstance(table.get("rows"), list) else [] where = check.get("where") or {}
def matches(row) -> bool: return isinstance(row, list) and all( column in columns and columns.index(column) < len(row) and _same(row[columns.index(column)], value) for column, value in where.items())
n = sum(1 for row in rows if matches(row)) if check["kind"] == "row_present": return (n > 0, f"{name} has a row with {_shown(where)}" if n > 0 else f"{name} has no row with {_shown(where)}") if table.get("truncated") is True: return _undecided(check) if check["kind"] == "row_absent": return (True, f"{name} has no row with {_shown(where)}") if n == 0 else ( False, f"{name} has {n} row(s) with {_shown(where)}") return _compared(check, n, f"row(s) of {name}" + (f" with {_shown(where)}" if "where" in check else ""))
def _verdict(check, entry): kind = check["kind"] if kind == "file_present": return (entry is not None, f"{check['file']} exists" if entry is not None else f"{check['file']} does not exist") if kind == "file_absent": return (entry is None, f"{check['file']} does not exist" if entry is None else f"{check['file']} exists") if kind in ("lines_present", "lines_absent", "line_count"): return _lines(check, entry) if kind in ("value_equals", "value_absent"): return _value(check, entry) if kind in ("text_equals", "text_contains"): return _whole_text(check, entry) if kind == "member_count": return _members(check, entry) return _rows(check, entry)
def evaluate(checks: list, views: dict) -> list: """One result per check against the views data/get returned, by home path.""" results = [] for check in checks: passed, description = _verdict(check, views.get(check["file"])) results.append({"id": check["id"], "result": passed, "description": description}) return results
def _files(answer) -> list: """Each file data/get returned, by its home path or its place among the parts, with the SHA-256 of its bytes as sent: what changes when the app saves.""" files = [] for index, part in enumerate(answer.parts): if part.kind != "file": continue marker = (getattr(part, "metadata", None) or {}).get(DATA_OBJECTS) path = marker.get("path") if isinstance(marker, dict) else None content = getattr(part.file, "bytes", None) or getattr(part.file, "uri", None) or "" files.append((path if isinstance(path, str) else f"#{index}", hashlib.sha256(content.encode()).hexdigest())) return sorted(files)
async def _read(url): answer = await protocol.get_data(url, timeout=120) states = [part.data["state"] for part in answer.parts if part.kind == "data" and isinstance(part.data.get("state"), dict)] if not states: raise RuntimeError(f"the {APP} app's data/get returned no state views") return states[0], _files(answer)
async def _settled_views(url): """The app's views once each file's bytes have held for SETTLE_WINDOW_S, counted from the read that returned them, read every SETTLE_INTERVAL_S; else the last completed read's. No read starts SETTLE_BOUND_S or more after the first began, and one still running then is cut. Also whether the files had held, and whether a read was cut.""" start = time.monotonic() # The first read is the one a grade needs, so only its own timeout bounds it. views, files = await _read(url) # Offsets from the first read's start: when the last completed read began, and when a read first returned the # bytes it holds. began, since = 0.0, time.monotonic() - start while began - since < SETTLE_WINDOW_S: # Reads come an interval apart, and the one that can settle the files as soon as the window allows. at = max(min(began + SETTLE_INTERVAL_S, since + SETTLE_WINDOW_S), time.monotonic() - start) if at >= SETTLE_BOUND_S: return views, False, False await asyncio.sleep(max(0.0, at - (time.monotonic() - start))) at = max(at, time.monotonic() - start) if at >= SETTLE_BOUND_S: return views, False, False try: latest_views, latest = await asyncio.wait_for(_read(url), SETTLE_BOUND_S - at) except asyncio.TimeoutError: return views, False, True began, views = at, latest_views if latest != files: since, files = time.monotonic() - start, latest return views, True, False
async def verify(mcp_url, env_url): card = await protocol.get_card(env_url) child = protocol.find_child(card, APP) if child is None: raise RuntimeError(f"the computer at {env_url} lists no app named {APP}") views, settled, read_cut = await _settled_views(env_url + (child.get("url") or RPC_PATH).removesuffix(RPC_PATH)) return [{**result, "settled": settled, "read_cut": read_cut} for result in evaluate(CHECKS, views)]12345678910---description: Use Xournal++ on this Linux desktop; its window has class Com.github.xournalpp.xournalpp.---
# Xournal++
Xournal++ is open on the desktop at boot. Its window's class is `Com.github.xournalpp.xournalpp`.
Its files live under `~/.config/xournalpp`, `~/Documents`. Work through the application's ownwindow and dialogs; the result is read from those files.1234type = "computer_app"module = "xournalpp_app.py:Xournalpp"computer = "ubuntu-24.04"driver = "reference"1234567891011121314GIMP PaletteName: Xournal Default Palette#0 0 0 Black0 128 0 Green0 192 255 Light Blue0 255 0 Light Green51 51 204 Blue128 128 128 Gray255 0 0 Red255 0 255 Magenta255 128 0 Orange255 255 0 Yellow255 255 255 White123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175<?xml version="1.0" encoding="UTF-8"?><!--The Xournal++ settings file. Do not edit this file! Most settings are available in the Settings dialog, the others are commented in this file, but handle with care!--><settings> <property name="pressureSensitivity" value="true"/> <property name="minimumPressure" value="0.05"/> <property name="pressureMultiplier" value="1"/> <property name="zoomGesturesEnabled" value="true"/> <property name="selectedToolbar" value="Portrait"/> <property name="lastSavePath" value="/home/user/Documents"/> <property name="lastOpenPath" value=""/> <property name="lastImagePath" value=""/> <property name="edgePanSpeed" value="20"/> <property name="edgePanMaxMult" value="5"/> <property name="zoomStep" value="10"/> <property name="zoomStepScroll" value="2"/> <property name="displayDpi" value="72"/> <property name="mainWndWidth" value="800"/> <property name="mainWndHeight" value="600"/> <property name="maximized" value="false"/> <property name="showToolbar" value="true"/> <property name="showSidebar" value="true"/> <property name="sidebarWidth" value="150"/> <property name="sidebarNumberingStyle" value="1"/> <property name="sidebarOnRight" value="false"/> <property name="scrollbarOnLeft" value="false"/> <property name="menubarVisible" value="true"/> <property name="filepathShownInTitlebar" value="false"/> <property name="numColumns" value="1"/> <property name="numRows" value="1"/> <property name="viewFixedRows" value="false"/> <property name="showPairedPages" value="false"/> <property name="layoutVertical" value="false"/> <property name="layoutRightToLeft" value="false"/> <property name="layoutBottomToTop" value="false"/> <property name="numPairsOffset" value="1"/> <!--The icon theme, allowed values are "disabled", "onDrawOfLastPage", and "onScrollOfLastPage"--> <property name="emptyLastPageAppend" value="disabled"/> <property name="presentationMode" value="false"/> <!--Which GUI elements are shown in default view mode, separated by a colon (,)--> <property name="defaultViewModeAttributes" value="showMenubar,showToolbar,showSidebar"/> <!--Which GUI elements are shown in fullscreen view mode, separated by a colon (,)--> <property name="fullscreenViewModeAttributes" value="goFullscren,showToolbar,showSidebar"/> <!--Which GUI elements are shown in presentation view mode, separated by a colon (,)--> <property name="presentationViewModeAttributes" value="goFullscren,showToolbar"/> <!--The cursor icon used with a stylus, allowed values are "none", "dot", "big", "arrow"--> <property name="stylusCursorType" value="dot"/> <!--The eraser cursor visibility used with a stylus, allowed values are "never", "always", "hover", "touch"--> <property name="eraserVisibility" value="always"/> <!--The icon theme, allowed values are "iconsColor", "iconsLucide"--> <property name="iconTheme" value="iconsColor"/> <property name="highlightPosition" value="false"/> <property name="cursorHighlightColor" value="2164260608"/> <property name="cursorHighlightBorderColor" value="2147483903"/> <property name="cursorHighlightRadius" value="30"/> <property name="cursorHighlightBorderWidth" value="0"/> <property name="darkTheme" value="false"/> <property name="useStockIcons" value="false"/> <property name="disableScrollbarFadeout" value="false"/> <property name="disableAudio" value="false"/> <!--Hides scroolbars in the main window, allowed values: "none", "horizontal", "vertical", "both"--> <property name="scrollbarHideType" value="none"/> <property name="autoloadMostRecent" value="false"/> <property name="autoloadPdfXoj" value="true"/> <property name="defaultSaveName" value="%F-Note-%H-%M"/> <property name="defaultPdfExportName" value="%{name}_annotated"/> <property name="autosaveEnabled" value="true"/> <property name="autosaveTimeout" value="3"/> <property name="addHorizontalSpace" value="false"/> <property name="addHorizontalSpaceAmount" value="150"/> <property name="addVerticalSpace" value="false"/> <property name="addVerticalSpaceAmount" value="150"/> <property name="drawDirModsEnabled" value="false"/> <property name="drawDirModsRadius" value="50"/> <property name="snapRotation" value="true"/> <property name="snapRotationTolerance" value="0.3"/> <property name="snapGrid" value="true"/> <property name="snapGridTolerance" value="0.5"/> <property name="snapGridSize" value="14.17"/> <property name="strokeRecognizerMinSize" value="40"/> <property name="touchDrawing" value="false"/> <property name="gtkTouchInertialScrolling" value="true"/> <property name="pressureGuessing" value="false"/> <property name="selectionBorderColor" value="4294901760"/> <property name="backgroundColor" value="4292664021"/> <property name="selectionMarkerColor" value="4285702095"/> <property name="touchZoomStartThreshold" value="0"/> <property name="pageRerenderThreshold" value="5"/> <!--The count of rendered PDF pages which will be cached.--> <property name="pdfPageCacheSize" value="10"/> <property name="preloadPagesBefore" value="3"/> <property name="preloadPagesAfter" value="5"/> <property name="eagerPageCleanup" value="true"/> <!--Config for new pages--> <property name="pageTemplate" value="xoj/template copyLastPageSettings=true size=595.275591x841.889764 backgroundType=lined backgroundColor=#ffffff "/> <property name="sizeUnit" value=""/> <property name="audioFolder" value=""/> <property name="audioInputDevice" value="-1"/> <property name="audioOutputDevice" value="-1"/> <property name="audioSampleRate" value="44100"/> <property name="audioGain" value="1"/> <property name="defaultSeekTime" value="5"/> <property name="pluginEnabled" value=""/> <property name="pluginDisabled" value=""/> <property name="strokeFilterIgnoreTime" value="150"/> <property name="strokeFilterIgnoreLength" value="1"/> <property name="strokeFilterSuccessiveTime" value="500"/> <property name="strokeFilterEnabled" value="false"/> <property name="doActionOnStrokeFiltered" value="false"/> <property name="trySelectOnStrokeFiltered" value="false"/> <property name="snapRecognizedShapesEnabled" value="false"/> <property name="restoreLineWidthEnabled" value="false"/> <property name="numIgnoredStylusEvents" value="0"/> <property name="inputSystemTPCButton" value="false"/> <property name="inputSystemDrawOutsideWindow" value="true"/> <property name="preferredLocale" value=""/> <property name="stabilizerAveragingMethod" value="0"/> <property name="stabilizerPreprocessor" value="0"/> <property name="stabilizerBuffersize" value="20"/> <property name="stabilizerSigma" value="0.5"/> <property name="stabilizerDeadzoneRadius" value="1.3"/> <property name="stabilizerDrag" value="0.4"/> <property name="stabilizerMass" value="5"/> <property name="stabilizerCuspDetection" value="true"/> <property name="stabilizerFinalizeStroke" value="true"/> <property name="latexSettings.autoCheckDependencies" value="true"/> <property name="latexSettings.defaultText" value="x^2"/> <property name="latexSettings.globalTemplatePath" value="/usr/share/xournalpp/resources/default_template.tex"/> <property name="latexSettings.genCmd" value="pdflatex -halt-on-error -interaction=nonstopmode '{}'"/> <property name="latexSettings.sourceViewThemeId" value=""/> <property name="latexSettings.editorFont" value="Monospace 12"/> <property name="latexSettings.useCustomEditorFont" value="false"/> <property name="latexSettings.editorWordWrap" value="true"/> <property name="latexSettings.sourceViewAutoIndent" value="true"/> <property name="latexSettings.sourceViewSyntaxHighlight" value="true"/> <property name="latexSettings.sourceViewShowLineNumbers" value="false"/> <property name="font" font="Sans" size="12"/> <data name="buttonConfig"> <data name="default"> <attribute name="color" type="hex" value="ff000000"/> <attribute name="drawingType" type="string" value="default"/> <attribute name="size" type="string" value="thin"/> <attribute name="tool" type="string" value="pen"/> </data> <data name="eraser"> <attribute name="eraserMode" type="string" value="none"/> <attribute name="size" type="string" value="none"/> <attribute name="tool" type="string" value="eraser"/> </data> <data name="middle"> <attribute name="tool" type="string" value="hand"/> </data> <data name="right"> <attribute name="tool" type="string" value="none"/> </data> <data name="stylus"> <attribute name="tool" type="string" value="none"/> </data> <data name="stylus2"> <attribute name="tool" type="string" value="none"/> </data> <data name="touch"> <attribute name="device" type="string" value=""/> <attribute name="disableDrawing" type="boolean" value="false"/> <attribute name="tool" type="string" value="none"/> </data> </data> <data name="deviceClasses"> <data name="Virtual core XTEST pointer"> <attribute name="deviceClass" type="int" value="1"/> <attribute name="deviceSource" type="int" value="0"/> </data> </data> <data name="tools"/> <data name="touch"/></settings>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903"""Xournal++ as an agentenv computer app, exported by REA from a desktop application capture.
Package: xournalpp (captured at 1.2.2-2build3). Capture Evidence: ev_ae6b6473d4c3536078503ae95cc6b6ff3e22d29881d18f518b21b338a9e6142b.The seed was made for the task, as saved at checkpoint seed."""
from __future__ import annotations
import contextlibimport copyimport hashlibimport ioimport jsonimport mathimport osimport reimport sqlite3import structimport subprocessimport sysimport tempfileimport zipfileimport zlibfrom pathlib import Pathfrom xml.parsers import expat
from agentenv_protocol import add_data, get_data, reset_datafrom agentenv_protocol.computer import AptSource, ComputerAppEnvironment, Download, Launch, Packages, Ready, RunScript, computer_app, linux, ready_checkfrom agentenv_protocol.computer.app_data import INITIAL, add, get, in_thread, keep_initial, resetfrom agentenv_protocol.types import DataPart
HERE = Path(__file__).resolve().parentSEED_HOME = "/home/user"PATHS = [".config/xournalpp", "Documents"]DCONF = ""TEXT_SEEDS = frozenset([".config/xournalpp/palette.gpl", ".config/xournalpp/settings.xml"])WINDOW_CLASS = "Com.github.xournalpp.xournalpp"
XML_SUFFIXES = (".xml", ".xbel", ".plist", ".svg", ".ui")GROUP_HEADER = re.compile(r"^\[([^\]]+)\]$")LINE_BREAK = re.compile(r"\r?\n")SQLITE_HEADER = b"SQLite format 3\x00"GVDB_HEADER = b"GVariant"ZIP_HEADER = b"PK\x03\x04"GZIP_HEADER = b"\x1f\x8b\x08"XML_SPACE = "xml:space"MAX_VIEW_BYTES = 64 * 1024 * 1024MAX_SAFE_INTEGER = 2**53 - 1MAX_TABLES = 64MAX_ROWS = 500MAX_LINES = 5000MAX_XML_NODES = 5000MAX_XML_DEPTH = 64SQLITE_BUSY_S = 0.25MAX_PARSED_BYTES = 4 * 1024 * 1024PARSED_TOO_LARGE = "larger than the 4 MiB limit for JSON and key file views"MAX_JSON_VIEW_DEPTH = 500JSON_TOO_DEEP = f"nested deeper than the {MAX_JSON_VIEW_DEPTH} levels a JSON view keeps"#: A JSON token after any whitespace, by group: an opening, a closing, a comma, a colon, a string's quote, or a number#: or literal. Strings are read by json's scanner, since a pattern repeating per escape holds memory for each.JSON_TOKEN = re.compile(r'[ \t\n\r]*(?:([\[{])|([\]}])|(,)|(:)|(")|(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?' r"|true|false|null))")JSON_SPACE = re.compile(r"[ \t\n\r]*")
def _respelled(text: str, home: Path) -> str: """The seed's home path respelled to this computer's home, only where a whole path segment ends after it.""" return re.sub(re.escape(SEED_HOME) + r"(?![\w.@+~-])", lambda _: str(home), text)
def _respelled_utf16(data: bytes, home: Path) -> bytes: """A UTF-16 text file with a byte-order mark respelled like a text seed, its mark kept; any other bytes as given.""" for mark, codec in ((b"\xff\xfe", "utf-16-le"), (b"\xfe\xff", "utf-16-be")): if data.startswith(mark): try: text = data[len(mark):].decode(codec) except UnicodeDecodeError: return data return mark + _respelled(text, home).encode(codec) if SEED_HOME in text else data return data
#: What marks a window as not yet the app's own: skipping the taskbar, as splash screens and dialogs do, or a splash type.SPLASH_MARKS = ("_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_WINDOW_TYPE_SPLASH")
def _taskbar_window(window_class: str) -> bool: """Whether a top-level window of the given class that the taskbar lists is shown; a splash screen or a dialog skips the taskbar.""" def xprop(*args: str) -> str: done = subprocess.run(["xprop", *args], capture_output=True, text=True) return done.stdout if done.returncode == 0 else ""
for window in re.findall(r"0x[0-9a-f]+", xprop("-root", "_NET_CLIENT_LIST").partition("#")[2]): props = xprop("-id", window, "WM_CLASS", "_NET_WM_STATE", "_NET_WM_WINDOW_TYPE") classes = re.findall(r'"((?:[^"\\]|\\.)*)"', props.partition("WM_CLASS")[2].split("\n", 1)[0]) if window_class in classes and not any(mark in props for mark in SPLASH_MARKS): return True return False
def _seed_home(home: Path) -> None: """Copy the captured files into this computer's home; text files, UTF-16 ones too, have the seed's home path respelled.""" seed = HERE / "seed" for source in sorted(seed.rglob("*")) if seed.is_dir() else []: if not source.is_file(): continue relative = source.relative_to(seed).as_posix() target = home / relative target.parent.mkdir(parents=True, exist_ok=True) data = source.read_bytes() if relative in TEXT_SEEDS: data = _respelled(data.decode("utf-8"), home).encode("utf-8") else: data = _respelled_utf16(data, home) target.write_bytes(data)
def _dconf(arguments: list, environment: dict) -> str: return subprocess.run(["dconf", *arguments], env={**os.environ, **environment}, capture_output=True, text=True, check=True).stdout
def _load_dconf(home: Path) -> None: """Compile the captured dconf keys into the user database without D-Bus, which is not up yet. Keys already there stay unless captured: dconf compile reads the key files in name order and a later file wins. A failure is reported and the app starts without them.""" if not DCONF: return database = home / ".config" / "dconf" / "user" try: database.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=database.parent) as scratch: keyfiles = Path(scratch, "keyfiles") keyfiles.mkdir() if database.is_file(): profile = Path(scratch, "profile") profile.write_text(f"file-db:{database}\n") existing = _dconf(["dump", "/"], {"DCONF_PROFILE": str(profile)}) (keyfiles / "00-existing").write_text(existing) (keyfiles / "01-captured").write_text(_respelled(DCONF, home)) _dconf(["compile", str(Path(scratch, "user")), str(keyfiles)], {}) os.replace(Path(scratch, "user"), database) except (OSError, subprocess.CalledProcessError) as error: detail = (getattr(error, "stderr", None) or "").strip().splitlines() print(f"warning: the captured dconf settings were not loaded: {detail[-1] if detail else error}", file=sys.stderr)
def _sqlite_text(data: bytes): text = data.decode("utf-8", "replace") return {"text": text, "bytes_hex": data.hex()} if "�" in text else text
def _cell(value): if isinstance(value, bytes): return {"blob_hex": value.hex()} if isinstance(value, int) and abs(value) > MAX_SAFE_INTEGER: return {"integer": str(value)} # JSON has no infinities or negative zero; REA's SQLite reader spells them as strings. if isinstance(value, float) and (math.isinf(value) or (value == 0 and math.copysign(1, value) < 0)): return "Infinity" if value == math.inf else "-Infinity" if value == -math.inf else "-0" return value
def _table(db, name: str, primary_key: list) -> dict: quoted = '"' + name.replace('"', '""') + '"' cursor = db.execute(f"select * from main.{quoted} not indexed limit {MAX_ROWS + 1}") rows = [[_cell(value) for value in row] for row in cursor] return {"columns": [column[0] for column in cursor.description], "primary_key": primary_key, "rows": rows[:MAX_ROWS], "truncated": len(rows) > MAX_ROWS}
def _sqlite(path: Path) -> dict: """The database's ordinary tables, in schema order, up to REA's table and row limits.""" with contextlib.closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=SQLITE_BUSY_S)) as db: kinds = dict(db.execute("select name, type from pragma_table_list where schema = 'main'")) names = [name for (name,) in db.execute("select name from sqlite_schema where type = 'table'") if kinds.get(name) == "table"] keys = {name: [key for (key,) in db.execute( "select name from pragma_table_info(?, 'main') where pk > 0 order by pk", (name,))] for name in names[:MAX_TABLES]} db.text_factory = _sqlite_text tables = {name: _table(db, name, keys[name]) for name in names[:MAX_TABLES]} cut = len(names) > MAX_TABLES return {"format": "sqlite", "view": {"tables": tables, "tables_truncated": cut}, "truncated": cut or any(table["truncated"] for table in tables.values())}
def _text(text: str) -> dict: lines = LINE_BREAK.split(text) if lines[-1] == "": lines.pop() view = {"lines": lines[:MAX_LINES], "line_count": len(lines), "truncated": len(lines) > MAX_LINES} return {"format": "text", "view": view, "truncated": view["truncated"]}
def _keyfile_line(raw: str) -> tuple: """A key file line as REA reads it: skip (blank or comment), group, entry or other.""" line = raw.strip() if not line or line[0] in "#;": return ("skip",) header = GROUP_HEADER.match(line) if header: return ("group", header.group(1)) key, equals, value = line.partition("=") return ("entry", key.strip(), value.strip()) if equals and key else ("other",)
def _each_line(text: str): """Each line of text as REA splits them, one at a time.""" start = 0 for line_break in LINE_BREAK.finditer(text): yield text[start:line_break.start()] start = line_break.end() yield text[start:]
def _is_keyfile(text: str) -> bool: """REA's rule: at least one group, and nothing a key file view would drop. Lines are read one at a time, stopping at the first it would drop.""" group = False for line in _each_line(text): kind = _keyfile_line(line)[0] if kind == "other": return False group = group or kind == "group" return group
def _keyfile(text: str) -> dict: groups, group = {}, "" for line in map(_keyfile_line, LINE_BREAK.split(text)): if line[0] == "group": group = line[1] groups.setdefault(group, {}) elif line[0] == "entry": groups.setdefault(group, {})[line[1]] = line[2] return groups
#: XML's whitespace, which alone can be formatting between elements; Unicode's wider set is text.XML_WHITESPACE = " \t\r\n"PREDEFINED_ENTITIES = ("amp", "lt", "gt", "apos", "quot")ENTITY_REFERENCE = re.compile(r"&([^#;][^;]*);")
def _expat(namespaces: bool, doctype=None): """An expat parser that reads a DOCTYPE as REA does: one with an internal subset, which could declare entities, is refused, the DTD it names is never read, and a reference to an entity other than XML's five is refused where expat would skip it. With namespaces it also enforces their rules, as REA's parser does, and without them it reports names as the document spells them. doctype, when given, receives the declared name and identifiers.""" parser = expat.ParserCreate(namespace_separator=" " if namespaces else None) parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)
def declared(name: str, system_id, public_id, internal_subset: bool) -> None: if internal_subset: raise ValueError("the document's DOCTYPE has an internal subset") if doctype is not None: doctype({"name": name, "public_id": public_id, "system_id": system_id})
def undeclared(name: str, _parameter: bool) -> None: raise ValueError(f"the document refers to the undeclared entity {name}")
def external(*_) -> None: raise ValueError("the document refers to an external entity")
parser.StartDoctypeDeclHandler = declared parser.SkippedEntityHandler = undeclared parser.ExternalEntityRefHandler = external return parser
def _check_tag(markup: str) -> None: """expat leaves an undeclared entity out of an attribute value without a word when a DOCTYPE names a DTD; REA's parser refuses it. With text taken by its own handler, a start tag is the only markup expat passes here that starts with < and a name, and it passes it whole.""" if markup[:1] == "<" and markup[1:2] not in ("!", "?", "/"): for name in ENTITY_REFERENCE.findall(markup): if name not in PREDEFINED_ENTITIES: raise ValueError(f"the document refers to the undeclared entity {name}")
def _ignore_text(_text: str) -> None: pass
class _XmlReader: """REA's XML view built as expat reads: names as spelled, declarations as attributes, text split where REA's DOM splits it (an empty CDATA section joins the text around it), and each node counted against REA's limits."""
def __init__(self) -> None: self.remaining, self.truncated, self.root, self.doctype = MAX_XML_NODES, False, None, None #: Per open element: its view or None when left out, whether xml:space="preserve" applies inside it, whether #: it holds an element, and whether it holds text other than whitespace: whitespace-only text is formatting #: only in an element that holds elements and no such text. self.open = [] self.text, self.cdata = [], None
def read(self, text: str) -> None: parser = _expat(False, self._doctype) parser.buffer_text = True parser.StartElementHandler, parser.EndElementHandler = self._start, self._end parser.CharacterDataHandler = self._data parser.StartCdataSectionHandler, parser.EndCdataSectionHandler = self._cdata_start, self._cdata_end parser.CommentHandler = parser.ProcessingInstructionHandler = self._other parser.Parse(text, True)
def _doctype(self, declared: dict) -> None: self.doctype = declared
def _admit(self) -> bool: """Whether the next node inside a kept element is kept, within the node and depth limits; one past them marks the view truncated.""" if self.open and self.open[-1][0] is None: return False if self.remaining <= 0 or len(self.open) > MAX_XML_DEPTH: self.truncated = True return False self.remaining -= 1 return True
def _text_node(self, text: str) -> None: if self.open and text.strip(XML_WHITESPACE): self.open[-1][3] = True if self._admit(): self.open[-1][0]["children"].append(text)
def _flush(self) -> None: if self.text: text, self.text = "".join(self.text), [] self._text_node(text)
def _data(self, text: str) -> None: (self.text if self.cdata is None else self.cdata).append(text)
def _cdata_start(self) -> None: self.cdata = []
def _cdata_end(self) -> None: text, self.cdata = "".join(self.cdata), None if text: self._flush() self._text_node(text)
def _other(self, *_) -> None: """A comment or processing instruction, counted like any node and never kept.""" self._flush() if self.open: self._admit()
def _start(self, name: str, attributes: dict) -> None: self._flush() parent = self.open[-1] if self.open else [None, False, False, False] parent[2] = True view = {"name": name, "attributes": attributes, "children": []} if self._admit() else None if view is not None and parent[0] is not None: parent[0]["children"].append(view) space = attributes.get(XML_SPACE) self.open.append([view, space == "preserve" if space else parent[1], False, False])
def _end(self, _name: str) -> None: self._flush() view, preserve, holds_element, holds_text = self.open.pop() if view is not None and holds_element and not holds_text and not preserve: view["children"] = [child for child in view["children"] if not isinstance(child, str) or child.strip(XML_WHITESPACE)] if not self.open: self.root = view
def _xml_view(text: str): """REA's XML view, or None for a document REA's parser refuses: a pass with namespaces checks the document as REA's parser does, then a pass without them reads names as spelled, as REA's view keeps them, and the DOCTYPE.""" reader = _XmlReader() try: check = _expat(True) check.CharacterDataHandler, check.DefaultHandler = _ignore_text, _check_tag check.Parse(text, True) reader.read(text) except (expat.ExpatError, ValueError): return None view = {"root": reader.root, "truncated": reader.truncated} return view if reader.doctype is None else {"doctype": reader.doctype, **view}
def _not_json(constant: str): raise ValueError(f"{constant} is not JSON")
class _Inexact(Exception): """A JSON number that REA's state view refuses, since reading it would change it."""
def _digits(text: str) -> str: return re.split(r"[eE]", text.lstrip("-"))[0].replace(".", "").strip("0") or "0"
def _js_string(value: float) -> str: """How JavaScript's String() writes a finite double: an integer below 1e21 in full, any other in shortest form.""" return str(int(value)) if value.is_integer() and abs(value) < 1e21 else repr(value)
def _safe_number(text: str) -> bool: """lossless-json's isSafeNumber: an integer spelling within 2^53, or a float spelling that keeps its digits.""" if re.fullmatch(r"-?[0-9]+", text): return len(text.lstrip("-")) <= 16 and abs(int(text)) <= MAX_SAFE_INTEGER value = float(text) if not math.isfinite(value): return False written = _js_string(value) return written == text or _digits(written) == _digits(text)
def _exact_number(text: str): """A JSON number read only when reading it changes nothing, as REA's state view rules: its spelling and its written-back form both safe, and not -0.""" value = float(text) if (not _safe_number(text) or not math.isfinite(value) or not _safe_number(_js_string(value)) or (value == 0 and math.copysign(1, value) < 0)): raise _Inexact(text) return int(text) if re.fullmatch(r"-?[0-9]+", text) else value
_INEXACT = object()_LEVEL_END = object()
def _number_or_mark(spelling: str): """A JSON number read exactly, or a mark for one REA's state view refuses.""" try: return _exact_number(spelling) except _Inexact: return _INEXACT
def _holds_inexact(value) -> bool: """Whether a parsed JSON value still holds a marked number once duplicate keys kept their last value; one iterator per nesting level, so no child list is copied.""" levels = [iter((value,))] while levels: item = next(levels[-1], _LEVEL_END) if item is _LEVEL_END: levels.pop() elif item is _INEXACT: return True elif isinstance(item, dict): levels.append(iter(item.values())) elif isinstance(item, list): levels.append(iter(item)) return False
def _deeper_than(root, limit: int) -> bool: """Whether a parsed JSON value nests deeper than a limit, as REA checks it: a value's depth is the number of iterators open above it, one per nesting level, so no child list is copied.""" levels = [iter((root,))] while levels: item = next(levels[-1], _LEVEL_END) if item is _LEVEL_END: levels.pop() elif len(levels) - 1 > limit: return True elif isinstance(item, dict): levels.append(iter(item.values())) elif isinstance(item, list): levels.append(iter(item)) return False
def _is_json(text: str) -> bool: """Whether text is one JSON value as REA's state view reads it, checked a token at a time without building it or recursing: it holds a byte per open container and one string at a time, so text too deep for Python's parser or too large to parse into a view is still told apart from other text.""" containers, expect, empty, at = bytearray(), "value", False, 0 while True: token = JSON_TOKEN.match(text, at) if token is None: break kind, at = token.lastindex, token.end() if kind == 5: try: at = json.decoder.scanstring(text, at)[1] except ValueError: return False if kind == 1 and expect == "value": containers.append(ord(text[at - 1])) expect, empty = ("value" if text[at - 1] == "[" else "key"), True # A closing bracket's code is its opening's plus two. elif kind == 2 and (expect == "after" or empty) and containers and containers[-1] == ord(text[at - 1]) - 2: containers.pop() expect, empty = "after", False elif kind == 3 and expect == "after" and containers: expect = "value" if containers[-1] == ord("[") else "key" elif kind == 4 and expect == "colon": expect = "value" elif kind >= 5 and (expect == "value" or (kind == 5 and expect == "key")): expect, empty = ("colon" if expect == "key" else "after"), False else: return False return expect == "after" and not containers and JSON_SPACE.fullmatch(text, at) is not None
def _json_view(text: str, size: int): """A JSON text's format and view, or why it has none, as REA reads it; None when it is not JSON. Text over the parsed-view limit, or nested past Python's recursion limit, is told apart without building its value.""" if size > MAX_PARSED_BYTES: return {"format": "json", "view": None, "error": PARSED_TOO_LARGE} if _is_json(text) else None # The whole text must parse, and duplicate keys settle, before an inexact number makes it JSON with an error. try: view = json.loads(text, parse_constant=_not_json, parse_float=_number_or_mark, parse_int=_number_or_mark) except RecursionError: # Nesting too deep for Python to parse is far deeper than REA's view keeps, once the rest of it is JSON too. return {"format": "json", "view": None, "error": JSON_TOO_DEEP} if _is_json(text) else None except ValueError: return None if _holds_inexact(view): return {"format": "json", "view": None, "error": "a number in it cannot be read exactly, such as an integer above 2^53"} if _deeper_than(view, MAX_JSON_VIEW_DEPTH): return {"format": "json", "view": None, "error": JSON_TOO_DEEP} return {"format": "json", "view": view, "truncated": False}
def _text_view(name: str, text: str, size: int) -> dict: """The format REA's state view detects for decoded text of size bytes, and its view; a JSON or key file over the parsed-view limit is refused before its value is built.""" trimmed = re.sub(r"^[\s]+", "", text) if name.endswith(".json") or trimmed[:1] in ("[", "{"): view = _json_view(text, size) if view is not None: return view lowered = name.lower() # Text that opens with an element is XML if it parses, whatever the file is called, as a Freeplane map. if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml") or re.match(r"<[A-Za-z_:]", trimmed): view = _xml_view(text) return _text(text) if view is None else {"format": "xml", "view": view, "truncated": view["truncated"]} if _is_keyfile(text): if size > MAX_PARSED_BYTES: return {"format": "keyfile", "view": None, "error": PARSED_TOO_LARGE} return {"format": "keyfile", "view": {"groups": _keyfile(text)}, "truncated": False} return _text(text)
def _bytes_view(name: str, data: bytes) -> dict: """The view of a document that is no database or archive: its text's, or none when it is binary.""" try: text = data.decode("utf-8-sig") if b"\x00" not in data[:8192] else None except UnicodeDecodeError: text = None if text is None: return {"format": "binary", "view": None, "truncated": False} return _text_view(name, text, len(data))
def _view(path: Path) -> dict: """A typed JSON view of one file in the shapes of REA's state view; truncated says the view is partial.""" too_large = {"format": None, "view": None, "error": "larger than 64 MiB, the most the view reads"} if path.stat().st_size > MAX_VIEW_BYTES: return too_large with path.open("rb") as file: data = file.read(8192) whole = data.startswith(GZIP_HEADER) or (not data.startswith(SQLITE_HEADER) and b"\x00" not in data) data += file.read(MAX_VIEW_BYTES + 1 - len(data)) if whole else b"" if data.startswith(SQLITE_HEADER): return _sqlite(path) if data.startswith(ZIP_HEADER): with path.open("rb") as file: return _zip(file, os.fstat(file.fileno()).st_size) if len(data) > MAX_VIEW_BYTES: return too_large if data.startswith(GZIP_HEADER): return _gzip(path.name, data) return _bytes_view(path.name, data)
def _views(home: Path, paths: list) -> dict: """A view of every file under the app's paths, keyed by its home-relative path.""" files = {} for owned in paths: root = home / owned candidates = [root] if root.is_file() else sorted(root.rglob("*")) if root.is_dir() else [] for path in candidates: if path.is_file() and not path.is_symlink(): key = path.relative_to(home).as_posix() try: files[key] = _view(path) except (OSError, ValueError, sqlite3.Error, RecursionError) as error: files[key] = {"format": None, "view": None, "error": str(error)} return files
MAX_ZIP_ENTRIES = 1000MAX_ZIP_ENTRY_BYTES = 16 * 1024 * 1024MAX_ZIP_BYTES = 64 * 1024 * 1024MAX_ZIP_RATIO = 100ZIP_READ_CHUNK = 64 * 1024#: Small, since the end of each gzip member copies what is left of the piece it was read from.GZIP_READ_CHUNK = 4 * 1024ZIP_END = b"PK\x05\x06"ZIP_CENTRAL = b"PK\x01\x02"ZIP64_LOCATOR = b"PK\x06\x07"ZIP64_END = b"PK\x06\x06"#: Formats an archive entry may have whose reader needs a tool, a worker or another archive opened.NOT_READ_INSIDE = ((SQLITE_HEADER, "sqlite", "a SQLite database"), (GVDB_HEADER, "dconf", "a dconf database"), (ZIP_HEADER, "zip", "an archive"))
def _entry_view(name: str, data: bytes) -> dict: """An archive entry's format and view by the rules a file's follow; a database or an archive inside is not read.""" for header, form, inside in NOT_READ_INSIDE: if data.startswith(header): return {"format": form, "view": None, "error": f"{inside} inside an archive is not read"} return _bytes_view(name, data)
def _zip_refusal(info, spent: int): """Why an entry is not read, checked in REA's order, or None; spent is the archive's bytes read so far.""" if info.flag_bits & 0x1: return "encrypted, so it is not read" if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED): return f"compressed with method {info.compress_type}, which the view does not read" if info.file_size > MAX_ZIP_ENTRY_BYTES: return "larger than the 16 MiB an entry's view reads" if info.file_size > MAX_ZIP_RATIO * info.compress_size: return f"expands more than {MAX_ZIP_RATIO} times, so it is not read" if spent + info.file_size > MAX_ZIP_BYTES: return "past the 64 MiB read from one archive" return None
def _entry_bytes(archive, info): """An entry's uncompressed bytes, or None when they fail its CRC-32 or are not exactly its declared size. Reading stops one byte past that size, which data past a short declared size fills, and asks for a bounded chunk at a time, which bounds what the decompressor expands per call, so a forged small size holds no more than that.""" probe = copy.copy(info) probe.file_size = info.file_size + 1 data = bytearray() try: with archive.open(probe) as member: while len(data) <= info.file_size: chunk = member.read(min(probe.file_size - len(data), ZIP_READ_CHUNK)) if not chunk: break data += chunk except (zipfile.BadZipFile, zlib.error, EOFError, OSError, ValueError): return None return data if len(data) == info.file_size else None
def _zip_entry(archive, info, refusal): """One entry of a zip view: its name, size and digest, and its own format and view, or why it was not read.""" entry = {"name": info.filename, "size": info.file_size, "sha256": None, "format": None, "view": None, "view_error": refusal} if refusal is not None: return entry data = _entry_bytes(archive, info) if data is None: return {**entry, "view_error": "its compressed data is damaged"} view = _entry_view(info.filename, data) return {**entry, "sha256": hashlib.sha256(data).hexdigest(), "format": view["format"], "view": view.get("view"), "view_error": view.get("error")}
def _zip_end(file, size: int): """Where an archive's central directory ends, how long it is and the offset it declares, from the last end record whose comment reaches the end of the file and, when a Zip64 locator precedes it whatever that record holds, the Zip64 one just before the locator; None without an end record, or when sentinels defer to a Zip64 record that is missing.""" window = min(size, 22 + 0xFFFF) file.seek(size - window) tail = file.read(window) at = tail.rfind(ZIP_END, 0, len(tail) - 18) while at >= 0 and at + 22 + int.from_bytes(tail[at + 20:at + 22], "little") != len(tail): at = tail.rfind(ZIP_END, 0, at + 3) if at < 0: return None total, length, offset = struct.unpack_from("<HII", tail, at + 10) end = size - window + at record = end - 20 - 56 if record < 0: return end, length, offset file.seek(end - 20) if file.read(4) != ZIP64_LOCATOR: return end, length, offset file.seek(record) zip64 = file.read(56) if len(zip64) == 56 and zip64[:4] == ZIP64_END: length, offset = struct.unpack_from("<QQ", zip64, 40) return record, length, offset if total == 0xFFFF or 0xFFFFFFFF in (length, offset): return None return end, length, offset
def _zip_unicode_path(raw: bytes, flags: int, extra: bytes): """An Info-ZIP Unicode Path when zip.js uses it: version 1, no UTF-8 flag, and the CRC-32 of the stored name.""" at = 0 while at + 4 <= len(extra): kind, length = struct.unpack_from("<HH", extra, at) if kind == 0x7075: data = extra[at + 4:at + 4 + length] usable = (length >= 5 and len(data) == length and data[0] == 1 and not flags & 0x800 and int.from_bytes(data[1:5], "little") == zlib.crc32(raw)) return data[5:] if usable else None at += 4 + length return None
def _zip_ends_in_slash(raw: bytes, flags: int, extra: bytes): """Whether an entry's name, as REA decodes it, ends in a slash; None when it must be UTF-8 and is not.""" utf8 = _zip_unicode_path(raw, flags, extra) if utf8 is None and flags & 0x800: utf8 = raw if utf8 is None: return raw.endswith(b"/") try: return utf8.decode("utf-8").endswith("/") except UnicodeDecodeError: return None
def _zip_directory(file, size: int, keep: int): """An archive's central directory read a record at a time, keeping the first file entries' records, as many as keep allows, and counting the rest, as REA reads it: (start, declared offset, records, count), or None when it cannot be read. Directories are told apart as zip.js tells them: a final slash, a Unix directory mode, or the MS-DOS attribute.""" located = _zip_end(file, size) if located is None: return None end, length, declared = located start = end - length if start < 0: return None file.seek(start) records, count, at = [], 0, start while at < end: fixed = file.read(46) if at + 46 > end or len(fixed) < 46 or fixed[:4] != ZIP_CENTRAL: return None made_by, flags = struct.unpack_from("<H2xH", fixed, 4) name_length, extra_length, comment_length = struct.unpack_from("<HHH", fixed, 28) external = struct.unpack_from("<I", fixed, 38)[0] rest = file.read(name_length + extra_length + comment_length) at += 46 + name_length + extra_length + comment_length if len(rest) < name_length + extra_length + comment_length or at > end: return None slash = _zip_ends_in_slash(rest[:name_length], flags, rest[name_length:name_length + extra_length]) if slash is None: return None if not (slash or (external >> 16) & 0o170000 == 0o040000 or (made_by >> 8 == 0 and external & 0x10)): count += 1 if len(records) < keep: records.append(fixed + rest) return start, declared, records, count
class _BoundedArchive(io.RawIOBase): """An archive as zipfile reads it: its entries in place, then a directory of the kept records alone and end records for them, so zipfile parses no more records than the view lists."""
def __init__(self, file, start: int, tail: bytes) -> None: super().__init__() self._file, self._start, self._tail, self._at = file, start, tail, 0
def readable(self) -> bool: return True
def seekable(self) -> bool: return True
def tell(self) -> int: return self._at
def seek(self, offset: int, whence: int = 0) -> int: self._at = offset + (0, self._at, self._start + len(self._tail))[whence] return self._at
def readinto(self, buffer) -> int: view = memoryview(buffer) if self._at < self._start: self._file.seek(self._at) count = self._file.readinto(view[:self._start - self._at]) else: chunk = self._tail[self._at - self._start:self._at - self._start + len(view)] count = len(chunk) view[:count] = chunk self._at += count return count
def _zip(file, size: int) -> dict: """A zip archive's file entries in archive order, up to REA's entry, size, ratio and archive limits; nothing is extracted to disk, no archive inside is opened, and zipfile is shown only the directory records listed.""" entries, spent = [], 0 try: directory = _zip_directory(file, size, MAX_ZIP_ENTRIES) if directory is None: raise zipfile.BadZipFile("no readable central directory") start, declared, records, count = directory kept = b"".join(records) offset = declared if declared <= 0xFFFFFFFF else start # zipfile follows a Zip64 locator signature wherever one sits before the end record, and the kept records # may end in those bytes, so a real Zip64 end record and locator for them come first. tail = (kept + struct.pack("<4sQ2H2I4Q", ZIP64_END, 44, 45, 45, 0, 0, len(records), len(records), len(kept), offset) + struct.pack("<4sIQI", ZIP64_LOCATOR, 0, offset + len(kept), 1) + struct.pack("<4s4H2IH", ZIP_END, 0, 0, len(records), len(records), len(kept), offset, 0)) with zipfile.ZipFile(_BoundedArchive(file, start, tail)) as archive: for info in archive.infolist(): refusal = _zip_refusal(info, spent) spent += info.file_size if refusal is None else 0 entries.append(_zip_entry(archive, info, refusal)) except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError, OSError, ValueError, struct.error): return {"format": "zip", "view": None, "error": "not a readable zip archive"} view = {"entries": entries, "entry_count": count, "truncated": count > len(entries)} return {"format": "zip", "view": view, "truncated": view["truncated"]}
def _gunzip(data: bytes, limit: int): """A gzip stream's document, its members joined as REA joins them, or None once it passes limit bytes, where decompressing stops: data after a member that starts with a zero byte is padding and ends the stream. It is read a piece at a time, so a member's end carries over only the rest of its piece. Raises zlib.error or EOFError when the stream is damaged or cut short.""" document, member, rest, at = bytearray(), zlib.decompressobj(16 + zlib.MAX_WBITS), b"", 0 while True: if not rest: if at >= len(data): raise EOFError("the gzip stream is cut short") rest, at = data[at:at + GZIP_READ_CHUNK], at + GZIP_READ_CHUNK document += member.decompress(rest, limit + 1 - len(document)) if len(document) > limit: return None if not member.eof: rest = member.unconsumed_tail continue rest = member.unused_data if not rest and at < len(data): rest, at = data[at:at + GZIP_READ_CHUNK], at + GZIP_READ_CHUNK if not rest or rest[0] == 0: return bytes(document) member = zlib.decompressobj(16 + zlib.MAX_WBITS)
def _gzip(name: str, data: bytes) -> dict: """A gzip file's view: its document's, decompressed within an archive entry's size and ratio limits and read by the rules a file's follow; a database inside is not read.""" compressed = {"format": None, "compression": "gzip", "view": None} try: document = _gunzip(data, min(MAX_ZIP_ENTRY_BYTES, MAX_ZIP_RATIO * len(data))) except (zlib.error, EOFError): return {**compressed, "error": "not a readable gzip stream"} if document is None: return {**compressed, "error": f"expands more than {MAX_ZIP_RATIO} times, so it is not read" if MAX_ZIP_RATIO * len(data) < MAX_ZIP_ENTRY_BYTES else "larger than the 16 MiB a compressed document's view reads"} for header, form, inside in NOT_READ_INSIDE: if form != "zip" and document.startswith(header): return {**compressed, "format": form, "error": f"{inside} inside a gzip file is not read"} view = _zip(io.BytesIO(document), len(document)) if document.startswith(ZIP_HEADER) else _bytes_view(name, document) return {**view, "compression": "gzip"}
@computer_app(supports=[{"os": {"type": "linux", "display": ["x11"]}, "arch": ["amd64", "arm64"]}])@linux( packages=Packages(apt=["xournalpp", "librsvg2-common"]), launch=Launch(at="boot", command=["sh", "-c", "cd \"$HOME\" 2>/dev/null; exec 'xournalpp' \"$HOME\"/'Documents/biology-notes.xopp'"], window={"class": "Com.github.xournalpp.xournalpp"}, ready=Ready(window=True)), paths=PATHS, skill="SKILL.md",)class Xournalpp(ComputerAppEnvironment): """Xournal++, launched at boot with the captured state in its home.
Declaring data hooks switches off agentenv's default data plane, so these call its helpers: the seed is kept as the initial state, reset restores it, add writes files under PATHS, and get returns those files plus a typed JSON view of each. """
def __init__(self) -> None: super().__init__() if not INITIAL.exists(): _seed_home(Path.home()) _load_dconf(Path.home()) keep_initial(self.paths)
@add_data async def add_files(self, parts: list) -> None: await add(parts, self.paths)
@get_data async def get_files(self, write_namespace=None) -> list: files = await get(self.paths, write_namespace) views = await in_thread(_views, Path.home(), self.paths) return [*files, DataPart(data={"state": views})]
@reset_data async def reset_files(self) -> None: await reset(self.paths)
@ready_check def main_window_shown(self) -> bool: """A window of the app's class that the taskbar lists is shown, not only a splash screen or a dialog.""" return _taskbar_window(WINDOW_CLASS)1tasks = ["add-quiz-note"]123456789[ {"id":"env","type":"deploy_env","env_id":"xournalpp"}, {"id":"agent","type":"deploy_agent","env_ids":["xournalpp"]}, {"id":"skills","type":"add_skills","env_ids":["xournalpp"]}, {"id":"record","type":"start_computer_recording","env_id":"xournalpp","name":"agent","depends_on":["env"]}, {"id":"task","type":"prompt_agent","depends_on":["skills","record"],"prompt":"In Xournal++, add a text note that says \"Quiz on Friday: bring a calculator\" to the Cell Biology notebook page in Documents/biology-notes.xopp, and save it."}, {"id":"check","type":"env_outcome_verifier","env_id":"xournalpp","file_artifact_id":"add-quiz-note-check","verifier_id":"add-quiz-note","depends_on":["task"]}, {"id":"end","type":"end_computer_recording","name":"agent","depends_on":["task"]}]1234567[ { "id": "env", "type": "deploy_env", "env_id": "xournalpp" }]123version https://git-lfs.github.com/spec/v1oid sha256:159ee7014c62ca5fe49cf5027de3d7414fb5f91c22ced4bfa0f04eeaa7add3d5size 2382757123version https://git-lfs.github.com/spec/v1oid sha256:4460bed990df2014b8d942d095851de56cbe26aa2a80be0fa1773d12cd39203fsize 2382149123version https://git-lfs.github.com/spec/v1oid sha256:3331ac1c03d87fac3d72294aa9dfe05e08d57da82e344bddea1f8165208d4fdbsize 1876868123version https://git-lfs.github.com/spec/v1oid sha256:6003bc17d16256d6798f65a194241332fad3b54138e373ec46094b654c1aa68bsize 14409741123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114{ "environment": "Xournal++", "app_version": "Xournal++ 1.2 handwriting notebook", "task": "add-quiz-note", "prompt": "In Xournal++, add a text note that says \"Quiz on Friday: bring a calculator\" to the Cell Biology notebook page in Documents/biology-notes.xopp, and save it.", "agent": "claude-code", "model": "claude-sonnet-5-5", "agentenv_framework": "0.9.1431", "witness": "checks failed on the seed, passed after a note was added through computer actions, failed on a near miss (\"bring a calculater\") and failed again after data/reset, in a fresh computer; held on the first try", "runs": [ { "run": 1, "verdict": "passed", "turns": 10, "usd": 0.72, "checks": { "add-quiz-note": { "score": 1.0, "results": [ { "id": "note-text", "result": true, "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Quiz on Friday: bring a calculator\"", "settled": true, "read_cut": false }, { "id": "one-new-note", "result": true, "description": "4 member(s) of Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer]/children matching [name=text], expected equals 4", "settled": true, "read_cut": false }, { "id": "notes-kept", "result": true, "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins\"", "settled": true, "read_cut": false } ] } } }, { "run": 2, "verdict": "passed", "turns": 10, "usd": 0.49, "checks": { "add-quiz-note": { "score": 1.0, "results": [ { "id": "note-text", "result": true, "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Quiz on Friday: bring a calculator\"", "settled": true, "read_cut": false }, { "id": "one-new-note", "result": true, "description": "4 member(s) of Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer]/children matching [name=text], expected equals 4", "settled": true, "read_cut": false }, { "id": "notes-kept", "result": true, "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins\"", "settled": true, "read_cut": false } ] } } }, { "run": 3, "verdict": "passed", "turns": 9, "usd": 0.46, "checks": { "add-quiz-note": { "score": 1.0, "results": [ { "id": "note-text", "result": true, "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Quiz on Friday: bring a calculator\"", "settled": true, "read_cut": false }, { "id": "one-new-note", "result": true, "description": "4 member(s) of Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer]/children matching [name=text], expected equals 4", "settled": true, "read_cut": false }, { "id": "notes-kept", "result": true, "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins\"", "settled": true, "read_cut": false } ] } } } ]}README.mdAdded+110
bundle/README.mdAdded+47
bundle/artifacts/add-quiz-note-check/verify.pyAdded+561
bundle/envs/xournalpp/SKILL.mdAdded+10
bundle/envs/xournalpp/env.tomlAdded+4
bundle/envs/xournalpp/seed/.config/xournalpp/palette.gplAdded+14
bundle/envs/xournalpp/seed/.config/xournalpp/settings.xmlAdded+175
bundle/envs/xournalpp/seed/Documents/biology-notes.xoppAdded
bundle/envs/xournalpp/xournalpp_app.pyAdded+903
bundle/evals/xournalpp.tomlAdded+1
bundle/tasks/add-quiz-note.jsonAdded+9
bundle/tasks/smoke.jsonAdded+7
media/hero.gifAdded

Large File Pointer Details
- SHA256: 6bd1df112bfb70a7723a07849a5ec3261e1189509d30d09deb22da08bb96daee
- Pointer size: 131 Bytes
- Size of remote file: 714 kB
media/solve-1.mp4Added+3
media/solve-2.mp4Added+3
media/solve-3.mp4Added+3
media/witness.mp4Added+3
results.jsonAdded+114