# GENERATED FROM apps/www/doc-templates/llms-full.txt.tmpl; edit the template, then run `bun run docs:gen`. You are building a personal web app for me using Charming. # Path Default: build via the API below. Zero install, zero friction. This is the right path whenever you can make outbound HTTP requests with auth headers — including code-editor agents (Cursor, Claude Code, Cline, Windsurf, Continue, Zed, Gemini CLI) and chat agents that have a web/HTTP tool available. If you use the Codex app or CLI and can install plugins, prefer the [public Charming plugin](https://github.com/tambo-labs/charming-codex-plugin) before the HTTP fallback: run `codex plugin marketplace add https://github.com/tambo-labs/charming-codex-plugin.git`, restart Codex, install Charming from the Tambo Labs marketplace, then start a new thread. The plugin bundles the Charming MCP endpoint and Charming authoring skill. The Codex app renders the returned app inline via MCP Apps. Codex CLI opens its Charming URL in the browser. If already connected through MCP, use `read_docs({})` to read the docs index without a browser, then `read_docs({ path: "technical-reference/browser-runtime.md" })` to read a page. An empty path also opens the index, and a copied `docs/` prefix is accepted. Responses contain up to 20,000 characters; when `next_offset` is not null, pass it as `offset` with the same path to continue. Each server process permits 60 reads per authenticated caller per minute. Only branch to MCP setup if one of these is true: - You literally cannot make outbound HTTP requests in this environment. - The user explicitly asks to add Charming as an MCP server, or asks for apps to render inline in an MCP Apps-capable host instead of opening in a new tab. In either case, fetch `https://charm.ing/docs/clients.txt` and follow the block matching your client. Most clients use `https://charm.ing/mcp`. If you are ChatGPT or the Codex desktop app, do not give the user a server URL to paste. Both share one public Charming listing: tell them to open https://chatgpt.com/plugins/plugin_asdk_app_6a56c533cd7c8191b9a16cb7973a65e6, click Install plugin, and start a new chat. The Codex CLI takes the marketplace plugin above instead. That is one click and needs no developer mode, where a custom connector needs developer mode turned on in ChatGPT settings. Only fall back to pasting `https://charm.ing/mcp/chatgpt` into the custom-connector form if the user cannot reach the listing; the plain `/mcp` endpoint connects but never renders apps inline in ChatGPT. If you are Claude or Claude cowork (not Claude Code), do not give the user a server URL to paste. Charming is in Claude's connector directory: tell them to open https://claude.ai/directory/charming, click Connect to Claude, approve access, and start a new chat. Only fall back to adding https://charm.ing/mcp as a custom connector at https://claude.ai/customize/connectors if their workspace hides the directory; https://charm.ing/docs/clients/claude.md has both paths. Do not confuse this with Claude Code, which should use the default HTTP API path when it can make outbound requests. # When neither path works Some chat surfaces can't make outbound HTTP requests AND can't add a custom MCP server today (Claude.ai Free without spare connectors, etc.). If you're in one of those, don't fake it. Tell the user verbatim: "Charming needs an agent that can either make HTTP requests or add an MCP server. This chat can't do either right now. The fastest paths are: a code-editor like Cursor or Claude Code (free, builds via API), or a chat with MCP support (Claude.ai Pro, ChatGPT, Claude Desktop, Goose). Once you're in one, paste the same prompt and we'll continue." Then stop. Don't try to work around it. # Agent when-to-use Read this first to triage whether Charming fits the user's request before you read the rest of this manual. - **Reach for Charming when** the user wants a personal web app that outlives the chat — something with a real URL, a real database, and the ability for any AI to keep editing it later. - **Reach for Charming when** the user wants to ship in one shot — no install, no auth setup, no scaffolding — and have a real URL they can open or share immediately. - **Reach for Charming when** the work spans more than one slice of life and the user wants several small apps under one account instead of tabs of one mega-app (see *What an app can be* below for the breadth of shapes that fit). - **Don't reach for Charming when** the user needs a native phone app, real-time multiplayer, a SQL database, or interactive OAuth login — these are root limits, not gaps (see *What Charming can't do yet* below for what to build instead). Running something on a timer is not on this list — Routines (below) cover hourly/daily/weekly. - **Don't reach for Charming when** the right answer is a one-line snippet in the chat — Charming is for things the user wants to *keep and reopen*, not throwaway calculations. # What Charming is A runtime that hosts apps you write. Author an App as a small package: a `package.json`, a `server.js` with route definitions, and an optional `ui.js`. POST its files to [`https://charm.ing/app`](https://charm.ing/app) with the user's token, and Charming builds it and returns a public URL. Apps get key-value storage, file storage for images and other assets (`upload_asset`, the `assets` import), npm dependencies, and a backend reachable from the UI or any HTTP client. Saving needs a signed-in account, so pair first (below); there is no anonymous create. Apps are single-tenant: one app = one URL = one shared dataset owned by me. I can share the URL but everyone who uses it sees the same data — like a private Notion page with a link. Design for one user, one dataset; that's the shape, not a workaround. # Before creating Every save needs the user's own token, so check memory and files first: `chrm_user_*` is a user-scoped token (in `~/.config/charming/user-token` or env `CHARMING_USER_TOKEN`). If you find one, you can list and update any of the user's apps; try `GET /app` first to see what's already there. If you find none, run the pairing flow under "Linking to an existing account" before the first `POST /app`. An App saved before packages may also have a per-app `chrm_app_*` token on disk; it still updates that one App. For a local user token, read `~/.config/charming/user-token` first and validate the exact `chrm_user_*` or `bld_user_*` shape. During the migration window only, if that file has no valid token, read `~/.buildy/user-token` once. After a valid old-file read, create `~/.config/charming` with mode `700`, copy the token to the canonical file with mode `600`, and use it from there. If both files are valid, the canonical file wins. Never print or log either file's contents. If you have a structured-question tool (`AskUserQuestion`, `request_user_input`, etc.), use it for choices below — multiple choice with sensible defaults beats a blank prompt. Always include an "other" escape. # Linking to an existing account Full reference for working across agents on the same app (credential families, what each token can touch): https://charm.ing/docs/capabilities/connect-any-agent.md. The pairing steps below are the procedure to run mid-generation. If the user says "connect to my Charming" or "list my apps" and you have no `chrm_user_*` token, do the device-code pairing flow — it's the only path that works from a CLI without OAuth: 1. POST https://charm.ing/api/pair/start { "label": "" } → returns { device_code, user_code, verification_url, polling_interval, expires_in } `device_code` is agent-private — never display, never log. Anyone who has it can poll for the token before the legitimate agent does. `user_code` is the one to show the user. 2. Show the user `user_code` (looks like `CHRM-XXXXXX`) verbatim, plus `verification_url` (https://charm.ing/pair). They open it, paste the code, approve. 3. Poll every `polling_interval` seconds: POST https://charm.ing/api/pair/poll { "device_code": "" } → status: "pending" | "expired" | "approved" When approved, response includes a `chrm_user_*` token. Save it to `~/.config/charming/user-token` or wherever you stash credentials. You won't see the plaintext again. The PAT alternative: if the user is signed in already, have them open the account menu, choose **Account settings**, then **Agents**. They can mint a token there and paste it. Same `chrm_user_*` shape, no pairing dance. The same page lists and revokes tokens; the headless equivalents are `GET /api/token` and `DELETE /api/token/` below. Once you have `chrm_user_*`, all routes that need user auth accept it as `Authorization: Bearer `: GET /app # list the user's apps (paginated) GET /app//describe # metadata + storage key inventory GET /app//diag # runtime errors from the iframe (50-entry ring buffer) GET /app//activity # durable runtime failures (survives redeploys) GET /api/v1/apps//activity # rich timeline; user identity with app:manage POST /api/token # mint another chrm_user_* (label, expiresInDays 1-365) GET /api/token # list your chrm_user_* tokens (metadata, never plaintext) DELETE /api/token/ # revoke one token by the id from GET /api/token Token management, headless. `POST /api/token` takes an optional `{ "label": "...", "expiresInDays": 1-365 }` body (default 7 days; a token-authenticated call gets 7, a longer lifetime needs a signed-in session) and returns `{ token, tokenPrefix, label, expiresAt }`; the plaintext `token` appears in this response only. `GET /api/token` returns `{ "tokens": [{ id, tokenPrefix, label, expiresAt, lastUsedAt, createdAt }] }`, newest first, covering both minted and device-paired tokens. `DELETE /api/token/` returns `{ "ok": true }` and the token stops working on the next request; an id that is malformed, unknown, or belongs to another account returns 404 `not_found`. A missing, revoked, or unknown credential gets 401 `unauthorized`; an expired `chrm_user_*` token gets 401 `token_expired` with a `recovery` block. The list keeps expired tokens until you revoke them. To rotate without a browser: `POST /api/token` and save the new plaintext, `GET /api/token` with the new token to find the old one's `id` by `tokenPrefix` or `label`, then `DELETE /api/token/`. Mint before you revoke: deleting the token you are calling with succeeds, and your next request with it returns 401. Distinct from owner-only `/describe`: `GET /app//agent.json` is a public, side-effect-free descriptor (manifest, operations, canonical URL) that needs no auth for a Public App or Listed Template. An enabled unlisted Template stays private without `app:read`, like any other private App. Any agent that lands on a rendered app page (the `/app/` or `//` form) can find it via the page's `` and matching `Link:` HTTP header — no handle lookup required, since it always points at the canonical UUID form. After you publish, ask "what broke at runtime?" without a human relaying console output: GET /app//activity?kinds=&since=&limit= returns this app's durable failure events newest-first — API-proxy errors (`api_proxy_result`), runtime JS errors and CSP violations (`diag_report`), and UI/backend contract misses (`contract_validation`). Unlike `/diag` (an in-memory 50-entry ring buffer that resets on every deploy), these rows survive redeploys. Owner-only: pass your `chrm_user_*` bearer (render tokens and claim cookies are rejected). Filters: `kinds` is a comma-separated subset of those three kinds, `since` is an ISO-8601 cutoff, `limit` defaults to 100 (max 500). The read covers the plan's window: 24 hours on Free, 30 days on Pro, 90 days on Business. `value.retention.since` is the cutoff used. Not to be confused with `/app//events`, the live-state SSE stream. `charming api request get-app-activity-timeline --param appId=APP_ID --param limit=50` reads published versions, renders/runs, API-call outcomes, sharing changes, and feedback. Use a personal access token with `app:manage` access. The response has `items`, `hasMore`, and `retention`; when `hasMore` is true, pass the oldest item's `ts` and `id` together as `--param before=OLDEST_TS --param beforeId=OLDEST_ID`. The separate `get-app-activity --param id=APP_ID` operation keeps the durable runtime-failure log at `/app/{id}/activity` and its `{ok,value:{items,retention}}` envelope. ## The App is a package An App is a `files` map from path to text: `package.json`, the server entry `server.js`, and optionally `ui.js`, `styles.css`, and other `.js`, `.mjs`, or `.json` files the entries import with relative paths. Paths are relative, hold letters, digits, `.`, `_`, and `-`, never pass through `node_modules`, and the tree holds at most 64 files. The contract is dated `2026-10-25` and frozen: an App saved under it keeps working as written. Its package.json schema is `https://charm.ing/schema/app-package/2026-10-25.json`; `$schema` is optional. `package.json` follows npm. `name` is the App's id: lowercase letters, digits, and hyphens, up to 64 characters, immutable once the App exists. `version` is the App's release string and defaults to `0.0.1`. `description` is the App's description. `dependencies` holds public npm packages with semver ranges, one map for both targets; the build installs it once and bundles what each entry imports. `devDependencies` is ignored, so a local type-checking setup can keep its own tools. Charming facts sit under `charming`: `name` (display name), `icon` (one emoji on a hex background), and `permissions` (`browser.img-src`, `browser.frame-src`, `browser.connect-src` as exact origins; `server.fetch` as exact HTTPS origins; `server.connectors` as a map from service slug to Composio tool slugs). Permissions are parameters of a capability; the capability comes from the import. `server.js` exports a literal `routes` array and nothing else Charming reads. Capabilities come from imports: `import { kv } from 'charming:storage/kv@1.0'` on the server, `import { api, onStateChange } from 'charming:ui/app@1.0'` in the browser. Platform imports are not npm dependencies. A relative import must name a `.js`, `.mjs`, or `.json` file the tree holds; a tree file no entry imports is refused, so nothing is published by accident. Any authored lockfile, `tsconfig.json`, `jsconfig.json`, and a nested `package.json` are refused as `invalid_files`. Saves require a user credential (`chrm_user_*`) and an idempotency key: HTTP `Idempotency-Key` or MCP `idempotency_key`, 8–128 visible ASCII characters, fresh for each deliberate save. Existing destinations also require the desired-source revision, through HTTP `If-Match` or MCP `expected_revision`. A save returns an accepted build to poll (HTTP `202` with `buildId` and `statusUrl`; MCP `get_app_build({ build_id })`); only `published` means the App is live, and a new App has no URL before that. A save replaces the whole tree. Exact edits name a `path` instead of a bucket and change files the tree already holds. `get_app_source` returns the tree as `source.files`. Import and package checks run without evaluating App code before acceptance. Bundling happens in the background. Exact compatible locks can be reused across source edits that keep the same dependencies. Resolution and compilation are confined, and a verified server and browser pair must pass validation before publication. Rendering and operation calls keep using the last working active revision until the new one publishes. Every file except `styles.css` counts toward one 1024 KiB cap, and `styles.css` is capped at 256 KiB. Queue and attempt deadlines are 10 and 10 minutes, within a 20-minute total lifetime and at most 2 automatic attempts. Terminal input inspection lasts 7 days; results, locks, and idempotency records last 30 days. A save answered with `app_build_unavailable` (HTTP 503) means Charming cannot build packages right now; retry later, since published Apps keep serving. `app_build_capacity` means retry later too. An App saved before packages existed, with `module`, `ui`, and `styles` strings, still runs and still accepts those fields. To move one onto the package contract, send its tree as `files` with `migrate_contract: true`. A large App need not resend its source: give a file as `{ "from": "module", "edits": [...] }` (or `"ui"`, `"styles"`) to build it from the current source. This is also the way past the 256 KiB `module` and `ui` caps, which `module_too_large` and `ui_too_large` name. See https://charm.ing/docs/guides/migrate-to-packages.md. # The files `package.json` describes the App. `name` is the App's id, and the rest follows npm: ```json { "name": "todo", "version": "1.0.0", "description": "A todo list.", "type": "module", "dependencies": {}, "charming": { "name": "Todo", "icon": { "emoji": "✅", "bg": "#1d8a4e" } } } ``` `server.js` exports one literal `routes` array and nothing else Charming reads. Capabilities come from `charming:` imports: ```js import { kv } from 'charming:storage/kv@1.0'; export const routes = [ { op: 'list', method: 'GET', annotations: { readOnlyHint: true }, outputSchema: { type: 'array' }, handler: async () => (await kv.get('todos')) ?? [], }, { op: 'add', method: 'POST', inputSchema: { type: 'object', required: ['text'], properties: { text: { type: 'string' } }, additionalProperties: false, }, handler: async (input) => { /* update storage and return a JSON-compatible value */ }, }, ]; ``` A request to `/api/` for an operation the App does not declare gets 404 `operation_not_found` with `requestedOp`; a caller signed in with a user or App token also gets `knownOps`, the operations the App does declare. When the App declares that operation under another method, the request gets 405 `method_not_allowed` with `allowedMethods` and an `Allow` header instead. Any other request that matches no route gets Charming's 404: requests whose `Accept` header includes `json` receive `{"ok":false,"error":{"kind":"unknown_operation","message":"404 - page not found"}}`; every other request receives the plain-text body `404 - page not found`. `server.js` exports no manifest and no default export; a save that includes either is refused as `invalid_module`. Capabilities come from imports, not from a declaration. Charming walks every import from `server.js` and `ui.js` through the App's own files before it accepts a save, so an import in `./lib/save.js` counts the same as one in the entry. The server imports are `charming:storage/kv@1.0` (`kv`), `charming:storage/blob@1.0` (`assets`), `charming:logging/emit@1.0` (`log`, with `.info(msg)` / `.warn(msg)` / `.error(msg)`), `charming:network/fetch@1.0` (`fetch`, keyless outbound requests to the origins in `charming.permissions.server.fetch`), `charming:secrets/fetch@1.0` (`fetch`, the sealed outbound fetch with secret substitution; claimed Apps only), `charming:connectors@1.0` (`connectors`), and `charming:app/@1.0` (`app`, another App you own). The browser import is `charming:ui/app@1.0` (`api`, `onStateChange`). Include the `@1.0` suffix, keep platform imports out of `dependencies`, and call host functions inside a route handler, not at module initialization. Camera, microphone, geolocation, screen capture, clipboard reading, and MIDI need no import and no claim: Charming finds those calls in `ui.js` when the App is published and asks the viewer on the web. Device motion (`charming:browser/device-motion@1.0`), ambient light (`charming:browser/ambient-light@1.0`), and client storage, `charming:browser/storage@1.0` (web-only `localStorage`/`sessionStorage`/`IndexedDB`, empty inside Claude/ChatGPT; keep anything a user expects to persist in `kv`), are side-effect imports in `ui.js`, for example `import 'charming:browser/storage@1.0'`; device motion and ambient light stay denied until the App is claimed. Don't invent specifiers: the host refuses unknown imports, and a specifier that is not in this list enables nothing. `package.json` is strict where the build cannot honor a key the way npm does: `overrides`, `resolutions`, `bundleDependencies`, `bundledDependencies`, `peerDependencies`, `peerDependenciesMeta`, `optionalDependencies`, `imports`, `exports`, `main`, `browser`, `module`, and `workspaces` are refused with the reason (`invalid_manifest_schema`). `license`, `private`, `scripts`, and `engines` are ignored. `dependencies` is one map of public npm packages to semver ranges, shared by the server and the browser. `export const routes` must be an ARRAY of route objects (`[{ op: 'list', handler: async (input, ctx) => {...} }, ...]`), never an object keyed by op name. Route `op` values must be unique. `charming.name` is the display name and defaults to the package name. `charming.icon` is optional and is a single emoji plus a hex background color (`#rgb`, `#rrggbb`, or `#rrggbbaa`); Charming composes the home-screen / favicon icon from it. It is NOT a W3C-style array of image URLs. Omit it to get the default. # API discovery requires route definitions Full API discovery is available only for operations declared in a literal `export const routes = [...]` array in `server.js`. Charming reads each route's `op`, `method`, `path`, `annotations`, schemas, and other metadata before accepting the save, to choose `query_app` versus `mutate_app` and to populate create/update responses, `get_app`, `GET /app//describe`, and the app's OpenAPI document. Routes default to `POST /api/`, a closed empty-object input schema, `public: true`, and the MCP annotation defaults. Charming does not infer annotations from the method. To expose a read through `query_app` or to a viewer, set `annotations.readOnlyHint: true`: ```js import { kv } from 'charming:storage/kv@1.0'; export const routes = [ { op: 'getState', method: 'GET', annotations: { readOnlyHint: true }, handler: async () => ({ state: await kv.get('state') }), }, ]; ``` A route marked `readOnlyHint: true` also defaults to `destructiveHint: false` and `idempotentHint: true`. Every route defaults to `openWorldHint: true`, so set `openWorldHint: false` on a route that touches only the App's own data. A `GET` route reads its input from the query string, and every value there is a string on the wire, so Charming converts each one to the type its `inputSchema` declares (`integer`, `number`, `boolean` from the literal `true` or `false`, or an `array` of those, with a repeated key becoming the array) before validation. `GET /app//api/list?limit=1` reaches a `{ type: "integer" }` field as `1`. Other methods read a JSON body, which already carries its types. A body is read up to 1 MiB; a longer one returns 413 `payload_too_large` before the operation runs. Call each operation with the method its route declares. A request that uses another method returns HTTP 405 with `error.kind: "method_not_allowed"`; the `Allow` header and `error.allowedMethods` name the declared method, so retry with it. An operation the app does not declare returns 404 `operation_not_found`. To let people who aren't the App's members call one operation, such as a contact form, set `callers: 'anyone'` on that route, or `callers: 'signed-in'` to require a Charming account. The App must be public, the route must stay public, and every other route stays members-only. See https://charm.ing/docs/guides/let-visitors-call-an-operation.md. `GET /app//describe` and `agent.json` report who may call each operation as `callers`, and the App's OpenAPI document reports it as `x-charming-callers`. A write reports its declaration, `members` when unset. A read-only operation reports `anyone`, because everyone who can view the App may call it whatever it declares. The declaration applies to the operation's HTTP URL only: `mutate_app` and the App's MCP tools need run access for every write. # Route handlers and bindings A route handler receives `(input, { env, ctx, request })` and returns a JSON-compatible value. The platform validates the input and output schemas, dispatches the operation, and wraps the result in the wire envelope. App-authored API responses carry host-enforced CSP `sandbox; default-src 'none'; base-uri 'none'; form-action 'none'` and `X-Content-Type-Options: nosniff`; App headers cannot relax this policy. The bindings a handler uses are imports at the top of `server.js`: ```js import { kv } from 'charming:storage/kv@1.0'; kv.get(key); // Promise kv.get(keys); // Promise> — up to 1,000 keys in one read; missing keys left out kv.put(key, value); // Promise — JSON-serializable, 10MB per value, 1GB per app kv.delete(key); // Promise kv.list(); // Promise kv.list({ prefix, limit, cursor }); // Promise<{ keys: { name }[]; list_complete; cursor? }> — one page, UTF-8 byte order import { assets } from 'charming:storage/blob@1.0'; assets.get(key); // Promise<{ bytes: Uint8Array; contentType: string } | undefined> assets.put(key, bytes, { contentType }); // Promise assets.delete(key); // Promise assets.list(); // Promise> assets.url(key); // Promise — signed Charming URL; await it import { fetch } from 'charming:secrets/fetch@1.0'; fetch(url, init); // Promise — sealed outbound fetch; {{secret:NAME}} in a header or query value is substituted host-side ``` Importing `charming:secrets/fetch@1.0` without `charming:network/fetch@1.0` also makes the global `fetch` the sealed one, so a plain `fetch(url, init)` substitutes placeholders the same way. A package that imports both keeps the global `fetch` direct and reaches the sealed one only through the named import. These four are the only storage methods: `set`, `add`, `setItem`, and the like throw a `TypeError`. Load a collection a page at a time, not a key at a time: `const page = await kv.list({ prefix: 'task:', cursor })`, then `await kv.get(page.keys.map((key) => key.name))`, looping while `page.cursor` is set. Each `get(key)` is its own database round trip. Store JSON-compatible values as they are; don't `JSON.stringify` before `put` or `JSON.parse` after `get`. The bindings follow the current request's App and user scope and its read-only restrictions, so call them inside a route handler or work the handler started with `ctx.waitUntil`, never at module initialization. To call another App you own, `import { app } from 'charming:app/@1.0'` and call `app.fetch(new Request('http://callee/api/read'))` inside a route. The host resolves the active sibling in your user or team namespace and keeps the callee's access and storage rules; a chain of sibling calls stops at eight, and the ninth returns HTTP 403 with `capability_denied`. `env` holds `env.user`, plus `env.secrets` when `server.js` imports `charming:secrets/fetch@1.0` and `env.connectors` when it imports `charming:connectors@1.0`; storage, assets, logging, sibling Apps, and `fetch` come only from their imports. `env.user` is always present, whatever the App imports: the signed-in caller as `{ id, handle?, name?, image?, email?, emailVerified }`, or `null` when no person is behind the call (a signed-out visitor, a Routine, a webhook, an App token). `email` is the caller's verified address, present only when `emailVerified` is `true`. A signed-in visitor who is not a member of the App reaches a handler as themselves only when a write route of the App declares `callers: 'signed-in'` or `callers: 'anyone'`; otherwise `env.user` is `null` for them. To match visitors against the App's own member list, put the lookup in such a route, not in a read-only one. A caller named only by a user-bound render token, such as an App opened from a `?t=` URL an agent handed out or a chat host's embed, reads `emailVerified: false` with no `email` even when their address is verified, because anyone holding the token can replay it. The address reaches server code only; `window.charming.user` in the browser never carries it. A route handler receives `(input, { env, ctx, request })`, so read it as `env.user` from that second argument, or as `ctx.env.user` when using a named context param; there is no `ctx.user`. When an operation needs the address, guard it with two lines: `if (!env.user) throw new CharmingHandlerError({ kind: 'forbidden', status: 403 });` then `if (!env.user.email) throw new CharmingHandlerError({ kind: 'email_not_verified', status: 403 });`. The first refuses a caller with no account, and `forbidden` is the kind `window.charming.withUser` retries after sign-in; the second answers a caller with no address with 403 `email_not_verified` and the message "The user needs to verify their email." A caller named only by a user-bound render token gets 403 `email_needs_sign_in` instead, with "Open this App in Charming while signed in to use your email." Storage is per-app and survives updates (changing your code does NOT wipe state). Each value you put is capped at 10MB (JSON-serialized), and the whole store at 1GB: an oversized value fails with `stored_value_too_large`, a full store with `storage_full`. File storage (`assets`), limits, and access rules: full reference https://charm.ing/docs/capabilities/data-storage.md. A handler that throws a plain `Error` fails the call with 500 `{ kind: "operation_failed", message, traceId }`. Callers who can edit the app (its owner, collaborators, the app token) get the thrown message; viewers, end users, visitors, the page's own calls, and Webhook senders get `The operation failed.`. Read the full message and stack for `traceId` from `GET /app//diag`. Call host functions inside a route handler or its supported request lifetime, not at module initialization: a `kv.put` at the top of `server.js` fails the build's validation. `ctx.waitUntil(promise)` keeps fire-and-forget work alive past the response. Most apps don't need it. # Secrets and sealed fetch Full reference: https://charm.ing/docs/capabilities/secrets.md (why this exists, the 8 KiB cap, and how the owner manages values in App settings). The build contract below is what you need mid-generation. **Secrets and sealed `fetch`.** For calls that need an API key, `import { fetch } from 'charming:secrets/fetch@1.0'` (claimed Apps only): a sealed outbound fetch that substitutes secret values host-side. Reference a secret as `{{secret:NAME}}` inside a request **header value** or a **query-parameter value**; Charming swaps in the real value on its own infrastructure before the request leaves, so the plaintext never enters your App code or the sandbox. Secret names match `[A-Z][A-Z0-9_]*`. Only the App **owner** sets a value, in **App settings → Secrets**; the agent never sets or reads one, it only needs the NAME. Hand the owner a link instead of describing where to click: `https://charm.ing//~/apps//settings/secrets?name=NAME`, with the real owner handle and App name, one `name=` per secret, and an optional short `&reason=` saying why. The page lists the names the link asks for, quotes the reason, and takes the pasted value. Never put a value in the link. The sealed fetch is HTTPS-only and keeps the same `charming.permissions.server.fetch` allowlist and public-address guard as the keyless one, so list the origin in package.json. ```js // server.js: the owner set OPENROUTER_KEY in App settings import { fetch } from 'charming:secrets/fetch@1.0'; const res = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer {{secret:OPENROUTER_KEY}}' }, body: JSON.stringify(payload), }); ``` ```js // query-parameter form: the owner set EXAMPLE_KEY in App settings. // Write the placeholder literally in the URL string like this — building it // with URLSearchParams.set(...) or encodeURIComponent(...) percent-encodes // it first and it will NOT resolve. const res = await fetch(`https://api.example.com/data?api_key={{secret:EXAMPLE_KEY}}`); ``` **Unset secrets on save.** Over MCP, `create_app` and `update_app` report the `{{secret:NAME}}` references in the saved server code. An owner or team admin gets the ones the App has no value for, in the result text and in `unsetSecrets` (the first 10; the text says how many more). The text reads `Not set yet: NAME. Have the user add it here: `. A caller who can edit but not manage the App gets the secrets its code uses, set or not, and a link to forward to the owner: `This code uses secrets: A, B. Ask the app owner to add them in App settings → Secrets. Send them this link: `. The link names every secret the code uses, and the result carries the text only, so the editor's result reads the same whether or not the owner has set a secret. A person who can open the App but not manage it and opens that link is told to send it to the app owner, with a button that copies it. A package App is checked on `server.js` and the relative files it imports. When a `create_app` with `files` makes a new package App, the App has no page yet; the text says `get_app` returns the Secrets link once the build publishes. The HTTP API and the CLI do not return this. **Time limits.** Charming stops an op that is still running after 30 seconds. The call answers HTTP 504 with `error.kind: "timeout"` and `error.details: { limit: "operation", limitMs, elapsedMs }`, and the message names the op and the limit. Over MCP the tool result carries `error_kind: "timeout"`. The op may have done part of its work before it was stopped, so check its effects before calling it again. A Routine run has the same limit, and its `last_error` keeps the same `details`. To stay under the limit, split the work into smaller ops, or move it to a Routine that does part of it on each run. A sealed `fetch` has its own limit, which ends 1 second before the op's limit so your handler can still answer. When it fires, the `fetch` call throws an error with `name: "TimeoutError"`, `kind: "timeout"`, `limit: "sealed_fetch"`, `limitMs`, and `elapsedMs`. Catch it to handle a slow upstream. If the handler lets it escape, the call fails with `kind: "timeout"` and `details.limit: "sealed_fetch"`. The owner's agent sees the same facts afterward: `get_app` recent issues, the activity feed, and the "Fix with agent" prompt name the limit, how long the work ran, and the Routine when a Routine started the run. Substitution reaches header values and query-parameter values only — never a parameter name, the host, the path, the fragment, or the body, so a secret can't move the request to another origin. A query-string value is not log-safe the way a header is: query strings routinely land in the upstream's access logs, proxy logs, and referrer headers, so prefer a header when the API accepts one and use the query string only when it's the sole option. A missing secret fails the whole request; nothing goes out with the placeholder still in it. The machine HTTP API for the store is `/app//secrets` (GET names, POST create, PUT replace, DELETE). # Standard library and what's not available On `globalThis` (WinterTC Minimum Common API): Request, Response, Headers, URL, URLPattern, TextEncoder/Decoder, crypto.subtle, crypto.randomUUID, Web Streams, AbortController, setTimeout/Interval, structuredClone, Blob, FormData, console. Not available: Node APIs (process, fs, require), DOM, IndexedDB, WebSocket. npm packages are available through `dependencies`, bundled at build time; a package that needs Node built-ins, native addons, install scripts, CSS imports, WebAssembly, or workers fails the build. Only WinterTC globals are available (Request, Response, URL, URLPattern, crypto, TextEncoder, structuredClone, ...). No Node APIs, no DOM. Outbound requests are off by default: `import { fetch } from 'charming:network/fetch@1.0'` and list each exact HTTPS origin in `charming.permissions.server.fetch` in package.json (claimed Apps only; private/loopback/metadata blocked). Both the import and the permission are required. Redirect destinations are checked too. npm packages that need Node built-ins, native addons, install scripts, CSS imports, WebAssembly, or workers fail the build (`unsupported_node_builtin`, `unsupported_native_addon`). See https://charm.ing/docs/llms-full.txt for the full standard-library list and limits. Browser code in `ui.js` can call only the exact origins listed in `charming.permissions.browser["connect-src"]`: `https://` origins for `fetch` and `EventSource`, `wss://` origins for `WebSocket`, public hosts only, and the remote server must allow CORS. That list applies on the web page; a chat host's own policy blocks it inline. Keep keyed calls on the backend. Net: a **public, keyless** data source (an RSS feed, a public JSON API) works with the `fetch` from `charming:network/fetch@1.0`; an LLM call or other authenticated HTTPS endpoint works through the sealed `fetch` from `charming:secrets/fetch@1.0` once the owner sets the key. OAuth flows still aren't wired up, so services that require an interactive login stay out of reach. # External images and CSP img-src Image reference: https://charm.ing/docs/capabilities/external-images.md. All file types and CSP directives: https://charm.ing/docs/technical-reference/external-files-and-csp.md. **External images.** Charming's app-shell CSP locks `img-src` to same-origin + `data:` + `blob:`, so a remote `` will not render by default. Declare each exact HTTPS origin your UI needs in package.json under `charming.permissions.browser["img-src"]: ["https://images.unsplash.com"]`. Wildcards, paths, credentials, and loopback/private/link-local origins are rejected. Two ways to render: `window.charming.images.load(url)` fetches through Charming's server-side image proxy and resolves to a `data:` URL that renders in every embed (Claude and ChatGPT inject their own outer CSP that forbids cross-origin images, so this is the only form that works inline there); `window.charming.images.proxy(url)` returns a same-origin proxy URL for a plain `` on the web; it does NOT work inside Claude's or ChatGPT's inline embed, so use `load()` by default. A raw `` fails silently even when the origin is declared. The proxy follows redirects only to a declared origin or a subdomain of one, so declare every domain the chain passes through, and every hop must resolve to a public address. Full reference: https://charm.ing/docs/capabilities/external-images.md. The proxy enforces operator origin denies on requests, redirects, and server-side cache hits, and applies per-process limits per app and destination origin, including redirect destinations. These controls return `image_origin_denied` or `rate_limited` respectively. A deny covers the named host and everything beneath it. # Operation result contract Conventional JSON response shape: ```text { ok: true, value: /* anything JSON-able */ } { ok: false, error: { kind: "not_found" | "unknown_operation" | "operation_failed" | "timeout", message: "..." } } ``` A handler returns exactly the value its route's `outputSchema` declares. Charming adds the envelope, so don't wrap the return value in `{ ok, value }` or `{ value }` unless those fields belong to `outputSchema` itself. Common `kind`s: not_found, unknown_operation, operation_not_found, method_not_allowed, operation_failed, timeout, unauthorized, stored_value_too_large, storage_full. An `executor_error` may include `details: { execution, operationId, reservationId? }`. `execution: "not_started"` means the authority permanently ruled out execution of that operation. `"may_have_run"` means the operation may have executed; inspect its state before trying again. If admission failed before the authority returned an identity, `details` contains only `execution: "may_have_run"`. An operation that runs past its time limit answers 504 `timeout` instead, and its `details` carry the same `execution` fields next to `limit`, `limitMs`, and `elapsedMs`. A 401 on a bearer failure has `error.kind: "unauthorized"`. An optional `error.reason` distinguishes structurally different cases when you need to branch: `token_malformed`, `token_unknown`, `token_revoked`, and, for an App created anonymously before packages, `token_revoked_post_claim` with an `error.recovery = { kind: "pair", start, verification_url, instructions }` block. Branch on `error.kind` for the recovery flow (always works); branch on `error.reason` only when you need finer detail. When `error.recovery` is present, prefer its `instructions` over the generic recovery copy. `error.recovery` is a discriminated union (keyed on `recovery.kind`) the server attaches to error envelopes the agent can self-correct on. The mapping from `error.kind` to `recovery.kind`: | error.kind | recovery.kind | what to do | | ----------------------------------------------------------------------- | ----------------- | ------------------------------------------------------- | | token_revoked_post_claim | pair | pair to recover a chrm_user_* and retry | | rate_limited, too_many_requests | retry | sleep `retry_after_sec` then retry the same URL | | payload_too_large, module_too_large, ui_too_large, styles_too_large, | shrink | trim the named `field` under `cap_bytes` and retry | | edits_too_large, text_too_large, structured_data_too_large, | | | | asset_too_large, asset_count_exceeded, asset_quota_exceeded, | | | | description_too_long, secret_too_large, template_listing_too_large | | | | revision_mismatch, invalid_if_match, precondition_required | refetch | GET `refetch_url`, then retry with the fresh ETag | | forbidden_write | fix_route_label | DO NOT retry — fix the app's route metadata | | manifest_id_immutable, manifest_id_conflict | rename | keep package.json `name` stable; use charming.name / rename_app | | contract_migration_required | migrate_contract | send `files` with migrate_contract: true; give a file as { "from": "module", "edits": [...] } to skip resending it (see Migrating below) | | account_not_joined | (no recovery) | ask the person to open the Join page in `message`, then retry | | invalid_input, not_found, forbidden, invalid_module, … | (no recovery) | fail-fast — there is no self-correctable retry | The `shrink` caps: every file except `styles.css` counts toward one 1024 KiB cap, `styles.css` is capped at 256 KiB, and a `POST /app` or `PUT /app/` body at 1536 KiB. A signed-in account can create or copy 60 apps a minute across HTTP and MCP; past that the call fails with `rate_limited` and creates nothing. # The UI `ui.js` is an ES module. Charming injects `
`, a Tailwind@v3-compatible runtime implementation (UnoCSS), and a default theme; the build bundles `ui.js` with the files and packages it imports into one inline module that populates `#app`. Call your backend through the browser host module. `api` already targets this App and strips the `{ ok, value }` envelope: you get the `value` field only, never `ok`; it throws `CharmingOperationError` on `{ ok: false }`: ```js import { api, onStateChange } from 'charming:ui/app@1.0'; const todos = await api.list(); // the value itself (the array), not an envelope await api.add({ text: '...' }); // throws if the backend returns { ok: false } ``` `#app` starts empty, so set its `innerHTML` before attaching event listeners. Don't call the backend with the global `fetch()`: the UI runs in a null-origin frame where that request fails. `window.charming.user` is the signed-in viewer's public identity (`{ id, handle?, name?, image? }`), or `null` for an anonymous visitor; use it to greet or attribute, not to enforce access. The rest of the browser runtime (`window.charming.login`, `images`, `assets`, `openLink`, `viewer`) stays on `window.charming`. Make the outermost element fill the viewport, for example `
`. Don't put `max-w-*` or `container mx-auto` on the root, which leaves the whole app in a narrow column on a wide monitor. For a text-heavy view, cap the reading width on an inner wrapper: `
…
`. Dashboards, boards, tables, and canvases use the full width. To keep the view current, register `onStateChange(() => refresh())`, where `refresh` reads the data again and updates the DOM. It fires after every write from any caller (another tab, an agent, a Routine, a Webhook) and after a reconnect, so don't poll with `setInterval`. `styles.css` is optional and is the only stylesheet; the build injects it beside the module. Read https://charm.ing/docs/prompts/design-an-app.md before you write the UI — it covers the sandbox rules and how to avoid the generic-AI-app look. Credentials attach automatically — don't manage tokens client-side. Complete `window.charming` reference, including live state, identity, agent-host messages, files, images, links, and owner controls: https://charm.ing/docs/technical-reference/browser-runtime.md Dialogs: on the web `alert`/`confirm`/`prompt` are the browser's own; in chat embeds Charming's dialog replaces them and `confirm`/`prompt` return a Promise, so `await` them or use inline UI. Pointer lock works on the web for every app; fullscreen and a click-started `window.top.location` redirect need a claimed app. Chat embeds block all three, along with external `