# Control Lucky Engine from your agent

Start with the application URL. Its `Link` response header advertises
`/agent/manifest.json`, `/agent/openapi.json` and `/agents`. The same entry points
appear in `/llms.txt`. Discovery is an application convention, not a claimed
industry-wide well-known protocol. The manifest contains every operation's
location, required scope, mutation flag and input schema.

The readable editor walkthrough is [`/tutorial.html`](/tutorial.html), with
Juniper Kitchen, learned G1 motions, recording and advisory Jev examples. The
machine-readable [`/agent/workflows.json`](/agent/workflows.json) links these
workflows to registered operations. Read [`/agent/MOTIONS.md`](/agent/MOTIONS.md)
for the prepared ONNX contract. Use this application's origin for all relative
paths: production is `https://web.luckyrobots.com`; feature branches use native
Cloudflare Preview URLs, without separate feature domains.

## Connect once

Sign in with your approved email/password account, open **Settings → Agent connections**,
and create a named key. Choose full access or narrower scopes, an expiration, and
optionally owned projects. Copy the secret once. The server stores its hash; the
list shows only its prefix. Revoke it in the same panel. Keys inherit your current
account role, ownership and approval status; full access does not confer admin.

```sh
export LUCKY_URL=https://web.luckyrobots.com
curl -fsS "$LUCKY_URL/agent/lucky.mjs" -o lucky.mjs
read -rs -p 'Lucky API key: ' LUCKY_API_KEY; echo
export LUCKY_API_KEY
node lucky.mjs discover
node lucky.mjs execute account.get '{}'
```

The same operation registry is available directly over HTTP:

```sh
curl -fsS "$LUCKY_URL/api/v1/execute" \
  -H "Authorization: Bearer $LUCKY_API_KEY" \
  -H 'Content-Type: application/json' \
  --data '{"operation":"catalog.robots","args":{}}'
```

Keep the key in your local secret environment. Never put it in a URL, source file,
prompt, shared log or committed client configuration. Requests use
`Authorization: Bearer <key>`. Mutations from browser cookies require a same-origin
request. An API key cannot create another key.

Codex supports remote HTTP with a bearer environment variable:

```toml
[mcp_servers.lucky_engine]
url = "https://web.luckyrobots.com/mcp"
bearer_token_env_var = "LUCKY_API_KEY"
```

Claude Code supports a remote HTTP server in `.mcp.json`:

```json
{
  "mcpServers": {
    "lucky_engine": {
      "type": "http",
      "url": "https://web.luckyrobots.com/mcp",
      "headers": { "Authorization": "Bearer ${LUCKY_API_KEY}" }
    }
  }
}
```

Export the variable before starting the client. See the official
[Codex](https://developers.openai.com/codex/mcp) and
[Claude Code](https://code.claude.com/docs/en/mcp) references. This implementation
uses the official MCP SDK's Streamable HTTP transport. Its personal-key header
mode is not OAuth and does not support clients that require an OAuth login flow.
MCP tool names replace dots with underscores, such as `robot_add`. Tools use the
same schemas and handlers as HTTP. Read the capabilities and bootstrap resources,
then use the `panda-sweep`, `juniper-fruit` or `g1-learned-motion` prompt.

## Where execution happens

Account, library, project-package and artifact operations run on Cloudflare.
MuJoCo physics, behaviors, Three.js rendering and video encoding run in the real
browser editor. A session needs a connected browser; Cloudflare is not a physics
or GPU service. A terminal-only agent can start its own real browser:

```sh
npm install playwright
npx playwright install chromium
node lucky.mjs execute project.create '{"projectId":"<UUID>","writeId":"<UUID>","name":"My workcell"}'
node lucky.mjs execute runtime.create '{"projectId":"<owned project UUID>","name":"Local agent"}'
node lucky.mjs runner --session <session UUID>
```

Generate actual UUIDs, for example with `crypto.randomUUID()`. Keep the runner
process alive. `--headed` shows the real editor. The runner grants this session
exclusive control, so its GUI does not race with remote edits. Another editor can
still edit the cloud project; `project.save` detects that conflict.

For an existing project, use `projects.list` and `project.get`, then `runtime.create`.
Community examples must first be copied with `project.remix`, which preserves
provenance. Project-restricted keys cannot create unrelated projects or remixes.
A runner needs project read, runtime read/write and the scopes needed by its jobs;
an independently scoped controller can have narrower permissions.

## Run and prove a Panda sweep

```sh
node lucky.mjs smoke --out panda-proof
```

This executable example discovers the API, creates a project, starts a browser,
adds Panda, installs a small sandboxed behavior, resets with seed 7, steps the
actual physics, compares measured joint positions, reads contacts, captures PNG,
records a one-second LeRobot v3 episode with H.264 MP4, downloads both, and saves
the authored project. It writes `proof.json` with measured values. It does not
equate movement or successful recording with completion of a physical task.

The essential behavior is:

```js
let home;
function start({ robot }) {
  home = robot.controls();
}
function update({ robot, time }) {
  const q = [...home];
  q[0] = home[0] + 0.12 * Math.sin(time);
  robot.setControls(q);
}
```

For individual operations in a second terminal:

```sh
node lucky.mjs execute runtime.inspect '{}' --session <id>
node lucky.mjs execute simulation.command '{"action":"pause"}' --session <id>
node lucky.mjs execute simulation.command '{"action":"step","args":{"count":500}}' --session <id>
node lucky.mjs execute capture.image '{"width":512,"height":512}' --session <id>
node lucky.mjs execute recording.run '{"seconds":1,"size":256,"seed":7}' --session <id>
node lucky.mjs download <artifact-id> episode.zip
node lucky.mjs execute project.save '{}' --session <id>
```

The CLI fetches the current session generation/revision and waits for a terminal
job result. It never treats an HTTP 202 as completed execution. For long work use
HTTP/MCP to enqueue, poll `job_get` and cancel with `job_cancel`.

## Run the existing kitchen behavior

```sh
node lucky.mjs kitchen --out kitchen-proof
```

This example finds **Juniper Kitchen**, creates an attributed remix, inspects its
Panda, fruit, bowl and behaviors, and executes its existing fruit-pick behavior.
It records the measured task result and reason, contacts, before/after states and
a final camera image. A separate short recording resets the scene and captures
the beginning of the same behavior with synchronized video and dataset. That
short recording is not presented as proof that the entire pick task completed.
Read the two outcomes separately in `proof.json`.

## Run the included learned G1 motion

The shipped `/motions/g1-aiming.lucky.zip` includes the compatible robot and a
prepared mjlab fused ONNX policy. Start an owned runtime as above. Download this
public asset from the same application origin, then upload and import it into
that runtime; the artifact upload result supplies the actual artifact ID.

```sh
curl -fsS "$LUCKY_URL/motions/g1-aiming.lucky.zip" -o g1-aiming.lucky.zip
node lucky.mjs upload g1-aiming.lucky.zip --session <session-id>
node lucky.mjs execute asset.import '{"artifactId":"<uploaded-artifact-id>","kind":"project"}' --session <session-id>
node lucky.mjs execute runtime.inspect '{}' --session <session-id>
node lucky.mjs execute simulation.command '{"action":"reset","args":{"seed":0}}' --session <session-id>
node lucky.mjs execute simulation.command '{"action":"step","args":{"count":400}}' --session <session-id>
node lucky.mjs execute runtime.inspect '{}' --session <session-id>
node lucky.mjs execute recording.run '{"seconds":3,"size":256,"seed":0}' --session <session-id>
node lucky.mjs execute project.save '{}' --session <session-id>
```

Replace every placeholder with the returned ID. The CLI obtains each fresh
generation/revision and polls its job. Importing a project replaces the runtime
scene; preserve any existing draft first. `runtime.inspect` returns authored
fields under `project` and measured snapshot fields under `simulation`. Inspect
`simulation.motions[robotId]` for `state`, `modelHash`, `frame`, `tick`,
`inferenceTick`, `observations` and `actions`.

The example uses 0.005-second physics ticks and 50 Hz inference: four physics
steps per action. It ends after 400 physical steps and 100 inferences. A complete
recording includes 61 frames, from index 0 through 60 at 30 fps. Request a
three-second budget so the final boundary is included; a two-second frame
budget contains only 60 samples. Reference completion stops capture at the
aligned final frame. The last physical sample is at 2 seconds, while 61 encoded
frames span 61/30 seconds. `finished-reference` is **not** task success.

Download the returned `dataset.id` and `video.id` separately using
`node lucky.mjs download <artifact-id> <filename>`. Verify the actual MP4 and
archive; the server accepting a command is not evidence that it ran.

### Import or change a prepared policy

1. Upload the supported `.onnx` or policy ZIP to the owned runtime's artifact
   store, then call `asset.import` with `kind: "motion"` and its filename.
   A policy ZIP must contain exactly one supported fused model. A complete
   `.lucky.zip` is instead imported with `kind: "project"`.
2. Call `motion.list` (`projects:read`) for device-local imported asset IDs,
   names and validated contracts.
3. Call `motion.attach` (`projects:write`) with
   `{ "robotId": "<robot-id>", "assetId": "<sha256>", "enabled": true }`.
   Attachment validates compatibility, selects the declared scene timestep and
   reloads physics. All enabled policies in a scene must agree on the timestep.
4. Disable with the same IDs and `enabled: false`, or detach with
   `{ "robotId": "<robot-id>", "assetId": null }`. Disable or detach before
   joint sliders, scripts, trajectories or another controller drive that robot.
5. Save/export the project to preserve its model bytes. A fresh runner has a
   fresh browser profile; `motion.list` is not an account-wide cloud catalog.

The current contract supports a compatible floating-base G1 with 29 controlled
joints, float32 `[1,101]` observations, embedded normalization/reference
outputs, exact action scales and PD gains, and declared frame-zero pose and
velocities. Legacy exports missing physics/initial-state metadata need
preparation. Arbitrary ONNX adapters, generic velocity-command walking,
automatic blending/recovery and in-browser training are not implemented.
See `/agent/MOTIONS.md` and `/agent/MJLAB-POLICY-BASELINE.md` for preparation and
bounded numerical evidence. Imported inference needs no paid model request.

The recording evidence preserves `physics_hz`, every `raw_ctrl_ticks` vector,
per-inference `motion_trace` (including input/output/model hash and
`inferenceTick`), and frame-zero `initial_state` (`qpos`, `qvel`, `act`).
Recorded-control replay restores that state and consumes retained controls
without rerunning ONNX inference. Rejected models or failed rollouts must not
be relabeled as successful tasks.

## Author and inspect the whole scene

- `/agent/project.schema.json` is generated from the actual `Project` type.
  `runtime.inspect` returns the validated document. `scene.replace` validates a
  complete document. `scene.patch` atomically applies JSON Pointer add/replace/
  remove operations, then runs the editor's project validator. Inspect the
  normalized result. Arrays use numeric indices and `-` to append.
- The project schema describes objects, world transforms, parenting, components,
  colliders, mass/friction, materials, meshes, lights, cameras, mounted sensors,
  robot instances, input bindings, clips, prefabs, task rewards, seeds and scenes.
  Patch the active scene's top-level fields; use `scene.select` to switch scenes.
  Updating a parent transform through raw document fields does not automatically
  translate child world transforms. Update the complete desired world transforms together; the `parent` engine method reads hierarchy.
- `scene.add`, `scene.select`, `robot.add` and `behavior.put` are convenience
  operations. Behavior compilation/runtime errors appear in inspect diagnostics;
  saving source is not a claim it ran successfully. `catalog.robots` lists valid
  asset IDs and import metadata.
- Use `upload <file> --session <id>` then `asset.import` for robot MJCF ZIPs, GLB
  objects, prepared motion policies or portable projects. Multi-XML robot packages require an `entry`.
  Source artifacts must belong to the same account and an allowed project.
  `/api/v1/projects/<id>/package` downloads an existing portable cloud package;
  PUT `/api/v1/projects/<id>` with ZIP, `If-Match` revision and `X-Write-Id` UUID
  creates/updates one through the same importer, quotas and ownership checks.
- `/agent/SCRIPTING.md` and `/agent/scripting.json` describe behavior APIs.
  `/agent/engine-methods.json` gives exact raw bridge argument tuples for direct
  `engine.call` and read-only `engine.inspect`. Those tuples can differ from the
  convenient `ctx` wrappers' implicit robot/entity arguments. Calls are allowlisted;
  arbitrary host JavaScript evaluation is unavailable. Authored behaviors run in
  the editor's existing QuickJS sandbox and retain its execution budgets.
- `/agent/snapshot.schema.json` and `/agent/scene.schema.json` describe measured
  simulation state and compiled scene/robot metadata. Inspect time, tick, qpos,
  controls, task/episode status, logs, camera poses and sensor traces. Use
  `engine.inspect` for contacts, positions, sensors and other measured reads.
- `simulation.command` handles play/pause/step/reset, unsigned seeds, actuator and
  input events, drag forces and debugger breakpoints/step/continue. Engine methods
  cover IK, trajectories, tasks, grasping, components, forces, spawning, sensors,
  animation and randomization. Read the method schemas for model-specific inputs.

Units are meters, seconds and radians, Z up. Camera FOV is degrees.
`Project.physicsTimestep` is 0.002 seconds by default and also supports 0.005.
The compiled model timestep is authoritative. Step counts are physics ticks,
not policy actions or video frames. Robot controls use model actuator units; discover
the compiled metadata rather than assuming every actuator is a joint angle.
Contacts and settled task states provide stronger evidence than target commands.

## Rendering, datasets and paid providers

`view.configure` controls viewport home/focus/interior, grid, collisions and
photographic quality. Camera fields in the authored document control capture.
`capture.image` pauses and captures an actual rendered camera PNG, including an
optional mounted camera ID. `recording.run` resets and records the real renderer,
fixed-step sampler and existing encoder; `recording.batch` repeats per seed.
Recordings are 30 fps. Returned first/last traces and proof describe actual frames.
See `/agent/RECORDING.md` for LeRobot v3 fields and timestamp conventions.

`artifacts.list` lists private uploaded assets, images, portable exports, MP4s and
dataset ZIPs; download or delete them through `/api/v1/artifacts/<id>`. Use the
downloaded MP4 for playback and ZIP for analysis. Device-local datasets created
in some other browser profile are not cloud artifacts. A fresh runner has a fresh
browser profile. Supported motion uploads use the explicit import/attachment
workflow above; this transport does not add adapters for unsupported networks.

Each artifact is limited to 24 MiB; total account artifacts and daily uploads are
limited to 512 MiB. Large or long recordings may exceed this limit: shorten takes,
reduce capture size, or delete old artifacts. A failed upload does not produce a
successful job. Up to 20 seeds can be recorded sequentially; cancellation discards
the active incomplete episode, but earlier completed artifacts remain listed.

`provider.request` exposes existing AI status/models/turn, Blender build and Jev
evaluation through the existing paid gateway, quotas and payload contracts.
Authenticated `/api/ai/...` and `/api/jev/...` aliases preserve streaming/binary
responses. Ordinary scene edits, physics and recordings never require a paid
assistant call. Provider availability depends on configured backend credentials;
test fixtures are not proof of a live paid-provider response.
Jev labels, failure hypotheses and confidence remain advisory; compare them
with recorded task outcomes. Automatic weakness mining, camera optimization
and runtime AI Decision components from the design plan remain planned. The
implemented next-experiment skill recommends a manual follow-up rather than
launching one. See `/tutorial.html#planned` for the boundary.

## Revisions, cancellation and recovery

Raw HTTP uses POST `/api/v1/execute` with `operation`, `args` and, for runtime work,
`sessionId`, current `generation`, current `revision`, UUID `idempotencyKey`, and
optional `timeoutSeconds` (5–3600). Read `/api/v1/runtimes/<id>` first. Only one job
is active per runtime. Repeat an identical envelope with the same idempotency key
to recover a lost response; a changed envelope with that key is rejected. Terminal
job records expire after seven days, so idempotency recovery is bounded to that
period. Do not blindly retry a physical mutation with a new key.

A browser holds a 30-second lease and renews every five seconds. Reconnecting
increments generation and fences old commands/acknowledgments. Mutation results,
including partial failures or cancellation, advance runtime revision. Cloud
package revision is separate and advances on `project.save`. Closing a browser
loses unsaved in-memory scene edits; save or export checkpoints before closing.

Poll the returned job URL. `completed` confirms acknowledged execution only;
inspect measured output to establish physical success. `failed`, `cancelled`,
`expired`, `conflict` and `unknown` are not successful outcomes. `unknown` means
execution may have partially happened before lease loss or timeout. Reconnect and
inspect before deciding what to repeat. A reset intentionally resets physical
state. Cancellation is cooperative at operation boundaries and may leave partial
changes. Revoking the originating key requests cancellation and prevents a later
successful acknowledgment.

HTTP 400 indicates malformed input; 401 an expired/revoked/missing key; 403 a
scope, ownership or current-policy restriction; 409 an offline/busy/stale runtime
or project revision conflict; 413/429 a size/rate/storage limit; 503 unavailable
service. Error JSON contains the message. On a cloud-save conflict, export the
current draft and compare the latest package instead of overwriting another edit.
Neither client silently retries mutations nor replaces a conflicting revision.
