# OJPlay for agents

You were asked to make a cart on OJPlay (play.onejs.com), or handed one. This page is the whole loop. Every docs page is also plain Markdown; the list is at the end.

A cart is a small interactive program in React and TypeScript, and a git repository. **Work on it on this machine and push it**: you write, check and run it here, and a push to `main` builds it on the site and makes it what runs. Do not edit a cart in the site's editor; that is the user's.

## A new cart

```bash
npx ojplay new "<name>"          # the starter in ./<name>, a git repository; no login, no network
cd <name>
npm install
npx ojplay typecheck
npx ojplay run --watch           # the site's real container in a local Chrome, swapping in each save
npx ojplay test                  # headless; fails on a console error
git add -A && git commit -m "<what changed>"
npx ojplay push                  # the first push puts it on play.onejs.com
```

- **The first push makes the cart on the site**, its repo and its first cart both public, under the `name` in `oj.json`, and sends your commits. With no login it starts one first (below) and carries on once the user presses Allow. Pushes after that are ordinary pushes.
- **A name the account already has is refused**, with that cart's address, and nothing is made or pushed. That cart is the user's own work: rename yours in `oj.json`, commit, and push again, or ask the user whether they meant that cart. Never push to a cart you did not make unless the user asked you to.
- **A new cart is public, and so is its repo.** Anybody can open it, read its source and every commit in its history, and fork it, from the first push on. Making a cart Unlisted or Private changes who can play it, not who can read its source: that is the repo's setting: Private in the cart's Settings, or `npx ojplay push --private` on the first push, makes the repo private. Never commit a key, a token, a `.env` file or anything else the user would not publish. The catalog lists a Public cart once it has a build past the starter.
- **Run every command as `npx ojplay <command>`**, in a cart or outside one: inside a cart it runs the copy `npm install` put there. Never shorten it to `oj` after npx, which fetches an unrelated npm package, and never use onejs-play, ojplay's former name, which is frozen at an old version.
- `ojplay` needs Node 22 or newer. `run` and `test` need Chrome (`OJ_CHROME` names the binary when it is not in the usual place). `npx ojplay help` lists the rest.

## A cart already on the site

```bash
npx ojplay clone <@handle/name or sid>   # git pull and push in it then work with the login or OJ_TOKEN
cd <name>
npx ojplay init && npm install           # package.json, tsconfig.json, types; all gitignored
```

Then the same loop: `typecheck`, `run --watch`, `test`, commit, `npx ojplay push`.

## Log in

```bash
npx ojplay login
```

It prints a link. **Show it to the user**: they open it, signed in to play.onejs.com, and press Allow. The command waits (up to ten minutes) and then stores a token for this machine; git uses it for play.onejs.com from then on, so `git clone`, `pull` and `push` need nothing more. A first push with no login does the same. If your shell cannot wait that long, `npx ojplay login --no-wait` prints the link and exits, and `npx ojplay login --wait` collects the token once the user has pressed Allow (`--wait <code>` when more than one login is waiting on this machine).

- **What a login can do:** create carts, edit them, push and rebuild. Editing includes renaming: the name is `name` in `oj.json`. Deleting and the account settings stay with the user. They delete a cart in its Settings: the gear in its editor (its address plus `/edit`) or on [/manage](https://play.onejs.com/manage).
- **`main` takes fast forwards only** from a login: `git pull` first when the user may have edited in the browser.
- The Allow page shows the name the login sends, like `claude on mac`, read from your environment. `--name "<name>"` sets it.
- `npx ojplay logout` forgets the login, here and on the site. A login lasts 30 days. A refused login says why (replaced, revoked, logged out or expired); run `npx ojplay login` again.
- `OJ_TOKEN`, a token the user made at [/manage/tokens](https://play.onejs.com/manage/tokens), is used instead when set, by ojplay and by git in a cart ojplay made. Never commit a token, print it, or write it into a git config.

## Using another cart

```bash
npx ojplay add @singtaa/lightning   # oj.json gets its newest version; its source and art go in .oj/carts
```

- Then import it: `import { Bolt } from "@singtaa/lightning"`. `add` prints what the cart exports and the import line. A cart that exports nothing is a whole cart, and `import "@singtaa/lightning"` runs it.
- In an empty folder, `add` starts a new cart that uses it: `oj.json` and an `index.tsx` that shows it. No login is needed for a public cart.
- `npx ojplay update` moves each used cart to its newest version in the same major (`--major` for the newest of all). `npx ojplay remove <address>` takes one out and names the files that still import it.
- A cart's own `exports` in `oj.json` names the file other carts import from. Its `version` is what `add` pins.

## The user's carts

```bash
npx ojplay list            # every cart on the account, a repo's carts each on a line
```

Or `GET https://play.onejs.com/api/me/carts` with the bearer token: `{"handle", "carts": [{"sid", "name", "cart", "address", "ref", "visibility", "repoPublic", "url", "clone", "head", "live", "buildError"}]}`. `sid` is the repo, `cart` the cart's own id (the repo's first cart has the repo's sid), `ref` what it runs (`{"kind": "branch" | "version" | "commit", "name"}`), and `visibility` who can play it: `public`, `unlisted` or `private`.

- **Use this to answer "which carts do I have".** `GET /api/games` lists only Public carts, from everyone, and misses every Unlisted and Private one.
- **A cart's settings** (who can play it, what it runs, the repo's source) are `POST https://play.onejs.com/api/carts/<cart>/settings` with the bearer token and JSON `{"visibility"?, "runs"?: "branch:main" | "version:1.2.0" | "commit:<sha>", "source"?: "public" | "private"}`. Change them only when the user asks.

## What a push says

The site builds the pushed commit and answers on the push's own `remote:` lines.

```text
remote: built 3f2a91c: 2 files, 41 KB
remote: live at https://play.onejs.com/@<handle>/<name>
```

It moves every cart that follows the branch, with a `live at` line for each.

```text
remote: 3f2a91c did not build: index.tsx:12:5: Expected ";" but found "x"
remote: still running 9b04d1e
```

A push of another branch moves that branch's carts and never main's. A branch with no cart gets one, Unlisted:

```text
remote: built 5c19e07: 2 files, 41 KB
remote: live at https://play.onejs.com/@<handle>/<name>@<branch>
remote: main is unchanged, at 3f2a91c
```

- **A push that does not build is still kept.** The last commit that built keeps running. Fix it and push again.
- `npx ojplay push` is `git push origin <the branch you are on>` that exits 1 when the tip did not build, or when nothing was pushed because the changes are not committed. In a cart made with `new`, its first push makes the cart on the site first.
- `npx ojplay status` says what main built, why its tip differs, and what each cart runs, in sentences. `npx ojplay status --json`, or `GET https://play.onejs.com/api/games/<sid>` with the bearer token, answers `head` (the tip of `main`), `main` (`built`, main's newest build, and `buildError`, why `head` is not `built`, or null), `url`, `repoPublic`, and `carts`, each with its `cart`, `address`, `ref`, `visibility`, `live` (what it runs) and `buildError`.

## Rules

- **Work on `main`.** The user's edits in the browser are a draft only they see, and reach `main` when they press Push, so `git pull` before you push when they may have pushed. Your push never loses their unpushed edits.
- **Try a risky change on a branch.** `git switch -c <branch>`, commit, and `npx ojplay push` builds it as an Unlisted cart at the cart's address plus `@<branch>` and prints it; what players get on main does not change. Show the user the link. To ship it, merge it into `main` and push. A branch may not be named like a version (`1.2.0`) or a commit.
- **Release by changing `version` in `oj.json`**, never with a git tag. The site tags each release `v1.3.0` itself, and refuses a pushed tag named like a version.
- **Never force-push.** A login cannot, and with a token the site accepts one, which throws away what the user pushed from the browser.
- **Check before you push.** `npx ojplay typecheck` checks by the Play editor's rules, and it and `npx ojplay test` catch what the site's build would reject, and the console errors it would not.
- **The user's open editor swaps in each build as it goes live.** If they have edits they have not pushed, those stay, and their Push lists yours as coming in and asks about any file you both changed. `git pull` before your next push.
- **A cart is `index.tsx` and `oj.json`**, plus any files it imports or loads. What `init` writes stays out of git.
- **Say how a change was made, when the cart asks.** If `oj.json` has `"prompts": true`, end each commit message with the user's request as they wrote it and the agent that acted on it, as git trailers. The cart's history page shows them under the commit:

  ```text
  Keep a best score beside the score

  Prompt: Keep a best score that survives a restart, and show it next to the
   score.
  Agent: Claude Code (claude-opus-5-5)
  ```

  Continue a long prompt on lines that start with a space, and give one `Prompt:` line per message when a change took several. Only the user's words go in, never your plan or a file. Anything secret in them (a token, a password, an email address) becomes `[removed]`. Without `"prompts": true`, write neither trailer.

## Writing a cart

Everything comes from `"oj"`, and `mount()` renders the root.

```tsx
import { useRef } from "react"
import { View, Text, mount, useFrame, useStage, input, type VisualElement } from "oj"

function Game() {
    const stage = useStage()                  // { width, height }, the window in pixels
    const x = useRef(100)
    const box = useRef<VisualElement>(null)   // the element, once it mounts
    useFrame((dt) => {                        // every frame; dt in seconds
        x.current += input.keyboard.arrows().x * 300 * dt
        if (box.current) box.current.style.left = x.current   // move by style, not by React state
    })
    return (
        <View style={{ flexGrow: 1, backgroundColor: "#14181d" }}>
            <View ref={box} style={{ position: "absolute", top: stage.height / 2, width: 40, height: 40, backgroundColor: "#4ade80" }} />
            <Text style={{ color: "white", fontSize: 24, unityFontStyleAndWeight: "bold" }}>Score 0</Text>
        </View>
    )
}

mount(<Game />)
```

- **Keys are Unity's names:** `"LeftArrow"`, `"A"`, `"Space"`, `"Enter"`. `input.keyboard.isKeyDown(name)` while held, `wasKeyPressed(name)` and `wasKeyReleased(name)` for one frame, `keysPressed` for every key that went down this frame in the order it was typed (read it for text, since a fast typist puts several letters in one frame), `arrows()` and `wasd()` as a vector whose y is +1 for up, the opposite of the stage's y.
- **The mouse and touches:** `input.mouse.position`, `input.touches`, in window pixels. `useSwipe((direction) => ...)` for swipes.
- **Positive y is down.** The origin is the top left of the stage.
- **Styles are objects.** Numbers are pixels, colours are strings, layout is flexbox only. Bold is `unityFontStyleAndWeight: "bold"`, lower case; there is no `fontWeight`.
- **Per frame motion goes through a ref's `style`,** not `setState`. Re-render for things that change rarely, like a score.
- **Drawing:** `useDrawing(ref, (p) => p.fillColor("#fd0").beginPath().circle(x, y, r).fill(), "frame")` draws into a View and redraws every frame; pass deps instead of `"frame"` to redraw only when they change.
- **3D:** one `useScene()` per cart, near the top, and `useModel("ghost.glb")`, then `scene.spawn(model, { position, play })`. A scene with no options has a camera, a sun with soft shadows and ambient light; options only tune them, and `scene.sun()`, `scene.fog()` and friends change them live. An actor has `position`, `rotation`, `scale`, `speed` and `dissolve({ to, seconds })`; `scene.paused` holds them all. `scene.pick(e.x, e.y)` and `actor.screenPoint()` for clicks and labels. Details in [3D](https://play.onejs.com/docs/3d.md).
- **Files** (png, jpg, sounds, fonts, glb) sit in the repository and load by their path from the root: `useTexture("art/coin.png")` and `useSound("pop.wav")` (each null until it arrives), `assetUrl("logo.png")`. Never under a top level `assets/` folder.
- **What the first frame needs goes in `preload` in `oj.json`** (`"preload": ["music/theme.ogg", "levels/1/"]`, a trailing `/` for a folder): those files load before the cart appears. Later loads use `preload(names, onProgress)` from `oj`, and `unload(names)` frees a finished level's pictures and models.

## Testing with `npx ojplay test`

`npx ojplay test` with no script lets the cart run two seconds, then fails on a console error, an asset the site would not serve, or controls out of line. `npx ojplay test playtest.mjs` hands a script the running cart:

```js
export default async function (cart) {
    const before = await cart.read()                  // the text on screen, top to bottom
    const release = await cart.hold("ArrowRight")
    await cart.wait(500)
    await release()
    await cart.press("Space")
    await cart.until(async () => (await cart.read()).some((t) => t.includes("Score 1")), { what: "a coin" })
    await cart.shot(".oj/after.png")                  // look at it
}
```

`read()`, `find(text)` (where it is on screen, `{ x, y, width, height }`, once laid out), `click(x, y)`, `drag()`, `move(x, y)`, `press(code)`, `hold(code)` (returns a release function), `type(text)`, `wait(ms)`, `until(predicate, { timeoutMs, what })`, `stage()`, `eval(js)`, `shot(file)`, `reload()`, `errors`, `console`. Coordinates are stage pixels. A thrown error fails the run. A screenshot lands in `.oj/` either way.

## Every docs page, as Markdown

- [Start](https://play.onejs.com/docs/start.md): Open a cart, change a number, run it
- [Writing a Cart](https://play.onejs.com/docs/writing-a-cart.md): The entry point, the frame loop, and the manifest
- [Elements and Styling](https://play.onejs.com/docs/elements-and-styling.md): The elements a cart draws with, how styling works, and the traps in it
- [The Stage](https://play.onejs.com/docs/stage.md): The window your cart gets, and how to fit a fixed board inside it
- [Files](https://play.onejs.com/docs/files.md): Sprites, sounds, fonts and covers
- [Effects](https://play.onejs.com/docs/effects.md): Particles, textures and per pixel programs
- [3D](https://play.onejs.com/docs/3d.md): Models from .glb files, with a sun, shadows and lights
- [Physics](https://play.onejs.com/docs/physics.md): Bodies that fall and collide, a character that walks, rays, sight, triggers, rewind and paths, in 3D and on the 2D stage
- [Baked Light](https://play.onejs.com/docs/light.md): Light that bounces round a 3D scene, baked once and saved with the cart
- [Opening in Unity](https://play.onejs.com/docs/unity.md): Add a cart to a Unity project
- [Showing Values](https://play.onejs.com/docs/show.md): show() puts a value beside the line that made it, or draws it as a table or a graph
