/** * `export_open_bundle { kit, media? }`: a kit's library in the open formats * other apps read — Books as a Calibre tree with OPDS and a Goodreads CSV, * Films as a Kodi tree with NFOs and a Trakt export — zipped and kept as a * document of the owner's. Music and Podcasts are retired (TABLE DROP 1). * * The tree is the phone's own writer, run here as WASM * (cotton_rules::open_bundle, `open_bundle.lay`): it is handed the kit's live * rows and asks, round by round, what it must know of their media (whether a * key is held, or a playlist's text); answered from R2, it lays every file as * its text or the media key whose bytes it is. Media never enter the WASM: * each key's bytes stream from R2 into the ZIP (src/zip.ts), and the ZIP * streams into R2, its length known before a byte is written. */import { tryRule } from"../../rules/index.ts";import { zipLength, writeZip, typeZipEntry } from"../../zip.ts";import { fail, typeData, typeHandler, typeToolContext } from"../context.ts";import { Table } from"./records/table.ts";import { arriving } from"./records/write.ts";import { openStored, windowFor } from"./window.ts";import { isDeviceSealedKind } from"../../table_files.ts";/** The most an open bundle holds, ZIP and all. */exportconst OPEN_BUNDLE_MAX_BYTES = 2 * 1024 * 1024 * 1024;/** Each kit: its folder, the tables the writer reads (cotton_rules::open_bundle::Kit::tables) and what its rows are called. */exportconst OPEN_BUNDLE_KITS = { books: { root: "Books", tables: ["book", "highlight"], rows: "books" }, films: { root: "Films", tables: ["film", "film_season", "film_episode", "watch"], rows: "films or series" },} asconst;typeKit = keyoftypeof OPEN_BUNDLE_KITS;/** How many media questions are put to R2 at once. */const ASKS_AT_ONCE = 32;/** A playlist read as text is at most this long; past it, it is no playlist. */const PLAYLIST_MAX_BYTES = 8 * 1024 * 1024;interfaceAsk { key: string; read: boolean;}typeEntry = { path: string; text: string } | { path: string; media: string };typeLaid = { asks: Ask[] } | { tree: { entries: Entry[]; missing_media: string[] } };typeHeld = "held" | "missing" | { text: string };const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];/** `7 Nov 2026`: the day an instant falls on in the database's zone. */function dayWords(at: string, zone: string): string {const parts = newIntl.DateTimeFormat("en-US", { timeZone: zone, year: "numeric", month: "numeric", day: "numeric" }).formatToParts(newDate(at));const part = (type: string): number => Number(parts.find((p) => p.type === type)?.value);return`${part("day")} ${MONTHS[part("month") - 1]} ${part("year")}`;}function gigabytes(bytes: number): string {return`${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;}/** A photo or file column's value as its key: a bare key, or `{ ref, name }`. */function keyOf(v: unknown): string | null {if (typeof v === "string" && v.trim()) return v.trim();if (v && typeof v === "object" && typeof (v asData).ref === "string" && (v asData).ref) return (v asData).ref as string;returnnull;}/** Table `id`'s live rows (none in the bin) in the writer's domain form, each media column said as its key. */asyncfunction liveRows(ctx: ToolContext, id: string): Promise<Data[]> {const def = ctx.defs().table(id);if (!def) return [];const t = newTable(def);const media = t.columns.filter((c) => c.type === "photo" || c.type === "file").map((c) => c.key);const rows = [...ctx.scan(id)].filter((row) => t.binned(row) === null);// A sealed table's rows are read inside the owner's window for this assistant, else window_needed; a row that does not open is left out.const keys = await windowFor(ctx, t, "export_open_bundle");const out: Data[] = [];for (const held of rows) {const { row, parked } = await openStored(ctx, t, keys, held);if (parked) continue;const data: Data = { ...row.data, id: row.id, created_at: row.created_at, updated_at: row.updated_at };for (const key of media) if (key in data) data[key] = keyOf(data[key]); out.push(data); }return out;}/** What R2 says of each asked key; each held key's length is noted in `sizes`. */asyncfunction answer(ctx: ToolContext, asks: Ask[], known: Record<string, Held>, sizes: Map<string, number>, leftOut: Set<string>): Promise<void> {for (let i = 0; i < asks.length; i += ASKS_AT_ONCE) {awaitPromise.all( asks.slice(i, i + ASKS_AT_ONCE).map(async ({ key, read }) => {// AVATAR SEAL 4 (4): a file of a kind a device seals (a face, a photo, a book's file …) never goes into a bundle,// window or not: the zip is a plain document that outlives any window. Left out, and counted by itself.if (isDeviceSealedKind(ctx.database.id, key)) { known[key] = "missing"; leftOut.add(key);return; }let at: string;try { at = ctx.media.at(key); } catch {// A key that is not this database's is not held here. known[key] = "missing";return; }const head = await ctx.media.head(at);if (!head) { known[key] = "missing";return; } sizes.set(key, head.size);if (!read || head.size > PLAYLIST_MAX_BYTES) { known[key] = "held";return; }const object = await ctx.media.get(at);if (!object) { sizes.delete(key); known[key] = "missing";return; } known[key] = { text: await object.text() }; }), ); }}asyncfunction exportOpenBundle(ctx: ToolContext, args: Data): Promise<Data> {const asked = args.kit;if (typeof asked !== "string" || !(asked in OPEN_BUNDLE_KITS)) fail(`kit is one of ${Object.keys(OPEN_BUNDLE_KITS).join(", ")}`);const kit = asked asKit;const spec = OPEN_BUNDLE_KITS[kit];const media = args.media === undefined || args.media === null ? true : typeof args.media === "boolean" ? args.media : fail("media is true or false");// An empty library is said before any window is asked for.const held = (id: string): number => {const def = ctx.defs().table(id);if (!def) return0;const t = newTable(def);return [...ctx.scan(id)].filter((row) => t.binned(row) === null).length; };if (spec.tables.every((id) => held(id) === 0)) fail(`There are no ${spec.rows} in this database: the ${spec.root} library is empty, so there is nothing to export`);const tables: Record<string, Data[]> = {};for (const id of spec.tables) tables[id] = await liveRows(ctx, id);if (spec.tables.every((id) => tables[id]!.length === 0)) fail(`There are no ${spec.rows} in this database: the ${spec.root} library is empty, so there is nothing to export`);const known: Record<string, Held> = {};const sizes = newMap<string, number>();let tree: { entries: Entry[]; missing_media: string[] } | null = null;const leftOut = newSet<string>();for (let round = 0; !tree; round++) {if (round > 10) fail("the open bundle kept asking about its media: nothing was kept");const laid = tryRule<Laid>("open_bundle.lay", { kit, tables, database: ctx.database.id, exported_at: ctx.now, media, known });if ("error"in laid) fail(laid.error);if ("asks"in laid.ok) await answer(ctx, laid.ok.asks, known, sizes, leftOut);else tree = laid.ok.tree; }const encoder = newTextEncoder();const entries: ZipEntry[] = tree.entries.map((entry) => {if ("text"in entry) return { name: entry.path, size: encoder.encode(entry.text).byteLength, bytes: encoder.encode(entry.text) };const key = entry.media;return { name: entry.path, size: sizes.get(key)!, bytes: async () => {const object = await ctx.media.get(ctx.media.at(key));if (!object) thrownewError(`${key} was held a moment ago and is gone`);return object.body; }, }; });let bytes: number;try { bytes = zipLength(entries); } catch (error) { fail(`The ${spec.root} library is ${error instanceof Error ? error.message : String(error)}: ask again with media: false to take its lists and metadata alone`); }if (bytes > OPEN_BUNDLE_MAX_BYTES) { fail( media ? `The ${spec.root} library comes to ${gigabytes(bytes)} with its files, more than the ${gigabytes(OPEN_BUNDLE_MAX_BYTES)} an open bundle holds: ask again with media: false to take its lists and metadata alone, and fetch the files themselves with get_media` : `The ${spec.root} library's lists and metadata alone come to ${gigabytes(bytes)}, more than the ${gigabytes(OPEN_BUNDLE_MAX_BYTES)} an open bundle holds`, ); }const name = `${spec.root} library, ${dayWords(ctx.now, ctx.timezone)}`;const key = `${ctx.database.id}/documents/open-bundle-${kit}-${crypto.randomUUID()}.zip`;let sha256: string;try { ({ sha256 } = await ctx.media.storeStream(ctx.media.at(key), bytes, "application/zip", (write) => writeZip(entries, newDate(ctx.now), write))); } catch (error) {if (error instanceofError && error.constructor === Error) fail(`The ${spec.root} library could not be zipped: ${error.message}; nothing was kept`);throw error; }const document = ctx.defs().table("document") ?? fail("this database keeps no documents, so the bundle has nowhere to be kept");const id = crypto.randomUUID();const kept = await arriving(ctx, newTable(document), id, { title: name, original_name: `${name}.zip`, mime: "application/zip", byte_size: bytes, sha256, storage_path: key, source: "agent", mcp_token_id: ctx.caller.tokenId }); ctx.write((w) => w.create(document.id, kept, { id }));// The person's sealed files left out are said by count, apart from what is truly missing.return { document: id, files: entries.length, missing_media: tree.missing_media.filter((k) => !leftOut.has(k)), sealed_left_out: leftOut.size, bytes };}exportconst OPEN_BUNDLE_HANDLERS: Record<string, Handler> = { export_open_bundle: exportOpenBundle };