earakely-scale commited on
Commit
69ac23d
·
verified ·
1 Parent(s): 540a412

REA computer-use environment, v0.1.0

Browse files
README.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pretty_name: KmPlot computer-use environment from a one-line request (REA)
4
+ tags:
5
+ - computer-use
6
+ - cua
7
+ - gui-agent
8
+ - rl-environment
9
+ - agentenv
10
+ - desktop
11
+ - linux
12
+ - rea
13
+ - math
14
+ - plotting
15
+ - education
16
+ - from-request
17
+ ---
18
+
19
+ # KmPlot: a computer-use environment built from a one-line request
20
+
21
+ ![An agent solving the task in KmPlot](media/hero.gif)
22
+
23
+ **The real KmPlot 23.08 function plotter 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.**
24
+
25
+ Claude Code built this environment from a one-line request in about 21 minutes, with only REA's build skill and MCP tools; [How it was made](#how-it-was-made) has the request and the steps. KmPlot opens a small plot file, `Documents/lesson_plots.fkt`, at launch: three functions, f(x) = x^2 − 4, g(x) = 2sin(x) and h(x) = 0.5x + 1. The agent has to change h's formula to h(x) = 2x + 1 and save the plot file. It sees only the screen and acts only with the mouse and keyboard.
26
+
27
+ ## Watch
28
+
29
+ - 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)
30
+ - Witness, which proves the task can be done through the computer: [witness.mp4](media/witness.mp4)
31
+
32
+ Each video is the computer's own screen recording at 10 frames per second.
33
+
34
+ ## The task
35
+
36
+ > In KmPlot, change the formula of the function h in Documents/lesson_plots.fkt to h(x) = 2x + 1 and save the plot file.
37
+
38
+ `bundle/artifacts/change-h-formula-check/verify.py` reads the app's files through the computer's `data/get` view and passes only if every check holds:
39
+
40
+ | Check | Kind | File |
41
+ | --- | --- | --- |
42
+ | `h-new-formula` | `line_count` | `Documents/lesson_plots.fkt` |
43
+ | `h-old-formula-gone` | `line_count` | `Documents/lesson_plots.fkt` |
44
+ | `g-unchanged` | `line_count` | `Documents/lesson_plots.fkt` |
45
+ | `f-unchanged` | `line_count` | `Documents/lesson_plots.fkt` |
46
+ | `three-functions` | `line_count` | `Documents/lesson_plots.fkt` |
47
+
48
+ A `.fkt` file is XML, but it opens with `<!DOCTYPE kmpdoc>` and no XML declaration, and REA read it as text lines rather than XML. So the checks count lines: exactly one must contain `>h(x) = 2x + 1<` and none `>h(x) = 0.5x + 1<`, g's and f's equations must each still appear once, and the file must still hold three `<function ` lines. The f check reads only `>f(x) = x^2`, because KmPlot stores the minus in x^2 − 4 as U+2212, not a hyphen. REA's draft suggested checks on each function's whole line, whose attributes Qt writes in a different order in every process, and a guard that failed a correct edit in a fresh process for that reason; Claude Code narrowed two suggestions to the equation text, discarded the guard and wrote the rest.
49
+
50
+ ## Results
51
+
52
+ 3 of 3 runs passed, about $0.68 per run.
53
+
54
+ | Run | Outcome | Turns | Cost | Video |
55
+ | --- | --- | --- | --- | --- |
56
+ | 1 | passed | 11 | $1.02 | [video](media/solve-1.mp4) |
57
+ | 2 | passed | 14 | $0.55 | [video](media/solve-2.mp4) |
58
+ | 3 | passed | 10 | $0.47 | [video](media/solve-3.mp4) |
59
+
60
+ ## Run it
61
+
62
+ You need Docker. `agentenv-framework` builds the computer: Ubuntu 24.04 with the app installed from Ubuntu's archive (`kmplot` 23.08.5).
63
+
64
+ ```bash
65
+ pip install agentenv-framework==0.9.1431
66
+ hf download earakely-scale/KmPlotFromRequestComputerEnv-REA --repo-type dataset --local-dir kmplot-request
67
+ agent-env run kmplot-request/bundle --task change-h-formula --agent claude-code --model <model>
68
+ ```
69
+
70
+ 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.
71
+
72
+ ## How it was made
73
+
74
+ 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:
75
+
76
+ > Build me a KmPlot environment where the agent changes the formula of one plotted function and saves the plot file.
77
+
78
+ It asked only the skill's upfront questions, wrote no app-specific scripts, and finished in about 21 minutes. The steps were REA's usual ones:
79
+
80
+ 1. **Capture.** REA launched KmPlot 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.
81
+ 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.
82
+ 3. **Task.** The task's checks were validated against the capture: they fail on the starting state and pass on the captured end state.
83
+ 4. **Witness.** In a fresh computer, the edit was made through computer actions alone, and the checks were read at four stages. They held on the first try:
84
+
85
+ | Stage | Checks |
86
+ | --- | --- |
87
+ | `seed` | fail, as expected: h is still 0.5x + 1; the kept checks pass |
88
+ | `after_edit` | pass |
89
+ | `near_miss` | fail, as expected: the formula was typed as h(x) = 2x + 2 |
90
+ | `after_reset` | fail, as expected: `data/reset` restored the seed |
91
+
92
+ 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.
93
+
94
+ ## What's inside
95
+
96
+ ```
97
+ bundle/ the agentenv bundle: envs/ (app module, seed files), tasks/, artifacts/ (verifier), evals/
98
+ media/ witness and agent-run recordings (MP4) with short GIF previews
99
+ results.json the runs above, with each check's result
100
+ ```
101
+
102
+ ## Limits
103
+
104
+ - Because REA read the file as text, the checks are line counts, not checks on the XML's function elements. They need the equation exactly as the prompt writes it, `h(x) = 2x + 1`; an equivalent formula written differently, such as `2*x + 1`, fails.
105
+ - KmPlot stores the minus sign as U+2212 (−), not a hyphen, so a check on f's whole equation would need that character; the f check reads only the part before it.
106
+ - The computer installs whatever `kmplot` Ubuntu 24.04's archive holds at build time (23.08.5 for these runs); it is not pinned.
107
+ - Three runs is a small sample: the solve rate shows the task is solvable, not how hard it is.
108
+
109
+ ## Licences
110
+
111
+ The bundle code, the task and the synthetic seed files are Apache-2.0. KmPlot itself is not included: the computer installs it from Ubuntu's archive (`kmplot` 23.08.5) at build time, under its own licence (GPL-2.0-or-later).
bundle/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # KmPlot computer app
2
+
3
+ Exported by REA's `export-desktop-application` from a capture of the `kmplot` package
4
+ (capture Evidence `ev_d8ffd3e13d18b512c3269712baf199a9ad9e5890e664ca6dd4d5822ca14f1122`). It was checked against agentenv-framework
5
+ 0.9.1431.
6
+
7
+ - `envs/kmplot/` is a computer app on the `ubuntu-24.04` base with the `reference` driver, for
8
+ `amd64` and `arm64`. It installs `kmplot` from the distribution archive, launches `sh -c cd "$HOME" 2>/dev/null; exec 'kmplot' "$HOME"/'Documents/lesson_plots.fkt'` at boot and is ready
9
+ when a window of class `kmplot` appears.
10
+ - At launch the app opens `~/Documents/lesson_plots.fkt`, the seed's one document.
11
+ - Owned paths: `~/.config/kmplotrc`, `~/Documents`.
12
+ `data/get` returns their files and a typed JSON view of each; `data/reset` restores the seed.
13
+ - Seed: 2 file(s) made for the task, as saved at checkpoint `seed`.
14
+ Text files and dconf keys spell the capture host's name as `localhost`, `user@host` as `user@localhost`
15
+ and the home as `/home/user`, which the computer respells to its own at boot.
16
+ - Neither owned nor seeded, so the app starts without what it saved there: these files or folders, which changed
17
+ during the capture, `~/.config/QtProject.conf`.
18
+ To own them, capture again naming them with `state_paths` on `start_build_capture`, or `--state-path` on `capture-desktop-application`.
19
+ - `tasks/smoke.json` deploys the app.
20
+
21
+ Run the task with `agent-env run <this folder>`, or only the deploy with `--task smoke`.
22
+
23
+ The seed was made for this task, not taken from a user's own data; read `envs/kmplot/seed/` before publishing the bundle.
24
+
25
+ ## Task `change-h-formula`
26
+
27
+ `tasks/change-h-formula.json` deploys the app, has the agent work through the computer from the prompt below, and grades
28
+ the outcome with `artifacts/change-h-formula-check/verify.py`, which reads the app's `data/get` views and needs
29
+ no model. It grades once the app's files have held for 3 s, so a save the app makes on its own within that
30
+ time of the agent stopping counts; each result's `settled` is false when they were still changing 15 s after the
31
+ first read. `evals/kmplot.toml` names it, so a run of the bundle runs it.
32
+
33
+ > In KmPlot, change the formula of the function h in Documents/lesson_plots.fkt to h(x) = 2x + 1 and save the plot file.
34
+
35
+ Checks, each of which must pass:
36
+
37
+ - `h-new-formula`: `{"kind":"line_count","file":"Documents/lesson_plots.fkt","contains":">h(x) = 2x + 1<","equals":1}`
38
+ - `h-old-formula-gone`: `{"kind":"line_count","file":"Documents/lesson_plots.fkt","contains":">h(x) = 0.5x + 1<","equals":0}`
39
+ - `g-unchanged`: `{"kind":"line_count","file":"Documents/lesson_plots.fkt","contains":">g(x) = 2sin(x)<","equals":1}`
40
+ - `f-unchanged`: `{"kind":"line_count","file":"Documents/lesson_plots.fkt","contains":">f(x) = x^2","equals":1}`
41
+ - `three-functions`: `{"kind":"line_count","file":"Documents/lesson_plots.fkt","contains":"<function ","equals":3}`
42
+
43
+ REA kept the task because its checks fail on the seed (`h-new-formula`, `h-old-formula-gone`) and all
44
+ pass on the captured end state.
45
+
46
+ To measure a solve rate, run the task k times (3 by default) with the agent and model to measure, and count the runs
47
+ whose summary line says `passed`; a run that says `failed` did not finish and is run again rather than counted:
48
+
49
+ agent-env run <this folder> --task change-h-formula --agent claude-code --model MODEL
bundle/artifacts/change-h-formula-check/verify.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks of the task change-h-formula against the kmplot app's state, exported by REA from a desktop application capture.
2
+
3
+ It reads the app's data/get through the computer, takes the typed views of its files and evaluates each check: no
4
+ model, no code from the task. It grades once the app's files settle, since an app can save a few seconds after the
5
+ last change: each result's settled says whether they had held for SETTLE_WINDOW_S, or had not by SETTLE_BOUND_S and
6
+ the last completed read was graded, and read_cut whether a read still running at SETTLE_BOUND_S was cut. A failure to
7
+ reach the app raises, so the run fails rather than scoring the agent.
8
+ """
9
+ import asyncio
10
+ import hashlib
11
+ import json
12
+ import math
13
+ import re
14
+ import time
15
+
16
+ from agentenv_protocol import client as protocol
17
+ from agentenv_protocol.types import RPC_PATH
18
+
19
+ APP = "kmplot"
20
+ CHECKS = [
21
+ {"id": "h-new-formula", "kind": "line_count", "file": "Documents/lesson_plots.fkt", "contains": ">h(x) = 2x + 1<", "equals": 1},
22
+ {"id": "h-old-formula-gone", "kind": "line_count", "file": "Documents/lesson_plots.fkt", "contains": ">h(x) = 0.5x + 1<", "equals": 0},
23
+ {"id": "g-unchanged", "kind": "line_count", "file": "Documents/lesson_plots.fkt", "contains": ">g(x) = 2sin(x)<", "equals": 1},
24
+ {"id": "f-unchanged", "kind": "line_count", "file": "Documents/lesson_plots.fkt", "contains": ">f(x) = x^2", "equals": 1},
25
+ {"id": "three-functions", "kind": "line_count", "file": "Documents/lesson_plots.fkt", "contains": "<function ", "equals": 3},
26
+ ]
27
+ #: The app's data/get is read this often until its files settle.
28
+ SETTLE_INTERVAL_S = 0.5
29
+ #: How long each file's bytes must hold, from the read that returned them, before the views are graded.
30
+ SETTLE_WINDOW_S = 3.0
31
+ #: After the first read began: no read starts then or later, one still running is cut, and the last completed read is
32
+ #: graded though the files are still changing.
33
+ SETTLE_BOUND_S = 15.0
34
+ #: Where a data/get file part names its path in the home.
35
+ DATA_OBJECTS = "urn:agentenv:data-objects/v1"
36
+
37
+ MISSING = object()
38
+ INDEX = re.compile(r"0|[1-9][0-9]*")
39
+ VIEW_FORMATS = ("text", "json", "keyfile", "xml")
40
+ NUMERAL = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")
41
+ WHITESPACE_RUN = re.compile(r"[ \t\r\n]+")
42
+
43
+
44
+ def _shown(value) -> str:
45
+ text = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
46
+ return text if len(text) <= 200 else text[:200] + "…"
47
+
48
+
49
+ def _same(actual, expected) -> bool:
50
+ """JSON equality: numbers by value but never a boolean for a number, objects by their keys, arrays in order."""
51
+ if isinstance(expected, list):
52
+ return (isinstance(actual, list) and len(actual) == len(expected)
53
+ and all(_same(item, wanted) for item, wanted in zip(actual, expected)))
54
+ if isinstance(expected, dict):
55
+ return (isinstance(actual, dict) and len(actual) == len(expected)
56
+ and all(key in actual and _same(actual[key], value) for key, value in expected.items()))
57
+ if isinstance(expected, bool) or isinstance(actual, bool):
58
+ return isinstance(expected, bool) and isinstance(actual, bool) and actual == expected
59
+ if isinstance(expected, (int, float)):
60
+ return isinstance(actual, (int, float)) and actual == expected
61
+ return type(actual) is type(expected) and actual == expected
62
+
63
+
64
+ def _is_element(value) -> bool:
65
+ return (isinstance(value, dict) and isinstance(value.get("name"), str) and isinstance(value.get("attributes"), dict)
66
+ and isinstance(value.get("children"), list))
67
+
68
+
69
+ def _element_text(element, attribute=None) -> str:
70
+ """An element's text as XPath's string() reads it from what the view keeps: every text node among its children
71
+ and its descendants', in document order. With attribute, the values of that attribute on it and its descendants
72
+ instead, in document order, and no text node."""
73
+ parts, pending = [], [element]
74
+ while pending:
75
+ node = pending.pop()
76
+ if isinstance(node, str):
77
+ if attribute is None:
78
+ parts.append(node)
79
+ elif _is_element(node):
80
+ if attribute is not None and isinstance(node["attributes"].get(attribute), str):
81
+ parts.append(node["attributes"][attribute])
82
+ pending.extend(reversed(node["children"]))
83
+ return "".join(parts)
84
+
85
+
86
+ def _bracketed(token: str) -> bool:
87
+ return len(token) >= 2 and token.startswith("[") and token.endswith("]")
88
+
89
+
90
+ def _selector(token: str):
91
+ """A selector's conditions, [KEY=VALUE], [@KEY=VALUE] or [>KEY=VALUE] one or more times, or None when the token
92
+ is not one."""
93
+ if not _bracketed(token):
94
+ return None
95
+ conditions = []
96
+ for part in token[1:-1].split("]["):
97
+ key, equals, value = part.partition("=")
98
+ prefix = key[:1] if key[:1] in ("@", ">") else ""
99
+ name = key[len(prefix):]
100
+ if not equals or not name:
101
+ return None
102
+ conditions.append((prefix, name, value))
103
+ return conditions
104
+
105
+
106
+ def _has_child_text(member, key: str, value: str) -> bool:
107
+ """Whether an element has a child element named key whose text, its whitespace collapsed, is value."""
108
+ return _is_element(member) and any(
109
+ _is_element(child) and child["name"] == key and _collapse_whitespace(_element_text(child)) == value
110
+ for child in member["children"])
111
+
112
+
113
+ def _selects(member, conditions) -> bool:
114
+ """Whether an array member meets every condition; selectors compare strings only."""
115
+ if not isinstance(member, dict):
116
+ return False
117
+ for prefix, key, value in conditions:
118
+ if prefix == ">":
119
+ if not _has_child_text(member, key, value):
120
+ return False
121
+ continue
122
+ fields = member.get("attributes") if prefix == "@" else member
123
+ if not isinstance(fields, dict) or not isinstance(fields.get(key), str) or fields[key] != value:
124
+ return False
125
+ return True
126
+
127
+
128
+ def _step(items: list, token: str, last: bool):
129
+ """One step into an array, by index or by a selector that must match one member, or none when it is the last."""
130
+ if INDEX.fullmatch(token):
131
+ return ("member", items[int(token)]) if int(token) < len(items) else ("none", None)
132
+ conditions = _selector(token)
133
+ if conditions is None:
134
+ return ("unresolved", f"{token} is not a selector of the form [KEY=VALUE]") if _bracketed(token) else (
135
+ "none", None)
136
+ matched = [item for item in items if _selects(item, conditions)]
137
+ if len(matched) == 1:
138
+ return "member", matched[0]
139
+ if len(matched) > 1:
140
+ return "unresolved", f"{token} matches {len(matched)} members, not one"
141
+ return ("none" if last else "unresolved"), f"{token} matches no member"
142
+
143
+
144
+ def _locate(view, pointer: str):
145
+ """Where a pointer leads: ("value", value), ("none", why or None) or ("unresolved", problem), with the pointers
146
+ to the arrays a selector searched on the way."""
147
+ current, searched = view, []
148
+ segments = pointer[1:].split("/")
149
+ for position, segment in enumerate(segments):
150
+ token = segment.replace("~1", "/").replace("~0", "~")
151
+ if isinstance(current, list):
152
+ if not INDEX.fullmatch(token) and _selector(token) is not None:
153
+ searched.append("".join("/" + part for part in segments[:position]))
154
+ kind, found = _step(current, token, position == len(segments) - 1)
155
+ if kind != "member":
156
+ return kind, found, searched
157
+ current = found
158
+ elif isinstance(current, dict) and token in current:
159
+ current = current[token]
160
+ else:
161
+ return "none", None, searched
162
+ return "value", current, searched
163
+
164
+
165
+ def _number(value):
166
+ """A number, or a numeral string read as one; None for anything else, a boolean, or a numeral past the doubles."""
167
+ if isinstance(value, bool):
168
+ return None
169
+ if isinstance(value, (int, float)):
170
+ return value
171
+ if not isinstance(value, str) or not NUMERAL.fullmatch(value):
172
+ return None
173
+ number = float(value)
174
+ return number if math.isfinite(number) else None
175
+
176
+
177
+ def _entry_leaves_out(entry) -> bool:
178
+ return isinstance(entry, dict) and (isinstance(entry.get("view_error"), str) or (
179
+ entry.get("format") in ("text", "xml") and isinstance(entry.get("view"), dict)
180
+ and entry["view"].get("truncated") is True))
181
+
182
+
183
+ def _viewless_entry(view, pointer: str):
184
+ """The name of the entry whose view a pointer goes into when it has none, so its null is no JSON value, and
185
+ why: binary, unread, or of a format without a view; None when it has one."""
186
+ parts = pointer[1:].split("/")
187
+ if len(parts) < 3 or parts[0] != "entries" or parts[2] != "view":
188
+ return None
189
+ kind, item, _ = _locate(view, "/entries/" + parts[1])
190
+ if kind != "value" or not isinstance(item, dict):
191
+ return None
192
+ if isinstance(item.get("view_error"), str):
193
+ reason = f"has no view: {item['view_error']}"
194
+ elif item.get("format") == "binary":
195
+ reason = "is binary and has no view"
196
+ elif item.get("format") not in VIEW_FORMATS:
197
+ reason = "has no view"
198
+ else:
199
+ return None
200
+ return (item["name"] if isinstance(item.get("name"), str) else ""), reason
201
+
202
+
203
+ def _array_leaves_out(form, view, array: str) -> bool:
204
+ """Whether an array a selector searched may lack members: in a zip the listing or its entry's view, else the
205
+ view's own truncation."""
206
+ if form != "zip":
207
+ return _truncated(form, view)
208
+ if array == "/entries":
209
+ return isinstance(view, dict) and view.get("truncated") is True
210
+ return _zip_leaves_out(view, array)
211
+
212
+
213
+ def _zip_leaves_out(view, pointer: str) -> bool:
214
+ """Whether a zip view leaves out what a pointer reaches: for a pointer into one listed entry, only that entry."""
215
+ if not isinstance(view, dict):
216
+ return False
217
+ parts = pointer[1:].split("/")
218
+ if parts[0] == "entries" and len(parts) > 1:
219
+ kind, entry, _ = _locate(view, "/entries/" + parts[1])
220
+ return _entry_leaves_out(entry) if kind == "value" else view.get("truncated") is True
221
+ entries = view.get("entries") if isinstance(view.get("entries"), list) else []
222
+ return view.get("truncated") is True or any(_entry_leaves_out(entry) for entry in entries)
223
+
224
+
225
+ def _truncated(form, view) -> bool:
226
+ if not isinstance(view, dict):
227
+ return False
228
+ if form in ("text", "xml"):
229
+ return view.get("truncated") is True
230
+ if form != "sqlite":
231
+ return False
232
+ tables = view.get("tables")
233
+ return view.get("tables_truncated") is True or any(
234
+ isinstance(table, dict) and (table.get("truncated") is True or isinstance(table.get("error"), str))
235
+ for table in (tables.values() if isinstance(tables, dict) else []))
236
+
237
+
238
+ def _view_of(check, entry, form):
239
+ """The view, whether it is truncated, and why the check cannot read it; an absent file reads as empty."""
240
+ if entry is None:
241
+ return None, False, None
242
+ if isinstance(entry.get("error"), str):
243
+ return None, False, f"{check['file']} has no view: {entry['error']}"
244
+ if entry.get("format") in (None, "binary"):
245
+ return None, False, f"{check['file']} is binary and has no view"
246
+ if form is not None and entry.get("format") != form:
247
+ return None, False, f"{check['file']} is read as {entry.get('format')}, not {form}"
248
+ return entry.get("view"), _truncated(entry.get("format"), entry.get("view")), None
249
+
250
+
251
+ def _undecided(check):
252
+ return False, f"the view of {check['file']} is truncated, so what it leaves out is unknown"
253
+
254
+
255
+ def _compared(check, n: int, what: str):
256
+ operator = next(key for key in ("equals", "at_least", "at_most") if check.get(key) is not None)
257
+ expected = check[operator]
258
+ met = n == expected if operator == "equals" else n >= expected if operator == "at_least" else n <= expected
259
+ return met, f"{n} {what}, expected {operator.replace('_', ' ')} {expected}"
260
+
261
+
262
+ def _lines(check, entry):
263
+ view, truncated, problem = _view_of(check, entry, "text")
264
+ if problem is not None:
265
+ return False, problem
266
+ lines = view.get("lines") if isinstance(view, dict) and isinstance(view.get("lines"), list) else []
267
+ lines = [line for line in lines if isinstance(line, str)]
268
+ file = check["file"]
269
+ if check["kind"] == "lines_present":
270
+ missing = next((line for line in check["lines"] if line not in lines), None)
271
+ return (True, f"{file} has the line(s) {_shown(check['lines'])}") if missing is None else (
272
+ False, f"{file} has no line {_shown(missing)}")
273
+ if truncated:
274
+ return _undecided(check)
275
+ if check["kind"] == "lines_absent":
276
+ found = next((line for line in check["lines"] if line in lines), None)
277
+ return (True, f"{file} has none of the lines {_shown(check['lines'])}") if found is None else (
278
+ False, f"{file} still has the line {_shown(found)}")
279
+ if check.get("contains") is not None:
280
+ n = sum(1 for line in lines if check["contains"] in line)
281
+ return _compared(check, n, f"line(s) of {file} contain {_shown(check['contains'])}")
282
+ n = sum(1 for line in lines if line == check["exact"])
283
+ return _compared(check, n, f"line(s) of {file} match {_shown(check['exact'])}")
284
+
285
+
286
+ def _near(at: str, found, expected, tolerance):
287
+ """A value compared within a tolerance: numbers, and numeral strings, by their difference."""
288
+ number = _number(found)
289
+ within = f"within {_shown(tolerance)} of {_shown(expected)}"
290
+ if number is None:
291
+ return False, f"{at} is {_shown(found)}, not a number"
292
+ if abs(number - expected) <= tolerance:
293
+ return True, f"{at} is {_shown(found)}, {within}"
294
+ return False, f"{at} is {_shown(found)}, not {within}"
295
+
296
+
297
+ def _value(check, entry):
298
+ view, truncated, problem = _view_of(check, entry, None)
299
+ if problem is not None:
300
+ return False, problem
301
+ kind, found, searched = ("none", None, []) if entry is None else _locate(view, check["pointer"])
302
+ at = f"{check['file']} at {check['pointer']}"
303
+ viewless = _viewless_entry(view, check["pointer"]) if entry is not None and entry.get("format") == "zip" else None
304
+ if viewless is not None:
305
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
306
+ # A selector tells one member from several only in an array the view holds whole.
307
+ if any(_array_leaves_out(entry.get("format"), view, array) for array in searched):
308
+ return _undecided(check)
309
+ if kind == "unresolved":
310
+ return False, f"{at}: {found}"
311
+ if entry is not None and entry.get("format") == "zip":
312
+ truncated = _zip_leaves_out(view, check["pointer"])
313
+ if check["kind"] == "value_equals" and isinstance(check["value"], (dict, list)) and truncated:
314
+ return _undecided(check)
315
+ if check["kind"] == "value_equals":
316
+ if kind == "none":
317
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
318
+ expected = check["value"]
319
+ if check.get("tolerance") is not None and isinstance(expected, (int, float)) and not isinstance(expected, bool):
320
+ return _near(at, found, expected, check["tolerance"])
321
+ if _same(found, check["value"]):
322
+ return True, f"{at} is {_shown(check['value'])}"
323
+ return False, f"{at} is {_shown(found)}, not {_shown(check['value'])}"
324
+ if truncated:
325
+ return _undecided(check)
326
+ return (True, f"{at} has no value") if kind == "none" else (False, f"{at} is {_shown(found)}")
327
+
328
+
329
+ def _collapse_whitespace(text: str) -> str:
330
+ """Each run of XML whitespace (space, tab, CR, LF) made one space, none at either end, as normalize-space()."""
331
+ return WHITESPACE_RUN.sub(" ", text).strip(" ")
332
+
333
+
334
+ def _text_at(view, pointer: str) -> bool:
335
+ """Whether a string a pointer reaches is text of the document: a member of an element's children (a text node)
336
+ or attributes (an attribute's value), rather than an element's name or a field of the DOCTYPE."""
337
+ segments = pointer.split("/")
338
+ if len(segments) < 3 or segments[-2] not in ("children", "attributes"):
339
+ return False
340
+ kind, owner, _ = _locate(view, "/".join(segments[:-2]))
341
+ return kind == "value" and _is_element(owner)
342
+
343
+
344
+ def _not_xml_entry(check, view):
345
+ """Why a text check's pointer into an archive goes into no XML entry's view, or None when it does or names an
346
+ entry not listed."""
347
+ parts = check["pointer"].split("/")
348
+ if len(parts) < 4 or parts[3] != "view":
349
+ return f"{check['file']} at {check['pointer']} does not point into an entry's view"
350
+ if parts[1] != "entries":
351
+ return None
352
+ kind, item, _ = _locate(view, "/entries/" + parts[2])
353
+ if kind != "value" or not isinstance(item, dict) or item.get("format") == "xml":
354
+ return None
355
+ # An entry without a view failed before this, so its format is one with a view.
356
+ name, form = (value if isinstance(value, str) else "" for value in (item.get("name"), item.get("format")))
357
+ return f"{check['file']} entry {name} is read as {form}, not xml"
358
+
359
+
360
+ def _whole_text(check, entry):
361
+ """An element's whole text, or a text node's, compared with the value or searched for it."""
362
+ view, truncated, problem = _view_of(check, entry, None)
363
+ if problem is not None:
364
+ return False, problem
365
+ at = f"{check['file']} at {check['pointer']}"
366
+ if entry is None:
367
+ return False, f"{at} has no value"
368
+ form = entry.get("format")
369
+ if form not in ("xml", "zip"):
370
+ return False, f"{check['file']} is read as {form}, not xml"
371
+ kind, found, searched = _locate(view, check["pointer"])
372
+ viewless = _viewless_entry(view, check["pointer"]) if form == "zip" else None
373
+ if viewless is not None:
374
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
375
+ if any(_array_leaves_out(form, view, array) for array in searched):
376
+ return _undecided(check)
377
+ problem = _not_xml_entry(check, view) if form == "zip" else None
378
+ if problem is not None:
379
+ return False, problem
380
+ if kind == "unresolved":
381
+ return False, f"{at}: {found}"
382
+ if kind == "none":
383
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
384
+ # Only an element has attributes of its own and of its descendants to join.
385
+ attribute = check.get("text_attribute")
386
+ if not ((attribute is None and _text_at(view, check["pointer"])) if isinstance(found, str) else _is_element(found)):
387
+ what = "an element, a text node or an attribute value" if attribute is None else "an element"
388
+ return False, f"{at} is {_shown(found)}, not {what}"
389
+ # A text node is whole. An element's text in a cut view may lack what the cut dropped from its middle.
390
+ if form == "zip":
391
+ truncated = _zip_leaves_out(view, check["pointer"])
392
+ if not isinstance(found, str) and truncated:
393
+ return _undecided(check)
394
+ return _compared_text(check, at, _element_text(found, attribute))
395
+
396
+
397
+ def _compared_text(check, at: str, found: str):
398
+ """A text found at a pointer compared with the check's value or searched for it, both collapsed when it asks."""
399
+ collapse = check.get("normalize_whitespace") is True
400
+ text = _collapse_whitespace(found) if collapse else found
401
+ value = _collapse_whitespace(check["value"]) if collapse else check["value"]
402
+ attribute = check.get("text_attribute")
403
+ read = "" if attribute is None else f" in its {attribute} values"
404
+ how = read + (" with whitespace collapsed" if collapse else "")
405
+ if check["kind"] == "text_equals":
406
+ if text == value:
407
+ return True, f"{at} has the text {_shown(value)}{how}"
408
+ return False, f"{at} has the text {_shown(text)}{how}, not {_shown(value)}"
409
+ if value in text:
410
+ return True, f"{at} has text containing {_shown(value)}{how}"
411
+ return False, f"{at} has the text {_shown(text)}{how}, without {_shown(value)}"
412
+
413
+
414
+ def _members(check, entry):
415
+ """How many members of the array at a pointer, or of those a selector matches, compared with the expected
416
+ number."""
417
+ matching, pointer = check.get("matching"), check["pointer"]
418
+ view, truncated, problem = _view_of(check, entry, None)
419
+ if problem is not None:
420
+ return False, problem
421
+ form = None if entry is None else entry.get("format")
422
+ # The empty pointer names the whole view, as a JSON file whose top level is an array.
423
+ kind, found, searched = (("none", None, []) if entry is None else ("value", view, []) if pointer == ""
424
+ else _locate(view, pointer))
425
+ at = check["file"] if pointer == "" else f"{check['file']} at {pointer}"
426
+ viewless = _viewless_entry(view, pointer) if form == "zip" else None
427
+ if viewless is not None:
428
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
429
+ if any(_array_leaves_out(form, view, array) for array in searched):
430
+ return _undecided(check)
431
+ if kind == "unresolved":
432
+ return False, f"{at}: {found}"
433
+ if kind == "none":
434
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
435
+ if not isinstance(found, list):
436
+ return False, f"{at} is {_shown(found)}, not an array"
437
+ # A count is decided only on an array the view holds whole.
438
+ if _array_leaves_out(form, view, pointer):
439
+ return _undecided(check)
440
+ # The parser refuses a matching that is no selector.
441
+ conditions = None if matching is None else _selector(matching)
442
+ n = len(found) if matching is None else sum(1 for item in found if conditions and _selects(item, conditions))
443
+ return _compared(check, n, f"member(s) of {at}" + ("" if matching is None else f" matching {matching}"))
444
+
445
+
446
+ def _rows(check, entry):
447
+ view, _, problem = _view_of(check, entry, "sqlite")
448
+ if problem is not None:
449
+ return False, problem
450
+ view = view if isinstance(view, dict) else {}
451
+ tables = view.get("tables") if isinstance(view.get("tables"), dict) else {}
452
+ table = tables[check["table"]] if check["table"] in tables else MISSING
453
+ name = f"{check['file']} table {check['table']}"
454
+ if table is MISSING and view.get("tables_truncated") is True:
455
+ return _undecided(check)
456
+ table = table if isinstance(table, dict) else {}
457
+ if isinstance(table.get("error"), str):
458
+ return False, f"{name} could not be read: {table['error']}"
459
+ columns = table.get("columns") if isinstance(table.get("columns"), list) else []
460
+ rows = table.get("rows") if isinstance(table.get("rows"), list) else []
461
+ where = check.get("where") or {}
462
+
463
+ def matches(row) -> bool:
464
+ return isinstance(row, list) and all(
465
+ column in columns and columns.index(column) < len(row) and _same(row[columns.index(column)], value)
466
+ for column, value in where.items())
467
+
468
+ n = sum(1 for row in rows if matches(row))
469
+ if check["kind"] == "row_present":
470
+ return (n > 0, f"{name} has a row with {_shown(where)}" if n > 0 else f"{name} has no row with {_shown(where)}")
471
+ if table.get("truncated") is True:
472
+ return _undecided(check)
473
+ if check["kind"] == "row_absent":
474
+ return (True, f"{name} has no row with {_shown(where)}") if n == 0 else (
475
+ False, f"{name} has {n} row(s) with {_shown(where)}")
476
+ return _compared(check, n, f"row(s) of {name}" + (f" with {_shown(where)}" if "where" in check else ""))
477
+
478
+
479
+ def _verdict(check, entry):
480
+ kind = check["kind"]
481
+ if kind == "file_present":
482
+ return (entry is not None, f"{check['file']} exists" if entry is not None else f"{check['file']} does not exist")
483
+ if kind == "file_absent":
484
+ return (entry is None, f"{check['file']} does not exist" if entry is None else f"{check['file']} exists")
485
+ if kind in ("lines_present", "lines_absent", "line_count"):
486
+ return _lines(check, entry)
487
+ if kind in ("value_equals", "value_absent"):
488
+ return _value(check, entry)
489
+ if kind in ("text_equals", "text_contains"):
490
+ return _whole_text(check, entry)
491
+ if kind == "member_count":
492
+ return _members(check, entry)
493
+ return _rows(check, entry)
494
+
495
+
496
+ def evaluate(checks: list, views: dict) -> list:
497
+ """One result per check against the views data/get returned, by home path."""
498
+ results = []
499
+ for check in checks:
500
+ passed, description = _verdict(check, views.get(check["file"]))
501
+ results.append({"id": check["id"], "result": passed, "description": description})
502
+ return results
503
+
504
+
505
+ def _files(answer) -> list:
506
+ """Each file data/get returned, by its home path or its place among the parts, with the SHA-256 of its bytes as
507
+ sent: what changes when the app saves."""
508
+ files = []
509
+ for index, part in enumerate(answer.parts):
510
+ if part.kind != "file":
511
+ continue
512
+ marker = (getattr(part, "metadata", None) or {}).get(DATA_OBJECTS)
513
+ path = marker.get("path") if isinstance(marker, dict) else None
514
+ content = getattr(part.file, "bytes", None) or getattr(part.file, "uri", None) or ""
515
+ files.append((path if isinstance(path, str) else f"#{index}", hashlib.sha256(content.encode()).hexdigest()))
516
+ return sorted(files)
517
+
518
+
519
+ async def _read(url):
520
+ answer = await protocol.get_data(url, timeout=120)
521
+ states = [part.data["state"] for part in answer.parts
522
+ if part.kind == "data" and isinstance(part.data.get("state"), dict)]
523
+ if not states:
524
+ raise RuntimeError(f"the {APP} app's data/get returned no state views")
525
+ return states[0], _files(answer)
526
+
527
+
528
+ async def _settled_views(url):
529
+ """The app's views once each file's bytes have held for SETTLE_WINDOW_S, counted from the read that returned them,
530
+ read every SETTLE_INTERVAL_S; else the last completed read's. No read starts SETTLE_BOUND_S or more after the first
531
+ began, and one still running then is cut. Also whether the files had held, and whether a read was cut."""
532
+ start = time.monotonic()
533
+ # The first read is the one a grade needs, so only its own timeout bounds it.
534
+ views, files = await _read(url)
535
+ # Offsets from the first read's start: when the last completed read began, and when a read first returned the
536
+ # bytes it holds.
537
+ began, since = 0.0, time.monotonic() - start
538
+ while began - since < SETTLE_WINDOW_S:
539
+ # Reads come an interval apart, and the one that can settle the files as soon as the window allows.
540
+ at = max(min(began + SETTLE_INTERVAL_S, since + SETTLE_WINDOW_S), time.monotonic() - start)
541
+ if at >= SETTLE_BOUND_S:
542
+ return views, False, False
543
+ await asyncio.sleep(max(0.0, at - (time.monotonic() - start)))
544
+ at = max(at, time.monotonic() - start)
545
+ if at >= SETTLE_BOUND_S:
546
+ return views, False, False
547
+ try:
548
+ latest_views, latest = await asyncio.wait_for(_read(url), SETTLE_BOUND_S - at)
549
+ except asyncio.TimeoutError:
550
+ return views, False, True
551
+ began, views = at, latest_views
552
+ if latest != files:
553
+ since, files = time.monotonic() - start, latest
554
+ return views, True, False
555
+
556
+
557
+ async def verify(mcp_url, env_url):
558
+ card = await protocol.get_card(env_url)
559
+ child = protocol.find_child(card, APP)
560
+ if child is None:
561
+ raise RuntimeError(f"the computer at {env_url} lists no app named {APP}")
562
+ views, settled, read_cut = await _settled_views(env_url + (child.get("url") or RPC_PATH).removesuffix(RPC_PATH))
563
+ return [{**result, "settled": settled, "read_cut": read_cut} for result in evaluate(CHECKS, views)]
bundle/envs/kmplot/SKILL.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ description: Use KmPlot on this Linux desktop; its window has class kmplot.
3
+ ---
4
+
5
+ # KmPlot
6
+
7
+ KmPlot is open on the desktop at boot. Its window's class is `kmplot`.
8
+
9
+ Its files live under `~/.config/kmplotrc`, `~/Documents`. Work through the application's own
10
+ window and dialogs; the result is read from those files.
bundle/envs/kmplot/env.toml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ type = "computer_app"
2
+ module = "kmplot_app.py:Kmplot"
3
+ computer = "ubuntu-24.04"
4
+ driver = "reference"
bundle/envs/kmplot/kmplot_app.py ADDED
@@ -0,0 +1,903 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """KmPlot as an agentenv computer app, exported by REA from a desktop application capture.
2
+
3
+ Package: kmplot (captured at 4:23.08.5-0ubuntu4). Capture Evidence: ev_d8ffd3e13d18b512c3269712baf199a9ad9e5890e664ca6dd4d5822ca14f1122.
4
+ The seed was made for the task, as saved at checkpoint seed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import copy
11
+ import hashlib
12
+ import io
13
+ import json
14
+ import math
15
+ import os
16
+ import re
17
+ import sqlite3
18
+ import struct
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ import zipfile
23
+ import zlib
24
+ from pathlib import Path
25
+ from xml.parsers import expat
26
+
27
+ from agentenv_protocol import add_data, get_data, reset_data
28
+ from agentenv_protocol.computer import AptSource, ComputerAppEnvironment, Download, Launch, Packages, Ready, RunScript, computer_app, linux, ready_check
29
+ from agentenv_protocol.computer.app_data import INITIAL, add, get, in_thread, keep_initial, reset
30
+ from agentenv_protocol.types import DataPart
31
+
32
+ HERE = Path(__file__).resolve().parent
33
+ SEED_HOME = "/home/user"
34
+ PATHS = [".config/kmplotrc", "Documents"]
35
+ DCONF = ""
36
+ TEXT_SEEDS = frozenset([".config/kmplotrc", "Documents/lesson_plots.fkt"])
37
+ WINDOW_CLASS = "kmplot"
38
+
39
+ XML_SUFFIXES = (".xml", ".xbel", ".plist", ".svg", ".ui")
40
+ GROUP_HEADER = re.compile(r"^\[([^\]]+)\]$")
41
+ LINE_BREAK = re.compile(r"\r?\n")
42
+ SQLITE_HEADER = b"SQLite format 3\x00"
43
+ GVDB_HEADER = b"GVariant"
44
+ ZIP_HEADER = b"PK\x03\x04"
45
+ GZIP_HEADER = b"\x1f\x8b\x08"
46
+ XML_SPACE = "xml:space"
47
+ MAX_VIEW_BYTES = 64 * 1024 * 1024
48
+ MAX_SAFE_INTEGER = 2**53 - 1
49
+ MAX_TABLES = 64
50
+ MAX_ROWS = 500
51
+ MAX_LINES = 5000
52
+ MAX_XML_NODES = 5000
53
+ MAX_XML_DEPTH = 64
54
+ SQLITE_BUSY_S = 0.25
55
+ MAX_PARSED_BYTES = 4 * 1024 * 1024
56
+ PARSED_TOO_LARGE = "larger than the 4 MiB limit for JSON and key file views"
57
+ MAX_JSON_VIEW_DEPTH = 500
58
+ JSON_TOO_DEEP = f"nested deeper than the {MAX_JSON_VIEW_DEPTH} levels a JSON view keeps"
59
+ #: A JSON token after any whitespace, by group: an opening, a closing, a comma, a colon, a string's quote, or a number
60
+ #: or literal. Strings are read by json's scanner, since a pattern repeating per escape holds memory for each.
61
+ JSON_TOKEN = re.compile(r'[ \t\n\r]*(?:([\[{])|([\]}])|(,)|(:)|(")|(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?'
62
+ r"|true|false|null))")
63
+ JSON_SPACE = re.compile(r"[ \t\n\r]*")
64
+
65
+
66
+ def _respelled(text: str, home: Path) -> str:
67
+ """The seed's home path respelled to this computer's home, only where a whole path segment ends after it."""
68
+ return re.sub(re.escape(SEED_HOME) + r"(?![\w.@+~-])", lambda _: str(home), text)
69
+
70
+
71
+ def _respelled_utf16(data: bytes, home: Path) -> bytes:
72
+ """A UTF-16 text file with a byte-order mark respelled like a text seed, its mark kept; any other bytes as given."""
73
+ for mark, codec in ((b"\xff\xfe", "utf-16-le"), (b"\xfe\xff", "utf-16-be")):
74
+ if data.startswith(mark):
75
+ try:
76
+ text = data[len(mark):].decode(codec)
77
+ except UnicodeDecodeError:
78
+ return data
79
+ return mark + _respelled(text, home).encode(codec) if SEED_HOME in text else data
80
+ return data
81
+
82
+
83
+ #: What marks a window as not yet the app's own: skipping the taskbar, as splash screens and dialogs do, or a splash type.
84
+ SPLASH_MARKS = ("_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_WINDOW_TYPE_SPLASH")
85
+
86
+
87
+ def _taskbar_window(window_class: str) -> bool:
88
+ """Whether a top-level window of the given class that the taskbar lists is shown; a splash screen or a dialog
89
+ skips the taskbar."""
90
+ def xprop(*args: str) -> str:
91
+ done = subprocess.run(["xprop", *args], capture_output=True, text=True)
92
+ return done.stdout if done.returncode == 0 else ""
93
+
94
+ for window in re.findall(r"0x[0-9a-f]+", xprop("-root", "_NET_CLIENT_LIST").partition("#")[2]):
95
+ props = xprop("-id", window, "WM_CLASS", "_NET_WM_STATE", "_NET_WM_WINDOW_TYPE")
96
+ classes = re.findall(r'"((?:[^"\\]|\\.)*)"', props.partition("WM_CLASS")[2].split("\n", 1)[0])
97
+ if window_class in classes and not any(mark in props for mark in SPLASH_MARKS):
98
+ return True
99
+ return False
100
+
101
+
102
+ def _seed_home(home: Path) -> None:
103
+ """Copy the captured files into this computer's home; text files, UTF-16 ones too, have the seed's home path
104
+ respelled."""
105
+ seed = HERE / "seed"
106
+ for source in sorted(seed.rglob("*")) if seed.is_dir() else []:
107
+ if not source.is_file():
108
+ continue
109
+ relative = source.relative_to(seed).as_posix()
110
+ target = home / relative
111
+ target.parent.mkdir(parents=True, exist_ok=True)
112
+ data = source.read_bytes()
113
+ if relative in TEXT_SEEDS:
114
+ data = _respelled(data.decode("utf-8"), home).encode("utf-8")
115
+ else:
116
+ data = _respelled_utf16(data, home)
117
+ target.write_bytes(data)
118
+
119
+
120
+ def _dconf(arguments: list, environment: dict) -> str:
121
+ return subprocess.run(["dconf", *arguments], env={**os.environ, **environment}, capture_output=True, text=True,
122
+ check=True).stdout
123
+
124
+
125
+ def _load_dconf(home: Path) -> None:
126
+ """Compile the captured dconf keys into the user database without D-Bus, which is not up yet. Keys already there
127
+ stay unless captured: dconf compile reads the key files in name order and a later file wins. A failure is
128
+ reported and the app starts without them."""
129
+ if not DCONF:
130
+ return
131
+ database = home / ".config" / "dconf" / "user"
132
+ try:
133
+ database.parent.mkdir(parents=True, exist_ok=True)
134
+ with tempfile.TemporaryDirectory(dir=database.parent) as scratch:
135
+ keyfiles = Path(scratch, "keyfiles")
136
+ keyfiles.mkdir()
137
+ if database.is_file():
138
+ profile = Path(scratch, "profile")
139
+ profile.write_text(f"file-db:{database}\n")
140
+ existing = _dconf(["dump", "/"], {"DCONF_PROFILE": str(profile)})
141
+ (keyfiles / "00-existing").write_text(existing)
142
+ (keyfiles / "01-captured").write_text(_respelled(DCONF, home))
143
+ _dconf(["compile", str(Path(scratch, "user")), str(keyfiles)], {})
144
+ os.replace(Path(scratch, "user"), database)
145
+ except (OSError, subprocess.CalledProcessError) as error:
146
+ detail = (getattr(error, "stderr", None) or "").strip().splitlines()
147
+ print(f"warning: the captured dconf settings were not loaded: {detail[-1] if detail else error}",
148
+ file=sys.stderr)
149
+
150
+
151
+ def _sqlite_text(data: bytes):
152
+ text = data.decode("utf-8", "replace")
153
+ return {"text": text, "bytes_hex": data.hex()} if "�" in text else text
154
+
155
+
156
+ def _cell(value):
157
+ if isinstance(value, bytes):
158
+ return {"blob_hex": value.hex()}
159
+ if isinstance(value, int) and abs(value) > MAX_SAFE_INTEGER:
160
+ return {"integer": str(value)}
161
+ # JSON has no infinities or negative zero; REA's SQLite reader spells them as strings.
162
+ if isinstance(value, float) and (math.isinf(value) or (value == 0 and math.copysign(1, value) < 0)):
163
+ return "Infinity" if value == math.inf else "-Infinity" if value == -math.inf else "-0"
164
+ return value
165
+
166
+
167
+ def _table(db, name: str, primary_key: list) -> dict:
168
+ quoted = '"' + name.replace('"', '""') + '"'
169
+ cursor = db.execute(f"select * from main.{quoted} not indexed limit {MAX_ROWS + 1}")
170
+ rows = [[_cell(value) for value in row] for row in cursor]
171
+ return {"columns": [column[0] for column in cursor.description], "primary_key": primary_key,
172
+ "rows": rows[:MAX_ROWS], "truncated": len(rows) > MAX_ROWS}
173
+
174
+
175
+ def _sqlite(path: Path) -> dict:
176
+ """The database's ordinary tables, in schema order, up to REA's table and row limits."""
177
+ with contextlib.closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=SQLITE_BUSY_S)) as db:
178
+ kinds = dict(db.execute("select name, type from pragma_table_list where schema = 'main'"))
179
+ names = [name for (name,) in db.execute("select name from sqlite_schema where type = 'table'")
180
+ if kinds.get(name) == "table"]
181
+ keys = {name: [key for (key,) in db.execute(
182
+ "select name from pragma_table_info(?, 'main') where pk > 0 order by pk", (name,))]
183
+ for name in names[:MAX_TABLES]}
184
+ db.text_factory = _sqlite_text
185
+ tables = {name: _table(db, name, keys[name]) for name in names[:MAX_TABLES]}
186
+ cut = len(names) > MAX_TABLES
187
+ return {"format": "sqlite", "view": {"tables": tables, "tables_truncated": cut},
188
+ "truncated": cut or any(table["truncated"] for table in tables.values())}
189
+
190
+
191
+ def _text(text: str) -> dict:
192
+ lines = LINE_BREAK.split(text)
193
+ if lines[-1] == "":
194
+ lines.pop()
195
+ view = {"lines": lines[:MAX_LINES], "line_count": len(lines), "truncated": len(lines) > MAX_LINES}
196
+ return {"format": "text", "view": view, "truncated": view["truncated"]}
197
+
198
+
199
+ def _keyfile_line(raw: str) -> tuple:
200
+ """A key file line as REA reads it: skip (blank or comment), group, entry or other."""
201
+ line = raw.strip()
202
+ if not line or line[0] in "#;":
203
+ return ("skip",)
204
+ header = GROUP_HEADER.match(line)
205
+ if header:
206
+ return ("group", header.group(1))
207
+ key, equals, value = line.partition("=")
208
+ return ("entry", key.strip(), value.strip()) if equals and key else ("other",)
209
+
210
+
211
+ def _each_line(text: str):
212
+ """Each line of text as REA splits them, one at a time."""
213
+ start = 0
214
+ for line_break in LINE_BREAK.finditer(text):
215
+ yield text[start:line_break.start()]
216
+ start = line_break.end()
217
+ yield text[start:]
218
+
219
+
220
+ def _is_keyfile(text: str) -> bool:
221
+ """REA's rule: at least one group, and nothing a key file view would drop. Lines are read one at a time, stopping
222
+ at the first it would drop."""
223
+ group = False
224
+ for line in _each_line(text):
225
+ kind = _keyfile_line(line)[0]
226
+ if kind == "other":
227
+ return False
228
+ group = group or kind == "group"
229
+ return group
230
+
231
+
232
+ def _keyfile(text: str) -> dict:
233
+ groups, group = {}, ""
234
+ for line in map(_keyfile_line, LINE_BREAK.split(text)):
235
+ if line[0] == "group":
236
+ group = line[1]
237
+ groups.setdefault(group, {})
238
+ elif line[0] == "entry":
239
+ groups.setdefault(group, {})[line[1]] = line[2]
240
+ return groups
241
+
242
+
243
+ #: XML's whitespace, which alone can be formatting between elements; Unicode's wider set is text.
244
+ XML_WHITESPACE = " \t\r\n"
245
+ PREDEFINED_ENTITIES = ("amp", "lt", "gt", "apos", "quot")
246
+ ENTITY_REFERENCE = re.compile(r"&([^#;][^;]*);")
247
+
248
+
249
+ def _expat(namespaces: bool, doctype=None):
250
+ """An expat parser that reads a DOCTYPE as REA does: one with an internal subset, which could declare entities,
251
+ is refused, the DTD it names is never read, and a reference to an entity other than XML's five is refused where
252
+ expat would skip it. With namespaces it also enforces their rules, as REA's parser does, and without them it
253
+ reports names as the document spells them. doctype, when given, receives the declared name and identifiers."""
254
+ parser = expat.ParserCreate(namespace_separator=" " if namespaces else None)
255
+ parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)
256
+
257
+ def declared(name: str, system_id, public_id, internal_subset: bool) -> None:
258
+ if internal_subset:
259
+ raise ValueError("the document's DOCTYPE has an internal subset")
260
+ if doctype is not None:
261
+ doctype({"name": name, "public_id": public_id, "system_id": system_id})
262
+
263
+ def undeclared(name: str, _parameter: bool) -> None:
264
+ raise ValueError(f"the document refers to the undeclared entity {name}")
265
+
266
+ def external(*_) -> None:
267
+ raise ValueError("the document refers to an external entity")
268
+
269
+ parser.StartDoctypeDeclHandler = declared
270
+ parser.SkippedEntityHandler = undeclared
271
+ parser.ExternalEntityRefHandler = external
272
+ return parser
273
+
274
+
275
+ def _check_tag(markup: str) -> None:
276
+ """expat leaves an undeclared entity out of an attribute value without a word when a DOCTYPE names a DTD; REA's
277
+ parser refuses it. With text taken by its own handler, a start tag is the only markup expat passes here that
278
+ starts with < and a name, and it passes it whole."""
279
+ if markup[:1] == "<" and markup[1:2] not in ("!", "?", "/"):
280
+ for name in ENTITY_REFERENCE.findall(markup):
281
+ if name not in PREDEFINED_ENTITIES:
282
+ raise ValueError(f"the document refers to the undeclared entity {name}")
283
+
284
+
285
+ def _ignore_text(_text: str) -> None:
286
+ pass
287
+
288
+
289
+ class _XmlReader:
290
+ """REA's XML view built as expat reads: names as spelled, declarations as attributes, text split where REA's DOM
291
+ splits it (an empty CDATA section joins the text around it), and each node counted against REA's limits."""
292
+
293
+ def __init__(self) -> None:
294
+ self.remaining, self.truncated, self.root, self.doctype = MAX_XML_NODES, False, None, None
295
+ #: Per open element: its view or None when left out, whether xml:space="preserve" applies inside it, whether
296
+ #: it holds an element, and whether it holds text other than whitespace: whitespace-only text is formatting
297
+ #: only in an element that holds elements and no such text.
298
+ self.open = []
299
+ self.text, self.cdata = [], None
300
+
301
+ def read(self, text: str) -> None:
302
+ parser = _expat(False, self._doctype)
303
+ parser.buffer_text = True
304
+ parser.StartElementHandler, parser.EndElementHandler = self._start, self._end
305
+ parser.CharacterDataHandler = self._data
306
+ parser.StartCdataSectionHandler, parser.EndCdataSectionHandler = self._cdata_start, self._cdata_end
307
+ parser.CommentHandler = parser.ProcessingInstructionHandler = self._other
308
+ parser.Parse(text, True)
309
+
310
+ def _doctype(self, declared: dict) -> None:
311
+ self.doctype = declared
312
+
313
+ def _admit(self) -> bool:
314
+ """Whether the next node inside a kept element is kept, within the node and depth limits; one past them
315
+ marks the view truncated."""
316
+ if self.open and self.open[-1][0] is None:
317
+ return False
318
+ if self.remaining <= 0 or len(self.open) > MAX_XML_DEPTH:
319
+ self.truncated = True
320
+ return False
321
+ self.remaining -= 1
322
+ return True
323
+
324
+ def _text_node(self, text: str) -> None:
325
+ if self.open and text.strip(XML_WHITESPACE):
326
+ self.open[-1][3] = True
327
+ if self._admit():
328
+ self.open[-1][0]["children"].append(text)
329
+
330
+ def _flush(self) -> None:
331
+ if self.text:
332
+ text, self.text = "".join(self.text), []
333
+ self._text_node(text)
334
+
335
+ def _data(self, text: str) -> None:
336
+ (self.text if self.cdata is None else self.cdata).append(text)
337
+
338
+ def _cdata_start(self) -> None:
339
+ self.cdata = []
340
+
341
+ def _cdata_end(self) -> None:
342
+ text, self.cdata = "".join(self.cdata), None
343
+ if text:
344
+ self._flush()
345
+ self._text_node(text)
346
+
347
+ def _other(self, *_) -> None:
348
+ """A comment or processing instruction, counted like any node and never kept."""
349
+ self._flush()
350
+ if self.open:
351
+ self._admit()
352
+
353
+ def _start(self, name: str, attributes: dict) -> None:
354
+ self._flush()
355
+ parent = self.open[-1] if self.open else [None, False, False, False]
356
+ parent[2] = True
357
+ view = {"name": name, "attributes": attributes, "children": []} if self._admit() else None
358
+ if view is not None and parent[0] is not None:
359
+ parent[0]["children"].append(view)
360
+ space = attributes.get(XML_SPACE)
361
+ self.open.append([view, space == "preserve" if space else parent[1], False, False])
362
+
363
+ def _end(self, _name: str) -> None:
364
+ self._flush()
365
+ view, preserve, holds_element, holds_text = self.open.pop()
366
+ if view is not None and holds_element and not holds_text and not preserve:
367
+ view["children"] = [child for child in view["children"]
368
+ if not isinstance(child, str) or child.strip(XML_WHITESPACE)]
369
+ if not self.open:
370
+ self.root = view
371
+
372
+
373
+ def _xml_view(text: str):
374
+ """REA's XML view, or None for a document REA's parser refuses: a pass with namespaces checks the document as REA's
375
+ parser does, then a pass without them reads names as spelled, as REA's view keeps them, and the DOCTYPE."""
376
+ reader = _XmlReader()
377
+ try:
378
+ check = _expat(True)
379
+ check.CharacterDataHandler, check.DefaultHandler = _ignore_text, _check_tag
380
+ check.Parse(text, True)
381
+ reader.read(text)
382
+ except (expat.ExpatError, ValueError):
383
+ return None
384
+ view = {"root": reader.root, "truncated": reader.truncated}
385
+ return view if reader.doctype is None else {"doctype": reader.doctype, **view}
386
+
387
+
388
+ def _not_json(constant: str):
389
+ raise ValueError(f"{constant} is not JSON")
390
+
391
+
392
+ class _Inexact(Exception):
393
+ """A JSON number that REA's state view refuses, since reading it would change it."""
394
+
395
+
396
+ def _digits(text: str) -> str:
397
+ return re.split(r"[eE]", text.lstrip("-"))[0].replace(".", "").strip("0") or "0"
398
+
399
+
400
+ def _js_string(value: float) -> str:
401
+ """How JavaScript's String() writes a finite double: an integer below 1e21 in full, any other in shortest form."""
402
+ return str(int(value)) if value.is_integer() and abs(value) < 1e21 else repr(value)
403
+
404
+
405
+ def _safe_number(text: str) -> bool:
406
+ """lossless-json's isSafeNumber: an integer spelling within 2^53, or a float spelling that keeps its digits."""
407
+ if re.fullmatch(r"-?[0-9]+", text):
408
+ return len(text.lstrip("-")) <= 16 and abs(int(text)) <= MAX_SAFE_INTEGER
409
+ value = float(text)
410
+ if not math.isfinite(value):
411
+ return False
412
+ written = _js_string(value)
413
+ return written == text or _digits(written) == _digits(text)
414
+
415
+
416
+ def _exact_number(text: str):
417
+ """A JSON number read only when reading it changes nothing, as REA's state view rules: its spelling and its
418
+ written-back form both safe, and not -0."""
419
+ value = float(text)
420
+ if (not _safe_number(text) or not math.isfinite(value) or not _safe_number(_js_string(value))
421
+ or (value == 0 and math.copysign(1, value) < 0)):
422
+ raise _Inexact(text)
423
+ return int(text) if re.fullmatch(r"-?[0-9]+", text) else value
424
+
425
+
426
+ _INEXACT = object()
427
+ _LEVEL_END = object()
428
+
429
+
430
+ def _number_or_mark(spelling: str):
431
+ """A JSON number read exactly, or a mark for one REA's state view refuses."""
432
+ try:
433
+ return _exact_number(spelling)
434
+ except _Inexact:
435
+ return _INEXACT
436
+
437
+
438
+ def _holds_inexact(value) -> bool:
439
+ """Whether a parsed JSON value still holds a marked number once duplicate keys kept their last value; one
440
+ iterator per nesting level, so no child list is copied."""
441
+ levels = [iter((value,))]
442
+ while levels:
443
+ item = next(levels[-1], _LEVEL_END)
444
+ if item is _LEVEL_END:
445
+ levels.pop()
446
+ elif item is _INEXACT:
447
+ return True
448
+ elif isinstance(item, dict):
449
+ levels.append(iter(item.values()))
450
+ elif isinstance(item, list):
451
+ levels.append(iter(item))
452
+ return False
453
+
454
+
455
+ def _deeper_than(root, limit: int) -> bool:
456
+ """Whether a parsed JSON value nests deeper than a limit, as REA checks it: a value's depth is the number of
457
+ iterators open above it, one per nesting level, so no child list is copied."""
458
+ levels = [iter((root,))]
459
+ while levels:
460
+ item = next(levels[-1], _LEVEL_END)
461
+ if item is _LEVEL_END:
462
+ levels.pop()
463
+ elif len(levels) - 1 > limit:
464
+ return True
465
+ elif isinstance(item, dict):
466
+ levels.append(iter(item.values()))
467
+ elif isinstance(item, list):
468
+ levels.append(iter(item))
469
+ return False
470
+
471
+
472
+ def _is_json(text: str) -> bool:
473
+ """Whether text is one JSON value as REA's state view reads it, checked a token at a time without building it or
474
+ recursing: it holds a byte per open container and one string at a time, so text too deep for Python's parser or
475
+ too large to parse into a view is still told apart from other text."""
476
+ containers, expect, empty, at = bytearray(), "value", False, 0
477
+ while True:
478
+ token = JSON_TOKEN.match(text, at)
479
+ if token is None:
480
+ break
481
+ kind, at = token.lastindex, token.end()
482
+ if kind == 5:
483
+ try:
484
+ at = json.decoder.scanstring(text, at)[1]
485
+ except ValueError:
486
+ return False
487
+ if kind == 1 and expect == "value":
488
+ containers.append(ord(text[at - 1]))
489
+ expect, empty = ("value" if text[at - 1] == "[" else "key"), True
490
+ # A closing bracket's code is its opening's plus two.
491
+ elif kind == 2 and (expect == "after" or empty) and containers and containers[-1] == ord(text[at - 1]) - 2:
492
+ containers.pop()
493
+ expect, empty = "after", False
494
+ elif kind == 3 and expect == "after" and containers:
495
+ expect = "value" if containers[-1] == ord("[") else "key"
496
+ elif kind == 4 and expect == "colon":
497
+ expect = "value"
498
+ elif kind >= 5 and (expect == "value" or (kind == 5 and expect == "key")):
499
+ expect, empty = ("colon" if expect == "key" else "after"), False
500
+ else:
501
+ return False
502
+ return expect == "after" and not containers and JSON_SPACE.fullmatch(text, at) is not None
503
+
504
+
505
+ def _json_view(text: str, size: int):
506
+ """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
507
+ parsed-view limit, or nested past Python's recursion limit, is told apart without building its value."""
508
+ if size > MAX_PARSED_BYTES:
509
+ return {"format": "json", "view": None, "error": PARSED_TOO_LARGE} if _is_json(text) else None
510
+ # The whole text must parse, and duplicate keys settle, before an inexact number makes it JSON with an error.
511
+ try:
512
+ view = json.loads(text, parse_constant=_not_json, parse_float=_number_or_mark, parse_int=_number_or_mark)
513
+ except RecursionError:
514
+ # Nesting too deep for Python to parse is far deeper than REA's view keeps, once the rest of it is JSON too.
515
+ return {"format": "json", "view": None, "error": JSON_TOO_DEEP} if _is_json(text) else None
516
+ except ValueError:
517
+ return None
518
+ if _holds_inexact(view):
519
+ return {"format": "json", "view": None,
520
+ "error": "a number in it cannot be read exactly, such as an integer above 2^53"}
521
+ if _deeper_than(view, MAX_JSON_VIEW_DEPTH):
522
+ return {"format": "json", "view": None, "error": JSON_TOO_DEEP}
523
+ return {"format": "json", "view": view, "truncated": False}
524
+
525
+
526
+ def _text_view(name: str, text: str, size: int) -> dict:
527
+ """The format REA's state view detects for decoded text of size bytes, and its view; a JSON or key file over the
528
+ parsed-view limit is refused before its value is built."""
529
+ trimmed = re.sub(r"^[\s]+", "", text)
530
+ if name.endswith(".json") or trimmed[:1] in ("[", "{"):
531
+ view = _json_view(text, size)
532
+ if view is not None:
533
+ return view
534
+ lowered = name.lower()
535
+ # Text that opens with an element is XML if it parses, whatever the file is called, as a Freeplane map.
536
+ if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml") or re.match(r"<[A-Za-z_:]", trimmed):
537
+ view = _xml_view(text)
538
+ return _text(text) if view is None else {"format": "xml", "view": view, "truncated": view["truncated"]}
539
+ if _is_keyfile(text):
540
+ if size > MAX_PARSED_BYTES:
541
+ return {"format": "keyfile", "view": None, "error": PARSED_TOO_LARGE}
542
+ return {"format": "keyfile", "view": {"groups": _keyfile(text)}, "truncated": False}
543
+ return _text(text)
544
+
545
+
546
+ def _bytes_view(name: str, data: bytes) -> dict:
547
+ """The view of a document that is no database or archive: its text's, or none when it is binary."""
548
+ try:
549
+ text = data.decode("utf-8-sig") if b"\x00" not in data[:8192] else None
550
+ except UnicodeDecodeError:
551
+ text = None
552
+ if text is None:
553
+ return {"format": "binary", "view": None, "truncated": False}
554
+ return _text_view(name, text, len(data))
555
+
556
+
557
+ def _view(path: Path) -> dict:
558
+ """A typed JSON view of one file in the shapes of REA's state view; truncated says the view is partial."""
559
+ too_large = {"format": None, "view": None, "error": "larger than 64 MiB, the most the view reads"}
560
+ if path.stat().st_size > MAX_VIEW_BYTES:
561
+ return too_large
562
+ with path.open("rb") as file:
563
+ data = file.read(8192)
564
+ whole = data.startswith(GZIP_HEADER) or (not data.startswith(SQLITE_HEADER) and b"\x00" not in data)
565
+ data += file.read(MAX_VIEW_BYTES + 1 - len(data)) if whole else b""
566
+ if data.startswith(SQLITE_HEADER):
567
+ return _sqlite(path)
568
+ if data.startswith(ZIP_HEADER):
569
+ with path.open("rb") as file:
570
+ return _zip(file, os.fstat(file.fileno()).st_size)
571
+ if len(data) > MAX_VIEW_BYTES:
572
+ return too_large
573
+ if data.startswith(GZIP_HEADER):
574
+ return _gzip(path.name, data)
575
+ return _bytes_view(path.name, data)
576
+
577
+
578
+ def _views(home: Path, paths: list) -> dict:
579
+ """A view of every file under the app's paths, keyed by its home-relative path."""
580
+ files = {}
581
+ for owned in paths:
582
+ root = home / owned
583
+ candidates = [root] if root.is_file() else sorted(root.rglob("*")) if root.is_dir() else []
584
+ for path in candidates:
585
+ if path.is_file() and not path.is_symlink():
586
+ key = path.relative_to(home).as_posix()
587
+ try:
588
+ files[key] = _view(path)
589
+ except (OSError, ValueError, sqlite3.Error, RecursionError) as error:
590
+ files[key] = {"format": None, "view": None, "error": str(error)}
591
+ return files
592
+
593
+ MAX_ZIP_ENTRIES = 1000
594
+ MAX_ZIP_ENTRY_BYTES = 16 * 1024 * 1024
595
+ MAX_ZIP_BYTES = 64 * 1024 * 1024
596
+ MAX_ZIP_RATIO = 100
597
+ ZIP_READ_CHUNK = 64 * 1024
598
+ #: Small, since the end of each gzip member copies what is left of the piece it was read from.
599
+ GZIP_READ_CHUNK = 4 * 1024
600
+ ZIP_END = b"PK\x05\x06"
601
+ ZIP_CENTRAL = b"PK\x01\x02"
602
+ ZIP64_LOCATOR = b"PK\x06\x07"
603
+ ZIP64_END = b"PK\x06\x06"
604
+ #: Formats an archive entry may have whose reader needs a tool, a worker or another archive opened.
605
+ NOT_READ_INSIDE = ((SQLITE_HEADER, "sqlite", "a SQLite database"), (GVDB_HEADER, "dconf", "a dconf database"),
606
+ (ZIP_HEADER, "zip", "an archive"))
607
+
608
+
609
+ def _entry_view(name: str, data: bytes) -> dict:
610
+ """An archive entry's format and view by the rules a file's follow; a database or an archive inside is not
611
+ read."""
612
+ for header, form, inside in NOT_READ_INSIDE:
613
+ if data.startswith(header):
614
+ return {"format": form, "view": None, "error": f"{inside} inside an archive is not read"}
615
+ return _bytes_view(name, data)
616
+
617
+
618
+ def _zip_refusal(info, spent: int):
619
+ """Why an entry is not read, checked in REA's order, or None; spent is the archive's bytes read so far."""
620
+ if info.flag_bits & 0x1:
621
+ return "encrypted, so it is not read"
622
+ if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
623
+ return f"compressed with method {info.compress_type}, which the view does not read"
624
+ if info.file_size > MAX_ZIP_ENTRY_BYTES:
625
+ return "larger than the 16 MiB an entry's view reads"
626
+ if info.file_size > MAX_ZIP_RATIO * info.compress_size:
627
+ return f"expands more than {MAX_ZIP_RATIO} times, so it is not read"
628
+ if spent + info.file_size > MAX_ZIP_BYTES:
629
+ return "past the 64 MiB read from one archive"
630
+ return None
631
+
632
+
633
+ def _entry_bytes(archive, info):
634
+ """An entry's uncompressed bytes, or None when they fail its CRC-32 or are not exactly its declared size. Reading
635
+ stops one byte past that size, which data past a short declared size fills, and asks for a bounded chunk at a
636
+ time, which bounds what the decompressor expands per call, so a forged small size holds no more than that."""
637
+ probe = copy.copy(info)
638
+ probe.file_size = info.file_size + 1
639
+ data = bytearray()
640
+ try:
641
+ with archive.open(probe) as member:
642
+ while len(data) <= info.file_size:
643
+ chunk = member.read(min(probe.file_size - len(data), ZIP_READ_CHUNK))
644
+ if not chunk:
645
+ break
646
+ data += chunk
647
+ except (zipfile.BadZipFile, zlib.error, EOFError, OSError, ValueError):
648
+ return None
649
+ return data if len(data) == info.file_size else None
650
+
651
+
652
+ def _zip_entry(archive, info, refusal):
653
+ """One entry of a zip view: its name, size and digest, and its own format and view, or why it was not read."""
654
+ entry = {"name": info.filename, "size": info.file_size, "sha256": None, "format": None, "view": None,
655
+ "view_error": refusal}
656
+ if refusal is not None:
657
+ return entry
658
+ data = _entry_bytes(archive, info)
659
+ if data is None:
660
+ return {**entry, "view_error": "its compressed data is damaged"}
661
+ view = _entry_view(info.filename, data)
662
+ return {**entry, "sha256": hashlib.sha256(data).hexdigest(), "format": view["format"],
663
+ "view": view.get("view"), "view_error": view.get("error")}
664
+
665
+
666
+ def _zip_end(file, size: int):
667
+ """Where an archive's central directory ends, how long it is and the offset it declares, from the last end
668
+ record whose comment reaches the end of the file and, when a Zip64 locator precedes it whatever that record
669
+ holds, the Zip64 one just before the locator; None without an end record, or when sentinels defer to a
670
+ Zip64 record that is missing."""
671
+ window = min(size, 22 + 0xFFFF)
672
+ file.seek(size - window)
673
+ tail = file.read(window)
674
+ at = tail.rfind(ZIP_END, 0, len(tail) - 18)
675
+ while at >= 0 and at + 22 + int.from_bytes(tail[at + 20:at + 22], "little") != len(tail):
676
+ at = tail.rfind(ZIP_END, 0, at + 3)
677
+ if at < 0:
678
+ return None
679
+ total, length, offset = struct.unpack_from("<HII", tail, at + 10)
680
+ end = size - window + at
681
+ record = end - 20 - 56
682
+ if record < 0:
683
+ return end, length, offset
684
+ file.seek(end - 20)
685
+ if file.read(4) != ZIP64_LOCATOR:
686
+ return end, length, offset
687
+ file.seek(record)
688
+ zip64 = file.read(56)
689
+ if len(zip64) == 56 and zip64[:4] == ZIP64_END:
690
+ length, offset = struct.unpack_from("<QQ", zip64, 40)
691
+ return record, length, offset
692
+ if total == 0xFFFF or 0xFFFFFFFF in (length, offset):
693
+ return None
694
+ return end, length, offset
695
+
696
+
697
+ def _zip_unicode_path(raw: bytes, flags: int, extra: bytes):
698
+ """An Info-ZIP Unicode Path when zip.js uses it: version 1, no UTF-8 flag, and the CRC-32 of the stored name."""
699
+ at = 0
700
+ while at + 4 <= len(extra):
701
+ kind, length = struct.unpack_from("<HH", extra, at)
702
+ if kind == 0x7075:
703
+ data = extra[at + 4:at + 4 + length]
704
+ usable = (length >= 5 and len(data) == length and data[0] == 1 and not flags & 0x800
705
+ and int.from_bytes(data[1:5], "little") == zlib.crc32(raw))
706
+ return data[5:] if usable else None
707
+ at += 4 + length
708
+ return None
709
+
710
+
711
+ def _zip_ends_in_slash(raw: bytes, flags: int, extra: bytes):
712
+ """Whether an entry's name, as REA decodes it, ends in a slash; None when it must be UTF-8 and is not."""
713
+ utf8 = _zip_unicode_path(raw, flags, extra)
714
+ if utf8 is None and flags & 0x800:
715
+ utf8 = raw
716
+ if utf8 is None:
717
+ return raw.endswith(b"/")
718
+ try:
719
+ return utf8.decode("utf-8").endswith("/")
720
+ except UnicodeDecodeError:
721
+ return None
722
+
723
+
724
+ def _zip_directory(file, size: int, keep: int):
725
+ """An archive's central directory read a record at a time, keeping the first file entries' records, as many as keep allows, and
726
+ counting the rest, as REA reads it: (start, declared offset, records, count), or None when it cannot be read.
727
+ Directories are told apart as zip.js tells them: a final slash, a Unix directory mode, or the MS-DOS attribute."""
728
+ located = _zip_end(file, size)
729
+ if located is None:
730
+ return None
731
+ end, length, declared = located
732
+ start = end - length
733
+ if start < 0:
734
+ return None
735
+ file.seek(start)
736
+ records, count, at = [], 0, start
737
+ while at < end:
738
+ fixed = file.read(46)
739
+ if at + 46 > end or len(fixed) < 46 or fixed[:4] != ZIP_CENTRAL:
740
+ return None
741
+ made_by, flags = struct.unpack_from("<H2xH", fixed, 4)
742
+ name_length, extra_length, comment_length = struct.unpack_from("<HHH", fixed, 28)
743
+ external = struct.unpack_from("<I", fixed, 38)[0]
744
+ rest = file.read(name_length + extra_length + comment_length)
745
+ at += 46 + name_length + extra_length + comment_length
746
+ if len(rest) < name_length + extra_length + comment_length or at > end:
747
+ return None
748
+ slash = _zip_ends_in_slash(rest[:name_length], flags, rest[name_length:name_length + extra_length])
749
+ if slash is None:
750
+ return None
751
+ if not (slash or (external >> 16) & 0o170000 == 0o040000 or (made_by >> 8 == 0 and external & 0x10)):
752
+ count += 1
753
+ if len(records) < keep:
754
+ records.append(fixed + rest)
755
+ return start, declared, records, count
756
+
757
+
758
+ class _BoundedArchive(io.RawIOBase):
759
+ """An archive as zipfile reads it: its entries in place, then a directory of the kept records alone and end
760
+ records for them, so zipfile parses no more records than the view lists."""
761
+
762
+ def __init__(self, file, start: int, tail: bytes) -> None:
763
+ super().__init__()
764
+ self._file, self._start, self._tail, self._at = file, start, tail, 0
765
+
766
+ def readable(self) -> bool:
767
+ return True
768
+
769
+ def seekable(self) -> bool:
770
+ return True
771
+
772
+ def tell(self) -> int:
773
+ return self._at
774
+
775
+ def seek(self, offset: int, whence: int = 0) -> int:
776
+ self._at = offset + (0, self._at, self._start + len(self._tail))[whence]
777
+ return self._at
778
+
779
+ def readinto(self, buffer) -> int:
780
+ view = memoryview(buffer)
781
+ if self._at < self._start:
782
+ self._file.seek(self._at)
783
+ count = self._file.readinto(view[:self._start - self._at])
784
+ else:
785
+ chunk = self._tail[self._at - self._start:self._at - self._start + len(view)]
786
+ count = len(chunk)
787
+ view[:count] = chunk
788
+ self._at += count
789
+ return count
790
+
791
+
792
+ def _zip(file, size: int) -> dict:
793
+ """A zip archive's file entries in archive order, up to REA's entry, size, ratio and archive limits; nothing is
794
+ extracted to disk, no archive inside is opened, and zipfile is shown only the directory records listed."""
795
+ entries, spent = [], 0
796
+ try:
797
+ directory = _zip_directory(file, size, MAX_ZIP_ENTRIES)
798
+ if directory is None:
799
+ raise zipfile.BadZipFile("no readable central directory")
800
+ start, declared, records, count = directory
801
+ kept = b"".join(records)
802
+ offset = declared if declared <= 0xFFFFFFFF else start
803
+ # zipfile follows a Zip64 locator signature wherever one sits before the end record, and the kept records
804
+ # may end in those bytes, so a real Zip64 end record and locator for them come first.
805
+ tail = (kept
806
+ + struct.pack("<4sQ2H2I4Q", ZIP64_END, 44, 45, 45, 0, 0, len(records), len(records), len(kept), offset)
807
+ + struct.pack("<4sIQI", ZIP64_LOCATOR, 0, offset + len(kept), 1)
808
+ + struct.pack("<4s4H2IH", ZIP_END, 0, 0, len(records), len(records), len(kept), offset, 0))
809
+ with zipfile.ZipFile(_BoundedArchive(file, start, tail)) as archive:
810
+ for info in archive.infolist():
811
+ refusal = _zip_refusal(info, spent)
812
+ spent += info.file_size if refusal is None else 0
813
+ entries.append(_zip_entry(archive, info, refusal))
814
+ except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError, OSError, ValueError, struct.error):
815
+ return {"format": "zip", "view": None, "error": "not a readable zip archive"}
816
+ view = {"entries": entries, "entry_count": count, "truncated": count > len(entries)}
817
+ return {"format": "zip", "view": view, "truncated": view["truncated"]}
818
+
819
+
820
+ def _gunzip(data: bytes, limit: int):
821
+ """A gzip stream's document, its members joined as REA joins them, or None once it passes limit bytes, where
822
+ decompressing stops: data after a member that starts with a zero byte is padding and ends the stream. It is read
823
+ a piece at a time, so a member's end carries over only the rest of its piece. Raises zlib.error or EOFError when
824
+ the stream is damaged or cut short."""
825
+ document, member, rest, at = bytearray(), zlib.decompressobj(16 + zlib.MAX_WBITS), b"", 0
826
+ while True:
827
+ if not rest:
828
+ if at >= len(data):
829
+ raise EOFError("the gzip stream is cut short")
830
+ rest, at = data[at:at + GZIP_READ_CHUNK], at + GZIP_READ_CHUNK
831
+ document += member.decompress(rest, limit + 1 - len(document))
832
+ if len(document) > limit:
833
+ return None
834
+ if not member.eof:
835
+ rest = member.unconsumed_tail
836
+ continue
837
+ rest = member.unused_data
838
+ if not rest and at < len(data):
839
+ rest, at = data[at:at + GZIP_READ_CHUNK], at + GZIP_READ_CHUNK
840
+ if not rest or rest[0] == 0:
841
+ return bytes(document)
842
+ member = zlib.decompressobj(16 + zlib.MAX_WBITS)
843
+
844
+
845
+ def _gzip(name: str, data: bytes) -> dict:
846
+ """A gzip file's view: its document's, decompressed within an archive entry's size and ratio limits and read by
847
+ the rules a file's follow; a database inside is not read."""
848
+ compressed = {"format": None, "compression": "gzip", "view": None}
849
+ try:
850
+ document = _gunzip(data, min(MAX_ZIP_ENTRY_BYTES, MAX_ZIP_RATIO * len(data)))
851
+ except (zlib.error, EOFError):
852
+ return {**compressed, "error": "not a readable gzip stream"}
853
+ if document is None:
854
+ return {**compressed, "error": f"expands more than {MAX_ZIP_RATIO} times, so it is not read"
855
+ if MAX_ZIP_RATIO * len(data) < MAX_ZIP_ENTRY_BYTES
856
+ else "larger than the 16 MiB a compressed document's view reads"}
857
+ for header, form, inside in NOT_READ_INSIDE:
858
+ if form != "zip" and document.startswith(header):
859
+ return {**compressed, "format": form, "error": f"{inside} inside a gzip file is not read"}
860
+ view = _zip(io.BytesIO(document), len(document)) if document.startswith(ZIP_HEADER) else _bytes_view(name, document)
861
+ return {**view, "compression": "gzip"}
862
+
863
+
864
+ @computer_app(supports=[{"os": {"type": "linux", "display": ["x11"]}, "arch": ["amd64", "arm64"]}])
865
+ @linux(
866
+ packages=Packages(apt=["kmplot"]),
867
+ launch=Launch(at="boot", command=["sh", "-c", "cd \"$HOME\" 2>/dev/null; exec 'kmplot' \"$HOME\"/'Documents/lesson_plots.fkt'"], window={"class": "kmplot"}, ready=Ready(window=True)),
868
+ paths=PATHS,
869
+ skill="SKILL.md",
870
+ )
871
+ class Kmplot(ComputerAppEnvironment):
872
+ """KmPlot, launched at boot with the captured state in its home.
873
+
874
+ Declaring data hooks switches off agentenv's default data plane, so these call its helpers: the seed is kept as
875
+ the initial state, reset restores it, add writes files under PATHS, and get returns those files plus a typed JSON
876
+ view of each.
877
+ """
878
+
879
+ def __init__(self) -> None:
880
+ super().__init__()
881
+ if not INITIAL.exists():
882
+ _seed_home(Path.home())
883
+ _load_dconf(Path.home())
884
+ keep_initial(self.paths)
885
+
886
+ @add_data
887
+ async def add_files(self, parts: list) -> None:
888
+ await add(parts, self.paths)
889
+
890
+ @get_data
891
+ async def get_files(self, write_namespace=None) -> list:
892
+ files = await get(self.paths, write_namespace)
893
+ views = await in_thread(_views, Path.home(), self.paths)
894
+ return [*files, DataPart(data={"state": views})]
895
+
896
+ @reset_data
897
+ async def reset_files(self) -> None:
898
+ await reset(self.paths)
899
+
900
+ @ready_check
901
+ def main_window_shown(self) -> bool:
902
+ """A window of the app's class that the taskbar lists is shown, not only a splash screen or a dialog."""
903
+ return _taskbar_window(WINDOW_CLASS)
bundle/envs/kmplot/seed/.config/kmplotrc ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ [MainWindow]
2
+ 1280x800 screen: Height=615
3
+ 1280x800 screen: Width=416
4
+ 1280x800 screen: Window-Maximized=true
5
+ 1280x800 screen: XPosition=5
6
+ 1280x800 screen: YPosition=56
7
+ RestorePositionForNextInstance=false
8
+ State=AAAA/wAAAAD9AAAAAQAAAAAAAAGxAAACmvwCAAAAAfsAAAAcAEYAdQBuAGMAdABpAG8AbgBFAGQAaQB0AG8AcgEAAAA7AAACmgAAAhQA////AAADSQAAApoAAAAEAAAABAAAAAgAAAAI/AAAAAEAAAACAAAAAQAAABYAbQBhAGkAbgBUAG8AbwBsAEIAYQByAQAAAAD/////AAAAAAAAAAA=
9
+ ToolBarsMovable=Disabled
10
+ screen=screen
bundle/envs/kmplot/seed/Documents/lesson_plots.fkt ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE kmpdoc>
2
+ <kmpdoc version="4">
3
+ <axes tic-legth="0.5" tic-width="0.29999999999999999" color="#282828" width="0.20000000000000001">
4
+ <show-axes>1</show-axes>
5
+ <show-arrows>1</show-arrows>
6
+ <show-label>1</show-label>
7
+ <xmin>-8</xmin>
8
+ <xmax>8</xmax>
9
+ <ymin>-8</ymin>
10
+ <ymax>8</ymax>
11
+ </axes>
12
+ <grid color="#aeaeae" width="0.10000000000000001">
13
+ <mode>1</mode>
14
+ </grid>
15
+ <scale>
16
+ <tic-x-mode>0</tic-x-mode>
17
+ <tic-y-mode>0</tic-y-mode>
18
+ <tic-x>1</tic-x>
19
+ <tic-y>1</tic-y>
20
+ </scale>
21
+ <function f0-visible="1" f0-show-extrema="0" f0-width="0.29999999999999999" f0-show-plot-name="0" f0-color="#191970" parameter-slider="0" f2-color="#6dd03e" integral-show-tangent-field="0" f1-use-gradient="0" integral-use-gradient="0" f2-style="SolidLine" f0-show-tangent-field="0" f2-width="0.29999999999999999" f1-show-tangent-field="0" f2-visible="0" integral-width="0.29999999999999999" f1-visible="0" f2-use-gradient="0" f1-color="#cd5a86" integral-show-extrema="0" integral-show-plot-name="0" f2-show-plot-name="0" use-parameter-slider="0" f2-gradient="0;#000000,1;#ffffff," integral-visible="0" f1-style="SolidLine" integral-style="SolidLine" integral-gradient="0;#000000,1;#ffffff," f1-width="0.29999999999999999" f2-show-extrema="0" f2-show-tangent-field="0" f0-gradient="0;#000000,1;#ffffff," f1-show-plot-name="0" f0-use-gradient="0" f1-show-extrema="0" f1-gradient="0;#000000,1;#ffffff," f0-style="SolidLine" integral-color="#a2d2d7" use-parameter-list="0" type="cartesian">
22
+ <equation-0 step="0.05">f(x) = x^2 − 4<differential x="0" y="1"/>
23
+ </equation-0>
24
+ <arg-min use="0">0</arg-min>
25
+ <arg-max use="0">2π</arg-max>
26
+ </function>
27
+ <function f0-visible="1" f0-show-extrema="0" f0-width="0.29999999999999999" f0-show-plot-name="0" f0-color="#006400" parameter-slider="0" f2-color="#addae6" integral-show-tangent-field="0" f1-use-gradient="0" integral-use-gradient="0" f2-style="SolidLine" f0-show-tangent-field="0" f2-width="0.29999999999999999" f1-show-tangent-field="0" f2-visible="0" integral-width="0.29999999999999999" f1-visible="0" f2-use-gradient="0" f1-color="#468979" integral-show-extrema="0" integral-show-plot-name="0" f2-show-plot-name="0" use-parameter-slider="0" f2-gradient="0;#000000,1;#ffffff," integral-visible="0" f1-style="SolidLine" integral-style="SolidLine" integral-gradient="0;#000000,1;#ffffff," f1-width="0.29999999999999999" f2-show-extrema="0" f2-show-tangent-field="0" f0-gradient="0;#000000,1;#ffffff," f1-show-plot-name="0" f0-use-gradient="0" f1-show-extrema="0" f1-gradient="0;#000000,1;#ffffff," f0-style="SolidLine" integral-color="#88cafc" use-parameter-list="0" type="cartesian">
28
+ <equation-0 step="0.05">g(x) = 2sin(x)<differential x="0" y="1"/>
29
+ </equation-0>
30
+ <arg-min use="0">0</arg-min>
31
+ <arg-max use="0">2π</arg-max>
32
+ </function>
33
+ <function f0-visible="1" f0-show-extrema="0" f0-width="0.29999999999999999" f0-show-plot-name="0" f0-color="#ff4500" parameter-slider="0" f2-color="#686877" integral-show-tangent-field="0" f1-use-gradient="0" integral-use-gradient="0" f2-style="SolidLine" f0-show-tangent-field="0" f2-width="0.29999999999999999" f1-show-tangent-field="0" f2-visible="0" integral-width="0.29999999999999999" f1-visible="0" f2-use-gradient="0" f1-color="#f63790" integral-show-extrema="0" integral-show-plot-name="0" f2-show-plot-name="0" use-parameter-slider="0" f2-gradient="0;#000000,1;#ffffff," integral-visible="0" f1-style="SolidLine" integral-style="SolidLine" integral-gradient="0;#000000,1;#ffffff," f1-width="0.29999999999999999" f2-show-extrema="0" f2-show-tangent-field="0" f0-gradient="0;#000000,1;#ffffff," f1-show-plot-name="0" f0-use-gradient="0" f1-show-extrema="0" f1-gradient="0;#000000,1;#ffffff," f0-style="SolidLine" integral-color="#5638f5" use-parameter-list="0" type="cartesian">
34
+ <equation-0 step="0.05">h(x) = 0.5x + 1<differential x="0" y="1"/>
35
+ </equation-0>
36
+ <arg-min use="0">0</arg-min>
37
+ <arg-max use="0">2π</arg-max>
38
+ </function>
39
+ <fonts>
40
+ <axes-font>Sans Serif</axes-font>
41
+ <label-font>Sans Serif</label-font>
42
+ <header-table-font>Sans Serif</header-table-font>
43
+ </fonts>
44
+ </kmpdoc>
bundle/evals/kmplot.toml ADDED
@@ -0,0 +1 @@
 
 
1
+ tasks = ["change-h-formula"]
bundle/tasks/change-h-formula.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {"id":"env","type":"deploy_env","env_id":"kmplot"},
3
+ {"id":"agent","type":"deploy_agent","env_ids":["kmplot"]},
4
+ {"id":"skills","type":"add_skills","env_ids":["kmplot"]},
5
+ {"id":"record","type":"start_computer_recording","env_id":"kmplot","name":"agent","depends_on":["env"]},
6
+ {"id":"task","type":"prompt_agent","depends_on":["skills","record"],"prompt":"In KmPlot, change the formula of the function h in Documents/lesson_plots.fkt to h(x) = 2x + 1 and save the plot file."},
7
+ {"id":"check","type":"env_outcome_verifier","env_id":"kmplot","file_artifact_id":"change-h-formula-check","verifier_id":"change-h-formula","depends_on":["task"]},
8
+ {"id":"end","type":"end_computer_recording","name":"agent","depends_on":["task"]}
9
+ ]
bundle/tasks/smoke.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": "env",
4
+ "type": "deploy_env",
5
+ "env_id": "kmplot"
6
+ }
7
+ ]
media/hero.gif ADDED

Git LFS Details

  • SHA256: 1a6e362dd597cbeacffc036d65a10f460a148fcf1244bf76f78d444afd68ee3b
  • Pointer size: 131 Bytes
  • Size of remote file: 424 kB
media/solve-1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3129de7c098a8994d061d44238e1e5534cfcaaa6e721f36ba0fd95170192f2e4
3
+ size 1352729
media/solve-2.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7df1a3fb5e232c2318c169882841f7b72c2404e4cd5b32ef6861c1f240315f96
3
+ size 1358160
media/solve-3.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac38a328f5c8fdcbfe4a14a7663e5635ecd3aee0fbab23b00a054ad0fddd0a7e
3
+ size 1133148
media/witness.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fab5be13710f117ceae65421aec4cd96d0e74ab59f906048460dfaa4bce89db
3
+ size 6175368
results.json ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "environment": "KmPlot",
3
+ "app_version": "KmPlot 23.08 function plotter",
4
+ "task": "change-h-formula",
5
+ "prompt": "In KmPlot, change the formula of the function h in Documents/lesson_plots.fkt to h(x) = 2x + 1 and save the plot file.",
6
+ "agent": "claude-code",
7
+ "model": "claude-sonnet-5-5",
8
+ "agentenv_framework": "0.9.1431",
9
+ "witness": "checks failed on the seed, passed after an edit made through computer actions, failed on a near miss (h(x) = 2x + 2) and failed again after data/reset, in a fresh computer; held on the first try",
10
+ "runs": [
11
+ {
12
+ "run": 1,
13
+ "verdict": "passed",
14
+ "turns": 11,
15
+ "usd": 1.02,
16
+ "checks": {
17
+ "change-h-formula": {
18
+ "score": 1.0,
19
+ "results": [
20
+ {
21
+ "id": "h-new-formula",
22
+ "result": true,
23
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">h(x) = 2x + 1<\", expected equals 1",
24
+ "settled": true,
25
+ "read_cut": false
26
+ },
27
+ {
28
+ "id": "h-old-formula-gone",
29
+ "result": true,
30
+ "description": "0 line(s) of Documents/lesson_plots.fkt contain \">h(x) = 0.5x + 1<\", expected equals 0",
31
+ "settled": true,
32
+ "read_cut": false
33
+ },
34
+ {
35
+ "id": "g-unchanged",
36
+ "result": true,
37
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">g(x) = 2sin(x)<\", expected equals 1",
38
+ "settled": true,
39
+ "read_cut": false
40
+ },
41
+ {
42
+ "id": "f-unchanged",
43
+ "result": true,
44
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">f(x) = x^2\", expected equals 1",
45
+ "settled": true,
46
+ "read_cut": false
47
+ },
48
+ {
49
+ "id": "three-functions",
50
+ "result": true,
51
+ "description": "3 line(s) of Documents/lesson_plots.fkt contain \"<function \", expected equals 3",
52
+ "settled": true,
53
+ "read_cut": false
54
+ }
55
+ ]
56
+ }
57
+ }
58
+ },
59
+ {
60
+ "run": 2,
61
+ "verdict": "passed",
62
+ "turns": 14,
63
+ "usd": 0.55,
64
+ "checks": {
65
+ "change-h-formula": {
66
+ "score": 1.0,
67
+ "results": [
68
+ {
69
+ "id": "h-new-formula",
70
+ "result": true,
71
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">h(x) = 2x + 1<\", expected equals 1",
72
+ "settled": true,
73
+ "read_cut": false
74
+ },
75
+ {
76
+ "id": "h-old-formula-gone",
77
+ "result": true,
78
+ "description": "0 line(s) of Documents/lesson_plots.fkt contain \">h(x) = 0.5x + 1<\", expected equals 0",
79
+ "settled": true,
80
+ "read_cut": false
81
+ },
82
+ {
83
+ "id": "g-unchanged",
84
+ "result": true,
85
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">g(x) = 2sin(x)<\", expected equals 1",
86
+ "settled": true,
87
+ "read_cut": false
88
+ },
89
+ {
90
+ "id": "f-unchanged",
91
+ "result": true,
92
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">f(x) = x^2\", expected equals 1",
93
+ "settled": true,
94
+ "read_cut": false
95
+ },
96
+ {
97
+ "id": "three-functions",
98
+ "result": true,
99
+ "description": "3 line(s) of Documents/lesson_plots.fkt contain \"<function \", expected equals 3",
100
+ "settled": true,
101
+ "read_cut": false
102
+ }
103
+ ]
104
+ }
105
+ }
106
+ },
107
+ {
108
+ "run": 3,
109
+ "verdict": "passed",
110
+ "turns": 10,
111
+ "usd": 0.47,
112
+ "checks": {
113
+ "change-h-formula": {
114
+ "score": 1.0,
115
+ "results": [
116
+ {
117
+ "id": "h-new-formula",
118
+ "result": true,
119
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">h(x) = 2x + 1<\", expected equals 1",
120
+ "settled": true,
121
+ "read_cut": false
122
+ },
123
+ {
124
+ "id": "h-old-formula-gone",
125
+ "result": true,
126
+ "description": "0 line(s) of Documents/lesson_plots.fkt contain \">h(x) = 0.5x + 1<\", expected equals 0",
127
+ "settled": true,
128
+ "read_cut": false
129
+ },
130
+ {
131
+ "id": "g-unchanged",
132
+ "result": true,
133
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">g(x) = 2sin(x)<\", expected equals 1",
134
+ "settled": true,
135
+ "read_cut": false
136
+ },
137
+ {
138
+ "id": "f-unchanged",
139
+ "result": true,
140
+ "description": "1 line(s) of Documents/lesson_plots.fkt contain \">f(x) = x^2\", expected equals 1",
141
+ "settled": true,
142
+ "read_cut": false
143
+ },
144
+ {
145
+ "id": "three-functions",
146
+ "result": true,
147
+ "description": "3 line(s) of Documents/lesson_plots.fkt contain \"<function \", expected equals 3",
148
+ "settled": true,
149
+ "read_cut": false
150
+ }
151
+ ]
152
+ }
153
+ }
154
+ }
155
+ ]
156
+ }