AI mentor that corrects your written math visually with local harnesses.
Python
Live marks, and Codex and Antigravity alongside Claude Code
Abdullah A.992bed93daea
diff --git a/README.md b/README.mdindex f2ea492..45af3e6 100644--- a/README.md+++ b/README.md@@ -1,13 +1,13 @@<p align="center"><img src="docs/banner.png" alt="penmentor" width="100%"></p><p align="center">-A maths mentor at the tip of your pen. Press a key while you work by hand: Claude marks your work on the screen like a<br>-teacher with coloured pens, gives you hints instead of answers, and shows the idea as a 3Blue1Brown-style animation.+A maths mentor at the tip of your pen. Press a key while you work by hand: Claude, Gemini or GPT marks your work on the<br>+screen like a teacher with coloured pens, gives you hints instead of answers, and shows the idea as a 3Blue1Brown-style animation.</p><p align="center"><img src="docs/demo.gif" alt="Writing an integral in xournal++, penmentor marking the sign slip, then animating the area" width="860"><br><sub>Handwriting in xournal++ → one key → the slip is marked on the page → box the integral → an interactive manim animation.-(<a href="docs/demo.mp4">video</a>; for a repeatable recording the pen is scripted and Claude's answer is a fixed example.)</sub></p>+(<a href="docs/demo.mp4">video</a>; for a repeatable recording the pen is scripted and the model's answer is a fixed example.)</sub></p>## Why I use it@@ -20,13 +20,26 @@ the next step, and *show* me why. penmentor is that, one key away, on my own Cla- **Hints, not answers.** A ladder from a nudge to naming the technique to a faint ghost of the next line: you dothe thinking, which is what makes it stick.- **Feedback on your own work.** The first real mistake circled where you made it, correct lines ticked, later lines- that inherit the mistake underlined.+ that inherit the mistake underlined. The marks stay while you keep writing; Esc clears them.- **Practice that makes you recall.** Questions on your key steps (answer by typing or by writing), find-the-errordrills, "which technique fits?".- **See it.** Box what you want to understand and get an interactive animation made with 3Blue1Brown's own[manim](https://github.com/3b1b/manim): drag the bounds, retype a value, watch Riemann sums close in.- **Whole page aware.** A small xournal++ plugin shares the page you are on, not just what fits on screen.+## Works with Claude Code, Codex and Antigravity++penmentor runs on the AI command-line agent you already use, on that subscription. Pick the model in *Settings*; its+prefix says which agent answers:++| Prefix | Agent | For example |+|---|---|---|+| `claude:` | [Claude Code](https://claude.com/claude-code) | `claude:opus`, `claude:sonnet`, `claude:haiku` |+| `codex:` | [Codex](https://github.com/openai/codex) | `codex:gpt-5.6-terra` |+| `agy:` | Antigravity CLI | `agy:gemini-4-argon-medium`, `agy:gemini-3.8-flash-medium` |++Settings lists the agents you have installed. How each one is run and what it sees: [the guide](docs/guide.md#how-it-works-and-what-leaves-your-computer).+## Quick start```sh@@ -34,8 +47,8 @@ git clone https://github.com/AbdullahAlhariri/penmentor ~/src/penmentor~/src/penmentor/bin/penmentor --selftest```-Linux on X11 (best with i3), with [Claude Code](https://claude.com/claude-code) logged in, `rofi`, `slop`, `xdotool`-and PyQt6. Bind `bin/penmentor` to a key ([example](contrib/i3.conf)). Setup, keys and how it works: [the guide](docs/guide.md).+Linux on X11 (best with i3), with one of those agents logged in (`claude`, `codex` or `agy`), plus `rofi`, `slop`,+`xdotool` and PyQt6. Bind `bin/penmentor` to a key ([example](contrib/i3.conf)). Setup, keys and how it works: [the guide](docs/guide.md).## Licensediff --git a/docs/guide.md b/docs/guide.mdindex e9a7c76..2ce0f0e 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -1,6 +1,6 @@# penmentor: the full guide-Press a key while you work through maths by hand, and Claude answers by drawing on your screen, the way a teacher+Press a key while you work through maths by hand, and an AI model (Claude, Gemini or GPT) answers by drawing on your screen, the way a teachermarks work with coloured pens: rings round the mistake, ticks on the right lines, a faint ghost of the next step,arrows from cause to effect. Words are a last resort.@@ -14,41 +14,56 @@ but it reads whatever maths is on screen.| Did I make any mistakes? | the first real error circled with its fix, later lines that inherit it underlined, correct lines ticked || Solution check | is the final answer right, and is anything missing (+C, bounds, absolute values…)? || Give me a hint | the smallest nudge: one thing highlighted, the next step not given away |-| Which technique? | the features that point to a method are coloured, no method named; you pick one (`p`) and Claude says whether it fits |+| Which technique? | the features that point to a method are coloured, no method named; you pick one (`p`) and it says whether it fits || Quiz me on my steps | a question at the 1 or 2 steps that matter most; answer by typing (`a`) or by writing on the page (`w`) || Find-the-error drill | a new worked problem like yours with one planted mistake; tap the wrong line || Show me (animation) | box what you want to see (one box or several), then get an animation of it made with 3Blue1Brown's own [manim](https://github.com/3b1b/manim), on the other monitor, that you can play with: Riemann sums, areas, improper integrals, substitution as a stretch of the axis, solids of revolution, series, Taylor polynomials, polar and parametric curves || Ask about a box | drag a box round something and ask about just that |-In the answer overlay:+The marks stay on your live screen: keep writing, scroll, move windows, they stay until you press **Esc**. Only+the marks themselves catch the pen (tap one to pin its "why"); everywhere else it goes to your app. Their bar of+buttons, bottom right (tap with the pen; pressing the penmentor key again opens the same as a menu):-| Key | |+| Button | ||---|---|-| `h` | more help, one rung up the ladder: nudge → name the technique → ghost the next line → full fix |-| `?` | a follow-up question |-| `g` | show me: box what to animate, then watch it |-| `w` | step aside so you can write more; tap the badge at the top (or press an penmentor key) when done and it checks the new part |-| `t` / `s` | what Claude read / model, tokens and plan usage |-| `r` | replay the marks |-| `Esc` | stop penmentor, wherever you are: in a menu, while Claude is still thinking (Claude stops too), or while you write |+| check new work | write more, then tap it: the model checks what you added |+| more help | one rung up the ladder: nudge → name the technique → ghost the next line → full fix |+| ask… | a follow-up question |+| show me | box what to animate, then watch it |+| what I read / stats | what the model read / harness and model, tokens, plan usage (Claude Code) |+| replay | the marks again |+| close · esc | **Esc** stops penmentor wherever you are: in a menu, while the model thinks (it stops too), or with the marks up |++A tablet pad button (`penmentor --ask check`) while the marks are up checks the work as it is now.Show me starts on the frozen screen: drag boxes round what to animate (right-click takes one back), then tap the badge-or press Enter. The window opens straight away (a loading animation runs while Claude thinks) and stays until you+or press Enter. The window opens straight away (a loading animation runs while the model thinks) and stays until youpress `q` in it (Esc leaves it open). Drag in it to move the bound, the number of rectangles, the degree, the point on thecurve (or turn a 3D solid); where curves cross, and where the bounds x = a and x = b meet them, is marked withits coordinates. Change the maths in place: click a value in the row at the bottom (the function, a, b, n) and type anew one, or drag a bound line; it redraws at once (and goes in the history). Scroll to zoom, arrows to step, space to replay. Every animation is kept: *Settings →-history* plays an old one again, without asking Claude.+history* plays an old one again, without asking the model.-Hover or tap a mark for its one-line "why". Questions build on each other (one Claude conversation) until you pick-*Clear context*; turn that off in *Settings*, where you also choose the model and effort.+Hover or tap a mark for its one-line "why". Questions build on each other (one conversation) until you pick+*Clear context*; turn that off in *Settings*, where you also choose the model (see below) and effort.## How it works, and what leaves your computer-A screenshot of every monitor, plus (with the xournal++ plugin) the whole current page of your notes, goes to Claude-through the [Claude Code](https://claude.com/claude-code) CLI (`claude -p`), so it runs on your Claude subscription.-Claude answers in JSON (what it read, a verdict, marks with boxes); penmentor snaps the boxes onto your ink and draws them-on a frozen copy of the screen. Nothing else is sent and nothing runs in the background between questions.+A screenshot of every monitor, plus (with the xournal++ plugin) the whole current page of your notes, goes to the+model you picked in *Settings*, through its company's command-line agent, so it runs on a subscription you already+have. Models are written `harness:model`; the prefix says which agent runs it:++| Prefix | Agent | How it runs |+|---|---|---|+| `claude:` | [Claude Code](https://claude.com/claude-code) (`claude -p`) | images inline; no tools, no MCP servers |+| `agy:` | Antigravity (`agy --print`) | it reads the images as files, in its sandbox, told to use only its file viewer |+| `codex:` | [Codex](https://github.com/openai/codex) (`codex exec`) | images attached; read-only sandbox, your Codex config and rules ignored |++*Settings* lists the models of the agents you have installed. Any other name the agent accepts works too: put+`"model": "codex:gpt-5.6-terra"` in `~/.config/penmentor/settings.json`. Switching agent starts a new conversation.++The model answers in JSON (what it read, a verdict, marks with boxes); penmentor snaps the boxes onto your ink and draws them+on top of your live screen. Nothing else is sent and nothing runs in the background between questions.## Install@@ -59,7 +74,7 @@ sudo pacman -S python-pyqt6 python-numpy python-scipy python-pillow python-matplsudo pacman -S texlive-latex texlive-latexextra texlive-fontsextra # optional: real LaTeX and the CMU fonts```-Install [Claude Code](https://claude.com/claude-code) and log in once (`claude`). Then:+Install one of the agents above (`claude`, `agy` or `codex`) and log in once by running it. Then:```shgit clone <this repo> ~/src/penmentor@@ -68,7 +83,7 @@ git clone <this repo> ~/src/penmentorBind a key: see [contrib/i3.conf](../contrib/i3.conf) (or `pip install .` and bind `penmentor`).-**xournal++ plugin** (so Claude also sees the parts of the page that are scrolled away, and your unsaved strokes):+**xournal++ plugin** (so the model also sees the parts of the page that are scrolled away, and your unsaved strokes):```shln -s ~/src/penmentor/xournalpp-plugin/penmentor ~/.config/xournalpp/plugins/penmentor@@ -91,9 +106,9 @@ uv pip install -p ~/.local/share/penmentor/manim/bin/python manimgl audioop-lts## Development```sh-bin/penmentor --selftest # page analysis, text, formulas, plots, drill logic; no Claude, no screen-bin/penmentor --test shot.png check # ask Claude about a saved screenshot: shot.penmentor.json and shot.penmentor.png-bin/penmentor --render shot.png shot.penmentor.json # redraw a saved answer without Claude (tune the visuals)+bin/penmentor --selftest # page analysis, text, formulas, plots, drill logic; no model, no screen+bin/penmentor --test shot.png check # ask your model about a saved screenshot: shot.penmentor.json and shot.penmentor.png+bin/penmentor --render shot.png shot.penmentor.json # redraw a saved answer without the model (tune the visuals)PYTHONPATH=src ~/.local/share/penmentor/manim/bin/python -m penmentor.plot --png spec.json out.png # one animation's last frame~/.local/share/penmentor/manim/bin/python docs/assets.py # the README's banner```@@ -101,10 +116,10 @@ PYTHONPATH=src ~/.local/share/penmentor/manim/bin/python -m penmentor.plot --png| Module | ||---|---|| `cli.py` | entry point: capture, menu, settings |-| `prompts.py` | everything Claude is told, and the JSON schema it answers in |-| `claude.py` | the `claude -p` call, sessions, token and usage stats |+| `prompts.py` | everything the model is told, and the JSON schema it answers in |+| `harness.py` | the `claude`, `agy` and `codex` calls, sessions, token and usage stats || `desktop.py`, `xournal.py` | screenshots, monitors, i3 windows, rofi; the whole-page export || `page.py` | where the ink is: snapping boxes onto strokes, finding empty space |-| `overlay.py`, `draw.py`, `style.py` | the frozen frame, the marks, the modes |+| `overlay.py`, `draw.py`, `style.py` | the marks over your live screen (a shaped window), the modes || `typeset.py` | LaTeX (or mathtext) into images |-| `plot.py`, `show.py`, `expr.py` | Show me: the manim scenes (run by manim's Python), opening their window and its history, and a safe evaluator for Claude's formulas |+| `plot.py`, `show.py`, `expr.py` | Show me: the manim scenes (run by manim's Python), opening their window and its history, and a safe evaluator for the model's formulas |diff --git a/src/penmentor/__init__.py b/src/penmentor/__init__.pyindex f28d6f2..7c7df87 100644--- a/src/penmentor/__init__.py+++ b/src/penmentor/__init__.py@@ -1,4 +1,4 @@-"""penmentor: press a key, ask Claude about the maths on your screen, and see the answer drawn on it."""+"""penmentor: press a key, ask an AI model about the maths on your screen, and see the answer drawn on it."""import osos.environ.setdefault('QT_ENABLE_HIGHDPI_SCALING', '0') # 1 Qt pixel == 1 screen pixel; set before anything imports Qtdiff --git a/src/penmentor/claude.py b/src/penmentor/claude.pydeleted file mode 100644index 5b9f7a0..0000000--- a/src/penmentor/claude.py+++ /dev/null@@ -1,108 +0,0 @@-"""Asking Claude through the Claude Code CLI (`claude -p`), so it runs on your Claude subscription."""-import atexit-import base64-import io-import json-import shutil-import subprocess-import time-import uuid-from pathlib import Path--from PIL import Image, ImageDraw, ImageFont--from .config import CACHE, CONF, SESSION-from .prompts import SCHEMA, SYSTEM--CLAUDE = shutil.which('claude') or str(Path.home() / '.local/bin/claude') # i3's PATH may lack ~/.local/bin-SEND_EDGE = 1568 # long edge of the image Claude sees; its boxes come back in that space---def prepare(shot, boxes=()):- """PNG bytes Claude sees (your boxes drawn on in cyan: [(number or None, (x0, y0, x1, y1))]; shrunk) and its size."""- img = shot.copy()- draw = ImageDraw.Draw(img)- for n, box in boxes:- draw.rectangle(box, outline=(0, 220, 255), width=4)- if n:- draw.text((box[0] + 8, box[1] + 4), str(n), fill=(0, 220, 255), font=ImageFont.load_default(30))- s = min(1, SEND_EDGE / max(img.size))- if s < 1:- img = img.resize((round(img.width * s), round(img.height * s)), Image.LANCZOS)- buf = io.BytesIO()- img.save(buf, 'PNG')- return buf.getvalue(), img.size---def session():- try:- return json.loads(SESSION.read_text())- except (OSError, ValueError):- return None---RUNNING = set() # claude processes still answering---def stop():- """Kill Claude mid-answer: Esc, or penmentor quitting for any reason, must not leave it running on your plan."""- for p in list(RUNNING):- p.kill()---def image(png):- return {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': base64.b64encode(png).decode()}}---def ask(shots, text, main=0, new_shot=True, keep=True, page=None):- """shots: [(png, (w, h))] per monitor, left to right; main: the focused one; page: (png, label) of the whole xournal page.- new_shot=False: a follow-up on the screenshots Claude already has. keep=False: no shared context (offline tests)."""- content = [{'type': 'text', 'text': text}]- if new_shot:- content = []- for i, (png, (w, h)) in enumerate(shots):- content += [{'type': 'text', 'text': f'Screen {i}' + (' (focused)' if i == main else '') + f': {w}x{h} px'}, image(png)]- if page:- content += [{'type': 'text', 'text': f'The whole {page[1]} of the xournal notes, for context only (no marks on it):'},- image(prepare(Image.open(io.BytesIO(page[0])).convert('RGB'))[0])]- content.append({'type': 'text', 'text': 'Give every box in its own screen\'s pixels.\n\n' + text})- msg = {'type': 'user', 'message': {'role': 'user', 'content': content}}- s = session() if keep else None- sid = s['id'] if s else str(uuid.uuid4())- # isolated from your own Claude Code setup: no tools, hooks, plugins or MCP servers- cmd = [CLAUDE, '-p', '--restricted', '--strict-mcp-config', '--tools', '', '--disable-slash-commands',- *(['--resume', sid] if s else ['--session-id', sid] if keep else ['--no-session-persistence']),- '--model', CONF['model'], '--effort', CONF['effort'], '--system-prompt', SYSTEM,- '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',- '--json-schema', json.dumps(SCHEMA)]- CACHE.mkdir(parents=True, exist_ok=True)- t = time.monotonic()- with subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=CACHE) as p:- RUNNING.add(p)- try:- out, err = p.communicate(json.dumps(msg), timeout=300)- finally:- p.kill() # only does something on a timeout or when penmentor stops- RUNNING.discard(p)- for line in reversed(out.splitlines()):- try:- e = json.loads(line)- except ValueError:- continue- if e.get('type') == 'result':- if e.get('is_error') or 'structured_output' not in e:- raise RuntimeError(str(e.get('result') or e.get('subtype')))- if keep:- SESSION.write_text(json.dumps({'id': sid}))- u = e.get('usage') or {} # this question only; modelUsage adds up the whole session, every model in it- spent = sum(u.get(k, 0) for k in ('input_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens', 'output_tokens'))- total = sum(m.get(k, 0) for m in (e.get('modelUsage') or {}).values()- for k in ('inputTokens', 'cacheCreationInputTokens', 'cacheReadInputTokens', 'outputTokens'))- lim = [json.loads(l)['rate_limit_info'] for l in out.splitlines() if '"rate_limit_event"' in l]- return dict(e['structured_output'], _secs=round(time.monotonic() - t, 1), _tokens=[spent, u.get('cache_read_input_tokens', 0), total],- _limits=lim[-1].get('unifiedWindows', {}) if lim else {}) # plan usage: 5-hour and weekly- if s and 'No conversation found' in err: # Claude Code pruned the old session: start a new one, screenshots included- SESSION.unlink()- return ask(shots, text, main, True, keep, page)- raise RuntimeError(err.strip()[-300:] or 'no answer from claude')diff --git a/src/penmentor/cli.py b/src/penmentor/cli.pyindex f31e13a..734a9e4 100644--- a/src/penmentor/cli.py+++ b/src/penmentor/cli.py@@ -1,14 +1,15 @@-"""penmentor: press a key, ask about the maths on screen, Claude draws the answer on it.+"""penmentor: press a key, ask about the maths on screen, the model draws the answer on it.penmentor screenshot every monitor, rofi question, overlaypenmentor --last show the last answer againpenmentor --ask MODE skip the menu (for pen-tablet buttons); MODE is one of the presets in prompts.py- penmentor --test IMG [MODE|"question"] offline: ask Claude about IMG, writes IMG.penmentor.{json,png}- penmentor --render IMG JSON offline: redraw a saved answer (tune visuals without Claude)+ penmentor --test IMG [MODE|"question"] offline: ask the model about IMG, writes IMG.penmentor.{json,png}+ penmentor --render IMG JSON offline: redraw a saved answer (tune visuals without the model)penmentor --selftest-Overlay keys: h more help, ? follow-up, g show me (box what to animate), w write more, t what Claude read, s stats, r replay.-Esc stops penmentor at any point, Claude included.+The marks stay over your live screen while you keep writing; tap the buttons on their bar (or press the penmentor+key again for the same as a menu): check new work, more help, ask, show me, what I read, stats, replay.+Esc stops penmentor at any point, the model included.Hover or tap a mark for its one-line "why"."""import faulthandler@@ -21,7 +22,7 @@ import timeimport tracebackfrom pathlib import Path-from . import claude, show, xournal+from . import harness, show, xournalfrom .config import CACHE, CHOICES, CONF, SESSION, STATE, save, set_statefrom .desktop import Oops, capture, notify, on_escape, rofi, select_regionfrom .prompts import BOX_QS, PRESETS, TASKS@@ -29,25 +30,42 @@ from .prompts import BOX_QS, PRESETS, TASKSSETTINGS_ROW, CLEAR_ROW, HISTORY_ROW = '⚙ Settings', '✕ Clear context', 'history'+def model_choices():+ """The models of the harnesses you have installed, and the one you use now even if it is not listed."""+ have = harness.installed()+ out = [(a, n) for a, n in CHOICES['model'] if harness.pick(a)[0] in have]+ return out if any(a == CONF['model'] for a, _ in out) else [(CONF['model'], '(yours)')] + out+++def label(key, value):+ """A settings row's value: models show their harness first ("codex gpt-5.6-terra"), the rest as they are."""+ if key != 'model':+ return f'{value:<8}'+ h, m = harness.pick(value)+ return f'{h:<7}{m:<28}'++def settings(reopen):"""Pick model / effort / context until Esc; each pick is saved at once. History: reopen(spec) an old animation."""- while c := rofi([f'{k:<8}{CONF[k]}' for k in CHOICES] + [HISTORY_ROW], 'settings'):+ shown = lambda k: ':'.join(harness.pick(CONF[k])) if k == 'model' else CONF[k] # the model with its harness, always+ while c := rofi([f'{k:<8}{shown(k)}' for k in CHOICES] + [HISTORY_ROW], 'settings'):if c == HISTORY_ROW:return past_animations(reopen)key = c.split()[0]if key not in CHOICES:continue- rows = [f'{"●" if a == CONF[key] else "○"} {a:<8}{name}' for a, name in CHOICES[key]]- free = key == 'model' # any full model id works; a mistyped effort would only break the next ask+ choices = model_choices() if key == 'model' else CHOICES[key]+ rows = [f'{"●" if a == CONF[key] else "○"} {label(key, a)}{name}' for a, name in choices]+ free = key == 'model' # any model id works, typed as harness:model; a mistyped effort would only break the next askif (v := rofi(rows, key)) is None:return- v = dict(zip(rows, (a for a, _ in CHOICES[key]))).get(v, v if free else None)+ v = dict(zip(rows, (a for a, _ in choices))).get(v, v if free else None)if v:save(**{key: v})def past_animations(reopen):- """Every Show-me animation, newest first; the one you pick plays again (no Claude needed)."""+ """Every Show-me animation, newest first; the one you pick plays again (no model needed)."""from .typeset import plainpast = show.history()rows = [f'{time.strftime("%d %b %H:%M", time.localtime(h["t"]))} {plain(h["spec"].get("title") or h["spec"].get("kind", "?"))}'@@ -58,11 +76,13 @@ def past_animations(reopen):reopen(past[rows.index(pick)]['spec'])-def nudge_running():- """Another penmentor holds the lock. If it is waiting for you to finish writing, this key press means done."""+def nudge_running(what='menu'):+ """Another penmentor holds the lock. If its marks are up, this key press opens their menu ('menu'), or a pad+ button asks its question about the work on screen (a preset mode)."""try:state = STATE.read_text().split()- if state[0] == 'waiting' and b'penmentor' in Path(f'/proc/{int(state[1])}/cmdline').read_bytes():+ if state[0] == 'open' and b'penmentor' in Path(f'/proc/{int(state[1])}/cmdline').read_bytes():+ (CACHE / 'poke').write_text(what)return os.kill(int(state[1]), signal.SIGUSR1)except (OSError, ValueError, IndexError):pass@@ -96,13 +116,14 @@ def show_last():d.get('wins'), d.get('mode', 'check'))ov.set_result(d['result'])ov.present()+ on_escape(lambda: os._exit(0)) # the marks stay over your live screen until Escwatchdog(app)app.exec()def offline(a):from PIL import Image- from .claude import ask+ from .harness import askos.environ['QT_QPA_PLATFORM'] = 'offscreen'img = Path(a[1])shot = Image.open(img).convert('RGB')@@ -133,13 +154,13 @@ def main(a):try:fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)except BlockingIOError:- return nudge_running()+ return nudge_running(a[1] if a[:1] == ['--ask'] and a[1:2] else 'menu')set_state('busy')if a[:1] == ['--last']:return show_last()shot, screens, main_screen, wins = capture() # before rofi draws over the screenpage = xournal.PageRequest() # now, while the keyboard still goes to xournal- on_escape(lambda: (claude.stop(), os._exit(0))) # Esc anywhere stops penmentor, even while Claude thinks+ on_escape(lambda: (harness.stop(), os._exit(0))) # Esc anywhere stops penmentor, even while the model thinksgeom = (0, 0, *shot.size)on = CONF['context'] == 'on'if a[:1] == ['--ask']: # a tablet button: straight to the questiondiff --git a/src/penmentor/config.py b/src/penmentor/config.pyindex c0b3092..7faa358 100644--- a/src/penmentor/config.py+++ b/src/penmentor/config.py@@ -5,17 +5,20 @@ from pathlib import PathCACHE = Path(os.environ.get('XDG_CACHE_HOME') or Path.home() / '.cache') / 'penmentor'SETTINGS = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'penmentor' / 'settings.json'-SESSION = CACHE / 'session.json' # the Claude conversation every question builds on, until Clear context+SESSION = CACHE / 'session.json' # the conversation every question builds on (and its harness), until Clear contextDATA = Path(os.environ.get('XDG_DATA_HOME') or Path.home() / '.local/share') / 'penmentor' # kept: Show-me history, manimMANIM = DATA / 'manim' / 'bin' / 'python' # a venv with manimgl (README), for Show meSTATE = CACHE / 'state' # 'busy', or 'waiting <pid>' while penmentor waits for you to write; read by a second penmentor-CHOICES = { # claude --model aliases, --effort levels, shared context- 'model': [('opus', 'Opus 5.5'), ('sonnet', 'Sonnet 5.5'), ('haiku', 'Haiku 5.5'), ('fable', 'Fable 5.1')],+CHOICES = { # models as harness:model (which command-line agent runs it; see harness.py), effort levels, shared context+ 'model': [('claude:opus', 'Opus 5.5'), ('claude:sonnet', 'Sonnet 5.5'), ('claude:haiku', 'Haiku 5.5'), ('claude:fable', 'Fable 5.1'),+ ('agy:gemini-4-argon-medium', 'Gemini 4 Argon'), ('agy:gemini-3.8-flash-medium', 'Gemini 3.8 Flash'),+ ('agy:claude-opus-5-5-medium', 'Claude Opus 5.5 through Antigravity'),+ ('codex:gpt-5.6-terra', 'GPT-5.6 Terra')],'effort': [('low', 'fastest'), ('medium', 'balanced'), ('high', 'more careful'), ('xhigh', 'slower'), ('max', 'slowest, most careful')],'context': [('on', 'each question builds on the earlier ones'), ('off', 'each question starts fresh')],}-CONF = {'model': 'opus', 'effort': 'medium', 'context': 'on', 'stats': False, 'read': False} # stats/read: s and t panels, kept on between questions+CONF = {'model': 'claude:opus', 'effort': 'medium', 'context': 'on', 'stats': False, 'read': False} # stats/read: s and t panels, kept on between questionstry:CONF |= json.loads(SETTINGS.read_text())except (OSError, ValueError):diff --git a/src/penmentor/desktop.py b/src/penmentor/desktop.pyindex 577e139..081f672 100644--- a/src/penmentor/desktop.py+++ b/src/penmentor/desktop.py@@ -88,6 +88,32 @@ def activate(window):subprocess.run(['xdotool', 'windowactivate', window], capture_output=True)+_pointer = {}+++def pointer():+ """(x, y, held) of the mouse or pen anywhere on the desktop (held: a button or the pen tip is down), or None.+ The marks' window is only their own pixels, so the pointer is mostly over your app: this asks X directly."""+ if 'x' not in _pointer:+ try:+ x = ctypes.CDLL('libX11.so.6')+ except OSError:+ return None+ x.XOpenDisplay.restype, x.XDefaultRootWindow.restype = ctypes.c_void_p, ctypes.c_ulong+ x.XDefaultRootWindow.argtypes = [ctypes.c_void_p]+ P, I = ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_int)+ x.XQueryPointer.argtypes = [ctypes.c_void_p, ctypes.c_ulong, P, P, I, I, I, I, ctypes.POINTER(ctypes.c_uint)]+ dpy = x.XOpenDisplay(None)+ _pointer.update(x=x, dpy=dpy, root=dpy and x.XDefaultRootWindow(dpy))+ x, dpy = _pointer['x'], _pointer['dpy']+ if not dpy:+ return None+ w, i, m = [ctypes.c_ulong() for _ in range(2)], [ctypes.c_int() for _ in range(4)], ctypes.c_uint()+ if not x.XQueryPointer(dpy, _pointer['root'], *map(ctypes.byref, w), *map(ctypes.byref, i), ctypes.byref(m)):+ return None+ return i[0].value, i[1].value, bool(m.value & 0x1F00) # Button1Mask..Button5Mask++def on_escape(callback):"""callback() on a thread whenever Escape is pressed, wherever the focus is (other keys still reach your apps),so Esc stops penmentor while Claude thinks. Windows that grab the keyboard (rofi, the overlay) get their Esc themselves."""diff --git a/src/penmentor/harness.py b/src/penmentor/harness.pynew file mode 100644index 0000000..029d4fb--- /dev/null+++ b/src/penmentor/harness.py@@ -0,0 +1,241 @@+"""Asking the model you picked in Settings, through its own command-line agent, on your own subscription.++The model setting says which harness runs it: "claude:opus" (Claude Code), "agy:gemini-4-argon-medium" (Antigravity),+"codex:gpt-5.6-terra" (Codex). A bare name ("opus") is Claude Code's. Each gets the same screenshots, the same+instructions and the same JSON schema, and answers in the same shape.+"""+import atexit+import base64+import io+import json+import os+import shutil+import subprocess+import time+import uuid+from pathlib import Path++from PIL import Image, ImageDraw, ImageFont++from .config import CACHE, CONF, SESSION+from .prompts import SCHEMA, SYSTEM++HARNESSES = {'claude': 'Claude Code', 'agy': 'Antigravity', 'codex': 'Codex'}+BIN = {h: shutil.which(h) or str(Path.home() / '.local/bin' / h) for h in HARNESSES} # i3's PATH may lack ~/.local/bin+SEND_EDGE = 1568 # long edge of the images the model sees; its boxes come back in that space+TURN = CACHE / 'turn' # the screenshots as files, for the harnesses that take images as files+VIEW_ONLY = ('Open these image files with your file viewer, in this order, and use only the file viewer: run no commands '+ 'and use no other tools. Everything you need is in the images and this message.')+++def pick(model=None):+ """(harness, model) for a model setting: "codex:gpt-5.6-terra" -> ('codex', 'gpt-5.6-terra'), "opus" -> ('claude', 'opus')."""+ m = model or CONF['model']+ h, sep, name = m.partition(':')+ return (h, name) if sep and h in HARNESSES else ('claude', m)+++def installed():+ return [h for h in HARNESSES if os.access(BIN[h], os.X_OK)]+++def prepare(shot, boxes=()):+ """PNG bytes the model sees (your boxes drawn on in cyan: [(number or None, (x0, y0, x1, y1))]; shrunk) and its size."""+ img = shot.copy()+ draw = ImageDraw.Draw(img)+ for n, box in boxes:+ draw.rectangle(box, outline=(0, 220, 255), width=4)+ if n:+ draw.text((box[0] + 8, box[1] + 4), str(n), fill=(0, 220, 255), font=ImageFont.load_default(30))+ s = min(1, SEND_EDGE / max(img.size))+ if s < 1:+ img = img.resize((round(img.width * s), round(img.height * s)), Image.LANCZOS)+ buf = io.BytesIO()+ img.save(buf, 'PNG')+ return buf.getvalue(), img.size+++def session():+ try:+ return json.loads(SESSION.read_text())+ except (OSError, ValueError):+ return None+++RUNNING = set() # harness processes still answering+++def stop():+ """Kill the model mid-answer: Esc, or penmentor quitting for any reason, must not leave it running on your plan."""+ for p in list(RUNNING):+ p.kill()+++def run(cmd, stdin, cwd):+ with subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=cwd) as p:+ RUNNING.add(p)+ try:+ return p.communicate(stdin, timeout=300)+ finally:+ p.kill() # only does something on a timeout or when penmentor stops+ RUNNING.discard(p)+++def events(out):+ for line in out.splitlines():+ try:+ yield json.loads(line)+ except ValueError:+ pass+++def strict(s):+ """OpenAI's strict JSON schema (Codex insists): every key required, the optional ones allowed to be null."""+ if isinstance(s, list):+ return [strict(v) for v in s]+ if not isinstance(s, dict):+ return s+ out = {k: (v if k in ('properties', 'required', 'enum') else strict(v)) for k, v in s.items()}+ if 'properties' in out:+ need = set(s.get('required', []))+ out['properties'] = {k: strict(v) if k in need else {'anyOf': [strict(v), {'type': 'null'}]} for k, v in s['properties'].items()}+ out['required'] = list(out['properties'])+ return out+++def unnull(x):+ """Back from strict: the nulls go, so the answer looks the same whichever model gave it."""+ if isinstance(x, dict):+ return {k: unnull(v) for k, v in x.items() if v is not None}+ return [unnull(v) for v in x] if isinstance(x, list) else x+++def files(parts):+ """The images as files in TURN, in order: [(path, (w, h))]."""+ shutil.rmtree(TURN, ignore_errors=True)+ TURN.mkdir(parents=True)+ out = []+ for i, (png, size) in enumerate(p for kind, p in parts if kind == 'image'):+ path = TURN / f'image{i + 1}.png'+ path.write_bytes(png)+ out.append((path, size))+ return out+++def as_text(parts, names):+ """The message as one text, each image replaced by the name it goes by."""+ it = iter(names)+ return '\n'.join(p if kind == 'text' else f'[{next(it)}]' for kind, p in parts)+++# ---------- the harnesses: (parts, model, resume id or None, keep) -> (answer, session id, tokens, plan limits) ----------++def claude(parts, model, sid, keep):+ content = [{'type': 'text', 'text': p} if kind == 'text' else+ {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': base64.b64encode(p[0]).decode()}}+ for kind, p in parts]+ new = sid or str(uuid.uuid4())+ # isolated from your own Claude Code setup: no tools, hooks, plugins or MCP servers+ cmd = [BIN['claude'], '-p', '--restricted', '--strict-mcp-config', '--tools', '', '--disable-slash-commands',+ *(['--resume', sid] if sid else ['--session-id', new] if keep else ['--no-session-persistence']),+ '--model', model, '--effort', CONF['effort'], '--system-prompt', SYSTEM,+ '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--json-schema', json.dumps(SCHEMA)]+ out, err = run(cmd, json.dumps({'type': 'user', 'message': {'role': 'user', 'content': content}}), CACHE)+ for e in reversed(list(events(out))):+ if e.get('type') == 'result':+ if e.get('is_error') or 'structured_output' not in e:+ raise RuntimeError(str(e.get('result') or e.get('subtype')))+ u = e.get('usage') or {} # this question only; modelUsage adds up the whole session, every model in it+ spent = sum(u.get(k, 0) for k in ('input_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens', 'output_tokens'))+ total = sum(m.get(k, 0) for m in (e.get('modelUsage') or {}).values()+ for k in ('inputTokens', 'cacheCreationInputTokens', 'cacheReadInputTokens', 'outputTokens'))+ lim = [l['rate_limit_info'] for l in events(out) if l.get('type') == 'rate_limit_event']+ return e['structured_output'], new, [spent, u.get('cache_read_input_tokens', 0), total], \+ lim[-1].get('unifiedWindows', {}) if lim else {} # plan usage: 5-hour and weekly+ raise RuntimeError(err.strip()[-300:] or 'no answer from claude')+++def agy(parts, model, sid, keep):+ """Antigravity's print mode takes text only: the screenshots are files its agent opens with its viewer. Headless,+ it can't be granted commands (they are denied), and its terminal is sandboxed."""+ imgs = files(parts)+ names = [f'{p.name}, {w}x{h} px' for p, (w, h) in imgs]+ text = (SYSTEM + '\n\n' if not sid else '') + (f'{VIEW_ONLY}\n' + '\n'.join(map(str, (p for p, _ in imgs))) + '\n\n' if imgs else '')+ effort = [] if model.rsplit('-', 1)[-1] in ('low', 'medium', 'high') else ['--effort', CONF['effort']] # the name may say it+ cmd = [BIN['agy'], '--model', model, *effort, '--sandbox', '--disable-slash-commands', *(['--conversation', sid] if sid else []),+ '--input-format', 'stream-json', '--output-format', 'stream-json', '--json-schema', json.dumps(SCHEMA), '--print=']+ out, err = run(cmd, json.dumps({'event': 'user', 'message': {'content': text + as_text(parts, names)}}), TURN if imgs else CACHE)+ for e in reversed(list(events(out))):+ if e.get('event') == 'result':+ r = e['result']+ if r.get('status') != 'SUCCESS' or not isinstance(r.get('structured_output'), dict):+ raise RuntimeError(r.get('error') or err.strip()[-300:] or 'no answer from agy')+ u = r.get('usage') or {}+ return r['structured_output'], r.get('conversation_id'), [u.get('total_tokens', 0), u.get('cache_read_tokens', 0)], {}+ raise RuntimeError(err.strip()[-300:] or 'no answer from agy')+++def codex(parts, model, sid, keep):+ """Codex attaches the screenshots itself; its schema must be strict. Read-only sandbox, none of your codex config."""+ imgs = files(parts)+ names = [f'attached image {i + 1}, {w}x{h} px' for i, (_, (w, h)) in enumerate(imgs)]+ schema = TURN / 'schema.json' if imgs else CACHE / 'schema.json'+ schema.parent.mkdir(parents=True, exist_ok=True)+ schema.write_text(json.dumps(strict(SCHEMA)))+ effort = {'max': 'xhigh'}.get(CONF['effort'], CONF['effort'])+ cmd = [BIN['codex'], 'exec', *(['resume', sid] if sid else []), '--skip-git-repo-check', '--json',+ *([] if sid else ['--sandbox', 'read-only']), '--ignore-rules', '--ignore-user-config', *([] if keep else ['--ephemeral']),+ '-m', model, '-c', f'model_reasoning_effort="{effort}"', '--output-schema', str(schema),+ *[f'--image={p}' for p, _ in imgs], '-']+ text = (SYSTEM + '\n\n' if not sid else '') + 'Use no tools: everything you need is in the images and this message.\n\n'+ out, err = run(cmd, text + as_text(parts, names), schema.parent)+ thread, answer, usage = sid, None, {}+ for e in events(out):+ if e.get('type') == 'thread.started':+ thread = e.get('thread_id')+ elif e.get('type') == 'item.completed' and (e.get('item') or {}).get('type') == 'agent_message':+ answer = e['item'].get('text')+ elif e.get('type') == 'turn.completed':+ usage = e.get('usage') or {}+ elif e.get('type') in ('error', 'turn.failed'):+ raise RuntimeError(str(e.get('message') or e.get('error'))[-300:])+ try:+ answer = unnull(json.loads(answer))+ except (TypeError, ValueError):+ raise RuntimeError(err.strip()[-300:] or 'no answer from codex')+ spent = sum(usage.get(k, 0) for k in ('input_tokens', 'output_tokens', 'reasoning_output_tokens'))+ return answer, thread, [spent, usage.get('cached_input_tokens', 0)], {}+++RUN = {'claude': claude, 'agy': agy, 'codex': codex}+++def ask(shots, text, main=0, new_shot=True, keep=True, page=None):+ """shots: [(png, (w, h))] per monitor, left to right; main: the focused one; page: (png, label) of the whole xournal page.+ new_shot=False: a follow-up on the screenshots the model already has. keep=False: no shared context (offline tests)."""+ h, model = pick()+ s = session() if keep else None+ sid = s['id'] if s and s.get('harness', 'claude') == h else None # another harness can't pick up this conversation+ new_shot = new_shot or not sid+ parts = [('text', text)]+ if new_shot:+ parts = []+ for i, shot in enumerate(shots):+ parts += [('text', f'Screen {i}' + (' (focused)' if i == main else '') + f': {shot[1][0]}x{shot[1][1]} px'), ('image', shot)]+ if page:+ parts += [('text', f'The whole {page[1]} of the xournal notes, for context only (no marks on it):'),+ ('image', prepare(Image.open(io.BytesIO(page[0])).convert('RGB')))]+ parts.append(('text', 'Give every box in its own screen\'s pixels.\n\n' + text))+ CACHE.mkdir(parents=True, exist_ok=True)+ t = time.monotonic()+ try:+ answer, new, tokens, limits = RUN[h](parts, model, sid, keep)+ except RuntimeError:+ if not sid:+ raise+ SESSION.unlink(missing_ok=True) # the harness lost that conversation: start a new one, screenshots included+ return ask(shots, text, main, True, keep, page)+ if keep and new:+ SESSION.write_text(json.dumps({'harness': h, 'id': new}))+ return dict(answer, _secs=round(time.monotonic() - t, 1), _tokens=tokens, _limits=limits)diff --git a/src/penmentor/overlay.py b/src/penmentor/overlay.pyindex 8f66c18..6e9bb4e 100644--- a/src/penmentor/overlay.py+++ b/src/penmentor/overlay.py@@ -9,13 +9,13 @@ import timeimport numpy as npfrom PyQt6.QtCore import QPointF, QRect, QRectF, Qt, QTimer, pyqtSignal-from PyQt6.QtGui import QColor, QFontMetrics, QImage, QPainter, QPainterPath, QPolygonF, QRegion+from PyQt6.QtGui import QBitmap, QColor, QFontMetrics, QImage, QPainter, QPainterPath, QPolygonF, QRegionfrom PyQt6.QtWidgets import QApplication, QWidgetfrom . import show, xournal-from .claude import ask, prepare+from .harness import ask, pick, preparefrom .config import CACHE, CONF, save, set_state-from .desktop import Oops, activate, active_window, capture, rofi+from .desktop import Oops, activate, active_window, capture, pointer, rofifrom .draw import arrowhead, curve, edge, line_pts, panel, pen, qrect, ring, ring_rect, spin, tupfrom .page import Pagefrom .prompts import FOLLOWUPS, MORE, TASKS, TECHNIQUES@@ -167,12 +167,14 @@ class BoxPicker(QWidget):class Overlay(QWidget):- """Frozen frame: the screenshot plus Claude's marks, over every monitor it came from.- Needs no compositor and can't drift when you scroll; Esc returns to the live apps.+ """Claude's marks over your live screen, on every monitor it looked at. The window is shaped to the marks and+ panels themselves (an X shape: no compositor needed), so everywhere else you see and use your apps: write, scroll,+ move windows, while the marks stay. Only Esc closes it; the bar's buttons (or the penmentor key again) do the rest.geom: where the shot sits on the desktop. screens (monitors) and wins (windows) are (x, y, w, h) in shot pixels;the panels go on screens[main], the focused monitor."""done = pyqtSignal(object)asked = pyqtSignal(object)+ chose = pyqtSignal(object)def __init__(self, shot, geom, region=None, screens=None, main=0, wins=None, mode='check', page=None):# region: your boxes [(x0, y0, x1, y1)] in shot pixels, drawn on what Claude sees@@ -183,15 +185,20 @@ class Overlay(QWidget):self.load(shot, screens, main, wins)self.result, self.items, self.read_imgs, self.head, self.head_box, self.drill = None, [], None, None, None, Noneself.busy, self.error, self.hover, self.pinned = False, None, None, None- self.want_plot, self.pending = mode == 'show', None # pending: what to ask once you are done writing- self.app_window = active_window() # xournal, usually: it gets the focus back when the overlay steps aside+ self.want_plot = mode == 'show'+ self.app_window = active_window() # xournal, usually: it gets the focus back after the box picker had the keyboardself.pill, self.t0, self.end, self.tip_pos, self.pin_pos = None, time.monotonic(), 0, QPointF(0, 0), QPointF(0, 0)self.setGeometry(*geom)self.setMouseTracking(True)self.done.connect(self.on_done)self.asked.connect(self.on_asked)+ self.chose.connect(self.on_chose)self.tips, self.head_img, self.legend = {}, QImage(), None+ self.base, self.bar_items, self.bar_hover = QRegion(), [], None # base: the shape of everything but tooltipsself.tick = QTimer(self, interval=16, timeout=self.update)+ QTimer(self, interval=33, timeout=self.track).start() # hover from where the pointer is; and Python runs often+ # enough that the signal below is heard+ signal.signal(signal.SIGUSR1, lambda *a: QTimer.singleShot(0, self.poked)) # the penmentor key againdef load(self, shot, screens, main, wins):"""Freeze this frame. Its pages and Claude's copies are made from it lazily (the pages on a background thread)."""@@ -249,12 +256,9 @@ class Overlay(QWidget):screen = show.monitor(self.screens, self.main, self.geom)spot = show.rect(screen)show.open_window(spot) # now, so its loading animation runs while Claude thinks- # the frozen frame mustn't cover it: leave its whole monitor live (so you can move it or make it fullscreen);- # with one monitor, just the window and i3's frame round it- hole = QRect(*screen) if len(self.screens) > 1 else QRect(*spot).adjusted(-4, -30, 4, 4)- self.setMask(QRegion(self.rect()).subtracted(QRegion(hole.translated(-self.geom[0], -self.geom[1]))))if self.isVisible():self.tick.start()+ self.reshape() # the headline turns into "Thinking"else:self.pill = Pill(self.shot, self.top_geom())self.pill.show()@@ -275,11 +279,13 @@ class Overlay(QWidget):self.busy = Falseif self.want_plot:self.want_plot = False- show.send(spec=r['plot']) if r.get('plot') else show.send(error=r.get('error') or "Claude didn't send an animation this time.")+ show.send(spec=r['plot']) if r.get('plot') else show.send(error=r.get('error') or 'No animation came with this answer.')if 'error' in r:if self.isVisible():self.error = r['error']+ self.reshape()self.update()+ set_state(f'open {os.getpid()}')else:self.pill.fail(r['error'])return@@ -290,11 +296,35 @@ class Overlay(QWidget):self.set_result(r)if not self.isVisible():self.present()+ set_state(f'open {os.getpid()}') # the penmentor key opens the marks' menu againdef present(self):+ """Show the marks without taking the keyboard: it stays with the app you were writing in."""+ self.reshape()self.show()self.raise_()- QTimer.singleShot(80, lambda: (self.activateWindow(), self.grabKeyboard()))+ set_state(f'open {os.getpid()}')++ def reshape(self):+ """The window becomes exactly what is drawn on it (every mark at its end state, the panels): your live screen+ shows everywhere else and the pen reaches the app below. Pixels with any coverage count, so edges stay smooth."""+ img = QImage(self.size(), QImage.Format.Format_ARGB32)+ img.fill(0)+ p = QPainter(img)+ p.setRenderHint(QPainter.RenderHint.Antialiasing)+ self.paint_layer(p, math.inf, tips=False)+ p.end()+ a = np.frombuffer(img.bits().asarray(img.sizeInBytes()), np.uint8).reshape(img.height(), img.bytesPerLine() // 4, 4)+ a[..., 3] = np.where(a[..., 3] > 0, 255, 0) # createAlphaMask thresholds at half: keep the faint antialiased edge+ self.base = QRegion(QBitmap.fromImage(img.createAlphaMask()))+ self.apply_shape()++ def apply_shape(self):+ """base plus the tooltip, which moves with the pointer (cheap: a rectangle)."""+ shape = QRegion(self.base)+ if why := self.pinned or self.hover:+ shape = shape.united(QRegion(self.tip_rect(why, self.pin_pos if self.pinned else self.tip_pos)[0].toAlignedRect().adjusted(-2, -2, 2, 2)))+ self.setMask(shape)# --- turning the answer into drawables ---def set_result(self, r):@@ -397,6 +427,7 @@ class Overlay(QWidget):self.items = sorted(items, key=lambda d: d['layer'])self.end = max([d['t'] + d['dur'] for d in items], default=0) + .1self.replay()+ self.reshape()def replay(self):self.t0 = time.monotonic()@@ -407,10 +438,14 @@ class Overlay(QWidget):p = QPainter(self)p.setRenderHint(QPainter.RenderHint.Antialiasing)p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)- p.drawImage(0, 0, self.shot)+ p.drawImage(0, 0, self.shot) # under the marks: their soft edges blend onto what was therenow = time.monotonic() - self.t0if now > self.end and not self.busy:self.tick.stop()+ self.paint_layer(p, now)++ def paint_layer(self, p, now, tips=True):+ """Everything penmentor draws, as of `now` seconds into the marks' animation (inf: the end)."""dim = .3 if self.busy else 1for d in self.items:k = min(1, max(0, (now - d['t']) / d['dur']))@@ -423,7 +458,7 @@ class Overlay(QWidget):self.draw_drill(p)self.draw_headline(p)why = self.pinned or self.hover- if why:+ if why and tips:self.draw_tip(p, why)if CONF['read']:self.draw_read(p)@@ -526,16 +561,14 @@ class Overlay(QWidget):else:p.drawText(box.adjusted(22, 0, 0, 0), Qt.AlignmentFlag.AlignVCenter, icon)p.drawImage(QPointF(box.left() + 22 + fm.horizontalAdvance(icon + ' '), box.center().y() - img.height() / 2), img)- f.setPixelSize(15)- p.setFont(f)- self.draw_bar(p, f, self.keys(), right=True)+ self.draw_actions(p)if CONF['stats']:self.draw_stats(p)def stats(self):"""Bottom-left panel: (rect, label column width, rows). A row is (label, text, bar fraction or None); None is a gap."""r = self.result or {}- rows = [('model', CONF['model'], None), ('effort', CONF['effort'], None), ('context', CONF['context'], None)]+ rows = [('model', ':'.join(pick()), None), ('effort', CONF['effort'], None), ('context', CONF['context'], None)]n, cached, *total = r.get('_tokens') or [None, None]run = [('took', f"{r['_secs']:.1f} s", None)] if '_secs' in r else []if n is not None:@@ -579,14 +612,24 @@ class Overlay(QWidget):p.drawText(QRectF(x, y, r.right() - x, 22), Qt.AlignmentFlag.AlignVCenter, text)y += 22- def draw_bar(self, p, f, text, right):- w = QFontMetrics(f).horizontalAdvance(text) + 24- r = QRectF(self.M.right() - w - 12 if right else self.M.left() + 12, self.M.bottom() - 36, w, 28)- p.setPen(Qt.PenStyle.NoPen)- p.setBrush(QColor(18, 18, 22, 210))- p.drawRoundedRect(r, 14, 14)- p.setPen(QColor(170, 170, 180))- p.drawText(r, Qt.AlignmentFlag.AlignCenter, text)+ def draw_actions(self, p):+ """The bar of buttons, bottom right: tap one with the pen (the penmentor key opens the same as a menu)."""+ f = ui_font(15)+ fm = QFontMetrics(f)+ acts = self.actions()+ widths = [fm.horizontalAdvance(label) + 26 for label, _ in acts]+ x, y = self.M.right() - sum(widths) - 4 * (len(acts) - 1) - 12, self.M.bottom() - 36+ p.setFont(f)+ self.bar_items = []+ for (label, act), w in zip(acts, widths):+ r, hot = QRectF(x, y, w, 28), self.bar_hover == label+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(48, 48, 58, 240) if hot else QColor(18, 18, 22, 215))+ p.drawRoundedRect(r, 14, 14)+ p.setPen(QColor(238, 238, 242) if hot and not self.busy else QColor(170, 170, 180))+ p.drawText(r, Qt.AlignmentFlag.AlignCenter, label)+ self.bar_items.append((r, label, act))+ x += w + 4def tip_rect(self, text, pos):if text not in self.tips:@@ -625,94 +668,116 @@ class Overlay(QWidget):# --- input ---def mouseMoveEvent(self, e):- old, self.tip_pos = self.tip_pos, e.position()- if self.drill:- if (row := self.drill_row(self.tip_pos)) != self.drill['hover']:- self.drill['hover'] = row- self.update()- return- hit = next((why for o, why in self.hits if o.contains(self.tip_pos)), None) if self.result else None- hit = hit or next((d['why'] for d in self.items if d['kind'] == 'bubble' and d.get('why')- and d['rect'].contains(self.tip_pos)), None)+ """Over what we drew (the window is shaped): light a button or a drill row; marks' whys come from hover_at."""+ pos = e.position()+ bar = next((label for r, label, _ in self.bar_items if r.contains(pos)), None)+ if bar != self.bar_hover:+ self.bar_hover = bar+ self.update()+ row = self.drill_row(pos) if self.drill else None+ if self.drill and row != self.drill['hover']:+ self.drill['hover'] = row+ self.update()+ head = self.mode == 'technique' and self.head_box and self.head_box.contains(pos)+ self.setCursor(Qt.CursorShape.PointingHandCursor if bar or row is not None or head or self.hover else Qt.CursorShape.ArrowCursor)+ self.hover_at(pos)++ def track(self):+ """Hover a mark, anywhere over it, for its why, as before the marks went live: the window is only their pixels,+ so the pointer is usually over your app and we never hear of it. Ask X where it is instead (a hovering pen+ moves it too); while you draw (a button or the pen tip down) no tooltip pops up."""+ where = pointer()+ if where and self.isVisible():+ x, y, held = where+ self.hover_at(QPointF(x - self.geom[0], y - self.geom[1]), held)++ def hover_at(self, pos, held=False):+ old, self.tip_pos = self.tip_pos, pos+ hit = None+ if self.result and not self.drill and not held:+ hit = next((why for o, why in self.hits if o.contains(pos)), None) or next(+ (d['why'] for d in self.items if d['kind'] == 'bubble' and d.get('why') and d['rect'].contains(pos)), None)if hit != self.hover:self.hover = hit+ self.apply_shape()+ self.update()+ elif hit and not self.pinned and pos != old: # the tip follows the pointer: repaint where it was and where it goes+ self.apply_shape()+ for p in (old, pos):+ self.update(self.tip_rect(hit, p)[0].toAlignedRect().adjusted(-2, -2, 2, 2))++ def leaveEvent(self, e):+ if self.bar_hover: # the marks' whys follow the pointer anyway (track)+ self.bar_hover = Noneself.update()- elif hit and not self.pinned: # the tip follows the cursor: repaint only where it was and where it goes- for pos in (old, self.tip_pos):- self.update(self.tip_rect(hit, pos)[0].toAlignedRect().adjusted(-2, -2, 2, 2))def mousePressEvent(self, e):+ """A tap acts on what it hits. Nothing makes the marks go away but Esc (or the close button)."""self.tip_pos = e.position()- if e.button() == Qt.MouseButton.RightButton:- self.close()- elif self.drill: # pen taps miss: in a drill only Esc or right-click closes- if (row := self.drill_row(self.tip_pos)) is not None:- self.pick_line(row)+ if item := next(((label, act) for r, label, act in self.bar_items if r.contains(self.tip_pos)), None):+ if not self.busy or item[0].startswith('close'):+ item[1]()+ elif self.drill and (row := self.drill_row(self.tip_pos)) is not None:+ self.pick_line(row)elif self.mode == 'technique' and not self.busy and self.head_box and self.head_box.contains(self.tip_pos):self.pick_technique()- elif not self.hover:- self.close()- else: # tap a mark to pin its "why" (pens don't hover well)+ elif self.hover: # tap a mark to pin its "why" (pens don't hover well)self.pinned, self.pin_pos = None if self.pinned == self.hover else self.hover, self.tip_pos- self.update()-- def keyPressEvent(self, e):- t = e.text()- hyper = Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.ShiftModifier- pad = {Qt.Key.Key_M: 'check', Qt.Key.Key_S: 'final'}.get(e.key()) if e.modifiers() & hyper == hyper else None- if e.key() in (Qt.Key.Key_Escape, Qt.Key.Key_Q):- self.close()- elif self.busy:- return- elif pad: # a tablet button while this is open: we hold the keyboard, so i3 never sees it; ask here- self.followup(TASKS[pad])- elif t == 'h':- self.followup(MORE)- elif t == '?':- self.ask_rofi(FOLLOWUPS, 'follow-up')- elif t == 'p' and self.mode == 'technique':- self.pick_technique()- elif t == 'n' and self.drill:- self.followup(TASKS['drill_more'])- elif t == 'g':- self.pick_then_show()- elif t == 'a' and self.mode == 'why':- self.ask_rofi([], 'your answer', TASKS['why_typed'])- elif t == 'w':- self.write_then(TASKS['why_written' if self.mode == 'why' else 'written'])- elif t == 'r':- self.replay()- elif t in ('s', 't'):- key = 'stats' if t == 's' else 'read'- save(**{key: not CONF[key]})+ self.apply_shape()self.update()def on_asked(self, q):if q is None: # Esc in rofi stops penmentor, like Esc anywhere elsereturn self.close()- self.activateWindow()- self.grabKeyboard()if q:self.followup(q)def closeEvent(self, e):- activate(self.app_window)QApplication.quit()# --- the modes ---- def keys(self):+ def actions(self):+ """What you can do next: the bar's buttons, and the menu the penmentor key opens. (label, what it does)"""if self.drill:- return 'tap the wrong line · n new drill · esc close'- k = {'technique': ['p pick the technique'], 'why': ['a type answer', 'w write answer']}.get(self.mode, ['w write more'])- return ' · '.join(k + ['h more help', '? ask', 'g show me', 't what I read', 's stats', 'r replay', 'esc close'])+ first = [('new drill', lambda: self.followup(TASKS['drill_more']))]+ else:+ first = {'technique': [('pick the technique', self.pick_technique)],+ 'why': [('type your answer', lambda: self.ask_rofi([], 'your answer', TASKS['why_typed'])),+ ('check what I wrote', lambda: self.check_new(TASKS['why_written']))]}.get(+ self.mode, [('check new work', lambda: self.check_new(TASKS['written']))])+ return first + [('more help', lambda: self.followup(MORE)), ('ask…', lambda: self.ask_rofi(FOLLOWUPS, 'follow-up')),+ ('show me', self.pick_then_show), ('what I read', lambda: self.toggle('read')),+ ('stats', lambda: self.toggle('stats')), ('replay', self.replay), ('close · esc', self.close)]++ def toggle(self, key):+ save(**{key: not CONF[key]})+ self.reshape()+ self.update()- def pick_then_show(self):- """g: box what to show on this frame, then Claude animates it (no boxes: what the problem is about)."""- self.releaseKeyboard()+ def poked(self):+ """The penmentor key (or a pad button) while the marks are up: the actions as a menu, or straight to that question."""+ try:+ what = (CACHE / 'poke').read_text().strip()+ except OSError:+ what = 'menu'+ if self.busy:+ return+ if what in TASKS: # a pad button: that question about the work as it is now (you have probably written more)+ return self.check_new(TASKS[what])+ rows = [label for label, _ in self.actions()]+ threading.Thread(target=lambda: self.chose.emit(rofi(rows, 'penmentor')), daemon=True).start()++ def on_chose(self, label):+ if label is None: # Esc: as everywhere+ return self.close()+ act = dict(self.actions()).get(label)+ if act:+ act()+ def pick_then_show(self):+ """Show me: box what to show on this frame, then Claude animates it (no boxes: what the problem is about)."""def chosen(boxes):- self.activateWindow()- self.grabKeyboard()+ activate(self.app_window) # the picker had the keyboard; give it back to the appself.region, self.want_plot = boxes, Trueself.cache.pop('shots', None) # redraw what Claude sees, with the boxesself.request(TASKS['show_boxes' if boxes else 'show'], new_shot=bool(boxes) or self.result is None)@@ -721,8 +786,7 @@ class Overlay(QWidget):def ask_rofi(self, rows, prompt, template='{}'):"""A rofi pick (or typed text) turned into a follow-up. No rows: just a text box."""- self.releaseKeyboard() # only reaches X once we are back in the event loop, so rofi runs on a thread- def pick():+ def pick(): # on a thread: rofi waits for you, the marks keep drawingc = rofi(rows, prompt)self.asked.emit(None if c is None else c and template.format(c)) # None: Escthreading.Thread(target=pick, daemon=True).start()@@ -730,26 +794,10 @@ class Overlay(QWidget):def pick_technique(self):self.ask_rofi(TECHNIQUES, 'technique', TASKS['pick'])- def write_then(self, task):- """Step aside so you can write on the real page; ask `task` about the new screen once you tap the badge."""- self.pending = task- self.releaseKeyboard()+ def check_new(self, task):+ """Check what you wrote since: the marks step aside for the screenshot, then come back with the answer."""self.hide()- activate(self.app_window) # so your keys reach xournal again, and so does the page-export shortcut- self.pill = Pill(self.shot, self.top_geom(), 'Done writing? Tap here', self.retake, busy=False)- self.pill.show()- set_state(f'waiting {os.getpid()}')- signal.signal(signal.SIGUSR1, lambda *a: QTimer.singleShot(0, self.retake)) # pressing an penmentor key again = done too- QTimer.singleShot(30 * 60 * 1000, lambda: self.pending and QApplication.quit()) # nobody came back-- def retake(self):- if not self.pending or not self.pill:- return- task, self.pending = self.pending, None- signal.signal(signal.SIGUSR1, signal.SIG_IGN)- self.pill.close()- self.pill = None- QTimer.singleShot(150, lambda: self.reshoot(task)) # let X repaint under the badge before the screenshot+ QTimer.singleShot(150, lambda: self.reshoot(task)) # let X repaint where the marks weredef reshoot(self, task):try:@@ -800,11 +848,11 @@ class Overlay(QWidget):text = 'Found it' if d['found'] else f"It was line {(d['wrong'] or 0) + 1}"self.result = dict(self.result, headline=text, verdict='correct' if d['found'] else 'mistake')self.head_img = tex(text, 'white', HEAD)+ self.reshape()self.update()def draw_drill(self, p):d, pal = self.drill, self.pal- p.fillRect(self.rect(), QColor(0, 0, 0, 150)) # the drill is not your page: push the page backc = d['card']panel(p, c, 14, 255)p.drawImage(QPointF(c.left() + d['pad'], c.top() + d['pad']), d['prob'])diff --git a/src/penmentor/plot.py b/src/penmentor/plot.pyindex 1326501..0e472f7 100644--- a/src/penmentor/plot.py+++ b/src/penmentor/plot.py@@ -694,7 +694,7 @@ class Show(Scene):if (parent and os.getppid() != parent) or time.monotonic() > end: # penmentor stopped (Esc) before Claude answeredbreakself.wait(.1)- got = json.loads(spec_file.read_text()) if spec_file.exists() else {'error': 'Stopped before Claude answered.'}+ got = json.loads(spec_file.read_text()) if spec_file.exists() else {'error': 'Stopped before the answer came.'}arc.clear_updaters()self.play(FadeOut(VGroup(ring, arc, word)), run_time=.4)return got.get('spec') or {'error': got.get('error') or 'no animation this time'}diff --git a/src/penmentor/prompts.py b/src/penmentor/prompts.pyindex 27a69a2..6fb38ef 100644--- a/src/penmentor/prompts.py+++ b/src/penmentor/prompts.py@@ -1,4 +1,4 @@-"""What penmentor asks Claude, and the JSON shape Claude answers in."""+"""What penmentor asks the model, and the JSON shape it answers in."""PRESETS = [ # rofi menu: (label, mode)('✓ Did I make any mistakes?', 'check'),diff --git a/src/penmentor/selftest.py b/src/penmentor/selftest.pyindex 63b704b..20f2761 100644--- a/src/penmentor/selftest.py+++ b/src/penmentor/selftest.py@@ -151,7 +151,7 @@ def overlay():assert (display(drill['fix']), 19) in tex_jobs(r)ov.set_result(r)d = ov.drill- assert len(d['rows']) == 4 and 'tap the wrong line' in ov.keys()+ assert len(d['rows']) == 4 and ov.actions()[0][0] == 'new drill'centre = lambda i: d['rows'][i][0].center()assert ov.drill_row(centre(1)) == 1 and ov.drill_row(QPointF(-5, -5)) is Noneov.pick_line(0)@@ -165,7 +165,11 @@ def overlay():tech = Overlay(shot, (0, 0, 1200, 800), mode='technique')tech.set_result(dict(read_as=[], verdict='hint', headline='Which technique fits?', marks=[]))tech.grab()- assert tech.drill is None and tech.keys().startswith('p pick') and tech.head_box is not None+ assert tech.drill is None and tech.actions()[0][0] == 'pick the technique' and tech.head_box is not None+ # the marks sit on the live screen: the window is shaped to what is drawn, everything else stays the apps'+ from PyQt6.QtCore import QPoint+ assert not tech.base.isEmpty() and not tech.base.contains(QPoint(60, 400)) and tech.base.contains(tech.head_box.center().toPoint())+ assert [label for _, label, _ in tech.bar_items][-1] == 'close · esc' # the bar's buttons were laid outpill = Pill(tech.shot, (0, 0, 1200, 800))assert not pill.grab().isNull()@@ -193,32 +197,91 @@ def page_export():def stopping():"""Esc kills a claude that is still answering instead of leaving it running on your plan."""import threading- from . import claude+ from . import harnesswith tempfile.TemporaryDirectory() as d:- stub, saved, failed = Path(d) / 'claude', claude.CLAUDE, []+ stub, saved, failed = Path(d) / 'claude', harness.BIN['claude'], []stub.write_text('#!/bin/sh\nexec sleep 30\n')stub.chmod(0o755)- claude.CLAUDE = str(stub)+ harness.BIN['claude'] = str(stub)def ask():try:- claude.ask([], 'hi', keep=False)+ harness.ask([], 'hi', keep=False)except RuntimeError:failed.append(True)try:t = threading.Thread(target=ask)t.start()for _ in range(300):- if claude.RUNNING:+ if harness.RUNNING:breaktime.sleep(.01)- claude.stop()+ harness.stop()t.join(5)- assert not t.is_alive() and failed and not claude.RUNNING+ assert not t.is_alive() and failed and not harness.RUNNINGfinally:- claude.CLAUDE = saved+ harness.BIN['claude'] = saved+++STUB = r"""#!/usr/bin/env python3+import json, os, sys+open(os.environ['PM_LOG'], 'a').write(json.dumps({'argv': sys.argv, 'stdin': sys.stdin.read()}) + '\n')+answer = {'read_as': [], 'verdict': 'correct', 'headline': 'ok', 'marks': []}+name = os.path.basename(sys.argv[0])+if name == 'claude':+ print(json.dumps({'type': 'result', 'structured_output': answer, 'usage': {'input_tokens': 5, 'output_tokens': 2}}))+elif name == 'agy':+ print(json.dumps({'event': 'init', 'conversation_id': 'conv-1'}))+ print(json.dumps({'event': 'result', 'result': {'status': 'SUCCESS', 'conversation_id': 'conv-1', 'structured_output': answer,+ 'usage': {'total_tokens': 7}}}))+else:+ print(json.dumps({'type': 'thread.started', 'thread_id': 'thr-1'}))+ print(json.dumps({'type': 'item.completed', 'item': {'type': 'agent_message', 'text': json.dumps(dict(answer, drill=None, plot=None))}}))+ print(json.dumps({'type': 'turn.completed', 'usage': {'input_tokens': 5, 'output_tokens': 2}}))+"""+++def harnesses():+ """Claude Code, Antigravity and Codex, played by stand-ins that answer in each one's own format: the same answer+ shape whichever runs it, follow-ups resume that harness's conversation, switching harness starts a new one."""+ from . import config, harness+ saved = dict(harness.BIN), harness.SESSION, harness.TURN, harness.CACHE, dict(config.CONF)+ with tempfile.TemporaryDirectory() as d:+ d = Path(d)+ log = d / 'log.jsonl'+ os.environ['PM_LOG'] = str(log)+ for h in harness.HARNESSES:+ (d / h).write_text(STUB)+ (d / h).chmod(0o755)+ harness.BIN[h] = str(d / h)+ harness.SESSION, harness.TURN, harness.CACHE = d / 'session.json', d / 'turn', d+ shot = harness.prepare(__import__('PIL.Image').Image.new('RGB', (40, 30), 'white'))+ calls = lambda: [json.loads(l) for l in log.read_text().splitlines()]+ try:+ assert harness.pick('codex:gpt-x') == ('codex', 'gpt-x') and harness.pick('opus') == ('claude', 'opus')+ for h, resumes in (('claude', '--resume'), ('agy', '--conversation'), ('codex', 'resume')):+ config.CONF['model'] = f'{h}:m'+ r = harness.ask([shot], 'is it right?')+ assert r['headline'] == 'ok' and 'drill' not in r and r['_tokens'][0] > 0, (h, r)+ assert json.loads(harness.SESSION.read_text())['harness'] == h+ first = calls()[-1]+ strict = json.loads((d / 'turn' / 'schema.json').read_text()) if h == 'codex' else None+ harness.ask([shot], 'and now?', new_shot=False) # a follow-up: the same conversation+ assert resumes in calls()[-1]['argv'], (h, calls()[-1]['argv'])+ if h == 'agy': # its print mode takes text only: the screenshot is a file it is told to open+ assert str(d / 'turn' / 'image1.png') in first['stdin'] and '--sandbox' in first['argv']+ if h == 'codex': # attached by Codex; its schema strict (every key required)+ assert f"--image={d / 'turn' / 'image1.png'}" in first['argv']+ assert set(strict['required']) == set(strict['properties']) and '--sandbox' in first['argv']+ config.CONF['model'] = 'agy:m' # a codex conversation can't continue in agy: a new one, screenshots included+ harness.ask([shot], 'and now?', new_shot=False)+ assert '--conversation' not in calls()[-1]['argv'] and 'image1.png' in calls()[-1]['stdin']+ finally:+ harness.BIN.update(saved[0])+ harness.SESSION, harness.TURN, harness.CACHE = saved[1:4]+ config.CONF.clear(), config.CONF.update(saved[4])def selftest():- for check in (pages, text, desktop, menus, formulas, plots, overlay, page_export, stopping):+ for check in (pages, text, desktop, menus, formulas, plots, overlay, page_export, stopping, harnesses):check()print('selftest ok')