# Building a YouOS app — guide for coding agents

You are helping someone build an app for the YouOS app platform (https://widgetstore.net/apps).
Read this whole file before writing code. Human tutorial: https://widgetstore.net/docs/ai/first-app

## What an app is

- A **static web app**: HTML / JS / CSS / images / fonts / wasm. No server code (phase 1).
- Packaged as a zip (≤ 10 MB, ≤ 300 files, each file ≤ 5 MB) with `widgetstore.app.json` and the entry HTML at the root (or inside one top folder).
- Hosted by YouOS on a separate origin, inside a sandbox **without** same-origin: no cookies, no `localStorage` / `IndexedDB` that persists, no access to YouOS's pages. Everything platform-related goes through the SDK.
- Allowed file types: html, htm, js, mjs, css, json, map, txt, md, svg, png, jpg, jpeg, gif, webp, avif, ico, woff, woff2, ttf, otf, mp3, ogg, wav, m4a, mp4, webm, wasm, csv, xml, webmanifest.

## Manifest: `widgetstore.app.json`

```json
{
  "name": "My App",
  "version": "1.0.0",
  "entry": "index.html",
  "icon": "icon.svg",
  "description": "One or two sentences.",
  "permissions": ["login", "sparks", "ai", "storage", "share", "chat"],
  "network": ["api.example.com"],
  "screenshots": ["shots/1.png"],
  "display": "fullscreen",
  "orientation": "landscape"
}
```

- `version`: semver (`1.2.3`). Bump it on every publish.
- `permissions`: only what you use. `sparks`, `ai` and `chat` calls fail with `permission_not_declared` if missing. `chat` = the app can be opened inside a conversation (mini app in chat).
- `network`: external https hosts your code calls with `fetch` / loads images or scripts from (max 5). Everything else is blocked by CSP. Not allowed: widgetstore.net, workers.dev, IP addresses.
- `display` (optional): `"standalone"` (default — YouOS shows its title bar; a full-screen button is always in the ⋯ menu) or `"fullscreen"` (games: on phones YouOS offers “Tap to play full screen” right away and goes full screen as soon as the user taps). `orientation` (optional): `"any"` (default), `"landscape"` or `"portrait"` — locked in the YouOS Android app and in browsers that allow it; elsewhere YouOS shows a “Rotate your phone” hint.
- `icon`: png / svg / webp / jpg, square, ≤ 512 KB. `id` is added by the CLI after the first publish — keep it.

## SDK

```html
<script src="https://widgetstore.net/apps/sdk/v1.js"></script>
```

Types: https://widgetstore.net/apps/sdk/v1.d.ts. Global `ws`:

```js
const ctx = await ws.ready();          // { app, lang: 'zh-CN'|'zh-TW'|'en'|'ja'|'ko', theme: 'light'|'dark', platform, preview }
ws.on('theme', (t) => …);              // the SDK also sets <html data-ws-theme="dark|light">
const { user, idToken } = await ws.login();   // user = { sub, name, avatar }; sub is per-app (pairwise)
await ws.getUser();                    // null if not signed in (no prompt)
await ws.sparks.balance();
await ws.sparks.charge({ amount: 30, reason: 'Unlock all colors' });   // integer 1–5000; user confirms
const r = await ws.ai.run({ prompt, system, history, json, maxTokens }); // r.text, r.credits (charged to the user)
await ws.storage.set('key', value); await ws.storage.get('key'); await ws.storage.remove('key'); await ws.storage.keys();
await ws.share({ title, text, url }); await ws.openUrl('https://…'); await ws.toast('Saved');
```

### Full screen and orientation (SDK 1.3)

```js
fsButton.onclick = () => ws.display.toggle({ orientation: 'landscape' }); // must run inside a click / tap (browser rule)
ws.display.onChange((s) => layout(s));  // { fullscreen, mode, orientation, locked, safeArea: { top, right, bottom, left } }
await ws.display.configure({ escape: 'app', edgeToEdge: true, gestureExclusion: [{ x: 0, y: 0.4, w: 0.3, h: 0.6 }] });
```

- YouOS does the work for you on every platform: the browser Fullscreen API (desktop browsers, Android Chrome, iPad), the YouOS phone app (status / navigation bars hidden, orientation locked, content under the notch), the YouOS desktop app (window full screen, sidebar and toolbar hidden — macOS gets its own full-screen Space) and, on iPhone browsers that can't go full screen, an **immersive mode** (all YouOS UI hidden, the frame fills the visible area; YouOS suggests “Add to Home Screen” for no address bar).
- Don't call `document.documentElement.requestFullscreen()` yourself — it only fills the frame and can't hide the bars or lock orientation. Use `ws.display`.
- Safe area: by default YouOS keeps your frame out of the notch / rounded corners / home indicator. If you'd rather draw edge to edge, pass `edgeToEdge: true` and pad your HUD with `var(--ws-safe-left)` etc. (the SDK sets them on `<html>`; `env(safe-area-inset-*)` is always 0 inside a frame). `<html data-ws-fullscreen>` / `data-ws-orientation` are set too.
- Esc leaves full screen. Games that use Esc themselves pass `escape: 'app'`: the user then **holds** Esc to leave. `gestureExclusion` keeps the Android back gesture away from your joystick / buttons (default in full-screen landscape: the lower half of both side edges).
- Errors: `fullscreen_denied` (the user didn't tap, or the platform refused — YouOS shows its own “Tap for full screen” button, so you can just ignore it).

Errors are `Error` objects with `code`: `not_in_host`, `cancelled` (user said no — not an error to show loudly), `login_required`, `insufficient_sparks`, `daily_limit`, `ai_daily_limit`, `permission_not_declared`, `storage_full`, `value_too_large`, `invalid_key`, `version_outdated` (ask the user to reload), `timeout`.

### Mini apps in chat (`chat` permission)

People open your app from **Messages → + → Mini apps** (an invite card), from a card your app posted, or from your app page (“Share to chat”). Everyone who opens the same card shares one **session**:

```js
const c = await ws.chat.context();     // null when not opened from a chat
// c = { chat: { id, type: 'private'|'group' }, me: { id }, session: { id, starter, starterId }, startParam }
ws.chat.session.on(({ from, data }) => …);       // messages from others in this session (from = their anonymous id)
await ws.chat.session.send({ t: 'move', m: 42 }); // JSON ≤ 2 KB, rate-limited (≈ 12/s, 240/min); end-to-end encrypted, relayed live, never stored
await ws.chat.session.save(state); const s = await ws.chat.session.load();  // ≤ 32 KB, on this device only
await ws.chat.share({ title: 'I won!', text: '57 moves', startParam: 'r1.abc' });  // the user confirms in YouOS; opening that card gives you startParam
```

- IDs are anonymous and **pairwise**: the same person has a different id in every app and every conversation. You never get user ids, names, contacts or messages — design for “You / Opponent / Player 2”.
- Messages only reach people who have the panel open right now. To survive disconnects, keep the full state with `save`, send a `hello` when you open, and let peers answer with their state (see the official Gomoku / Xiangqi samples: `game-net.js` merges states and validates every move).
- `startParam`: `A–Z a–z 0–9 . _ - ~ :`, ≤ 1000 characters. Use it for replays or deep links, never for secrets.
- `ws.chat.share` always shows YouOS’s confirmation; `cancelled` is normal. Don’t spam it — post at most one card per meaningful moment (a game result, a poll closing).
- Template: `widgetstore app init my-game --template chat-game`; `widgetstore app dev` simulates a chat (click “+ Player 2”).

### Multiplayer rooms (official games only, SDK 1.2)

`ws.game.*` connects to a server-refereed room (rules run on YouOS's server, every player only receives their own view — hidden cards stay hidden). It is reserved for official YouOS games for now; third-party apps get `game_not_available`. Design: https://widgetstore.net/docs (docs/GAMES.md in the repo).

```js
const { roomId, inviteCard } = await ws.game.create({ game: 'doudizhu', seats: 3 });
await ws.chat.share(inviteCard);                 // startParam "g.<roomId>"
await ws.game.join(roomId, { spectate: false });
ws.game.on('state', (s) => …);                   // { room, you, view, seq, turn, now }
await ws.game.act({ type: 'play', cards: [...] });
```

Limits: storage keys `^[A-Za-z0-9._:-]{1,100}$`, values JSON ≤ 16 KB, ≤ 200 keys and 512 KB per user per app. AI ≤ 100 calls per user per app per day. Charges ≤ 20,000 Sparks per user per app per day.

## Rules (checked automatically and by human review)

1. Support the user's language from `ctx.lang` when you can (zh-CN, zh-TW, en, ja, ko). If you ship one language, say so in the description.
2. Follow `ctx.theme` (light / dark) — the platform UI around your app follows it.
3. **Never** ask for passwords, card numbers, verification codes or YouOS credentials. Don't imitate YouOS's or another brand's UI. Password fields get extra review.
4. Before calling `ws.sparks.charge`, show clearly what the user gets. Never charge in a loop or on page load.
5. No crypto mining, no tracking scripts, no redirects to other sites without `ws.openUrl`.
6. If you store user data with `ws.storage` or send it to a `network` host, the app needs a privacy policy URL (set in the developer center).
7. Don't fake data: no made-up reviews, users or statistics. Sample content must be labelled as sample.

## Develop

```bash
widgetstore app init my-app --template blank|sparks|ai|chat-game
cd my-app && widgetstore app dev          # http://127.0.0.1:5178/ — simulated user, Sparks and AI, same sandbox
```

No desktop app? Serve the folder with any static server and open it inside an iframe that implements the protocol in `v1.js` (messages `{ ws: "wsapp/1", id, method, params }`), or just publish and use the private preview link.

## Publish

```bash
widgetstore app publish --slug my-app      # first time (creates the app; slug = URL name, 3–32 chars, a-z 0-9 -)
widgetstore app publish --notes "What changed"
```

Without the CLI, use the YouOS MCP server (https://widgetstore.net/mcp, scope `write:apps`):
`apps_create` → `apps_publish` (text files up to 48 KB) or `apps_upload_url` (then `curl -X PUT --data-binary @app.zip -H "Content-Type: application/zip" <url>`) → `apps_status` → `apps_release` (canary `pct` 1–99, roll back by releasing an older approved version).

Every upload is an immutable version. Automatic scan → human review for the first listing, new permissions / network hosts or password fields → live. Users always get the live version automatically.

## Money

The developer gets 50% of the Sparks users pay in the app (the part paid with purchased Sparks is withdrawable after a 30-day hold; payouts are reviewed and paid manually from 500,000 Sparks ≈ $50). AI calls are charged to the user at cost-based prices and are not shared.
