Data storage
Every app comes with storage your agent can read and write: lists, settings, totals, even files.
What your app can store
Values. Lists, settings, totals, notes: the everyday things an app needs to remember. Whatever your app saves survives between visits and across code updates.
Files. Your app can keep images, PDFs, audio, video, JavaScript, and other files. See Limits for current caps.
Technical
Apps import kv from charming:storage/[email protected] for JSON values and assets from charming:storage/[email protected] for files on the server; the browser uses window.charming.assets. An agent can also call upload_asset.
Copy this prompt for your agent
Add persistent storage to my Charming app. Read
https://charm.ing/docs/capabilities/data-storage.md first. Work out
from the app what it should save, values or files; if it isn't
obvious, ask me.
If you haven't built a Charming app before, read
https://charm.ing/docs/build-mcp.md (or build-http.md for the HTTP API)
for the app skeleton first.
How an agent performs this job
Your agent adds import { kv } from 'charming:storage/[email protected]' to server.js (or a file it imports) and saves the App (create_app / update_app over MCP, or POST /app / PUT /app/<id> over HTTP). The import is the capability; nothing is declared elsewhere. Inside a route handler, it calls kv.get, kv.put, kv.delete, or kv.list. To read or change stored data without touching the app’s code, an agent (including a different one from whichever built it) calls query_app for a read-only operation or mutate_app for one that writes.
Files have two paths:
- Agent upload. Call
upload_asset. The tool reference defines its inputs and errors. - App storage.
import { assets } from 'charming:storage/[email protected]'in a handler’s file, or usewindow.charming.assetsin the UI.
The contract
kv is the key-value store the charming:storage/[email protected] import provides. Its shape:
import { kv } from 'charming:storage/[email protected]';
kv.get(key); // Promise<unknown | undefined>
kv.get(keys); // Promise<Map<string, unknown>> - up to 1,000 keys in one call
kv.put(key, value); // Promise<void> - value must be JSON-serializable
kv.delete(key); // Promise<boolean>
kv.list(); // Promise<string[]> - every key
kv.list({ prefix, limit, cursor }); // Promise<{ keys: { name: string }[]; list_complete: boolean; cursor?: string }>
Those four are the only methods: set, add, setItem, and the like throw a TypeError. get and list follow Workers KV: an array of keys reads them all at once, and options read one page of keys. Storage is per-app and per-key, not a shared database across apps. The binding follows the current request’s App and user scope and its read-only restrictions, so call it inside a route handler or work the handler started with ctx.waitUntil, never at module initialization.
Read many keys at once
Each get(key) is a round trip to the database. A handler that loads a whole collection key by key spends most of its time waiting, and a Routine that does it for thousands of keys can run out of time. Read a page of keys, then read their values in one call:
import { kv } from 'charming:storage/[email protected]';
async function loadTasks() {
const tasks = [];
let cursor;
do {
const page = await kv.list({ prefix: 'task:', cursor });
const values = await kv.get(page.keys.map((key) => key.name));
for (const task of values.values()) tasks.push(task);
cursor = page.cursor;
} while (cursor);
return tasks;
}
That is two calls for every 1,000 keys. Reading a handful of known keys with get(key) is fine; reach for the array form when the number of keys grows with the data.
get(keys)resolves to aMapin the order you asked, each key once. A key with no value is left out, sovalues.get(key)returnsundefinedfor it, asget(key)does. A second argument such as'json'is accepted and ignored; values are always JSON.list(options)returns up tolimitkeys (1 to 1,000, default 1,000) that start withprefix, in UTF-8 byte order. Whilelist_completeisfalse, passcursorback to read the next page. A cursor works only for the same App and the sameprefix, and it holds the last key of its page in readable form, so an App that hands cursors to visitors shows them that key. Each page reads storage as it is at that moment, so a key written after the cursor shows up on a later page and a key present throughout appears once.- The page is also iterable.
for (const key of await kv.list({ prefix }))walks the key names of that page, so code written forlist()keeps working; it reads only the first page, so loop oncursorwhen a prefix can hold more than 1,000 keys.list()with no argument, or with an argument that is not an object, still returns every key as astring[]. - Caps. One
get(keys)names at most 1,000 keys and returns about 10 MiB of keys and values at most, measured as the stored JSON text, so the exact cutoff varies a little between hosts; a single value returns whatever its size. A call past a cap throws instead of returning part of the answer. - Errors. A refused call throws an
Errorwhosekindnames the reason and whose message starts with it:too_many_keysfor more than 1,000 keys,payload_too_largefor values past 10 MiB together,invalid_inputfor a key that is not a string, an unknownlistoption, alimitoutside 1 to 1,000, or a cursor this App did not get for this prefix.storage_method_unavailablemeans the call reached an App host that has no bulk reads yet; it does not fall back to reading key by key.
Reads within one call
Within one call (an operation call, a Routine tick, a webhook delivery, or a request to the App’s fetch handler), Charming remembers what the call has read from storage and answers later reads from it. Code that loads the same state several times, or loops over list() and awaits get(key) for each key, does not pay a round trip per key.
- Repeated reads. A second
get(key)of a key the call already read, a repeatedlist(), or the samelist(options)page returns what the first read returned, as a fresh copy. A key with no value is remembered too. - Your own writes. After a
putordeletefinishes, the next read of that key,list(), and any page reflect the write. - Parallel gets.
get(key)calls made together, as inPromise.all(keys.map((key) => kv.get(key))), are read as oneget(keys)call. - Read-ahead. When
get(key)misses a key that the lastlist()or page returned, Charming also reads the listed keys after it: 64 keys at first, then four times as many each time the loop uses every key of the last batch, up to 1,000. Listing alone reads no values. Read-ahead follows the order the list returned and stops for the rest of the call once more of the keys it read have been passed over than used. - Limits. A call remembers about 16 MiB, counting two bytes per character of keys and values, and no single value over 1 MiB. A value it does not keep, and a key the call wrote, is read from the database again the next time the call asks.
The one difference from reading the database every time: within a call, a key already read is not read again, so a write another request makes to that key during the call shows up only in the next call. An App that waits for another request’s write should end the call and check again in the next one, not loop and re-read within the same call.
Existing code gets faster without changes. New code should still read a page and then its values with one get(keys), as above: the cost stays visible in the code and does not depend on the order of reads.
assets is the file store the charming:storage/[email protected] import provides. Its shape:
import { assets } from 'charming:storage/[email protected]';
assets.get(key); // Promise<{ bytes: Uint8Array; contentType: string } | undefined>
assets.put(key, bytes, { contentType }); // Promise<void>
assets.delete(key); // Promise<boolean>
assets.list(); // Promise<Array<{ key: string; contentType: string; sizeBytes: number }>>
assets.url(key); // Promise<string> - signed Charming URL; await it
Accepted file types are images other than SVG, audio, video, fonts, PDF, JSON, plain text, CSV, Markdown, JavaScript, and application/octet-stream. JavaScript uploads (text/javascript, application/javascript, or application/x-javascript) are stored as text/javascript, and a .js or .mjs upload that declares no type is treated as JavaScript. HTML, SVG, XHTML, WebAssembly, and other types fail with asset_invalid_content_type. Only a caller who can edit the app, such as the agent with upload_asset or the app token, can upload JavaScript; window.charming.assets.upload() from the page is refused with 401. An uploaded script runs only at the app’s own origin on the web; see uploaded scripts and workers.
Use await assets.url(key) or window.charming.assets.getUrl(key) for a time-limited signed Charming URL. assets.url returns a Promise, so return { url: await assets.url(key) } from a route, not the unawaited call. Store the key, not the URL. Use window.charming.assets.load(key) when an uploaded image must render in a chat embed. See External files and CSP for URL lifetime and host behavior. A browser UI can also upload, list, and delete files directly:
const uploaded = await window.charming.assets.upload(file, { key: 'avatar.png' });
const files = await window.charming.assets.list();
await window.charming.assets.delete(uploaded.key);
Reading and listing require app read access. Uploading and deleting require app run access, so a read-only viewer cannot use them. The Browser runtime API defines the full method and error contract.
Limits, access, and deletion
- Serialization.
putstores JSON-compatible data: objects, arrays, strings, numbers, booleans, andnull. A value that can’t be JSON-serialized (a circular reference, aBigInt) fails the write. Store values as they are; don’tJSON.stringifybeforeputorJSON.parseafterget. - Key order.
list()returns your keys but doesn’t guarantee an order; sort them yourself if order matters.list(options)always returns keys in UTF-8 byte order. - Caps and errors. See Limits and
upload_asset. - Access. Storage belongs to the app. See Privacy and sharing.
- Deletion. Deleting an app from its settings page always deletes its key-value storage and secrets with it. Through an agent,
delete_apptakespurge_storage: trueandDELETE /app/{id}takes?purge=storageto do the same. Without the flag, the app’s secrets are kept, and an hourly cleanup clears its key-value storage once no app owns it. Files are different: deleting an app always removes its stored files too, whether or notpurge_storageis set.