ADR 0018doc/{zh,en}/adr/0018-media-parsing.md

ADR 0018: Media Parsing: a Host Service, Parser Plugins and Rendering at the Model Boundary

Status: accepted, 2026-11-27, from the owner's decisions in the media parsing research (section 12) and its native plan (section 7). Slice S1 builds decisions 1–5; the media tool,

Status: accepted, 2026-11-27, from the owner's decisions in the media parsing research (section 12) and its native plan (section 7). Slice S1 builds decisions 1–5; the media tool, ranged reads, parts and the process protocol of parsers come with S2; the model parser (media.models, plugin.ModelParser, plugin.MediaModel) with S3. Orquelo's own PDF reader, pkg/pdf, behind the native pdf parser comes with S4a; its layout (reading order, columns, paragraphs, headings, running headers and footers as the media.v1 block types header and footer, left out of the Markdown) and the outline from bookmarks with S4b; tables, from ruling lines or aligned text, as media.v1 table blocks with S4c, and with its follow-up tables drawn with horizontal rules only, cells that wrap, and a table across pages as one block on its first page (Block.LastPage); with S4e, Document.Meta (the file's own properties, its first page's size, the tables and images found) and the running headers and footers, each once, which a model reads as "name: value" lines before the content; with S4f, the same for every kind (photos, recordings through the native parse-av parser, text, CSV), and beside a file a model takes as it is; and with S4d, Document.Quality: each PDF page's visible, invisible and unreadable characters and how much of it images cover, from which a page is named scanned, as carrying an OCR layer, or garbled (its noise withheld), and orquelo media eval scores scan detection against hand labels; with S5a, a parser may give the image a page is made of (plugin.PageImager), and the parsing service has each scanned page without text read from it by the parser of images that produces ocr (the model parser, asked with media.Input.Want for the text as written), putting the reading in place of the page's note; pkg/pdf decodes scan images (JPEG, raw pixels, CCITT through golang.org/x/image, and JBIG2, with Huffman, MMR and halftone regions, ported from pdf.js into pkg/pdf/jbig2, and JPEG 2000 with every option OpenJPEG decodes, HTJ2K included, ported from pdf.js and OpenJPEG into pkg/pdf/jpx; the owner asked for every option), and orquelo media parse -c starts the configured media models (owner's choice); with S5b and S5c, without an image model, local OCR reads images and scanned pages: the builtin ocr parser of parse-ocr has its worker process orquelo-ocr run PP-OCR models on ONNX Runtime through pkg/onnx (purego), all installed with the release in deps/parse-ocr, never by a parse, a missing piece named with the error code media.unavailable (local OCR). With S6, without an audio or video model, the builtin speech parser of parse-speech decodes recordings natively and has Whisper small transcribe them in the same model worker (renamed orquelo-onnx, one process per task, shared in deps/onnx), into transcript blocks with times, silence as "no speech detected"; a parser may split a file into pieces the Host reads in turn (plugin.Splitter, at most two levels), with which the video parser of parse-video has ffmpeg, a system prerequisite, take out the sound track and frames, read into one timeline (local speech and video). With S6's diarization follow-up (2026-12-04), a transcript of several voices names who speaks (media.Block.Speaker, rendered "Speaker N: ", numbered by first appearance), from speaker embeddings (3D-Speaker's CAM++, shipped in deps/parse-speech, optional) computed in the same worker and clustered by the parser; one voice, or no speaker model, leaves the transcript as before. With S7a, a compound file (OLE2) is told by the stream at its root that holds the document, read by pkg/media/cfb: Word, Excel and PowerPoint 97–2003 files (application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint) go to the native parsers doc, xls and ppt of parse-office, and any other compound file, or one whose directory does not read, to its parser ole, which says it is damaged, encrypted or of an unsupported kind. With the local OCR follow-up, a parser spec may list the recognition languages a call may name (languages), passed as media.Input.Language with the configured media.ocr.language or a call's (the media tool's language, orquelo media parse --lang), an unknown one refused with the error code media.language; the parse cache keys on it; and media.ocr.max_memory bounds the model worker's memory (media.Input.MaxMemory), past which an image is media.too_large (local OCR). With S4d's follow-up (2026-12-03), pkg/pdf/render draws PDF pages natively (with pkg/pdf/fontprog for embedded font programs and the Go fonts for others), parse-pdf gives any page's image through plugin.PageImager (a scan's own image, else the page drawn), and the parsing service reads from its image a garbled page and a page without text that draws shapes or images, and compares every page with enough text with local OCR of its drawing: a layer that does not match is replaced by the reading, marked, and media.Quality records reread, read_by and ocr_similarity (PDF renderer). The media harness review's slice D (2026-12-03, findings M-09 and M-10) builds RTF (pkg/media/rtf, the parser rtf of parse-office), email (pkg/media/mail; .eml and Outlook .msg, the parsers eml and msg of the new parse-mail), Jupyter notebooks (the parser notebook of parse-html) and archives (ZIP, tar, gzip, bzip2 and 7z, with pkg/media/sevenzip and pkg/media/lzma, in the new parse-archive), each typed by its bytes; a file an archive or an email holds is read by name as a file of its own (media.Range.Member, the media tool's member, orquelo media parse --member) through plugin.Unpacker, at most four files deep, a member past media.MaxMember (256 MiB) or 200 times its packed size refused with media.bomb; and the Office details of M-10: DOCX comments, notes, running headers and footers, links and text boxes, XLSX merged cells, comments, hidden sheets and uncalculated formulas, ODF repeats, and Meta.Macros. With M-18 (2026-12-04), the native model plugins anthropic and gemini declare their file limits through plugin.MediaLimits like openai, take PDFs (and for Gemini audio and video) natively, and upload files over a request's inline budget to the vendor's file API, kept by pkg/modelfiles with a deadline per upload; a step refused as llm.payload_too_large with native files goes through C5 too (native model APIs). The review's slice E2 (2026-12-03, findings M-15 and M-17) builds process parsers: a parser may be a process plugin in any language, which the Host calls with parser/parse (the file's ref, sniffed type and range) and which reads the file back through host/read_artifact at offsets, at most 4 MiB a call, never by path; its document is validated (media.Validate), a crash, a hang past the parse time limit or a bad reply fails that parse alone with a media code and the process starts again, and installed parsers are chosen like builtins within media.allow; a parser may teach the Host its own format by its bytes (magic, media.SniffWith), never over a type the Host knows (parser protocol, the example plugins/parse-sample). It also reads Parquet (pkg/media/parquet, with pkg/media/snappy and pkg/media/zstd) and SQLite databases (pkg/media/sqlite, read-only, each table a sheet) in the new parse-data, Excel binary workbooks (xlsb) and Apple Pages, Numbers and Keynote files (iwork, pkg/media/iwa: text, '09 tables, the preview as a figure and a member) in parse-office, and a text, log, JSON or CSV file over 32 MiB in pages of 16 KiB read from their offsets (pkg/media/textpages); not built: the cells of 2013+ Numbers tables, LZ4, Brotli and LZO pages of Parquet, a SQLite database's -wal file. With the review's M-16 (2026-12-04), local OCR reads an image or a scanned page by its regions with the layout model PP-DocLayout-S and its tables with the table structure model SLANet_plus, installed with its other models: titles, headings, list items, tables as table blocks, figures as figure blocks whose region (media.Region, a Block.Ref) ocr or the Host, through the parser's PageImager, cuts out for a model that sees images, the headers and footers of scanned pages kept once (media.Running, shared with pdftext), and a table of a scanned page that goes on at the top of the next under the same header read as one table, on its first page (media.TablesAcross, 2026-12-05); without those models a page reads line by line (local OCR). Since 2026-12-04 the formula model PP-FormulaNet_plus-S, installed with them, reads a page's formulas as LaTeX, $$...$$ apart or $...$ in a sentence; a readable PDF text layer stays as it is. With xz and MBOX (2026-12-04), parse-archive reads xz files and tar.xz (pkg/media/xz: streams and padding, LZMA2 behind delta and the branch filters of pkg/media/filter, shared with 7z, CRC32, CRC64 and SHA-256 checks verified), and the one file a gzip, bzip2 or xz file holds is read as that file (plugin.Splitter) within the member limits, counted on the bytes it gives (media.CopyPacked); a mailbox (application/mbox, by its first From line and header fields) is listed by the mbox parser of parse-mail, 100 messages a page, and a message is read as an .eml by its number or full subject (member; 3/report.pdf for its attachment); a parser may read fewer pages a part than asked, its Span setting the parts' width. With the PDF forms slice (2026-12-04), the pdf parser reads a filled-in form's fields, a page's comments with their replies, the text its marks cover, and its links, as blocks beside the page (media.Block.Aside, which a page read again from its image keeps), and lists the files a PDF holds, each read by name through plugin.Unpacker like an email's attachments, under the same bomb and depth limits; the listing, names and limits are shared in pkg/media (PDF forms). With block positions and chunks (2026-12-05), media.v1 blocks carry box (x, y, width, height from the page's top-left corner, in points on a PDF page and pixels on an image) and a table's cell_boxes, from the PDF text layer, from local OCR (its worker sends paragraph_boxes and an item's box and cells) and, for a scanned page, moved onto the page in points; merged blocks get the union of their boxes, a block running onto later pages keeps its first page's; and media.Chunks cuts a document into chunks for retrieval (orquelo media parse --chunks). With RAR (2026-12-05), parse-archive lists and reads RAR 5 and RAR 1.5–4.x archives (application/vnd.rar, by their signatures; pkg/media/rar, its decoders ported from nwaples/rardecode, BSD-2-Clause): stored members, RAR 5 LZ with its delta, E8, E8E9 and ARM filters, RAR 2.9–4.x LZ and PPMd with their standard filters, and solid archives, a member decoded after those before it, its CRC32 checked, under the same bomb and depth limits; a volume lists what it holds and says the other volumes are needed, and members split across volumes, encrypted members, links and RAR 1.5–2.0 methods are listed but not read; an archive with encrypted headers cannot be listed, and a damaged one is media.malformed. With Outlook data files (2026-12-05), pkg/media/pst reads PST and OST files as [MS-PST] publishes them, at their offsets with bounded caches: ANSI, Unicode and 4 KiB-page OST files, the permute and cyclic encodings, the node and block B-trees, data and subnode trees, heaps, property and table contexts, the message store, folders, items, recipients, attachments, attached messages and named properties; the pst parser of parse-mail (typed by the bytes "!BDN") lists the folders with their items, a folder named by its path as the member is listed 100 items a page (a listing that the parser pstfolder reads, typed by its first line), an item named by its folder's path and its number or full subject reads as an .eml (a contact's or an appointment's fields first; Inbox/3/report.pdf for its attachment), and a subfolder's name wins over a subject; a password-protected file is media.encrypted and lists nothing, a damaged or truncated one media.malformed. With selectable speech models (2026-12-05, local speech section 4a), media.speech chooses Whisper small (shipped, the default) or whisper-large-v3-turbo, which downloads once, on first use, into <state_dir>/deps/parse-speech (pinned URLs and SHA-256, resumed, a deadline per try, the directory appearing only whole; package internal/download): the one case where a parse downloads anything, a model the operator chose; a parser's manifest lists its models (plugin.ParserSpec.Models) and an unknown name is refused at load. SenseVoice is not offered: its weight licence (FunASR Model License v1.1) is not clearly permissive. With Hangul documents (2026-12-05), pkg/media/hwp, written from the specifications Hancom publishes for open use (HWP 5.0, OWPML / KS X 6101), reads HWP 5.x (application/x-hwp, a compound file whose FileHeader stream names it) and HWPX (application/hwp+zip, a ZIP package) as the parsers hwp and hwpx of parse-office, each typed by its bytes: paragraphs, headings by outline level, numbered and bulleted items, tables with a merged cell read once, footnotes and endnotes, hidden comments, running headers and footers once, title and author, and pictures as figures (plugin.Figurer); a password-protected, distribution or DRM document is refused with media.encrypted, a damaged one with media.malformed naming HWP or HWPX (a compound file or ZIP whose directory does not read is typed by an HWP FileHeader in it or by the mimetype entry it starts with); not built: equations, charts, OLE objects and HWP 3.x. With XPS (2026-12-05), XPS and OpenXPS documents (application/vnd.ms-xpsdocument, application/oxps), told by the fixed document sequence of their package whatever their name, are read by the xps parser of parse-office through pkg/media/xps, written from XPS 1.0 and ECMA-388: each page's glyphs, from their Unicode strings or from their glyph indices through the embedded font's cmap, obfuscated fonts unlocked, laid out as a PDF's pages are (pdftext.Lay: reading order by position, columns, paragraphs, headings, pages and parts), the images the pages paint as figures, the outline of the document structure and the core properties; a page whose glyphs a font left unread is kept with a note naming the font, and a damaged package is media.malformed. With vertical text (2026-12-05), local OCR reads Chinese and Japanese set vertically column by column, right to left and each top to bottom, reading each column's cells again for the marks vertical setting turns or moves and for small kana, ruby left out; a page mixing such columns with horizontal headings and captions reads each block in its own direction (local OCR). With DjVu (2026-12-05), pkg/media/djvu reads DjVu documents as the DjVu3 Specification publishes them: the IFF container, single-page, bundled and indirect documents, each page's hidden text layer, the outline and the metadata annotation, and draws a page from its JB2 mask (jb2, with shared dictionaries) and IW44 layers (iw44) over the ZP-coder and BZZ (zp); the djvu parser of parse-djvu (typed application/x-djvu by the bytes "AT&TFORM" and DJVU or DJVM, whatever the name) reads pages and parts as the PDF parser does, a text layer as an OCR layer the Host checks, a page without one drawn (plugin.PageImager) and read from its image; an indirect document's files are opened beside it through media.Input.Beside, which only orquelo media parse sets, each missing one named; a damaged page is named and the others read, a document with none readable media.malformed. With charts (2026-12-05), a native chart of a DOCX, PPTX or XLSX file (a DrawingML chart part, or a chartex part) reads as one table where it stands: its categories, then a column per series, from the values the part caches, in their number format, marked by the optional media.v1 field chart (media.Block.Chart: its kind in plain words, title, axis titles and name) and rendered after a line naming them; a damaged or missing part is named in a note and the rest reads. Where an image model is configured, a chart that is only a picture (an image file, a scanned page, and the first 8 figures of each parse, asked with media.WantChart) is read by it into such a table marked estimated, after a note saying its values are estimated; without one a picture stays a figure (charts).

Context

A file reaches the model only when the model takes its kind natively; every other file becomes a one-line note, so a model cannot read a DOCX, a spreadsheet or a web page sent as a file, and a text-only model cannot read a PDF. The owner asked for one framework, used by the Host and by plugins, that gives the model structured input only where the model lacks the ability, with parsers written natively in Go.

Decision

  1. A Host service owns the mechanism. internal/host/media sniffs a file's type from its content, applies the guards, chooses a parser, runs it under a deadline, caches the result and renders it. It holds no format knowledge: formats belong to parsers, choices to configuration (media: {allow, inline_bytes, max_bytes}).
  2. Parsers are plugins of the role parser. A parser declares in its manifest which types it accepts and what it produces, and implements plugin.Parser: bytes by position in, a media.v1 Document out (pkg/media). The first parsers are builtin and native (office, html, pdf, image). Builtin parsers get no rights other plugins lack; they are available without an instance, as the Host's defaults, and media.allow narrows them.
  3. Parse only what the model cannot take, and render at the model boundary. When a model request is prepared (prepareParts), a part whose kind the model declares is sent natively, as before; any other part is replaced by the rendering of its parse, an <orq:file> element whose body is untrusted Markdown. A small result goes inline in full; a larger one gives the outline, the first part and a [more] line. Kinds no model takes (Office, HTML, CSV, EPUB) are parsed as soon as the file arrives, so the first step does not wait.
  4. Failures are results. An empty, corrupt, encrypted, oversized or unknown file, or a decompression bomb, gives a Document with a stable code (media.*) and one sentence the model can relay; the run and the other files go on.
  5. Results are cached per user by content hash and parser version (the owner's decision), and expire with the user's last artifact of that content.
  6. Tools never parse (S2): read reads text only, and the media tool chooses a file and a range and waits for its parse; plugins that want data call Caller.Parse.

Consequences

  • ◆New public contract: pkg/media (media.v1), plugin.Parser, the manifest field parsers and the role parser. Process and third-party parsers need the parser protocol of S2; until then only builtin parsers run.
  • ◆A model that takes no files gets readable content instead of a note; a model that takes a kind is unaffected, so no request grows where the model could already read the file.
  • ◆The parse cache adds a table (media_parses), cleaned with artifacts.
  • ◆pkg/inert, the escaping of untrusted text, moves out of the agent plugin, as both the agent and the Host now use it.
  • ◆box and cell_boxes (2026-12-05) are optional fields added to media.v1 without a new version: a consumer that ignores them reads as before, the Markdown a model reads never shows them, a parse cached before them has none, and a process parser may send them (validated: finite, no negative size).
  • ◆chart (2026-12-05) is an optional field of a table block added to media.v1 without a new version, like box: a consumer that ignores it reads the table as before, the Markdown shows it as one line above the table, a parse cached before it has none, and a process parser may send it (validated: only on a table, with a type, in UTF-8).