# oyp -- ownyourpdf for agents

`oyp` is ownyourpdf's command line for scripts and agents: read, render,
measure, verify, mark up and assemble pdfs. ONE json object on stdout, a
meaningful exit code, no window, no dialog, no prompt, no network, ever. it is
the same pdf layer and pixel engine the desktop app runs on, so what oyp
writes opens in the app and in revu like a hand-made markup.

this file is the contract. `oyp help`, `oyp help <verb>` and `oyp schema`
are generated from the same parameter table the parser uses, so they can't
drift from the binary you have; when this page and `oyp schema` disagree,
the schema is right and this page has a bug.

## install (pinned, hashed, offline)

from a checkout of this repo (needs a .NET 10 sdk to BUILD; the installed
binary is self-contained and needs nothing):

```bash
tools/install-cli.sh [--add-to-path]   # linux x64/arm64, macos arm64/x64
# -> ~/.local/share/oyp/builds/<version>-<sha8>/, ~/.local/bin/oyp -> current/oyp
# --add-to-path: one marked PATH line in ~/.profile (+ ~/.zshenv, ~/.bashrc)
```

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File tools/install-cli.ps1 [-AddToPath]
# -> %LOCALAPPDATA%\Programs\oyp\current\oyp.exe
```

both publish in nuget LOCKED mode (the committed lock files), smoke-test the
build (engine loads, a fixture reads and renders) before installing, keep
the build in a content-addressed folder with a `SHA256SUMS`, and print one
json line with the `buildDigest` (the sha256 of `SHA256SUMS`, which lists
every file of the build) plus the sha256 of `oyp` and of the pdfium beside
it -- record those like any pinned binary. builds are reproducible: the same
commit and sdk give the same digest. re-running is safe; current + two older builds are
kept. not found on PATH? the
stable full paths are `~/.local/bin/oyp` and
`%LOCALAPPDATA%\Programs\oyp\current\oyp.exe` (clients/python/oyp.py
looks there too).

### verifying an installed build

every build installed via `tools/install-cli.sh` or `tools/install-cli.ps1`
writes a content-addressed `SHA256SUMS` beside the binary and records its
`buildDigest`. run `oyp version --check` to re-hash every installed file
against `SHA256SUMS` (exits 1 with `build_modified` on any mismatch).

the pixel engine is stock pdfium 156.0.8076.0 (bblanchon builds), vendored
per platform under `vendor/pdfium/` with its provenance and hashes. linux x64, windows x64, macos arm64, and linux arm64 are verified on real
hardware; osx-x64 (intel macs) has been verified under rosetta 2 only (not
yet run natively on intel mac hardware).
the desktop app (not oyp) has run on windows only.

check what you have: `oyp version` ->
`{"ok":true,"verb":"version","version":"0.12.2","platform":"linux-x64","engine":true,"buildDigest":"9a3a...",...}`.
`buildDigest` is the installer's digest (null on a dev build), so a caller can
pin and compare without re-hashing; `oyp version --check` also re-hashes every
file listed in `SHA256SUMS` and exits 1 (`build_modified`) if any differ.
the default windows install path is
`%LOCALAPPDATA%\Programs\oyp\current\oyp.exe`.

first run on a new box: `tools/test-drive.sh` (after `tools/install-cli.sh`)
runs every verb on the tracked fixtures and prints one json summary line.

linux note: .NET decrypts through openssl there. oyp's own hashing is
managed, so a box with no libcrypto reads every unencrypted pdf; an encrypted
one is refused as `unsupported` (exit 1) instead of aborting the process.

## the envelope

success, exit 0:

```json
{"ok":true,"verb":"measure","file":"/abs/plan.pdf", ...the verb's result...}
```

failure, nonzero exit:

```json
{"ok":false,"verb":"info","error":{"code":"not_found","message":"no file at nope.pdf"}}
```

| exit | meaning | typical `error.code` |
|------|---------|----------------------|
| 0 | ok | |
| 1 | failed (a write refused, internal) | `internal`, ... |
| 2 | usage: unknown verb/option, missing value, a bad markup spec (`markup 3: ...`) | `usage` |
| 3 | input not found / not readable | `not_found`, `unreadable` |
| 4 | needs a password: none given, or the `--password-file` one does not open it | `password_required` |
| 5 | the pixel engine is not beside oyp | `engine_missing` |
| 6 | not a pdf, or no readable pages | `not_a_pdf`, `no_pages` |
| 7 | `verify`: a check failed | `verify_failed` |

what you can pin on: the exit codes above and the keys this page names keep
their meaning. changes are additive (a new key, a new verb, a new error code);
removing or renaming a documented key or code is a breaking change, named in
the release that does it. there is no separate schema version number:
`version` + `buildDigest` say which build answered.

never exit 0 with nothing written: a write verb reports `path`, `bytes`,
`sha256`, `pages` of the file it wrote, and only after reading it back.
`--pretty` indents the json; nothing else changes. stderr is not part of the
contract (it is normally empty).

## conventions

- **pages** are 1-based. ranges: `1-3,5,8-`, `all`, `last`.
- **coordinates** are pdf points (1/72 in), origin at the BOTTOM-left of the
  page's unrotated user space. text bboxes, annotation rects, markup points,
  viewport boxes and `measure` / `snap` all use the same space, so a bbox
  from `text` can be fed straight into `add-markups`.
- **inputs are read once, with full share mode**: a file another program has
  open (revu, a share drive's live copy) is read, never locked or refused,
  and never held open after the read. oyp does not cache anything anywhere.
- **writes never touch the input** unless you pass `--in-place`. `--out` must
  differ from the input. every edit is an APPENDED REVISION: the input's bytes
  stay a byte-identical prefix, so a signature keeps covering what it signed
  and nothing another tool wrote is re-serialized. an edit that changes
  nothing writes nothing (`"changed":false`). page ops (`merge`, `extract`,
  `split`) write new files. an owner-locked (empty user password) file is
  read and edited. a file that needs a real password takes
  `--password-file <file>` (every verb that opens one pdf; mcp:
  `password_file`): the file holds the user password, utf-8, one trailing
  newline ignored. the password itself never goes in argv (ps, shell history,
  ci logs see argv) and is never echoed in a result. without it, exit 4.
  writes to such a file stay encrypted under the same password; `unlock`
  writes it out plain. pdf 2.0 (aes-256 r6) passwords are taken as given,
  without saslprep normalization.
- results go to a temp file and an atomic rename: a reader never sees half a
  pdf.

## verbs

| verb | what it does |
|------|--------------|
| `info` | pages + sizes (media/crop box, rotate), fonts per page (embedded? subset?) + images (px, bits, color space, filter), metadata, annotations by type, measurement viewports + scales, signatures (intact?), layers, print scaling, revisions, repaired?, sha256. `--ink` adds each page's inked share (0 = blank) |
| `text` | text with positions, font and size: `--mode lines` (default) / `words` / `chars` / `plain` / `rows` (each line cut into cells at gaps over `--gap` font sizes: a heuristic table read, not cell reconstruction). decodes cad subset fonts (rhino, autocad) through the pdf's own maps |
| `render` | pages to png at `--dpi` or `--width`, annotations drawn. `--out p{page}.png` for several; `--inline` for base64 |
| `annots` | every annotation: type, rect, contents, author; for markups the geometry and the calibrated measurement |
| `measure` | calibrated length (or `--closed` area + perimeter) between points, using the page scale or the detail viewport the points sit in; `--scale` overrides |
| `snap` | the nearest exact point of the drawing itself (end, mid, perp foot, crossing) to a point |
| `vectors` | the page's own linework as polylines: `--format json` (default) / `svg` / `dxf` (r12, opens in rhino / autocad as curves), `--units pt\|in\|mm` (paper), `--out`. curves arrive as chords to their end points; text is not linework |
| `verify` | check against expectations: `--pages`, `--min-pages`, `--max-pages`, `--even-pages`, `--size` (+ `--any-orientation`), `--max-bytes`, `--text` (+ `--text-every-page`), `--print-scaling`, `--signatures-intact`, `--no-repair`, `--fonts-embedded`, `--min-ink` (blank / failed-capture pages), `--fills-page 0.9` (chrome's print shrink-to-fit: a chrome page is judged by the print scale skia wrote into its content stream, so a stray box that inks the edge cannot fool it; other pdfs by ink reach across or down, needs the pixel engine), `--plain` / `--plain-fonts` / `--plain-ink` (the house plain pdf style, opt-in: one font family <= 2 weights, no colored ink; `--plain-pages` keeps it off drawing sheets), `--text-on 4:S-3` (text on one page), `--no-text "site TBD"` (must be absent), `--text-word` (whole tokens: `S-1` misses `S-10`). exit 7 (or `--fail-exit n`) + every check's expected vs saw; `--fills-page` also lists `pages` (each page's chrome `scale`, or ink `reach` / `across` / `down`), on a pass too, for an archive (0.12.8+) |
| `set-print-scaling` | `/ViewerPreferences /PrintScaling` `none` (print dialogs default to actual size) or `appdefault` |
| `add-viewports` | standard `/VP` measurement viewports: a box + the drawing scale inside it (per-detail scales revu and oyp both read); `label` sets the scale text a viewer shows (`0.17" = 1'-0"`) |
| `add-markups` | standard markups with appearance streams: line, length, dimension, arrow, polyline, polylength, polygon, area, perimeter, cloud, rectangle, ellipse, text, callout |
| `stamp` | a line of real page text (footer marker, build id) at a corner or x,y; `{page}` / `{pages}` tokens |
| `rotate` | turn pages by multiples of 90 |
| `flatten` | burn each markup's appearance into the page content (what bluebeam's flatten does): it prints and looks the same, nothing stays editable. links, form fields and markups with no appearance are kept; hidden ones are dropped |
| `merge` | one new pdf from several: `a.pdf b.pdf:2-9 c.pdf:last`; `--bookmarks` adds one outline entry per input (its file name, or `--bookmark-titles "a\|b"`) |
| `extract` | a new pdf of some pages |
| `unlock` | a new pdf, unencrypted, of an owner-locked file (opens with no password but carries edit / print restrictions), or of one that needs a password, given by `--password-file` |
| `split` | one pdf per page (or per `--every n`) into `--out-dir` |
| `schema` | every verb's parameters as json schema |
| `mcp` | serve every verb as an mcp tool over stdio |

`oyp help <verb>` prints each verb's options and an example.

### a few results, verbatim

```
$ oyp measure two-detail.pdf --points "900,300 900,348"
{"ok":true,"verb":"measure","file":"...","page":1,"points":2,
 "length":{"lengthPts":48,"lengthPaperIn":0.667,"length":1.333333,"unit":"ft","lengthLabel":"1'-4\""},
 "scale":{"label":"scale: 1/2\" = 1'-0\"","unit":"ft","pointsPerUnit":35.99999999999999},"scaleSource":"viewport"}

$ oyp text two-detail.pdf --mode words
{"ok":true,"verb":"text",...,"pages":[{"page":1,"text":"SHOP-PDF-TABLOID",
 "words":[{"text":"SHOP-PDF-TABLOID","bbox":[76.511,646.897,1046.106,722.179],"font":"PGSPHH+ArialMT","size":100.24}]}, ...]}

$ oyp verify grid-multi.pdf --pages 2 --size letter ; echo $?
{"ok":false,"verb":"verify","error":{"code":"verify_failed","message":"pages: expected 2, saw 3; size: expected 612x792pt on every page (+-1pt), saw 2 off: p2 1224x792pt, p3 288x288pt"},
 "file":"...","sha256":"...","pageCount":3,"passed":false,"checks":[{"check":"pages","expected":"2","saw":"3","pass":false}, ...]}
7
```

### add-markups spec

`--spec` is a json array (a file path, inline json, or `-` for stdin):

```json
[
  {"type": "cloud", "page": 1, "points": [[100,100],[300,100],[300,200],[100,200]], "color": "#e04040"},
  {"type": "length", "points": [[144,144],[360,144]]},
  {"type": "dimension", "points": [[144,144],[360,144]], "offset": 24},
  {"type": "area", "points": [[100,300],[300,300],[300,400]], "scale": "1/4in=1ft"},
  {"type": "arrow", "points": [[400,400],[450,450]], "width": 2},
  {"type": "text", "at": [72,720], "text": "field verify", "fontSize": 12},
  {"type": "callout", "points": [[200,200]], "at": [260,260], "text": "see detail 3"},
  {"type": "rectangle", "points": [[50,50],[150,120]], "opacity": 0.5}
]
```

measurements (`length`, `dimension`, `polylength`, `area`, `perimeter`) take
the scale from the viewport their points sit in, else the page calibration,
else `scale` on the item; the caption is computed (`"1'-4\""`, `"128.5 sq ft"`).
every markup is a standard pdf annotation (iso 32000-2) with its own
appearance stream and a standard `/Measure`, author from `--author`.

## from python

`clients/python/oyp.py` -- one stdlib file; copy or vendor it.

```python
import oyp                                  # finds $OYP, PATH, or the default install
pages = oyp.run("info", "pkg.pdf")["pageCount"]
oyp.run("verify", "pkg.pdf", pages=12, size="17x11", any_orientation=True,
        text=["ISSUED FOR CONSTRUCTION"], text_every_page=True)     # raises oyp.OypError(code="verify_failed") with .result
oyp.run("set-print-scaling", "shop.pdf", value="none", in_place=True)
```

## as an mcp server

```bash
claude mcp add oyp -- ~/.local/bin/oyp mcp
# windows: claude mcp add oyp -- "%LOCALAPPDATA%\Programs\oyp\current\oyp.exe" mcp
```

stdio json-rpc 2.0 (protocol 2025-06-18, also 2025-03-26 / 2024-11-05). one
tool per verb, named with underscores (`add_markups`, `set_print_scaling`),
input schema from the same table; `readOnlyHint` is false on write verbs.
results carry `structuredContent` (the verb's json) and a text copy; a
failure is `isError: true`, not a protocol error. `render` without `out`
returns the png as an image content block so the model can look at it.

## common migration patterns

| hand-rolled pattern | with oyp |
|---|---|
| regex preflight over raw pdf bytes (misses object streams) | `oyp verify out.pdf --size 17x11 --max-pages 40 --max-bytes 50000000` (real reader: xref streams, object streams, repair) |
| post-chrome page count or paper-size checks | `oyp verify out.pdf --pages 12 --size letter` |
| custom census script (classic xref only) | `oyp info --ink` (fonts, images, mediabox, ink per page) + `oyp text --mode words` |
| blank-page or incomplete-capture check | `oyp verify pkg.pdf --min-ink 0.001` (every page has ink) |
| chrome print shrink-to-fit detection | `oyp verify out.pdf --fills-page 0.9` |
| monochrome plain-document style gate | `oyp verify memo.pdf --plain` (or `--plain-ink`, `--plain-pages 1-2` for text pages only) |
| custom ci exit code on check failure | `oyp verify ... --fail-exit 2` |
| ad-hoc row/column scraping | `oyp text doc.pdf --mode rows` (cells at wide gaps; heuristic) |
| setting `/ViewerPreferences /PrintScaling /None` | `oyp set-print-scaling shop.pdf --value none --in-place` |
| writing per-detail `/VP` measurement viewports | `oyp add-viewports sheet.pdf --spec viewports.json --in-place` |
| greppable footer marker check | `oyp verify pkg.pdf --text "ISSUED FOR CONSTRUCTION" --text-every-page` (or `oyp stamp` to add real text) |
| stapling pdfs with python scripts | `oyp merge --out book.pdf cover.pdf sheets.pdf:2-9` |
| page-to-png rendering scripts | `oyp render scan.pdf --pages all --dpi 150 --out page-{page}.png` |
| positioned word extraction | `oyp text doc.pdf --mode words` |

NOT oyp's job (say so rather than bending it): html -> pdf (chrome stays),
printing to a device, table reconstruction (`--mode rows` cuts lines at
wide gaps; no ruled-line or column-span detection), ocr of scanned pages, qr decoding. (password-protected files: `--password-file`, above.)

## guarantees, and their limits

- offline: no code path opens a socket. no telemetry, no update check.
- no ui: no window, dialog, console prompt or popup on any path, including
  errors. safe on unattended boxes.
- the input is never modified without `--in-place`; with it, only appended.
- every written file is re-read by our reader and by pdfium before it lands.
- limits, stated: no intel mac has run oyp natively (osx-x64 runs under
  rosetta 2); the desktop app is windows-only so far; a
  `measure` of a foreign viewport with a nonuniform scale is reported
  uncalibrated rather than guessed; `text` on a page with no font maps (a
  scan) returns nothing, not ocr.
