candypunk commited on
Commit
a0a9254
·
verified ·
1 Parent(s): 8da1e4a

Release NanoJev-Web browser action model

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitattributes CHANGED
@@ -1,35 +1,4 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ docs/assets/browser-demo.png filter=lfs diff=lfs merge=lfs -text
3
+ docs/assets/seed-43129.gif filter=lfs diff=lfs merge=lfs -text
4
+ model/tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Local runtime and browser evidence must never be uploaded.
2
+ .local/
3
+ .runtime/
4
+ .venv/
5
+ node_modules/
6
+ __pycache__/
7
+ *.pyc
8
+ .env
9
+ .env.*
10
+ .DS_Store
11
+ *.log
12
+ runs/
LICENSE ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NanoJev-Web license and attribution
2
+
3
+ This repository contains components under two upstream licenses:
4
+
5
+ 1. NanoJev-derived decision architecture, head, inference implementation and
6
+ NanoJev-Web runtime additions: MIT terms in licenses/NanoJev-MIT.txt.
7
+ The original NanoJev copyright notice is retained in that file.
8
+ 2. Qwen3-0.6B backbone weights, configuration and tokenizer: Apache License 2.0
9
+ in licenses/Qwen-Apache-2.0.txt.
10
+
11
+ The complete model checkpoint incorporates the Qwen backbone and NanoJev-derived
12
+ head. Retain both notices when redistributing it. Browser head parameters were
13
+ further trained on synthetic browser decision states. Runtime and documentation
14
+ were adapted for a browser-only distribution. These changes are described in
15
+ README.md and docs/TRAINING.md.
16
+
17
+ Upstream sources:
18
+ https://github.com/TianyuCodings/NanoJev
19
+ https://huggingface.co/C-Tianyu/NanoJev
20
+ https://huggingface.co/Qwen/Qwen3-0.6B
21
+
22
+ Third-party installed dependencies retain their own licenses; node_modules and
23
+ Python packages are not bundled in the upload artifact.
MANIFEST.json ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "1.0.0",
3
+ "documentation_revision": 7,
4
+ "distribution": "model-and-browser-runtime",
5
+ "files": {
6
+ ".gitattributes": {
7
+ "bytes": 50,
8
+ "sha256": "ee05350c7fda0af4da116020dd7b976d731de3beed4f5e717d5bcc95ead24550"
9
+ },
10
+ ".gitignore": {
11
+ "bytes": 153,
12
+ "sha256": "cd833291e588d262baa004f1bb00e7a97dd20c9bf09114bf7fb0176bc68d02e7"
13
+ },
14
+ "LICENSE": {
15
+ "bytes": 1061,
16
+ "sha256": "37a9c907152bf9e33adf0376fea426e4af1ff268ba8040b88cb5178b4e40dbb6"
17
+ },
18
+ "PROVENANCE.json": {
19
+ "bytes": 1006,
20
+ "sha256": "96628b16a9784ccd0c6fecdc4dcc4213afafaf411f052ecde54ceca9c8b6d408"
21
+ },
22
+ "README.md": {
23
+ "bytes": 8191,
24
+ "sha256": "2f751fbb280bd4b182f11deb3812c6b1e8df9e8975d0c2171673ac54f143623c"
25
+ },
26
+ "docs/ACTIONS.md": {
27
+ "bytes": 5151,
28
+ "sha256": "32b371bad8e5465e8173a5fd6321e5ada47c3bdfdd96a075ad8560b560210fd5"
29
+ },
30
+ "docs/INTEGRATION.md": {
31
+ "bytes": 7595,
32
+ "sha256": "155705fe56cd7d1bf7dd8c77ae2da9e6421ecac87541310d3f6f66c46668e0e5"
33
+ },
34
+ "docs/PRIVACY.md": {
35
+ "bytes": 3988,
36
+ "sha256": "bb0296e9886e19420e8da97d829f1d165cca45180af70de9b2c483d09e4699c7"
37
+ },
38
+ "docs/PUBLISHING.md": {
39
+ "bytes": 3736,
40
+ "sha256": "cb63b1ffa8801b48e900458013b26fc092987c0f2f27a77d665fe4ec1e508053"
41
+ },
42
+ "docs/SINGLE_FORM_REPORT.md": {
43
+ "bytes": 15900,
44
+ "sha256": "3141d1ad8047a90f30d7a60b644cc80d17b3dfff206fcbca6e4f1e463e2dd28f"
45
+ },
46
+ "docs/TRAINING.md": {
47
+ "bytes": 3651,
48
+ "sha256": "b41069afc8be09875ba90f8aeab00b8ea9b2de586aab43f05b6f41dc98982884"
49
+ },
50
+ "docs/assets/browser-demo.png": {
51
+ "bytes": 563972,
52
+ "sha256": "95a778e02ea9e444aba3926d3f8b03a6cc1a22e53d4eee6315f92c189a9604ca"
53
+ },
54
+ "docs/assets/seed-43129.gif": {
55
+ "bytes": 1147189,
56
+ "sha256": "4e86be028cf41f9b3cab7e62626a6b0d1965c6e7139dbc68a472f9b40e1fecd8"
57
+ },
58
+ "docs/demo/decisions.json": {
59
+ "bytes": 185132,
60
+ "sha256": "227bbef162b48b5c2887a05443b18bd8af0ab566b82a9c90abf564e128e82c78"
61
+ },
62
+ "docs/demo/measurements.json": {
63
+ "bytes": 2500,
64
+ "sha256": "1c12802129b9bd6b8dee5561131bb8dc0dc3fcabfe2bf5a859b5ac135f799c16"
65
+ },
66
+ "docs/demo/media-provenance.json": {
67
+ "bytes": 1285,
68
+ "sha256": "7140e6854691a4f31506ec5ce2657cfc4ac57eb6c5947874506a5b48a166b2c9"
69
+ },
70
+ "evals/privacy-audit.json": {
71
+ "bytes": 936,
72
+ "sha256": "84f1b751889f2539310bef2243fa2e2e4c570346f48117b2a583996050c97bef"
73
+ },
74
+ "evals/release-checks.json": {
75
+ "bytes": 1585,
76
+ "sha256": "3050d399c02f711955f6ce6a948980cccf562342f2bf1c740691f97b4c06925e"
77
+ },
78
+ "evals/tokenizer-provenance.json": {
79
+ "bytes": 507,
80
+ "sha256": "bb1ce268b91023c6c94bd0891b62566ed2041040c594ca2af0669cdea646417b"
81
+ },
82
+ "evals/training-results.json": {
83
+ "bytes": 3827,
84
+ "sha256": "eea199c88ff1d89be00798ebadedb17bc9cd4ee782cfaa7623aa4bf999780c67"
85
+ },
86
+ "evals/weight-audit.json": {
87
+ "bytes": 1469,
88
+ "sha256": "cf5d57709e7cdca7cf521c27f7a7c5655f2553fb5fcfdcfc40091478f13ba2ec"
89
+ },
90
+ "examples/browser-task.json": {
91
+ "bytes": 611,
92
+ "sha256": "4ed080a17f19d6c672fab427c931194c346649ef2aefcd5a58a2700896b0ee12"
93
+ },
94
+ "examples/choice-request.json": {
95
+ "bytes": 1146,
96
+ "sha256": "781bcc6fb1b269cd1026eb9707120005513be4b1b416fbf26bbfb07f06ca7e5a"
97
+ },
98
+ "licenses/NanoJev-MIT.txt": {
99
+ "bytes": 1077,
100
+ "sha256": "c69c1bb0b33112f68f9e8ef7e91dd38ec59066fcba3f62f70cbc8c9c83cf6a8e"
101
+ },
102
+ "licenses/Qwen-Apache-2.0.txt": {
103
+ "bytes": 11343,
104
+ "sha256": "832dd9e00a68dd83b3c3fb9f5588dad7dcf337a0db50f7d9483f310cd292e92e"
105
+ },
106
+ "model/backbone_config/config.json": {
107
+ "bytes": 1417,
108
+ "sha256": "30c011854471509747858ac07ffb8a4dab2bc6c04035b184729b69500c557c54"
109
+ },
110
+ "model/best.safetensors": {
111
+ "bytes": 2385039280,
112
+ "sha256": "0a93cfcf7121112fdf90336bda1198ad67a3bb45247da6eedf0dd8672d4d53b5"
113
+ },
114
+ "model/config.json": {
115
+ "bytes": 293,
116
+ "sha256": "e7ea2cf40026a03c9318f25639b20638307118d673310678b5e0fd47f651874c"
117
+ },
118
+ "model/tokenizer/chat_template.jinja": {
119
+ "bytes": 4168,
120
+ "sha256": "a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8"
121
+ },
122
+ "model/tokenizer/tokenizer.json": {
123
+ "bytes": 11422650,
124
+ "sha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506"
125
+ },
126
+ "model/tokenizer/tokenizer_config.json": {
127
+ "bytes": 692,
128
+ "sha256": "1cc816812993bff176eb4f7495433b736f06fba9b6e7b05cac7b4a1780650c95"
129
+ },
130
+ "package-lock.json": {
131
+ "bytes": 797,
132
+ "sha256": "22f2f67a372aff46ed8f794ea5b55f8b80ba74fc13811b128545124cdd0c8c03"
133
+ },
134
+ "package.json": {
135
+ "bytes": 266,
136
+ "sha256": "b38d2461b7b71a70c248539e8b77213010ed4b10ec0720d2f4ff81f6763a1740"
137
+ },
138
+ "python/model.py": {
139
+ "bytes": 3265,
140
+ "sha256": "03c1344e68c827173c476c2fbafcc3c4b4c3b8a4d7b493fc274d02368a417f95"
141
+ },
142
+ "python/predictor.py": {
143
+ "bytes": 10827,
144
+ "sha256": "dbb4747ce4f6fbd90a0665f5ab611998713de781b275a311eadca17d7902a729"
145
+ },
146
+ "python/schema.py": {
147
+ "bytes": 2208,
148
+ "sha256": "402271d475ab2fd57d021fa9020fad1df75258f5415009557dc5b9db2e87050f"
149
+ },
150
+ "python/server.py": {
151
+ "bytes": 3383,
152
+ "sha256": "606094003088d2dd4f5fde443c2ab7632f7299c4d321857f186d0f696a1514b6"
153
+ },
154
+ "requirements-lock.txt": {
155
+ "bytes": 556,
156
+ "sha256": "da94964239d2de8c4ba55c9f2b1ef8fbbad20b0ffb41e02a9323168a3ee81f3d"
157
+ },
158
+ "run.command": {
159
+ "bytes": 136,
160
+ "sha256": "681f4a4fb3d7f4cb80b7e654b5e2e7d241120b9e6a04c4537d2c2b54bcccbfc8"
161
+ },
162
+ "runtime/agent.mjs": {
163
+ "bytes": 514,
164
+ "sha256": "645b85a90b14c7ff3ae4f36024de22ce3556103c5bb85dcd041ba90fa23d1413"
165
+ },
166
+ "runtime/browser.mjs": {
167
+ "bytes": 19718,
168
+ "sha256": "1f5fab039f68bf21206667504868a104ba542f8e113d05b2167847f6ea913ad2"
169
+ },
170
+ "scripts/check-install.py": {
171
+ "bytes": 1040,
172
+ "sha256": "8966908dd906398e5accac138eca144653ab1bdf331a529c0e81b7b159dc7811"
173
+ },
174
+ "scripts/common.sh": {
175
+ "bytes": 847,
176
+ "sha256": "e2f7a6d5ee6917a504b736b9e541c74f70b6eb0b7ebfcb3e88b70c21cc86675f"
177
+ },
178
+ "scripts/publish.py": {
179
+ "bytes": 1551,
180
+ "sha256": "4418cfa35475bb340f7604740c511b12e780c8898555cd7fdff70222d8f50842"
181
+ },
182
+ "scripts/release.py": {
183
+ "bytes": 2433,
184
+ "sha256": "6f04c7bbfb7e6e7afd6c4579ad9818a7104c8be8c6153bad8f828beba7237ba2"
185
+ },
186
+ "setup.command": {
187
+ "bytes": 1486,
188
+ "sha256": "31aa4b86c19cd7e6c80e03a98bd5b86972f83176d4e30583795df6f06a12cd3b"
189
+ },
190
+ "start.command": {
191
+ "bytes": 282,
192
+ "sha256": "45fe2204cbe6802bd08e559534fc6f55de4f118dded67bd46f6b50b0b68b8277"
193
+ },
194
+ "test.command": {
195
+ "bytes": 193,
196
+ "sha256": "db5abb97615127815d66b836af788c5810856cd016fb55960b49d450a61aefa0"
197
+ },
198
+ "tests/parity.py": {
199
+ "bytes": 1633,
200
+ "sha256": "5519e4474dbff60143e3982901292c0f2b6e88f203302ee089dd08a534550f27"
201
+ },
202
+ "tests/reference-decisions.json": {
203
+ "bytes": 46779,
204
+ "sha256": "37927cdc85bbcc7c08953ec9332775d2fddb705051b95b4d7db998b053c6441a"
205
+ },
206
+ "tests/test_contract.py": {
207
+ "bytes": 1628,
208
+ "sha256": "735743357e096ea6a7eac7522e309b71ec7da429fbb27a9aea57a83eec92d753"
209
+ },
210
+ "training-data/calibration.jsonl": {
211
+ "bytes": 1073763,
212
+ "sha256": "3245ee66ccacbc1372bc1ca8d6b9e41829b64cd8a6a1d163eefda2b6f6044d9c"
213
+ },
214
+ "training-data/dev.jsonl": {
215
+ "bytes": 1065438,
216
+ "sha256": "4f86da59b82d8c08487ec5144efc7fa84b502558387922e205cb9c5f8e89d79e"
217
+ },
218
+ "training-data/test.jsonl": {
219
+ "bytes": 1231173,
220
+ "sha256": "3097ca379e1d1c4087ae8614f4a181e1ef4761566e672283cdd5889e98d620c1"
221
+ },
222
+ "training-data/train.jsonl": {
223
+ "bytes": 6431793,
224
+ "sha256": "1f596b1dff78510693a33432d874df11b53c46a85fcd0d2488b0ca73ff8ef297"
225
+ }
226
+ }
227
+ }
PROVENANCE.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "NanoJev-Web",
3
+ "version": "1.0.0",
4
+ "weights_variant": "browser-head-v5",
5
+ "checkpoint_sha256": "0a93cfcf7121112fdf90336bda1198ad67a3bb45247da6eedf0dd8672d4d53b5",
6
+ "upstream": {
7
+ "model": "C-Tianyu/NanoJev",
8
+ "revision": "unified-games-v1",
9
+ "checkpoint_sha256": "f68c47d66998231b86b7e91b4ed5e82ae23acf104c8b7cd6d165c3ac7b7ffe1b",
10
+ "source": "https://github.com/TianyuCodings/NanoJev",
11
+ "source_commit": "618cea6d906d54e128360786d12f703fff2b1245"
12
+ },
13
+ "backbone": {
14
+ "model": "Qwen/Qwen3-0.6B",
15
+ "revision": "c1899de289a04d12100db370d81485cdf75e47ca",
16
+ "frozen_parameters": 596049920
17
+ },
18
+ "head": {
19
+ "trained_parameters": 200578,
20
+ "set_head": "attention"
21
+ },
22
+ "storage": "FP32 safetensors",
23
+ "full_parameters": 596250498,
24
+ "release_changes": "Browser head v5 weights unchanged; model-focused distribution with local choice inference, browser executor and integration documentation. Comparison application and cloud-provider integrations excluded."
25
+ }
README.md ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: other
5
+ license_name: mit-and-apache-2.0
6
+ license_link: LICENSE
7
+ library_name: pytorch
8
+ base_model: C-Tianyu/NanoJev
9
+ base_model_relation: finetune
10
+ tags:
11
+ - browser-automation
12
+ - agent-browser
13
+ - action-selection
14
+ - local-inference
15
+ - apple-silicon
16
+ - safetensors
17
+ - nanojev
18
+ - jev
19
+ ---
20
+
21
+ # NanoJev-Web
22
+
23
+ **Open-weight browser hands for a larger planning agent.** NanoJev-Web is a lightweight browser-action model derived from NanoJev. It runs locally and selects the next action from a host-provided set of permitted browser operations. The included **agent-browser** runtime executes the selected action and checks the resulting page state.
24
+
25
+ Use it as an execution component for form filling and bounded web workflows. A larger model or your application supplies the goal, selectors, values and success conditions; NanoJev-Web handles action selection within that contract. The weights, inference code and browser runtime are available for local integration. No hosted model service or API key is required.
26
+
27
+ ## How it fits into an agent
28
+
29
+ ```text
30
+ Planning agent / application
31
+ supplies the task, allowed controls, values and success conditions
32
+ ↓
33
+ Host observer → abstract page state + available action candidates
34
+ ↓
35
+ NanoJev-Web → selected action ID + candidate probabilities
36
+ ↓
37
+ Browser executor → performs the action → observes the new page state
38
+ ↺
39
+ Host verifies the outcome or handles a blocked workflow
40
+ ```
41
+
42
+ The model scores supplied alternatives without generating text. Selectors and literal form values stay with the supplied executor; it sends abstract action descriptions and page-state flags to the model. Planning, page understanding and independent outcome verification belong to the host. [Integration guide and API](docs/INTEGRATION.md).
43
+
44
+ ## Inheritance and browser specialization
45
+
46
+ NanoJev-Web inherits its decision architecture and tokenizer from [C-Tianyu/NanoJev](https://huggingface.co/C-Tianyu/NanoJev), using the **Qwen3-0.6B** backbone. All **596,049,920 backbone parameters remain frozen**. The **200,578-parameter decision head** was further trained on synthetic browser action states.
47
+
48
+ The released weights are the verified `browser-head-v5` checkpoint. Packaging it as NanoJev-Web did not introduce another training run. Game interfaces, game datasets, game training commands and teacher-service integrations are excluded. Removing those components does not erase knowledge from the inherited weights. [Training details](docs/TRAINING.md) · [Provenance](PROVENANCE.json).
49
+
50
+ | Property | Value |
51
+ |---|---|
52
+ | Total parameters | 596,250,498 |
53
+ | Output | One supplied action ID and probabilities over the alternatives |
54
+ | Storage | Full FP32 safetensors checkpoint; no quantization or adapter |
55
+ | Checkpoint size | 2,385,039,280 bytes |
56
+ | Candidate context limit | 768 tokens per separately encoded candidate path; overflows rejected |
57
+ | Local inference | PyTorch MPS on Apple Silicon; explicit CPU option |
58
+ | Tested hardware | MacBook Pro, Apple M2 Pro, 16 GB unified memory |
59
+
60
+ ## Available browser actions
61
+
62
+ The supplied executor supports:
63
+
64
+ - **Inputs:** `fill`, `type`, `clear`, `select`, `multiselect`, `check`, `uncheck`, `radio`, `upload`.
65
+ - **Interactions:** `click`, `hover`, `dblclick`, `drag`, `focus`, `press`.
66
+ - **Structured controls and navigation:** `open`, `option`, `add`, `remove`, `link`, `tab`.
67
+ - **Visibility:** observer-generated `scroll` to reveal an allowed target.
68
+ - **Control decisions:** `DONE`, `WAIT`, `BLOCKED`.
69
+
70
+ These are executor capabilities exposed as permitted choices. The model does not invent commands. Same-origin frame targeting is available through a control's `frame` property. See the [complete action reference](docs/ACTIONS.md) for required data, semantics and boundaries.
71
+
72
+ ## Run locally
73
+
74
+ The supplied installer targets **native Apple Silicon, macOS 14+, Node.js 24+ with npm, and uv**. It installs pinned Python 3.12.13 dependencies and agent-browser 0.37.1. Installation downloads dependencies; model inference then uses local files. Other Apple Silicon generations have not all been benchmarked.
75
+
76
+ **Tested on MacBook Pro with Apple M2 Pro and 16 GB unified memory.** Successful operation was reported in a separate functional test. [Hardware specifications and test scope](docs/INTEGRATION.md#apple-m2-pro-compatibility).
77
+
78
+ ```bash
79
+ cd NanoJev-Web
80
+ chmod +x *.command
81
+ ./setup.command
82
+ ./start.command
83
+ ```
84
+
85
+ The model listens on **127.0.0.1:8774**. In another terminal:
86
+
87
+ ```bash
88
+ curl http://127.0.0.1:8774/api/health
89
+ curl -H 'Content-Type: application/json' \
90
+ --data-binary @examples/choice-request.json \
91
+ http://127.0.0.1:8774/api/evaluate
92
+ ```
93
+
94
+ For browser execution, adapt [examples/browser-task.json](examples/browser-task.json) to your own page, selectors and desired values, then run:
95
+
96
+ ```bash
97
+ ./run.command --task your-task.json
98
+ ```
99
+
100
+ The runner creates an isolated agent-browser session and stores its local trace and final screenshot in `.local/runs/`. The example describes a page contract; it does not start or include a demo website. For a Python-only model setup or your own executor, see [integration](docs/INTEGRATION.md).
101
+
102
+ This is a custom decision checkpoint. Load it with the supplied inference code; the repository root is not a standard `AutoModelForCausalLM` chat checkpoint or a configured Hugging Face Inference widget.
103
+
104
+ ## Evaluation and limits
105
+
106
+ On held-out synthetic decision states, the browser head selected an acceptable action in **228/228** cases. Development scored **191/192** and calibration **189/192**. These splits share the training schema; they measure action selection within that schema, not success on arbitrary websites. Probabilities have not been certified as calibrated confidence. [Data and methodology](docs/TRAINING.md).
107
+
108
+ The current model and runtime target bounded workflows with supplied controls. They do not independently discover a site's workflow, invent form values, interpret arbitrary screenshots, manage credentials or make business decisions. The host must define success and verify any required saved data; a `DONE` choice alone does not establish business correctness. Changing the observation/action schema can change model behavior and requires evaluation.
109
+
110
+ ## Browser demonstration
111
+
112
+ The following recording illustrates the model in use. In one 15-field form attempt, NanoJev-Web completed and saved all assigned values in **19.85 seconds**, using **20 browser actions and 21 decisions** on Apple M3 Max / 36 GB. Jev and GPT-6 Astra High ran alongside it through the same browser executor for context.
113
+
114
+ ![Final recorded browser demonstration: Jev stopped, NanoJev-Web and GPT-6 Astra passed](docs/assets/browser-demo.png)
115
+
116
+ ![Browser demonstration with NanoJev-Web, Jev and GPT-6 Astra High](docs/assets/seed-43129.gif)
117
+
118
+ *Recording excerpt, seed 43129 (26.51 seconds of GIF playback). The clip ends with Astra showing “Booking saved” while its final decision is still pending. Final verified outcomes and elapsed times come from the saved run logs and result screenshot; GIF playback duration is not execution time.*
119
+
120
+ This is one observed demonstration with supplied selectors and values, not a general browser reliability claim. The [detailed recording report](docs/SINGLE_FORM_REPORT.md) retains the comparison, timing, token accounting and verification evidence. The comparison application and its cloud-provider integrations are separate from this model distribution; only static documentation assets are included.
121
+
122
+ ## Release contents and privacy
123
+
124
+ The distribution contains the checkpoint, tokenizer, inference API, agent-browser executor, integration examples, synthetic browser-head data, model checks, documentation and license notices. The model's inherited **MIT and Apache-2.0** terms are described in [LICENSE](LICENSE).
125
+
126
+ Private machine paths, credentials, browser profiles and raw local run files are excluded. The safetensors header has no author metadata, and head training used abstract synthetic states. This audit does not establish that inherited pretrained weights contain no personal information. [Privacy audit](docs/PRIVACY.md) · [Publishing instructions](docs/PUBLISHING.md).
docs/ACTIONS.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Browser action reference
2
+
3
+ The host supplies an explicit task contract: URL, allowed origins, selectors, labels, desired values, optional preconditions and success conditions. NanoJev-Web chooses an action ID. The executor re-observes the page before executing it and rejects stale observations, ambiguous targets and disallowed navigation.
4
+
5
+ | Action | Executor behavior | Host-supplied data / boundary |
6
+ |---|---|---|
7
+ | `fill` | Replace an input or textarea value | `selector`, `value`; text, email, telephone, URL, number, date, time and datetime-local. Native temporal segments use keyboard input. |
8
+ | `type` | Focus, move to the end and type text | `value`; provide `finalValue` when appending to existing content. |
9
+ | `clear` | Empty the target input | Explicitly permitted target. |
10
+ | `select` | Select one native option | Option value. |
11
+ | `multiselect` | Select several native options | Array of option values. |
12
+ | `check` / `uncheck` | Set a checkbox state | Explicit desired boolean state. |
13
+ | `radio` | Click the assigned radio option | Correct option is supplied by the host. |
14
+ | `click` | Click an allowed element | Explicit purpose and expected postcondition when needed; supports switches through `aria-checked`. |
15
+ | `open` | Click a reveal control | Opens a supplied dropdown/dialog trigger; it does not invent a URL. |
16
+ | `option` | Click a custom dropdown option | Supplied option selector and postcondition. |
17
+ | `hover` | Hover over an element | Expected revealed state should be supplied. |
18
+ | `dblclick` | Double-click an element | Explicit target and postcondition. |
19
+ | `drag` | Drag a source to a destination | Source `selector`, `destination` selector and expected result. |
20
+ | `focus` | Focus an allowed control | Use a `focused` success condition. |
21
+ | `press` | Send a permitted keyboard key/chord | `key`; host controls focus. macOS Escape uses agent-browser's documented keyboard stream. |
22
+ | `add` / `remove` | Click an allowed add/remove control | Suitable for repeatable form rows with an explicit expected count/state. These are click aliases, not DOM modifications. |
23
+ | `link` | Click a link | Actual destination must remain in the task's `allowedOrigins`. |
24
+ | `tab` | Open an authorized URL or return to an owned parent tab | `mode: "open"` plus `url`, or `mode: "return"`; arbitrary tab discovery is not supported. |
25
+ | `upload` | Supply an explicitly authorized local file to a file input | `value`: one path or an array. The host is responsible for authorizing these files. |
26
+ | `scroll` | Scroll an offscreen target into view | Generated by the observer from an allowed control; it is not a task control operation. |
27
+ | `WAIT` | Wait for the page's visible busy state to clear | No browser action is invented. |
28
+ | `DONE` | Finish when the host's visible success condition is met | The host must separately verify saved data and business rules where required. |
29
+ | `BLOCKED` | Stop for host assistance | No forced click, bypass or automatic substitute model. |
30
+
31
+ **Frames:** a control may specify a `frame` selector for a same-origin iframe. The executor enters it for the action and returns to the main frame. `frame` is context on a control, not a standalone action. Cross-origin frames are outside this release's observation contract.
32
+
33
+ **Observations:** snapshots, read-only DOM inspection, screenshots and audit reads belong to the host. They are not extra model actions. Candidate descriptions contain operation, purpose, current value-match state, assignment state, viewport visibility, enabled state and blocking state. Supplied values and selectors remain local.
34
+
35
+ **Conditions:** `visible`, `absent`, `count`, `text`, `includes`, `attribute`, `property`, `value`, `focused`, `any` and `all` express expected states. Satisfied assigned controls and non-executable offscreen actions are removed from the choice set; the corresponding scroll action can remain. Optional distractors remain available so incorrect selection can be measured.
36
+
37
+ **Unsupported work:** arbitrary JavaScript or shell execution, canvas/game control, CAPTCHA bypass, downloads, general file chooser exploration, cross-origin frame reading, autonomous workflow discovery and secret entry. Password fields stop the generic runner; PINs, OTPs and other secrets must stay with a dedicated host helper. Control allowlists do not grant permission for consequential real-world actions.
38
+
39
+ ## Minimal task
40
+
41
+ ```json
42
+ {
43
+ "name": "contact-test",
44
+ "url": "http://127.0.0.1:9000/contact",
45
+ "allowedOrigins": ["http://127.0.0.1:9000"],
46
+ "controls": [
47
+ {"id":"name","op":"fill","selector":"#name","label":"Name","value":"Test Contact"},
48
+ {"id":"agree","op":"check","selector":"#agree","label":"Use test data"},
49
+ {"id":"save","op":"click","purpose":"submit","selector":"#save","label":"Save"}
50
+ ],
51
+ "success":{"selector":"#status","kind":"text","value":"Saved"}
52
+ }
53
+ ```
54
+
55
+ Replace the example URL and selectors with your own authorized page. `run.command` records evidence in `.local/runs/`. Define persistence and business checks in your host application. See the [integration guide](INTEGRATION.md) and [task template](../examples/browser-task.json).
docs/INTEGRATION.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Integrating NanoJev-Web
2
+
3
+ NanoJev-Web chooses among supplied actions. Your application or planning model owns the workflow, page interpretation, selectors, assigned values and verification. You can use the bundled browser runner or call the local inference API from your own executor.
4
+
5
+ ## Use the browser runner
6
+
7
+ After `setup.command`, start the local model with `start.command`. Copy [browser-task.json](../examples/browser-task.json) and replace the example URL, origins, selectors and values with those for your own authorized page. Then run:
8
+
9
+ ```bash
10
+ ./run.command --task your-task.json
11
+ ```
12
+
13
+ The task contract has these fields:
14
+
15
+ | Field | Responsibility |
16
+ |---|---|
17
+ | `name` | A simple run name, used for local report filenames |
18
+ | `url` | Initial page to open |
19
+ | `allowedOrigins` | Origins authorized for this task |
20
+ | `controls` | Explicit targets, operations, desired values and optional conditions |
21
+ | `success` | A condition describing the expected final page state |
22
+
23
+ Each control has a unique `id`, an `op`, a `selector` and a `label`. Input actions also carry the required value or desired state. `when` makes a control conditional; `expect` can describe its postcondition. The [action reference](ACTIONS.md) lists supported operations and conditions.
24
+
25
+ The observer reads the page through agent-browser, removes satisfied or non-executable candidates and offers scrolling for allowed offscreen targets. The model receives abstract state and action descriptions. The executor rechecks the observation before acting, handles permitted input mechanics, and stops on completion, blocking, action cycles or execution limits. These checks are part of the host runtime, not learned model behavior.
26
+
27
+ The runner uses the local endpoint by default. An explicit alternative local port can be selected with `--endpoint http://127.0.0.1:PORT`. A JSON trace and final screenshot are written under `.local/runs/`. They may contain the task's values and must remain private for private tasks. The runner checks visible success; your application must separately verify persistence and business rules where needed.
28
+
29
+ ## Call the model directly
30
+
31
+ `GET /api/health` reports readiness, device, precision and checkpoint identity. `POST /api/evaluate` accepts a JSON object containing `states`. Each state has a unique `id`, a `state` description and named `questions`.
32
+
33
+ Every question must contain:
34
+
35
+ - `type`: exactly `choice`.
36
+ - `instructions`: a nonempty string explaining the decision.
37
+ - `criteria`: a mapping from candidate IDs to nonempty action descriptions.
38
+
39
+ Use [choice-request.json](../examples/choice-request.json) as a concrete request:
40
+
41
+ ```bash
42
+ curl -H 'Content-Type: application/json' \
43
+ --data-binary @examples/choice-request.json \
44
+ http://127.0.0.1:8774/api/evaluate
45
+ ```
46
+
47
+ Read the selected ID at `states[0].answers.next.choice` and the distribution at `states[0].answers.next.probabilities`. Candidate IDs are local to each request. The response also contains checkpoint identity and execution accounting. `execution.input_tokens` sums separately encoded candidate paths, including repeated context; `execution.output_tokens` is zero because there is no autoregressive decoding.
48
+
49
+ The default limit is **768 tokens per complete candidate path**, including state, instructions, candidate text and formatting. Oversized paths are rejected instead of truncated. A request supports 1–32 states, 2–255 alternatives per question, at most 96 questions and at most 256 total candidate paths. The HTTP server rejects request bodies over 2,000,000 bytes. The choice schema is broader than the browser training distribution: supplying arbitrary text does not establish reliable general-purpose reasoning.
50
+
51
+ For an existing agent framework, map its observed page state and permitted actions into the browser schema, call the model, execute the returned choice, then observe again. Preserve the semantics of busy/success state, unfinished fields/interactions, visibility, assignment and blocking flags. [runtime/browser.mjs](../runtime/browser.mjs) contains the reference state formatter and action descriptions. Keeping literal values and selectors in the host is a feature of this runtime; the low-level API does not itself remove private text supplied by a caller.
52
+
53
+ ## Apple M2 Pro compatibility
54
+
55
+ **Tested on MacBook Pro with Apple M2 Pro and 16 GB unified memory.** A contributor confirmed successful local operation of NanoJev-Web on this configuration. This is a reported functional check; no detailed trace or timing measurements were supplied. The CPU/GPU core counts and macOS version were not recorded.
56
+
57
+ Apple lists the following M2 Pro configurations for the 2023 MacBook Pro. These describe the hardware family, not the exact configuration of the reported test machine. [Apple technical specifications](https://support.apple.com/en-us/111340).
58
+
59
+ | Component | M2 Pro specification |
60
+ |---|---|
61
+ | CPU / GPU | 10-core CPU with 16-core GPU, or 12-core CPU with 19-core GPU |
62
+ | Unified memory | 16 GB or 32 GB |
63
+ | Memory bandwidth | 200 GB/s |
64
+ | OS requirement for this package | macOS 14+ |
65
+
66
+ The supplied runtime uses the GPU through PyTorch MPS. Apple Silicon and macOS 14+ meet the documented platform requirements. The functional check covers the reported machine; it does not establish performance on every configuration. [Apple's PyTorch/MPS guidance](https://developer.apple.com/metal/pytorch/) · [PyTorch MPS documentation](https://docs.pytorch.org/docs/main/notes/mps.html).
67
+
68
+ The full FP32 checkpoint occupies about 2.39 GB on disk, while inference also needs activations, temporary buffers, framework memory and browser processes. Candidate count and path length affect memory consumption. A 32 GB configuration provides more headroom than 16 GB, but no M2 Pro peak-memory measurement is available from this functional check. Running a larger planning model on the same Mac adds its own requirements.
69
+
70
+ The recorded demonstration was measured on M3 Max / 36 GB; its completion times remain attributed to that machine. The M2 Pro functional result is recorded separately in [release-checks.json](../evals/release-checks.json). After installation, use the package checks and a representative page contract to verify your environment. The installer checks `torch.backends.mps.is_available()` before declaring setup complete.
71
+
72
+ ## Python-only inference setup
73
+
74
+ If your application already supplies browser execution, the model server does not require Node.js or agent-browser. On native Apple Silicon with macOS 14+ and `uv`, from the release root:
75
+
76
+ ```bash
77
+ export UV_PYTHON_INSTALL_DIR="$PWD/.runtime/python"
78
+ export UV_CACHE_DIR="$PWD/.runtime/cache"
79
+ uv python install 3.12.13 --no-bin
80
+ uv venv --managed-python --python 3.12.13 .venv
81
+ uv pip sync --python .venv/bin/python requirements-lock.txt
82
+ ./start.command
83
+ ```
84
+
85
+ The server loads the included checkpoint once and binds to loopback. To use CPU explicitly, run `./start.command --device cpu`; CPU latency has not been benchmarked. No external model calls or teacher fallback are used. Installation needs network access for dependencies; inference uses local model files.
86
+
87
+ ## Verify the model package
88
+
89
+ ```bash
90
+ ./test.command
91
+ ```
92
+
93
+ This runs the six request-contract tests and verifies the public file manifest. With the model server running, the frozen v5 reference decisions can also be checked:
94
+
95
+ ```bash
96
+ .venv/bin/python tests/parity.py
97
+ ```
98
+
99
+ Parity compares action choices and probabilities with saved reference outputs at a tolerance of `1e-4`. These are model checks; they do not contact comparison models or run a comparison website.
docs/PRIVACY.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Release privacy audit
2
+
3
+ The public distribution is a neutral model/tool release. It contains no personal project branding or identifying maintainer metadata. Attribution to NanoJev and Qwen remains because it describes the model's actual origin and preserves their license notices.
4
+
5
+ ## Checked material
6
+
7
+ - All public source, configuration, documentation, examples and evaluation summaries were scanned for machine-specific home paths, private account identifiers, access-token patterns and private-key blocks.
8
+ - All **1,863 browser head training rows** were inspected as structured data and scanned for contact details, URLs, local paths and private identifiers. The rows describe abstract operations, visibility, assignment, busy states and acceptable actions. They do not contain user form values or conversation transcripts.
9
+ - The safetensors header contains **322 tensors** and **no `__metadata__` author field or other author metadata**.
10
+ - The released checkpoint retains the verified v5 weight hash. The recorded tensor audit establishes that the Qwen backbone was frozen during browser head training.
11
+ - The tokenizer vocabulary, merge rules and added-token inventory exactly match the pinned upstream Qwen tokenizer. Saved pre-tokenizer/decoder settings differ; the verified v5 tokenizer is retained as-is. [Comparison record](../evals/tokenizer-provenance.json). No private tokens were added.
12
+ - The inference response identifies `NanoJev-Web/browser-head-v5` instead of returning an absolute checkpoint directory.
13
+ - Published benchmark evidence contains selected numeric results, model identities, reproducibility information, synthetic assigned values and allowlisted abstract decision traces. Private raw run files, machine paths and browser sessions are excluded.
14
+ - Archive entries use blank owner/group names, numeric ownership zero and normalized timestamps. Publication uses an explicit manifest, not the contents of an installed runtime directory.
15
+
16
+ The explicitly supplied synthetic benchmark screenshot and GIF are included as public report assets. The image metadata contains resolution, dimensions, a color profile and a generic Screenshot comment; the GIF contains animation timing and loop metadata. No identifying author/location metadata was found. Both files are preserved byte-for-byte. See [media provenance](demo/media-provenance.json).
17
+
18
+ The machine-specific audit denylist itself is not published, because that would reintroduce the identifiers being removed. Findings are recorded as counts in [privacy-audit.json](../evals/privacy-audit.json).
19
+
20
+ ## Excluded from the upload
21
+
22
+ Credentials, environment files, local connection configuration, browser profiles, unreviewed recordings, private run receipts, screenshots from arbitrary sites, old workspaces, development archives, dependency installations and caches are not release files. Running the package later creates `.local/` evidence; that directory stays outside the manifest.
23
+
24
+ The model and browser runtime require no hosted-model credentials. The comparison application and cloud-provider integrations are excluded from this distribution. The local model has no teacher or external model fallback. Package installation still needs network access to obtain dependencies.
25
+
26
+ ## Limits of the audit
27
+
28
+ This is a release-file and browser-head-data audit, not proof that pretrained neural weights cannot encode personal information. The inherited backbone and multilingual tokenizer have not been retrained or semantically scrubbed. Ordinary names or words in a tokenizer vocabulary are upstream model assets, not evidence of a local user's training records; deleting them would change tokenization and invalidate the checkpoint.
29
+
30
+ The model's API is deliberately narrow, but the caller can still supply text. Hosts remain responsible for using appropriate data and authorized pages. Downloaders should use the verified release manifest rather than sharing their own working directory after running private tests.
docs/PUBLISHING.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Publish the prepared release on Hugging Face
2
+
3
+ The repository root is already a model repository layout: an English `README.md` model card, license notices, local weights/tokenizer/configuration, source, tests and evidence. No hosted Inference API integration or Hugging Face Space is configured. This distribution contains the model and browser runtime. It does not contain a comparison application or cloud-provider integrations.
4
+
5
+ ## Review and dry run
6
+
7
+ After setup:
8
+
9
+ ```bash
10
+ ./test.command
11
+ .venv/bin/python scripts/publish.py --repo-id YOUR_NAMESPACE/NanoJev-Web
12
+ ```
13
+
14
+ The default is a **dry run**: it verifies hashes and prints the exact upload file count. It makes no network writes and does not need a token. Replace `YOUR_NAMESPACE` with the intended account or organization; no personal namespace is embedded in the release.
15
+
16
+ ## Explicit publication
17
+
18
+ Authenticate through the Hugging Face CLI or provide `HF_TOKEN` through your environment. Keep credentials outside this folder. Then:
19
+
20
+ ```bash
21
+ .venv/bin/python scripts/publish.py \
22
+ --repo-id YOUR_NAMESPACE/NanoJev-Web --publish
23
+ ```
24
+
25
+ This explicitly creates a **public** model repository and uploads only verified manifest files. If the repository already exists, the command fails unless you add `--update-existing`. That flag adds/replaces the listed files and does not delete unrelated remote files. Choose a new clean repository for a first release.
26
+
27
+ The helper uses `HfApi` with an exact file allowlist. It does not upload `.local`, `.venv`, `.runtime`, `node_modules`, `.env`, browser evidence, development history, shell configuration or hidden parent directories. Do not use an unrestricted recursive upload on an installed workspace.
28
+
29
+ ## Portable archive
30
+
31
+ ```bash
32
+ .venv/bin/python scripts/release.py --export ../NanoJev-Web-1.0.0.tar.gz
33
+ ```
34
+
35
+ The archive contains the same manifest files plus the manifest. Tar ownership IDs and names are normalized, as are timestamps, so machine usernames and local filesystem metadata are not copied into the archive. Dependencies and browsers are installed on the destination machine with `setup.command`.
36
+
37
+ The checkpoint's SHA-256 is recorded in `PROVENANCE.json`. `.gitattributes` marks safetensors for large-file handling. Hugging Face handles large-file transfer through its upload API.
38
+
39
+ ## Model-card scope
40
+
41
+ The card identifies the NanoJev parent, the Qwen backbone, browser head training, mixed upstream license terms and the specialized decision interface. It does not label this custom checkpoint as a generic text-generation pipeline or claim universal browser benchmark performance.
42
+
43
+ References: [Hugging Face model cards](https://huggingface.co/docs/hub/model-cards), [Hugging Face upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload).
44
+
45
+ ## Static demonstration assets
46
+
47
+ The demonstration image is `docs/assets/browser-demo.png`, showing the final verified results. The recording is `docs/assets/seed-43129.gif`, embedded in the model card and [detailed report](SINGLE_FORM_REPORT.md). Both supplied files are preserved byte-for-byte and included as documentation assets in the release manifest and archive. They are shown in the demonstration section after the model description, integration and limitations. The executable comparison stand is not distributed.
48
+
49
+ The GIF contains 26.51 seconds of playback and ends before Astra's final Passed badge. The caption distinguishes this recording excerpt from the complete run metrics, which come from the saved benchmark logs.
50
+
51
+ If you later replace a media file or edit the Markdown locally, update the corresponding manifest entries before using the verified uploader and regenerate the archive. A direct edit on the Hub does not change the local archive.
docs/SINGLE_FORM_REPORT.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Recorded browser demonstration: Jev, NanoJev-Web and GPT-6 Astra High
2
+
3
+ This is supporting documentation for NanoJev-Web. The comparison application used to record it is separate from the model distribution and is not included here. Local model inference and browser execution do not require a comparison provider.
4
+
5
+ **Observed result:** NanoJev-Web and Astra completed and saved all 15 assigned values. Jev filled four values, then alternated between two scroll targets until the harness stopped the repeated state/action cycle.
6
+
7
+ This is the manually started English **Workshop booking** test on **2026-09-21**, seed **43129**, attempt `20260921T120532066-91fc95`. It is one attempt per model, not an average or a multi-seed reliability claim. No model was rerun to replace its result.
8
+
9
+ ## Recording
10
+
11
+ ![Live recording of Jev, NanoJev-Web and GPT-6 Astra High on the seed-43129 form](assets/seed-43129.gif)
12
+
13
+ *Recording excerpt, seed 43129 (26.51 seconds of GIF playback). The clip ends with Astra showing “Booking saved” while its final decision is still pending. Final verified outcomes and elapsed times come from the saved run logs and the result screenshot; GIF playback duration is not benchmark execution time.*
14
+
15
+ **Final verified result:**
16
+
17
+ ![Final state: Jev stopped, NanoJev-Web passed, and GPT-6 Astra passed](assets/browser-demo.png)
18
+
19
+ ## Test conditions
20
+
21
+ | Item | Recorded condition |
22
+ |---|---|
23
+ | Hardware | Apple M3 Max, 36 GB unified memory |
24
+ | Operating system | macOS 26.5.2 |
25
+ | Browser execution | agent-browser 0.37.1, three isolated sessions |
26
+ | Viewport | 1000 × 820 pixels per session |
27
+ | Execution order | Three models run concurrently on separate copies of the same form |
28
+ | Local inference | NanoJev-Web browser-head-v5, PyTorch MPS, FP32 |
29
+ | Jev identity | `typesafe/jev-1.13-20260917` |
30
+ | Astra identity | `openai/gpt-6-astra`, high reasoning |
31
+ | Display pauses | 0 ms; no artificial action delay in this attempt |
32
+ | Start | Manual Run click, followed by a six-second countdown |
33
+ | Limits | 100 decisions; 300 seconds checked between steps; 60-second model-request timeout |
34
+ | Repair policy | No scripted repair, teacher fallback, substitute model or automatic retry |
35
+
36
+ All three models started with **identical decision inputs**, verified by hashes. Each model received a stateless abstract page state and the same action-description format. Candidate sets then evolved independently as their actions changed their own sessions.
37
+
38
+ The host supplied selectors, assigned form values and success conditions. These remained in the executor; models did not receive the full DOM, screenshots, field labels, URLs or literal values. The field names used in this report identify the host-side targets. The decision inputs described actions using operation, purpose, current match state, assignment, viewport, enabled and blocked flags. No previous-action history was included.
39
+
40
+ This evaluates the model-plus-executor system's ability to choose and perform bounded actions. It does not measure autonomous website discovery or the ability to infer form values from an open-ended request.
41
+
42
+ ## Results
43
+
44
+ | Model | Outcome | Elapsed | Valid fields | Exact assigned values | Decisions / executed actions | Input / output tokens | API cost (USD) |
45
+ |---|---|---:|---:|---:|---:|---:|---:|
46
+ | Jev | `action_cycle`; not saved | 8.7733 s | 6/15 (40.0%) | 4/15 (26.7%) | 11 / 10 | 13,307 / 1,916 | $0.000558894 |
47
+ | NanoJev-Web | `completed`; saved | 19.8501 s | 15/15 (100%) | 15/15 (100%) | 21 / 20 | 52,743 / 0 | $0 local API |
48
+ | GPT-6 Astra High | `completed`; saved | 79.1565 s | 15/15 (100%) | 15/15 (100%) | 20 / 19 | 14,661 / 812 | $0.187210000 |
49
+
50
+ All scored model requests have recorded usage; there are no unknown-usage requests in this attempt. Combined reported hosted API cost was **$0.187768894**. This excludes the coordinating assistant, preparation, hardware, electricity and earlier runs. NanoJev-Web encodes candidate paths separately, so its token count includes repeated context and is not directly comparable to provider billing. Astra's 812 output tokens include **505 reported reasoning tokens**; these are not additional tokens to add to that total.
51
+
52
+ Elapsed time measures the action loop, including observation, model requests, execution and status updates. Navigation/setup, countdown and final audit/screenshots are excluded. With zero display pauses, elapsed and “without pauses” are equal. Failed-run duration is time until stopping, not time to successful completion.
53
+
54
+ | Component | Jev | NanoJev-Web | Astra High |
55
+ |---|---:|---:|---:|
56
+ | Model HTTP request wall time | 5.1236 s | 13.0616 s | 71.8182 s |
57
+ | Browser command wall time in the loop | 3.6104 s | 6.7261 s | 7.2716 s |
58
+ | Other loop overhead | 0.0393 s | 0.0624 s | 0.0668 s |
59
+ | Browser calls in the loop | 85 | 170 | 163 |
60
+
61
+ HTTP time includes service/network overhead and is not a pure neural inference measurement. All sessions and live streaming shared the same machine; this was not an isolated hardware latency benchmark.
62
+
63
+ ## The exact Jev cycle
64
+
65
+ Jev first filled **Notes → Contact name → Project website → Time** correctly. From decision 5 onward, it repeatedly chose scrolling over available input actions:
66
+
67
+ | Decision | Selected action | Target location before action | Selected probability | Execution |
68
+ |---:|---|---|---:|---|
69
+ | 5 | `scroll` to **Status notifications** (`#notifications`) | below | 0.38 | Executed |
70
+ | 6 | `scroll` to **I confirm these are test data** (`#consent`) | above | 0.25 | Executed |
71
+ | 7 | `scroll` to **Status notifications** (`#notifications`) | below | 0.29 | Executed |
72
+ | 8 | `scroll` to **I confirm these are test data** (`#consent`) | above | 0.24 | Executed |
73
+ | 9 | `scroll` to **Status notifications** (`#notifications`) | below | 0.39 | Executed |
74
+ | 10 | `scroll` to **I confirm these are test data** (`#consent`) | above | 0.28 | Executed |
75
+ | 11 | `scroll` to **Status notifications** (`#notifications`) | below | 0.31 | **Rejected before execution** |
76
+
77
+ The observed loop was:
78
+
79
+ ```text
80
+ Upper form: consent is visible and can be checked
81
+ ↓ scroll to #notifications
82
+ Lower form: notifications are visible and can be enabled
83
+ ↑ scroll back to #consent
84
+ Repeat without changing either control
85
+ ```
86
+
87
+ There were **six executed scroll actions**, forming **three complete down/up loops**. At decision **11**, Jev selected the fourth downward scroll to `#notifications`. The repeated-state guard rejected that action before calling the browser. Therefore the trace contains **11 model decisions but only 10 executed actions**: four fills plus six scrolls.
88
+
89
+ The guard counts visits to a key formed from the fresh host state, operation, target selector, target match state and viewport position. It stops when a key is selected more than three times, including nonconsecutive repetitions. It is not a “three consecutive identical clicks” rule. The successful terminal `DONE` decisions for the other models are also not browser actions.
90
+
91
+ ### The useful actions were available
92
+
93
+ At decisions **5, 7, 9 and 11**, the upper-page inputs and ordered candidates were exactly identical. Candidate `a2` offered `check` on the visible, enabled, unblocked consent checkbox. Jev instead selected `a0`, the scroll to the offscreen notifications switch.
94
+
95
+ At decisions **6, 8 and 10**, the lower-page inputs and ordered candidates were exactly identical. Candidate `a0` offered `click` on the visible, enabled, unblocked notifications switch. Jev instead selected `a2`, the scroll back to consent above the viewport.
96
+
97
+ For example, at decision 6 the returned distribution assigned **0.25** to scrolling up and **0.07** to clicking the notifications switch. The harness used the selected choice without a confidence cutoff, consistently with the common comparison policy. These reported probabilities are not calibrated estimates of task success, and action IDs such as `a0` are local to each observation.
98
+
99
+ The trace establishes that scrolling changed which controls were in view, the corresponding local input actions remained available, and no additional values were completed during the loop. There was **no provider error, input-parser error, recorded keyboard error, invalid submission or permission block**. Jev did not attempt to click either loop target and fail; it kept choosing another scroll.
100
+
101
+ ### What caused it, and what is still uncertain
102
+
103
+ The immediate observed failure was **action selection**: the returned rankings favored another offscreen target over useful controls already in view. The interface was stateless and did not provide action history, so the two identical recurring inputs did not carry an explicit reminder that this navigation had already failed to make progress. That is a plausible contributor, not a proven explanation of the model's internal reasoning. The trace does not show private model reasoning.
104
+
105
+ This does not establish that Jev is unable to operate checkboxes, switches or forms in general. NanoJev-Web and Astra completed the same fixture through the same executor. A separate experiment could test action-history summaries or scroll-after-arrival constraints, but neither was added to rescue this measured attempt. The weights, prompt and action policy were not changed in response to this failure.
106
+
107
+ ## Field-by-field verification
108
+
109
+ All values below are synthetic test data. An exact value match is stricter than HTML validity.
110
+
111
+ | Field | Assigned value | Jev final value | Jev valid / exact | NanoJev-Web | Astra High |
112
+ |---|---|---|---|---|---|
113
+ | Project website | https://form-632.example.test | https://form-632.example.test | Yes / Yes | Exact, valid | Exact, valid |
114
+ | I confirm these are test data | true | false | No / No | Exact, valid | Exact, valid |
115
+ | Notes | Synthetic booking 35548. Prepare the workshop materials. | Synthetic booking 35548. Prepare the workshop materials. | Yes / Yes | Exact, valid | Exact, valid |
116
+ | Support team | coral | (empty) | No / No | Exact, valid | Exact, valid |
117
+ | Contact name | Test Contact Gamma / sample 185 | Test Contact Gamma / sample 185 | Yes / Yes | Exact, valid | Exact, valid |
118
+ | Time | 18:00 | 18:00 | Yes / Yes | Exact, valid | Exact, valid |
119
+ | Priority | low | (empty) | No / No | Exact, valid | Exact, valid |
120
+ | Extras | recording, screen | (none selected) | No / No | Exact, valid | Exact, valid |
121
+ | Date | 2030-11-16 | (empty) | No / No | Exact, valid | Exact, valid |
122
+ | Receive marketing emails | false | true | Yes / No | Exact, valid | Exact, valid |
123
+ | Email address | form.2652@example.test | (empty) | No / No | Exact, valid | Exact, valid |
124
+ | Location | north | (empty) | No / No | Exact, valid | Exact, valid |
125
+ | Phone number | +12025550197 | (empty) | No / No | Exact, valid | Exact, valid |
126
+ | Status notifications | true | false | Yes / No | Exact, valid | Exact, valid |
127
+ | Participants | 37 | (empty) | No / No | Exact, valid | Exact, valid |
128
+
129
+ Jev's two additional valid fields were unchanged defaults: marketing emails remained **true** and notifications remained **false**. Both were valid boolean states, but both contradicted the assigned values. This explains **6 valid fields versus only 4 exact values**; the report does not count valid defaults as completed task data.
130
+
131
+ ## Persistence and workflow audit
132
+
133
+ | Check | Jev | NanoJev-Web | Astra High |
134
+ |---|---:|---:|---:|
135
+ | Server submissions | 0 | 1 | 1 |
136
+ | Exactly one submission with all assigned values | No | Yes | Yes |
137
+ | Server accepted all field constraints | No submission | Yes | Yes |
138
+ | Visible “Booking saved” success | No | Yes | Yes |
139
+ | Optional/reset/cancel actions executed | 0 | 0 | 0 |
140
+ | Invalid advance/review/submission attempts | 0 | 0 | 0 |
141
+ | Recorded unidentified keyboard events | 0 | 0 | 0 |
142
+ | Whole workflow passed | No | Yes | Yes |
143
+
144
+ A model's `DONE` selection alone is not sufficient to pass. Both successful attempts passed the DOM match checks, independent server validation, exact saved-data comparison, single-submission check and workflow-event checks.
145
+
146
+ The bench also recorded a **Stop request at the overall job level**. Individual attempt outcomes are preserved exactly as recorded: Jev `action_cycle`, NanoJev-Web `completed`, and Astra `completed`. The job-level flag is not treated as a new model failure or as the cause of Jev's earlier cycle.
147
+
148
+ ## Complete decision sequence
149
+
150
+ Each cell identifies the model-selected operation and host-side target. `DONE` confirms visible success and is not an executed browser input. Jev's last selected scroll was rejected by the cycle guard.
151
+
152
+ | Decision | Jev | NanoJev-Web | Astra High |
153
+ |---:|---|---|---|
154
+ | 1 | `fill` Notes | `fill` Notes | `fill` Notes |
155
+ | 2 | `fill` Contact name | `open` Support team | `check` I confirm these are test data |
156
+ | 3 | `fill` Project website | `check` I confirm these are test data | `fill` Contact name |
157
+ | 4 | `fill` Time | `fill` Project website | `open` Support team |
158
+ | 5 | `scroll` Status notifications | `fill` Contact name | `fill` Project website |
159
+ | 6 | `scroll` I confirm these are test data | `fill` Time | `fill` Time |
160
+ | 7 | `scroll` Status notifications | `option` Coral | `option` Coral |
161
+ | 8 | `scroll` I confirm these are test data | `radio` Low | `radio` Low |
162
+ | 9 | `scroll` Status notifications | `scroll` Extras | `scroll` Status notifications |
163
+ | 10 | `scroll` I confirm these are test data | `multiselect` Extras | `click` Status notifications |
164
+ | 11 | `scroll` Status notifications **(blocked by cycle guard)** | `fill` Date | `fill` Email address |
165
+ | 12 | — | `fill` Email address | `uncheck` Receive marketing emails |
166
+ | 13 | — | `uncheck` Receive marketing emails | `fill` Date |
167
+ | 14 | — | `fill` Phone number | `multiselect` Extras |
168
+ | 15 | — | `click` Status notifications | `select` Location |
169
+ | 16 | — | `select` Location | `fill` Participants |
170
+ | 17 | — | `scroll` Participants | `fill` Phone number |
171
+ | 18 | — | `fill` Participants | `click` Review booking |
172
+ | 19 | — | `click` Review booking | `click` Save booking |
173
+ | 20 | — | `click` Save booking | `DONE` — visible success |
174
+ | 21 | — | `DONE` — visible success | — |
175
+
176
+ ## Recorded protocol and evidence
177
+
178
+ The recording used seed **43129**, no display pauses, three fresh browser sessions and the same initial decision inputs. The original fixture, comparison server and cloud adapters are not bundled with this model release. Repeating this exact three-model experiment requires that separate demonstration application; the release itself provides local inference and a runner for your own page contracts.
179
+
180
+ Fixture SHA-256: `03e4713e07448df49bd9c5f56830ef41275e20c32299a64ed5beb9b638cb898b`. Protocol SHA-256: `6fa80a82af021e45f8446d0980636af5b619941601862b41b582e6c15e12dd6c`. Weight SHA-256: `0a93cfcf7121112fdf90336bda1198ad67a3bb45247da6eedf0dd8672d4d53b5`.
181
+
182
+ The two repeated Jev input hashes are:
183
+
184
+ - Upper-page decisions 5/7/9/11: `805e8da7365a5b6529811bd317b36cedf7b51c2d00bdbcceceb44c27a224d4bd`.
185
+ - Lower-page decisions 6/8/10: `0447597c79b267d77718dee96eef6b43a40ec43e516c0cddf67df33989444600`.
186
+
187
+ Input hashes use UTF-8 JSON with preserved key order and compact separators, matching `JSON.stringify` for these payloads. The [detailed machine-readable report](demo/decisions.json) includes all 52 decisions, model-facing inputs, selected actions, usage and independent final audits. The [compact result](demo/measurements.json) contains the headline measurements. The repeated-state guard used for this attempt is described above; executable comparison code is excluded from this release.
188
+
189
+ This release report contains only synthetic fixture data and allowlisted evidence. Local filesystem paths, credentials, browser profiles and private provider identifiers are omitted. The comparison is a single specialized action-selection test and does not establish general browser-agent superiority. Earlier comparisons are not merged into this recorded attempt.
docs/TRAINING.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model lineage and browser head training
2
+
3
+ ## Lineage
4
+
5
+ - Decision model: [C-Tianyu/NanoJev](https://huggingface.co/C-Tianyu/NanoJev), revision `unified-games-v1`.
6
+ - Source: [TianyuCodings/NanoJev](https://github.com/TianyuCodings/NanoJev), commit `618cea6d906d54e128360786d12f703fff2b1245`.
7
+ - Backbone: [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B), revision `c1899de289a04d12100db370d81485cdf75e47ca`.
8
+ - Original checkpoint SHA-256: `f68c47d66998231b86b7e91b4ed5e82ae23acf104c8b7cd6d165c3ac7b7ffe1b`.
9
+ - Released browser checkpoint SHA-256: `0a93cfcf7121112fdf90336bda1198ad67a3bb45247da6eedf0dd8672d4d53b5`.
10
+
11
+ Each candidate path combines state, question, candidate text and a terminal EOS token. The backbone's final candidate representation is normalized and scored, with an attention-based set head mixing candidate information. Inference applies softmax across the supplied alternatives. There is no autoregressive decoding and no generated text to parse in the NanoJev-Web API.
12
+
13
+ The set head uses a 1024-wide LayerNorm, a scalar projection, a 1025-to-128 set projection, four-head attention with width 128, and a final 128-to-1 projection. All **200,578 head parameters** were trainable; all **596,049,920 backbone parameters** were frozen. The frozen-backbone comparison and changed-head audit are retained in [weight-audit.json](../evals/weight-audit.json).
14
+
15
+ ## Synthetic browser data
16
+
17
+ The shipped JSONL files contain **1,863 abstract synthetic states**, not collected user forms, browsing histories, names, email addresses, passwords or conversations. Labels define acceptable next actions in a known action schema. Some states admit more than one acceptable action.
18
+
19
+ | Split | Rows | Generator seed | Correct acceptable-action choices |
20
+ |---|---:|---:|---:|
21
+ | Train | 1,251 | 731 | Not reported as a held-out result |
22
+ | Development | 192 | 1709 | 191/192 (99.48%) |
23
+ | Calibration | 192 | 2081 | 189/192 (98.44%) |
24
+ | Test | 228 | 3253 | 228/228 (100%) |
25
+
26
+ The development process included 51 feedback-derived examples and 240 small-page curriculum examples. Exact cross-split input duplicates were absent in the recorded data audit. The splits share a synthetic state grammar and action families; they do not test unfamiliar website reasoning. Development feedback influenced iteration. “Calibration” is a dataset split name; release probabilities have not been certified as calibrated confidence estimates.
27
+
28
+ ## Optimization recipe
29
+
30
+ - Frozen backbone feature extraction; head optimization on cached representations.
31
+ - AdamW, learning rate `0.0007`, weight decay `0.005`, batch size `24`.
32
+ - Gradient norm clipping at `1.0`, seed `42`, `200` epochs.
33
+ - Soft-target cross-entropy over candidate choices.
34
+ - Best checkpoint chosen by development accuracy, then development cross-entropy; selected epoch `191`.
35
+ - Final held-out test evaluated after checkpoint selection.
36
+
37
+ The recorded **58.14 seconds** cover cached head optimization, not feature extraction, previous experiments or total development. Full numeric results are in [training-results.json](../evals/training-results.json). Training data and the inference architecture are published for inspection; this package does not include the old game trainer or its feature caches. It is a runnable inference release, not a claim of a fully reproduced upstream training environment.
38
+
39
+ Distribution cleanup did not change the weights. The reference browser interface explicitly distinguishes unfinished inputs from available advance/submit actions and supplies only executable candidates. A recorded browser demonstration is documented separately from model-only synthetic accuracy.
docs/assets/browser-demo.png ADDED

Git LFS Details

  • SHA256: 95a778e02ea9e444aba3926d3f8b03a6cc1a22e53d4eee6315f92c189a9604ca
  • Pointer size: 131 Bytes
  • Size of remote file: 564 kB
docs/assets/seed-43129.gif ADDED

Git LFS Details

  • SHA256: 4e86be028cf41f9b3cab7e62626a6b0d1965c6e7139dbc68a472f9b40e1fecd8
  • Pointer size: 132 Bytes
  • Size of remote file: 1.15 MB
docs/demo/decisions.json ADDED
The diff for this file is too large to render. See raw diff
 
docs/demo/measurements.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "kind": "user-started English single-form live comparison",
3
+ "date": "2026-09-21",
4
+ "seed": 43129,
5
+ "fixtureSha256": "03e4713e07448df49bd9c5f56830ef41275e20c32299a64ed5beb9b638cb898b",
6
+ "displayPauseMs": 0,
7
+ "concurrency": 3,
8
+ "equalInitialInputs": true,
9
+ "results": [
10
+ {
11
+ "model": "jev",
12
+ "form": "Workshop booking",
13
+ "passed": false,
14
+ "status": "action_cycle",
15
+ "seconds": 8.773282124999998,
16
+ "validFields": 6,
17
+ "fieldsCorrect": 4,
18
+ "serverValid": false,
19
+ "inputTokens": 13307,
20
+ "outputTokens": 1916,
21
+ "costUsd": 0.000558894,
22
+ "unknownRequests": 0,
23
+ "executionSeconds": 8.773282124999998,
24
+ "insertedPauseMs": 0,
25
+ "decisions": 11,
26
+ "actions": 10,
27
+ "error": null
28
+ },
29
+ {
30
+ "model": "nanojev",
31
+ "form": "Workshop booking",
32
+ "passed": true,
33
+ "status": "completed",
34
+ "seconds": 19.850137833000016,
35
+ "validFields": 15,
36
+ "fieldsCorrect": 15,
37
+ "serverValid": true,
38
+ "inputTokens": 52743,
39
+ "outputTokens": 0,
40
+ "costUsd": 0,
41
+ "unknownRequests": 0,
42
+ "executionSeconds": 19.850137833000016,
43
+ "insertedPauseMs": 0,
44
+ "decisions": 21,
45
+ "actions": 20,
46
+ "error": null
47
+ },
48
+ {
49
+ "model": "astra",
50
+ "form": "Workshop booking",
51
+ "passed": true,
52
+ "status": "completed",
53
+ "seconds": 79.15651054199998,
54
+ "validFields": 15,
55
+ "fieldsCorrect": 15,
56
+ "serverValid": true,
57
+ "inputTokens": 14661,
58
+ "outputTokens": 812,
59
+ "costUsd": 0.18721,
60
+ "unknownRequests": 0,
61
+ "executionSeconds": 79.15651054199998,
62
+ "insertedPauseMs": 0,
63
+ "decisions": 20,
64
+ "actions": 19,
65
+ "error": null
66
+ }
67
+ ],
68
+ "identities": {
69
+ "jev": "typesafe/jev-1.13-20260917",
70
+ "nanojev": "NanoJev-Web/browser-head-v5",
71
+ "astra": "openai/gpt-6-astra"
72
+ },
73
+ "scope": "One attempt per model. Individual model outcomes were recorded; a Stop request was also registered at the bench job level. This is not a multi-seed reliability estimate.",
74
+ "detailedReport": "../SINGLE_FORM_REPORT.md",
75
+ "detailedEvidence": "decisions.json",
76
+ "jevFailureSummary": {
77
+ "cycle": "scroll to #notifications below, then scroll to #consent above",
78
+ "cycleStartsAtDecision": 5,
79
+ "stopDecision": 11,
80
+ "executedScrolls": 6,
81
+ "completedDownUpLoops": 3,
82
+ "rejectedAction": "Fourth scroll to #notifications, rejected before browser execution",
83
+ "usefulActionsAvailable": true
84
+ }
85
+ }
docs/demo/media-provenance.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "kind": "Supplied benchmark media, included with authorization",
3
+ "seed": 43129,
4
+ "imagesPreservedByteForByte": true,
5
+ "hero": {
6
+ "format": "PNG",
7
+ "width": 3116,
8
+ "height": 1240,
9
+ "sha256": "95a778e02ea9e444aba3926d3f8b03a6cc1a22e53d4eee6315f92c189a9604ca",
10
+ "bytes": 563972,
11
+ "path": "docs/assets/browser-demo.png"
12
+ },
13
+ "recording": {
14
+ "format": "GIF",
15
+ "width": 1316,
16
+ "height": 720,
17
+ "frames": 795,
18
+ "durationMs": 26510,
19
+ "loop": 0,
20
+ "sha256": "4e86be028cf41f9b3cab7e62626a6b0d1965c6e7139dbc68a472f9b40e1fecd8",
21
+ "bytes": 1147189,
22
+ "path": "docs/assets/seed-43129.gif"
23
+ },
24
+ "privacyReview": {
25
+ "heroExif": "Resolution, dimensions and generic Screenshot comment only",
26
+ "heroXmp": "Dimensions and generic Screenshot comment only",
27
+ "gifExtensions": "Animation timing and loop metadata",
28
+ "personalAuthorOrLocationMetadataDetected": false,
29
+ "visibleContent": "Synthetic local benchmark interface; no visible account identifiers, private paths or credentials found in the supplied image and reviewed recording frames"
30
+ },
31
+ "recordingScope": "The 26.51-second GIF shows the test in progress and ends before the final Astra Passed badge. Completion metrics are independently recorded in the existing run logs."
32
+ }
evals/privacy-audit.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "personalIdentifierMatches": 0,
4
+ "machinePathMatches": 0,
5
+ "credentialMatches": 0,
6
+ "trainingRows": {
7
+ "train": 1251,
8
+ "test": 228,
9
+ "dev": 192,
10
+ "calibration": 192
11
+ },
12
+ "safetensorsMetadata": null,
13
+ "tensorCount": 322,
14
+ "scope": "Release text and complete browser-head datasets; safetensors header. Tokenizer data treated as inherited assets, not scanned as user text. Numerical weights are not decoded for personal content.",
15
+ "detailedReportEvidence": {
16
+ "decisions": 52,
17
+ "syntheticFields": 15,
18
+ "rawPrivateRunFilesIncluded": false,
19
+ "publicFieldsAllowlisted": true
20
+ },
21
+ "reviewedPublicMedia": {
22
+ "screenshotIncluded": true,
23
+ "animatedGifIncluded": true,
24
+ "sourceFilesPreservedByteForByte": true,
25
+ "personalAuthorOrLocationMetadataDetected": false
26
+ },
27
+ "distributionScope": "Model, local inference and browser runtime; static demonstration documentation only"
28
+ }
evals/release-checks.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "distribution": "model-and-browser-runtime",
3
+ "choiceContractTests": {
4
+ "passed": 6,
5
+ "total": 6
6
+ },
7
+ "frozenDecisionParity": {
8
+ "passed": 12,
9
+ "total": 12,
10
+ "maxProbabilityDifference": 0.0,
11
+ "tolerance": 0.0001
12
+ },
13
+ "standaloneBrowserSmoke": {
14
+ "passed": true,
15
+ "execution": "agent-browser 0.37.1",
16
+ "localModelDevice": "mps",
17
+ "decisions": 6,
18
+ "actions": [
19
+ "fill",
20
+ "scroll",
21
+ "select",
22
+ "check",
23
+ "click"
24
+ ],
25
+ "exactServerReceipts": 1,
26
+ "externalModelCalls": 0,
27
+ "scope": "Synthetic local contact form; execution check, not a model comparison"
28
+ },
29
+ "packaging": {
30
+ "comparisonApplicationIncluded": false,
31
+ "cloudProviderIntegrationsIncluded": false,
32
+ "weightsUnchanged": true,
33
+ "staticDemonstrationDocsRetained": true
34
+ },
35
+ "modelCardMetadataParsed": true,
36
+ "localMarkdownLinksValid": true,
37
+ "documentationPreview": {
38
+ "agentBrowserPagesChecked": 3,
39
+ "imagesLoaded": true
40
+ },
41
+ "dependencyInstallation": "Existing pinned runtime reused for verification; installer not rerun",
42
+ "reportedHardwareChecks": [
43
+ {
44
+ "hardware": "Apple M2 Pro",
45
+ "status": "passed",
46
+ "source": "contributor-reported functional test",
47
+ "unifiedMemoryGB": 16,
48
+ "cpuCores": null,
49
+ "gpuCores": null,
50
+ "macOSVersion": null,
51
+ "scope": "Successful local operation reported on Apple M2 Pro with 16 GB unified memory. CPU/GPU core counts, macOS version, detailed trace, peak memory and benchmark timing were not supplied.",
52
+ "computer": "MacBook Pro"
53
+ }
54
+ ]
55
+ }
evals/tokenizer-provenance.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "https://huggingface.co/Qwen/Qwen3-0.6B/resolve/c1899de289a04d12100db370d81485cdf75e47ca/tokenizer.json",
3
+ "localSha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506",
4
+ "upstreamSha256": "aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4",
5
+ "identical": false,
6
+ "parsedJsonIdentical": false,
7
+ "differentTopLevelKeys": [
8
+ "pre_tokenizer",
9
+ "decoder"
10
+ ],
11
+ "vocabularyIdentical": true,
12
+ "mergesIdentical": true,
13
+ "addedTokensIdentical": true
14
+ }
evals/training-results.json ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "initial_dev": {
3
+ "n": 192,
4
+ "accuracy": 0.21354166666666666,
5
+ "ce": 2.8574434829254947,
6
+ "min_top_probability": 0.05820043385028839,
7
+ "by_mode": {
8
+ "0": [
9
+ 4,
10
+ 12
11
+ ],
12
+ "1": [
13
+ 2,
14
+ 12
15
+ ],
16
+ "2": [
17
+ 4,
18
+ 12
19
+ ],
20
+ "3": [
21
+ 6,
22
+ 12
23
+ ],
24
+ "4": [
25
+ 7,
26
+ 12
27
+ ],
28
+ "5": [
29
+ 2,
30
+ 12
31
+ ],
32
+ "6": [
33
+ 0,
34
+ 12
35
+ ],
36
+ "7": [
37
+ 12,
38
+ 12
39
+ ],
40
+ "8": [
41
+ 0,
42
+ 12
43
+ ],
44
+ "9": [
45
+ 0,
46
+ 12
47
+ ],
48
+ "10": [
49
+ 0,
50
+ 12
51
+ ],
52
+ "11": [
53
+ 4,
54
+ 12
55
+ ],
56
+ "late": [
57
+ 0,
58
+ 48
59
+ ]
60
+ }
61
+ },
62
+ "best_epoch": 191,
63
+ "dev": {
64
+ "n": 192,
65
+ "accuracy": 0.9947916666666666,
66
+ "ce": 0.35310630897861417,
67
+ "min_top_probability": 0.25886979699134827,
68
+ "by_mode": {
69
+ "0": [
70
+ 12,
71
+ 12
72
+ ],
73
+ "1": [
74
+ 12,
75
+ 12
76
+ ],
77
+ "2": [
78
+ 12,
79
+ 12
80
+ ],
81
+ "3": [
82
+ 11,
83
+ 12
84
+ ],
85
+ "4": [
86
+ 12,
87
+ 12
88
+ ],
89
+ "5": [
90
+ 12,
91
+ 12
92
+ ],
93
+ "6": [
94
+ 12,
95
+ 12
96
+ ],
97
+ "7": [
98
+ 12,
99
+ 12
100
+ ],
101
+ "8": [
102
+ 12,
103
+ 12
104
+ ],
105
+ "9": [
106
+ 12,
107
+ 12
108
+ ],
109
+ "10": [
110
+ 12,
111
+ 12
112
+ ],
113
+ "11": [
114
+ 12,
115
+ 12
116
+ ],
117
+ "late": [
118
+ 48,
119
+ 48
120
+ ]
121
+ }
122
+ },
123
+ "calibration": {
124
+ "n": 192,
125
+ "accuracy": 0.984375,
126
+ "ce": 0.33100821026738864,
127
+ "min_top_probability": 0.25569725036621094,
128
+ "by_mode": {
129
+ "0": [
130
+ 12,
131
+ 12
132
+ ],
133
+ "1": [
134
+ 12,
135
+ 12
136
+ ],
137
+ "2": [
138
+ 12,
139
+ 12
140
+ ],
141
+ "3": [
142
+ 12,
143
+ 12
144
+ ],
145
+ "4": [
146
+ 11,
147
+ 12
148
+ ],
149
+ "5": [
150
+ 12,
151
+ 12
152
+ ],
153
+ "6": [
154
+ 12,
155
+ 12
156
+ ],
157
+ "7": [
158
+ 12,
159
+ 12
160
+ ],
161
+ "8": [
162
+ 12,
163
+ 12
164
+ ],
165
+ "9": [
166
+ 12,
167
+ 12
168
+ ],
169
+ "10": [
170
+ 12,
171
+ 12
172
+ ],
173
+ "11": [
174
+ 10,
175
+ 12
176
+ ],
177
+ "late": [
178
+ 48,
179
+ 48
180
+ ]
181
+ }
182
+ },
183
+ "test": {
184
+ "n": 228,
185
+ "accuracy": 1.0,
186
+ "ce": 0.2591661242724497,
187
+ "min_top_probability": 0.21027213335037231,
188
+ "by_mode": {
189
+ "0": [
190
+ 15,
191
+ 15
192
+ ],
193
+ "1": [
194
+ 15,
195
+ 15
196
+ ],
197
+ "2": [
198
+ 15,
199
+ 15
200
+ ],
201
+ "3": [
202
+ 15,
203
+ 15
204
+ ],
205
+ "4": [
206
+ 15,
207
+ 15
208
+ ],
209
+ "5": [
210
+ 15,
211
+ 15
212
+ ],
213
+ "6": [
214
+ 15,
215
+ 15
216
+ ],
217
+ "7": [
218
+ 15,
219
+ 15
220
+ ],
221
+ "8": [
222
+ 15,
223
+ 15
224
+ ],
225
+ "9": [
226
+ 15,
227
+ 15
228
+ ],
229
+ "10": [
230
+ 15,
231
+ 15
232
+ ],
233
+ "11": [
234
+ 15,
235
+ 15
236
+ ],
237
+ "late": [
238
+ 48,
239
+ 48
240
+ ]
241
+ }
242
+ },
243
+ "parameter_max_deltas": {
244
+ "norm.weight": 0.8984187245368958,
245
+ "norm.bias": 0.8645385503768921,
246
+ "scalar.weight": 0.351028710603714,
247
+ "scalar.bias": 1.5365861654281616,
248
+ "set_project.weight": 0.6894388794898987,
249
+ "set_project.bias": 0.01813795045018196,
250
+ "set_attention.in_proj_weight": 0.4288993179798126,
251
+ "set_attention.in_proj_bias": 0.20365960896015167,
252
+ "set_attention.out_proj.weight": 0.3465597927570343,
253
+ "set_attention.out_proj.bias": 0.15903449058532715,
254
+ "set_output.weight": 0.7788041830062866,
255
+ "set_output.bias": 1.535990834236145
256
+ },
257
+ "seconds": 58.1388258934021,
258
+ "data_sha256": "b5d7f7a704da29658b9ea1542e268cc4d43f672468838efcbdf7fdfd441458df",
259
+ "checkpoint_sha256": "0a93cfcf7121112fdf90336bda1198ad67a3bb45247da6eedf0dd8672d4d53b5"
260
+ }
evals/weight-audit.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backboneParametersExactlyUnchanged": 596049920,
3
+ "changedHeadElements": {
4
+ "norm.bias": 1024,
5
+ "norm.weight": 1024,
6
+ "scalar.bias": 1,
7
+ "scalar.weight": 1024,
8
+ "set_attention.in_proj_bias": 384,
9
+ "set_attention.in_proj_weight": 49152,
10
+ "set_attention.out_proj.bias": 128,
11
+ "set_attention.out_proj.weight": 16384,
12
+ "set_output.bias": 1,
13
+ "set_output.weight": 128,
14
+ "set_project.bias": 128,
15
+ "set_project.weight": 131200
16
+ },
17
+ "servedModelParityCases": [
18
+ {
19
+ "id": "dev-browser-00000",
20
+ "maxProbabilityDifference": 3.5762786865234375e-07,
21
+ "servedChoice": "a3",
22
+ "cachedChoice": "a3"
23
+ },
24
+ {
25
+ "id": "dev-browser-00001",
26
+ "maxProbabilityDifference": 2.384185791015625e-07,
27
+ "servedChoice": "a4",
28
+ "cachedChoice": "a4"
29
+ },
30
+ {
31
+ "id": "dev-browser-00002",
32
+ "maxProbabilityDifference": 1.1324882507324219e-06,
33
+ "servedChoice": "a1",
34
+ "cachedChoice": "a1"
35
+ },
36
+ {
37
+ "id": "dev-late-00000",
38
+ "maxProbabilityDifference": 2.6193447411060333e-09,
39
+ "servedChoice": "DONE",
40
+ "cachedChoice": "DONE"
41
+ },
42
+ {
43
+ "id": "dev-late-00001",
44
+ "maxProbabilityDifference": 1.3812950783176348e-11,
45
+ "servedChoice": "a16",
46
+ "cachedChoice": "a16"
47
+ },
48
+ {
49
+ "id": "dev-late-00002",
50
+ "maxProbabilityDifference": 1.1641532182693481e-10,
51
+ "servedChoice": "a3",
52
+ "cachedChoice": "a3"
53
+ }
54
+ ],
55
+ "passed": true
56
+ }
examples/browser-task.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "contact-form",
3
+ "url": "http://127.0.0.1:9000/contact",
4
+ "allowedOrigins": [
5
+ "http://127.0.0.1:9000"
6
+ ],
7
+ "controls": [
8
+ {
9
+ "id": "name",
10
+ "op": "fill",
11
+ "selector": "#name",
12
+ "label": "Name",
13
+ "value": "Test Contact"
14
+ },
15
+ {
16
+ "id": "agree",
17
+ "op": "check",
18
+ "selector": "#agree",
19
+ "label": "Use test data"
20
+ },
21
+ {
22
+ "id": "save",
23
+ "op": "click",
24
+ "purpose": "submit",
25
+ "selector": "#save",
26
+ "label": "Save"
27
+ }
28
+ ],
29
+ "success": {
30
+ "selector": "#status",
31
+ "kind": "text",
32
+ "value": "Saved"
33
+ }
34
+ }
examples/choice-request.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "states": [
3
+ {
4
+ "id": "browser",
5
+ "state": "Task: complete the assigned browser form and confirm successful saving.\nPage busy=false; success=false; incomplete fields=false; incomplete interactions=false; blocking dialog=true; actionable pending in viewport=true.",
6
+ "questions": {
7
+ "next": {
8
+ "type": "choice",
9
+ "instructions": "Choose one allowed next browser action. Complete assigned inputs and interactions before advancing or submitting. Use scroll to reveal an offscreen target. Do not change satisfied fields or use optional reset/cancel actions. While busy wait. DONE requires visible success. If blocked and no permitted action can help choose BLOCKED.",
10
+ "criteria": {
11
+ "a0": "operation=click; purpose=dismiss; current=empty; expected=assigned; viewport=inside; enabled=true; blocked=false; target purpose=dismiss.",
12
+ "DONE": "Task is successfully saved; finish.",
13
+ "WAIT": "Page is busy; wait for a new observation.",
14
+ "BLOCKED": "Required progress is unavailable; stop for host assistance."
15
+ }
16
+ }
17
+ }
18
+ }
19
+ ]
20
+ }
licenses/NanoJev-MIT.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OpenJev contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
licenses/Qwen-Apache-2.0.txt ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
model/backbone_config/config.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "dtype": "float32",
9
+ "eos_token_id": 151645,
10
+ "head_dim": 128,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 1024,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "layer_types": [
16
+ "full_attention",
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention",
43
+ "full_attention"
44
+ ],
45
+ "max_position_embeddings": 40960,
46
+ "max_window_layers": 28,
47
+ "model_type": "qwen3",
48
+ "num_attention_heads": 16,
49
+ "num_hidden_layers": 28,
50
+ "num_key_value_heads": 8,
51
+ "pad_token_id": null,
52
+ "rms_norm_eps": 1e-06,
53
+ "rope_parameters": {
54
+ "rope_theta": 1000000,
55
+ "rope_type": "default"
56
+ },
57
+ "sliding_window": null,
58
+ "tie_word_embeddings": true,
59
+ "transformers_version": "5.17.0",
60
+ "use_cache": false,
61
+ "use_sliding_window": false,
62
+ "vocab_size": 151936
63
+ }
model/best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a93cfcf7121112fdf90336bda1198ad67a3bb45247da6eedf0dd8672d4d53b5
3
+ size 2385039280
model/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "Qwen/Qwen3-0.6B",
3
+ "resolved_model_revision": "c1899de289a04d12100db370d81485cdf75e47ca",
4
+ "set_head": "attention",
5
+ "max_length": 768,
6
+ "schema_version": "nanojev-browser-v1",
7
+ "browser_version": "browser-head-v5",
8
+ "precision": "fp32",
9
+ "parameter_storage": "float32"
10
+ }
model/tokenizer/chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
model/tokenizer/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506
3
+ size 11422650
model/tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<|im_start|>",
10
+ "<|im_end|>",
11
+ "<|object_ref_start|>",
12
+ "<|object_ref_end|>",
13
+ "<|box_start|>",
14
+ "<|box_end|>",
15
+ "<|quad_start|>",
16
+ "<|quad_end|>",
17
+ "<|vision_start|>",
18
+ "<|vision_end|>",
19
+ "<|vision_pad|>",
20
+ "<|image_pad|>",
21
+ "<|video_pad|>"
22
+ ],
23
+ "is_local": true,
24
+ "local_files_only": true,
25
+ "model_max_length": 131072,
26
+ "pad_token": "<|endoftext|>",
27
+ "split_special_tokens": false,
28
+ "tokenizer_class": "Qwen2Tokenizer",
29
+ "unk_token": null
30
+ }
package-lock.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "nanojev-web",
3
+ "version": "1.0.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "nanojev-web",
9
+ "version": "1.0.0",
10
+ "dependencies": {
11
+ "agent-browser": "0.37.1"
12
+ },
13
+ "engines": {
14
+ "node": ">=24"
15
+ }
16
+ },
17
+ "node_modules/agent-browser": {
18
+ "version": "0.37.1",
19
+ "resolved": "https://registry.npmjs.org/agent-browser/-/agent-browser-0.37.1.tgz",
20
+ "integrity": "sha512-NDojTSXrIq7zS090T0VwI1uzBryZWvewgxXvS0swj8/5GGnziBZLmyhEkfETO8n4n3DsJpZbZkq9F/MV2rIQKw==",
21
+ "hasInstallScript": true,
22
+ "license": "Apache-2.0",
23
+ "bin": {
24
+ "agent-browser": "bin/agent-browser.js"
25
+ },
26
+ "engines": {
27
+ "node": ">=24.0.0",
28
+ "pnpm": ">=11.0.0"
29
+ }
30
+ }
31
+ }
32
+ }
package.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "nanojev-web",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "Local browser action model and agent-browser execution runtime",
7
+ "engines": {
8
+ "node": ">=24"
9
+ },
10
+ "dependencies": {
11
+ "agent-browser": "0.37.1"
12
+ }
13
+ }
python/model.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decision network extracted from NanoJev; no trainer or game imports."""
2
+ import torch
3
+ from torch import nn
4
+ import torch.nn.functional as F
5
+
6
+ class DecisionModel(nn.Module):
7
+ def __init__(self, backbone, set_head):
8
+ super().__init__()
9
+ self.backbone = backbone
10
+ hidden = backbone.config.hidden_size
11
+ self.norm = nn.LayerNorm(hidden)
12
+ self.scalar = nn.Linear(hidden, 1) # Nonzero random initialization avoids a dead first step.
13
+ nn.init.normal_(self.scalar.weight, std=0.02)
14
+ nn.init.zeros_(self.scalar.bias)
15
+ self.set_head = set_head
16
+ if set_head == 'attention':
17
+ self.set_project = nn.Linear(hidden + 1, 128)
18
+ self.set_attention = nn.MultiheadAttention(128, 4, dropout=0.0, batch_first=True)
19
+ self.set_output = nn.Linear(128, 1)
20
+ # Only the final residual projection starts at zero; its upstream layers are nonzero.
21
+ nn.init.zeros_(self.set_output.weight)
22
+ nn.init.zeros_(self.set_output.bias)
23
+
24
+ def forward(self, examples, pad_token):
25
+ paths = [ids for ex in examples for ids in ex['leaf_tokens']]
26
+ device = self.scalar.weight.device
27
+ lengths = torch.tensor([len(ids) for ids in paths], device=device)
28
+ width = int(lengths.max())
29
+ tokens = torch.full((len(paths), width), pad_token, dtype=torch.long, device=device)
30
+ for i, ids in enumerate(paths):
31
+ tokens[i, :len(ids)] = torch.tensor(ids, device=device)
32
+ attention = torch.arange(width, device=device)[None, :] < lengths[:, None]
33
+ hidden = self.backbone(input_ids=tokens, attention_mask=attention,
34
+ use_cache=False).last_hidden_state
35
+ leaves = hidden[torch.arange(len(paths), device=device), lengths-1]
36
+ kmax = max(len(ex['candidate_ids']) for ex in examples)
37
+ h = leaves.new_zeros((len(examples), kmax, leaves.shape[-1]))
38
+ valid = torch.zeros((len(examples), kmax), dtype=torch.bool, device=device)
39
+ offset = 0
40
+ for i, ex in enumerate(examples):
41
+ n = len(ex['leaf_tokens'])
42
+ h[i, :n] = leaves[offset:offset+n]
43
+ valid[i, :len(ex['candidate_ids'])] = True
44
+ offset += n
45
+ h = self.norm(h)
46
+ z = self.scalar(h).squeeze(-1).float()
47
+ choice = torch.tensor([i for i, ex in enumerate(examples) if ex['type'] == 'choice'], device=device)
48
+ if self.set_head == 'attention' and len(choice):
49
+ log_k = valid[choice].sum(-1).float().log()[:, None, None].expand(-1, kmax, 1)
50
+ u = self.set_project(torch.cat([h[choice], log_k.to(h.dtype)], dim=-1))
51
+ mixed, _ = self.set_attention(u, u, u, key_padding_mask=~valid[choice], need_weights=False)
52
+ delta = self.set_output(torch.tanh(u + mixed)).squeeze(-1).float()
53
+ z = z.index_add(0, choice, delta)
54
+ # Boolean has one semantic path and one scalar, representing logits [0,z].
55
+ out = []
56
+ for i, ex in enumerate(examples):
57
+ if ex['type'] == 'boolean':
58
+ out.append(F.pad(torch.stack([z[i, 0] * 0, z[i, 0]]), (0, kmax-2)))
59
+ else:
60
+ out.append(z[i])
61
+ return torch.stack(out).masked_fill(~valid, -1e9), valid
python/predictor.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local browser decision inference. No downloads, teacher or game runtime."""
2
+ from contextlib import nullcontext
3
+ import json,math,os
4
+ from pathlib import Path
5
+ from schema import validate_request
6
+
7
+ def unique_object(pairs):
8
+ obj = {}
9
+ for key, value in pairs:
10
+ if key in obj:
11
+ raise ValueError(f"JSON contains duplicate key: {key}")
12
+ obj[key] = value
13
+ return obj
14
+
15
+ def reject_nonfinite(value):
16
+ raise ValueError(f"JSON disallows non-finite number: {value}")
17
+
18
+ def read_json(path):
19
+ return json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=unique_object,
20
+ parse_constant=reject_nonfinite)
21
+
22
+ def nonempty_text(value):
23
+ return isinstance(value, str) and bool(value.strip())
24
+
25
+ def prepare_examples(payload, tokenizer, max_length):
26
+ """Segment encoding, candidate text and EOS follow the upstream training tokenization exactly."""
27
+ states = validate_request(payload)
28
+ if type(max_length) is not int or max_length <= 0:
29
+ raise ValueError("max_length must be a positive integer")
30
+ if type(tokenizer.eos_token_id) is not int or tokenizer.eos_token_id < 0:
31
+ raise ValueError("Checkpoint tokenizer must have a valid eos_token_id")
32
+ examples = []
33
+ for row in states:
34
+ for qid, q in row["questions"].items():
35
+ typ = q["type"]
36
+ ids = list(q["criteria"])
37
+ texts = [f"{key}: {q['criteria'][key]}" for key in ids]
38
+ segments = [f"State:\n{row['state']}\n",
39
+ f"Question type: {typ}\nQuestion:\n{q['instructions']}\n"]
40
+ prefix = sum([tokenizer.encode(t, add_special_tokens=False) for t in segments], [])
41
+ leaves = [prefix + tokenizer.encode(f"Candidate:\n{t}\nDecision:", add_special_tokens=False)
42
+ + [tokenizer.eos_token_id] for t in texts]
43
+ largest = max(map(len, leaves))
44
+ if largest > max_length:
45
+ raise ValueError(f"{row['id']}:{qid} candidate path has {largest} tokens, exceeding max_length={max_length}; input was not truncated")
46
+ examples.append({"id": f"{row['id']}:{qid}", "state_id": row["id"], "qid": qid,
47
+ "type": typ, "candidate_ids": ids, "candidate_texts": texts,
48
+ "leaf_tokens": leaves})
49
+ return examples
50
+
51
+ def complete_question_batches(examples, batch_questions=0):
52
+ if type(batch_questions) is not int or batch_questions < 0:
53
+ raise ValueError("batch_questions must be nonnegative; zero batches all questions together")
54
+ size = batch_questions or len(examples)
55
+ if not examples:
56
+ return []
57
+ return [examples[i:i + size] for i in range(0, len(examples), size)]
58
+
59
+ def answer_from_probabilities(example, probabilities):
60
+ ids = example["candidate_ids"]
61
+ if len(probabilities) != len(ids) or not all(math.isfinite(p) and 0 <= p <= 1 for p in probabilities):
62
+ raise ValueError("Model produced invalid probabilities")
63
+ if abs(math.fsum(probabilities) - 1.0) > 1e-5:
64
+ raise ValueError("Model probabilities do not sum to one")
65
+ best = max(range(len(ids)), key=probabilities.__getitem__)
66
+ result = {"type": example["type"], "probabilities": dict(zip(ids, probabilities))}
67
+ result.update(choice=ids[best], value=ids[best])
68
+ return result
69
+
70
+ def local_checkpoint_files(checkpoint_dir):
71
+ root = Path(checkpoint_dir).expanduser().resolve(strict=True)
72
+ if not root.is_dir():
73
+ raise ValueError("Checkpoint must be a local directory")
74
+ paths = {"run_config": root / "config.json", "body_config": root / "backbone_config",
75
+ "tokenizer": root / "tokenizer", "weights": root / "best.safetensors"}
76
+ for label, path in paths.items():
77
+ if not path.exists():
78
+ raise ValueError(f"Checkpoint missing {label}: {path.name}")
79
+ if not paths["run_config"].is_file() or not paths["weights"].is_file():
80
+ raise ValueError("config.json and best.safetensors must be files")
81
+ if not paths["body_config"].is_dir() or not paths["tokenizer"].is_dir():
82
+ raise ValueError("backbone_config and tokenizer must be directories")
83
+ return root, paths
84
+
85
+ class DecisionPredictor:
86
+ """Persistent local inference: load weights once, evaluate complete candidate sets per question."""
87
+
88
+ def __init__(self, checkpoint_dir, max_length=None, device_name="mps",
89
+ disable_native_triton=False, precision="fp32"):
90
+ if precision != "fp32":
91
+ raise ValueError("precision must be fp32")
92
+ root, paths = local_checkpoint_files(checkpoint_dir)
93
+ run_config = read_json(paths["run_config"])
94
+ if not isinstance(run_config, dict) or run_config.get("set_head") not in {"none", "attention"}:
95
+ raise ValueError("Checkpoint config has no valid set_head")
96
+
97
+ # Load local checkpoint only; no environment files, Hub requests or model downloads.
98
+ os.environ["HF_HUB_OFFLINE"] = "1"
99
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
100
+ os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
101
+ import torch
102
+ from safetensors.torch import load_file
103
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
104
+
105
+ device = torch.device(device_name)
106
+ if device.type == "mps":
107
+ if not torch.backends.mps.is_available():
108
+ raise ValueError("MPS is unavailable; native Apple Silicon Python is required")
109
+ elif device.type != "cpu":
110
+ raise ValueError("This package supports mps and cpu")
111
+ if precision != "fp32":
112
+ raise ValueError("This package uses FP32 inference")
113
+
114
+ tokenizer = AutoTokenizer.from_pretrained(str(paths["tokenizer"]), local_files_only=True,
115
+ trust_remote_code=False)
116
+ if tokenizer.pad_token_id is None:
117
+ tokenizer.pad_token = tokenizer.eos_token
118
+ body_config = AutoConfig.from_pretrained(str(paths["body_config"]), local_files_only=True,
119
+ trust_remote_code=False)
120
+ body_config.use_cache = False
121
+ limit = run_config.get("max_length", 512) if max_length is None else max_length
122
+ if type(limit) is not int or limit <= 0:
123
+ raise ValueError("max-length must be a positive integer")
124
+ context_limit = getattr(body_config, "max_position_embeddings", None)
125
+ if isinstance(context_limit, int) and limit > context_limit:
126
+ raise ValueError("max-length exceeds the backbone context length")
127
+
128
+ # Build the architecture from config; load every parameter from best.safetensors without downloading a base model.
129
+ body = AutoModel.from_config(body_config, attn_implementation="sdpa", trust_remote_code=False).float()
130
+ from model import DecisionModel
131
+ model = DecisionModel(body, run_config["set_head"])
132
+ weights = load_file(str(paths["weights"]), device="cpu")
133
+ model.load_state_dict(weights, strict=True)
134
+ del weights
135
+ model.to(device=device, dtype=torch.float32)
136
+ model.eval()
137
+ self.model = model
138
+ self.tokenizer = tokenizer
139
+ self.root = root
140
+ self.run_config = run_config
141
+ self.limit = limit
142
+ self.device = device
143
+ self.precision = precision
144
+ self.disable_native_triton = disable_native_triton
145
+ self.inference_calls = 0
146
+ self._torch = torch
147
+
148
+ def predict(self, payload, batch_questions=0, temperature=1.0):
149
+ states = validate_request(payload)
150
+ if not isinstance(temperature, (int, float)) or isinstance(temperature, bool) or not math.isfinite(temperature) or temperature <= 0:
151
+ raise ValueError("temperature must be finite and positive")
152
+ torch = self._torch
153
+ model, tokenizer = self.model, self.tokenizer
154
+ root, run_config, limit = self.root, self.run_config, self.limit
155
+ device, precision = self.device, self.precision
156
+ disable_native_triton = self.disable_native_triton
157
+ examples = prepare_examples(payload, tokenizer, limit)
158
+ batches = complete_question_batches(examples, batch_questions)
159
+ self.inference_calls += 1
160
+ model.eval()
161
+ outputs = {state["id"]: {"id": state["id"], "answers": {}} for state in states}
162
+ with torch.inference_mode():
163
+ for batch in batches:
164
+ context = nullcontext()
165
+ with context:
166
+ logits, _ = model(batch, tokenizer.pad_token_id)
167
+ for example, values in zip(batch, logits):
168
+ k = len(example["candidate_ids"])
169
+ scores = values[:k].float()
170
+ if not torch.isfinite(scores).all():
171
+ raise ValueError("Model produced non-finite logits; no partial prediction returned")
172
+ probabilities = (scores / temperature).softmax(-1).cpu().tolist()
173
+ outputs[example["state_id"]]["answers"][example["qid"]] = answer_from_probabilities(example, probabilities)
174
+ return {
175
+ "schema_version": "nanojev-browser-inference-v1",
176
+ "checkpoint": {"id": "NanoJev-Web/browser-head-v5", "base_model": run_config.get("model"),
177
+ "base_revision": run_config.get("resolved_model_revision"), "set_head": run_config["set_head"]},
178
+ "temperature": {"value": float(temperature), "fitted_by_this_command": False,
179
+ "note": "Applies the supplied scalar; the default of 1 does not imply calibration."},
180
+ "execution": {"device": str(device), "parameter_storage": "float32", "precision": precision,
181
+ "forward_autocast": "bfloat16" if precision == "bf16" else "disabled",
182
+ "states": len(states), "questions": len(examples),
183
+ "candidate_paths": sum(len(ex["leaf_tokens"]) for ex in examples),
184
+ "input_tokens": sum(len(path) for ex in examples for path in ex["leaf_tokens"]),
185
+ "padded_input_tokens": sum(
186
+ max(len(path) for ex in batch for path in ex["leaf_tokens"])
187
+ * sum(len(ex["leaf_tokens"]) for ex in batch) for batch in batches),
188
+ "output_tokens": 0,
189
+ "forward_passes": len(batches), "batch_questions_limit": batch_questions or "all",
190
+ "autoregressive_decode_steps": 0, "prefix_sharing": False,
191
+ "max_length": limit, "disable_native_triton": disable_native_triton,
192
+ "network_model_calls": 0, "persistent_model_load_count": 1,
193
+ "inference_call_index": self.inference_calls},
194
+ "states": list(outputs.values()),
195
+ }
python/schema.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict browser decision request contract; values and UI mechanics stay in Node."""
2
+ def validate_request(payload):
3
+ if not isinstance(payload,dict) or set(payload)!={'states'}:
4
+ raise ValueError('Expected {"states": [...]}')
5
+ states=payload['states']
6
+ if not isinstance(states,list) or not 1<=len(states)<=32:
7
+ raise ValueError('Expected 1–32 states')
8
+ seen=set();question_count=path_count=0
9
+ for state in states:
10
+ if not isinstance(state,dict) or set(state)!={'id','state','questions'}:
11
+ raise ValueError('Each state requires id, state, questions')
12
+ sid=state['id']
13
+ if not isinstance(sid,str) or not sid.strip() or sid in seen:
14
+ raise ValueError('State IDs must be unique nonempty strings')
15
+ seen.add(sid)
16
+ if not isinstance(state['state'],(str,dict,list)) or not state['state']:
17
+ raise ValueError('State must be nonempty text, object or list')
18
+ questions=state['questions']
19
+ if not isinstance(questions,dict) or not questions:
20
+ raise ValueError('Questions must be a nonempty object')
21
+ for qid,q in questions.items():
22
+ if not isinstance(qid,str) or not qid.strip() or not isinstance(q,dict):
23
+ raise ValueError('Invalid question')
24
+ if set(q)!={'type','instructions','criteria'} or q['type']!='choice':
25
+ raise ValueError('Browser API supports choice questions only')
26
+ if not isinstance(q['instructions'],str) or not q['instructions'].strip():
27
+ raise ValueError('Instructions must be nonempty text')
28
+ criteria=q['criteria']
29
+ if not isinstance(criteria,dict) or not 2<=len(criteria)<=255:
30
+ raise ValueError('Expected 2–255 candidate actions')
31
+ if any(not isinstance(k,str) or not k.strip() or not isinstance(v,str) or not v.strip() for k,v in criteria.items()):
32
+ raise ValueError('Candidate IDs and descriptions must be nonempty text')
33
+ question_count+=1;path_count+=len(criteria)
34
+ if question_count>96 or path_count>256:
35
+ raise ValueError('Request exceeds 96 questions or 256 candidate paths')
36
+ return states
python/server.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persistent local inference API, without a game UI, trainer or external model calls."""
2
+ import argparse,json,time
3
+ from http.server import HTTPServer,BaseHTTPRequestHandler
4
+ from pathlib import Path
5
+ from urllib.parse import urlsplit
6
+ from predictor import DecisionPredictor,unique_object,reject_nonfinite
7
+ from schema import validate_request
8
+ ROOT=Path(__file__).resolve().parents[1]
9
+
10
+ def make_handler(engine):
11
+ class Handler(BaseHTTPRequestHandler):
12
+ def reply(self,status,data):
13
+ raw=json.dumps(data,ensure_ascii=False,allow_nan=False).encode()
14
+ self.send_response(status);self.send_header('Content-Type','application/json; charset=utf-8')
15
+ self.send_header('Content-Length',str(len(raw)));self.send_header('Cache-Control','no-store')
16
+ self.end_headers();self.wfile.write(raw)
17
+ def do_GET(self):
18
+ if urlsplit(self.path).path in ['/', '/api/health']:
19
+ self.reply(200,{'service':'NanoJev-Web','version':'1.0.0-web','ready':True,'model':'browser-head-v5','device':str(engine.device),'precision':engine.precision,'provider_calls':0})
20
+ else:self.reply(404,{'error':'Not found'})
21
+ def do_POST(self):
22
+ if urlsplit(self.path).path!='/api/evaluate':return self.reply(404,{'error':'Not found'})
23
+ try:
24
+ n=int(self.headers.get('Content-Length',0))
25
+ if not 0<n<=2_000_000:raise ValueError('Expected 1–2000000 request bytes')
26
+ origin=self.headers.get('Origin')
27
+ if origin and urlsplit(origin).netloc!=self.headers.get('Host'):
28
+ return self.reply(403,{'error':'Cross-origin requests are disabled'})
29
+ body=json.loads(self.rfile.read(n),object_pairs_hook=unique_object,parse_constant=reject_nonfinite)
30
+ validate_request(body);start=time.perf_counter();result=engine.predict(body,batch_questions=1)
31
+ result['execution']['server_evaluation_seconds']=time.perf_counter()-start
32
+ self.reply(200,result)
33
+ except (ValueError,KeyError,TypeError) as e:self.reply(400,{'error':str(e)})
34
+ except Exception:
35
+ import traceback;traceback.print_exc()
36
+ self.reply(500,{'error':'Local inference failed; no external fallback was used'})
37
+ def log_message(self,fmt,*args):print(fmt%args,flush=True)
38
+ return Handler
39
+
40
+ def main():
41
+ p=argparse.ArgumentParser(description=__doc__)
42
+ p.add_argument('--model',type=Path,default=ROOT/'model');p.add_argument('--port',type=int,default=8774)
43
+ p.add_argument('--device',choices=['mps','cpu'],default='mps');p.add_argument('--max-length',type=int,default=768)
44
+ a=p.parse_args()
45
+ if not 1024<=a.port<=65535:p.error('Use an unprivileged port from 1024 to 65535')
46
+ # Bind first: an occupied port fails before loading another copy of the model.
47
+ server=HTTPServer(('127.0.0.1',a.port),BaseHTTPRequestHandler)
48
+ try:
49
+ engine=DecisionPredictor(a.model,device_name=a.device,precision='fp32',max_length=a.max_length)
50
+ server.RequestHandlerClass=make_handler(engine)
51
+ print(json.dumps({'service':'NanoJev-Web','ready':True,'url':f'http://127.0.0.1:{a.port}','device':a.device}),flush=True)
52
+ server.serve_forever()
53
+ except KeyboardInterrupt:pass
54
+ finally:server.server_close()
55
+ if __name__=='__main__':main()
requirements-lock.txt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated-doc==0.0.5
2
+ anyio==4.15.1
3
+ certifi==2026.7.22
4
+ click==8.5.0
5
+ filelock==4.0.1
6
+ fsspec==2026.9.0
7
+ h11==0.16.0
8
+ hf-xet==1.6.0
9
+ httpcore==1.0.9
10
+ httpx==0.28.1
11
+ huggingface-hub==1.32.0
12
+ idna==3.20
13
+ jinja2==3.1.6
14
+ markdown-it-py==4.2.0
15
+ markupsafe==3.0.3
16
+ mdurl==0.1.2
17
+ mpmath==1.3.0
18
+ networkx==3.6.1
19
+ numpy==2.5.3
20
+ packaging==26.3
21
+ pygments==2.21.0
22
+ pyyaml==6.0.3
23
+ regex==2026.9.10
24
+ rich==15.0.0
25
+ safetensors==0.8.0
26
+ setuptools==84.0.0
27
+ shellingham==1.5.4
28
+ sympy==1.14.0
29
+ tokenizers==0.23.2
30
+ torch==2.14.0
31
+ tqdm==4.70.1
32
+ transformers==5.17.0
33
+ typer==0.27.2
34
+ typing-extensions==4.16.0
run.command ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ source "$(dirname -- "$0")/scripts/common.sh"
4
+ exec "$nanojev_node" "$nanojev_root/runtime/agent.mjs" "$@"
runtime/agent.mjs ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import {readFile} from 'node:fs/promises';
2
+ import {runTask} from './browser.mjs';
3
+ const i=process.argv.indexOf('--task');
4
+ if(i<0)throw Error('Usage: ./run.command --task task.json [--endpoint http://127.0.0.1:8774]');
5
+ const task=JSON.parse(await readFile(process.argv[i+1],'utf8'));
6
+ const e=process.argv.indexOf('--endpoint');
7
+ const {report,browser}=await runTask(task,{endpoint:e>=0?process.argv[e+1]:'http://127.0.0.1:8774'});
8
+ await browser.command(['close']);
9
+ if(report.status!=='completed')process.exitCode=1;
runtime/browser.mjs ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {execFile} from 'node:child_process';
2
+ import {promisify} from 'node:util';
3
+ import {readFile,writeFile,mkdir} from 'node:fs/promises';
4
+ import {resolve,dirname} from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {createHash} from 'node:crypto';
7
+ const exec=promisify(execFile);
8
+ const AB=process.env.NANOJEV_AGENT_BROWSER_BIN??resolve(dirname(fileURLToPath(import.meta.url)),'../node_modules/.bin/agent-browser');
9
+ const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..');
10
+ export const INSTRUCTION='Choose one allowed next browser action. Complete assigned inputs and interactions before advancing or submitting. When the current stage has no unfinished fields or interactions, choose its assigned advance action, then submit on the final review. The unfinished-input indicator does not describe availability of advance/submit actions. Use scroll to reveal an offscreen target. Do not change satisfied fields or use optional reset/cancel actions. While busy wait. DONE requires visible success. If blocked and no permitted action can help choose BLOCKED.';
11
+ export const SPECIALS={DONE:'Task is successfully saved; finish.',WAIT:'Page is busy; wait for a new observation.',BLOCKED:'Required progress is unavailable; stop for host assistance.'};
12
+ const INPUTS=new Set(['fill','type','clear','select','multiselect','check','uncheck','radio','upload']);
13
+ const OPS=new Set([...INPUTS,'click','hover','dblclick','drag','focus','press','open','option','add','remove','link','tab']);
14
+ const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
15
+
16
+ export function description(a){return `operation=${a.op}; purpose=${a.purpose}; current=${a.current}; expected=${a.expected}; viewport=${a.viewport}; enabled=${a.enabled}; blocked=${a.blocked}; target purpose=${a.sourcePurpose??a.purpose}.`;}
17
+ export function stateText(s){return `Task: complete the assigned browser form and confirm successful saving.\nPage busy=${s.busy}; success=${s.success}; incomplete fields=${Boolean(s.fields)}; incomplete interactions=${Boolean(s.interactions)}; blocking dialog=${s.modal}; unfinished input/interaction in viewport=${Boolean(s.ready)}.`;}
18
+
19
+ export class Browser{
20
+ constructor(session,{origins}={}){this.session=session;this.calls=0;this.ms=0;this.targetId=null;this.parentTargets=[];this.flags=['--session',session,'--pin-tab','--headed','false','--idle-timeout','0'];if(origins?.length)this.flags.push('--allowed-domains',[...new Set(origins.map(x=>new URL(x).hostname))].join(','));}
21
+ async command(args){const start=performance.now();this.calls++;const {stdout}=await exec(AB,[...this.flags,'--json',...args],{timeout:20000,maxBuffer:8*1024*1024,encoding:'utf8'});this.ms+=performance.now()-start;const result=JSON.parse(stdout);if(!result.success)throw Error(`agent-browser: ${String(result.error).slice(0,200)}`);return result.data;}
22
+ async observe(task){
23
+ const tabs=(await this.command(['tab'])).tabs.filter(x=>x.active);if(tabs.length!==1)throw Error('Ambiguous active tab');
24
+ if(this.targetId&&this.targetId!==tabs[0].targetId)throw Error('Active tab changed unexpectedly');this.targetId=tabs[0].targetId;
25
+ const snapshot=await this.command(['snapshot']);
26
+ if(!task.allowedOrigins.includes(new URL(snapshot.origin).origin))throw Error('Origin outside authorized task');
27
+ // Pure DOM read: no mutation, no access to fixture state, answers, receipts or request APIs.
28
+ const expression=`JSON.stringify(((${readDom.toString()})(${JSON.stringify(task)})))`;
29
+ const raw=await this.command(['eval',expression]);const dom=typeof raw.result==='string'?JSON.parse(raw.result):raw.result;
30
+ const refs=Object.entries(snapshot.refs??{}).map(([ref,m])=>{const line=snapshot.snapshot.split('\n').find(l=>new RegExp('\\bref='+ref+'\\b').test(l))??'';return {ref,...m,disabled:/\[(?:[^\]]*,\s*)?disabled(?:,|\])/.test(line),checked:/\bchecked(?:=true)?(?:,|\])/.test(line)&&!line.includes('checked=false')};});
31
+ const actions=[];let fields=0,interactions=0;
32
+ for(const c of dom.controls){
33
+ if(c.count>1)throw Error(`Ambiguous selector for ${c.label}`);
34
+ if(!c.visible)continue;
35
+ if(c.type==='password')throw Error('Secret input requires host helper');
36
+ const purpose=c.purpose??(INPUTS.has(c.op)?'input':'interaction');
37
+ if(!c.blocked&&c.expected!=='optional'&&c.current!=='match'){
38
+ if(purpose==='input')fields++;
39
+ if(purpose==='interaction')interactions++;
40
+ }
41
+ // Disabled and modal-covered controls cannot be authorized executable actions.
42
+ if(c.blocked||!c.enabled)continue;
43
+ const role=c.role||refs.find(r=>r.name===c.label)?.role?.toLowerCase()||'button';
44
+ const a={...c,role,purpose,expected:c.expected??'assigned'};
45
+ actions.push(a);
46
+ if(c.viewport!=='inside')actions.push({...a,op:'scroll',role:'viewport',purpose:'reveal',sourcePurpose:purpose});
47
+ }
48
+ const ready=actions.filter(a=>a.op!=='scroll'&&a.current!=='match'&&a.expected==='assigned'&&a.viewport==='inside'&&['input','interaction','dismiss'].includes(a.purpose)).length;
49
+ const s={busy:dom.busy,success:dom.success,fields,interactions,modal:dom.modal,ready};
50
+ const relevant={s,actions:actions.map(a=>({...a,value:undefined,condition:undefined,expect:undefined,when:undefined})),targetId:this.targetId};
51
+ return {state:stateText(s),s,actions,snapshot,dom,signature:hash(relevant)};
52
+ }
53
+ async act(a){
54
+ if(!a.enabled||a.blocked)throw Error('Model selected a disabled or covered action');
55
+ if(a.op!=='scroll'&&a.viewport!=='inside')throw Error('Model attempted an offscreen action without scrolling');
56
+ if(a.href&&['click','link'].includes(a.op)&&!this.allowedOrigins.includes(new URL(a.href).origin))throw Error('Link destination outside task origins');
57
+ if(a.frame){
58
+ if(a.op==='scroll')await this.command(['scrollintoview',a.frame]);
59
+ await this.command(['frame',a.frame]);
60
+ try{return await this.act({...a,frame:null});}finally{await this.command(['frame','main']);}
61
+ }
62
+ const sel=a.selector;
63
+ switch(a.op){
64
+ case 'fill':
65
+ if(['date','time','datetime-local'].includes(a.type))return this.fillTemporal(a);
66
+ return this.command(['fill',sel,String(a.value)]);
67
+ case 'type':
68
+ await this.command(['focus',sel]);
69
+ await this.command(['press','End']);
70
+ return this.command(['keyboard','type',String(a.value)]);
71
+ case 'clear':return this.command(['fill',sel,'']);
72
+ case 'select':return this.command(['select',sel,String(a.value)]);
73
+ case 'multiselect':return this.command(['select',sel,...a.value.map(String)]);
74
+ case 'check':case 'uncheck':case 'hover':case 'dblclick':case 'focus':return this.command([a.op,sel]);
75
+ case 'scroll':return this.command(['scrollintoview',sel]);
76
+ case 'press':return process.platform==='darwin'&&/^(Escape|Esc)$/i.test(a.key)?this.pressEscape():this.command(['press',a.key]);
77
+ case 'drag':return this.command(['drag',sel,a.destination]);
78
+ case 'upload':return this.command(['upload',sel,...(Array.isArray(a.value)?a.value:[a.value]).map(String)]);
79
+ case 'tab':{
80
+ if(a.mode==='open'){
81
+ if(!this.allowedOrigins.includes(new URL(a.url).origin))throw Error('Tab URL outside task origins');
82
+ this.parentTargets.push(this.targetId);await this.command(['tab','new',a.url]);
83
+ }else if(a.mode==='return'){
84
+ const parent=this.parentTargets.pop();if(!parent)throw Error('No authorized parent tab');await this.command(['tab',parent]);
85
+ }else throw Error('Unsupported tab operation');
86
+ const tabs=(await this.command(['tab'])).tabs.filter(t=>t.active);if(tabs.length!==1)throw Error('Tab activation ambiguous');this.targetId=tabs[0].targetId;return;
87
+ }
88
+ case 'radio':case 'click':case 'open':case 'option':case 'add':case 'remove':case 'link':return this.command(['click',sel]);
89
+ default:throw Error(`Unsupported runtime operation ${a.op}`);
90
+ }
91
+ }
92
+ async pressEscape(){
93
+ // agent-browser 0.37.1 CLI press on this Mac emits a stream of unrelated
94
+ // native Minus key events after Escape. Its documented input_keyboard
95
+ // channel sends the intended native key once without that translation.
96
+ const status=await this.command(['stream','status']);
97
+ if(!status.enabled||!Number.isInteger(status.port)||status.port<1||status.port>65535)throw Error('agent-browser keyboard stream unavailable');
98
+ const ws=new WebSocket(`ws://127.0.0.1:${status.port}/?pacing=ack&maxFps=1`);
99
+ try{
100
+ await new Promise((resolve,reject)=>{const timer=setTimeout(()=>reject(Error('Keyboard stream connection timed out')),5000);ws.onopen=()=>{clearTimeout(timer);resolve();};ws.onerror=()=>{clearTimeout(timer);reject(Error('Keyboard stream connection failed'));};});
101
+ for(const eventType of ['keyDown','keyUp'])ws.send(JSON.stringify({type:'input_keyboard',eventType,key:'Escape',code:'Escape',windowsVirtualKeyCode:27,modifiers:0}));
102
+ this.streamKeyboardEvents=(this.streamKeyboardEvents??0)+2;
103
+ await this.command(['wait','100']);
104
+ }finally{ws.close();}
105
+ }
106
+ async fillTemporal(a){
107
+ const raw=String(a.value),parts=[];
108
+ if(a.type!=='time'){
109
+ const m=raw.match(/^(\d{4})-(\d{2})-(\d{2})/);if(!m)throw Error('Date must use ISO format');
110
+ parts.push([/День|\bDay\b/i,m[3]],[/Месяц|\bMonth\b/i,m[2]],[/Год|\bYear\b/i,m[1]]);
111
+ }
112
+ if(a.type!=='date'){
113
+ const m=raw.match(/(?:T|^)(\d{2}):(\d{2})(?::(\d{2}))?$/);if(!m)throw Error('Time must use HH:MM[:SS]');
114
+ parts.push([/Час|\bHour\b/i,m[1]],[/Минут|\bMinute\b/i,m[2]]);if(m[3])parts.push([/Секунд|\bSecond\b/i,m[3]]);
115
+ }
116
+ for(const [pattern,value] of parts){
117
+ const s=await this.command(['snapshot','-s',a.selector]);
118
+ const found=Object.entries(s.refs).filter(([r,m])=>m.role==='spinbutton'&&pattern.test(m.name)&&new RegExp('\\bref='+r+'\\b').test(s.snapshot));
119
+ if(found.length!==1)throw Error('Date/time segment is missing or ambiguous in current locale');
120
+ await this.command(['click','@'+found[0][0]]);
121
+ for(const digit of value)await this.command(['press',digit]);
122
+ }
123
+ await this.command(['press','Tab']);
124
+ const result=await this.command(['get','value',a.selector]);if(result.value!==raw)throw Error('Date/time input did not preserve the assigned value');return result;
125
+ }
126
+ }
127
+
128
+ function readDom(task){
129
+ const context=frame=>frame?document.querySelector(frame)?.contentDocument:document;
130
+ const query=(s,frame)=>s?Array.from(context(frame)?.querySelectorAll(s)??[]):[];
131
+ const shown=e=>!!e&&!!e.getClientRects().length&&getComputedStyle(e).visibility!=='hidden'&&getComputedStyle(e).display!=='none';
132
+ const value=e=>!e?null:e.type==='checkbox'||e.type==='radio'?e.checked:e.tagName==='SELECT'&&e.multiple?Array.from(e.selectedOptions).map(o=>o.value):e.type==='file'?Array.from(e.files).map(f=>({name:f.name,size:f.size})):('value'in e?e.value:e.textContent.trim());
133
+ const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
134
+ const viewBounds=el=>{
135
+ const w=el.ownerDocument.defaultView,b={top:0,left:0,right:w.innerWidth,bottom:w.innerHeight};
136
+ for(let p=el.parentElement;p;p=p.parentElement){
137
+ const style=w.getComputedStyle(p),r=p.getBoundingClientRect();
138
+ if(/auto|scroll|hidden|clip/.test(style.overflowY)){b.top=Math.max(b.top,r.top+p.clientTop);b.bottom=Math.min(b.bottom,r.top+p.clientTop+p.clientHeight);}
139
+ if(/auto|scroll|hidden|clip/.test(style.overflowX)){b.left=Math.max(b.left,r.left+p.clientLeft);b.right=Math.min(b.right,r.left+p.clientLeft+p.clientWidth);}
140
+ }return b;
141
+ };
142
+ const condition=(c,frame)=>{
143
+ if(!c)return false;frame=c.frame??frame;const els=query(c.selector,frame),e=els[0];
144
+ if(c.kind==='any')return c.conditions.some(x=>condition(x,frame));
145
+ if(c.kind==='all')return c.conditions.every(x=>condition(x,frame));
146
+ if(c.kind==='absent')return !e||!shown(e);
147
+ if(c.kind==='visible')return shown(e);
148
+ if(c.kind==='count')return els.filter(shown).length===c.value;
149
+ if(c.kind==='text')return !!e&&e.textContent.trim()===c.value;
150
+ if(c.kind==='includes')return !!e&&e.textContent.includes(c.value);
151
+ if(c.kind==='attribute')return !!e&&e.getAttribute(c.attribute)===c.value;
152
+ if(c.kind==='focused')return !!e&&e.ownerDocument.activeElement===e;
153
+ if(c.kind==='property')return !!e&&e[c.property]===c.value;
154
+ if(c.kind==='value')return same(value(e),c.value);
155
+ return false;
156
+ };
157
+ const openDialogs=query('dialog[open],[role="dialog"][aria-modal="true"]').filter(shown),dialog=openDialogs.at(-1);
158
+ const controls=task.controls.map(c=>{
159
+ const els=query(c.selector,c.frame),e=els[0],frameElement=c.frame?document.querySelector(c.frame):null,visible=shown(e)&&(!c.frame||shown(frameElement))&&(!c.when||condition(c.when,c.frame));
160
+ if(!e)return {...c,count:0,visible:false};
161
+ const r=e.getBoundingClientRect(),bounds=viewBounds(e),fr=frameElement?.getBoundingClientRect();
162
+ let above=r.top<bounds.top-1||r.left<bounds.left-1,below=r.bottom>bounds.bottom+1||r.right>bounds.right+1;
163
+ if(frameElement){const outer=viewBounds(frameElement);above||=r.top+fr.top<outer.top-1||r.left+fr.left<outer.left-1;below||=r.bottom+fr.top>outer.bottom+1||r.right+fr.left>outer.right+1;}
164
+ const viewport=above?'above':below?'below':'inside';
165
+ let matched=false;
166
+ if(c.expect)matched=condition(c.expect,c.frame);
167
+ else if(c.op==='check'||c.op==='radio')matched=e.checked===true;
168
+ else if(c.op==='uncheck')matched=e.checked===false;
169
+ else if(c.op==='clear')matched=value(e)==='';
170
+ else if(c.op==='multiselect')matched=same([...value(e)].sort(),[...c.value].sort());
171
+ else if(c.op==='upload')matched=same(value(e).map(f=>f.name).sort(),(Array.isArray(c.value)?c.value:[c.value]).map(p=>p.split('/').at(-1)).sort());
172
+ else if(['fill','type','select'].includes(c.op))matched=same(value(e),c.finalValue??c.value);
173
+ const current=matched?'match':value(e)===''||value(e)===false?'empty':'wrong';
174
+ const enabled=!e.disabled&&e.getAttribute('aria-disabled')!=='true'&&!e.closest('[inert]')&&(!['fill','type','clear'].includes(c.op)||!e.readOnly);
175
+ const nativeRole=e.getAttribute('role')||(e.tagName==='SELECT'?(e.multiple?'listbox':'combobox'):e.tagName==='TEXTAREA'?'textbox':e.tagName==='INPUT'?({number:'spinbutton',checkbox:'checkbox',radio:'radio',file:'button'}[e.type]??'textbox'):e.tagName==='A'?'link':'button');
176
+ return {...c,role:c.role??nativeRole,count:els.length,visible,current,enabled,viewport,blocked:!!dialog&&!dialog.contains(frameElement??e),type:e.type??null,href:e.tagName==='A'?e.href:null,actual:value(e)};
177
+ });
178
+ return {controls,errors:query(task.errorSelector??'[role="alert"]').filter(shown).map(e=>e.textContent.trim()).filter(Boolean),busy:query(task.busySelector??'[aria-busy="true"]').some(shown),success:condition(task.success),modal:controls.some(c=>c.visible&&!c.blocked&&c.purpose==='dismiss')};
179
+ }
180
+
181
+ export function validateTask(t){
182
+ if(!t.name||!t.url||!Array.isArray(t.controls)||!t.controls.length||!Array.isArray(t.allowedOrigins)||!t.allowedOrigins.includes(new URL(t.url).origin))throw Error('Invalid task contract');
183
+ if(t.controls.some(c=>!OPS.has(c.op)||!c.selector||!c.label))throw Error('Invalid control');
184
+ if(new Set(t.controls.map(c=>c.id)).size!==t.controls.length)throw Error('Duplicate control IDs');
185
+ return t;
186
+ }
187
+ export async function runTask(task,{session,endpoint,maxSteps=100,outDir=resolve(ROOT,'.local/runs'),setup=true}={}){
188
+ if(!endpoint)throw Error('An explicit NanoJev endpoint is required');
189
+ validateTask(task);session??=`nanojev-${task.name}-${Date.now()}`;const browser=new Browser(session,{origins:task.allowedOrigins});browser.allowedOrigins=task.allowedOrigins;await mkdir(outDir,{recursive:true});
190
+ if(setup){await browser.command(['open',task.url]);await browser.command(['set','viewport','1100','800']);}
191
+ const runnerSha256=createHash('sha256').update(await readFile(fileURLToPath(import.meta.url))).digest('hex');
192
+ const start=performance.now(),trace=[],visits=new Map();let status='step_limit',error=null,last=null,repeats=0,modelIdentity=null;
193
+ try{
194
+ for(let step=0;step<maxSteps;step++){
195
+ if(performance.now()-start>600000){status='time_limit';break;}
196
+ const observation=await browser.observe(task);
197
+ observation.actions=observation.actions.filter(a=>(a.op==='scroll'||a.viewport==='inside')&&!(a.current==='match'&&a.expected==='assigned'&&['input','interaction','dismiss','reveal'].includes(a.purpose)));
198
+ const criteria=Object.fromEntries(observation.actions.map((a,i)=>[`a${i}`,description(a)]));Object.assign(criteria,SPECIALS);
199
+ const request={states:[{id:'browser',state:observation.state,questions:{next:{type:'choice',instructions:INSTRUCTION,criteria}}}]};
200
+ const then=performance.now();const response=await fetch(endpoint+'/api/evaluate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(request),signal:AbortSignal.timeout(60000)});const result=await response.json();
201
+ if(!response.ok)throw Error(`NanoJev inference HTTP ${response.status}: ${result.error}`);
202
+ const answer=result.states[0].answers.next;const identity=result.checkpoint.id;
203
+ if(modelIdentity&&modelIdentity!==identity)throw Error('Model changed mid-run');modelIdentity=identity;
204
+ const a=answer.choice.startsWith('a')?observation.actions[Number(answer.choice.slice(1))]:null;
205
+ if(!a&&!Object.hasOwn(SPECIALS,answer.choice))throw Error('Invalid choice');
206
+ const row={step:step+1,request,answer,execution:result.execution,apiMs:performance.now()-then,action:a??answer.choice,before:observation.dom,executed:false};trace.push(row);
207
+ const fresh=await browser.observe(task);
208
+ if(fresh.signature!==observation.signature){row.skipped='stale_observation';continue;}
209
+ if(answer.choice==='DONE'){status=fresh.s.success?'completed':'premature_done';break;}
210
+ if(answer.choice==='BLOCKED'){status='model_blocked';break;}
211
+ const key=hash([fresh.s,a?.op??answer.choice,a?.selector,a?.current,a?.viewport]);repeats=key===last?repeats+1:0;last=key;
212
+ visits.set(key,(visits.get(key)??0)+1);
213
+ if(answer.choice!=='WAIT'&&visits.get(key)>3){status='action_cycle';break;}
214
+ if(answer.choice!=='WAIT'&&repeats>=2){status='no_progress';break;}
215
+ if(answer.choice==='WAIT')await browser.command(['wait','--fn',`![...document.querySelectorAll(${JSON.stringify(task.busySelector??'[aria-busy="true"]')})].some(e=>e.getClientRects().length&&getComputedStyle(e).visibility!=='hidden')`]);
216
+ else await browser.act(a);
217
+ row.executed=true;console.log(JSON.stringify({run:task.name,step:step+1,choice:answer.choice,op:a?.op??'WAIT',label:a?.label,probability:answer.probabilities[answer.choice]}));
218
+ }
219
+ }catch(e){status='error';error=String(e.message);}
220
+ const elapsedMs=performance.now()-start;let final=null,screenshot=null,evidenceError=null;
221
+ try{final=(await browser.observe(task)).dom;screenshot=resolve(outDir,task.name+'.png');await browser.command(['screenshot','--full',screenshot]);}
222
+ catch(e){evidenceError=String(e.message);screenshot=null;if(status==='completed'){status='error';error='Could not verify final browser state: '+evidenceError;}}
223
+ const report={name:task.name,session,status,error,evidenceError,modelIdentity,runnerSha256,elapsedMs,browserCalls:browser.calls,browserMs:browser.ms,agentBrowserStreamKeyboardEvents:browser.streamKeyboardEvents??0,taskHash:hash(task),trace,final,screenshot};
224
+ await writeFile(resolve(outDir,task.name+'.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({finished:task.name,status,error,steps:trace.length,elapsedMs}));return {report,browser};
225
+ }
scripts/check-install.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check the local runtime without loading a second model."""
2
+ from pathlib import Path
3
+ import hashlib,json,platform,subprocess
4
+ import torch,transformers,safetensors
5
+ ROOT=Path(__file__).resolve().parents[1]
6
+ assert platform.system()=='Darwin' and platform.machine()=='arm64','Native Apple Silicon Python required'
7
+ assert torch.backends.mps.is_available(),'PyTorch MPS is unavailable'
8
+ expected='0a93cfcf7121112fdf90336bda1198ad67a3bb45247da6eedf0dd8672d4d53b5'
9
+ h=hashlib.sha256()
10
+ with (ROOT/'model/best.safetensors').open('rb') as f:
11
+ for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block)
12
+ assert h.hexdigest()==expected,'Model checksum mismatch'
13
+ browser=subprocess.check_output([str(ROOT/'node_modules/.bin/agent-browser'),'--version'],text=True).strip()
14
+ assert browser=='agent-browser 0.37.1',browser
15
+ print(json.dumps({'passed':True,'platform':platform.platform(),'torch':torch.__version__,'transformers':transformers.__version__,'safetensors':safetensors.__version__,'agent_browser':browser,'modelSha256':expected},indent=2))
scripts/common.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ nanojev_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
4
+ nanojev_saved_node=""
5
+ if [[ -f "$nanojev_root/.runtime/node-path" ]]; then
6
+ IFS= read -r nanojev_saved_node < "$nanojev_root/.runtime/node-path" || true
7
+ [[ -x "$nanojev_saved_node" ]] || nanojev_saved_node=""
8
+ fi
9
+ nanojev_node="${NANOJEV_NODE_BIN:-${nanojev_saved_node:-$(command -v node || true)}}"
10
+ if [[ -z "$nanojev_node" ]] || ! "$nanojev_node" -e 'process.exit(Number(process.versions.node.split(".")[0])>=24?0:1)' 2>/dev/null; then
11
+ printf '%s\n' 'Node.js 24+ required. Install Node 24 or set NANOJEV_NODE_BIN to its executable.' >&2
12
+ exit 1
13
+ fi
14
+ export PATH="$(dirname -- "$nanojev_node"):$nanojev_root/node_modules/.bin:$PATH"
15
+ export NANOJEV_AGENT_BROWSER_BIN="${NANOJEV_AGENT_BROWSER_BIN:-$nanojev_root/node_modules/.bin/agent-browser}"
scripts/publish.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepare an allowlisted Hugging Face upload; no network writes without --publish."""
2
+ import argparse,json,re
3
+ from pathlib import Path
4
+ from release import ROOT,verify
5
+
6
+ def main():
7
+ p=argparse.ArgumentParser(description=__doc__)
8
+ p.add_argument('--repo-id',help='Your Hugging Face namespace/NanoJev-Web')
9
+ p.add_argument('--publish',action='store_true',help='Create a PUBLIC repository and upload the verified files')
10
+ p.add_argument('--update-existing',action='store_true',help='Explicitly allow adding/replacing these files in an existing repository')
11
+ a=p.parse_args();m=verify();paths=sorted([*m['files'],'MANIFEST.json'])
12
+ if a.repo_id and not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*',a.repo_id):p.error('Expected namespace/repository')
13
+ print(json.dumps({'mode':'publish' if a.publish else 'dry-run','repo_id':a.repo_id,'public':True,'files':len(paths),'bytes':sum((ROOT/x).stat().st_size for x in paths),'local_runtime_and_runs_excluded':True}))
14
+ if not a.publish:return
15
+ if not a.repo_id:p.error('--repo-id is required for publishing')
16
+ from huggingface_hub import HfApi,CommitOperationAdd
17
+ api=HfApi();api.create_repo(repo_id=a.repo_id,repo_type='model',private=False,exist_ok=a.update_existing)
18
+ commit=api.create_commit(repo_id=a.repo_id,repo_type='model',commit_message='Release NanoJev-Web browser action model',operations=[CommitOperationAdd(path_in_repo=name,path_or_fileobj=str(ROOT/name)) for name in paths])
19
+ print(commit.commit_url)
20
+ if __name__=='__main__':main()
scripts/release.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify or export the exact public files listed in MANIFEST.json."""
2
+ import argparse,gzip,hashlib,json,tarfile
3
+ from pathlib import Path
4
+ ROOT=Path(__file__).resolve().parents[1]
5
+ FORBIDDEN={'.local','.runtime','.venv','node_modules','__pycache__','.git','runs','bench'}
6
+ def digest(path):
7
+ h=hashlib.sha256()
8
+ with path.open('rb') as f:
9
+ for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block)
10
+ return h.hexdigest()
11
+ def verify():
12
+ manifest=json.loads((ROOT/'MANIFEST.json').read_text())
13
+ for name,info in manifest['files'].items():
14
+ p=Path(name)
15
+ if name=='bench.command' or p.is_absolute() or '..' in p.parts or set(p.parts)&FORBIDDEN or any(x.startswith('.env') for x in p.parts):raise ValueError('Forbidden manifest path')
16
+ file=ROOT/p
17
+ if file.is_symlink() or not file.is_file() or ROOT not in file.resolve().parents:raise ValueError('Release file missing or not a regular contained file')
18
+ if file.stat().st_size!=info['bytes'] or digest(file)!=info['sha256']:raise ValueError('Release checksum mismatch: '+name)
19
+ return manifest
20
+
21
+ def export(path,manifest):
22
+ path=path.resolve()
23
+ if path==ROOT or ROOT in path.parents:raise ValueError('Export outside the release directory')
24
+ path.parent.mkdir(parents=True,exist_ok=True)
25
+ if path.exists():raise ValueError('Output already exists; choose a new filename')
26
+ with path.open('xb') as raw,gzip.GzipFile(filename='',fileobj=raw,mode='wb',mtime=0,compresslevel=6) as gz,tarfile.open(fileobj=gz,mode='w') as archive:
27
+ for name in sorted([*manifest['files'],'MANIFEST.json']):
28
+ file=ROOT/name;info=tarfile.TarInfo('NanoJev-Web/'+name)
29
+ info.size=file.stat().st_size;info.mode=0o755 if name.endswith('.command') or name.endswith('.sh') else 0o644
30
+ info.uid=info.gid=0;info.uname=info.gname='';info.mtime=0
31
+ with file.open('rb') as src:archive.addfile(info,src)
32
+ checksum=digest(path);path.with_suffix(path.suffix+'.sha256').write_text(checksum+' '+path.name+'\n')
33
+ print(json.dumps({'archive':path.name,'bytes':path.stat().st_size,'sha256':checksum}))
34
+ if __name__=='__main__':
35
+ p=argparse.ArgumentParser(description=__doc__);p.add_argument('--export',type=Path);a=p.parse_args();m=verify()
36
+ print(json.dumps({'verified':True,'files':len(m['files']),'bytes':sum(i['bytes'] for i in m['files'].values())}))
37
+ if a.export:export(a.export,m)
setup.command ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ cd -- "$(dirname -- "$0")"
4
+ source scripts/common.sh
5
+ if [[ "$(uname -s)" != Darwin || "$(uname -m)" != arm64 ]]; then
6
+ printf '%s\n' 'This installer targets native macOS Apple Silicon. Use an ARM terminal, without Rosetta.' >&2
7
+ exit 1
8
+ fi
9
+ nanojev_macos_version="$(sw_vers -productVersion)"
10
+ if (( ${nanojev_macos_version%%.*} < 14 )); then
11
+ printf '%s\n' 'macOS 14 or newer is required by the pinned PyTorch build.' >&2
12
+ exit 1
13
+ fi
14
+ if ! command -v uv >/dev/null; then
15
+ printf '%s\n' 'Install uv first (for example: brew install uv), then run setup.command again.' >&2
16
+ exit 1
17
+ fi
18
+ command -v npm >/dev/null || { printf '%s\n' 'npm is required; install Node.js with npm.' >&2; exit 1; }
19
+ export UV_PYTHON_INSTALL_DIR="$nanojev_root/.runtime/python"
20
+ export UV_CACHE_DIR="${NANOJEV_UV_CACHE:-$nanojev_root/.runtime/cache}"
21
+ uv python install 3.12.13 --no-bin
22
+ uv venv --clear --managed-python --python 3.12.13 "$nanojev_root/.venv"
23
+ uv pip sync --python "$nanojev_root/.venv/bin/python" "$nanojev_root/requirements-lock.txt"
24
+ if [[ -f package-lock.json ]]; then npm ci --no-audit --no-fund; else npm install --no-audit --no-fund; fi
25
+ "$nanojev_root/node_modules/.bin/agent-browser" install
26
+ "$nanojev_root/.venv/bin/python" "$nanojev_root/scripts/check-install.py"
27
+ printf '%s\n' "$nanojev_node" > "$nanojev_root/.runtime/node-path"
28
+ printf '%s\n' 'Ready. Start the model with ./start.command. To execute your page contract, run ./run.command --task your-task.json.'
start.command ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ nanojev_root="$(cd -- "$(dirname -- "$0")" && pwd)"
4
+ nanojev_python="$nanojev_root/.venv/bin/python"
5
+ [[ -x "$nanojev_python" ]] || { printf '%s\n' 'Run setup.command first.' >&2; exit 1; }
6
+ exec "$nanojev_python" -u "$nanojev_root/python/server.py" "$@"
test.command ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ cd -- "$(dirname -- "$0")"
4
+ export PYTHONDONTWRITEBYTECODE=1
5
+ .venv/bin/python -m unittest discover -s tests -p test_contract.py
6
+ .venv/bin/python scripts/release.py
tests/parity.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare the extracted model to frozen decisions from the original v5 server."""
2
+ from pathlib import Path
3
+ import argparse,json,urllib.request
4
+ ROOT=Path(__file__).resolve().parents[1]
5
+ def main():
6
+ p=argparse.ArgumentParser();p.add_argument('--endpoint',default='http://127.0.0.1:8774');p.add_argument('--out',type=Path,default=ROOT/'.local/parity.json');a=p.parse_args()
7
+ reference=json.loads((ROOT/'tests/reference-decisions.json').read_text());results=[]
8
+ for case in reference['cases']:
9
+ r=json.load(urllib.request.urlopen(urllib.request.Request(a.endpoint+'/api/evaluate',json.dumps(case['request']).encode(),{'Content-Type':'application/json'}),timeout=60))
10
+ diffs=[];choices=[]
11
+ for expected,actual in zip(case['expected'],r['states'],strict=True):
12
+ assert expected['id']==actual['id']
13
+ for qid,e in expected['answers'].items():
14
+ found=actual['answers'][qid];assert set(e['probabilities'])==set(found['probabilities'])
15
+ diffs.extend(abs(v-found['probabilities'][k]) for k,v in e['probabilities'].items());choices.append(e['choice']==found['choice'])
16
+ delta=max(diffs);passed=delta<=1e-4 and all(choices)
17
+ results.append({'case':case['case'],'maxProbabilityDifference':delta,'sameChoices':all(choices),'passed':passed})
18
+ print(json.dumps(results[-1]),flush=True)
19
+ out={'passed':all(x['passed'] for x in results),'cases':results,'tolerance':1e-4}
20
+ a.out.parent.mkdir(parents=True,exist_ok=True);a.out.write_text(json.dumps(out,indent=2)+'\n')
21
+ if not out['passed']:raise SystemExit(1)
22
+ if __name__=='__main__':main()