# File Upload SDK Framework-independent browser and native file/source lifecycle management. Sites declare contracts and render snapshots; this package owns transport, storage, identity checks, confirmations, deletion, reconciliation and workflow recovery. Public contract: https://file-upload-sdk.pages.dev/example. The Pages example is static documentation; product Workers still authorize requests and own server data. No API keys or session tokens enter local storage. ## Managed selections ```js import { createFileManager } from '@agentcore/file-upload'; const manager = createFileManager(config); const unsubscribe = manager.subscribe(snapshot => render(snapshot)); await manager.restore(); await manager.addFiles(selectedFiles); await manager.addLinks([{ kind: 'web', url: 'https://example.org/article' }]); await manager.markPending(); // Persist explicit intent before sign-in/navigation. await manager.run(verifiedAccountId); // Also: remove(id, verifiedAccountId), retry(id, verifiedAccountId), // reconcile(verifiedAccountId), confirmPartial(), cancelPartial(), cancel(), dispose(). ``` `config` declares storage (`memory` or `indexeddb`), namespace/lock, admitted kinds, MIME/URL allowlists, file/total/count limits, request ID prefix, optional image normalization, public auth-controller subscription, messages and HTTP operations. No site-provided callbacks decide mutation outcomes or recovery. Each operation declares a same-origin path, method, bounded deadline and response size. Request bodies support JSON, multipart or raw bytes. `{$ref:'contextId'}` selects an operation parameter; `{$template:'Item {draftId}'}` formats text. Response descriptors select `result`, validate consumed fields with `schema`, check envelope `success` and identity `matches`, then optionally `projection` renames fields. Unknown fields are not consumed. Missing required values fail. Multipart operations also accept an ordered array of `{name,value,filename?}` parts, preserving repeated field names and original file bytes. A native `FormData` can be passed through a `{$ref:...}` descriptor. `{$json:descriptor}` serializes a resolved value for a multipart JSON field; ordinary `$ref` values are never implicitly JSON-encoded. Configure `successStatus:202` for a job admission rather than treating acceptance as completed processing. `headerMatches` checks configured response headers before accepting either JSON or binary responses. Schemas can bound string lengths and array counts, and enforce finite numeric values, integer byte counts and numeric ranges. These checks complement response byte limits and exact request correlation. Operations: create/verify a context, complete source lists, imports by kind, download, remove, prepare-one, preparation report, and generation. Binary reads return `{blob,headers}`. Generation projects its proof into `{fingerprint}`; preparation reports contain `{extractions:[{sourceId,fingerprint}]}`. The SDK checks exact source IDs and SHA-256 of sorted unique preparation fingerprints before clearing a selection. It validates again after generation. The complete deployed-product configuration is maintained in ../capyrecap-website/src/lib/file-manager-config.ts. Keep new products declarative; never copy SDK state machines into their components. ## Ownership and recovery Sources retain local IDs, original files/URLs, optional normalized upload files, SHA-256/URL identities, server receipts and `pending/importing/imported/failed/uncertain` states. Drafts retain revision, owner, context and workflow progress. Every mutation rereads under its configured Web Lock; unavailable IndexedDB/Web Locks fail visibly. Memory-only selections need no browser persistence. The SDK queues file batches, reports individual rejection reasons and retains a batch in memory when persistence fails. Resume it explicitly with `retry()`. Partial processing requires `confirmPartial()`, no uncertain sources, and at least one confirmed receipt. A changed selection invalidates confirmation. Transport cancellation, timeout, HTTP failure or malformed success never proves absence of a server write. Only an explicitly configured, contract-proven `rejectedBeforeWrite` tuple does. Otherwise reconcile through complete owned lists and downloaded byte hashes/exact URLs; never match filenames or request IDs. A failed or ambiguous read preserves uncertainty. No automatic mutation replay. Imported file removal verifies ownership, then deletes the exact server ID. A lost reply is resolved by a complete server list; failed verification keeps the receipt. Local removal occurs after confirmed deletion/absence only. A local persistence failure can be retried without uploading or deleting an unrelated file. `restore()` never starts uploads or generation. `markPending()` records the user's explicit intent. `run()` checkpoints context creation before sending; unknown creation cannot silently create another context. Confirmed imports survive failed preparation/generation. Account changes cancel protected operations when an auth controller subscription is configured; ownership remains enforced server-side. ## Draft storage Only schema version 3 is supported. Reading an older draft deletes it and returns an empty store. Current drafts retain validated source bytes, ownership, receipts and revision checks. There is no conversion of older schemas or field names. ## Streaming transfer responses An operation may declare `response:'sse'` and an `events` descriptor with `maxFrameBytes`, `progressSchema`, `identityField`, `sequenceField`, `monotonicFields` and optional `progressMatches`. The descriptor validates consumed progress fields; product configuration owns its schema and identity constraints. Requests use fetch with `Accept: text/event-stream`, including multipart bodies, cookie credentials and the existing request ID. The stream contains UTF-8 `storage.transfer` events with IDs `:`, then a separate `result` event carrying the ordinary correlated product success envelope, or an `error` event carrying `{ok:false,rid,status,error:{code,message,category,retryable}}`. Sequence numbers must increase within one operation; configured counters cannot decrease. Frames and total response bytes are bounded separately. A partial frame, missing result, wrong correlation, changed operation, invalid schema or data following the result fails the request. LF and CRLF framing are accepted. Storage progress, including Storage success, never substitutes for the product receipt. The result passes the same projection, schema and proof checks as JSON. Progress is delivered incrementally through the request progress callback. Managed source imports also expose the validated event in `snapshot.progress.transfer`; this nested snapshot is detached from SDK state before presentation. With `events.clientIdentity:true`, the SDK allocates `{operationId,rid}` and checkpoints them together with `state:'importing'` before invoking fetch. Supply the UUID through the operation descriptor, for example `headers:{'X-Storage-Operation-Id':{$ref:'source.transfer.operationId'}}`. The request uses the stored RID, and received events must match both identities. Without client allocation, the first validated event checkpoints this pair before accepting subsequent events or the product receipt. Later samples with the same identity do not rewrite IndexedDB. Reloading and recovering an interrupted import retain this identity. An empty file list does not prove that an uncertain write has stopped; the source remains uncertain and cannot be resent. Progress callbacks may return promises; stream consumption waits for them within the original request deadline. This preserves the checkpoint ordering. Client allocation retains identity even when the connection fails before the first response/event. The other mode starts at the first received event. Only a configured, correlated pre-write rejection clears the unused local identity and permits an explicit retry with a fresh UUID. Missing tracking reads never grant retry permission. Stateless source clients allocate an ephemeral identity when configured; they do not persist a managed draft. Declare `operations.transfer` as a correlated JSON read with a `snapshot` result (nullable while the first persisted sample is pending), and bind its response operation ID to `transfer.operationId` in `matches`. `readTransfer(sourceId, accountId)` performs one owner-bound read under the draft lock. It validates the snapshot against the import event schema, original operation/RID, configured identity matches and monotonic counters. `snapshot.transferReadings[sourceId]` contains a detached reading; it does not persist progress samples or change the source import state. Reconciliation also performs this read when configured. Missing, foreign, malformed or regressive evidence fails visibly. Storage success never marks the file imported: only the usual metadata/byte reconciliation can. Declare `operations.transferStream` as `response:"sse"` with `events.tracking:{operationId:{$ref:"transfer.operationId"},rid:{$ref:"transfer.rid"},stateField:"status",closedStates:["succeeded","failed","cancelled","uncertain"]}`. Its progress schema, identity, sequence and monotonic fields use the same canonical snapshot contract as the upload. `watchTransfer(sourceId,accountId)` subscribes explicitly using the saved original pair; HTTP/error correlation uses the new read request ID. `snapshot.watchingTransferId` identifies the active subscription. `cancel()`, disposal and account changes stop notification delivery. There is no automatic reconnect or upload replay; call `watchTransfer` again explicitly. Counter regressions and changed equal-sequence snapshots across reads/subscriptions are rejected. A closed tracking stream returns its final snapshot, never a product import receipt. Native and browser drafts from older schema versions are discarded without conversion. The original absolute timeout covers request and stream consumption. Timeout, cancellation or malformed data detaches the client stream without waiting for stuck cancellation cleanup; it never automatically repeats the upload or reconnects. A streamed error cannot prove the upload was rejected before writing. Server authorization, native IO ownership and metadata completion remain product-owned. This transport capability requires an implemented product relay. ## Stateless and transient requests `upload(options)` remains the bounded multipart/raw XHR primitive for consumers requiring byte progress only. It never interprets 100% sent as persisted success. `createContractClient(prefix, getSignal)` handles configured JSON/blob requests, correlation, schemas, deadlines and cleanup. It is the upload-only/transient mode: no local draft, deletion endpoint or persistent server resource is required. `createSourceClient(config)` shares admission and image normalization with managed selections. Its `prepare(context, progress, signal)` sequences per-source analysis and checks the final report. `generate(context, progress, signal)` also verifies the generation fingerprint and rereads the complete source set. These stateless actions are suitable for existing server contexts and one-shot covers; they do not persist local recovery receipts or automatically resend mutations. Durable selections use `createFileManager`. URL admission can declare permitted hosts and identifier selectors (`query`, `pathPrefix`, `segment`, `hosts`) with an `identityPattern`; products never implement their own video-link parser. `file-upload-sdk/preview` exports `createPreviewLoader(config)`. It owns preview scheduling, PDF/image rasterization, byte transport and resource cleanup. PDF.js is an optional peer; importing the core does not load it. Local originals remain untouched; preview endpoints must not persist the preview as an imported source. `FileManagerError` carries code, status, operation and requestId. Source snapshots also expose safe display errors, imported/excluded sources, removable/retryable IDs, partial confirmation, queued files and truthful phase/byte progress. `UploadError` retains its transport-only format. No tokens, file contents or transcripts appear in SDK error diagnostics. ## Asynchronous processing `createProcessingClient(config)` handles multipart admission and asynchronous processing without requiring preparation or generation fingerprints. Its configuration declares create/read/remove/download operations, input fields, file limits, status values, output identities and the server's idempotency contract. The SDK preserves original bytes; it does not render or modify a Fabric canvas. Fabric exports or selected original files are ordinary inputs. ```js const jobs = createProcessingClient(config); const receipt = await jobs.run({ fields: {capability_id: modelId, catalog_type: category, params}, files: [{field: 'input', file: originalFile}], }, {ownerId: accountId, signal, onProgress, onStatus}); const output = await jobs.download(receipt.outputs[0].url, {ownerId: accountId}); // restore(ownerId), retry(checkpointId, options), remove(checkpointId, options) // subscribe(listener), cancel(), dispose() ``` Checkpoints use a separate version-1 store in configured memory or IndexedDB. IndexedDB requires a named database and Web Lock namespace. Each input fingerprint has its own lock: distinct files may run concurrently; the same pending request cannot be submitted by two tabs. Checkpoints retain the owner, stable UUID, declared fields, original files and filenames, state and receipts. Authentication credentials are supplied only through ephemeral options and never saved. An auth-controller subscription cancels protected work on account change. The SDK saves before sending. A lost admission response triggers an owned read for that UUID; a matching receipt resumes polling without another POST. `run()` reuses unfinished identical inputs, including after reload. `restore()` reads local checkpoints without network requests or automatic processing. Explicit `retry()` may replay an unacknowledged admission only when a correlated, validated error matches the configured absence status and code, and the server guarantees atomic `same-id-and-body` replay. Previously accepted or expired jobs are never recreated by this mechanism. A failed read preserves uncertainty. `rejectedBeforeWrite` declares exact status/code pairs whose backend contract guarantees rejection before admission. Only a validated, correlated error may mark a checkpoint `rejected`; a generic HTTP status never suffices. Explicit retry retains original bytes and UUID. Other failure responses remain uncertain. Credential descriptors use `credentials.` and cannot replace checkpoint identifiers, multipart parts or saved input fields. Success requires a terminal receipt with exact job identity, unique output slots, job-bound output paths and available outputs. Downloads reread the owned terminal receipt and check the selected output path and returned MIME type. Reads and binary bodies have independent bounds within the total processing deadline. Failures and cancellation retain checkpoints. Deletion clears the local record only after a configured deletion proof or a verified server absence. Server completion and browser delivery are separate. Snapshots expose `delivered` and `deliveredSlots`; a completed job whose outputs were not delivered is reused by the next identical `run()`, including after reload. Successful, nonempty, MIME-verified downloads atomically checkpoint each slot. Only delivery of every reserved output permits a fresh identical run. JSON-only jobs complete delivery with their validated terminal receipt. Cancellation or account change prevents a late result from being published. Presentation callbacks receive independent snapshots and cannot modify recovery proofs. Throwing subscribers and status callbacks are isolated individually; they cannot change committed state, stop healthy observers, or turn a confirmed server result into a processing failure. Related product: ../editgator-website/src/features/processing-upload-config.js owns routes, limits and proofs; processing-job-api.js owns account activation, presentation errors and conversion to existing tool result shapes. The private ../workers/editgator/editgator-api/ owns authorization, credit reservation, idempotent admission, queued execution and artifact storage. Browser-only Fabric, image, PDF, audio and video capabilities remain local and create no remote jobs. ## Request-addressed assets `createAssetClient(config)` manages original files that become reusable stored references, without starting a processing job. `upload(file, fields, options)` persists original bytes before admission and returns only after reading back the stored bytes and checking their size. Each new upload receives an opaque UUID; retrying a checkpoint retains that same UUID. Identical new uploads create separate references. Canvas import remains local; the host invokes upload only for a save or an explicit remote action. Declare `contentTypes` as MIME-to-extension mappings, `maxFileBytes`, a total `timeoutMs`, bounded `inputSchema`, independent IndexedDB database/Web Lock, authentication subscription, and `operations.create/lookup/download/remove`. Every operation uses the same response/schema/identity descriptors as the other SDK clients. The operation context contains `ownerId`, `id`, original `file`, `bytes`, `contentType`, `extension`, `fields`, and runtime `credentials`. The declarative `receipt` is resolved from those verified values after the owned lookup and binary read have succeeded. Lookup results are available as `stored.` for the binary-read request and receipt, so an API may issue opaque references without the browser constructing storage addresses. Saved receipt values are available as `receipt.` for configured deletion. ```js import {createAssetClient} from '@agentcore/file-upload'; const assets = createAssetClient(assetConfig); const receipt = await assets.upload(originalFile, {canvasId}, { ownerId: verifiedAccountId, onProgress: renderProgress, }); // restore(ownerId) reads local state without making requests. // retry(checkpointId, options) explicitly resumes uncertain uploads. // remove(checkpointId, options) confirms server deletion/detachment first. // cancel()/dispose() abort active operations and fence account changes. ``` A lost upload response triggers an owned lookup and file-size verification, never a second automatic upload. Unverified writes remain recoverable after reload. `idempotency.replay:'same-request-id'` permits explicit retry only after a correlated canonical absence with the configured code/status. Declare this guarantee only when the backend retains one immutable owner-bound address for the same upload UUID. New uploads never deduplicate by content. Give asset and processing clients separate storage databases. Authentication credentials are never saved. CoffeeFrame maintains two declarative asset configurations: `../coffeeframe-website/src/services/canvas-upload-config.js` owns persistent, authenticated canvas asset references; `../coffeeframe-website/src/services/chat-upload-config.js` owns chat attachments, including memory-only guest checkpoints and ephemeral credential headers. ## Cancellation and object ownership Processing and asset operations register cancellation before file reads or SHA-256 preparation. An already aborted signal prevents preparation; cancellation, disposal and account changes prevent late persistence or upload admission. Web Crypto work already started may finish, but its result cannot admit a request. Preview lifecycle waits reject on cancellation; PDF destruction never holds the preview queue open, and late image bitmaps are reclaimed. Transport failures abort owned requests and cancel response bodies, including unread header-invalid bodies and responses arriving after cancellation. Cleanup is nonblocking and preserves the original failure. Header descriptor resolution happens before timers and caller listeners are allocated. Memory and IndexedDB checkpoint reads expose detached data. Restored receipts, output-slot arrays, source drafts, and nested input fields can be edited by the caller without altering saved recovery or delivery proof. Blob/File bytes remain immutable; changing stored state requires a validated store write. File-byte limits are separate from product-owned multipart wire ceilings. CapyRecap admits 25 MiB documents and 10 MiB images, with 64 KiB additional metadata/framing capacity. EditGator admits 25 MiB aggregate inputs, with 2 MiB additional metadata/framing capacity for bounded filenames and parameters. Neither allowance increases admitted file or artifact sizes. ## Publication and validation commands Maintain plain JavaScript source and TypeScript declarations; no local build. Storage suites use the development-only `fake-indexeddb` fixture. Run packaged `tests/*.test.js` remotely through all three browser consumers: | Consumer | Configuration | Remote Full gate | | --- | --- | --- | | CapyRecap | `src/lib/file-manager-config.ts` | `scripts/cloudflare-full-check.mjs` | | EditGator | `src/features/processing-upload-config.js` | `scripts/check-full.mjs` | | CoffeeFrame | `src/services/canvas-upload-config.js`, `src/services/chat-upload-config.js` | `scripts/check-full.mjs` | Publish each consumer from its canonical repository with exactly one `[cloudflare:full]` marker. Its native Pages build executes the installed immutable SDK suites alongside product integration checks. Browser acceptance also checks real IndexedDB, reloads, multiple tabs and interrupted network operations. Pack a new immutable version with `npm pack --ignore-scripts`, update the consumers' archives/dependencies/lockfiles and checksums, and publish each owning repository with `github-publish-main`. Existing sites pinned to 1.0.0 are unaffected. Publication on canonical `main` triggers the remote Pages build. Verify its exact commit, terminal deployment result and GET /example. Server APIs are unchanged by this SDK publication. ## Native entrypoint (2.3.0) `file-upload-sdk/native` exports `createNativeFileManager(config, adapters)` and TypeScript declarations without DOM, IndexedDB or browser preview imports. Expo consumers provide SQLite persistence, sandboxed file descriptors, SHA-256, verified account identity and bounded transport adapters. No credentials are stored in drafts. The existing workflow engine owns import checkpoints, content reconciliation, exact source sets, preparation and generation proofs. `config.namespace` identifies the storage slot and serializes mutations across manager instances in the same JavaScript runtime. Configure `maxSources`, `maxTotalBytes`, admitted `kinds` and operation names: `create`, `findContext`, `verify`, `upload`, `ingest`, `list`, `fingerprint`, `prepare`, `plan`. Adapters implement `storage.read/write/clear`, `id`, `accountId`, `sha256`, `transport`, `confirmedRejection`, and `releaseFiles`; see src/native.d.ts. Transport maps owning product DTOs only; recovery decisions remain SDK-owned. Native file descriptors contain `uri`, `name`, `size`, `type`; source fingerprints are SHA-256 of original bytes or canonical URLs. Admission requires sandboxed `file://` descriptors, configured MIME/byte/count limits and permitted URLs. Lost upload responses are reconciled against owned remote sources and downloaded byte hashes. Filenames are not content evidence. An absent uncertain source needs an explicit subsequent retry. Ambiguous matches remain blocked. `load()` restores version-3 drafts. `edit(change)` validates and persists a selection, then releases removed local files. Imported receipts cannot be silently removed. `run(accountId, progress)` imports, prepares and generates; `{verifyOnly: true}` reconciles without new imports, and `{importOnly:true}` stops after confirmed imports for account assets. `recoverContext(accountId)` uses the declared read-only lookup after uncertain creation, without automatically repeating creation. `discard()` refuses uncertain writes and releases confirmed local drafts only. SDK identity checks surround transport and checkpoints. Native previews belong to maintained native PDF/image components in the consuming app. `tests/native.test.js` is included in the immutable package for the authorized CapyRecap EAS/Unikraft quality gate. These tests are prepared, not executed locally. The immutable native 2.3.0 archive is retained for CapyRecap. SDK documentation and contract tests publish independently through Cloudflare Pages. Browser audit corrections are released in a new immutable 2.3.2 package for the three websites. Do not overwrite an archive once published to a consumer. ## Pages publication commands From this repository, publish canonical main with `github-publish-main "message"`. The shared launcher at scripts/project-command.mjs owns build admission and Fast/Full selection. Pages runs `npm run build:cloudflare`; a single `[cloudflare:full]` commit marker additionally runs the guarded `npm run check:full` after generating the same output. Local dev/build/test/deploy aliases are blocked. `publication.json` requires verification of the exact deployed commit. Install Git hooks with `git config core.hooksPath git-hooks`. No install lifecycle hook is added to packaged SDK consumers. Preserve every previously published archive; update dependency pins only to a newly packed, verified version. Raw binary part operations may declare `method:"PUT"` and `raw:{$ref:"part"}` with their native Content-Type and idempotency headers. They use fetch with the same bounded response, RID/schema checks and absolute cancellation deadline. There is no XHR fallback, automatic retry or invented upload progress. Complete multipart file requests keep their POST contract. Existing account spaces can declare `operations.context` as a read-only, correlated operation returning `{id}` with an owner match. `run(accountId,{importOnly:true})` imports and keeps the confirmed managed receipt without project creation or generation. `operations.reconcile` can address the exact product receipt by the saved transfer identity; validate its ID/type in the descriptor. Recovery still downloads and hashes the confirmed product bytes. It never substitutes a Storage snapshot for the receipt, lists unrelated candidates, or retries the mutation. Explicit `reconciliationNotFound` entries require a verified correlated error with exact path/status/code; absence leaves an uncertain source uncertain. No old-state migration is provided. `releaseConfirmed(sourceId,accountId)` releases an imported local checkpoint after verifying the current owner context. It never deletes remote media, sends another upload, or releases a pending/failed/uncertain receipt. Use it to remove completed imports from a managed queue. Blob operations may declare `downloadTracking: {operationIdHeader, operation}`. The required header supplies the admitted UUID; `operation` is a declarative SSE read using `transfer.operationId` and the original `transfer.rid` in its context. The progress callback receives `{transferIdentity:{operationId,rid}}` at headers, then `{transfer:snapshot}` or `{transferTrackingError:{code}}`. No binary replay is performed. EOF, cancellation and the binary deadline detach notifications. Tracking failures are separate from binary delivery. This transport does not persist a download checkpoint or automatically reconnect. The initial download identity callback is bounded by the binary request abort and deadline, including asynchronous callbacks that remain pending. Abandoning this callback cancels the unread binary response and prevents tracking admission. File-manager reconciliation publishes `snapshot.downloadReading` while checking owned remote bytes: fileId, admitted identity, measured snapshot and separate tracking error. These samples never replace an upload receipt. Action completion, Stop or replaced authentication discards obsolete delivery; samples are transient. Managed sources retain separate `downloadTransfers` checkpoints under their verified draft account/context: fileId, admitted UUID/RID, and validated consumed snapshot fields. At most 64 read identities are retained per source. Admission is checkpointed before subscribing; interrupted reads keep their evidence across restore without another binary request. This storage does not itself reconnect tracking or authorize replay, and does not replace source.transfer upload proof. `watchDownload(sourceId, operationId, accountId)` explicitly revalidates the configured project ownership before reading the saved UUID/RID over SSE. Saved measurements seed monotonic checks across connections; changed confirmed outcomes and lost observations are rejected. It never calls the binary download or import operation. `dismissDownload` removes only the local checkpoint for its verified draft owner. Neither restoration nor dismissal replays or deletes server bytes. Asset operation context exposes `assetId` for the stored object and `id` for the upload request. New uploads use the same UUID for both. Existing version-1 asset checkpoints recover their saved object identifier without calculating an array or file digest. Confirmed recovery preserves the original file and receipt and replaces obsolete checkpoint fields with `objectId`. Explicit replay after verified absence uses the request UUID for the new object.