Skip to content

backends: read PDF and generic attachment contents with bounded fallbacks #3154

Closed

Description

@schlessera

Out of scope

No promise to decode every binary, OCR/decryption or external conversion service, archive expansion, uploaded-code execution, new public reader/plugin registry or file-picker implementation. Do not rely on a backend's native PDF support as the baseline. Attachment admission/storage policy belongs to #3153; interaction choices belong to #3155.

Context

Part of #3150.

Blocked by #3151
Blocked by #3153

Generic staging is not content access: PDF in EXTENSION_BY_TYPE (packages/ui-server/src/share/staging.ts:91-107) supplies a stored extension, not an extractor. withTrackFiles (packages/ui-server/src/tracks/read.ts:69-72) provides track-specific context only. The pi read_file implementation (packages/ui-backend-pi/src/tools.ts, read_file) decodes bytes as UTF-8; that does not establish PDF content access. #3151 must source-qualify the actual library/API/runtime before implementation rather than assume backend parity.

The maintainer now selects shared local extraction and reference-first/on-demand PDF/text delivery. This supersedes the October 29 deferral for those strategy/context questions; concrete bounded implementation design remains #3151's deliverable.

Decisions (maintainer, 2026-11-02)

  • Baseline A: one shared bounded local deterministic text/PDF extraction path serves both first-party backends. Native capabilities may be verified supplements, not the primary baseline or a prerequisite for reading a real text-bearing PDF. Reject native-reader-first/shared-fallback as the primary strategy.
  • Context A: for PDF/text, give the agent authorized file references and minimal useful metadata at send, then add relevant contents through an explicit on-demand read. Do not automatically inject a full extraction or bounded excerpt merely because a file was uploaded/sent. Reject automatic excerpt injection. Both choices preserve actual filesystem originals for later reads.
  • Preserve established specialized image/validated-track presentation, including the original-file requirement for images; the PDF/text context ruling does not silently remove those existing capabilities.

Scope

Implement the common local baseline, an authorized on-demand reading path for pages/sections, explicit partial/unavailable outcomes and retained provenance. Reuse concrete code/CLI/tool surfaces where suitable. If a new deterministic command is necessary, put execution in code with supported --json/contract classification, not algorithms in a skill. No public reader registration framework is approved.

#3151 must choose source-verified library/runtime/API/licensing and explicit time, memory, input/page/expanded-output/result/context bounds, then reconcile concrete implementation briefs. Those technical choices must remain within approved policy and attachment storage limits; an unavailable reader or exceeded budget gets an honest bounded outcome, not an unapproved external service or silent limit relaxation.

Acceptance criteria

  • A real text-bearing PDF and ordinary UTF-8 file yield a fixture-specific fact through the production original-file read/extraction path on both first-party backends, using keyless provider doubles. Filename/metadata, cached authored answers or native PDF availability alone are insufficient.
  • The provider's initial new message carries only PDF/text references and minimal useful metadata, not automatically injected document text. A subsequent actual read adds the requested content at the new tool/message tail. Capture both backends to prove the fact reaches the provider through the real read result and was absent from the initial injected context.
  • Pages/sections can be read in bounded pieces with explicit location/continuation and partial/truncation semantics. Do not present a clipped excerpt as the whole document. The same original remains readable/referenceable in later conversation turns without modifying earlier provider history.
  • A readable text file with an unfamiliar extension and empty/octet-stream MIME works without a new picker filter. Detection is based on actual bytes; validated tracks retain current geometry/partial semantics and image processing remains established. A failed specialized detector may fall through to a valid generic reader under the concrete design, without inventing a valid track or executing content.
  • Distinguish reader unavailable, unsupported/unreadable binary, scanned/encrypted/malformed PDF, processing failure and partial/truncated content. Capability/upload readiness is not proof that the agent read the contents; an actual successful read may be recorded truthfully. No OCR, decryption, uploaded-code execution or external converter is implicitly added.
  • Retain byte-identical filesystem originals under ui-server: admit generic chat files and retain specialized content routing #3153's authenticated draft/chat ownership, quotas and cleanup protection. Revalidate exact references and authority before reads; reject stale/altered/cross-owner/symlink/outside-store inputs. Extracted text and file-provided instructions remain untrusted; recipient/taint restrictions still apply.
  • Enforce ui-server: design generic attachment intake, routing and content access #3151's explicit extraction time/memory/page/input/expanded-output/result/provider-context bounds and cancellation through the real path. Derived artifacts share the bounded attachment pool and never substitute for original ownership. Limit failures remain partial/unavailable as specified, and do not silently discard originals or broaden egress.
  • Tools/system definitions stay byte-identical within a provider session. Install any required reader surface at a stable session boundary; do not add/remove tools when an upload arrives. New references/read results enter only the new tail. Internal diagnostics, quota receipts and status labels remain internal/UI data, not provider context.
  • A concrete additional fixture reader can be added without changing the picker or creating a public registry; document the code/dispatcher steps. Verify dependencies/APIs/licenses from installed/upstream source, and load the release skill before any actual package/dependency/shipped-content change.
  • Record the baseline/context choices and rejected alternatives in the attachment design/decision guidance delivered under ui-server: design generic attachment intake, routing and content access #3151, and update authoritative contract docs/runtime schemas/API reports for any supported CLI/tool/result/capability addition. Preserve old clients and source behavior outside the new generic path.

Verification

Offline deterministic Odysseus PDF/text/binary fixtures, original-file/digest checks and keyless production read/extraction tests for both backends. Loopback provider captures assert initial reference-only PDF/text context, actual tool-read facts and later-turn rereads, with no live provider traffic. Include unknown extensions/MIME, malformed/encrypted/scanned/binary inputs, truncation/continuation, every resource/cancellation guard and rejected reference authority.

Retain a mutation removing the real read that fails the named content fact/capture assertion; restore it. Mutations of output bounds, path/ownership and eager-text injection must fail their intended guards. Run focused suites, both provider-history guards and bun run check:pr --base origin/main. No new dependency or extractor is installed by this decision review.

Contract impact

Any new supported CLI/MCP/backend reader input/result, runtime schema, capability or package API is an additive machine contract unless the concrete design establishes otherwise. Carry contract, CONTRACT-prefixed implementation commits, same-commit authoritative integration-contract updates/API reports and appropriate minor changesets. New generic-path references/read results must preserve provider history. Any additional breaking change requires its own prior ruling. No particular library, public schema signature or release milestone is selected here.

Inherited attachment policies

Approved shared constraints (maintainer, 2026-11-02; #3153)

  • Admission: separate neutral composer-upload endpoint reusing concrete staging internals, with no operational inbox/queue/triage side effects. Existing share/track callers retain their documented behavior; preserve the settled phone Photo library/Camera/unrestricted Files entry points and common processing pipeline.
  • Actual files: every attachment, including images, has a byte-identical uploaded-original filesystem file and authorized stable reference readable from the agent's execution environment. Inline/base64 context, previews or extracted text alone are insufficient. Preserve specialized processing, taint/recipient/permission rules and honest content-access outcomes; a stored binary is not automatically semantically readable.
  • Ownership/lifetime: originals belong to the exact acknowledged draft revision and, after accepted send, the retained conversation. A saved draft including its file bindings survives reload/tab close and normal host restart. Sending retains originals for later agent reads without consuming newer edits or another draft. No automatic filing into canonical brain content. Unacknowledged/legacy data never falsely reads as saved; unresolved sends protect their files. This explicitly amends D52's tab-only staged-track exception for the new generic path.
  • Per-draft/message envelope: 10 attachments total, 25,000,000 original bytes per file and 50,000,000 original bytes combined, including images. Preserve the 65,536-byte text allowance separately and reconcile the old 8,388,608-byte draft ceiling so an eligible original batch can be saved subject to aggregate admission. Original-byte limits do not relax separate image/provider-frame/track-parser bounds or authorize silent omission.
  • Aggregate storage: a configurable host attachment-pool cap, default 1,073,741,824 bytes (1 GiB), covers draft, sent, pending and grace-period attachments. Account materialized originals/derived attachment storage and in-flight reservations under bounded accounting; do not leave an uncharged derivative or pending-file escape. Preserve the 100-live-draft default and 268,435,456-byte host draft sub-limit. Draft storage is a subset of the attachment pool, not an additional 256 MiB on top. Shared physical storage/reference accounting must be explicit. At capacity refuse new work honestly and preserve existing references; no early purge to make room.
  • Cleanup: never-bound uploads have a one-hour window; formerly referenced originals have seven days from authoritative last-reference removal. Saved draft/chat references, active work and unresolved sends protect files. Revalidate ownership, identity and all references immediately before deletion, coordinating rebinding against unlink. Unknown reference state fails closed. Rebinding cancels collection; a later last-reference removal starts a new seven-day interval. Incidental access/mtime does not reset it. Grace-period storage remains charged. No implied Undo feature or permission to delete unrelated canonical/share data.
  • Design/compatibility: ui-server: design generic attachment intake, routing and content access #3151 must turn these settled constraints into exact reference/route/capability schemas, durable ownership/admission accounting, detection/resource bounds and executable proof briefs. Record choices and rejected alternatives in D52/attachment decision guidance and authoritative contract docs. Concrete names and internal implementation details may be chosen within these constraints; a proposal exceeding them requires a new ruling. No release commitment is made.

#3153 is now policy-decided and scoped for implementation, still blocked on #3151's concrete design. This issue retains its own unresolved scope and labels: the epic is never agent-ready, the design spike remains an agent-ready design deliverable, and reader/UI decisions are not approved by propagation of these shared constraints.

2026-11-02 decision reconciliation: consolidated the shared policies, including the configurable 1 GiB attachment pool and unchanged draft sub-limits, and removed superseded open-policy wording from the repeated intermediate supplements. Comments retain the intermediate history. No implementation, proof completion or release commitment is claimed.

Readiness and design dependencies

Both reader-strategy/context policy questions are resolved. Remove needs: decision and add agent-ready because no other needs label remains. Retain blocked on #3151 and #3153: source-qualified bounded design and admission delivery precede implementation/integration. #3155's remaining interaction and visual approval remains independently open.

2026-11-02 decision review: consolidated shared local extraction and reference-first/on-demand PDF/text delivery into checkable criteria, with filesystem originals, inherited quotas/lifetimes and append-only history. No implementation, dependency installation, proof completion or release commitment is claimed.

Activity

  1. added
    type: featA new capability or a change in user-visible behaviour.
    area: ui-serverHono app factory: turn coordinator, auth, session catalog, routes, cron.
    area: backendsAgentBackend implementations and the seam they share.
    blockedWaiting on another issue or an upstream dependency. Say which in the body.
    on Oct 29, 2026
  2. added
    priority: p2Wanted, not scheduled. Pulled in when a milestone has room.
    needs: decisionBlocked on a maintainer or designer ruling, not on code.
    on Oct 29, 2026
  3. schlessera commented on Oct 29, 2026

    @schlessera
    OwnerAuthor

    Decision (maintainer, 2026-10-29): Selected option 1: wait for #3151's verified reading/extraction capability design before selecting backend readers or a deterministic fallback. Neither backend-reader-first nor a shared extraction-first implementation is selected in advance of source-backed evidence.

    #3151 must establish both backends' actual text/PDF capabilities, fallback strategy, partial/unavailable outcomes, extraction/output/context limits and compatibility, then fold them into this brief. Keep #3154 blocked on #3151 and admission #3153, retain needs: decision and keep agent-ready absent. The baseline text-bearing PDF/text outcome and existing image/validated-track behavior remain required. No dependency/library, provider transfer, uploaded-code execution, runtime implementation or release commitment is approved by this deferral.

  4. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Decision reconciliation (maintainer, 2026-11-02): The #3153 review selected a separate neutral composer-upload endpoint reusing staging internals, without operational inbox side effects.

    The maintainer also requires: Every chat attachment, including images, must exist as an actual filesystem file containing the uploaded original bytes, not solely inline/base64 model context, a preview or extracted text. The agent must receive an authorized stable reference that resolves to that file inside its execution environment and can read/refer to it using appropriate tools. Preserve specialized image/track processing; derived provider representations do not replace the retained original. Server-owned identity/ownership and existing sandbox, taint and recipient rules still apply. This does not promise that every binary can be semantically decoded. Retention duration, unsent recovery, send ownership, cleanup and exact resource limits remain separate decisions; filesystem existence alone is not a permanent-filing or saved-draft promise.

    The current body now incorporates this cross-cutting requirement. This propagation does not resolve this issue's other choices, select a retention duration or change its labels/dependencies. No implementation or release commitment is claimed.

  5. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Decision (maintainer, 2026-11-02): Selected A for attachment-original lifetime: draft/chat-owned files rather than automatically filing every upload into canonical brain content.

    Selected A: originals are owned by the draft and, after accepted send, by the conversation. A host-acknowledged exact draft revision, including its filesystem attachment bindings, survives reload/tab close and normal host restart; restore it only for the authorized owner/devices under the existing host/root identity. Merely completing an upload or saving text is not enough to claim the entire draft saved. Accepted send transfers or adds the durable conversation reference without deleting the original when the submitted draft revision is consumed. Later turns can read/reference the same original through an authorized stable filesystem reference. Preserve edited/newer draft revisions and held/uncertain sends: no premature deletion, cross-draft rebinding or automatic resend. Do not automatically file these originals as canonical brain content. A live draft, retained conversation or unresolved accepted-send outcome protects its files from staging TTL cleanup. Removal of an owning reference is not permission to delete files still referenced elsewhere; detailed unreferenced-file cleanup, storage admission and exact limits remain to be specified. Never silently purge referenced files to make room.

    This explicitly amends D52's tab-only staged-track exception for the new generic path. Record the acknowledged-recovery/ownership amendment and alternatives in docs/decisions/design-kit/sessions-and-drafts.md and authoritative contract documentation during implementation; legacy or unacknowledged data must not falsely read as saved.

    The body now contains the shared lifetime choice. Next reconcile upload versus draft/host resource limits and cleanup protection; their exact values/policy are not selected here. Preserve existing labels/dependencies pending the rest of each issue's review. No implementation or release commitment is claimed.

  6. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Decision (maintainer, 2026-11-02): Selected A: expand durable draft attachment capacity to match the existing shared-upload limits rather than constrain generic batches to the old 8 MiB draft ceiling.

    Selected A: align durable draft attachment capacity with the existing shared-upload envelope: at most 10 attachments total, 25,000,000 original bytes per file, and 50,000,000 original bytes combined per draft/message. These are decimal byte limits and include image originals; they are not an extra allowance per file type. Retain the existing 65,536-byte draft text allowance separately, so an otherwise eligible full-size original batch is not unsaveable merely because of the old 8,388,608-byte combined draft ceiling. Update the public draft limit/accounting contract to describe original bytes, text and bounded derived representations accurately. Existing image-transformation/provider-frame and track-parser bounds remain separate; generic admission does not assert that a specialized processor can handle the entire original. Never drop originals or silently claim processed/saved status to fit a lower processing limit. Preserve the existing 100 live draft default and 268,435,456-byte host draft pool limit, charging retained/pending bytes according to explicit bounded accounting. An attachment within per-file/per-draft limits may still be refused when aggregate capacity is full; report the reason and preserve existing referenced content. No increase to host-wide capacity, sent-file retention quota, processing/context budgets or unreferenced-cleanup policy is selected by this upload/draft-envelope ruling.

    The body now incorporates this selected envelope. Reconcile the public draft limit/accounting fields and migration in #3151 and the implementation; do not claim every within-envelope upload is saved if host admission refuses it. The existing draft text/count/host-pool defaults are preserved. Other unresolved policy/design choices and labels remain unchanged; no implementation or release commitment is claimed.

  7. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Decision (maintainer, 2026-11-02): Selected A for unreferenced-original cleanup: one hour for uploads never bound to a draft/chat, and seven days after authoritative removal of the last reference for formerly referenced originals.

    Selected A: never-bound uploads retain the existing one-hour cleanup window; originals that previously had an owning draft/chat reference retain a seven-day grace period starting when the last reference is authoritatively removed. Referenced saved drafts, retained conversations, unresolved sends and active operations protect their files. Lost acknowledgements, ambiguous ownership, unavailable reference state or uncertain cleanup are not proof that a file is unreferenced. Recheck identity, ownership, active work and all references immediately before deletion; coordinate rebinding and cleanup so a live reference cannot race the unlink. If the file becomes referenced again, cancel its unreferenced eligibility; a later last-reference removal starts a new seven-day interval. Do not reset the clock from incidental access or file mtime. No early purge of referenced or still-in-grace originals to admit a new upload. Refuse new storage with an honest reason when necessary. The grace period alone promises no Undo UI or automatic recovery feature, and this ruling does not authorize deleting canonical brain assets or unrelated share/intake stores.

    The body now contains the exact cleanup clocks and safety boundary. Immediate deletion and manual-only cleanup are not selected. Record these semantics in the attachment/D52 decision and authoritative contract during implementation. Other outstanding admission/design choices and labels remain unchanged; no actual deletion or release commitment is claimed.

  8. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Shared policy reconciliation (maintainer, 2026-11-02): The #3153 review is complete. A configurable host attachment pool defaults to 1 GiB across draft/sent/pending/grace attachments; retain the existing 256 MiB/100-draft sub-limits, and never purge protected/in-grace content to admit new work.

    The body now consolidates this with the selected neutral upload route, actual filesystem originals including images, acknowledged draft/chat lifetime, 10/25-MB/50-MB original envelope, one-hour never-bound/seven-day post-last-reference cleanup and required contract/legacy boundaries. #3151 must deliver the concrete reconciled design; #3154/#3155 retain their reader/UI choices and current labels. No implementation, actual cleanup, proof completion or release commitment is claimed.

  9. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Decision (maintainer, 2026-11-02): Selected A for #3154: shared local deterministic text/PDF extraction baseline for both first-party backends, rather than native/backend-reader-first with a shared fallback.

    Selected A: a shared, bounded, local deterministic text/PDF extraction baseline serves both first-party agent backends. Do not make successful text-bearing PDF access depend on a backend's native PDF capability or choose native/backend-reader-first as the primary path. Native capabilities may supplement the common baseline when separately verified and permitted, but may not replace or weaken its both-backend content proof. Retain byte-identical filesystem originals and source provenance under the #3153 ownership/quota/cleanup policies; extracted text/previews are derived artifacts. Preserve existing specialized image and validated-track processing. Distinguish actual readable content, partial/truncated extraction, unavailable capability and unreadable/encrypted/scanned/malformed inputs. No OCR, decryption, uploaded-code execution, archive expansion or external conversion service is approved. Dependency/API/license and bounded resource qualification remain #3151 design work; no particular extraction library or package addition is selected here.

    The body now incorporates the strategy. It supersedes the prior deferral for this branch choice only; automatic versus on-demand PDF/text context delivery remains to be decided, and #3151 still owes concrete bounded resource/reader/result contracts and source-qualified implementation recommendations. Preserve the issue's current labels/dependencies pending its remaining review. No implementation, library selection or release commitment is claimed.

  10. added
    agent-readyContext and acceptance criteria are complete enough for an agent to take this unattended.
    contractTouches the integration contract: CONTRACT: commit, contract doc updated in the same commit.
    and removed
    needs: decisionBlocked on a maintainer or designer ruling, not on code.
    on Nov 2, 2026
  11. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Decision (maintainer, 2026-11-02): Selected A for PDF/text context delivery: send authorized references and minimal metadata first; read relevant contents on demand through the shared local extraction/reading path. Do not inject extracted text automatically at upload/send.

    This completes #3154's policy review with the earlier A shared-local-extraction baseline. Both backends must prove real PDF/text content reads; native PDF support is not the baseline. Originals stay filesystem-readable for later turns under #3153. Preserve existing specialized image/track presentation and distinguish ready-to-attempt-reading from actual content read.

    Tools/system/earlier messages stay unchanged within the provider session; references and newly requested contents enter the new tail only. The body now requires actual read-result/provider captures, bounded page/section continuation, truthful partial/unavailable states, quota/authority guards and failing-first/restored proof.

    #3151 still owes source-qualified library/runtime/API/licensing and concrete resource/schema design under the selected policies; it does not need another ruling to choose ordinary implementation details within them. No particular library, new egress/OCR capability or release commitment is approved.

    Remove needs: decision and add agent-ready; retain blocked on #3151/#3153. Add contract for any supported reader/result/capability surface, with the implementation's required authoritative docs, CONTRACT prefix and changeset. No implementation or new runtime proof is claimed here.

  12. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    #3151 design available for review (PR #3301). Source-qualified reader: pdfjs-dist 6.3.289, Apache-2.0. It is already a workspace dependency and already runs server-side in ui-render-puppeteer. A keyless probe under Bun 1.4.4 extracted the corpus star-chart text, and malformed or non-PDF inputs gave InvalidPDFException. See the capability matrix.

    §7 the design:

    • a child-process extractor with these proposed bounds, to be measured on a 25 MB, 500-page fixture before they are kept:
      • 20 pages and 64 KiB per call;
      • 256 KiB per turn;
      • 30 s wall clock, 20 s CPU;
      • 1 GiB RLIMIT_DATA;
      • 2 concurrent extractors;
    • a host-side text reader;
    • the stable read_attachment bridge tool on both backends, with its outcome vocabulary in §5;
    • no derived cache;
    • the §12 proof brief.

    Labels are unchanged.

  13. schlessera commented on Nov 4, 2026

    @schlessera
    OwnerAuthor

    Unblocked: #3151, #3153 are closed, so scripts/sync-project.ts is removing the blocked label.

  14. removed
    blockedWaiting on another issue or an upstream dependency. Say which in the body.
    on Nov 4, 2026
  15. self-assigned this
    on Nov 4, 2026
  16. schlessera commented on Nov 4, 2026

    @schlessera
    OwnerAuthor

    Claiming for implementation (token claim-3154-4576ec8b). Branch: feat/3154-read-attachment, based on epic/3150-attachments (= main 5c9b23d44). Building the #3151 design §7: the bounded pdf.js extractor child, the host text reader, read_attachment on both backends through the bridge, and attachment_reads. PR will target the epic branch with Refs #3154.

  17. added this to the 0.45.0 milestone on Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

agent-readyContext and acceptance criteria are complete enough for an agent to take this unattended.area: backendsAgentBackend implementations and the seam they share.area: ui-serverHono app factory: turn coordinator, auth, session catalog, routes, cron.contractTouches the integration contract: CONTRACT: commit, contract doc updated in the same commit.priority: p2Wanted, not scheduled. Pulled in when a milestone has room.type: featA new capability or a change in user-visible behaviour.

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions