File size: 34,182 Bytes
37d21bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b782d1
37d21bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b782d1
dcf6ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b782d1
dcf6ff7
1b782d1
 
 
 
e489a70
dcf6ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
1b782d1
dcf6ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b782d1
 
 
 
 
 
 
 
 
 
dcf6ff7
 
 
 
1b782d1
 
 
 
dcf6ff7
 
 
 
1b782d1
dcf6ff7
 
 
 
 
 
 
 
 
1b782d1
dcf6ff7
 
 
 
 
 
 
 
 
 
 
 
1b782d1
dcf6ff7
 
 
 
 
 
e489a70
 
 
 
 
 
 
 
 
 
dcf6ff7
 
 
1b782d1
dcf6ff7
 
 
 
 
 
e489a70
 
 
 
dcf6ff7
 
 
1b782d1
dcf6ff7
 
 
 
 
 
 
1b782d1
dcf6ff7
 
 
 
 
 
 
 
1b782d1
dcf6ff7
 
 
 
 
 
 
 
 
 
1b782d1
dcf6ff7
 
 
 
 
 
 
 
 
 
 
 
 
37d21bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64900a8
37d21bb
 
dcf6ff7
37d21bb
 
 
 
dcf6ff7
37d21bb
 
 
64900a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d21bb
 
 
 
 
 
 
 
 
 
 
 
 
 
64900a8
37d21bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64900a8
37d21bb
 
 
 
 
 
 
 
 
 
64900a8
37d21bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64900a8
dcf6ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64900a8
dcf6ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
64900a8
dcf6ff7
 
 
 
 
 
 
 
 
64900a8
dcf6ff7
 
 
 
 
 
 
 
 
 
 
64900a8
dcf6ff7
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
diff --git a/README.md b/README.md
index 4e354cf..6d4801c 100644
--- a/README.md
+++ b/README.md
@@ -20,8 +20,18 @@ pip install --no-deps -e <vggt-omega checkout>   # optional; gated weights, FAIR
 pytest -q
 ```
 
-Generation also needs Docker, the agent CLIs logged in on the host (Claude Code at `~/.local/bin/claude`, Codex CLI,
-OpenCode's login in `~/.local/share/opencode/auth.json`) and the two images:
+Generation also needs Docker and host logins (Claude Code at `~/.local/bin/claude`, Codex's login in
+`~/.codex/auth.json`, OpenCode V2's active account via `opencode auth export <provider>`, or a legacy
+`~/.local/share/opencode/auth.json`). The runner converts V2 credentials into a private temporary V1 login for
+the container; it does not require or create a host `auth.json`, or copy the host database. Credential refreshes
+use `opencode auth import`, preserving a concurrent user login or account switch.
+Codex 0.167.0 and OpenCode 1.19.5
+are installed inside both images; a host Codex executable is not mounted or required.
+The images target Linux AMD64. On Apple Silicon, build with `--platform linux/amd64`; Docker Desktop must share
+the repository and run directories. MuJoCo generation can use emulation. Isaac Sim requires a supported NVIDIA GPU
+host and NVIDIA Container Toolkit; building its image on a Mac does not verify GPU simulation.
+Claude Code still mounts the host executable and therefore requires a compatible Linux binary.
+Build the two images:
 
 ```bash
 docker build -t simready-generation:latest -f src/simready/generation/runtime/Dockerfile src/simready/generation/runtime
diff --git a/docs/generation.md b/docs/generation.md
index 01f7d87..b9ccf2c 100644
--- a/docs/generation.md
+++ b/docs/generation.md
@@ -58,12 +58,18 @@ from; do not read authentication files.
 
 - **Claude Code** (host `~/.local/bin/claude`, mounted read-only): every tool but `WebFetch`; `WebSearch` runs on
   Anthropic's side. `--claude-config-dir` picks the login folder (default `~/.claude`, e.g. `~/.claude-huan`).
-- **Codex CLI** (host `codex`, mounted read-only): `web_search="live"`, browser features off. Model `gpt-6.1-sol`
-  (`codex debug models`).
+- **Codex CLI** 0.167.0 (Linux x64, installed in both images, pinned by archive and binary sha256 in
+  `runtime/install_codex.sh`): `web_search="live"`, browser features off. Model `gpt-6.1-sol`.
+  The runner copies only the host login (`~/.codex/auth.json`) into the session state, not the host executable.
 - **OpenCode** 1.19.5 (in both images, pinned by sha256 with the ripgrep its glob and grep tools need):
   `opencode run --pure --auto --format json -m opencode-go/<model>`; `webfetch` denied by its permission config, so not
   offered; `websearch` (Exa or Parallel) on. Its config, cache, login and session database live in the session's state
   folder (`XDG_*`); updates, the models.dev fetch, plugins, project config and Claude Code compatibility are off.
+  On a V2 host, the runner exports only the model provider's active account with `opencode auth export <provider>`.
+  It converts V2 API-key credentials into the V1 schema in the private temporary state folder. The host needs no
+  `auth.json`; its database is neither mounted nor copied. Rotated credentials return through `opencode auth import`
+  only if the exported account and credentials still match the initial login. A V1 host can still use its existing
+  `~/.local/share/opencode/auth.json`. CLI credential output is captured and excluded from errors and run logs.
 - **Isolation.** Read-only input and tools, writable output and scratch, the login copied into a private state folder and
   saved back when it rotates (a backup first; a login changed meanwhile by someone else is kept). Every 20 s a running
   session exchanges rotated tokens with the saved login, so sessions sharing a login do not invalidate each other.
@@ -77,14 +83,18 @@ from; do not read authentication files.
 
 | Image | Dockerfile | Contents |
 |---|---|---|
-| `simready-generation:latest` | `runtime/Dockerfile` | Python 3.12, MuJoCo 4.0.0, NumPy, SciPy, Pillow, imageio-ffmpeg, ffmpeg, Blender 5.2.3, OpenCode 1.19.5 + ripgrep 15.1.0, `runtime/requirements-tools.txt` (trimesh, Open3D, OpenCV, scikit-image, PyMeshLab, manifold3d, usd-core, shapely, pandas, matplotlib, scikit-learn, networkx, pygltflib, rtree) |
-| `simready-isaac-generation:latest` | `runtime/Dockerfile.isaac` | `nvcr.io/nvidia/isaac-sim:6.2.0` plus the same Blender and OpenCode; the host ffmpeg is mounted |
+| `simready-generation:latest` | `runtime/Dockerfile` | Python 3.12, MuJoCo 4.0.0, NumPy, SciPy, Pillow, imageio-ffmpeg, ffmpeg, Blender 5.2.3, Codex 0.167.0, OpenCode 1.19.5 + ripgrep 15.1.0, `runtime/requirements-tools.txt` (trimesh, Open3D, OpenCV, scikit-image, PyMeshLab, manifold3d, usd-core, shapely, pandas, matplotlib, scikit-learn, networkx, pygltflib, rtree) |
+| `simready-isaac-generation:latest` | `runtime/Dockerfile.isaac` | `nvcr.io/nvidia/isaac-sim:6.2.0` plus the same Blender, Codex and OpenCode; the host ffmpeg is mounted |
 
 ```bash
 docker build -t simready-generation:latest -f src/simready/generation/runtime/Dockerfile src/simready/generation/runtime
 docker build -t simready-isaac-generation:latest -f src/simready/generation/runtime/Dockerfile.isaac src/simready/generation/runtime
 ```
 
+Both images target Linux AMD64; add `--platform linux/amd64` when building on Apple Silicon. Docker Desktop must
+share the repository and run directories. Codex and OpenCode use image binaries; Claude Code still needs a compatible
+Linux host executable. Isaac Sim also requires a supported NVIDIA GPU host with NVIDIA Container Toolkit.
+
 An Isaac session needs its CLI's shader-cache volume warmed once (`data/runtime/isaac/smoke_<cli>/smoke.json`):
 
 ```bash
@@ -98,6 +108,35 @@ docker run --rm --gpus device=GPU-... --user 1234:1234 --entrypoint bash -e ACCE
 
 ## Commands
 
+Campaigns can enforce subscription reserves with an optional top-level `quota` object:
+
+```json
+"quota": {
+  "codex_weekly_remaining_percent": 30,
+  "poll_seconds": 30,
+  "opencode_pause_on_limit": true
+}
+```
+
+The host's Codex app-server `account/rateLimits/read` supplies the weekly window (10080 minutes).
+At or below the configured reserve, the runner stops dispatching Codex jobs and stops active Codex containers
+at their next monitoring check (at most 20 seconds after detection). With a positive reserve, missing or invalid quota data also pause Codex.
+Polling and provider reporting delays mean this is not an exact account-wide billing cap; other sessions also use
+the account. No reset credits are consumed. Set the reserve to `0` to use the full weekly allowance. Quota policy edits
+reload into the existing guard. A reserve-threshold pause otherwise stays paused for this invocation; another CLI
+may continue. With a positive reserve, a quota-query failure pauses spending while quota remains unknown. With a
+zero reserve, unavailable quota reporting leaves exhaustion enforcement to the provider. Queries retry at the configured
+poll interval; a fresh valid reading above the reserve releases only the query-failure pause and its partial job.
+OpenCode HTTP 402/429 errors pause its login without retrying the same rejected job. These responses can indicate
+either exhausted allowance or a temporary provider rate limit; they do not establish a remaining balance.
+Partial quota-stopped runs are retained as `quota_paused`, skipped by evaluation, and never counted as generated.
+An explicit restart retries these jobs from the beginning while retaining the partial attempts as provenance.
+Completed runs are kept. Existing saved adaptive concurrency cannot exceed the configured `per_cli_max`.
+Only one `campaign run` process can hold a campaign's `.run.lock` at once.
+
+For unattended local runs, redirect stdout/stderr to a persistent log and detach stdin; a closed terminal pipe must
+not be the process's output destination. Keep Docker, network connectivity and the workstation available.
+
 ```bash
 simready generate --track scenes --engine mujoco --id 41159420 --cli codex --model gpt-6.1-sol --budget 900 1800
 simready generate --track objects --engine mujoco --id input_2d_001 --cli claude --claude-config-dir ~/.claude-huan --model claude-opus-5-5
diff --git a/src/simready/generation/campaign.py b/src/simready/generation/campaign.py
index 1224349..5aa0fc8 100644
--- a/src/simready/generation/campaign.py
+++ b/src/simready/generation/campaign.py
@@ -10,6 +10,7 @@ each other's rotated tokens in step (Session.sync_login). The config format is i
     simready campaign status configs/campaigns/example.json
 """
 import os
+import fcntl
 from pathlib import Path
 import queue
 import subprocess
@@ -22,6 +23,7 @@ from ..common.gpu import MINIMUM_FREE_MIB, driver_busy, free_mib
 from ..common.io import DATA, read_json, write_json
 from .session import Session, shown
 from .stage import frozen_protocol
+from .quota import QuotaGuard
 
 LOAD_PAUSE_SECONDS = 600
 LOGIN_START_GAP_SECONDS = 60  # a session refreshing an expired login rotates its refresh token; one starting beside it then fails
@@ -58,7 +60,7 @@ def recover(state):
         for run in job["runs"]:
             if run["evaluation"] in {"running", "failed"}:
                 run["evaluation"] = "pending"
-        if job["state"] in {"running", "failed"}:
+        if job["state"] in {"running", "failed"} or any(r.get("status") == "quota_paused" for r in job["runs"]):
             job["attempts_abandoned"] = job.get("attempts_abandoned", []) + [r["run"] for r in job["runs"]]
             job.update(state="pending", runs=[])
             job.pop("error", None)
@@ -131,6 +133,10 @@ def settle(job, held):
     """A finished session's outcome. A CLI crash well into a session starts over once; a session failed by a rate limit
     goes back to the queue (the login's limit is lowered elsewhere), and so does a first early failure; an early failure
     that repeats looks like a lost login, so that login takes no more sessions."""
+    if any(r["status"] == "quota_paused" for r in job["runs"]):
+        job["state"] = "pending"
+        held[login(job)] = job["id"]
+        return
     failure = next((r for r in job["runs"] if r["status"] == "cli_failed"), None)
     if not job["runs"]:
         job["state"] = "failed"
@@ -180,6 +186,8 @@ class Campaign:
         self.state = recover(read_json(self.path)) if self.path.is_file() else {"jobs": [], "held": {}}
         self.merge_jobs()
         self.state.setdefault("login_limits", {})
+        self.quota_guard = QuotaGuard(self.config.get("quota", {}))
+        self.state["quota"] = self.quota_guard.snapshot()
         if self.config.get("evaluate", True):  # results generated with evaluation off (e.g. on another machine) are evaluated now
             for entry in (r for j in self.state["jobs"] for r in j["runs"] if r["evaluation"] == "skipped"):
                 entry["evaluation"] = "pending"
@@ -223,6 +231,8 @@ class Campaign:
             return
         old, self.config_stamp = self.config["limits"], stamp
         self.config = {**read_json(self.config_path), "name": self.config["name"]}
+        if self.quota_guard.config != self.config.get("quota", {}):
+            self.quota_guard.update_policy(self.config.get("quota", {}))
         self.merge_jobs()
         self.tune_pools()
         for key, cap in (("isaac_sessions", "sessions"), ("isaac_evaluations", "evaluations")):
@@ -261,7 +271,11 @@ class Campaign:
             self.isaac_changed = now
 
     def allowed(self, job):
-        return self.state["login_limits"].get(login(job), limit(self.config["limits"], job))
+        configured = limit(self.config["limits"], job)
+        current = self.state["login_limits"].get(login(job), configured)
+        if current == 0 and configured > 0:
+            current = configured
+        return min(current, limit(self.config["limits"], job, "per_cli_max", current))
 
     def rate_limited(self, job):
         """A rate limit: halve the login's session limit and pause it."""
@@ -283,7 +297,8 @@ class Campaign:
             entry = {"run": str(shown(run)), "status": record["status"], "budget_seconds": record["budget_seconds"],
                      "elapsed_seconds": record["elapsed_seconds"], "stage_seconds": record.get("stage_seconds", record["elapsed_seconds"]),
                      "api_retries": record["api_retries"], "rate_limit_events": record["rate_limit_events"],
-                     "usd": (record.get("cost") or {}).get("usd"), "evaluation": "pending" if self.config.get("evaluate", True) else "skipped"}
+                     "usd": (record.get("cost") or {}).get("usd"),
+                     "evaluation": "pending" if self.config.get("evaluate", True) and record["status"] != "quota_paused" else "skipped"}
             with self.lock:
                 job["runs"].append(entry)
                 if entry["rate_limit_events"]:
@@ -292,8 +307,10 @@ class Campaign:
             if entry["evaluation"] == "pending":
                 (self.isaac if job["engine"] == "isaac" else self.mujoco).put((job, entry, run))
         try:
-            Session(job["track"], job["engine"], job["item"], job["cli"], job["model"], job.get("effort"), job.get("gpu"),
-                    job.get("claude_config_dir"), campaign=self.config["name"]).run(job["budgets"], on_result)
+            session = Session(job["track"], job["engine"], job["item"], job["cli"], job["model"], job.get("effort"), job.get("gpu"),
+                              job.get("claude_config_dir"), campaign=self.config["name"])
+            session.quota_guard = getattr(self, "quota_guard", None)
+            session.run(job["budgets"], on_result)
             with self.lock:
                 settle(job, self.state["held"])
                 if job["state"] == "pending":  # requeued: it may have been taken out of the config meanwhile
@@ -330,7 +347,18 @@ class Campaign:
     def finished(self):
         jobs = self.state["jobs"]
         return (all(j["state"] != "running" for j in jobs) and all(r["evaluation"] in {"done", "failed", "skipped"} for j in jobs for r in j["runs"])
-                and all(j["state"] != "pending" or login(j) in self.state["held"] for j in jobs))
+                and all(j["state"] != "pending" or login(j) in self.state["held"]
+                        or j["cli"] in self.quota_guard.blocked() for j in jobs))
+
+    def release_revalidated_quota_holds(self, blocked):
+        """Release only partial quota-stopped jobs after a fresh successful quota check."""
+        for job in self.state["jobs"]:
+            name = login(job)
+            if (job["cli"] not in blocked and self.state["held"].get(name) == job["id"]
+                    and job["state"] == "pending" and any(r.get("status") == "quota_paused" for r in job["runs"])):
+                job["attempts_abandoned"] = job.get("attempts_abandoned", []) + [r["run"] for r in job["runs"]]
+                job["runs"] = []
+                del self.state["held"][name]
 
     def run(self):
         from ..common.io import REPO_ROOT
@@ -351,6 +379,13 @@ class Campaign:
             threading.Thread(target=self.evaluator, args=(self.mujoco, False), daemon=True).start()
         loaded_since, started = None, {}
         while not self.finished():
+            quota_blocked = self.quota_guard.blocked()
+            quota = self.quota_guard.snapshot()
+            if quota != self.state.get("quota"):
+                with self.lock:
+                    self.release_revalidated_quota_holds(quota_blocked)
+                    self.state["quota"] = quota
+                    self.save()
             ceiling = self.config["limits"].get("pause_new_jobs_above_load")
             loaded_since = (loaded_since or time.monotonic()) if ceiling and os.getloadavg()[0] > ceiling else None
             paused = loaded_since is not None and time.monotonic() - loaded_since >= LOAD_PAUSE_SECONDS  # a shared host: others' work comes first
@@ -360,6 +395,7 @@ class Campaign:
                 now = time.monotonic()
                 blocked = {name for name, at in started.items() if now - at < LOGIN_START_GAP_SECONDS}
                 blocked |= {name for name, at in self.cooling.items() if now - at < COOL_SECONDS}
+                blocked |= quota_blocked
                 self.tune_isaac()
                 limits = {**self.config["limits"], "isaac_sessions": self.isaac_caps()["sessions"]}
                 job = None if paused else next_job(self.state["jobs"], limits, self.state["held"],
@@ -375,6 +411,8 @@ class Campaign:
                 time.sleep(2)
             else:
                 time.sleep(5)
+        self.state["quota"] = self.quota_guard.snapshot()
+        self.save()
         print(summary(self.state), flush=True)
 
 
@@ -389,6 +427,10 @@ def summary(state):
              f"throttled results {sum(bool(r['api_retries'] or r['rate_limit_events']) for r in runs)}, "
              f"list price so far ${sum(r['usd'] or 0 for j in jobs for r in j['runs'][-1:]):.2f}"]
     lines += [f"HELD {name}: {job}" for name, job in state["held"].items()]
+    quota = state.get("quota", {})
+    if quota.get("codex_weekly"):
+        lines += [f"Codex weekly quota remaining {quota['codex_weekly']['remaining_percent']}% (last check)"]
+    lines += [f"QUOTA PAUSED {cli}: {reason}" for cli, reason in quota.get("paused", {}).items()]
     lines += [f"FAILED {j['id']}: {(j.get('error') or '').strip().splitlines()[-1:]}" for j in jobs if j["state"] == "failed"]
     lines += [f"EVALUATION FAILED {r['run']}" for r in runs if r["evaluation"] == "failed"]
     return "\n".join(lines)
@@ -401,5 +443,12 @@ def status(config_path):
 
 def main_run(config, generation_gpus="", evaluation_gpus="", render_gpu=None):
     split = lambda value: [g for g in (value or "").split(",") if g]
-    Campaign(config, split(generation_gpus), split(evaluation_gpus), render_gpu).run()
+    directory = CAMPAIGNS / read_json(config)["name"]
+    directory.mkdir(parents=True, exist_ok=True)
+    with (directory / ".run.lock").open("a") as lock:
+        try:
+            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+        except BlockingIOError:
+            raise SystemExit("This campaign is already running.") from None
+        Campaign(config, split(generation_gpus), split(evaluation_gpus), render_gpu).run()
 
diff --git a/src/simready/generation/contracts.py b/src/simready/generation/contracts.py
index 411377b..c688906 100644
--- a/src/simready/generation/contracts.py
+++ b/src/simready/generation/contracts.py
@@ -10,7 +10,6 @@ import hashlib
 import json
 from pathlib import Path
 import re
-import shutil
 import subprocess
 
 from ..common.io import BENCHMARK
@@ -33,18 +32,19 @@ BLENDER_VERSION = "5.2.3"
 OPENCODE_HOSTS = ("opencode.ai", "mcp.exa.ai", "search.parallel.ai")
 EGRESS_HOSTS = ("api.anthropic.com", "platform.claude.com", "chatgpt.com", "auth.openai.com") + OPENCODE_HOSTS
 
-# The agent CLIs. Claude Code and Codex are the host's binaries, mounted read-only (their version is read at each run);
-# OpenCode is installed in both generation images, pinned by version and sha256 (runtime/install_opencode.sh).
+# Claude Code is mounted from the host. Codex and OpenCode are installed in both images,
+# pinned by version and sha256 (runtime/install_codex.sh and runtime/install_opencode.sh).
 CLIS = {
     "claude": {"name": "Claude Code", "binary": "host ~/.local/bin/claude, mounted read-only",
                "login": "<config dir>/.credentials.json (default ~/.claude; --claude-config-dir)",
                "tools": "every tool but WebFetch (--disallowedTools WebFetch); WebSearch runs on Anthropic's side",
                "hosts": ["api.anthropic.com", "platform.claude.com"]},
-    "codex": {"name": "Codex CLI", "binary": "host codex, mounted read-only", "login": "~/.codex/auth.json",
+    "codex": {"name": "Codex CLI", "version": "0.167.0", "binary": "/opt/codex/bin/codex in both generation images",
+              "binary_sha256": "cdcb45aaa01d0f14e298985e09465aebccd47f64ecd298aea44814af7b62bbda", "login": "~/.codex/auth.json",
               "tools": 'every tool, web_search="live", browser features off', "hosts": ["chatgpt.com", "auth.openai.com"]},
     "opencode": {"name": "OpenCode", "version": "1.19.5", "binary": "/opt/opencode/bin/opencode in both generation images",
                  "binary_sha256": "7df4e4136301f16589b0f30bf91a61380fca5f8ef22dd36570f5ebe1d4ec802c",
-                 "login": "~/.local/share/opencode/auth.json", "billing": "subscription (OpenCode Go)",
+                 "login": "host OpenCode V2 auth export/import API, or legacy ~/.local/share/opencode/auth.json", "billing": "subscription (OpenCode Go)",
                  "tools": "every tool but webfetch (denied by its permission config, so not offered); websearch on (Exa or Parallel)",
                  "hosts": list(OPENCODE_HOSTS)},
 }
@@ -218,7 +218,7 @@ def cli_version(cli):
     """The installed version of a host-mounted CLI, or the pinned one."""
     if "version" in CLIS[cli]:
         return CLIS[cli]["version"]
-    binary = shutil.which("codex") if cli == "codex" else str(Path.home() / ".local/bin/claude")
+    binary = str(Path.home() / ".local/bin/claude")
     try:
         return subprocess.run([binary, "--version"], capture_output=True, text=True, timeout=30).stdout.strip() or None
     except (OSError, TypeError, subprocess.SubprocessError):
diff --git a/src/simready/generation/runtime/Dockerfile b/src/simready/generation/runtime/Dockerfile
index 931130f..74ec948 100755
--- a/src/simready/generation/runtime/Dockerfile
+++ b/src/simready/generation/runtime/Dockerfile
@@ -1,5 +1,5 @@
 # simready-generation:latest, the MuJoCo agents' runtime: MuJoCo, headless Blender (install_blender.sh), the geometry and
-# vision packages of requirements-tools.txt and the pinned OpenCode CLI with ripgrep (install_opencode.sh).
+# vision packages of requirements-tools.txt, pinned Codex (install_codex.sh) and OpenCode with ripgrep (install_opencode.sh).
 #   docker build -t simready-generation:latest -f src/simready/generation/runtime/Dockerfile src/simready/generation/runtime
 FROM python:3.12-slim-bookworm
 RUN apt-get update && apt-get install -y --no-install-recommends \
@@ -14,6 +14,8 @@ COPY requirements-tools.txt /tmp/requirements-tools.txt
 RUN pip install --no-cache-dir -r /tmp/requirements-tools.txt numpy==2.4.4 && rm /tmp/requirements-tools.txt
 COPY install_opencode.sh /tmp/install_opencode.sh
 RUN bash /tmp/install_opencode.sh && rm /tmp/install_opencode.sh && rm -rf /root/.local /root/.cache /root/.config
+COPY install_codex.sh /tmp/install_codex.sh
+RUN bash /tmp/install_codex.sh && rm /tmp/install_codex.sh
 # No network but the CLI API (session.EGRESS_HOSTS): every package an agent may use is installed here.
 ENV MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 PIP_DISABLE_PIP_VERSION_CHECK=1 PATH=/tmp/agent-home/.local/bin:$PATH
 WORKDIR /work
diff --git a/src/simready/generation/runtime/Dockerfile.isaac b/src/simready/generation/runtime/Dockerfile.isaac
index df215f4..0f49e7d 100644
--- a/src/simready/generation/runtime/Dockerfile.isaac
+++ b/src/simready/generation/runtime/Dockerfile.isaac
@@ -1,5 +1,5 @@
 # simready-isaac-generation:latest, the Isaac Sim agents' runtime: Isaac Sim plus the same pinned headless Blender and
-# OpenCode CLI as simready-generation:latest. Isaac evaluation keeps the plain nvcr image.
+# Codex and OpenCode CLIs as simready-generation:latest. Isaac evaluation keeps the plain nvcr image.
 #   docker build -t simready-isaac-generation:latest -f src/simready/generation/runtime/Dockerfile.isaac src/simready/generation/runtime
 FROM nvcr.io/nvidia/isaac-sim:6.2.0
 USER root
@@ -9,5 +9,7 @@ COPY install_blender.sh /tmp/install_blender.sh
 RUN bash /tmp/install_blender.sh && rm /tmp/install_blender.sh
 COPY install_opencode.sh /tmp/install_opencode.sh
 RUN bash /tmp/install_opencode.sh && rm /tmp/install_opencode.sh && rm -rf /root/.local /root/.cache /root/.config
+COPY install_codex.sh /tmp/install_codex.sh
+RUN bash /tmp/install_codex.sh && rm /tmp/install_codex.sh
 ENV PIP_DISABLE_PIP_VERSION_CHECK=1
 USER isaac-sim
diff --git a/src/simready/generation/session.py b/src/simready/generation/session.py
index c51a4b3..25bb5ed 100644
--- a/src/simready/generation/session.py
+++ b/src/simready/generation/session.py
@@ -29,6 +29,8 @@ from . import contracts
 from .contracts import EGRESS_HOSTS, IMAGES
 from .cost import combine_costs, events, keep_codex_usage, keep_opencode_usage, run_cost
 from .stage import contract_for, frozen_protocol, item_input, stage
+from .opencode_auth import OpenCodeLogin
+from .quota import opencode_limit
 
 MUJOCO_IMAGE, ISAAC_IMAGE = IMAGES["mujoco"], IMAGES["isaac"]
 RUNS, RUNTIME = DATA / "runs", DATA / "runtime"
@@ -157,8 +159,13 @@ def throttling(log):
     retries = limited = 0
     for event in events(log):
         retries += event.get("subtype") == "api_retry"
-        limited += (event.get("type") == "rate_limit_event" and (event.get("rate_limit_info") or {}).get("status") not in {"allowed", "allowed_warning"}
-                    or event.get("type") == "error")
+        if event.get("type") == "rate_limit_event":
+            limited += (event.get("rate_limit_info") or {}).get("status") not in {"allowed", "allowed_warning"}
+        elif event.get("type") == "error":
+            error = event.get("error") or {}
+            if isinstance(error, dict):
+                data = error.get("data") or {}
+                limited += isinstance(data, dict) and data.get("statusCode") == 429
     return {"api_retries": retries, "rate_limit_events": limited}
 
 
@@ -214,7 +221,13 @@ class Session:
         self.contract = contract_for(track, engine, item)
         if contracts.missing_files(self.contract):
             raise SystemExit(f"{self.contract} stages {', '.join(contracts.missing_files(self.contract))}, not present yet.")
-        if not (self.login / self.auth_name).is_file():
+        if cli == "opencode":
+            self.opencode_login = OpenCodeLogin(self.login, model.split("/", 1)[0])
+            try:
+                self.read_login()
+            except (OSError, RuntimeError) as error:
+                raise SystemExit(f"OpenCode login is unavailable: {error}") from None
+        elif not (self.login / self.auth_name).is_file():
             raise SystemExit(f"The {cli} login is unavailable ({self.login / self.auth_name}).")
         if self.isaac and not gpu:
             raise SystemExit("Isaac generation needs a GPU (--gpu UUID).")
@@ -229,9 +242,16 @@ class Session:
     def persist(self, original, state, initial):
         """Save a refreshed login from the state folder back to the CLI's own login."""
         if self.cli == "opencode":
+            login = getattr(self, "opencode_login", None)
+            if login is not None and login.v2:
+                return login.persist(state / self.held, initial)
             return persist_opencode(original, state / OPENCODE_DATA, initial)
         return (persist_codex if self.cli == "codex" else persist_claude)(original, state, initial)
 
+    def read_login(self):
+        login = getattr(self, "opencode_login", None)
+        return login.read() if login is not None else (self.login / self.auth_name).read_bytes()
+
     def agent(self):
         if self.cli == "opencode":
             variant = ["--variant", self.effort] if self.effort != "default" else []
@@ -261,9 +281,7 @@ class Session:
         if self.cli == "opencode":  # the binary is the image's own (pinned); its config, cache and sessions live in the state folder
             command += [part for key, value in OPENCODE_ENV.items() for part in ("-e", f"{key}={value}")]
         elif self.cli == "codex":
-            binary = Path(shutil.which("codex")).resolve()
-            command += ["-e", "CODEX_HOME=/auth", "-e", "PATH=/opt/codex/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin",
-                        "--mount", f"type=bind,src={binary.parent},dst=/opt/codex/bin,readonly"]
+            command += ["-e", "CODEX_HOME=/auth", "-e", "PATH=/opt/codex/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin"]
         else:
             binary = (Path.home() / ".local/bin/claude").resolve()
             command += ["-e", "CLAUDE_CONFIG_DIR=/auth", "-e", "DISABLE_AUTOUPDATER=1", "--mount", f"type=bind,src={binary},dst=/usr/local/bin/claude,readonly"]
@@ -276,27 +294,27 @@ class Session:
         Returns what both now hold."""
         try:
             held = subprocess.run(["docker", "exec", name, "cat", "/auth/" + self.held], capture_output=True, timeout=15, check=True).stdout
-            saved = (self.login / self.auth_name).read_bytes()
+            saved = self.read_login()
             if held and held != known:
                 with tempfile.TemporaryDirectory() as directory:
                     fresh = Path(directory)
                     (fresh / self.held).parent.mkdir(parents=True, exist_ok=True)
                     (fresh / self.held).write_bytes(held)
                     (fresh / self.held).chmod(0o600)
-                    self.persist(self.login, fresh, saved)
-                return (self.login / self.auth_name).read_bytes()
+                    self.persist(self.login, fresh, known)
+                return self.read_login()
             if saved != known:
                 subprocess.run(["docker", "exec", "-i", name, "sh", "-c", f"cat > /auth/{self.held}.new && mv /auth/{self.held}.new /auth/{self.held}"],
                                input=saved, capture_output=True, timeout=15, check=True)
                 return saved
-        except (subprocess.SubprocessError, OSError, ValueError):
+        except (subprocess.SubprocessError, OSError, ValueError, RuntimeError):
             pass  # the end of the stage saves it anyway
         return known
 
     def stage(self, run, record, prompt, seconds, state, scratch):
         """One timed container. Stopping at the budget is normal; the agent's session survives in `state`."""
         public, output, log = run / "input", run / "output", run / "generation.jsonl"
-        initial = (self.login / self.auth_name).read_bytes()
+        initial = self.read_login()
         (state / self.held).parent.mkdir(mode=0o700, exist_ok=True)
         (state / self.held).write_bytes(initial)
         (state / self.held).chmod(0o600)
@@ -312,6 +330,16 @@ class Session:
         started = time.monotonic()
         record.update(status="running", started_at=datetime.now(timezone.utc).isoformat())
         save_record(run / "run.json", record)
+        guard = getattr(self, "quota_guard", None)
+        if guard:
+            reason = guard.reason(self.cli)
+            if reason:
+                log.touch()
+                record.update(status="quota_paused", quota_pause_reason=reason,
+                              api_retries=0, rate_limit_events=0, exit_code=None,
+                              credential_refresh_persistence="unchanged", cli_session_id=self.session_id,
+                              finished_at=datetime.now(timezone.utc).isoformat())
+                return 0.
         try:
             with log.open("w") as stream:
                 ensure_egress()
@@ -325,6 +353,14 @@ class Session:
                             process.wait(timeout=min(LOGIN_SYNC_SECONDS, max(seconds - (time.monotonic() - started), .1)))
                             break
                         except subprocess.TimeoutExpired:
+                            reason = guard.reason(self.cli) if guard else None
+                            if guard and self.cli == "opencode" and guard.config.get("opencode_pause_on_limit"):
+                                reason = reason or opencode_limit(log)
+                                if reason:
+                                    guard.pause(self.cli, reason)
+                            if reason:
+                                record["quota_pause_reason"] = reason
+                                raise
                             if time.monotonic() - started >= seconds:
                                 raise
                             if not record.get("model_answered"):
@@ -341,7 +377,8 @@ class Session:
                     except subprocess.TimeoutExpired:
                         process.kill()
                         process.wait()
-                    record.update(status="cli_failed" if record.get("stalled") else "budget_expired", exit_code=process.returncode)
+                    record.update(status="quota_paused" if record.get("quota_pause_reason") else
+                                  "cli_failed" if record.get("stalled") else "budget_expired", exit_code=process.returncode)
         finally:
             subprocess.run(["docker", "rm", "-f", name], capture_output=True)
             if self.isaac:
@@ -352,6 +389,11 @@ class Session:
         self.session_id = self.session_id or session_identity(self.cli, log)
         record["cli_session_id"] = self.session_id
         record.update(throttling(log))
+        if guard and self.cli == "opencode" and guard.config.get("opencode_pause_on_limit"):
+            reason = opencode_limit(log)
+            if reason:
+                guard.pause(self.cli, reason)
+                record.update(status="quota_paused", quota_pause_reason=reason)
         if record.get("stalled"):  # no answer at all: a refused login (rate or usage limit), not the agent's work
             record["rate_limit_events"] = max(1, record["rate_limit_events"])
         return time.monotonic() - started
@@ -410,7 +452,7 @@ class Session:
                     previous = run
                     if on_result:
                         on_result(run, record)
-                    if record["status"] == "cli_failed" or not self.session_id:
+                    if record["status"] in {"cli_failed", "quota_paused"} or not self.session_id:
                         break
             finally:
                 if self.isaac: