--- name: adding-an-app description: Add a custom app to a kody-os install — definition contract, bundle contract, state schema, set/append actions, and the pre-add_app checklist. Use when the user wants to add, author, validate, install, update, export, or remove an app, asks how app definitions, bundles, or actions work, or asks about the bundle/shell interaction contract, and when an app's display goes stale after a shell action. --- # Adding an app An app is a JSON definition in `packageStorage()`. Adding one is a registry write: no source change, no commit, no publish, no republish. The same definition works in the hosted OS and the local preview; the two stores are separate, so add it to each target you use. The browser shell has no add control. Agents add with the package's MCP `add_app` (or an `execute` wrapper). The shell can hide, pin, and add an app to the homepage; deletion is MCP-only (`remove_app`). Before installing any app, read `pkg/docs/install-guide.md` and follow it: security-check the bundle, tell the user the capabilities, and get the user’s go-ahead first. This applies to every install — from the App Store, from a recipe, or from anywhere else. Before writing a bundle that displays state, read the [Bundle/shell interaction contract](#bundleshell-interaction-contract) below and run the [pre-`add_app` authoring checklist](#pre-add_app-authoring-checklist). A bundle that only follows the definition contract above will render, but its display can go stale the first time a shell action form fires; the contract is what keeps bundle display and shell state in sync. ## Definition contract | Field | Required | Value | | --- | --- | --- | | `id` | yes | Slug matching `^[a-z0-9][a-z0-9-]{0,63}$`. Routes and storage keys use it. When the user did not supply an id, derive it from the display name (lowercase, non-alphanumerics to single dashes, trim leading/trailing dashes); check `list_apps` first — if that id is already installed, ask the user before reusing it. | | `name` | yes | Non-empty display name. | | `label` | no | Tile label. Defaults to `name`. | | `icon` | no | Plain-text glyph or short mark (never an emoji), OR a sanitized inline SVG starting with `` always renders the full page, and home widget presence is governed by the homepage list, not by this field. | | `ui.placements` | deprecated | Old allowlist (`page`, `modal`, `widget`). Still accepted, but it gates nothing: when a definition carries `placements` but no `openAs`, the shell derives `openAs` from it — `["modal"]` without `"page"` derives `"modal"`, any other value derives `"page"` — and when both fields are present, `openAs` wins. Stored and exported definitions carry `openAs` and no `placements`; re-export once to migrate an old definition. | | `ui.actions` | no | Array of `{ action, label }`. Each `action` must exist in `actions`. Buttons are no-argument GET forms. | | `ui.menuBar` | no | Boolean. When `true`, the app also appears in the top menu bar while installed (after Apps, alphabetically by label, linking to `/apps/`). Author-controlled, not a user toggle: there is no menu on/off control, and uninstalling the app removes its link automatically. Hidden apps are excluded from the menu. Defaults to `false`. | | `ui.help` | no | Plain-text how-to-use string (one string, one or two short lines saying what the controls do; line breaks are preserved in the dialog). Ship one on every app: every catalog app carries it. When present, the app header gains a `[?]` button immediately left of expand that opens the standard modal (no fragment, no navigation) showing a `{app name} - Help` header line, this text (escaped, never interpreted as HTML/markdown — no links in v1), and a normal Close button. Absent (missing, or empty/whitespace-only, which canonicalization drops) means no button. Distinct from `description`: `description` is what the app is for; `help` is how to use it. | | `stateSchema.type` | yes | `"object"`. | | `stateSchema.initial` | yes | Initial values. Every key must be declared in `fields`. | | `stateSchema.fields` | yes | Map of field name to `{ type, min?, max?, maxLength?, items?, maxItems? }`; `type` is `integer`, `string`, `boolean`, `array`, or `object` (schemaVersion 5). `min`/`max` apply to integers; `maxLength` to strings; `items` (`integer`/`string`/`boolean`/`object`) and `maxItems` to arrays. | | `bundle` | yes | `{ entry: "index.html", files: { path: content } }` (inline map, the `add_app` transport and stored form) or `{ entry: "index.html", files: [path, ...] }` (on-disk manifest list, the catalog authoring form). Never both. See the bundle contract below. | | `actions` | yes | `{ [name]: { description?, args?, effects } }`. | | `actions.*.effects` | yes | Non-empty array of `set` / `append` effects (see below), applied in order. `increment`, `toggle`, and `reset` are deprecated sugar kept only until migration retires them; do not use them in new apps. | | `actions.*.args` | no | `{ [name]: { type, required?, default?, min?, max?, maxLength? } }`. Values are coerced from form strings. | | `capabilities.feeds` | no | Array of `{ name, url, ttlSeconds?, maxBytes? }` (at most 8). Declares allowlisted upstream feeds the app may read through `GET /feed//` — HTTPS only, served same-origin with storage caching. Never put a URL from user input here; the route takes only the declared feed name. | | `capabilities.proxy` | no | Array of `{ name, url, ttlSeconds?, maxBytes? }` (at most 8), same limits as feeds. Declares allowlisted generic upstreams the app may read through `GET /proxy//` — HTTPS only, served same-origin with storage caching. The route takes only the declared proxy name. | | `capabilities.manageApps` | no | Boolean. When `true`, the app may use the shell management API (`GET /manage/rows|install|update|restore`). Undeclared callers get a plain 404. Capabilities are installer disclosure plus this allowlist, not a sandbox: bundle scripts run same-origin with the visitor's authority, so declaring a capability does not stop a malicious bundle from calling a shell route directly. | | `capabilities.theme` | no | `{ view: boolean, set: boolean }`. Declares shell theme access through `GET /theme/`: `view` allows the read route, `set` allows set and reset. A definition with neither flag true is treated as not declaring theme. Undeclared callers get a plain 404. Capabilities are installer disclosure plus this allowlist, not a sandbox: bundle scripts run same-origin with the visitor's authority, so declaring a capability does not stop a malicious bundle from calling a shell route directly. | Effects: | `op` | Fields | Notes | | --- | --- | --- | | `set` | `field`, `value?`, `fromArg?` | `field` must be declared. Provide `value` or `fromArg` (an arg name). | | `append` | `field`, `value?`, `fromArg?`, `cap?`, `maxEntryBytes?` | `field` must be a declared `array`. Appends one entry; oldest entries drop first past `cap` (default 500); string entries over `maxEntryBytes` (default 2048) are rejected. | Definitions are JSON: no code, `eval`, or imports. The two effect operators are implemented once in the package registry; `add_app` validation rejects any other `op`. Agents compose apps from these fixed operators—they do not invent new operators per app. Each action carries a non-empty `effects[]` sequence applied in order. The package storage budget is 16 MiB. ### What `set` and `append` actually are They are generic data-write operators, not a built-in counter app. `counter` is only a test harness that happens to use them. Any app may define its own actions with either of: - `set`: write a fixed value—or a validated arg—to a declared field. - `append`: append a fixed entry—or a validated arg—to a declared array field, with length and entry-byte caps. Each app has isolated state at `kody-os.apps.state.`. Every action coerces its args, applies the effect to a copy of state, re-validates the result against the schema, then writes with a single set. A bad action returns `{ ok: false, error }` and leaves stored state untouched. One app cannot touch another app’s state. Stated plainly: there is no `random`/`shuffle` operator, and UI buttons carry no arguments. A true Magic 8-ball “shake” keeps its randomness in bundle JS and persists the outcome through a `set`/`append` action (see `catalog/eight-ball/definition.json`); arg-taking actions are driven through MCP `act(id, action, args)` or bundle `fetch`. Do not invent new operators per app; they are only these two. ### Kindle Scribe browser: what agents may assume Available: - Plain server-rendered HTML, links, and GET forms. - Inline CSS only; system fonts; high-contrast black-on-white. - Server-side state in `packageStorage()`; no reliance on cookies or `localStorage`. - Guarded vanilla-JS enhancement: if `fetch`/JSON parsing exist, the shell may replay the same GET action with `?format=json` and patch fields in place. If not, the same form still works through full navigation. Not available to depend on: - Client-side routing, or JS-required actions. - Mutating POST forms or `fetch` POST in the UI; the Kody edge rejects cross-origin/null-origin POSTs to package-app subdomains. - WebSockets, timers/polling, auto-refresh, background sync, animations/transitions. - External stylesheets or external scripts. - Cookies/`localStorage` as functional storage; treat them as absent. The shell provides the bridge adapter, `window.KodyBridge` v1, and the vendored Lit, `window.KodyLit` (Lit 3.3.3) — see the provided surface in the [Bundle/shell interaction contract](#bundleshell-interaction-contract). The second-app gate is passed for both: Counter and xkcd are ported to the bridge, and Counter and link-drop are ported to the provided Lit. Per-app framework vendoring is not the recommended path; it is a documented fallback only (pinned version + update owner). JavaScript itself is assumed: the on-device probe in `scribe-limitations.md` proves Chromium 80 with working fetch, timers, events, DOM, and storage. The span-based state contract in this guide documents current shell behavior for existing bundles; new bundles use the JSON seed through the bridge, not span scraping. ReKindle is existence proof that guarded vanilla JS can run in a Kindle browser. It is not proof of modern APIs, storage, sockets, or timers. So: enhance where present, never require. ### Access transport Access is Kody login only: a platform-verified Kody visitor is served, verified per request — no code, no session, no cookie, no credential of any kind. The client enhancement's `fetch` (`format=json`) fast path and bundle bridge actions send same-origin requests (`credentials: 'same-origin'`) and attach no credential to the URL, falling back to native submit on any failure. Without JavaScript the plain GET still submits. No `?k=`, no hidden credential field, ever: a request presenting a retired credential is denied exactly like an unauthenticated request. Access is decided by Kody's permission system, not by the shell: any browser signed in to Kody with Use / `app:execute` on the app is served, and the shell performs no access check of its own. Local `kody dev --target mock` needs no credential because there is no gate at all. See the [Setup guide](../../../docs/setup.md). ### Bundle contract Every app ships its own UI files: there is no separate bundle kind and no `kind` field. Two forms, one runtime (carrying both is an error): the inline files map `{ bundle: { entry: "index.html", files: { path: content } } }` — the `add_app` transport form (an agent can only pass JSON) and the stored form — and the on-disk manifest list `{ bundle: { entry: "index.html", files: ["index.html", "app.js", ...] } }` — the catalog authoring form, with the real files flat next to `definition.json` and `RECIPE.md`. Tooling (`scripts/build-catalog-index.ts`, `assembleBundleFiles`) resolves the list to the runtime map before validating references, fingerprinting, or storing. The entry HTML references its assets explicitly by bare relative path (``, ``); the loader inlines each referenced file at serve time so the served document stays one self-contained HTML document. Every reference must resolve to a manifest file, every `.js`/`.css` manifest file must be referenced (dead files are an error; unreferenced non-entry `.html` is ignored), references carry no attributes beyond `src`/`href` (`rel` for links), and absolute or external URLs are rejected. Every path must be a relative `.html`, `.js`, or `.css` path with no `..` and no absolute path; deeper nesting beyond one level is not accepted. The files in one bundle must total no more than 256 KiB (`BUNDLE_CAP_BYTES = 256 * 1024`, part of the 16 MiB package storage budget). A definition with a `kind` field is rejected with guidance naming the unified shape. Catalog rule: editing an app's bundle files requires re-running the catalog-index generator (`bun scripts/build-catalog-index.ts` from the repo root) — never hand-edit `catalog.json`; extraction without content change needs no `catalogVersion` bump. See `catalog/counter/index.html` with `catalog/counter/definition.json`, `catalog/app-store/` (manifest plus `store.js`/`store.css`), and `catalog/clock/` (modal placement) for installable shapes. Validation rejects bad bundles before any write and returns `{ ok: false, error }`: - `definition.bundle.entry must be "index.html"` - `definition.bundle.files is missing the entry "index.html"` - `definition.bundle.files has bad path "..." (relative .html/.js/.css only, no "..", no absolute paths)` - `definition.bundle.files."..." must be a string` - `definition.bundle.files total ... bytes exceeds the 256 KiB cap` - manifest-list errors: bad path, duplicate entry, file missing on disk, dangling `
…bundle HTML…

:

``` The bundle container sits inside `
` on app pages and modal overlays; a home widget renders the same content inside `
`. (Widget sections carried no `data-app-id` before v0.2.1 — that gap made the bridge read another app's seed on the home screen; do not assume it is absent.) The state readout is a `

` containing the field name as text and a plain `` holding the escaped value. There is **no `data-value` attribute** on the paragraph or the span. With `ui.hideState: true` the paragraph carries `hidden`; the span stays in the DOM with the current value. `ui.actions` forms are shell-owned GET forms: `form.app-action`, hidden `action` input (plus `from` when present), one submit button. No form carries a credential. A bundle must not rewrite, replace, or restyle these forms as its own, and must not assume any other markup for state or actions. **2. Initial-state reading.** A bundle using the bridge reads its initial value from the JSON seed the shell renders before the bundle (rule 1) — the seed is present at bundle-script time, which the span readout is not (2026-10-30 Scribe probe: span present only by `DOMContentLoaded`). The bridge (`KodyBridge.create`) reads the seed for the bundle's section, falling back to the spans only when no seed is present. A hand-rolled bundle that displays a declared state field reads its initial value from the rendered `[data-field]` span's text. Never assume a `data-value` attribute exists: the renderer emits none, so a bundle that reads one silently falls back to whatever it hardcoded. The Counter bundle's stored display is hardcoded to `0`; reading its own display alone would restart the counter at `0` on every page load. Read the seed (bridge) or the span (hand-rolled) first, and treat the bundle's own static markup only as a last-resort fallback when neither is present at all. **3. Shell-client patch semantics.** In a capable browser (where `fetch`, `querySelector`, and JSON parsing all exist), the shell client (`pkg/src/client/index.ts`) replays a submitted `form.app-action` as the same GET URL plus `?format=json` with `Accept: application/json`. On `{ ok: true, state }` it patches **only** the `[data-field]` spans inside the nearest `[data-app-id]` ancestor (or the enclosing `

`, or the document when neither exists), setting each span's `textContent` from the returned state for keys present in it, and clears or shows the in-place `role="alert"` error. It never writes to bundle-owned DOM and never touches bundle variables. Any failure — fetch error, unparsable response, missing `ok`, non-object state, cross-origin URL guard — falls back to native `form.submit()`: full navigation, server redirect, fresh render. On the server, `k`, `from`, and `format` are stripped before the action runs, so they never become action arguments. A bundle therefore cannot rely on the shell client to update its display: after a shell-form action, only the span has moved. **4. Form ownership and the capture/sequencing pattern.** When a bundle has its own buttons for an action that a shell `ui.actions` form also performs (Counter's `+1`/`-1` buttons share state with the shell Reset form), the bundle must handle the shared action with all four parts, scoped to its own section: - **Capture-phase claim, scoped to the app's own form.** Register a capture-phase `submit` listener on the document. Claim a submit only when the form is inside the bundle's own section scope, its `input[name="action"]` names the shared action, and its form action base matches the bundle's own `data-action-base`. On a claim, prevent the default and stop propagation so the shell client's fetch never starts, paint optimistically at once, and send the write through the bundle's single-flight queue (rule 5). Never claim another app's form, and never claim a form for a different action. - **Optimistic paint.** Paint the intended value immediately, in both the bundle's display and the shell span (rule 6), before any fetch resolves. A shell-form action with no optimistic paint feels a full round trip behind the bundle's own buttons. - **Sequencing guard.** Count local actions (steps and claimed submits) in order. Record the sequence number of a Reset-style submit; a shell span patch that arrives after the sequence has moved past it is stale and must not be adopted. Without this guard, a late shell patch (the Reset value) overwrites a step taken after Reset was pressed, and the in-flight handler can then re-send the stale value server-side, losing the step for good. The reverse ordering fails the same way: a stale pre-Reset response must not repaint the old value after Reset. - **`MutationObserver` adoption, with a form-level fallback.** Observe the `[data-field]` paragraph (child list, character data, subtree, attributes) and adopt a value the bundle did not itself paint — that is how a shell-form action the bundle did not claim (or a claim that never delivered) still resets the bundle's display and internal count. The observer must not loop (painting the same value back is no change) and must not fire extra fetches. As a fallback for engines that do not deliver submit capture, attach a form-level `submit` listener that paints and sequences at submit time without claiming the submit: the shell client's fetch still owns the server call, and the sequencing guard keeps its late patch from losing steps taken since. A bundle with no shared actions needs none of this; a bundle whose buttons are the only writers to its fields needs only rules 5 and 6. The no-JS path needs none of it either: native submit reloads the page and initialization reads the freshly rendered span. **5. Single-flight ordered queue.** One in-flight state write per app. Clicks update a single desired value and paint it immediately; `flush` sends at most one request at a time, and inputs made while one is in flight coalesce into a single follow-up request for the latest desired value — rapid clicks never send duplicate writes with the same value. On a response, if the server value differs from the in-flight value (someone else moved the state), rebase the pending deltas onto the server value instead of overwriting the desired value. On fetch or JSON failure, fall back to full navigation for the latest desired value, and clear the in-flight flag so the bundle is not wedged: the next input must send again. The Counter bundle's `flushCounter` / `stepCounter` / `desiredCount` / `confirmedCount` variables are the reference shape of this queue. **6. Paint/sync.** When a bundle paints, it writes the same value to its own display and to the shell `[data-field]` span, so the two never diverge. Initialize on `DOMContentLoaded`, guarded against double initialization, by reading the span (rule 2) and painting that value before wiring observers and listeners. Keep one source of truth after initialization (desired vs. confirmed counts in the Counter bundle): never re-read the painted DOM as the current value, because it only changes when a fetch returns or the shell patches it. **7. Action-URL resolution (`data-action-base`).** Bundle buttons that mutate state SHALL resolve their action URL from their own `.bundle` container's `data-action-base` attribute, never from `window.location.pathname` alone. The shell stamps `data-action-base="/apps/"` on every bundle container it renders — app page, modal overlay, and home widget — so the same button acts on the owning app from the dashboard as well as from the app's own page. Walk up from the clicked element to the nearest ancestor carrying the attribute and fall back to `window.location.pathname` only when it is absent (an older shell). When the button uses `fetch` for the `?format=json` fast path, pass `credentials: 'same-origin'` so the platform-verified Kody visitor authenticates the request, attach no credential to the URL, and keep the full-navigation fallback. The Counter bundle's `actionBase()` is the reference implementation. The checklist below rejects any bundle that builds action URLs from `window.location.pathname` alone. **Bridge adapter (recommended path, `window.KodyBridge` v1).** A stateful bundle SHOULD use the bridge. It is loaded once by the shell client module (so it exists by `DOMContentLoaded`, when bundles init), and it is instantiated per app section — one store per section, never shared across sections. The source of truth is `pkg/src/client/bridge.js` (plain ES2019, classic-script compatible); the Counter bundle is the reference consumer. **FE/BE boundary.** The shell's browser code (FE) lives in `pkg/src/client/` — the client module, the bridge adapter, and the shared `os-*` elements — and the Kody code (BE) lives in `pkg/src/` outside `client/`. No FE module imports a BE module. A bundle talks to the BE only through the contract above (bridge, JSON seed, action URLs, `data-*` attributes); it never imports shell code or reads BE-only state. See `pkg/AGENTS.md` ("Frontend / backend boundary"). **Client-side navigation (shell pages only).** The shell client navigates Home (`/`) and Apps (`/apps`) client-side: it intercepts same-origin clicks to those pages, fetches the target as HTML, and swaps the `#os-main` content in place, updating the title and nav `aria-current` and pushing the URL with `history.pushState`; back/forward works the same way. Any failure falls back to a native full page load. App pages, Help, and About stay full-load. A bundle therefore cannot rely on `DOMContentLoaded` re-firing when the user navigates between Home and Apps — the page is not reloaded, only `#os-main` is swapped. Bundles mount at `DOMContentLoaded` and are not re-mounted after a swap. Home widgets render app bundles, and a swap does not re-mount them, so a page whose `#os-main` contains a bundle section (`section[data-app-id]`) is never swapped in — it falls back to a native full load so the bundle mounts. A bundle must not assume it will be re-initialised by a shell-page navigation, including when it appears as a Home widget. - **Create:** `var store = window.KodyBridge.create(section, { fieldTypes: { count: 'integer' }, reassert: fn })`, where `section` is the bundle's `
` (capture it from `document.currentScript` at parse time, falling back to the first `section[data-app-id]` — never to a seed `