Skip to content

armgit / chums

Public Imported from GitHub
0

Talk to Claude Code and Codex agents from an Apple Watch and an iPhone. Each agent is a character on the watch.

Chums

Lucas Couto32dc1f539cd4
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..1941e04
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,61 @@
+name: Bug report
+description: Something in the watch app, the hub or the channel doesn't work.
+labels: [bug]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Remove tokens, absolute paths under your home folder and device IDs from anything you paste.
+ Security problems go through private reporting instead (see SECURITY.md).
+ - type: textarea
+ id: what
+ attributes:
+ label: What happened
+ description: What you did, what you expected, and what happened instead.
+ validations:
+ required: true
+ - type: textarea
+ id: steps
+ attributes:
+ label: Steps to reproduce
+ placeholder: |
+ 1. bin/chums-hub
+ 2. …
+ validations:
+ required: true
+ - type: dropdown
+ id: part
+ attributes:
+ label: Where
+ options:
+ - Watch app (device)
+ - Watch app (Simulator)
+ - Hub
+ - Channel or hooks (Claude Code)
+ - Codex agents
+ - Tailscale Funnel
+ - Background agents
+ - Setup scripts (bin/)
+ - iPhone app or widgets
+ - Design tools
+ validations:
+ required: true
+ - type: input
+ id: versions
+ attributes:
+ label: Versions
+ description: macOS, watchOS, iOS, Xcode, Node.js, Claude Code (claude --version) or Codex (codex --version), and the Chums commit.
+ validations:
+ required: true
+ - type: textarea
+ id: doctor
+ attributes:
+ label: bin/chums-doctor
+ description: The output of bin/chums-doctor (it never prints tokens). docs/troubleshooting.md covers the known problems.
+ render: text
+ - type: textarea
+ id: logs
+ attributes:
+ label: Logs
+ description: The hub's output (terminal or ~/.chums/hub.log) around the problem, and for the watch or the iPhone, ~/.chums/watch-events.log.
+ render: text
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..14ccf24
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,5 @@
+blank_issues_enabled: false
+contact_links:
+ - name: Security problem
+ url: https://docs.github.com/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability
+ about: Report it privately (Security › Report a vulnerability on this repository), not as an issue.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..8038fad
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,16 @@
+name: Feature or character idea
+description: Something Chums should do, or a new character.
+labels: [enhancement]
+body:
+ - type: textarea
+ id: what
+ attributes:
+ label: What you want to do
+ description: What you want to do from the watch or the iPhone, or what the character should be, and why.
+ validations:
+ required: true
+ - type: textarea
+ id: how
+ attributes:
+ label: How it could work
+ description: Optional. For a character, say how it shows each state (design/STATES.md lists them).
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..8bfcdda
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,18 @@
+## What this changes
+
+<!-- One change per pull request. What it does, in a sentence or two. -->
+
+## How I checked it
+
+- [ ] `node tools/test-channel.mjs` passes
+- [ ] `node tools/test-hub.mjs` passes (or `CHUMS_TEST_NO_MODEL=1 node tools/test-hub.mjs`)
+- [ ] `node tools/test-runtimes.mjs` passes
+- [ ] Watch changes: built with `bin/chums-sim`; screenshots or a recording below
+- [ ] Character changes: every state checked (`design/STATES.md`)
+- [ ] No tokens, personal paths, device IDs or team IDs in the diff
+
+## Screenshots or recording
+
+<!-- For anything visible on the watch. -->
+
+By submitting this pull request I agree that my contribution is licensed under the Apache License 2.0.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..b9dce9c
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,82 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+# a newer push to the same branch or pull request cancels the run before it
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+# "shell: bash" runs steps with -eo pipefail (the default shell has no pipefail): an xcodebuild that fails before
+# "| tail" fails its step
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ node-tests:
+ name: Hub and channel tests
+ # macOS: the hub renders pages with WebKit (tools/page-shot.swift) and images with sips
+ runs-on: macos-15
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v5
+ - uses: actions/setup-node@v5
+ with:
+ node-version: 22
+ cache: npm
+ - run: npm ci
+ - name: Channel test (hub + channel, no Claude Code)
+ run: node tools/test-channel.mjs
+ - name: Hub test (no model calls)
+ run: node tools/test-hub.mjs
+ env:
+ CHUMS_TEST_NO_MODEL: '1'
+ - name: Artifacts test (every kind of file made into a picture, and the routes the iPhone opens them by)
+ run: node tools/test-artifacts.mjs
+ - name: Runtimes test (Codex, Copilot and ACP drivers against stand-ins; no model calls)
+ run: node tools/test-runtimes.mjs
+
+ app-build:
+ name: Watch and iPhone apps build (Simulator, unsigned)
+ # the app targets watchOS 26, so it needs Xcode 26
+ runs-on: macos-26
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v5
+ - name: Check the Xcode version
+ run: |
+ xcodebuild -version
+ [ "$(xcodebuild -version | sed -n 's/^Xcode \([0-9]*\).*/\1/p')" -ge 26 ] ||
+ { echo "::error::The apps need Xcode 26 or later; select one with sudo xcode-select -s /Applications/Xcode_26.x.app"; exit 1; }
+ - name: Install XcodeGen
+ run: brew install xcodegen
+ env:
+ HOMEBREW_NO_AUTO_UPDATE: '1'
+ HOMEBREW_NO_INSTALL_CLEANUP: '1'
+ - name: Stand-in hub config (tools/gen-config.sh reads it)
+ run: |
+ mkdir -p ~/.chums
+ echo '{"port": 7717, "publicPort": 7718, "token": "ci", "watchToken": "ci"}' > ~/.chums/config.json
+ - name: Generate the project
+ run: |
+ tools/gen-config.sh
+ cd app && CHUMS_BUNDLE=dev.chums.ci xcodegen generate
+ - name: Build ChumsWatch for the Simulator
+ # pipefail (defaults above): a failed build fails the step
+ run: |
+ cd app
+ xcodebuild -project Chums.xcodeproj -target ChumsWatch -sdk watchsimulator -configuration Debug \
+ CODE_SIGNING_ALLOWED=NO SYMROOT="$PWD/build/sym" build | tail -40
+ - name: Build the iPhone app, its widgets and the watch app inside it, for the Simulator
+ # the scheme, not -target with -sdk: -sdk would build the embedded watch widget against the iOS SDK
+ run: |
+ cd app
+ xcodebuild -project Chums.xcodeproj -scheme Chums -destination 'generic/platform=iOS Simulator' \
+ -configuration Debug -derivedDataPath "$PWD/build/dd" CODE_SIGNING_ALLOWED=NO build | tail -40
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..9034466
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,38 @@
+# dependencies
+node_modules/
+
+# Xcode: the project and the Info.plists are generated from app/project.yml (xcodegen generate)
+app/build/
+app/Chums.xcodeproj/
+app/ChumsPhone/Info.plist
+app/ChumsWatch/Info.plist
+app/ChumsWidget/Info.plist
+app/ChumsPhoneWidgets/Info.plist
+xcuserdata/
+DerivedData/
+*.xcuserstate
+
+# generated per machine: they hold your hub token or absolute paths
+app/ChumsWatch/HubConfig.swift
+channel/mcp.json
+channel/hooks.json
+.env
+.env.*
+
+# macOS, Python, Blender
+.DS_Store
+__pycache__/
+*.pyc
+*.blend1
+design/characters/**/*.npz
+
+# Blender renders: the raw frames and logs stay local
+design/noodle/renders/*.png
+design/noodle/renders/*.log
+design/noodle/renders/anim/
+design/noodle/renders/preview/
+design/noodle/renders/preview.log
+
+# logs
+*.log
+.claude/
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..3f10735
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,118 @@
+# AGENTS.md
+
+Instructions for a coding agent (Claude Code, Codex or another) working in this repository: most often because its user
+asked it to "set up Chums", sometimes to change the code.
+
+Chums is an Apple Watch app, an iPhone app and a hub on the Mac for talking to coding agents by voice. The user builds
+the apps from source in Xcode, signs them with their own Apple ID, and puts the hub on the internet with Tailscale
+Funnel. Some steps need the user's hands, accounts and devices; you do the rest and check each step.
+
+- The steps, in order, with "How to know it worked" for each: [docs/setup.md](docs/setup.md). Follow it; this file only
+ says who does what.
+- Known problems and their fixes: [docs/troubleshooting.md](docs/troubleshooting.md).
+- The check for every step: `bin/chums-doctor`. It is read-only, never prints tokens, and exits 0 when nothing fails.
+ Run it first, after each step, and at the end. Until the last step, the sections for later steps fail; each step's
+ "How to know it worked" in setup.md names the section to read.
+
+## Rules
+
+- **Never print, paste, log or commit the tokens.** They are `token` and `watchToken` in `~/.chums/config.json`, and
+ the watch token is also in `app/ChumsWatch/HubConfig.swift`. Don't `cat` either file or show them in a diff. To see
+ which keys are set: `python3 -c 'import json,os; print(sorted(json.load(open(os.path.expanduser("~/.chums/config.json")))))'`.
+ If a token was shown anywhere, tell the user and follow "Rotating a token" in [SECURITY.md](SECURITY.md).
+- Don't commit the generated files: `app/ChumsWatch/HubConfig.swift`, `channel/mcp.json`, `channel/hooks.json` (all
+ git-ignored).
+- Don't paste the output of `claude auth status`: it contains the account's email. Report only whether it is signed in.
+- Ask before anything outside this checkout that is hard to undo, puts something on the internet or changes what runs
+ at login: `bin/chums-setup --launchd`, `bin/chums-agents install`, `bin/chums-tunnel` (it publishes the hub's watch
+ API with Tailscale Funnel), `launchctl bootout`, `tailscale … funnel reset`, deleting `~/.chums`,
+ removing an app from the watch, changing `team` or `bundleId` after the app is installed, and any `sudo`.
+- `bin/chums-hub` runs until stopped. Prefer `bin/chums-setup --launchd` (ask first): a hub you start in your own
+ shell stops when your shell does, and the permissions on the Mac and Codex's screenshots need the hub to run as
+ Chums. Until they agree, run `bin/chums-hub` in the background.
+- On a Mac without Xcode or its Command Line Tools, the first `python3` (which every `bin/` script but the doctor
+ uses) opens an install dialog. Have the user install Xcode (step 1) before you run `bin/` scripts.
+- Don't run `bin/chums-claude` inside your own session: it starts an interactive Claude Code session for the user's
+ terminal.
+- If you are yourself running as a Chums agent, restarting the hub or `bin/chums-agents` cuts off the watch's
+ conversation: ask first.
+
+## Who does what
+
+| Step ([setup.md](docs/setup.md)) | You can do it | Only the user can do it |
+| --- | --- | --- |
+| 1. What you need | `brew install node xcodegen whisperkit-cli ffmpeg tailscale uv` (uv is for the agents' voices). Claude Code: `curl -fsSL https://claude.ai/install.sh \| bash`. Codex: `npm install -g @openai/codex` | Install Xcode from the App Store (their Apple ID). Install Homebrew if it's missing (it asks for their password) |
+| 2. Pick your agent | Ask which agent they use: Claude Code, Codex or both | Sign in: `claude` then `/login`, and/or `codex login` (both open a browser). Check with `codex login status`, or `claude auth status` without showing its output |
+| 3. Get the code and check the Mac | `bin/chums-setup`: npm packages, the Whisper model (about 150 MB), and the agents' voices when uv is installed (about 1.5 GB). Run it until it prints `Ready`. If only the Xcode lines are `MISSING`, go on to step 4 and come back after step 6 | |
+| 4. Start the hub | `bin/chums-setup --launchd` once they agree, else `bin/chums-hub` in the background. Ask what the agents should call them and set `ownerName` (below) before step 10 | |
+| 5. Tailscale Funnel | Run `bin/chums-tunnel` in the background and read its output. When it prints a `login.tailscale.com` link and waits, stop and give the user the link | Create a Tailscale account, open the sign-in link, and approve the Funnel link if a second one appears |
+| 6. Apple ID in Xcode | Check with `bin/chums-doctor` (the `signing team` line) | Xcode › Settings › Apple Accounts › + › Apple ID |
+| 7. Connect the devices | Watch progress with `bin/chums-doctor` (section 7) | Plug the iPhone in by USB, tap Trust on the iPhone and the watch, keep the watch unlocked, open Window › Devices and Simulators and wait for "Preparing" to finish |
+| 8. Developer Mode | Check with `bin/chums-doctor` (section 7) | Turn it on in Settings › Privacy & Security on the iPhone and on the watch; each restarts and asks to confirm |
+| 9. Build and install | `bin/chums-install`, once the doctor shows the watch with Developer Mode on. It installs the watch app, then the iPhone app when Xcode knows the iPhone and its Developer Mode is on. Tell the user to keep the watch and the iPhone unlocked while it runs | Register the devices from Xcode if the build stops at "Your team has no devices" ([troubleshooting](docs/troubleshooting.md#your-team-has-no-devices)) |
+| 10. Start the agents | `bin/chums-agents install` once they agree (Chums.app is signed for the same team as the apps, so it keeps its permissions across rebuilds): eight Claude Code agents, one per character, about 200 MB of memory each. Skip it if they use only Codex. Change the agents' folders only if they ask (below) | Switch an agent to Codex: on the watch (swipe its row left, Runs on) or on its card in the iPhone app (Runs on). Answer Claude Code's first-start screens if they run `bin/chums-claude` themselves |
+| 11. Talk to it | Read the hub log (the output of `bin/chums-hub`, or `~/.chums/hub.log` under launchd) to confirm the clip arrived (`utterance … -> order`) | Allow the microphone on the watch, hold the screen and speak |
+| Keyring mode (optional) | | Allow Health › Workouts on the watch; change the watch settings listed in setup.md |
+| Permissions on the Mac (once) | Check with `bin/chums-permissions check` (asks nothing); the hub and the agents must run through Chums.app first (`bin/chums-setup --launchd`, `bin/chums-agents install`, once they agree) | Open Chums from `~/Applications` (`bin/chums-permissions` opens it) and click Allow All: Allow or OK on each macOS dialog, and switch Chums on in the System Settings panes macOS's alerts open (Accessibility, Screen Recording) ([setup](docs/setup.md#permissions-on-the-mac)) |
+
+When you stop for the user, say exactly what to do, on which device, and what they will see when it worked. Then wait,
+and check with `bin/chums-doctor` before you go on.
+
+## What to say at each hand-over
+
+Use these words, with the parts in brackets filled in. Then wait for the user, and run the check.
+
+| When | Say | Check |
+| --- | --- | --- |
+| Xcode is missing | "Install Xcode from the Mac App Store, open it once, and let it install its components. Tell me when that's done." | doctor, "6.": Xcode 26 `PASS` |
+| Claude Code isn't signed in | "In a terminal, run `claude`, type `/login`, and sign in in the browser. Tell me when that's done." | doctor, "2.": Claude Code signed in |
+| Codex isn't signed in | "In a terminal, run `codex login` and sign in in the browser. Tell me when that's done." | doctor, "2.": Codex signed in |
+| `bin/chums-tunnel` printed a `login.tailscale.com/a/…` link | "Open [link], sign in to Tailscale (a free account works), and connect the machine. Tell me when the page says it's connected." | the script goes on; doctor, "5.": signed in |
+| It printed a `login.tailscale.com/f/funnel…` link | "Open [link] and approve Funnel for your tailnet. Tell me when that's done." | doctor, "5.": the tailnet allows HTTPS certificates and Funnel |
+| No Apple ID in Xcode | "In Xcode, open Settings › Apple Accounts, click +, choose Apple ID, and sign in. A free Apple ID works." | doctor, "6.": a `signing team` line |
+| Xcode doesn't know the watch | "Connect your iPhone to this Mac with a USB cable and unlock it; tap Trust if it asks. Unlock your watch, keep it near the iPhone, and tap Trust on it if it asks. In Xcode, open Window › Devices and Simulators and wait until the watch is listed and preparing has finished; the first time it can take 10 minutes or more. Keep the watch unlocked until then." | doctor, "7.": `Apple Watch [name]` |
+| Developer Mode is off | "On the iPhone: Settings › Privacy & Security › Developer Mode, turn it on, and restart when it asks; after the restart, unlock it and tap Turn On. Then on the watch: Settings › Privacy & Security › Developer Mode, turn it on, and restart it from the prompt it shows; after the restart, unlock it and confirm Turn On." | doctor, "7.": `Developer Mode on` for the watch, `Developer Mode enabled` for the iPhone |
+| The build stops at "Your team has no devices" | "Open app/Chums.xcodeproj in Xcode. Choose the Chums scheme and your iPhone, and press Run (⌘R). Then choose the ChumsWatch scheme and your watch, and press Run. Tell me when both have run." | `bin/chums-install` again |
+| Before `bin/chums-install` | "Keep your watch and your iPhone unlocked and awake until I say the install is done. Tap the watch's screen now and then." | it prints `Chums is running on the watch.` |
+| Permissions on the Mac | "At the Mac, in the Chums window I opened, click Allow All. Click Allow or OK on each macOS dialog, and switch Chums on in each System Settings pane it opens (Accessibility, Screen Recording). Tell me when every row says Allowed." | `bin/chums-permissions check` |
+| First talk | "On the watch, allow the microphone, notifications and Workouts when Chums asks. Then hold the screen, say 'What folder are you in?', and let go." | the hub log: `utterance … -> order` |
+
+To set one key in `~/.chums/config.json` without printing the file (here `ownerName`; it keeps the file's mode 0600):
+
+```bash
+python3 -c 'import json,os,sys; p=os.path.expanduser("~/.chums/config.json"); c=json.load(open(p)); c[sys.argv[1]]=sys.argv[2]; json.dump(c,open(p,"w"),indent=2); os.chmod(p,0o600)' ownerName Sam
+```
+
+## Writing ~/.chums/agents.json
+
+Every character is its own agent. The hub writes one per character on its first start (the id is the character's:
+`noodle`, `stretch`, `peeps`, `squint`, `ray`, `tangle`, `crunch`, `nana`), all on Claude Code. The user switches an
+agent to Codex, and picks its model, on the watch (its soul screen, Runs on) or on its card in the iPhone app (Runs
+on, Model); don't do that by editing the file. To change their folders:
+
+1. Ask the user which folders each agent may work in (`cwd`, and `addDirs` for more).
+2. Copy the file to `~/.chums/agents.json.bak` first.
+3. Keep one entry per character, its `id` the character's, and an absolute `cwd`.
+ [tools/agents.example.json](tools/agents.example.json) shows the shape.
+4. `"model"` is the model the user picks on the iPhone; set it in the file only if they ask (for example when
+ Codex's default model isn't on their plan). Every field: [docs/other-agents.md](docs/other-agents.md#agentsjson).
+5. Keep the `sessionId` of existing agents: it is the agent's conversation.
+6. Run `bin/chums-doctor` (section 3 validates the file), then restart the hub and, for Claude Code agents,
+ `bin/chums-agents install`.
+
+## Working on the code
+
+- Tests, which run a private hub with its own temporary home and ports, never the user's `~/.chums` or hub:
+
+ ```bash
+ node tools/test-channel.mjs
+ CHUMS_TEST_NO_MODEL=1 node tools/test-hub.mjs # without CHUMS_TEST_NO_MODEL it also calls a model (claude -p)
+ node tools/test-artifacts.mjs # every kind of file an agent can show
+ node tools/test-runtimes.mjs
+ ```
+
+- The watch app builds for the Simulator with `bin/chums-sim`, with no signing. Shut the simulator down afterwards
+ (`xcrun simctl shutdown "Chums Watch"`): a simulator left running without a window plays sounds on the Mac.
+- Where things are, and how to propose a change: [CONTRIBUTING.md](CONTRIBUTING.md). How it works:
+ [docs/architecture.md](docs/architecture.md).
+- Copy in docs, the app and the agents' prompts is plain and literal: every line states a fact.
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..94108e6
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,5 @@
+# CLAUDE.md
+
+The instructions for coding agents in this repository are in [AGENTS.md](AGENTS.md).
+
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..a3aa30f
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,20 @@
+# Code of conduct
+
+This project follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).
+It applies in the repository, its issues, pull requests and discussions, and anywhere you represent the project.
+
+In short:
+
+- Be respectful. Disagree with ideas, not with people.
+- No harassment, insults, sexual language or imagery, or personal attacks.
+- Don't publish other people's private information.
+- Maintainers may remove comments, commits, code and issues that break these rules, and may ban people who break
+ them.
+
+## Reporting
+
+Report unacceptable behaviour in an issue, a pull request or a comment with GitHub's Report content (its … menu). To
+reach the maintainers privately, open a private report on this repository (Security › Report a vulnerability) and say
+in its title that it is about conduct. Reports are kept confidential. The Contributor Covenant's
+[enforcement guidelines](https://www.contributor-covenant.org/version/2/1/code_of_conduct/#enforcement-guidelines)
+decide the response.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..8340492
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,85 @@
+# Contributing
+
+Thanks for helping. Bug reports, fixes and new characters are welcome.
+
+## License of contributions
+
+Chums is licensed under the [Apache License 2.0](LICENSE). By submitting a contribution you agree that it is licensed
+under Apache-2.0, as section 5 of the license says, and that you have the right to submit it.
+
+## Before you start
+
+- For a bug, open an issue with the steps to reproduce, your macOS, watchOS and Xcode versions, the output of
+ `bin/chums-doctor`, and the hub log (`~/.chums/hub.log` or the terminal running `bin/chums-hub`). Remove tokens and
+ personal paths from logs first. Setup problems: [docs/troubleshooting.md](docs/troubleshooting.md) first.
+- For a feature or a new character, open an issue first so we can agree on the shape before you build it.
+- Security problems: see [SECURITY.md](SECURITY.md). Don't file them as public issues.
+
+## Set up
+
+```bash
+git clone https://github.com/lcoutodemos/chums.git && cd chums
+bin/chums-setup # checks requirements, installs npm packages and the Whisper model
+bin/chums-hub # first start writes ~/.chums/config.json
+bin/chums-sim # the watch app in the watchOS Simulator, no signing
+bin/chums-doctor # read-only check of the whole chain
+```
+
+[docs/setup.md](docs/setup.md) covers a real watch, Tailscale Funnel and the background agents.
+
+## Where things are
+
+| Folder | What it is |
+| --- | --- |
+| `app/` | The apps (SwiftUI). `app/project.yml` is the XcodeGen spec; the `.xcodeproj` is generated |
+| `app/ChumsWatch/` | The watchOS app, and the engine the iPhone app shares (watch-only parts are `#if os(watchOS)`) |
+| `app/ChumsWatch/Rig/` | The characters: the shared rig and one `<Name>Stage.swift` per self-drawn character |
+| `app/ChumsPhone/` | The iPhone app |
+| `app/ChumsPhoneWidgets/`, `app/ChumsPhoneShared/` | The iPhone's widgets and the Talk control, and what they share with the app (hub calls, App Intents, widget views) |
+| `app/ChumsWidget/` | The watch's widget (complications, Smart Stack) |
+| `app/Shared/` | The characters' faces, used by every target |
+| `hub/` | The hub on the Mac: `hub.mjs` (sessions, routing, approvals, speech, the watch API, artifacts), `runtimes.mjs` (the agents it runs itself: Codex; experimental: Copilot, ACP), `render.mjs` (Markdown, text and tables as HTML pages), `standing.mjs` (what every agent is told) |
+| `channel/` | The Claude Code channel (MCP) and the hook script |
+| `bin/` | The commands you run |
+| `tools/` | Tests, build helpers, the doctor's checks (`doctor.py`), the background agents' launcher, the Mac app the hub and the agents run through (`mac-app/`), the agents' voices (`kokoro-server.py`) |
+| `design/` | The state map (`STATES.md`), Crunch and Nana in JavaScript (`pix/`), Stretch's Blender sources (`noodle/`), Noodle's shape tools (`characters/coil3d/`), the watch mockup (`mockup/`) |
+| `docs/` | Setup, troubleshooting, architecture, characters, other agents; `docs/media/` holds the README's pictures and the characters' loops (`tools/readme-loops.sh`) |
+
+## Tests
+
+```bash
+npm test # all four below, with no model calls
+node tools/test-channel.mjs # hub + channel, no Claude Code needed
+node tools/test-hub.mjs # hub routing, approvals, artifacts, agents, souls
+CHUMS_TEST_NO_MODEL=1 node tools/test-hub.mjs # the same without the soul-editor checks (they call a model)
+node tools/test-artifacts.mjs # every kind of file shown as a picture, and the iPhone's routes to them
+node tools/test-runtimes.mjs # the Codex, Copilot and ACP drivers against stand-ins
+```
+
+Every command in `bin/` prints what it does and its options with `--help`.
+
+These start a private hub with its own temporary home folder and ports, so they never touch your real hub or
+sessions. CI runs them on macOS and builds the watch and iPhone apps for the Simulator (`.github/workflows/ci.yml`).
+
+The iPhone app has UI tests that drive it with real touches in the Simulator, against the hub on your Mac (they send
+no orders): `cd app && xcodebuild test -project Chums.xcodeproj -scheme Chums -destination 'platform=iOS Simulator,name=iPhone 17 Pro'`.
+`app/ChumsPhoneUITests/ChumsPhoneUITests.swift` says which settings they read.
+
+End-to-end checks with a real Claude Code session, against your running hub (they read `~/.chums/config.json`):
+`python3 tools/e2e-claude.py <dir>` and `python3 tools/e2e-watch.py <dir>`. With the real Codex, in a private hub:
+`node tools/e2e-runtimes.mjs codex` (about 14 turns on your Codex account).
+
+## Pull requests
+
+- Keep a pull request to one change. Say what it does and how you checked it.
+- Run the Node tests. For watch changes, build with `bin/chums-sim` and include a short screen recording or
+ screenshots of what changed (`xcrun simctl io booted recordVideo out.mp4`).
+- For a character change, check every state: `design/STATES.md` lists them, and the Simulator's demo
+ (`-demo YES`) plays them all.
+- Don't commit generated files: `app/Chums.xcodeproj`, the Info.plists, `app/ChumsWatch/HubConfig.swift`,
+ `channel/mcp.json`, `channel/hooks.json`. `.gitignore` covers them.
+- Don't commit personal data: tokens, absolute paths under your home folder, device IDs, Apple team IDs.
+
+## Writing
+
+Code comments, docs and UI text are plain and literal: say what a thing is or does. No metaphors, no marketing.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..c7358d6
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,4 @@
+Chums
+Copyright 2026 The Chums Authors
+
+This product is licensed under the Apache License, Version 2.0 (see LICENSE), including the character art.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..26de34b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,242 @@
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/readme/wordmark-light.svg">
+ <img src="docs/media/readme/wordmark-dark.svg" height="64" alt="chums">
+ </picture>
+</p>
+
+<h3 align="center">The AI you already use. Now on your keychain, your backpack or your wrist.</h3>
+
+<p align="center">
+ Chums puts the Claude Code and Codex already running on your Mac on an Apple Watch and an iPhone.<br>
+ Hold the screen, say what you want, let go. Each agent is a character that acts out what it's doing.
+</p>
+
+<p align="center">
+ <img src="docs/media/readme/watch-ray.webp" width="380" alt="Ray on an Apple Watch">
+</p>
+
+<p align="center">
+ <a href="https://chums.club"><b>chums.club</b></a> ·
+ <a href="docs/setup.md">Setup</a> ·
+ <a href="docs/troubleshooting.md">Troubleshooting</a> ·
+ <a href="docs/architecture.md">How it works</a> ·
+ <a href="docs/characters.md">Characters</a> ·
+ <a href="CONTRIBUTING.md">Contributing</a>
+</p>
+
+<table>
+ <tr>
+ <td width="33%" valign="top"><b>No new model</b><br>Your agents run on Claude Code or Codex, on your Mac.</td>
+ <td width="33%" valign="top"><b>No new subscription</b><br>Chums is free and open source. The AI subscription you already have does the work.</td>
+ <td width="33%" valign="top"><b>No Chums account</b><br>No Chums login. The watch and the iPhone talk to the hub on your own Mac.</td>
+ </tr>
+</table>
+
+Everyone is building a cute new assistant: another subscription, another app, another company holding your data.
+Chums is a team of agents on the AI you already pay for.
+
+Each agent runs on Claude Code or Codex, picked per agent from the watch or the iPhone:
+[docs/other-agents.md](docs/other-agents.md).
+
+**What you need:** an Apple Watch on watchOS 26 and the iPhone it is paired with (iOS 26), a Mac with Apple silicon
+and Xcode 26, an Apple ID (a free one works), a free Tailscale account, and Claude Code or Codex. You build the apps
+from source and run the hub on your Mac. The first setup takes 20–30 minutes, plus up to half an hour of waiting for
+Xcode to prepare the watch and for a new Funnel address to reach public DNS. [Requirements](#requirements) ·
+[Quickstart](#quickstart) · [Set it up with your agent](#set-it-up-with-your-agent)
+
+## Set it up with your agent
+
+Chums is source code, not an App Store download. Paste this into Claude Code or Codex on your Mac. It does the setup
+and stops when it needs your hands: signing in, plugging in your iPhone, turning on Developer Mode.
+
+```text
+Set up Chums for me: clone https://github.com/lcoutodemos/chums and follow its AGENTS.md.
+```
+
+## What you can do from the watch
+
+<img src="docs/media/readme/watch-noodle.webp" width="300" align="right" alt="Noodle on an Apple Watch: listening, thinking, working, asking to run git push, answering">
+
+- **Talk to an agent.** Hold the screen, say what you want, let go. The Mac transcribes it and sends it to the agent.
+- **See what it is doing.** The character acts out the agent's state: listening, thinking, working, waiting for you,
+ done, blocked. Each tool call appears on screen as it runs.
+- **Approve or deny actions.** When the agent asks for permission, hold the card to allow it or tap × to deny it.
+- **Hear short replies.** The agent answers in one short sentence, spoken on the watch in the character's own voice (with the voices installed),
+ and kept in a conversation you can scroll.
+- **Get pictures.** Ask for a screenshot of your screen, an app or a web page, or for something the agent made; it
+ arrives as a picture you can zoom.
+- **Switch between agents.** Each agent is its own session and character. Tap the faces at the top left to pick one;
+ what you say goes to the one on screen. Another agent's news arrives as a haptic tap.
+- **Change who an agent is.** Say what should be different about an agent (its name, what it looks after, how it
+ talks) and save the change. What it runs on, its model, its permissions and its voice are a tap away.
+- **Carry it on your keys.** Keyring mode keeps the app on screen with the watch off your wrist.
+
+<br clear="right">
+
+## The iPhone app
+
+The same agents and conversations, on a screen with room for them. Type or talk, send photos and files, approve, and
+change an agent: what it runs on, its model, its permissions, its voice and its soul.
+
+What an agent shows you opens live. Ask for a chart and it makes an HTML page that runs on the iPhone: drag across it,
+switch what it shows. A web page loads, a PDF scrolls page by page, a table scrolls, a video plays, and Word, Excel,
+Keynote and other documents open in Quick Look ([setup](docs/setup.md#the-iphone-app)).
+
+<p align="center">
+ <img src="docs/media/readme/phone-conversation.webp" width="260" alt="The iPhone app: a conversation with Noodle, Noodle at the bottom running the tests">
+ <img src="docs/media/readme/phone-artifact.webp" width="260" alt="The iPhone app: a checkout chart Noodle made, open and live, with tabs for conversion, orders and codes">
+ <img src="docs/media/readme/phone-card.webp" width="260" alt="The iPhone app: Noodle's card, with what it runs on, its model, permissions, voice and soul">
+</p>
+
+Widgets show the agents on the Home Screen and the Lock Screen and answer approvals; a control opens the app
+listening, from Control Center or the Action Button.
+
+<p align="center">
+ <img src="docs/media/readme/widget-agents.webp" width="420" alt="The Agents widget: Noodle, Squint, Ray, Tangle and Peeps">
+ <img src="docs/media/readme/widget-asking.webp" width="420" alt="The Agent widget: an agent asking to run a command, with Deny and Allow">
+</p>
+
+## The characters
+
+No big brand to obey, so each one tries a different way to build and animate a character: real-time 3D, Blender
+renders, vectors, one line, strokes on springs, plain eyes, pixels. Each is also its own agent, with its own
+conversation and voice. To make your own, start from Ray's Swift file: [docs/characters.md](docs/characters.md).
+
+<table>
+ <tr>
+ <td align="center" valign="top"><img src="docs/media/characters/noodle.webp" width="150" alt="Noodle"><br><b>Noodle</b><br>a 3D tube, computed live on the watch</td>
+ <td align="center" valign="top"><img src="docs/media/characters/stretch.webp" width="150" alt="Stretch"><br><b>Stretch</b><br>rendered in Blender, a clip for each state</td>
+ <td align="center" valign="top"><img src="docs/media/characters/peeps.webp" width="150" alt="Peeps"><br><b>Peeps</b><br>plain eyes that follow your finger</td>
+ <td align="center" valign="top"><img src="docs/media/characters/squint.webp" width="150" alt="Squint"><br><b>Squint</b><br>white marker strokes on springs</td>
+ </tr>
+ <tr>
+ <td align="center" valign="top"><img src="docs/media/characters/ray.webp" width="150" alt="Ray"><br><b>Ray</b><br>a sun in vector shapes</td>
+ <td align="center" valign="top"><img src="docs/media/characters/tangle.webp" width="150" alt="Tangle"><br><b>Tangle</b><br>a ball of yarn in one line</td>
+ <td align="center" valign="top"><img src="docs/media/characters/crunch.webp" width="150" alt="Crunch"><br><b>Crunch</b><br>pixel art; its moods are render settings</td>
+ <td align="center" valign="top"><img src="docs/media/characters/nana.webp" width="150" alt="Nana"><br><b>Nana</b><br>pixel art, like Crunch</td>
+ </tr>
+</table>
+
+The states come from what the agent reports: Claude Code through its hooks, Codex through its app-server.
+
+| State | When |
+| --- | --- |
+| Listening | You hold the screen |
+| Thinking | What you said is on its way to the agent; also while the agent compacts its context |
+| Working | The agent is at work; each tool call (read, search, edit, run) shows on screen |
+| Subagents | Subagents are running |
+| Speaking | The agent replies |
+| Needs you | The agent asked you something |
+| Approval | The agent asks for permission |
+| Done | A turn in which it used tools ended |
+| Blocked | An error stopped it, or it hit a rate limit |
+| Sleep | The agent isn't running on the Mac, or the watch can't reach the Mac |
+
+The full map from hook events to states, including the ones the watch doesn't show yet, is in
+[design/STATES.md](design/STATES.md).
+
+## How it works
+
+```mermaid
+flowchart LR
+ W["Apple Watch<br/>Chums app"] -- "HTTPS + watch token" --> F["Tailscale Funnel"]
+ F --> H["Hub on your Mac<br/>(Node.js)"]
+ H <--> S["WhisperKit<br/>speech to text"]
+ H <-- "localhost" --> C["Channel + hooks"]
+ C <-- "MCP" --> A["Claude Code session"]
+ H <-- "JSON-RPC" --> X["codex app-server"]
+```
+
+- **The watch app** (`app/ChumsWatch`, SwiftUI) draws the character, records your voice and polls the hub. **The
+ iPhone app** (`app/ChumsPhone`) reaches the same hub with the same address and token.
+- **The hub** (`hub/hub.mjs`) runs on your Mac. It tracks sessions, routes what you say, holds approvals, transcribes
+ speech (WhisperKit) and voices the replies (Kokoro), all on the Mac.
+- **The channel and hooks** (`channel/`) connect each Claude Code session to the hub. `bin/chums-agents` runs each
+ Claude Code agent's session with both, in the background; `bin/chums-claude` starts one in a terminal.
+- **Codex agents** are run by the hub itself through Codex's app-server protocol (`hub/runtimes.mjs`). `bin/chums-codex`
+ opens a Codex terminal on the same conversation, so you can follow and type into it on the Mac.
+- watchOS apps can't reliably reach an address on your home network, so the hub's watch API is published with
+ Tailscale Funnel and protected by a token. See [SECURITY.md](SECURITY.md) for what that exposes.
+
+Details: [docs/architecture.md](docs/architecture.md).
+
+## On your keys
+
+Keyring mode keeps Chums on screen when nobody is wearing the watch, and your agents keep working on your Mac.
+
+<table>
+ <tr>
+ <td><img src="docs/media/readme/keys.webp" width="420" alt="An Apple Watch on a keyring"></td>
+ <td><img src="docs/media/readme/lanyard.webp" width="420" alt="An Apple Watch on a lanyard"></td>
+ </tr>
+ <tr>
+ <td><img src="docs/media/readme/stand.webp" width="420" alt="An Apple Watch on a stand on a desk"></td>
+ <td><img src="docs/media/readme/counter.webp" width="420" alt="An Apple Watch on a kitchen counter"></td>
+ </tr>
+</table>
+
+## Requirements
+
+- A Mac with Apple silicon on macOS 15.6 or later, Xcode 26 and [XcodeGen](https://github.com/yonaskolb/XcodeGen)
+- An Apple Watch on watchOS 26, paired with an iPhone on iOS 26, and a USB cable for that iPhone (the first time)
+- Node.js 20.11 or later
+- [Claude Code](https://docs.claude.com/en/docs/claude-code) and/or [Codex CLI](https://github.com/openai/codex), signed in
+- [WhisperKit CLI](https://github.com/argmaxinc/WhisperKit) for speech to text, and [ffmpeg](https://ffmpeg.org) to convert the clips
+- [Tailscale](https://tailscale.com) (free account) for Funnel
+- An Apple ID in Xcode. A free Personal Team works; its installs expire after 7 days
+- Optional: [uv](https://docs.astral.sh/uv/), to install the agents' voices (Kokoro, about 1.5 GB). Without them the
+ watch reads replies in its own voice
+
+Every dependency, its minimum version, why it's needed and how to install it: [docs/setup.md](docs/setup.md#1-what-you-need).
+
+## Quickstart
+
+Chums is distributed as source only: you build the watch and iPhone apps in Xcode and sign them with your own Apple
+ID. The first setup takes about 20–30 minutes and needs Xcode and an Apple ID (a free one works). Follow
+[docs/setup.md](docs/setup.md) step by step; this is the short version.
+
+```bash
+git clone https://github.com/lcoutodemos/chums.git && cd chums
+bin/chums-setup # checks the requirements; installs npm packages, the Whisper model and the agents' voices
+bin/chums-hub # start the hub, in its own terminal (first start writes ~/.chums/config.json and the agents)
+bin/chums-tunnel # publish the watch API with Tailscale Funnel (sign in the first time)
+bin/chums-install # build and install the watch and iPhone apps (the first time: setup.md steps 6–8, Xcode and devices)
+bin/chums-agents install # run each character's agent (Claude Code) in the background
+bin/chums-setup --launchd # the hub in the background, as Chums (stop the terminal's hub first: Ctrl-C)
+bin/chums-permissions # once, at the Mac: opens Chums; click Allow All (the agents' permissions, granted once)
+bin/chums-doctor # check the whole chain, read-only; prints the fix for each failure
+```
+
+Every character is its own agent, on Claude Code until you switch it to Codex: on the watch (swipe its row left in
+the agents list, then Runs on) or on its card in the iPhone app ([docs/other-agents.md](docs/other-agents.md)).
+
+No watch? `bin/chums-sim` runs the app in the watchOS Simulator against the same hub, without signing.
+
+Full steps, keyring mode, background agents and every setting: [docs/setup.md](docs/setup.md). When a step fails:
+`bin/chums-doctor`, then [docs/troubleshooting.md](docs/troubleshooting.md). To have a coding agent do the setup with
+you, point it at [AGENTS.md](AGENTS.md): it lists what the agent can do and what only you can do.
+
+## Docs
+
+- [Setup](docs/setup.md): what you need, every step from a clone to talking from the watch, the iPhone app, keyring
+ mode, background agents, settings
+- [Troubleshooting](docs/troubleshooting.md): known problems, each with its cause and fix
+- [How it works](docs/architecture.md): network, channel, hooks, speech, agents, souls, the watch and iPhone apps
+- [Characters](docs/characters.md): how each one is made, gestures, adding a character
+- [Codex and other agents](docs/other-agents.md): running agents on Codex, and experimental Copilot and ACP support
+- [States](design/STATES.md): every Claude Code hook event and Codex app-server event, and what the watch shows for it
+- [Security](SECURITY.md): tokens and what Tailscale Funnel exposes
+- [AGENTS.md](AGENTS.md): for a coding agent (Claude Code, Codex) that sets Chums up with you: what it does, what
+ only you do, and what it says at each hand-over
+
+## Roadmap
+
+- GitHub Copilot CLI and other ACP agents out of experimental ([docs/other-agents.md](docs/other-agents.md))
+- Distinct Waiting (rate limited) and Compacting states on the watch; today they show as Blocked and Thinking
+- A status row with the permission mode and task progress (for example 3 / 5)
+
+## License
+
+Apache License 2.0, for the code and the character art. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
+Chums is not affiliated with or endorsed by Anthropic, OpenAI, GitHub or Apple.
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..2c9fdd6
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,113 @@
+# Security
+
+Chums lets a watch and an iPhone send instructions to AI coding agents that run on your Mac with your user account.
+Anyone who holds the watch token can do what the watch does. Read this before you run it.
+
+## Reporting a vulnerability
+
+Do not open a public issue for a security problem. Use GitHub's private vulnerability reporting on this repository
+(Security › Report a vulnerability). Include the version (commit), what an attacker needs, and the steps to reproduce.
+The report reaches the maintainers only.
+
+## What runs where
+
+| Part | Listens on | Who can reach it |
+| --- | --- | --- |
+| Hub, local side (`hub/hub.mjs`) | `127.0.0.1:7717` (`port` in `~/.chums/config.json`) | Processes on this Mac: the channel and hooks of each Claude Code session, the Simulators |
+| Hub, watch side | `127.0.0.1:7718` (`publicPort`) | Only `/v1/…` paths. Reached from the internet through Tailscale Funnel |
+| Tailscale Funnel (`bin/chums-tunnel`) | `https://<machine>.<tailnet>.ts.net` | Anyone on the internet. Funnel forwards HTTPS requests to `127.0.0.1:7718` |
+| Speech to text (`whisperkit-cli serve`) | `localhost:50061` | Processes on this Mac |
+| The agents' voices (`tools/kokoro-server.py`) | `127.0.0.1:50062` | Processes on this Mac |
+| Codex agents (`codex app-server`) | Unix sockets in `/tmp/chums-<uid>/`, a folder only your user can open (`0700`, its owner checked) | Your user |
+
+The hub never listens on a non-loopback address. The only way in from outside the Mac is the Funnel URL.
+
+## Tokens
+
+The hub creates two random tokens (18 bytes each, base64url) on its first start and stores them in
+`~/.chums/config.json` with file mode `0600`:
+
+- `token`: for the Claude Code side on this Mac (channel and hooks). It is accepted only on the local listener.
+- `watchToken`: for the watch. It is accepted on both listeners. The public listener refuses the local `token`.
+
+Every request carries one of them as `Authorization: Bearer <token>`. Tokens are compared in constant time. On the
+public listener a wrong token waits one second before the `401`.
+
+`tools/gen-config.sh` writes the watch token and the Funnel URL into `app/ChumsWatch/HubConfig.swift`, which is
+compiled into the watch app, the iPhone app and the iPhone's widgets. That file is git-ignored. Do not commit it, and
+do not share a built `.app` or `.ipa`: the token can be read out of the binary.
+
+## What the watch token allows
+
+With the watch token, a client on the internet can do what the watch and the iPhone app do:
+
+- read the current state: session names, their status, the conversation, tool call summaries (file names, commands),
+ pending approval requests and the command they would run;
+- send text or audio that becomes an instruction to an agent, Claude Code or Codex (`/v1/say`, `/v1/utterance`);
+- answer a pending permission request with allow or deny (`/v1/verdict`);
+- fetch pictures the sessions showed and of what you sent (screenshots of your screen or an app, rendered pages and
+ files), and the files themselves as they were, up to 25 MB each (`/v1/artifact/<id>/source` and `/view`: a document,
+ a text file, a video an agent showed);
+- read and change the agents' souls (`~/.chums/souls`): a change said by voice runs `claude -p` once on your account,
+ and a typed one (`/v1/agents/<id>/soul/set`) is saved as written;
+- switch an agent between Claude Code and Codex (`/v1/agents/<id>/runtime`, which stops one and starts the other),
+ change its model (`/v1/agents/<id>/model`, which restarts it) and its voice (`/v1/agents/<id>/voice`);
+- change an agent's permission mode (`/v1/agents/<id>/permission`, which restarts it), including the modes that don't
+ ask you: "Decides on its own" (Claude Code's auto mode, which acts without asking and refuses only what its
+ classifier finds risky) and "Never asks" (Codex's `never`, which runs commands without asking, inside its sandbox).
+ It can't set Claude Code's `bypassPermissions` or change a Codex agent's sandbox;
+- set which agent the iPhone's widgets show (`/v1/focus`);
+- fetch the agents' spoken replies (`/v1/speech/<id>`);
+- put files on the Mac (`/v1/upload`: into `~/.chums/uploads` only, 25 MB at most each, the last 40 kept, names made
+ safe) and send an order that names them; an order can only name files in that folder. Claude Code agents may read
+ that folder without asking. An uploaded HTML or SVG file is turned into a picture by WebKit on the Mac, which can
+ load what the Mac can reach (your network, localhost). Other uploads are read on the Mac to make their picture, by
+ PDFKit, Quick Look, ffmpeg or the hub's own Markdown, text and CSV reader (`hub/render.mjs`), each in a process of
+ its own with a time limit: a file made to exploit one of them runs as your user;
+- add lines to `~/.chums/watch-events.log` (`/v1/event`, the apps' diagnostics; the hub starts a new file past 10 MB).
+
+That is remote control of your coding agents. What a session can then do is limited by its permission mode, which
+the watch token can change, and by the rest of Claude Code's or Codex's settings on your Mac (permission rules, the
+Codex sandbox); approvals that an agent asks for can be granted from the watch.
+
+## Rotating a token
+
+If the watch token may have leaked (a lost watch, a shared build, a log or screenshot that shows it):
+
+1. Stop the hub.
+2. Delete `watchToken` (and `token`, if needed) from `~/.chums/config.json`.
+3. Start the hub. It writes new tokens.
+4. Run `bin/chums-install` to build the new token into the watch app and the iPhone app.
+5. Restart the Claude Code sessions so the channel and hooks read the new `token`: `bin/chums-agents install` for the
+ background agents, and any `bin/chums-claude` session in a terminal. Codex agents restart with the hub.
+
+To take the watch API off the internet at once: `tailscale --socket ~/.chums/tailscale/tailscaled.sock funnel reset`.
+
+## Things to know
+
+- Funnel hostnames are public. Tailscale issues a TLS certificate for the name, so it appears in certificate
+ transparency logs. Assume people can find the URL; the token is what protects it.
+- `bin/chums-claude` starts Claude Code with `--dangerously-load-development-channels server:chums` (channels are a
+ research preview), allows `chums_reply` without asking (`--allowedTools`), and adds permission rules for that
+ session only (its `--settings` file, `channel/hooks.json`): it may read `~/.chums/uploads` (the photos and files you
+ send from the iPhone) without asking; its Edit, Write and MultiEdit tools may not write in `~/.chums/souls` (a shell
+ command still could; the souls are yours to change, from the watch or the iPhone); and it may not open Claude Code's
+ question dialog (`AskUserQuestion`), which only its terminal would show: it asks on the watch and the iPhone with
+ `chums_reply` instead. It does not change your other permission settings.
+- The background agents (`bin/chums-agents`) run Claude Code sessions with access to the folders listed in
+ `~/.chums/agents.json`. Every default agent is given your home folder. Edit `agents.json` to narrow it.
+- Every default agent's guide (`"guide"` in `agents.json`) tells it it can run JavaScript in Safari with `osascript`
+ to read or click inside pages you're logged in to, once you allow Develop › Allow JavaScript from Apple Events. So
+ whoever has the watch token can, through an agent, act in your logged-in Safari. Leave that setting off, or remove
+ the sentence from the agents' guides, if you don't want that.
+- `chums_show` can take screenshots. macOS asks for Screen Recording permission for the app the session runs in.
+- `chums_show` can show any file the session can read: a text file is shown as text, and the file is kept (up to
+ 25 MB) in `~/.chums/artifacts` for the iPhone to open.
+- An HTML or SVG file a session showed or you sent is served to the iPhone with `Content-Security-Policy: sandbox
+ allow-scripts`: its scripts run, in an origin of their own, not the hub's.
+- Speech is transcribed on the Mac by WhisperKit, and the replies are spoken by Kokoro on the Mac. Audio is not sent
+ to a third party by Chums. Instructions you speak go to the agent (Claude Code or Codex), which sends them to its
+ provider like any other prompt. With `"tts": { "engine": "openai" }` in `~/.chums/config.json`, the text of every
+ reply goes to OpenAI to be spoken.
+- A Codex agent's MCP server is given the path of `~/.chums/config.json`, not the token, because `codex app-server`'s
+ arguments are in the process list.
diff --git a/app/ChumsPhone/AgentSheet.swift b/app/ChumsPhone/AgentSheet.swift
new file mode 100644
index 0000000..16d9f2a
--- /dev/null
+++ b/app/ChumsPhone/AgentSheet.swift
@@ -0,0 +1,520 @@
+import SwiftUI
+
+/// An agent, opened (a card that slides up; drag it down to put it away): its name and what it's doing, what it runs
+/// on and on which model, its voice, and its soul. A tap on the name, or on a part of the soul, edits it right there; Save writes it as
+/// you typed it, and it applies from the agent's next order. Undo puts the last change back.
+struct AgentSheet: View {
+ let agent: AgentInfo
+ let hub: HubClient
+ @State private var card: SoulCard?
+ @State private var runtime: String?
+ @State private var switching = false
+ @State private var voice: String?
+ @State private var models: [String: ModelChoices]?
+ @State private var modelsAnswered = false // the hub answered (models still nil: it couldn't be reached)
+ @State private var model: String? // the model picked here, once one is (until then, the hub's)
+ @State private var modelPicked = false
+ @State private var permissions: [String: PermissionChoices]?
+ @State private var permission: String? // the mode picked here, once one is (until then, the hub's)
+ @State private var permissionPicked = false
+ @State private var editing: Part?
+ @State private var text = ""
+ @State private var saving = false
+ @State private var message: String?
+ @FocusState private var focused: Bool
+ @Namespace private var pill
+
+ /// A part of a soul, as the hub keeps it.
+ enum Part: String, CaseIterable, Identifiable {
+ case name, owns, refers, voice, body
+ var id: String { rawValue }
+ var title: String {
+ switch self {
+ case .name: "Name"
+ case .owns: "What it does"
+ case .refers: "Hands off"
+ case .voice: "How it talks"
+ case .body: "Notes"
+ }
+ }
+ var limit: Int { switch self { case .name: 24; case .owns, .refers: 180; case .voice: 90; case .body: 2500 } }
+ /// What goes in it, when it's empty or being written.
+ var hint: String {
+ switch self {
+ case .name: "Its name"
+ case .owns: "Its job: what it takes care of, and where"
+ case .refers: "What it gives to which other agent"
+ case .voice: "How it answers you"
+ case .body: "Anything else it should know"
+ }
+ }
+ static let soul: [Part] = [.owns, .refers, .voice, .body]
+ }
+
+ private var live: AgentInfo { hub.state?.agents?.first { $0.id == agent.id } ?? agent }
+ private var currentRuntime: String { runtime ?? live.runtime ?? "claude" }
+ private var currentModel: String? { modelPicked ? model : live.model }
+ /// The model it runs on, by name: its own, or what its runtime is set to use.
+ private var modelName: String {
+ guard let c = models?[currentRuntime] else { return modelsAnswered ? currentModel ?? " " : " " } // asking: nothing
+ if let m = currentModel { return c.models.first { $0.id == m }?.name ?? m }
+ return c.default ?? "\(AgentChoices.runtimeName(currentRuntime))'s own"
+ }
+ private var currentPermission: String? { permissionPicked ? permission : live.permission }
+ /// How it asks before acting, in words: its own mode, or what its runtime is set to.
+ private var permissionName: String {
+ guard let c = permissions?[currentRuntime] else { return modelsAnswered ? currentPermission ?? " " : " " }
+ if let m = currentPermission { return c.modes.first { $0.id == m }?.name ?? m }
+ return c.default ?? "\(AgentChoices.runtimeName(currentRuntime))'s own"
+ }
+ /// What this Mac can run (an older hub doesn't say: then both).
+ private var installed: [String] { hub.state?.runtimes ?? ["claude", "codex"] }
+
+ var body: some View {
+ NavigationStack {
+ ScrollViewReader { proxy in
+ ScrollView {
+ VStack(alignment: .leading, spacing: 0) {
+ header.id(Part.name).padding(.bottom, 26)
+ label("Runs on")
+ runsOn.padding(.bottom, 14)
+ modelRow
+ permissionRow
+ voiceRow.padding(.bottom, 26)
+ label("Soul")
+ soul
+ if card?.canUndo == true && editing == nil {
+ Button { undo() } label: {
+ Label("Undo the last change", systemImage: "arrow.uturn.backward")
+ .font(.subheadline.weight(.medium)).foregroundStyle(Ink.quiet)
+ .frame(minHeight: M.target).contentShape(Rectangle())
+ }
+ .buttonStyle(Pressable())
+ .padding(.top, 8)
+ }
+ if let message {
+ Text(message).font(.footnote).foregroundStyle(Pal.amber).padding(.top, 8)
+ }
+ Text("Tap a part to change it.")
+ .font(.footnote).foregroundStyle(Ink.quiet).padding(.top, 10).padding(.leading, 2)
+ }
+ .padding(.horizontal, 20).padding(.top, 30).padding(.bottom, 30)
+ .animation(Move.settle, value: editing)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .onChange(of: focused) { _, on in
+ guard on, let p = editing else { return }
+ Task { try? await Task.sleep(for: .milliseconds(350)); withAnimation(Move.settle) { proxy.scrollTo(p, anchor: .center) } }
+ }
+ }
+ .toolbar(.hidden, for: .navigationBar)
+ }
+ .cardSheet(character: agent.character)
+ .task {
+ let c = await hub.soul(agent.id)
+ withAnimation(Move.fade) { card = c }
+ if c == nil { message = "Couldn't get its soul from your Mac." }
+ }
+ .task {
+ async let m = hub.models(), p = hub.permissions()
+ let (ms, ps) = await (m, p)
+ withAnimation(Move.fade) { models = ms; permissions = ps; modelsAnswered = true }
+ }
+ }
+
+ private func label(_ s: String) -> some View {
+ Text(s).font(.footnote.weight(.semibold)).foregroundStyle(Ink.quiet).padding(.leading, 2).padding(.bottom, 8)
+ }
+
+ // MARK: who it is
+
+ /// Its face, its name (a tap edits it here), what it's doing.
+ private var header: some View {
+ HStack(alignment: .center, spacing: 16) {
+ AgentFace(character: agent.character, size: 68)
+ VStack(alignment: .leading, spacing: 4) {
+ if editing == .name {
+ TextField(Part.name.hint, text: $text)
+ .font(.title.weight(.bold)).foregroundStyle(.white).tint(.white)
+ .focused($focused).submitLabel(.done).onSubmit { save(.name) }
+ Rectangle().fill(Color.white.opacity(0.3)).frame(height: 1)
+ editButtons(.name).padding(.top, 6)
+ } else {
+ HStack(spacing: 10) {
+ Text(card?.name ?? live.name).font(.title.weight(.bold)).foregroundStyle(.white)
+ // a pen on glass: the name can be changed here
+ Image(systemName: "pencil").font(.footnote.weight(.semibold)).foregroundStyle(.white)
+ .frame(width: 30, height: 30)
+ .glassEffect(.regular, in: Circle())
+ .accessibilityHidden(true)
+ }
+ .contentShape(Rectangle())
+ .onTapGesture { if editing == nil { begin(.name) } }
+ .accessibilityHint("Renames \(live.name)")
+ .accessibilityIdentifier("part-name")
+ Text(AgentWords.state(live)).font(.subheadline.weight(.medium)).foregroundStyle(AgentWords.color(live))
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ .opacity(editing != nil && editing != .name ? 0.4 : 1)
+ }
+
+ /// Claude Code or Codex: the chosen one lit, sliding across.
+ private var runsOn: some View {
+ HStack(spacing: 4) {
+ ForEach([("claude", "Claude Code"), ("codex", "Codex")], id: \.0) { id, title in
+ let on = currentRuntime == id, can = installed.contains(id)
+ Button {
+ guard can else { message = "\(title) isn't installed on your Mac."; Haptics.play(.failure); return }
+ switchTo(id)
+ } label: {
+ HStack(spacing: 6) {
+ Text(title)
+ if switching && on { ProgressView().controlSize(.mini).tint(.black) }
+ }
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(on ? .black : can ? Color(white: 0.8) : Color(white: 0.35))
+ .frame(maxWidth: .infinity).frame(height: 40)
+ .background { if on { Capsule().fill(.white).matchedGeometryEffect(id: "pill", in: pill) } }
+ .contentShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ }
+ }
+ .padding(3)
+ .background(Color.white.opacity(0.09), in: Capsule())
+ .disabled(switching)
+ .opacity(editing != nil ? 0.4 : 1)
+ .animation(Move.snap, value: currentRuntime)
+ }
+
+ private var modelRow: some View {
+ NavigationLink {
+ AgentChoices(agent: live, title: "Model", tag: "model", runtime: currentRuntime,
+ items: models?[currentRuntime]?.models, defaultLabel: models?[currentRuntime]?.default, answered: modelsAnswered,
+ footer: "\(live.name) restarts on the model you pick. Its conversation carries on.",
+ restart: "Restart it on the new model",
+ picked: Binding(get: { currentModel }, set: { model = $0; modelPicked = true })) { await hub.setModel(agent.id, model: $0) }
+ .cardPage()
+ } label: {
+ row("Model", value: modelName)
+ }
+ .buttonStyle(Pressable())
+ .opacity(editing != nil || switching ? 0.4 : 1)
+ .disabled(editing != nil || switching)
+ .accessibilityIdentifier("model-row")
+ }
+
+ /// How it asks before acting (Asks first, Edits on its own, Decides on its own…): a page like Model's.
+ private var permissionRow: some View {
+ NavigationLink {
+ AgentChoices(agent: live, title: "Permissions", tag: "permission", runtime: currentRuntime,
+ items: permissions?[currentRuntime]?.modes, defaultLabel: permissions?[currentRuntime]?.default, answered: modelsAnswered,
+ footer: "\(live.name) restarts with what you pick. Its conversation carries on.",
+ restart: "Restart it with the new permissions",
+ picked: Binding(get: { currentPermission }, set: { permission = $0; permissionPicked = true })) { await hub.setPermission(agent.id, mode: $0) }
+ .cardPage()
+ } label: {
+ row("Permissions", value: permissionName)
+ }
+ .buttonStyle(Pressable())
+ .opacity(editing != nil || switching ? 0.4 : 1)
+ .disabled(editing != nil || switching)
+ .accessibilityIdentifier("permission-row")
+ }
+
+ /// A row that opens a page: what it is, its value, a chevron.
+ private func row(_ title: String, value: String) -> some View {
+ HStack {
+ Text(title).font(.body).foregroundStyle(.white)
+ Spacer(minLength: 12)
+ Text(value).font(.body).foregroundStyle(Ink.quiet).lineLimit(1)
+ Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Ink.ghost)
+ }
+ .frame(minHeight: M.target).contentShape(Rectangle())
+ }
+
+ private var voiceRow: some View {
+ NavigationLink {
+ AgentVoices(agent: live, hub: hub, picked: Binding(get: { voice ?? live.voice }, set: { voice = $0 }))
+ .cardPage()
+ } label: {
+ row("Voice", value: (voice ?? live.voice).map(AgentVoices.label) ?? "The phone's own")
+ }
+ .buttonStyle(Pressable())
+ .opacity(editing != nil ? 0.4 : 1)
+ .disabled(editing != nil)
+ }
+
+ // MARK: the soul: one glass panel, a part per row
+
+ private var soul: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(Part.soul.enumerated()), id: \.element) { i, p in
+ if i > 0 { Rectangle().fill(Color.white.opacity(0.08)).frame(height: 0.5).padding(.leading, 16) }
+ part(p).id(p)
+ }
+ }
+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: M.tile, style: .continuous))
+ }
+
+ private func value(_ p: Part) -> String {
+ switch p {
+ case .name: card?.name ?? ""
+ case .owns: card?.owns ?? ""
+ case .refers: card?.refers ?? ""
+ case .voice: card?.voice ?? ""
+ case .body: card?.body ?? ""
+ }
+ }
+
+ private func part(_ p: Part) -> some View {
+ let on = editing == p, v = value(p)
+ return VStack(alignment: .leading, spacing: 5) {
+ HStack {
+ Text(p.title).font(.footnote.weight(.semibold)).foregroundStyle(on ? .white : Ink.quiet)
+ Spacer()
+ if on {
+ Text("\(text.count) / \(p.limit)").font(.caption.weight(.medium)).monospacedDigit()
+ .foregroundStyle(text.count > p.limit ? Pal.red : Ink.ghost)
+ }
+ }
+ if on {
+ TextField(p.hint, text: $text, axis: .vertical)
+ .font(.body).foregroundStyle(.white).tint(.white)
+ .lineLimit(1...(p == .body ? 14 : 6))
+ .focused($focused)
+ .submitLabel(p == .body ? .return : .done)
+ .onSubmit { if p != .body { save(p) } }
+ editButtons(p).padding(.top, 6)
+ } else if card == nil {
+ Text(" ").font(.body).accessibilityHidden(true) // still coming from the Mac: blank, not the hint
+ } else {
+ Text(v.isEmpty ? p.hint : v).font(.body)
+ .foregroundStyle(v.isEmpty ? Ink.ghost : .white)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ .padding(.horizontal, 16).padding(.vertical, 13)
+ .contentShape(Rectangle())
+ .onTapGesture { if editing == nil && card != nil { begin(p) } }
+ .opacity(editing != nil && !on ? 0.4 : 1)
+ .accessibilityElement(children: on ? .contain : .combine)
+ .accessibilityHint(on ? "" : "Edits \(p.title.lowercased())")
+ .accessibilityIdentifier("part-\(p.rawValue)")
+ }
+
+ private func editButtons(_ p: Part) -> some View {
+ HStack(spacing: 14) {
+ Spacer()
+ Button("Cancel") { stopEditing() }
+ .font(.subheadline.weight(.medium)).foregroundStyle(Ink.quiet)
+ .buttonStyle(Pressable())
+ Button { save(p) } label: {
+ Group { if saving { ProgressView().tint(.black) } else { Text("Save") } }
+ .font(.subheadline.weight(.semibold)).foregroundStyle(.black)
+ .frame(minWidth: 60).frame(height: 34).padding(.horizontal, 6)
+ .background(Color.white, in: Capsule())
+ }
+ .buttonStyle(Pressable())
+ .disabled(saving || text.count > p.limit || (p == .name && text.trimmingCharacters(in: .whitespaces).isEmpty))
+ }
+ }
+
+ // MARK: doing it
+
+ private func begin(_ p: Part) {
+ Haptics.play(.click)
+ text = value(p); message = nil
+ withAnimation(Move.settle) { editing = p }
+ Task { try? await Task.sleep(for: .milliseconds(60)); focused = true }
+ }
+ private func stopEditing() {
+ focused = false
+ withAnimation(Move.settle) { editing = nil }
+ }
+ private func save(_ p: Part) {
+ guard !saving else { return }
+ if text == value(p) { stopEditing(); return }
+ saving = true
+ Task {
+ let (c, e) = await hub.setSoul(agent.id, field: p.rawValue, value: text)
+ saving = false
+ if let c { card = c; Haptics.play(.success); stopEditing() } else { message = e ?? "Couldn't save that."; Haptics.play(.failure) }
+ }
+ }
+ private func switchTo(_ r: String) {
+ guard r != currentRuntime, !switching else { return }
+ switching = true; message = nil
+ Haptics.play(.click)
+ Task {
+ if let e = await hub.setRuntime(agent.id, runtime: r) { message = e; Haptics.play(.failure) }
+ else { runtime = r; modelPicked = false; permissionPicked = false; Haptics.play(.success) } // each runtime keeps its own
+ switching = false
+ }
+ }
+ private func undo() {
+ Task {
+ let (c, e) = await hub.undoSoul(agent.id)
+ if let c { card = c; Haptics.play(.success) } else { message = e }
+ }
+ }
+}
+
+/// One of an agent's settings picked from a list (its model, its permissions): its runtime's own setting first
+/// (Default), then each choice with a line about it. A tap switches it: the agent restarts with it, and its
+/// conversation carries on. While it works, it asks first.
+struct AgentChoices: View {
+ let agent: AgentInfo
+ let title: String // the page's: "Model", "Permissions"
+ let tag: String // its rows' identifiers: "model-opus", "permission-default"
+ let runtime: String
+ let items: [ModelChoices.Model]?
+ let defaultLabel: String? // what the runtime uses when the agent has none of its own
+ let answered: Bool // the hub answered: no items now means it couldn't be reached
+ let footer: String
+ let restart: String // the button that restarts it while it works
+ @Binding var picked: String?
+ let apply: (String?) async -> String? // nil once it's set, else why not
+ @State private var busy: Choice?
+ @State private var asking: Choice?
+ @State private var error: String?
+
+ /// A row: a choice, or none (the runtime's own setting).
+ struct Choice: Identifiable, Equatable { let value: String?; var id: String { value ?? "" } }
+ static func runtimeName(_ r: String) -> String { r == "codex" ? "Codex" : "Claude Code" }
+ private var working: Bool { agent.status == "working" || agent.status == "compacting" }
+
+ var body: some View {
+ List {
+ if let items {
+ Section {
+ item(Choice(value: nil), "Default",
+ about: defaultLabel.map { "\(Self.runtimeName(runtime))'s setting: \($0)" } ?? "\(Self.runtimeName(runtime))'s own setting")
+ ForEach(items) { m in item(Choice(value: m.id), m.name, about: m.about) }
+ } footer: {
+ Text(footer)
+ }
+ .cardRows()
+ } else {
+ Text(answered ? error ?? "Can't reach your Mac" : "Asking your Mac…").foregroundStyle(Ink.quiet)
+ .listRowBackground(Color.clear)
+ }
+ if let error, items != nil { Text(error).font(.footnote).foregroundStyle(Pal.amber).listRowBackground(Color.clear) }
+ }
+ .navigationTitle(title)
+ .confirmationDialog("\(agent.name) is working", isPresented: Binding(get: { asking != nil }, set: { if !$0 { asking = nil } }),
+ titleVisibility: .visible, presenting: asking) { c in
+ Button(restart) { set(c) }
+ } message: { _ in
+ Text("It restarts and stops what it's doing now.")
+ }
+ }
+
+ private func item(_ c: Choice, _ name: String, about: String?) -> some View {
+ Button {
+ guard busy == nil, c.value != picked else { return }
+ Haptics.play(.click)
+ if working { asking = c } else { set(c) }
+ } label: {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(name).foregroundStyle(.white)
+ if let about { Text(about).font(.footnote).foregroundStyle(Ink.quiet) }
+ }
+ Spacer(minLength: 12)
+ if busy == c { ProgressView().tint(.white) }
+ else if picked == c.value { Image(systemName: "checkmark").font(.body.weight(.semibold)).foregroundStyle(.white) }
+ }
+ .contentShape(Rectangle())
+ }
+ .accessibilityAddTraits(picked == c.value ? .isSelected : [])
+ .accessibilityIdentifier("\(tag)-\(c.value ?? "own")") // own: the runtime's setting (a mode can be "default")
+ }
+
+ private func set(_ c: Choice) {
+ busy = c; error = nil
+ Task {
+ if let e = await apply(c.value) { error = e; Haptics.play(.failure) }
+ else { picked = c.value; Haptics.play(.success) }
+ busy = nil
+ }
+ }
+}
+
+extension View {
+ /// The app's sliding card: the whole height, a handle to drag it down by (no Done), rounded, over a frosted ground
+ /// made of the agent's own colours. Every card in the app (an agent, Settings, a picture) is this one.
+ func cardSheet(character: String) -> some View {
+ self
+ .presentationDetents([.large])
+ .presentationDragIndicator(.visible)
+ .presentationCornerRadius(34)
+ .presentationBackground {
+ ZStack {
+ Color.black
+ AgentFace(character: character, size: 460)
+ .blur(radius: 70).opacity(0.34).offset(y: -170)
+ Rectangle().fill(Color.black.opacity(0.18))
+ }
+ .ignoresSafeArea()
+ }
+ .preferredColorScheme(.dark)
+ }
+
+ /// A page a card opens (Model, Voice): its list on the card's frosted ground, its title at the top, and back as a
+ /// plain chevron, with no plate (a swipe from the left edge goes back too).
+ func cardPage() -> some View { modifier(CardPage()) }
+
+ /// The rows of a card's page: one surface, the same on every page.
+ func cardRows() -> some View { listRowBackground(Color.white.opacity(0.08)) }
+}
+
+private struct CardPage: ViewModifier {
+ @Environment(\.dismiss) private var dismiss
+
+ func body(content: Content) -> some View {
+ content
+ .scrollContentBackground(.hidden)
+ .containerBackground(.clear, for: .navigation)
+ .toolbar(.visible, for: .navigationBar)
+ .navigationBarBackButtonHidden(true)
+ .toolbar {
+ ToolbarItem(placement: .topBarLeading) {
+ Button { dismiss() } label: {
+ Image(systemName: "chevron.left").font(.system(size: 20, weight: .semibold)).foregroundStyle(.white)
+ .frame(width: M.target, height: M.target).contentShape(Rectangle())
+ }
+ .buttonStyle(Pressable())
+ .accessibilityLabel("Back")
+ .accessibilityIdentifier("back")
+ }
+ .sharedBackgroundVisibility(.hidden)
+ }
+ .background(EdgeSwipeBack())
+ }
+}
+
+/// A hidden back button turns off the swipe from the left edge: while the page is up, this turns it back on (it goes
+/// back whenever there's a page to go back to), and gives it back to the stack as the page goes.
+private struct EdgeSwipeBack: UIViewControllerRepresentable {
+ func makeUIViewController(context: Context) -> Hook { Hook() }
+ func updateUIViewController(_ hook: Hook, context: Context) {}
+
+ final class Hook: UIViewController, UIGestureRecognizerDelegate {
+ private weak var stack: UIGestureRecognizerDelegate?
+
+ override func viewDidAppear(_ animated: Bool) {
+ super.viewDidAppear(animated)
+ guard let g = navigationController?.interactivePopGestureRecognizer, g.delegate !== self else { return }
+ stack = g.delegate; g.delegate = self
+ }
+ override func viewWillDisappear(_ animated: Bool) {
+ super.viewWillDisappear(animated)
+ if let g = navigationController?.interactivePopGestureRecognizer, g.delegate === self { g.delegate = stack }
+ }
+ func gestureRecognizerShouldBegin(_ g: UIGestureRecognizer) -> Bool { (navigationController?.viewControllers.count ?? 0) > 1 }
+ }
+}
diff --git a/app/ChumsPhone/AppSettings.swift b/app/ChumsPhone/AppSettings.swift
new file mode 100644
index 0000000..45add3a
--- /dev/null
+++ b/app/ChumsPhone/AppSettings.swift
@@ -0,0 +1,102 @@
+import SwiftUI
+
+/// The iPhone app's own settings (each agent's are in its card: what it runs on, its voice, its soul), on a card that
+/// slides up (drag it down to put it away): the connection to your Mac, reading replies aloud, haptics, the agents'
+/// order, and which build this is.
+struct AppSettings: View {
+ let hub: HubClient
+ var character: String = Agents.fallback // the agent on screen: its colours are the card's ground
+ @AppStorage("voice") private var speak = true
+ @AppStorage("haptics") private var haptics = true
+ @AppStorage("agentOrder") private var order = ""
+ @State private var ms: Double?
+ @State private var checking = false
+ @State private var checked = false
+
+ private var host: String { URL(string: hub.address)?.host() ?? hub.address }
+ private var version: String {
+ let v = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "?"
+ return "\(v) · built \(HubConfig.build)"
+ }
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("Settings").font(.title.weight(.bold)).foregroundStyle(.white).padding(.leading, 4).padding(.bottom, 6)
+
+ card {
+ HStack(spacing: 14) {
+ Image(systemName: hub.connected ? "desktopcomputer" : "exclamationmark.triangle.fill")
+ .font(.title3).foregroundStyle(hub.connected ? .white : Pal.amber)
+ .frame(width: 32)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(hub.connected ? "Connected to your Mac" : "Can't reach your Mac").font(.body.weight(.semibold))
+ Text(hub.lastError ?? (host.hasSuffix(".ts.net") ? "Through Tailscale Funnel" : "On this network"))
+ .font(.footnote).foregroundStyle(Ink.quiet)
+ }
+ }
+ divider
+ row("Address") { Text(host).foregroundStyle(Ink.quiet).lineLimit(1).truncationMode(.middle) }
+ divider
+ row("Answers in") {
+ if checking { ProgressView().controlSize(.small).tint(.white) }
+ else if let ms { Text("\(Int(ms.rounded())) ms").monospacedDigit().foregroundStyle(Ink.quiet) }
+ else { Text(checked ? "No answer" : "–").foregroundStyle(checked ? Pal.amber : Color(white: 0.5)) }
+ }
+ divider
+ Button { check() } label: {
+ Text("Check the connection").font(.body).frame(maxWidth: .infinity, alignment: .leading)
+ .frame(height: 44).contentShape(Rectangle())
+ }
+ .buttonStyle(Pressable()).foregroundStyle(.white).disabled(checking)
+ }
+ note("Chums reaches the hub on your Mac at this address. If it can't, check that the hub is running, and run bin/chums-doctor on the Mac.")
+
+ card {
+ Toggle("Read replies aloud", isOn: $speak).font(.body).frame(minHeight: 44)
+ divider
+ Toggle("Haptics", isOn: $haptics).font(.body).frame(minHeight: 44)
+ }
+ .toggleStyle(InkToggle())
+ note("Replies to what you say on the iPhone are read aloud here, each in its agent's voice. Off, they only show in the conversation.")
+
+ if !order.isEmpty {
+ card {
+ Button { withAnimation(Move.settle) { order = "" }; Haptics.play(.success) } label: {
+ Text("Put the agents back in their first order").font(.body)
+ .frame(maxWidth: .infinity, alignment: .leading).frame(minHeight: 44).contentShape(Rectangle())
+ }
+ .buttonStyle(Pressable())
+ .foregroundStyle(.white)
+ }
+ note("You changed the agents' order. This puts them back as they came.")
+ .transition(.opacity)
+ }
+
+ Text(version).font(.footnote).foregroundStyle(Ink.ghost)
+ .frame(maxWidth: .infinity).padding(.top, 14)
+ }
+ .padding(.horizontal, 20).padding(.top, 30).padding(.bottom, 30)
+ }
+ .cardSheet(character: character)
+ .task { check() }
+ }
+
+ private func card<C: View>(@ViewBuilder _ content: () -> C) -> some View {
+ VStack(alignment: .leading, spacing: 0) { content() }
+ .padding(.horizontal, 16).padding(.vertical, 8)
+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 24, style: .continuous))
+ }
+ private func row<V: View>(_ title: String, @ViewBuilder value: () -> V) -> some View {
+ HStack { Text(title).font(.body); Spacer(minLength: 12); value().font(.body) }.frame(minHeight: 44)
+ }
+ private var divider: some View { Rectangle().fill(Color.white.opacity(0.08)).frame(height: 0.5) }
+ private func note(_ s: String) -> some View {
+ Text(s).font(.footnote).foregroundStyle(Color(white: 0.5)).padding(.horizontal, 6).padding(.bottom, 10)
+ }
+
+ private func check() {
+ checking = true
+ Task { ms = await hub.ping(); checking = false; checked = true }
+ }
+}
diff --git a/app/ChumsPhone/Assets.xcassets/AppIcon.appiconset/Contents.json b/app/ChumsPhone/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 0000000..0eca1fe
--- /dev/null
+++ b/app/ChumsPhone/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,14 @@
+{
+ "images": [
+ {
+ "filename": "icon-1024.png",
+ "idiom": "universal",
+ "platform": "ios",
+ "size": "1024x1024"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ }
+}
\ No newline at end of file
diff --git a/app/ChumsPhone/Assets.xcassets/AppIcon.appiconset/icon-1024.png b/app/ChumsPhone/Assets.xcassets/AppIcon.appiconset/icon-1024.png
new file mode 100644
index 0000000..4aec82b
Binary files /dev/null and b/app/ChumsPhone/Assets.xcassets/AppIcon.appiconset/icon-1024.png differ
diff --git a/app/ChumsPhone/Assets.xcassets/Contents.json b/app/ChumsPhone/Assets.xcassets/Contents.json
new file mode 100644
index 0000000..fe97fb1
--- /dev/null
+++ b/app/ChumsPhone/Assets.xcassets/Contents.json
@@ -0,0 +1 @@
+{"info": {"author": "xcode", "version": 1}}
\ No newline at end of file
diff --git a/app/ChumsPhone/ChumsPhoneApp.swift b/app/ChumsPhone/ChumsPhoneApp.swift
new file mode 100644
index 0000000..b6d3653
--- /dev/null
+++ b/app/ChumsPhone/ChumsPhoneApp.swift
@@ -0,0 +1,43 @@
+import SwiftUI
+import WidgetKit
+
+/// Chums on the iPhone: the same agents as the watch, through the same hub. One screen per agent (HomeView): its
+/// conversation with the character as its last row, the other agents in a panel from the left, a box to type, talk or
+/// send photos and files. Widgets, Lock Screen widgets, a Control (Control Center, the Action Button) and Siri reach it
+/// too (ChumsPhoneWidgets, PhoneIntents).
+@main
+struct ChumsPhoneApp: App {
+ @State private var hub = HubClient()
+ @Environment(\.scenePhase) private var phase
+
+ init() { CharacterKind.migrate() }
+
+ var body: some Scene {
+ WindowGroup {
+ HomeView(hub: hub)
+ .preferredColorScheme(.dark)
+ .onChange(of: phase, initial: true) { old, p in
+ // a system alert or Control Center over it (inactive) keeps it listening; only the background stops it
+ if p == .active { hub.start() } else if p == .background { hub.stop() }
+ // what the widgets show is what the app last saw
+ if p != .active { WidgetCenter.shared.reloadAllTimelines() }
+ if old != p { hub.event("phone: app \(p == .active ? "active" : p == .inactive ? "inactive" : "background")") }
+ }
+ }
+ }
+}
+
+/// What a link from a widget, the Control or Siri asks for: chums://agent/<id> shows that agent, chums://talk[/<id>]
+/// also starts listening.
+enum PhoneLink: Equatable {
+ case agent(String), talk(String?)
+ init?(_ url: URL) {
+ guard url.scheme == "chums" else { return nil }
+ let id = url.pathComponents.dropFirst().first
+ switch url.host {
+ case "agent": guard let id else { return nil }; self = .agent(id)
+ case "talk": self = .talk(id)
+ default: return nil
+ }
+ }
+}
diff --git a/app/ChumsPhone/Composer.swift b/app/ChumsPhone/Composer.swift
new file mode 100644
index 0000000..2e6ffb8
--- /dev/null
+++ b/app/ChumsPhone/Composer.swift
@@ -0,0 +1,442 @@
+import PhotosUI
+import SwiftUI
+import UniformTypeIdentifiers
+
+/// The box at the bottom. + on its left adds photos (the camera or the library) and files; they wait above the box till
+/// the next message takes them. The microphone on its right: tap it and talk, then send (↑) or throw it away (×); or
+/// hold it, talk and let go to send (slide left onto × to throw it away). Once something is typed or added, it's the
+/// send button. Opened from a widget, the Control or Siri, it's already listening: × or ↑.
+struct Composer: View {
+ let name: String
+ @Binding var draft: String
+ @Binding var attachments: [Attachment]
+ var typing: FocusState<Bool>.Binding
+ let model: ScreenModel
+ @Binding var handsFree: Bool // listening with no finger down (a tap on the mic, a widget, Siri)
+ @Binding var attaching: Bool // the + menu is open (the screen behind it dims)
+ let sending: Bool
+ let send: (String) -> Void
+ @State private var holding = false // listening while a finger is on the mic
+ @State private var pressedAt = Date.distantPast
+ @State private var since = Date() // when this listening began
+ @State private var refused = false // this touch couldn't start the microphone: ignore it till it lifts
+ @State private var slide = 0.0
+ @State private var boxH = 52.0 // the box's height: the + menu floats just above it
+ @State private var photos: [PhotosPickerItem] = []
+ @State private var choosingPhotos = false
+ @State private var choosingFiles = false
+ @State private var camera = false
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ private static let cancelAt = -64.0
+
+ private var listening: Bool { holding || handsFree }
+ private var armed: Bool { holding && slide <= Self.cancelAt } // letting go now throws it away
+ private var canSend: Bool { !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ if !attachments.isEmpty && !listening { tray.transition(.move(edge: .bottom).combined(with: .opacity)) }
+ // the + menu floats over whatever is above the box: it moves nothing
+ box
+ .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { boxH = $0 }
+ .overlay(alignment: .bottomLeading) {
+ if attaching { menu.fixedSize().offset(y: -(boxH + 10)) }
+ }
+ }
+ .dynamicTypeSize(...DynamicTypeSize.accessibility1) // the box grows with the text, up to here
+ .animation(Move.snap, value: listening)
+ .animation(Move.snap, value: attachments)
+ .animation(.snappy(duration: 0.18), value: canSend)
+ .onChange(of: listening) { _, on in if on { since = Date() } }
+ // listening ends on its own (the time limit, a failed microphone): the box follows the model
+ .task(id: listening) {
+ while listening && !Task.isCancelled {
+ try? await Task.sleep(for: .milliseconds(400))
+ if listening && !model.listening { holding = false; handsFree = false; slide = 0 }
+ }
+ }
+ .photosPicker(isPresented: $choosingPhotos, selection: $photos, maxSelectionCount: 6, matching: .images)
+ .onChange(of: photos) { _, items in
+ guard !items.isEmpty else { return }
+ Task {
+ for item in items {
+ if let d = try? await item.loadTransferable(type: Data.self) { await addPhoto { UIImage(data: d) } }
+ }
+ photos = []
+ }
+ }
+ .fileImporter(isPresented: $choosingFiles, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in
+ let urls = (try? result.get()) ?? []
+ Task { await addFiles(urls) }
+ }
+ .fullScreenCover(isPresented: $camera) {
+ CameraPicker { img in Task { await addPhoto { img } } }
+ .ignoresSafeArea()
+ }
+ }
+
+ // MARK: the box
+
+ /// Left, middle, right, at one height whatever it's doing (the conversation above it never moves). The right slot
+ /// is the same view from the touch that starts listening to the touch that ends it.
+ private var box: some View {
+ HStack(alignment: .bottom, spacing: 4) {
+ leading.frame(width: 42, height: 42)
+ ZStack(alignment: .leading) {
+ field.opacity(listening ? 0 : 1).allowsHitTesting(!listening) // keeps the box's height
+ if listening { voice.transition(.opacity) }
+ }
+ .frame(maxWidth: .infinity, minHeight: 42, alignment: .leading)
+ trailing.frame(width: 42, height: 42)
+ }
+ .padding(5)
+ .glassEffect(listening ? .regular.tint(.white.opacity(0.07)) : .regular, in: RoundedRectangle(cornerRadius: 26, style: .continuous))
+ }
+
+ @ViewBuilder private var leading: some View {
+ if listening {
+ Button { stop(cancel: true) } label: {
+ Image(systemName: "xmark").font(.system(size: 14, weight: .bold))
+ .foregroundStyle(armed || handsFree ? .white : Ink.quiet)
+ .frame(width: 34, height: 34)
+ .background(armed ? Pal.red : Color(white: 0.2), in: Circle())
+ .scaleEffect(armed ? 1.12 : 1)
+ .frame(width: 42, height: 42).contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .animation(Move.snap, value: armed)
+ .transition(.scale(scale: 0.5).combined(with: .opacity))
+ .accessibilityLabel("Cancel")
+ .accessibilityIdentifier("cancel-talk")
+ } else {
+ Button {
+ typing.wrappedValue = false
+ withAnimation(Move.snap) { attaching.toggle() }
+ Haptics.play(.click)
+ } label: {
+ Image(systemName: "plus").font(.system(size: 20, weight: .medium))
+ .foregroundStyle(Color(white: attaching ? 1 : 0.82))
+ .rotationEffect(.degrees(attaching ? 45 : 0))
+ .frame(width: M.target, height: M.target).contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .transition(.scale(scale: 0.5).combined(with: .opacity))
+ .accessibilityLabel(attaching ? "Close" : "Add photos or files")
+ }
+ }
+
+ private var field: some View {
+ TextField("Message \(name)", text: $draft, axis: .vertical)
+ .font(.body).lineLimit(1...6)
+ .focused(typing)
+ .submitLabel(.send)
+ .onSubmit(submit)
+ .padding(.leading, 2).padding(.vertical, 10)
+ .accessibilityIdentifier("message")
+ .onChange(of: typing.wrappedValue) { _, on in if on && attaching { withAnimation(Move.snap) { attaching = false } } }
+ }
+
+ /// The middle while it listens: your voice as bars, and how long; or what letting go will do.
+ private var voice: some View {
+ HStack(spacing: 10) {
+ if armed {
+ Text("Let go to cancel").font(.subheadline.weight(.medium)).foregroundStyle(Pal.red)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .transition(.opacity)
+ } else {
+ TimelineView(.animation(minimumInterval: 1.0 / 30)) { _ in Waveform(level: model.talkLevel) }
+ .frame(height: 22)
+ }
+ TimelineView(.periodic(from: since, by: 1)) { t in
+ let s = max(0, Int(t.date.timeIntervalSince(since)))
+ Text(String(format: "%d:%02d", s / 60, s % 60)).font(.subheadline.monospacedDigit()).foregroundStyle(Ink.quiet)
+ }
+ }
+ .frame(height: 42)
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel("Listening to you for \(name)")
+ }
+
+ @ViewBuilder private var trailing: some View {
+ if sending {
+ ProgressView().tint(.black).frame(width: 36, height: 36).background(Color.white, in: Circle())
+ } else if canSend && !listening {
+ Button(action: submit) {
+ Image(systemName: "arrow.up").font(.system(size: 17, weight: .bold)).foregroundStyle(.black)
+ .frame(width: 36, height: 36).background(Color.white, in: Circle())
+ .frame(width: 42, height: 42).contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .transition(.scale(scale: 0.6).combined(with: .opacity))
+ .accessibilityLabel("Send")
+ } else {
+ mic
+ }
+ }
+
+ /// Tap: listen till ↑ or ×. Hold: listen till you let go (slide left onto × first to throw it away). Listening with
+ /// no finger down, it's ↑. One gesture on one view, from the first touch to the last.
+ private var mic: some View {
+ // held, it grows with your voice, read 30 times a second (a change in the level doesn't redraw the box)
+ TimelineView(.animation(minimumInterval: 1.0 / 30, paused: !holding)) { _ in
+ ZStack {
+ Circle().fill(Color.white)
+ Image(systemName: handsFree ? "arrow.up" : "mic.fill")
+ .font(.system(size: 17, weight: .bold)).foregroundStyle(.black)
+ .contentTransition(.symbolEffect(.replace))
+ }
+ .frame(width: 36, height: 36)
+ .scaleEffect(holding ? 1.3 + model.talkLevel * 0.15 : 1)
+ }
+ .offset(x: holding ? max(slide, -90) * 0.5 : 0)
+ .frame(width: 42, height: 42)
+ .contentShape(Circle().inset(by: -10))
+ .gesture(
+ DragGesture(minimumDistance: 0)
+ .onChanged { v in
+ if attaching { withAnimation(Move.snap) { attaching = false } } // the + menu goes at the first touch
+ guard !handsFree, !refused else { return }
+ if !holding {
+ typing.wrappedValue = false
+ model.micDown()
+ guard model.listening else { refused = true; return } // not allowed (yet), or the mic is busy
+ holding = true; pressedAt = Date(); slide = 0
+ }
+ let s = min(0, v.translation.width)
+ if (s <= Self.cancelAt) != (slide <= Self.cancelAt) { Haptics.play(.click) }
+ slide = s
+ }
+ .onEnded { v in
+ if refused { refused = false; return }
+ if handsFree { stop(cancel: false); return } // ↑
+ guard holding else { return }
+ let tap = Date().timeIntervalSince(pressedAt) < 0.35 && abs(v.translation.width) < 12
+ holding = false
+ if tap { handsFree = true; slide = 0; return } // a tap: keep listening
+ let cancel = slide <= Self.cancelAt
+ slide = 0
+ model.micUp(cancel: cancel)
+ }
+ )
+ .animation(.interactiveSpring(response: 0.25, dampingFraction: 0.8), value: slide)
+ .animation(Move.snap, value: holding)
+ .accessibilityLabel(handsFree ? "Send" : "Talk to \(name)")
+ .accessibilityHint(handsFree ? "" : "Tap to start, or hold while you talk")
+ .accessibilityIdentifier("mic")
+ }
+
+ private func stop(cancel: Bool) {
+ holding = false; handsFree = false; slide = 0
+ if !cancel { Haptics.play(.click) }
+ model.micUp(cancel: cancel)
+ }
+
+ // MARK: adding things
+
+ /// What + opens: the camera, the photo library and Files, as glass pills of one size that grow up out of the +, one
+ /// after another.
+ private var menu: some View {
+ let options: [(id: String, symbol: String, title: String, run: () -> Void)] =
+ (UIImagePickerController.isSourceTypeAvailable(.camera) ? [("camera", "camera", "Take Photo", { camera = true })] : [])
+ + [("photos", "photo.on.rectangle", "Photo Library", { choosingPhotos = true }), ("files", "folder", "Files", { choosingFiles = true })]
+ return VStack(alignment: .leading, spacing: 8) {
+ ForEach(Array(options.enumerated()), id: \.element.id) { i, o in
+ Button { pickThen(o.run) } label: {
+ HStack(spacing: 12) {
+ Image(systemName: o.symbol).font(.body.weight(.medium)).frame(width: 24)
+ Text(o.title).font(.body.weight(.medium))
+ Spacer(minLength: 0)
+ }
+ .foregroundStyle(.white)
+ .frame(width: 170, height: 30)
+ }
+ .buttonStyle(.glass).buttonBorderShape(.capsule).controlSize(.large)
+ .transition(reduceMotion ? .opacity : .asymmetric(
+ insertion: .scale(scale: 0.6, anchor: .bottomLeading).combined(with: .opacity)
+ .animation(Move.snap.delay(Double(options.count - 1 - i) * 0.04)),
+ removal: .opacity.animation(.easeIn(duration: 0.12))))
+ }
+ }
+ .padding(.leading, 4)
+ }
+ private func pickThen(_ open: @escaping () -> Void) {
+ withAnimation(Move.snap) { attaching = false }
+ Task { try? await Task.sleep(for: .milliseconds(180)); open() }
+ }
+
+ /// A photo, made smaller to send off the main thread (six of them take a moment), then added.
+ private func addPhoto(_ image: @escaping @Sendable () -> UIImage?) async {
+ let name = "photo-\(attachments.count + 1).jpg"
+ let a = await Task.detached(priority: .userInitiated) { image().flatMap { Attachment.photo($0, name: name) } }.value
+ if let a { attachments.append(a); Haptics.play(.click) }
+ }
+
+ /// Files, read off the main thread, then added; one over 25 MB isn't, and the conversation says so.
+ private func addFiles(_ urls: [URL]) async {
+ var big: [String] = []
+ for url in urls {
+ switch await Task.detached(priority: .userInitiated, operation: { Result { try Attachment.file(url) } }).value {
+ case .success(let a): attachments.append(a); Haptics.play(.click)
+ case .failure(Attachment.Refusal.tooBig): big.append(url.lastPathComponent)
+ case .failure: model.onNotice?("Couldn't read \(url.lastPathComponent).")
+ }
+ }
+ if let one = big.first {
+ model.onNotice?(big.count == 1 ? "\(one) wasn't added: it's over 25 MB." : "\(big.count) files weren't added: they're over 25 MB.")
+ }
+ }
+
+ /// What goes with the next message: pictures as thumbnails, files by name; × takes one out.
+ private var tray: some View {
+ ScrollView(.horizontal) {
+ HStack(spacing: 10) {
+ ForEach(attachments) { a in
+ AttachmentChip(attachment: a, dim: sending) {
+ withAnimation(Move.snap) { attachments.removeAll { $0.id == a.id } }
+ Haptics.play(.click)
+ }
+ .transition(.scale(scale: 0.8).combined(with: .opacity))
+ }
+ }
+ .padding(.top, 10).padding(.horizontal, 4)
+ }
+ .scrollIndicators(.hidden)
+ }
+
+ private func submit() {
+ let t = draft.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard (!t.isEmpty || !attachments.isEmpty) && !sending else { return }
+ Haptics.play(.click) // at the tap, not after the round trip
+ draft = ""
+ send(t)
+ }
+}
+
+/// One thing waiting to go with the next message: a picture as itself, a file by its name; × takes it out.
+private struct AttachmentChip: View {
+ let attachment: Attachment
+ let dim: Bool
+ let remove: () -> Void
+
+ var body: some View {
+ content
+ .opacity(dim ? 0.5 : 1)
+ .overlay(alignment: .topTrailing) {
+ Button(action: remove) {
+ Image(systemName: "xmark").font(.system(size: 9, weight: .heavy)).foregroundStyle(.white)
+ .frame(width: 20, height: 20).background(Color(white: 0.28), in: Circle())
+ .overlay(Circle().strokeBorder(.black, lineWidth: 1.5))
+ .frame(width: 32, height: 32).contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .offset(x: 10, y: -10)
+ .accessibilityLabel("Remove \(attachment.name)")
+ }
+ }
+
+ @ViewBuilder private var content: some View {
+ if let img = attachment.preview {
+ Image(uiImage: img).resizable().scaledToFill().frame(width: 66, height: 66)
+ .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
+ } else {
+ HStack(spacing: 8) {
+ Image(systemName: "doc.fill").font(.body).foregroundStyle(Color(white: 0.7))
+ Text(attachment.name).font(.footnote.weight(.medium)).foregroundStyle(.white).lineLimit(2)
+ .frame(maxWidth: 130, alignment: .leading)
+ }
+ .padding(.horizontal, 12).frame(height: 66)
+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
+ }
+ }
+}
+
+/// Pressed, a row lights up behind its content.
+struct RowPress: ButtonStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .background(Color.white.opacity(configuration.isPressed ? 0.1 : 0), in: RoundedRectangle(cornerRadius: 16, style: .continuous))
+ .animation(.easeOut(duration: 0.12), value: configuration.isPressed)
+ }
+}
+
+/// Something to send with the next message: a picture (made smaller to send) or a file.
+struct Attachment: Identifiable, Equatable {
+ let id = UUID()
+ let name: String
+ let type: String // its MIME type
+ let data: Data
+ let preview: UIImage? // pictures
+ static func == (a: Attachment, b: Attachment) -> Bool { a.id == b.id }
+
+ /// A photo, at most 2048 px on its longest side, as JPEG.
+ static func photo(_ image: UIImage, name: String) -> Attachment? {
+ let k = min(1, 2048 / max(image.size.width, image.size.height, 1))
+ let size = CGSize(width: (image.size.width * k).rounded(), height: (image.size.height * k).rounded())
+ let format = UIGraphicsImageRendererFormat(); format.scale = 1
+ let small = UIGraphicsImageRenderer(size: size, format: format).image { _ in image.draw(in: CGRect(origin: .zero, size: size)) }
+ guard let d = small.jpegData(compressionQuality: 0.82) else { return nil }
+ return Attachment(name: name, type: "image/jpeg", data: d, preview: small.preparingThumbnail(of: CGSize(width: 192, height: 192)) ?? small)
+ }
+
+ /// Why a file can't go: it's over 25 MB (the most the Mac takes), or it can't be read.
+ enum Refusal: Error { case tooBig, unreadable }
+
+ /// A file from Files (25 MB at most: a bigger one isn't read). A big picture goes as a smaller JPEG; a small one as it is.
+ static func file(_ url: URL) throws -> Attachment {
+ let scoped = url.startAccessingSecurityScopedResource()
+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }
+ let most = 25 * 1024 * 1024
+ if let n = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, n > most { throw Refusal.tooBig }
+ guard let d = try? Data(contentsOf: url) else { throw Refusal.unreadable }
+ guard d.count <= most else { throw Refusal.tooBig }
+ let t = UTType(filenameExtension: url.pathExtension)
+ if t?.conforms(to: .image) == true, let img = UIImage(data: d) {
+ if d.count > 4 * 1024 * 1024, let a = photo(img, name: url.deletingPathExtension().lastPathComponent + ".jpg") { return a }
+ return Attachment(name: url.lastPathComponent, type: t?.preferredMIMEType ?? "image/png", data: d,
+ preview: img.preparingThumbnail(of: CGSize(width: 192, height: 192)))
+ }
+ return Attachment(name: url.lastPathComponent, type: t?.preferredMIMEType ?? "application/octet-stream", data: d, preview: nil)
+ }
+}
+
+/// The camera, to take a photo for the next message.
+struct CameraPicker: UIViewControllerRepresentable {
+ let done: (UIImage) -> Void
+ @Environment(\.dismiss) private var dismiss
+
+ func makeUIViewController(context: Context) -> UIImagePickerController {
+ let p = UIImagePickerController()
+ p.sourceType = .camera
+ p.delegate = context.coordinator
+ return p
+ }
+ func updateUIViewController(_ vc: UIImagePickerController, context: Context) {}
+ func makeCoordinator() -> Coordinator { Coordinator(self) }
+
+ final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
+ let parent: CameraPicker
+ init(_ p: CameraPicker) { parent = p }
+ func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
+ if let img = info[.originalImage] as? UIImage { parent.done(img) }
+ parent.dismiss()
+ }
+ func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { parent.dismiss() }
+ }
+}
+
+/// The voice while it listens: bars that move with how loud you are.
+struct Waveform: View {
+ let level: Double
+ @State private var history: [Double] = Array(repeating: 0.05, count: 28)
+
+ var body: some View {
+ HStack(alignment: .center, spacing: 3) {
+ ForEach(history.indices, id: \.self) { i in
+ Capsule().fill(Color.white.opacity(0.4 + 0.6 * Double(i) / Double(history.count)))
+ .frame(width: 3, height: max(3, history[i] * 22))
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .onChange(of: level) { _, v in history.removeFirst(); history.append(max(0.06, v)) }
+ }
+}
diff --git a/app/ChumsPhone/Design.swift b/app/ChumsPhone/Design.swift
new file mode 100644
index 0000000..0a2d338
--- /dev/null
+++ b/app/ChumsPhone/Design.swift
@@ -0,0 +1,94 @@
+import SwiftUI
+
+// The iPhone app's few constants, in one place: sizes, the motions, the inks, a pressed state, the chat's edge fades
+// and the switch. Every screen takes its numbers from here, so a change is made once.
+
+/// Sizes, in points.
+enum M {
+ static let margin: CGFloat = 16 // the screen's side margin
+ static let target: CGFloat = 44 // the smallest thing a finger has to hit
+ static let tile: CGFloat = 24 // a glass tile's corner
+ static let bubble: CGFloat = 18 // a message's corner
+}
+
+/// The motions. Springs for things that move with a finger or between places; one ease for bars and scrims.
+enum Move {
+ static let place = Animation.spring(response: 0.55, dampingFraction: 0.84) // the character between its places
+ static let panel = Animation.spring(response: 0.38, dampingFraction: 0.86) // the agents' panel
+ static let snap = Animation.spring(response: 0.30, dampingFraction: 0.78) // controls changing under the thumb
+ static let settle = Animation.spring(response: 0.50, dampingFraction: 1.00) // text and layout: never bounces
+ static let lift = Animation.spring(response: 0.32, dampingFraction: 0.72) // a row picked up
+ static let fade = Animation.easeOut(duration: 0.20) // bars, scrims
+
+ /// The same motion, or a plain fade when Reduce Motion is on.
+ static func or(_ a: Animation, reduced: Bool) -> Animation { reduced ? .easeInOut(duration: 0.2) : a }
+}
+
+/// The inks: white and grays, amber (needs you) and red (stuck) are the only colours.
+enum Ink {
+ static let text = Color.white
+ static let quiet = Color(white: 0.6) // secondary words, readable at small sizes
+ static let ghost = Color(white: 0.42) // placeholders
+ static let you = Color(white: 0.2) // your messages
+ static let agent = Color(white: 0.11) // the agent's
+ static let panel = Color(white: 0.065) // the agents' panel
+}
+
+/// Pressed: a little smaller and dimmer, at once.
+struct Pressable: ButtonStyle {
+ func makeBody(configuration c: Configuration) -> some View {
+ c.label
+ .scaleEffect(c.isPressed ? 0.97 : 1)
+ .opacity(c.isPressed ? 0.75 : 1)
+ .animation(Move.snap, value: c.isPressed)
+ }
+}
+
+/// A mask that thins content out toward the top and bottom edges on a smoothstep curve (no visible start or end).
+/// Each edge has a bar over it (`top`, `bottom` points): content is gone `depth` of the way under the bar and whole
+/// again `reach` points past it, where it rests.
+struct EdgeFade: View {
+ let top: CGFloat
+ let bottom: CGFloat
+ var topReach: CGFloat = 30, topDepth: CGFloat = 0.25 // gone before the name under the character
+ var bottomReach: CGFloat = 14, bottomDepth: CGFloat = 0.6 // gone by the middle of the box
+
+ private static let stops: [Gradient.Stop] = stride(from: 0.0, through: 1.0, by: 0.0625).map { t in
+ .init(color: .black.opacity(t * t * (3 - 2 * t)), location: t)
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ Color.clear.frame(height: max(0, top * (1 - topDepth)))
+ LinearGradient(stops: Self.stops, startPoint: .top, endPoint: .bottom).frame(height: top * topDepth + topReach)
+ Color.black
+ LinearGradient(stops: Self.stops, startPoint: .bottom, endPoint: .top).frame(height: bottom * bottomDepth + bottomReach)
+ Color.clear.frame(height: max(0, bottom * (1 - bottomDepth)))
+ }
+ }
+}
+
+/// The switch, in the app's inks: on, a white track with a black knob; off, a gray track with a white knob.
+struct InkToggle: ToggleStyle {
+ func makeBody(configuration c: Configuration) -> some View {
+ Button {
+ withAnimation(Move.snap) { c.isOn.toggle() }
+ Haptics.play(.click)
+ } label: {
+ HStack {
+ c.label
+ Spacer(minLength: 12)
+ Capsule().fill(c.isOn ? Color.white : Color(white: 0.24))
+ .frame(width: 51, height: 31)
+ .overlay(alignment: c.isOn ? .trailing : .leading) {
+ Circle().fill(c.isOn ? Color.black : Color.white).padding(3)
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityElement(children: .combine)
+ .accessibilityAddTraits(.isToggle)
+ .accessibilityValue(c.isOn ? "On" : "Off")
+ }
+}
diff --git a/app/ChumsPhone/HomeView.swift b/app/ChumsPhone/HomeView.swift
new file mode 100644
index 0000000..9c54a4b
--- /dev/null
+++ b/app/ChumsPhone/HomeView.swift
@@ -0,0 +1,576 @@
+import SwiftUI
+import WidgetKit
+
+/// The one screen, for the agent you talk to. Before you've said anything to it, it stands in the middle in a window
+/// the shape of the watch's screen (the same character, touches and crown as on the watch). Once there's a
+/// conversation, it is the conversation's last row, unframed, at the left: its newest line arrives right above it, what
+/// it's doing plays out beside it (StateLane), and it scrolls with the rest. A tap on it brings it in front. At the top, only its name
+/// (a tap opens its card), the agents' button (a panel from the left, or a swipe from the edge) and the app's settings.
+/// At the bottom: type, tap or hold the microphone and talk, or add photos and files.
+struct HomeView: View {
+ let hub: HubClient
+ @State private var model: ScreenModel
+ @AppStorage("agent") private var agent = Agents.fallback
+ @State private var draft = ""
+ @FocusState private var typing: Bool
+ @State private var sheet: AgentInfo?
+ @State private var appSettings = false
+ @State private var viewing: Artifact?
+ @State private var attachments: [Attachment] = []
+ @State private var sending = false
+ @State private var attaching = false
+ @State private var boxHeight = 70.0 // the box at the bottom, which the conversation runs under
+ @AppStorage("agentOrder") private var order = "" // the agents' order in the panel, if you changed it
+ @State private var front = false // the character brought in front of the conversation
+ @State private var sidecar = false // the agents' panel
+ @GestureState(resetTransaction: Transaction(animation: .spring(response: 0.38, dampingFraction: 0.86)))
+ private var sideDrag: CGFloat = 0 // the open panel, dragged
+ @State private var edgeDrag: CGFloat = 0 // the panel coming in from the screen's left edge
+ @State private var handsFree = false // opened from a widget, the Control or Siri: listening, no finger down
+ @State private var pendingLink: PhoneLink?
+ @State private var prepared = false
+ @State private var lastWidgetReload = Date.distantPast
+ @Namespace private var names
+ @State private var notice: String? // what just went wrong, as the conversation's last note
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.scenePhase) private var phase
+
+ private var move: Animation { Move.or(Move.place, reduced: reduceMotion) }
+ private var side: Animation { Move.or(Move.panel, reduced: reduceMotion) }
+ private static let dock = CGSize(width: 100, height: 78) // the character at the bottom of the conversation
+
+ init(hub: HubClient) {
+ self.hub = hub
+ let m = ScreenModel(hub: hub)
+ m.rig.chrome = false // the faces, status and approval card are the iPhone's own, around it
+ _model = State(initialValue: m)
+ }
+
+ /// Every agent: in your order if you changed it, else the characters' order; any others after.
+ private var agents: [AgentInfo] {
+ let all = hub.state?.agents ?? Agents.known
+ let ids = order.split(separator: ",").map(String.init) + SoulView.looks
+ var seen = Set<String>()
+ let first = ids.compactMap { id in seen.insert(id).inserted ? all.first { $0.id == id } : nil }
+ return first + all.filter { !seen.contains($0.id) }
+ }
+ private var me: AgentInfo { model.controller.info(agent) }
+ private var approval: Approval? { hub.state?.approvals.first { $0.session == agent } ?? demoApproval }
+ @State private var demoApproval: Approval? // debug pictures only (-approval YES)
+ /// The others, for the agents button: the ones that need you first, then the ones at work.
+ private var others: [AgentInfo] {
+ func rank(_ a: AgentInfo) -> Int { a.needs ? 0 : a.status == "blocked" ? 1 : a.status == "working" ? 2 : a.status == "offline" ? 4 : 3 }
+ return agents.filter { $0.id != agent }.enumerated()
+ .sorted { (rank($0.element), $0.offset) < (rank($1.element), $1.offset) }.map(\.element)
+ }
+ /// Each agent's last line in its conversation (yours too, as "You: …"), for the agents' panel.
+ private var lastLines: [String: String] {
+ var d: [String: String] = [:]
+ for l in hub.state?.spoken ?? [] where l.kind != "verdict" {
+ d[l.owner] = l.kind == "echo" ? "You: " + l.text.replacingOccurrences(of: "“", with: "").replacingOccurrences(of: "”", with: "") : l.text
+ }
+ return d
+ }
+ private var place: StagePlace {
+ if front { return .front }
+ if hub.state == nil { return .dock } // before the hub has answered: no guess, no jump
+ if model.conversation.isEmpty && !typing { return .middle }
+ return .dock
+ }
+ /// It's working on what you asked (or tidying its memory).
+ private var working: Bool { me.status == "working" || me.status == "compacting" || demoWorking }
+ @State private var demoWorking = false // debug pictures only (-working YES)
+ @State private var sawItStart: Date? // when this screen saw it start working
+ @State private var firstStep: String? // the last step it had taken before that (not shown again)
+ /// Since when it has been on what you asked: your last message to it, if it hasn't answered it yet; else when this
+ /// screen saw it start.
+ private var workingSince: Date? {
+ guard working else { return nil }
+ let mine = (hub.state?.spoken ?? []).filter { $0.owner == agent }
+ guard let i = mine.lastIndex(where: { $0.kind == "echo" }), let at = mine[i].at,
+ !mine[(i + 1)...].contains(where: { ["done", "question", "blocked"].contains($0.kind) }) else {
+ // no message of yours it's answering (it's older than the hub's window, or not yours): its first step since
+ // it last stopped
+ let all = (hub.state?.tools ?? []).filter { $0.session == agent }
+ let current = all.lastIndex { $0.type == "stop" }.map { all[($0 + 1)...] } ?? all[...]
+ let first = current.compactMap(\.at).min().map { Date(timeIntervalSince1970: $0 / 1000) }
+ return [first, sawItStart].compactMap { $0 }.min()
+ }
+ return Date(timeIntervalSince1970: at / 1000)
+ }
+ /// Its steps on what you asked so far, newest last (its tool calls: "Read hub.mjs", "Bash npm test").
+ private var steps: [ToolInfo] {
+ let mine = (hub.state?.tools ?? []).filter { $0.session == agent && $0.type != "stop" }
+ guard let f = firstStep, let i = mine.lastIndex(where: { $0.id == f }) else { return mine }
+ return Array(mine[(i + 1)...])
+ }
+ /// What the lane beside it says now: the action, and exactly what on.
+ private var lane: StateLane.Words? {
+ if hub.state == nil { return patient ? nil : .init(main: "Can't reach your Mac", tone: .amber, detail: "Trying again") }
+ if !reachable { return .init(main: "Can't reach your Mac", tone: .amber, detail: "Trying again") }
+ if model.listening { return .init(main: "Listening", detail: "↑ sends it to \(me.name), × throws it away") }
+ if sending { return .init(main: attachments.contains { $0.preview != nil } ? "Sending your photo" : "Sending your file", tone: .live, detail: "To your Mac") }
+ if model.controller.talk == .sending { return .init(main: "Sending what you said", tone: .live, detail: "Your Mac turns it into text") }
+ if model.controller.talk == .speaking { return .init(main: "Speaking", detail: "Tap to stop") }
+ if let a = approval { return .init(main: "Needs you", tone: .amber, detail: Self.asks(a).text, code: Self.asks(a).code) }
+ if me.needs { return .init(main: "Needs you", tone: .amber, detail: "It asked you a question") }
+ if working {
+ let since = workingSince ?? Date()
+ if me.status == "compacting" { return .init(main: "Tidying its memory", tone: .live, detail: "Making its conversation shorter", since: since) }
+ let s = demoWorking ? [ToolInfo(id: "d1", session: agent, type: "read", text: "Read hub.mjs", ok: true),
+ ToolInfo(id: "d2", session: agent, type: "test", text: "Bash npm test", ok: nil)] : steps
+ if let t = s.last {
+ let w = StateLane.step(t.text, test: t.type == "test")
+ return .init(main: w.main, tone: .live, detail: w.detail, code: w.code, since: since)
+ }
+ if answered { return .init(main: "Finishing up", tone: .live, detail: "Writing the rest on your Mac", since: since) }
+ return .init(main: "Thinking", tone: .live, detail: askedWithFiles > 0 ? "About your message and \(askedWithFiles == 1 ? "photo" : "files")" : "About your message", since: since)
+ }
+ switch me.status {
+ case "offline": return .init(main: "Not running on your Mac", tone: .quiet)
+ case "blocked": return .init(main: "Stuck", tone: .red, detail: "It said why above")
+ case "limited": return .init(main: "Rate limited", tone: .amber, detail: "It goes on by itself")
+ default: return nil // idle: the character alone
+ }
+ }
+ /// Its lines since your last message to it.
+ private var sinceAsked: ArraySlice<Spoken> {
+ let mine = (hub.state?.spoken ?? []).filter { $0.owner == agent }
+ guard let i = mine.lastIndex(where: { $0.kind == "echo" }) else { return [] }
+ return mine[i...]
+ }
+ /// It has already answered what you asked (it's still at work: writing on the Mac).
+ private var answered: Bool { sinceAsked.dropFirst().contains { ["done", "question", "blocked"].contains($0.kind) } }
+ /// What you sent with your last message: 0, or 1 for a photo, 2 for files.
+ private var askedWithFiles: Int {
+ guard let echo = sinceAsked.first, echo.artifact != nil else { return 0 }
+ return echo.artifact?.kind == "image" ? 1 : 2
+ }
+ /// What an approval asks, in words: "Asks to read photo-1.jpg", "Asks to run a command".
+ static func asks(_ a: Approval) -> (text: String, code: Bool) {
+ let input = (try? JSONSerialization.jsonObject(with: Data(a.preview.utf8))) as? [String: Any] ?? [:]
+ let file = (input["file_path"] as? String ?? input["path"] as? String).map { f -> String in
+ let base = (f as NSString).lastPathComponent
+ return StateLane.sentName(base) ?? base
+ }
+ switch a.tool {
+ case "Read": return ("Asks to read \(file ?? "a file")", false)
+ case "Edit", "MultiEdit": return ("Asks to edit \(file ?? "a file")", false)
+ case "Write": return ("Asks to write \(file ?? "a file")", false)
+ case "Bash": return ("Asks to run a command", false) // the card under it shows which
+ case "WebFetch": return ("Asks to open \(URL(string: input["url"] as? String ?? "")?.host() ?? "a page")", false)
+ default: return ("Asks to use \(a.tool)", false)
+ }
+ }
+ /// For the first few seconds the hub hasn't answered yet, it isn't "can't reach" — just not yet.
+ @State private var patient = true
+ @State private var settled = false // the first answer from the hub has been laid out
+ private var reachable: Bool { hub.connected || patient }
+
+ var body: some View {
+ GeometryReader { geo in
+ let sideW = min(330, geo.size.width * 0.84)
+ let raw = (sidecar ? 1 : 0) + (sideDrag + edgeDrag) / sideW // how far the agents' panel is out
+ let p = min(1, max(0, raw))
+ let over = max(0, raw - 1) * sideW * 0.18 // pulled past open: it gives a little
+ ZStack(alignment: .topLeading) {
+ screen(geo)
+ .scaleEffect(1 - 0.06 * p, anchor: .trailing)
+ .overlay {
+ Color.black.opacity(0.6 * p).ignoresSafeArea()
+ .allowsHitTesting(p > 0.01)
+ .onTapGesture { withAnimation(side) { sidecar = false } }
+ }
+ Sidecar(agents: agents, active: agent, connected: reachable, last: lastLines) { id in
+ pick(id)
+ withAnimation(side) { sidecar = false }
+ } settings: { a in sheet = a } reorder: { ids in order = ids.joined(separator: ",") }
+ .frame(width: sideW)
+ .offset(x: -sideW * (1 - p) + over - 24 * max(0, 1 - p * 20)) // its shadow off screen when shut
+ .shadow(color: .black.opacity(0.5 * p), radius: 24, x: 8)
+ .gesture(sideGesture(sideW))
+ }
+ // a swipe in from the left edge opens the agents (the system's edge pan: taps and scrolls there pass through)
+ .gesture(EdgePan(enabled: !sidecar && place != .front) { edgeDrag = max(0, $0) } ended: { _, end in
+ withAnimation(side) { edgeDrag = 0; sidecar = end > sideW * 0.5 }
+ })
+ }
+ .background(Color.black.ignoresSafeArea())
+ // a soft knock when the character comes in front or goes back (not when the keyboard moves it)
+ .sensoryFeedback(.impact(flexibility: .soft, intensity: 0.7), trigger: front)
+ .sensoryFeedback(.selection, trigger: sidecar)
+ // a soft tap when the agent you're looking at answers
+ .sensoryFeedback(.impact(flexibility: .soft, intensity: 0.5), trigger: model.conversation.count) { _, _ in
+ model.conversation.last?.who == .chums
+ }
+ .task {
+ guard !prepared else { return }
+ prepared = true
+ Task { try? await Task.sleep(for: .seconds(4)); patient = false }
+ model.onNotice = { text in
+ withAnimation(Move.fade) { notice = text }
+ let life = text == ScreenModel.micRefused ? 15.0 : 6.0 // time to reach Settings
+ Task { try? await Task.sleep(for: .seconds(life)); if notice == text { withAnimation(Move.fade) { notice = nil } } }
+ }
+ await model.prepare()
+ model.setAgent(agent)
+ if let l = pendingLink { pendingLink = nil; follow(l) }
+ #if DEBUG
+ await WidgetShots.run()
+ let args = UserDefaults.standard
+ if let id = args.string(forKey: "sheet") { sheet = agents.first { $0.id == id } } // -sheet <agent>
+ if args.bool(forKey: "agents") { sidecar = true } // -agents YES
+ if args.bool(forKey: "front") { front = true } // -front YES
+ if args.bool(forKey: "settings") { appSettings = true } // -settings YES
+ if let id = args.string(forKey: "viewer") { // -viewer <artifact id>
+ viewing = Artifact(id: id, kind: "image", title: "Test picture", from: nil, w: 1200, h: 1600)
+ }
+ if args.bool(forKey: "approval") { // -approval YES
+ demoApproval = Approval(requestId: "demo", session: agent, tool: "Bash", description: "Delete the build folder",
+ preview: "{\"command\":\"rm -rf ~/Developer/chums/app/build\"}", summary: "rm -rf ~/Developer/chums/app/build")
+ }
+ if args.bool(forKey: "attach") { // -attach YES
+ let r = UIGraphicsImageRenderer(size: CGSize(width: 600, height: 800))
+ for (i, c) in [UIColor.systemOrange, .systemPink].enumerated() {
+ let img = r.image { ctx in c.setFill(); ctx.fill(CGRect(x: 0, y: 0, width: 600, height: 800)) }
+ if let a = Attachment.photo(img, name: "photo-\(i + 1).jpg") { attachments.append(a) }
+ }
+ attachments.append(Attachment(name: "notes.pdf", type: "application/pdf", data: Data([1]), preview: nil))
+ }
+ if args.bool(forKey: "listen") { follow(.talk(nil)) } // -listen YES (with -quiet YES)
+ if args.bool(forKey: "working") { demoWorking = true } // -working YES
+ // -viewerJSON <artifact JSON, base64> opens it, as a tap on it would; -readmeDemo <artifact JSON, base64>
+ // puts it in a made-up conversation (the README's pictures)
+ let artifact = { (key: String) in args.string(forKey: key).flatMap { Data(base64Encoded: $0) }
+ .flatMap { try? JSONDecoder().decode(Artifact.self, from: $0) } }
+ if let a = artifact("viewerJSON") { viewing = a }
+ if args.string(forKey: "readmeDemo") != nil { model.controller.readmeDemo(agent, chart: artifact("readmeDemo")) }
+ if let n = args.string(forKey: "demoConversation").flatMap(Int.init) { // -demoConversation 24
+ model.controller.demoConversation(n, agents: agents.map(\.id))
+ }
+ if args.bool(forKey: "crownDemo") { await model.crownDemo() } // -crownDemo YES
+ // -say "…" sends that as if typed, once the hub has answered
+ if let text = args.string(forKey: "say") {
+ for _ in 0..<40 where hub.state == nil { try? await Task.sleep(for: .milliseconds(250)) }
+ _ = await model.send(text: text)
+ }
+ #endif
+ }
+ .onChange(of: agent, initial: true) { _, id in
+ model.setAgent(id)
+ // the widgets show the agent you're on: the hub hears it first, then they look again
+ Task { await hub.focus(id); WidgetCenter.shared.reloadAllTimelines() }
+ }
+ .onChange(of: phase) { _, p in
+ if p == .background { WidgetCenter.shared.reloadAllTimelines() } // back on the Home Screen: up to date
+ }
+ .onChange(of: me.character, initial: true) { _, c in
+ if let k = CharacterKind(id: c) { model.rig.character = k }
+ }
+ .onChange(of: hub.state != nil) { _, has in
+ if has { Task { try? await Task.sleep(for: .milliseconds(400)); settled = true } }
+ }
+ .onChange(of: hub.state?.rev) { _, _ in
+ // the widgets follow what the app sees, at most every 20 s
+ if Date().timeIntervalSince(lastWidgetReload) > 20 { lastWidgetReload = Date(); WidgetCenter.shared.reloadAllTimelines() }
+ }
+ .onChange(of: working, initial: true) { was, on in
+ sawItStart = on ? Date() : nil
+ // it starts on something new here: its steps from before aren't this work's (at launch, or on another
+ // agent, they may be: they show)
+ firstStep = on && !was ? (hub.state?.tools ?? []).last(where: { $0.session == agent && $0.type != "stop" })?.id : nil
+ }
+ .onChange(of: agent) { firstStep = nil; sawItStart = working ? Date() : nil }
+ .onChange(of: typing) { _, on in
+ guard on else { return }
+ model.hush(); hub.nudge() // typing while it's out of reach: look again now
+ withAnimation(move) { front = false }
+ }
+ .accessibilityAction(.magicTap) { follow(.talk(nil)) } // two-finger double tap: talk, hands-free
+ .onOpenURL { url in
+ guard let l = PhoneLink(url) else { return }
+ if prepared { follow(l) } else { pendingLink = l }
+ }
+ .sheet(item: $sheet) { a in AgentSheet(agent: a, hub: hub) }
+ .sheet(isPresented: $appSettings) { AppSettings(hub: hub, character: me.character) }
+ .sheet(item: $viewing) { a in ArtifactSheet(artifact: a, character: me.character) }
+ }
+
+ // MARK: the screen
+
+ /// The conversation and its controls, with the character over them in its place.
+ private func screen(_ geo: GeometryProxy) -> some View {
+ let w = geo.size.width, h = geo.size.height
+ let r = stageRect(w, h)
+ return ZStack(alignment: .top) {
+ // the conversation fills the screen and runs under the bar at the top and the box at the bottom, fading out
+ // under each over most of its height
+ ZStack(alignment: .bottom) {
+ // a tap anywhere here puts the keyboard away
+ Color.black.contentShape(Rectangle()).onTapGesture { typing = false }
+ if place == .dock || front {
+ Conversation(lines: model.conversation, name: me.name, top: Self.barHeight,
+ bottom: boxHeight, notice: notice, hush: { model.hush() },
+ askFirst: (me.runtime ?? "claude") == "claude" && me.permission != "default" ? { askFirst() } : nil,
+ open: { viewing = $0 }) { nowRow }
+ .id(agent) // each agent's conversation opens on its newest line
+ .simultaneousGesture(TapGesture().onEnded { typing = false })
+ .transition(.opacity)
+ }
+ if attaching {
+ // a tap or a scroll behind the menu closes it, the moment the finger lands
+ Color.black.opacity(0.45).ignoresSafeArea()
+ .gesture(DragGesture(minimumDistance: 0).onChanged { _ in
+ if attaching { withAnimation(Move.snap) { attaching = false } }
+ })
+ .transition(.opacity)
+ }
+ VStack(spacing: 0) {
+ if let a = approval {
+ ApprovalCard(approval: a, name: me.name) { model.decide(a.requestId, allow: $0) }
+ .padding(.bottom, 10)
+ .transition(.move(edge: .bottom).combined(with: .opacity))
+ }
+ Composer(name: me.name, draft: $draft, attachments: $attachments, typing: $typing, model: model,
+ handsFree: $handsFree, attaching: $attaching, sending: sending) { text in send(text) }
+ }
+ .padding(.horizontal, 16).padding(.bottom, 8)
+ .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { boxHeight = $0 }
+ .opacity(front ? 0 : 1)
+ }
+ .blur(radius: front && !reduceMotion ? 16 : 0)
+ .overlay {
+ if front {
+ Color.black.opacity(reduceMotion ? 0.7 : 0.55).ignoresSafeArea()
+ .onTapGesture { withAnimation(move) { front = false } }
+ .gesture(DragGesture(minimumDistance: 20).onEnded { v in
+ if v.translation.height > 60 { withAnimation(move) { front = false } }
+ })
+ .transition(.opacity)
+ }
+ }
+ .overlay(alignment: .top) { topBar(w) }
+
+ // in the middle (no conversation yet) or in front: over everything. At the bottom it's the conversation's
+ // last row (nowRow), and the same character flies between the two.
+ if place != .dock {
+ stage(small: false)
+ .frame(width: r.width, height: r.height)
+ .matched("stage", in: names, if: !reduceMotion) // Reduce Motion: it fades instead of flying
+ .position(x: r.midX, y: r.midY)
+ }
+
+ if place == .middle || place == .front { caption(below: r, width: w) }
+ }
+ .animation(settled ? move : nil, value: place)
+ .animation(Move.snap, value: approval?.requestId)
+ .animation(Move.settle, value: model.listening)
+ }
+
+ /// The conversation's last row: the agent, small and unframed, and what it's doing beside it. It scrolls with the
+ /// conversation; in front, its place stays empty while it's out.
+ private var nowRow: some View {
+ HStack(spacing: 4) {
+ ZStack {
+ if place == .dock {
+ stage(small: true)
+ .matched("stage", in: names, if: !reduceMotion)
+ .modifier(VoiceScale(model: model, on: model.listening, base: 1.06, gain: 0.06)) // grows with your voice
+ }
+ }
+ .frame(width: Self.dock.width, height: Self.dock.height)
+ .padding(.leading, -12) // its edges fade out: the character itself lines up
+ StateLane(words: place == .dock ? lane : nil) { if model.controller.talk == .speaking { model.hush() } }
+ .frame(height: Self.dock.height)
+ }
+ .padding(.top, 8)
+ }
+
+ private func stage(small: Bool) -> some View {
+ CharacterStage(model: model, agent: me, small: small,
+ paused: sheet != nil || viewing != nil || appSettings || sidecar) {
+ withAnimation(move) { front = true }
+ } settings: { sheet = me }
+ }
+
+ /// The agents button, the agent's name (a tap opens its card) and the app's settings. Its state is at the bottom,
+ /// beside it.
+ private func topBar(_ w: CGFloat) -> some View {
+ ZStack {
+ HStack {
+ AgentsButton(others: others) { withAnimation(side) { sidecar = true } }
+ Spacer()
+ DotsButton(label: "Settings") { appSettings = true }
+ }
+ .padding(.leading, 14).padding(.trailing, 6)
+ if place == .dock {
+ Button { sheet = me } label: {
+ HStack(spacing: 4) {
+ Text(me.name).font(.headline).foregroundStyle(.white)
+ .lineLimit(1).minimumScaleFactor(0.85)
+ .matchedGeometryEffect(id: "name", in: names)
+ Image(systemName: "chevron.right").font(.caption.weight(.bold)).foregroundStyle(Ink.ghost)
+ }
+ .frame(minHeight: M.target).padding(.horizontal, 10).contentShape(Rectangle())
+ }
+ .frame(maxWidth: max(120, w - 2 * 96)) // clear of the faces and the dots
+ .buttonStyle(Pressable())
+ .dynamicTypeSize(...DynamicTypeSize.xxLarge) // the bar's height is fixed
+ .accessibilityIdentifier("name-button")
+ .accessibilityHint("Opens \(me.name)'s card")
+ .transition(.opacity)
+ }
+ }
+ .padding(.top, 4)
+ .frame(height: Self.barHeight, alignment: .top)
+ }
+ private static let barHeight = 52.0 // the bar at the top: the buttons and the name
+
+ /// Under the big character: its name and what it's doing (and, before you've talked to it, how).
+ private func caption(below r: CGRect, width w: CGFloat) -> some View {
+ let talk = model.listening || model.controller.talk != .none // the box listens, sends or it speaks
+ return
+ VStack(spacing: 6) {
+ HStack(spacing: 2) {
+ if place == .front { Color.clear.frame(width: 44, height: 1) } // keeps the name centred
+ Text(me.name).font(.largeTitle.weight(.bold)).foregroundStyle(.white)
+ .lineLimit(1).minimumScaleFactor(0.7)
+ .matchedGeometryEffect(id: "name", in: names)
+ if place == .front {
+ DotsButton(label: "\(me.name)'s settings") { sheet = me } // its card, from right here
+ .transition(.opacity)
+ }
+ }
+ Text(hub.state == nil ? " " : talk ? lane?.main ?? " " : AgentWords.state(me, connected: reachable))
+ .font(.subheadline.weight(.medium))
+ .foregroundStyle(talk ? .white : AgentWords.color(me, connected: reachable))
+ .contentTransition(.opacity)
+ .matchedGeometryEffect(id: "status", in: names)
+ if place == .middle && !talk {
+ Text("Hold the screen to talk to \(me.name), or type.")
+ .font(.footnote).foregroundStyle(Color(white: 0.55)).padding(.top, 6)
+ if let notice { NoticeLine(text: notice).transition(.opacity) }
+ }
+ }
+ .multilineTextAlignment(.center)
+ .frame(width: min(w - 2 * M.margin, 380))
+ .position(x: r.midX, y: r.maxY + (place == .middle ? 70 : 54))
+ .allowsHitTesting(place == .front || notice == ScreenModel.micRefused) // its dots; or the way to Settings
+ .transition(.opacity.combined(with: .scale(scale: 0.96)))
+ }
+
+ /// Where the character is drawn, in this screen's points.
+ private func stageRect(_ w: CGFloat, _ h: CGFloat) -> CGRect {
+ let aspect = DESIGN.width / DESIGN.height
+ switch place {
+ case .dock:
+ // (drawn in the conversation's last row; this is where that row is when the conversation is at its end)
+ return CGRect(x: 2, y: h - boxHeight - 2 - Self.dock.height, width: Self.dock.width, height: Self.dock.height)
+ case .middle:
+ let top = 70.0, bottom = h - boxHeight - 130 // the box below, the caption under it
+ let wh = min(h < 700 ? 280 : 340, max(180, bottom - top)), ww = wh * aspect
+ return CGRect(x: (w - ww) / 2, y: top + max(0, (bottom - top - wh) * 0.45), width: ww, height: wh)
+ case .front:
+ let wh = min(h < 700 ? 320 : 400, h * 0.5), ww = wh * aspect
+ return CGRect(x: (w - ww) / 2, y: max(70, h * 0.4 - wh / 2), width: ww, height: wh)
+ }
+ }
+
+ private func sideGesture(_ width: CGFloat) -> some Gesture {
+ DragGesture(minimumDistance: 12)
+ .updating($sideDrag) { v, s, _ in s = v.translation.width }
+ .onEnded { v in
+ let p = (sidecar ? 1 : 0) + v.predictedEndTranslation.width / width
+ withAnimation(side) { sidecar = p > 0.5 }
+ }
+ }
+
+ /// Sends what's typed, with the photos and files above the box: they go to the Mac first, then the message names them.
+ private func send(_ text: String) {
+ let files = attachments
+ guard !files.isEmpty else {
+ Task { if await model.send(text: text) == nil, draft.isEmpty { draft = text } } // didn't go: your words come back
+ return
+ }
+ sending = true
+ Task {
+ var paths: [String] = []
+ for f in files { if let u = await hub.upload(f.data, name: f.name, type: f.type) { paths.append(u.path) } }
+ sending = false
+ guard !paths.isEmpty else { // nothing reached the Mac: try again
+ Haptics.play(.failure); if draft.isEmpty { draft = text }
+ withAnimation(Move.fade) { notice = hub.connected ? "Couldn't send the files. Try again." : "Can't reach your Mac." }
+ return
+ }
+ if await model.send(text: text, files: paths) == nil { if draft.isEmpty { draft = text }; return } // kept for again
+ withAnimation(.snappy) { attachments.removeAll { a in files.contains(a) } }
+ }
+ }
+
+ /// Under a refusal: this agent asks you from now on (Asks first); it restarts, and its conversation carries on.
+ private func askFirst() {
+ Haptics.play(.click)
+ let name = me.name
+ Task {
+ if let e = await hub.setPermission(agent, mode: "default") { model.onNotice?(e); Haptics.play(.failure) }
+ else { model.onNotice?("\(name) asks first now."); Haptics.play(.success) }
+ }
+ }
+
+ private func pick(_ id: String) {
+ guard id != agent else { return }
+ Haptics.play(.click)
+ withAnimation(move) { front = false }
+ withAnimation(Move.fade) { agent = id } // its conversation replaces the other's: no morph
+ }
+
+ private func follow(_ l: PhoneLink) {
+ switch l {
+ case .agent(let id): pick(id)
+ case .talk(let id):
+ if let id { agent = id; model.setAgent(id) }
+ typing = false
+ model.micDown()
+ if model.listening { handsFree = true }
+ }
+ }
+}
+
+extension View {
+ /// matchedGeometryEffect, or nothing (Reduce Motion: things fade where they are instead of flying).
+ @ViewBuilder func matched(_ id: String, in ns: Namespace.ID, if on: Bool) -> some View {
+ if on { matchedGeometryEffect(id: id, in: ns) } else { self }
+ }
+}
+
+/// The system's pan from the screen's left edge, for SwiftUI: it only starts on a horizontal drag that begins at the
+/// edge, and other pans (the conversation's scroll) wait for it to fail, so a tap or a vertical scroll there goes
+/// through. `changed` gets the distance, `ended` the distance and where a flick would have taken it.
+struct EdgePan: UIGestureRecognizerRepresentable {
+ var enabled: Bool
+ var changed: (CGFloat) -> Void
+ var ended: (CGFloat, CGFloat) -> Void
+
+ func makeCoordinator(converter: CoordinateSpaceConverter) -> Coordinator { Coordinator() }
+ func makeUIGestureRecognizer(context: Context) -> UIScreenEdgePanGestureRecognizer {
+ let g = UIScreenEdgePanGestureRecognizer()
+ g.edges = .left
+ g.delegate = context.coordinator
+ return g
+ }
+ func updateUIGestureRecognizer(_ g: UIScreenEdgePanGestureRecognizer, context: Context) { g.isEnabled = enabled }
+ func handleUIGestureRecognizerAction(_ g: UIScreenEdgePanGestureRecognizer, context: Context) {
+ let t = g.translation(in: g.view).x, v = g.velocity(in: g.view).x
+ switch g.state {
+ case .changed: changed(t)
+ case .ended, .cancelled, .failed: ended(t, t + v * 0.15)
+ default: break
+ }
+ }
+
+ final class Coordinator: NSObject, UIGestureRecognizerDelegate {
+ func gestureRecognizer(_ g: UIGestureRecognizer, shouldBeRequiredToFailBy other: UIGestureRecognizer) -> Bool {
+ other is UIPanGestureRecognizer && !(other is UIScreenEdgePanGestureRecognizer)
+ }
+ }
+}
diff --git a/app/ChumsPhone/Parts.swift b/app/ChumsPhone/Parts.swift
new file mode 100644
index 0000000..88de659
--- /dev/null
+++ b/app/ChumsPhone/Parts.swift
@@ -0,0 +1,509 @@
+import SwiftUI
+
+// The iPhone screen's parts. All black; the type is SF; color only where it means something (amber needs you, white
+// working, red stuck), as on the watch.
+
+/// What an agent is doing, in a word or two (its words are in the conversation), and its color: amber needs you, red
+/// stuck, gray otherwise.
+enum AgentWords {
+ static func state(_ a: AgentInfo, connected: Bool = true) -> String {
+ if !connected { return "Can't reach your Mac" }
+ if a.needs { return "Needs you" }
+ switch a.status {
+ case "offline": return "Not running on your Mac"
+ case "working": return "Working"
+ case "compacting": return "Tidying its memory"
+ case "limited": return "Rate limited"
+ case "blocked": return "Stuck"
+ default: return "Idle"
+ }
+ }
+ static func color(_ a: AgentInfo, connected: Bool = true) -> Color {
+ !connected || a.needs ? Pal.amber : a.status == "blocked" ? Pal.red : Ink.quiet
+ }
+}
+
+/// The agent's conversation, newest at the bottom: you on the right, it on the left, what it showed you as a picture,
+/// notes in the middle, and last of all `now` (the agent itself and what it's doing), which scrolls with the rest. It
+/// runs the height of the screen, under the bar at the top (`top` points) and the box at the bottom (`bottom` points):
+/// at rest the first and last rows sit clear of them; scrolled, they thin out on a curve as they pass under
+/// (EdgeFade). `notice` is something that just went wrong, as the last note.
+struct Conversation<Now: View>: View {
+ let lines: [ChatLine]
+ let name: String
+ var top: CGFloat = 0
+ var bottom: CGFloat = 0
+ var notice: String? = nil
+ var hush: () -> Void = {}
+ var askFirst: (() -> Void)? = nil // under a refusal: switch the agent to Asks first (nil: it does)
+ let open: (Artifact) -> Void
+ @ViewBuilder var now: () -> Now
+ @State private var phase: ScrollPhase = .idle
+ @State private var pinned = true // at the newest line: it stays there as lines come and the room changes
+
+ private struct Spot: Equatable { var top: Double; var fromBottom: Double; var room: Double }
+
+ var body: some View {
+ ScrollViewReader { proxy in
+ ScrollView {
+ // laid out whole (at most ~120 lines): scrolling to the end lands on it exactly, no estimated heights
+ VStack(spacing: 0) {
+ ForEach(Array(lines.enumerated()), id: \.element.id) { i, l in
+ // 4 pt between lines from the same side, 12 when the side changes
+ Bubble(line: l, name: name, open: open, hush: hush, askFirst: askFirst)
+ .padding(.top, i == 0 ? 0 : lines[i - 1].who == l.who ? 4 : 12)
+ .id(l.id)
+ .accessibilityIdentifier(i == lines.count - 1 ? "last-line" : "line")
+ }
+ if let notice {
+ NoticeLine(text: notice).frame(maxWidth: .infinity).padding(.top, 12).transition(.opacity)
+ }
+ now()
+ Color.clear.frame(height: 2).id("end")
+ }
+ .padding(.horizontal, M.margin - 2)
+ }
+ // room above and below as safe area (not content margins): short content then sits on the box, its end
+ // above it, instead of a margin too low
+ .safeAreaPadding(.top, top + 40)
+ .safeAreaPadding(.bottom, bottom + 16)
+ .mask { EdgeFade(top: top, bottom: bottom, topReach: 40, topDepth: 0) } // gone before it reaches the name
+ .defaultScrollAnchor(.bottom) // opens on the newest line; short, sits on the box
+ .scrollBounceBehavior(.basedOnSize, axes: .vertical) // all of it on screen: it doesn't move
+ .scrollDismissesKeyboard(.interactively)
+ .onScrollPhaseChange { _, p in phase = p }
+ .onScrollGeometryChange(for: Spot.self) { g in
+ Spot(top: g.contentOffset.y + g.contentInsets.top,
+ fromBottom: g.contentSize.height + g.contentInsets.bottom - g.contentOffset.y - g.containerSize.height,
+ room: g.containerSize.height)
+ } action: { old, s in
+ // pinned and at rest, it never drifts off the newest line (the box measured, lines arriving, the
+ // keyboard coming or going): put it back at once
+ if pinned && phase == .idle && s.fromBottom > 1 { proxy.scrollTo("end", anchor: .bottom); return }
+ if s.room != old.room { // an approval, the keyboard
+ if pinned { proxy.scrollTo("end", anchor: .bottom) }
+ return
+ }
+ // only your finger scrolling unpins it: not a scroll the app makes, and not a tap (a tap that puts the
+ // keyboard away lands while the room is still changing)
+ guard phase == .interacting || phase == .decelerating else { return }
+ pinned = s.fromBottom < 60
+ }
+ .onChange(of: lines.count) { old, _ in
+ // the conversation arriving opens on its newest line, at once; after that a new line shows unless
+ // you're reading further back (your own always shows)
+ if old == 0 { proxy.scrollTo("end", anchor: .bottom); return }
+ guard pinned || lines.last?.who == .you else { return }
+ pinned = true
+ withAnimation(Move.settle) { proxy.scrollTo("end", anchor: .bottom) }
+ }
+ .onChange(of: notice) { if pinned { withAnimation(Move.settle) { proxy.scrollTo("end", anchor: .bottom) } } }
+ // the box below (or the bar above) changed height: the newest line stays on it
+ .onChange(of: bottom) { if pinned { proxy.scrollTo("end", anchor: .bottom) } }
+ .onChange(of: top) { if pinned { proxy.scrollTo("end", anchor: .bottom) } }
+ // once the keyboard has finished coming or going, back on the newest line
+ .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardDidHideNotification)) { _ in
+ if pinned { withAnimation(Move.settle) { proxy.scrollTo("end", anchor: .bottom) } }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardDidShowNotification)) { _ in
+ if pinned { withAnimation(Move.settle) { proxy.scrollTo("end", anchor: .bottom) } }
+ }
+ }
+ }
+}
+
+/// Something that just went wrong, in amber, as the conversation's last note. A refused microphone has the way to
+/// Settings under it.
+struct NoticeLine: View {
+ let text: String
+ var body: some View {
+ VStack(spacing: 2) {
+ Text(text).font(.footnote.weight(.medium)).foregroundStyle(Pal.amber).multilineTextAlignment(.center)
+ if text == ScreenModel.micRefused {
+ Button("Open Settings") {
+ if let u = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(u) }
+ }
+ .font(.footnote.weight(.semibold)).foregroundStyle(.white)
+ .frame(minHeight: M.target).contentShape(Rectangle())
+ .buttonStyle(Pressable())
+ }
+ }
+ }
+}
+
+struct Bubble: View {
+ let line: ChatLine
+ var name = "" // the agent's, for VoiceOver ("Ray: …")
+ let open: (Artifact) -> Void
+ var hush: () -> Void = {}
+ var askFirst: (() -> Void)? = nil
+ @AppStorage("voice") private var speak = true
+
+ var body: some View {
+ switch line.who {
+ case .you:
+ VStack(alignment: .trailing, spacing: 6) {
+ if line.artifact.map({ $0.title != line.text }) ?? true {
+ HStack {
+ Spacer(minLength: 56)
+ text(line.text, on: Ink.you)
+ }
+ }
+ if let a = line.artifact { PhotoBubble(artifact: a) { open(a) } }
+ }
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("You: \(line.text)")
+ case .chums:
+ VStack(alignment: .leading, spacing: 6) {
+ if line.artifact.map({ $0.title != line.text }) ?? true {
+ HStack {
+ text(line.text, on: Ink.agent)
+ .accessibilityLabel(name.isEmpty ? line.text : "\(name): \(line.text)")
+ Spacer(minLength: 56)
+ }
+ }
+ if let a = line.artifact { ArtifactCard(artifact: a) { open(a) } }
+ }
+ .accessibilityElement(children: .combine)
+ case .note:
+ VStack(spacing: 2) {
+ Text(line.text).font(.caption.weight(.medium)).foregroundStyle(Color(white: 0.55))
+ .multilineTextAlignment(.center)
+ // auto mode refused it without asking: from now on, it can ask you instead
+ if line.refused, let askFirst {
+ Button("Ask first instead", action: askFirst)
+ .font(.caption.weight(.semibold)).foregroundStyle(.white)
+ .frame(minHeight: M.target).contentShape(Rectangle())
+ .buttonStyle(Pressable())
+ .accessibilityIdentifier("ask-first")
+ }
+ }
+ .frame(maxWidth: .infinity).padding(.vertical, 2)
+ }
+ }
+
+ /// Press and hold a message: copy it; on the agent's, mute (or bring back) reading its replies aloud.
+ private func text(_ s: String, on fill: Color) -> some View {
+ Text(s).font(.body).foregroundStyle(.white)
+ .padding(.horizontal, 14).padding(.vertical, 9)
+ .background(fill, in: RoundedRectangle(cornerRadius: M.bubble, style: .continuous))
+ .contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: M.bubble, style: .continuous))
+ .contextMenu {
+ Button { UIPasteboard.general.string = s } label: { Label("Copy", systemImage: "doc.on.doc") }
+ if line.who == .chums {
+ Button {
+ speak.toggle()
+ if !speak { hush() }
+ } label: {
+ Label(speak ? "Mute replies" : "Read replies aloud", systemImage: speak ? "speaker.slash" : "speaker.wave.2")
+ }
+ }
+ }
+ }
+}
+
+/// A picture you sent, as itself, on your side of the conversation, whole (not cropped). A tap opens it full screen.
+struct PhotoBubble: View {
+ let artifact: Artifact
+ let open: () -> Void
+ @State private var image: CGImage?
+
+ var body: some View {
+ let aspect = artifact.w / max(artifact.h, 1)
+ let w = min(240, 300 * aspect), h = w / max(aspect, 0.01)
+ Button(action: open) {
+ Group {
+ if let image { Image(decorative: image, scale: 1).resizable().aspectRatio(contentMode: .fill) } else { Ink.agent }
+ }
+ .frame(width: w, height: min(300, h))
+ .clipShape(RoundedRectangle(cornerRadius: M.bubble, style: .continuous))
+ .contentTransition(.opacity)
+ }
+ .buttonStyle(Pressable())
+ .accessibilityLabel("Your picture, \(artifact.title)")
+ .task {
+ image = ArtifactImages.shared.cachedThumb(artifact)
+ if let whole = await ArtifactImages.shared.whole(artifact) { withAnimation(Move.fade) { image = whole } }
+ }
+ }
+}
+
+/// Something an agent showed you, in the conversation: its picture, its title and what it is. A tap opens it full screen.
+struct ArtifactCard: View {
+ let artifact: Artifact
+ let open: () -> Void
+ @State private var image: CGImage?
+
+ var body: some View {
+ Button(action: open) {
+ HStack(spacing: 12) {
+ Group {
+ if let image { Image(decorative: image, scale: 1).resizable().scaledToFill() }
+ else { Color(white: 0.15) }
+ }
+ .frame(width: 64, height: 64).clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
+ VStack(alignment: .leading, spacing: 2) {
+ Text(artifact.title).font(.subheadline.weight(.semibold)).foregroundStyle(.white).lineLimit(2)
+ Text(artifact.label).font(.caption).foregroundStyle(Ink.quiet)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(8)
+ .background(Ink.agent, in: RoundedRectangle(cornerRadius: M.bubble, style: .continuous))
+ .frame(maxWidth: 300, alignment: .leading)
+ }
+ .buttonStyle(Pressable())
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .task { image = ArtifactImages.shared.cachedThumb(artifact); if image == nil { image = await ArtifactImages.shared.thumb(artifact) } }
+ }
+}
+
+/// An agent asks to run something: what, and Allow or Deny (a spoken yes or no answers it too). On amber-tinted glass,
+/// over the conversation.
+struct ApprovalCard: View {
+ let approval: Approval
+ let name: String
+ let decide: (Bool) -> Void
+ @State private var expanded = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 7) {
+ Image(systemName: "hand.raised.fill").foregroundStyle(Pal.amber)
+ Text("\(name) asks to use \(approval.tool)").font(.subheadline.weight(.semibold)).foregroundStyle(.white)
+ }
+ Text(approval.summary ?? approval.description).font(.subheadline).foregroundStyle(Color(white: 0.88))
+ .lineLimit(expanded ? nil : 3)
+ .fixedSize(horizontal: false, vertical: true)
+ .onTapGesture { withAnimation(Move.settle) { expanded.toggle() } }
+ if let detail {
+ Text(detail).font(.footnote.monospaced()).foregroundStyle(Color(white: 0.72))
+ .lineLimit(expanded ? nil : 4).padding(10).frame(maxWidth: .infinity, alignment: .leading)
+ .background(Color.black.opacity(0.35), in: RoundedRectangle(cornerRadius: 12, style: .continuous))
+ }
+ HStack(spacing: 10) {
+ Button { Haptics.play(.click); decide(false) } label: {
+ Text("Deny").font(.body.weight(.semibold)).frame(maxWidth: .infinity).frame(height: 46)
+ .background(Color(white: 0.18), in: Capsule()).foregroundStyle(.white)
+ }
+ Button { Haptics.play(.click); decide(true) } label: {
+ Text("Allow").font(.body.weight(.semibold)).frame(maxWidth: .infinity).frame(height: 46)
+ .background(Color.white, in: Capsule()).foregroundStyle(.black)
+ }
+ }
+ .buttonStyle(Pressable())
+ }
+ .padding(14)
+ .glassEffect(.regular.tint(Pal.amber.opacity(0.12)), in: RoundedRectangle(cornerRadius: 22, style: .continuous))
+ }
+
+ /// The tool's input, readable (its command, file or address), unless the line above already says it.
+ private var detail: String? {
+ var d = approval.preview
+ if let o = (try? JSONSerialization.jsonObject(with: Data(d.utf8))) as? [String: Any] {
+ d = ["command", "file_path", "path", "url", "pattern"].lazy.compactMap { o[$0] as? String }.first
+ ?? o.values.compactMap { $0 as? String }.joined(separator: "\n")
+ }
+ d = d.trimmingCharacters(in: .whitespacesAndNewlines)
+ let said = approval.summary ?? approval.description
+ return d.isEmpty || said.contains(d) ? nil : d
+ }
+}
+
+/// Beside the character at the bottom: what it's doing, in two lines of plain words. The first says the action ("Looking
+/// at your photo", "Running tests", "Needs you"), shimmering while it's under way; the second says exactly what on (the
+/// file, the command, the question) and, at work, for how long. Amber when it needs you, red when it's stuck. Idle,
+/// nothing: the character alone.
+struct StateLane: View {
+ /// What the lane says, worked out by the screen.
+ struct Words: Equatable {
+ enum Tone: Equatable { case live, plain, amber, red, quiet }
+ var main: String // the action: "Running tests", "Needs you"
+ var tone: Tone = .plain
+ var detail: String? = nil // exactly what: "npm test", "Asks to read photo-1.jpg"
+ var code = false // the detail is a command or a path (the code face)
+ var since: Date? = nil // at work: since when (after the detail)
+ }
+ let words: Words?
+ var tap: () -> Void = {}
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 3) {
+ if let w = words {
+ main(w).id("main-" + w.main).transition(roll)
+ if w.detail != nil || w.since != nil {
+ detail(w).id("detail-" + (w.detail ?? "")).transition(roll)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .dynamicTypeSize(...DynamicTypeSize.xxLarge) // two lines in the character's height
+ .contentShape(Rectangle())
+ .onTapGesture(perform: tap)
+ .animation(Move.or(Move.settle, reduced: reduceMotion), value: words)
+ .accessibilityElement(children: .combine)
+ .accessibilityAction { tap() }
+ .accessibilityIdentifier("state-lane")
+ }
+
+ /// The new words come in from below and the old go up, like a line of a log.
+ private var roll: AnyTransition {
+ reduceMotion ? .opacity : .asymmetric(insertion: .move(edge: .bottom).combined(with: .opacity),
+ removal: .move(edge: .top).combined(with: .opacity))
+ }
+
+ @ViewBuilder private func main(_ w: Words) -> some View {
+ let font = Font.subheadline.weight(.semibold)
+ switch w.tone {
+ case .live: Shimmer(text: w.main, font: font, still: reduceMotion)
+ case .amber: Text(w.main).font(font).foregroundStyle(Pal.amber).lineLimit(1)
+ case .red: Text(w.main).font(font).foregroundStyle(Pal.red).lineLimit(1)
+ case .quiet: Text(w.main).font(font).foregroundStyle(Ink.quiet).lineLimit(1)
+ case .plain: Text(w.main).font(font).foregroundStyle(.white).lineLimit(1)
+ }
+ }
+
+ private func detail(_ w: Words) -> some View {
+ HStack(spacing: 0) {
+ if let d = w.detail {
+ Text(d).font(w.code ? .footnote.monospaced() : .footnote).lineLimit(1).truncationMode(.middle)
+ .layoutPriority(-1)
+ }
+ if let since = w.since {
+ Text((w.detail == nil ? "" : " · ") as String) + Text(timerInterval: since...since.addingTimeInterval(86_400), countsDown: false)
+ }
+ }
+ .font(.footnote).monospacedDigit().foregroundStyle(Ink.quiet)
+ }
+
+ // MARK: steps in words
+
+ /// A file the iPhone sent, by the name it had there (the hub adds a time and a tag in front: 1791…-f7c9ca-photo-1.jpg).
+ static func sentName(_ file: String) -> String? {
+ guard let r = file.range(of: #"^\d{10,}-[0-9a-f]{6}-"#, options: .regularExpression) else { return nil }
+ return String(file[r.upperBound...])
+ }
+ private static let pictures: Set<String> = ["jpg", "jpeg", "png", "heic", "gif", "webp", "tiff"]
+
+ /// A step as the hub names it ("Read hub.mjs", "Bash npm test", "Grep TODO") in words: the action, and what on.
+ static func step(_ text: String, test: Bool = false) -> (main: String, detail: String?, code: Bool) {
+ let parts = text.split(separator: " ", maxSplits: 1).map(String.init)
+ let verb = parts.first ?? text, rest = parts.count > 1 ? parts[1] : nil
+ guard let rest else { return (verb == "Thinking" ? verb : "Using \(verb)", nil, false) }
+ switch verb {
+ case "Read":
+ if let name = sentName(rest) {
+ let ext = (name as NSString).pathExtension.lowercased()
+ return (pictures.contains(ext) ? "Looking at your photo" : "Reading your file", name, false)
+ }
+ return ("Reading a file", rest, true)
+ case "Edit": return ("Editing a file", rest, true)
+ case "Write": return ("Writing a file", rest, true)
+ case "Grep": return ("Searching the code", "“\(rest)”", false)
+ case "Glob": return ("Finding files", rest, true)
+ case "WebFetch": return ("Opening a page", rest, false)
+ case "WebSearch": return ("Searching the web", rest, false)
+ case "Subagent": return ("Running a helper agent", rest, false)
+ case "Bash":
+ var c = rest // the command alone, up to its first ; && | or redirect
+ for sep in [" && ", " || ", ";", " | ", " 2>", " >", " <"] { if let r = c.range(of: sep) { c = String(c[..<r.lowerBound]) } }
+ c = c.trimmingCharacters(in: .whitespaces)
+ return (test ? "Running tests" : "Running a command", c.isEmpty ? rest : c, true)
+ default: return ("Using \(verb)", rest, false) // a tool from an MCP server: its server, then its name
+ }
+ }
+}
+
+/// Words with light passing across them, left to right, again and again: it's happening now.
+struct Shimmer: View {
+ let text: String
+ let font: Font
+ var still = false
+ var body: some View {
+ let base = Text(text).font(font).lineLimit(1)
+ if still { base.foregroundStyle(.white) } else {
+ base.foregroundStyle(Color.white.opacity(0.5))
+ .overlay {
+ TimelineView(.animation(minimumInterval: 1.0 / 30)) { t in
+ let p = (t.date.timeIntervalSinceReferenceDate / 1.7).truncatingRemainder(dividingBy: 1) * 1.8 - 0.4
+ base.foregroundStyle(.white)
+ .mask(LinearGradient(colors: [.clear, .black, .clear],
+ startPoint: UnitPoint(x: p - 0.35, y: 0.5), endPoint: UnitPoint(x: p + 0.35, y: 0.5)))
+ }
+ }
+ }
+ }
+}
+
+/// The watch's crown, on the side of the character's window: roll it up or down with a finger and it turns like the
+/// watch's (a flick keeps it spinning a moment). Each detent ticks; its ridges roll with it.
+struct Crown: View {
+ let turn: (Double) -> Void
+ @State private var lastY = 0.0
+ @State private var detent = 0.0
+ @State private var roll = 0.0 // where its ridges are, in detents
+ @State private var held = false
+ @State private var coast: Task<Void, Never>?
+ private static let perDetent = 7.0 // points of finger travel for one detent
+
+ var body: some View {
+ Canvas { ctx, size in
+ let r = CGRect(origin: .zero, size: size)
+ ctx.fill(Path(roundedRect: r, cornerRadius: 3.5),
+ with: .linearGradient(Gradient(colors: [Color(white: 0.18), Color(white: held ? 0.6 : 0.42), Color(white: 0.22)]),
+ startPoint: .zero, endPoint: CGPoint(x: size.width, y: 0)))
+ // the ridges, rolling as it turns
+ let gap = 3.0, off = (roll * gap).truncatingRemainder(dividingBy: gap)
+ var y = -gap + (off < 0 ? off + gap : off)
+ while y < size.height + gap {
+ var line = Path(); line.move(to: CGPoint(x: 1.5, y: y)); line.addLine(to: CGPoint(x: size.width - 1.5, y: y))
+ ctx.stroke(line, with: .color(.black.opacity(0.45)), lineWidth: 0.8)
+ y += gap
+ }
+ }
+ .frame(width: 9, height: 32)
+ .scaleEffect(held ? 1.08 : 1)
+ .animation(.snappy(duration: 0.15), value: held)
+ .padding(.horizontal, 14).padding(.vertical, 18) // a finger-sized place to grab it
+ .contentShape(Rectangle())
+ .gesture(
+ DragGesture(minimumDistance: 0)
+ .onChanged { v in
+ if !held { held = true; coast?.cancel(); lastY = 0 }
+ let dy = v.translation.height - lastY
+ lastY = v.translation.height
+ step(-dy / Self.perDetent)
+ }
+ .onEnded { v in
+ held = false
+ flick(-v.velocity.height / Self.perDetent)
+ }
+ )
+ .accessibilityElement()
+ .accessibilityLabel("Crown")
+ .accessibilityHint("Turns like the watch's Digital Crown")
+ .accessibilityAdjustableAction { d in step(d == .increment ? 1 : -1) }
+ }
+
+ private func step(_ d: Double) {
+ guard d != 0 else { return }
+ roll += d; detent += d
+ turn(d)
+ if abs(detent) >= 1 { detent -= detent.rounded(.towardZero); Haptics.play(.click) }
+ }
+ /// Let go while moving: it keeps turning, slowing down.
+ private func flick(_ v0: Double) {
+ guard abs(v0) > 4 else { return }
+ coast = Task { @MainActor in
+ var v = min(60, max(-60, v0))
+ while abs(v) > 1.5 && !Task.isCancelled {
+ try? await Task.sleep(for: .milliseconds(16))
+ step(v / 60)
+ v *= 0.92
+ }
+ }
+ }
+}
+
diff --git a/app/ChumsPhone/PhoneShortcuts.swift b/app/ChumsPhone/PhoneShortcuts.swift
new file mode 100644
index 0000000..2f0228d
--- /dev/null
+++ b/app/ChumsPhone/PhoneShortcuts.swift
@@ -0,0 +1,33 @@
+import AppIntents
+import Foundation
+
+/// Siri and Shortcuts: "Ask Chums" sends what you say to an agent and reads its answer back; "Talk to Chums" opens
+/// the app listening.
+struct AskAgent: AppIntent {
+ static let title: LocalizedStringResource = "Ask an agent"
+ static let description = IntentDescription("Sends a message to one of your Chums agents and reads its answer.")
+ @Parameter(title: "Agent") var agent: AgentEntity
+ @Parameter(title: "Message", inputOptions: String.IntentInputOptions(multiline: true)) var message: String
+
+ static var parameterSummary: some ParameterSummary { Summary("Ask \(\.$agent) \(\.$message)") }
+
+ func perform() async throws -> some IntentResult & ProvidesDialog & ReturnsValue<String> {
+ let t0 = Date().timeIntervalSince1970 * 1000
+ guard await WidgetHub.say(message, agent: agent.id) else {
+ return .result(value: "", dialog: "I can't reach your Mac.")
+ }
+ if let reply = await WidgetHub.reply(agent: agent.id, after: t0, timeout: 45) {
+ return .result(value: reply, dialog: "\(reply)")
+ }
+ return .result(value: "", dialog: "\(agent.name) is still working on it. The answer will be in Chums.")
+ }
+}
+
+struct PhoneShortcuts: AppShortcutsProvider {
+ static var appShortcuts: [AppShortcut] {
+ AppShortcut(intent: AskAgent(), phrases: ["Ask \(.applicationName)", "Ask \(\.$agent) in \(.applicationName)"],
+ shortTitle: "Ask an agent", systemImageName: "bubble.left.and.text.bubble.right")
+ AppShortcut(intent: TalkToAgent(), phrases: ["Talk to \(.applicationName)", "Talk to \(\.$agent) in \(.applicationName)"],
+ shortTitle: "Talk to an agent", systemImageName: "waveform")
+ }
+}
diff --git a/app/ChumsPhone/Sidecar.swift b/app/ChumsPhone/Sidecar.swift
new file mode 100644
index 0000000..b62a8cd
--- /dev/null
+++ b/app/ChumsPhone/Sidecar.swift
@@ -0,0 +1,262 @@
+import SwiftUI
+
+/// Every agent, in a panel that slides in from the left over the screen: its face (ringed when it's doing something:
+/// white working, amber needs you, red stuck), its name, and the last thing said in its conversation. A tap talks to
+/// it; … opens its card. Press and hold one: it lifts under your finger, the others make room, and it settles where
+/// you let go.
+struct Sidecar: View {
+ let agents: [AgentInfo]
+ let active: String
+ let connected: Bool
+ let last: [String: String] // each agent's last line in its conversation
+ let pick: (String) -> Void
+ let settings: (AgentInfo) -> Void
+ let reorder: ([String]) -> Void
+ @State private var lifted: String? // the agent under your finger
+ @State private var from = 0 // where it was picked up
+ @State private var target = 0 // where it would land
+ @State private var dragY = 0.0
+ @State private var local: [String]? // the order just dropped, until the saved one comes back
+ @GestureState private var touching = false // a finger is on a row's press (ends however the gesture ends)
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ private static let rowH = 68.0
+
+ /// The rows, in the order on screen: the one just dropped, else the saved one.
+ private var rows: [AgentInfo] {
+ guard let local else { return agents }
+ return local.compactMap { id in agents.first { $0.id == id } } + agents.filter { !local.contains($0.id) }
+ }
+
+ /// The agents in a few words: those that need you, else those working, stuck or rate limited, else how many are
+ /// idle and how many aren't running.
+ private var summary: String {
+ if !connected { return "Can't reach your Mac" }
+ let needs = agents.filter(\.needs).count
+ func count(_ s: String...) -> Int { agents.filter { s.contains($0.status) }.count }
+ let working = count("working", "compacting"), stuck = count("blocked"), limited = count("limited"), off = count("offline")
+ if needs > 0 { return needs == 1 ? "1 needs you" : "\(needs) need you" }
+ if working > 0 { return "\(working) working" }
+ if stuck > 0 { return "\(stuck) stuck" }
+ if limited > 0 { return "\(limited) rate limited" }
+ if off == 0 { return "All idle" }
+ if off == agents.count { return "None running on your Mac" }
+ return "\(agents.count - off) idle, \(off) not running"
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Agents").font(.largeTitle.weight(.bold)).foregroundStyle(.white)
+ Text(summary).font(.subheadline.weight(.medium))
+ .foregroundStyle(!connected || agents.contains(where: \.needs) ? Pal.amber : Ink.quiet)
+ .contentTransition(.numericText())
+ }
+ .padding(.horizontal, 22).padding(.top, 14).padding(.bottom, 14)
+
+ ScrollView {
+ VStack(spacing: 0) {
+ ForEach(Array(rows.enumerated()), id: \.element.id) { i, a in row(a, at: i) }
+ }
+ .padding(.horizontal, 10).padding(.bottom, 10)
+ }
+ .scrollIndicators(.hidden)
+ .scrollDisabled(lifted != nil)
+
+ HStack(spacing: 8) {
+ Circle().fill(connected ? Color.white : Pal.amber).frame(width: 7, height: 7)
+ Text(connected ? "Connected to your Mac" : "Can't reach your Mac")
+ .font(.footnote).foregroundStyle(Ink.quiet)
+ }
+ .padding(.horizontal, 22).padding(.vertical, 14)
+ }
+ .frame(maxHeight: .infinity, alignment: .top)
+ .background {
+ UnevenRoundedRectangle(bottomTrailingRadius: 34, topTrailingRadius: 34, style: .continuous)
+ .fill(Ink.panel)
+ .overlay(UnevenRoundedRectangle(bottomTrailingRadius: 34, topTrailingRadius: 34, style: .continuous)
+ .strokeBorder(Color.white.opacity(0.08), lineWidth: 0.5))
+ .ignoresSafeArea()
+ }
+ .animation(.snappy, value: summary)
+ .onChange(of: agents.map(\.id)) { _, ids in if ids == local { local = nil } } // the saved order caught up
+ // the press ended without a drop (let go without dragging, or the system took the touch): it settles anyway
+ .onChange(of: touching) { _, on in if !on && lifted != nil { drop() } }
+ }
+
+ private func row(_ a: AgentInfo, at i: Int) -> some View {
+ let up = lifted == a.id
+ return AgentRow(agent: a, on: a.id == active, lifted: up, line: last[a.id]) { settings(a) }
+ .frame(height: Self.rowH)
+ .scaleEffect(up && !reduceMotion ? 1.035 : 1) // Reduce Motion: lifted by its shadow only
+ .shadow(color: .black.opacity(up ? 0.55 : 0), radius: 20, y: 10)
+ .dynamicTypeSize(...DynamicTypeSize.accessibility1) // the rows' height is fixed
+ .offset(y: offset(a.id, i))
+ .zIndex(up ? 2 : 0)
+ .contentShape(Rectangle())
+ .onTapGesture { pick(a.id) }
+ .gesture(
+ LongPressGesture(minimumDuration: 0.32)
+ .sequenced(before: DragGesture(minimumDistance: 0))
+ .updating($touching) { _, t, _ in t = true }
+ .onChanged { v in
+ switch v {
+ case .first(true):
+ if lifted == nil { lift(a.id, i) }
+ case .second(true, let d):
+ if lifted == nil { lift(a.id, i) }
+ guard let d else { return }
+ dragY = d.translation.height // under the finger, no easing
+ let t = min(rows.count - 1, max(0, from + Int((dragY / Self.rowH).rounded())))
+ if t != target { withAnimation(Move.snap) { target = t }; Haptics.play(.click) }
+ default: break
+ }
+ }
+ .onEnded { _ in drop() }
+ )
+ .accessibilityAction(named: "Move up") { move(i, to: i - 1) }
+ .accessibilityAction(named: "Move down") { move(i, to: i + 1) }
+ .accessibilityValue(up ? "Lifted" : "")
+ }
+
+ private func lift(_ id: String, _ i: Int) {
+ from = i; target = i; dragY = 0
+ withAnimation(Move.or(Move.lift, reduced: reduceMotion)) { lifted = id }
+ Haptics.play(.start)
+ }
+
+ /// While one is carried: it sits under the finger; the ones it has passed sit a row toward where it came from.
+ private func offset(_ id: String, _ i: Int) -> CGFloat {
+ guard let l = lifted else { return 0 }
+ if id == l { return dragY }
+ if from < target && i > from && i <= target { return -Self.rowH }
+ if from > target && i >= target && i < from { return Self.rowH }
+ return 0
+ }
+
+ /// Let go: in one movement the order changes and every row settles into its place (the carried one from under the
+ /// finger to its new place; the others are already there).
+ private func drop() {
+ guard lifted != nil else { return }
+ var ids = rows.map(\.id)
+ if target != from { ids.insert(ids.remove(at: from), at: target) }
+ withAnimation(Move.settle) {
+ local = ids
+ lifted = nil; dragY = 0
+ }
+ if target != from { reorder(ids) }
+ Haptics.play(.settle) // set down: firmer than a row passing
+ }
+
+ private func move(_ i: Int, to: Int) {
+ guard to >= 0, to < rows.count, i != to else { return }
+ var ids = rows.map(\.id)
+ ids.insert(ids.remove(at: i), at: to)
+ withAnimation(Move.settle) { local = ids }
+ reorder(ids)
+ }
+}
+
+/// One agent in the panel: its face (ringed when it's doing something), its name, the last thing said, and … for its
+/// card.
+struct AgentRow: View {
+ let agent: AgentInfo
+ let on: Bool
+ var lifted = false
+ var line: String? = nil
+ let settings: () -> Void
+
+ /// What it's doing, when it's doing something (idle says nothing: its last words say more).
+ private var busy: (Color, String)? {
+ if agent.needs { return (Pal.amber, "Needs you") }
+ switch agent.status {
+ case "working", "compacting": return (.white, "Working")
+ case "blocked": return (Pal.red, "Stuck")
+ case "limited": return (Pal.amber, "Rate limited")
+ default: return nil
+ }
+ }
+
+ var body: some View {
+ HStack(spacing: 13) {
+ AgentFace(character: agent.character, size: 44)
+ .opacity(agent.status == "offline" ? 0.45 : 1)
+ .padding(3)
+ .overlay { if let b = busy { Circle().strokeBorder(b.0, lineWidth: 2) } }
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ Text(agent.name).font(.body.weight(.semibold)).foregroundStyle(.white)
+ .lineLimit(1).minimumScaleFactor(0.85)
+ if agent.runtime == "codex" {
+ Text("Codex").font(.caption2.weight(.semibold)).foregroundStyle(Color(white: 0.75))
+ .padding(.horizontal, 6).padding(.vertical, 2)
+ .background(Color(white: 0.2), in: Capsule())
+ }
+ }
+ Group {
+ if let b = busy { Text(b.1).foregroundStyle(b.0 == .white ? Color(white: 0.85) : b.0) }
+ else if agent.status == "offline" { Text("Not running on your Mac").foregroundStyle(Ink.ghost) }
+ else { Text(line ?? agent.line ?? "Nothing said yet").foregroundStyle(Ink.quiet) }
+ }
+ .font(.footnote).lineLimit(1)
+ }
+ Spacer(minLength: 0)
+ Button(action: settings) {
+ Image(systemName: "ellipsis").font(.body.weight(.bold)).foregroundStyle(Color(white: 0.55))
+ .frame(width: 44, height: 44).contentShape(Rectangle())
+ }
+ .buttonStyle(Pressable())
+ .accessibilityLabel("\(agent.name)'s settings")
+ .accessibilityIdentifier("settings-\(agent.id)")
+ }
+ .padding(.leading, 8).padding(.trailing, 4).padding(.vertical, 6)
+ .background(Color(white: lifted ? 0.17 : on ? 0.13 : 0.065).opacity(on || lifted ? 1 : 0),
+ in: RoundedRectangle(cornerRadius: 20, style: .continuous))
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(agent.name)
+ .accessibilityIdentifier("agent-\(agent.id)")
+ .accessibilityAddTraits(on ? [.isButton, .isSelected] : .isButton)
+ }
+}
+
+/// The agents button at the top left, as on the watch: the others' faces stacked, the most urgent in front and bigger,
+/// two behind it smaller and dimmer (an amber ring on any that needs you). Just the faces, no plate behind them. A tap
+/// opens the agents.
+struct AgentsButton: View {
+ let others: [AgentInfo]
+ let action: () -> Void
+
+ var body: some View {
+ let shown = Array(others.prefix(3))
+ Button(action: action) {
+ ZStack(alignment: .leading) {
+ ForEach(Array(shown.enumerated().reversed()), id: \.element.id) { i, a in
+ let front = i == 0
+ AgentFace(character: a.character, size: front ? 32 : 26)
+ .padding(2).background(Circle().fill(a.needs ? Pal.amber : .black))
+ .opacity(front ? 1 : 0.75)
+ .offset(x: front ? 0 : 24 + CGFloat(i - 1) * 15)
+ }
+ }
+ .frame(width: 36 + CGFloat(max(0, shown.count - 1)) * 15 + (shown.count > 1 ? 9 : 0), height: 44, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(Pressable())
+ .accessibilityLabel("Agents")
+ .accessibilityValue({ let n = others.filter(\.needs).count; return n == 0 ? "" : n == 1 ? "1 needs you" : "\(n) need you" }())
+ }
+}
+
+/// Three dots, on their own (no plate): a corner's way into settings.
+struct DotsButton: View {
+ let label: String
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: action) {
+ Image(systemName: "ellipsis").font(.system(size: 20, weight: .bold)).foregroundStyle(.white)
+ .frame(width: 44, height: 44).contentShape(Rectangle())
+ }
+ .buttonStyle(Pressable())
+ .accessibilityLabel(label)
+ }
+}
diff --git a/app/ChumsPhone/Stage.swift b/app/ChumsPhone/Stage.swift
new file mode 100644
index 0000000..97402ea
--- /dev/null
+++ b/app/ChumsPhone/Stage.swift
@@ -0,0 +1,111 @@
+import SwiftUI
+
+/// Where the character is: at the bottom left of the conversation once there is one (what it's doing beside it, its
+/// newest line just above it), in the middle when there's no conversation yet, or in front when you tap it.
+enum StagePlace { case dock, middle, front }
+
+/// The character, drawn by the watch's rig every frame. Big, it's in a window the shape of the watch's screen with the
+/// crown on its side, and takes the watch's touches (hold to talk, tap to poke, stroke to pet, the crown or a two-finger
+/// twist). Small, it's the character alone, its edges fading into the black (no frame); a tap brings it to the front, a
+/// long press opens its settings. It's one view that moves between the two, so it shrinks and grows without a cut.
+/// It only draws: the rig moves on the model's own clock (ScreenModel.frame), drawn or not.
+struct CharacterStage: View {
+ let model: ScreenModel
+ let agent: AgentInfo
+ let small: Bool
+ let paused: Bool
+ let open: () -> Void
+ let settings: () -> Void
+ @State private var crop = Crop()
+ @State private var twisted = 0.0
+
+ /// How far it's cropped in, eased each frame (small: closer in on the character).
+ final class Crop { var k = 1.0; var last: Date? }
+ /// 30 frames a second when it's small or plays frames; the screen's own rate when it's big and drawn live.
+ private var live: Bool { !small && CharacterKind(id: agent.character)?.framed != true }
+
+ var body: some View {
+ GeometryReader { g in
+ let shape = RoundedRectangle(cornerRadius: small ? min(g.size.width, g.size.height) / 2 : g.size.width * 0.21,
+ style: .continuous)
+ TimelineView(.animation(minimumInterval: live ? nil : 1.0 / 30, paused: paused)) { tl in
+ Canvas { ctx, size in
+ let dt = crop.last.map { tl.date.timeIntervalSince($0) } ?? 1
+ crop.last = tl.date
+ crop.k += ((small ? 1.3 : 1) - crop.k) * min(1, max(0, dt) * 9)
+ var c = ctx
+ c.translateBy(x: size.width / 2, y: size.height / 2)
+ c.scaleBy(x: crop.k, y: crop.k)
+ c.translateBy(x: -size.width / 2, y: -size.height / 2)
+ Renderer.draw(model.rig, c, size: size)
+ }
+ }
+ .mask {
+ // big: the watch's screen; small: no edge at all, it fades out
+ ZStack {
+ shape.fill(.black).opacity(small ? 0 : 1)
+ Rectangle().fill(LinearGradient(stops: [.init(color: .clear, location: 0), .init(color: .black, location: 0.14),
+ .init(color: .black, location: 0.7), .init(color: .clear, location: 1)],
+ startPoint: .top, endPoint: .bottom))
+ .mask(LinearGradient(stops: [.init(color: .clear, location: 0), .init(color: .black, location: 0.12),
+ .init(color: .black, location: 0.88), .init(color: .clear, location: 1)],
+ startPoint: .leading, endPoint: .trailing))
+ .opacity(small ? 1 : 0)
+ }
+ }
+ .contentShape(shape)
+ .gesture(
+ DragGesture(minimumDistance: 0)
+ .onChanged { v in model.drag(v.location, in: g.size) }
+ .onEnded { v in _ = model.dragEnd(v.location, in: g.size) },
+ including: small ? .none : .all
+ )
+ .simultaneousGesture(
+ RotateGesture()
+ .onChanged { v in model.crown((v.rotation.degrees - twisted) / 12); twisted = v.rotation.degrees }
+ .onEnded { _ in twisted = 0 },
+ including: small ? .none : .all
+ )
+ .overlay {
+ shape.strokeBorder(LinearGradient(colors: [Color(white: 0.32), Color(white: 0.1)], startPoint: .top, endPoint: .bottom),
+ lineWidth: 1.5)
+ .opacity(small ? 0 : 1)
+ }
+ .overlay(alignment: .topTrailing) {
+ if !small { // only with the watch's window around it
+ Crown { model.crown($0) }
+ .offset(x: 24, y: g.size.height * 0.17 - 18) // just outside the right edge, where the watch has it
+ .transition(.opacity)
+ }
+ }
+ .overlay {
+ if small {
+ Color.clear.contentShape(Rectangle())
+ .onTapGesture(perform: open)
+ .onLongPressGesture(minimumDuration: 0.45) { Haptics.play(.strong); settings() }
+ }
+ }
+ }
+ // the big one, drawing live, has the clock run at the screen's rate with it
+ .onChange(of: live && !paused, initial: true) { _, on in if !small { model.fullRate = on } }
+ .onDisappear { if !small { model.fullRate = false } }
+ .accessibilityElement()
+ .accessibilityIdentifier("character")
+ .accessibilityLabel(agent.name)
+ .accessibilityHint(small ? "Shows \(agent.name) in front" : "Hold to talk to \(agent.name)")
+ .accessibilityAddTraits(small ? .isButton : [])
+ }
+}
+
+/// A scale that follows your voice while `on` (the character in its row, the microphone held). The voice's level is
+/// read from the recorder, not tracked, so it's read here every frame, 30 a second, without redrawing what it scales.
+struct VoiceScale: ViewModifier {
+ let model: ScreenModel
+ let on: Bool
+ let base: Double, gain: Double
+ func body(content: Content) -> some View {
+ TimelineView(.animation(minimumInterval: 1.0 / 30, paused: !on)) { _ in
+ content.scaleEffect(on ? base + model.talkLevel * gain : 1)
+ }
+ }
+}
diff --git a/app/ChumsPhone/Viewer.swift b/app/ChumsPhone/Viewer.swift
new file mode 100644
index 0000000..9d8faab
--- /dev/null
+++ b/app/ChumsPhone/Viewer.swift
@@ -0,0 +1,302 @@
+import SwiftUI
+import UIKit
+import WebKit
+import PDFKit
+import QuickLook
+import AVKit
+
+/// Something an agent showed you (or you sent), opened on the app's sliding card (drag it down by its handle to put it
+/// away), live where the iPhone can: a web page or an agent's HTML page runs (scripts, charts, scrolling), a PDF scrolls
+/// page by page, a video plays, a document opens in Quick Look. Anything else, or anything that can't be had from the
+/// Mac, is its picture: pinch to zoom where your fingers are, drag to look around, double-tap to zoom in or back out.
+/// Its title at the top left; Share at the top right sends the original (the file, or the page's address).
+struct ArtifactSheet: View {
+ let artifact: Artifact
+ var character: String = Agents.fallback
+ @State private var image: UIImage?
+ @State private var zoomed = false
+ @State private var file: URL? // the original, from the Mac (a PDF, a video, a document, a page)
+ @State private var html: String? // an HTML page to run (an agent's, or the Mac's rendering of a text)
+ @State private var failed = false // the live one couldn't be had: its picture instead
+ @State private var pageLoaded = false // the live page has loaded: until then, its picture
+
+ private var view: ArtifactView? { artifact.view }
+ private var live: String? { failed ? nil : view?.type }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(alignment: .center, spacing: 12) {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(artifact.title).font(.headline).foregroundStyle(.white).lineLimit(1)
+ Text(artifact.label).font(.footnote).foregroundStyle(Ink.quiet)
+ }
+ Spacer(minLength: 8)
+ share.transition(.opacity)
+ }
+ .frame(minHeight: 44) // Share coming in doesn't move what's below
+ .padding(.leading, 22).padding(.trailing, 10).padding(.top, 24).padding(.bottom, 6)
+ ZStack { content }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .animation(Move.fade, value: image != nil)
+ .animation(Move.fade, value: file != nil || html != nil)
+ .cardSheet(character: character)
+ .task { await load() }
+ }
+
+ /// What it opens as: the live view for its type, else the picture. The picture shows while the live one comes.
+ @ViewBuilder private var content: some View {
+ switch live {
+ case "url":
+ if let u = view?.url.flatMap(URL.init(string:)) { page(.url(u)) } else { picture }
+ case "html", "text":
+ if let html { page(.html(html)) } else { picture }
+ case "pdf":
+ if let file { PDFPages(url: file) } else { picture }
+ case "video":
+ if let file { VideoPlayer(player: AVPlayer(url: file)).ignoresSafeArea(edges: .bottom) } else { picture }
+ case "doc":
+ if let file { DocPreview(url: file).ignoresSafeArea(edges: .bottom) } else { picture }
+ default:
+ picture
+ }
+ }
+
+ /// A live page over its picture, which shows until the page has loaded (Safari's engine can take seconds to start):
+ /// the picture is the page at phone width, so it sits where the page will. A page that doesn't load stays its picture.
+ private func page(_ source: LiveWeb.Source) -> some View {
+ ZStack(alignment: .top) {
+ if !pageLoaded {
+ if let image {
+ GeometryReader { g in
+ Image(uiImage: image).resizable().scaledToFit().frame(width: g.size.width)
+ .frame(width: g.size.width, height: g.size.height, alignment: .top).clipped()
+ }
+ } else { ProgressView().tint(.white).frame(maxWidth: .infinity, maxHeight: .infinity) }
+ }
+ LiveWeb(source: source, loaded: { pageLoaded = true }, failed: { failed = true })
+ .opacity(pageLoaded ? 1 : 0)
+ .allowsHitTesting(pageLoaded)
+ }
+ .animation(Move.fade, value: pageLoaded)
+ }
+
+ @ViewBuilder private var picture: some View {
+ if let image { ZoomableImage(image: image, zoomed: $zoomed) {}.transition(.opacity) }
+ else { ProgressView().tint(.white) }
+ }
+
+ /// Share: the original file, or the page's address, or the picture.
+ @ViewBuilder private var share: some View {
+ Group {
+ if let file { ShareLink(item: file) { shareIcon } }
+ else if live == "url", let u = view?.url.flatMap(URL.init(string:)) { ShareLink(item: u) { shareIcon } }
+ else if let image { ShareLink(item: Image(uiImage: image), preview: SharePreview(artifact.title, image: Image(uiImage: image))) { shareIcon } }
+ }
+ .buttonStyle(Pressable())
+ .accessibilityLabel("Share")
+ }
+ private var shareIcon: some View {
+ Image(systemName: "square.and.arrow.up").font(.system(size: 19, weight: .semibold)).foregroundStyle(.white)
+ .frame(width: 44, height: 44).contentShape(Rectangle())
+ }
+
+ /// The picture always (it's the fallback, and Share's when there's nothing else); then what its type opens live.
+ private func load() async {
+ async let pic: CGImage? = ArtifactImages.shared.whole(artifact)
+ let hub = ArtifactImages.shared.hub
+ switch view?.type {
+ case "html", "text":
+ if let d = await hub?.fetch("/v1/artifact/\(artifact.id)/view"), let s = String(data: d, encoding: .utf8) { html = s }
+ else { failed = true }
+ if let d = await hub?.fetch("/v1/artifact/\(artifact.id)/source") { file = save(d) }
+ case "pdf", "video", "doc":
+ if let d = await hub?.fetch("/v1/artifact/\(artifact.id)/source") { file = save(d) } else { failed = true }
+ default: break
+ }
+ if let cg = await pic { image = UIImage(cgImage: cg) }
+ }
+
+ /// The original, as a file with its own name (what Quick Look, the player and Share go by).
+ private func save(_ data: Data) -> URL? {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("artifacts/\(artifact.id)", isDirectory: true)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let name = (view?.name).flatMap { $0.isEmpty ? nil : $0 } ?? artifact.title
+ let url = dir.appendingPathComponent(name.replacingOccurrences(of: "/", with: "-"))
+ return (try? data.write(to: url)) != nil ? url : nil
+ }
+}
+
+/// A web page, live: an address, or an agent's HTML (its scripts run: charts, tables you can scroll). In a private
+/// store (nothing kept between pages); a link you tap opens in Safari, not in here. An agent's HTML stays the page it
+/// is: it can't go to another page or send a form by itself.
+struct LiveWeb: UIViewRepresentable {
+ enum Source: Equatable { case url(URL), html(String) }
+ let source: Source
+ var loaded: () -> Void = {}
+ var failed: () -> Void = {}
+
+ func makeUIView(context: Context) -> WKWebView {
+ let c = WKWebViewConfiguration()
+ c.websiteDataStore = .nonPersistent()
+ c.allowsInlineMediaPlayback = true
+ let w = WKWebView(frame: .zero, configuration: c)
+ w.navigationDelegate = context.coordinator
+ w.isOpaque = false
+ w.backgroundColor = .clear
+ w.scrollView.backgroundColor = .clear
+ w.accessibilityIdentifier = "artifact-web"
+ switch source {
+ case .url(let u): w.load(URLRequest(url: u))
+ case .html(let h): w.loadHTMLString(h, baseURL: URL(string: "about:blank"))
+ }
+ return w
+ }
+ func updateUIView(_ w: WKWebView, context: Context) { context.coordinator.loaded = loaded; context.coordinator.failed = failed }
+ func makeCoordinator() -> Coordinator { Coordinator(loaded, failed, html: { if case .html = source { true } else { false } }()) }
+
+ final class Coordinator: NSObject, WKNavigationDelegate {
+ var loaded: () -> Void, failed: () -> Void
+ let html: Bool
+ init(_ loaded: @escaping () -> Void, _ failed: @escaping () -> Void, html: Bool) {
+ self.loaded = loaded; self.failed = failed; self.html = html
+ }
+ func webView(_ w: WKWebView, didFinish _: WKNavigation!) { loaded() }
+ func webView(_ w: WKWebView, didFail _: WKNavigation!, withError _: Error) { failed() }
+ func webView(_ w: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError _: Error) { failed() }
+ func webView(_ w: WKWebView, decidePolicyFor a: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
+ if a.navigationType == .linkActivated, let u = a.request.url, ["http", "https"].contains(u.scheme) {
+ UIApplication.shared.open(u); decisionHandler(.cancel)
+ } else if html, a.targetFrame?.isMainFrame ?? true, a.request.url?.absoluteString != "about:blank" {
+ decisionHandler(.cancel) // a script or a form taking the page somewhere else
+ } else { decisionHandler(.allow) }
+ }
+ }
+}
+
+/// A PDF, page after page: scroll through it, pinch to zoom.
+struct PDFPages: UIViewRepresentable {
+ let url: URL
+ func makeUIView(context: Context) -> PDFView {
+ let v = PDFView()
+ v.document = PDFDocument(url: url)
+ v.displayMode = .singlePageContinuous
+ v.displayDirection = .vertical
+ v.autoScales = true
+ v.backgroundColor = .clear
+ v.pageShadowsEnabled = false
+ v.accessibilityIdentifier = "artifact-pdf"
+ return v
+ }
+ func updateUIView(_ v: PDFView, context: Context) {}
+}
+
+/// A document Quick Look can open (Word, Pages, Keynote, Numbers, Excel, RTF, a table, a 3D model…), as Files shows it.
+struct DocPreview: UIViewControllerRepresentable {
+ let url: URL
+ func makeUIViewController(context: Context) -> QLPreviewController {
+ let q = QLPreviewController()
+ q.dataSource = context.coordinator
+ return q
+ }
+ func updateUIViewController(_ q: QLPreviewController, context: Context) {}
+ func makeCoordinator() -> Coordinator { Coordinator(url) }
+
+ final class Coordinator: NSObject, QLPreviewControllerDataSource {
+ let url: URL
+ init(_ url: URL) { self.url = url }
+ func numberOfPreviewItems(in q: QLPreviewController) -> Int { 1 }
+ func previewController(_ q: QLPreviewController, previewItemAt i: Int) -> QLPreviewItem { url as NSURL }
+ }
+}
+
+/// UIKit's zooming scroll view, for the natural pinch, pan and bounce: the picture fits the screen, zooms up to 6×
+/// about the fingers, stays centered when it's smaller than the screen.
+struct ZoomableImage: UIViewRepresentable {
+ let image: UIImage
+ @Binding var zoomed: Bool
+ let tap: () -> Void
+
+ func makeUIView(context: Context) -> ZoomView {
+ let v = ZoomView(image: image)
+ v.delegate = context.coordinator
+ let double = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.doubleTap(_:)))
+ double.numberOfTapsRequired = 2
+ let single = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.singleTap))
+ single.require(toFail: double)
+ v.addGestureRecognizer(double)
+ v.addGestureRecognizer(single)
+ return v
+ }
+ func updateUIView(_ v: ZoomView, context: Context) { context.coordinator.parent = self }
+ func makeCoordinator() -> Coordinator { Coordinator(self) }
+
+ final class Coordinator: NSObject, UIScrollViewDelegate {
+ var parent: ZoomableImage
+ init(_ p: ZoomableImage) { parent = p }
+ func viewForZooming(in scrollView: UIScrollView) -> UIView? { (scrollView as? ZoomView)?.imageView }
+ func scrollViewDidZoom(_ scrollView: UIScrollView) {
+ (scrollView as? ZoomView)?.center()
+ let z = scrollView.zoomScale > scrollView.minimumZoomScale + 0.01
+ if z != parent.zoomed { parent.zoomed = z }
+ }
+ @objc func singleTap() { parent.tap() }
+ @objc func doubleTap(_ g: UITapGestureRecognizer) {
+ guard let v = g.view as? ZoomView else { return }
+ if v.zoomScale > v.minimumZoomScale + 0.01 { v.setZoomScale(v.minimumZoomScale, animated: true); return }
+ let p = g.location(in: v.imageView), k = 2.5
+ let size = CGSize(width: v.bounds.width / k, height: v.bounds.height / k)
+ v.zoom(to: CGRect(x: p.x - size.width / 2, y: p.y - size.height / 2, width: size.width, height: size.height), animated: true)
+ }
+ }
+}
+
+final class ZoomView: UIScrollView {
+ let imageView: UIImageView
+ private var laidOut = CGSize.zero
+
+ init(image: UIImage) {
+ imageView = UIImageView(image: image)
+ super.init(frame: .zero)
+ imageView.contentMode = .scaleAspectFit
+ addSubview(imageView)
+ minimumZoomScale = 1; maximumZoomScale = 6
+ bouncesZoom = true; alwaysBounceVertical = false; alwaysBounceHorizontal = false
+ showsVerticalScrollIndicator = false; showsHorizontalScrollIndicator = false
+ contentInsetAdjustmentBehavior = .never
+ decelerationRate = .normal
+ backgroundColor = .clear
+ accessibilityIdentifier = "viewer-scroll"
+ // VoiceOver can't pinch: the same zoom, as actions
+ accessibilityCustomActions = [
+ UIAccessibilityCustomAction(name: "Zoom in") { [weak self] _ in
+ guard let self else { return false }
+ setZoomScale(min(maximumZoomScale, zoomScale * 2), animated: true); return true
+ },
+ UIAccessibilityCustomAction(name: "Zoom out") { [weak self] _ in
+ guard let self else { return false }
+ setZoomScale(max(minimumZoomScale, zoomScale / 2), animated: true); return true
+ },
+ ]
+ }
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ // the picture fitted to the screen at 1×, laid out again only when the screen's size changes
+ guard bounds.size != laidOut, let img = imageView.image, img.size.width > 0, img.size.height > 0 else { return }
+ laidOut = bounds.size
+ zoomScale = 1
+ let k = min(bounds.width / img.size.width, bounds.height / img.size.height)
+ imageView.frame = CGRect(origin: .zero, size: CGSize(width: img.size.width * k, height: img.size.height * k))
+ contentSize = imageView.frame.size
+ center()
+ }
+
+ /// Smaller than the screen in a direction, the picture sits in the middle of it.
+ func center() {
+ let dx = max(0, (bounds.width - contentSize.width) / 2), dy = max(0, (bounds.height - contentSize.height) / 2)
+ contentInset = UIEdgeInsets(top: dy, left: dx, bottom: dy, right: dx)
+ accessibilityValue = String(format: "zoom %.1f", zoomScale)
+ }
+}
diff --git a/app/ChumsPhone/WidgetShots.swift b/app/ChumsPhone/WidgetShots.swift
new file mode 100644
index 0000000..8f51b6c
--- /dev/null
+++ b/app/ChumsPhone/WidgetShots.swift
@@ -0,0 +1,68 @@
+#if DEBUG
+import SwiftUI
+import WidgetKit
+
+/// Debug builds only: launched with -widgetShots YES, the app draws every widget size, with the hub's state now and
+/// with Ray asking for an approval, to Documents/widgets/*.png (`xcrun simctl get_app_container <sim> dev.chums data`).
+/// For checking the widgets without putting each one on a Home Screen.
+@MainActor enum WidgetShots {
+ static func run() async {
+ guard UserDefaults.standard.bool(forKey: "widgetShots") else { return }
+ let live = await WidgetHub.state() ?? WidgetHub.sample
+ let asking = WState(
+ rev: live.rev,
+ agents: live.agents.map { a in
+ a.id == "ray" ? WAgent(id: a.id, name: a.name, character: a.character, status: "waiting", line: "Delete the build folder?", needs: true) : a
+ },
+ approvals: [WApproval(requestId: "shot", session: "ray", tool: "Bash", description: "Delete the build folder",
+ summary: "rm -rf ~/Developer/chums/app/build")],
+ spoken: [])
+ let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("widgets")
+ try? FileManager.default.removeItem(at: dir)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+
+ // the iPhone 17 Pro's widget sizes, in points
+ let agentSizes: [(String, WidgetFamily, CGSize)] = [
+ ("small", .systemSmall, CGSize(width: 170, height: 170)),
+ ("medium", .systemMedium, CGSize(width: 364, height: 170)),
+ ("circular", .accessoryCircular, CGSize(width: 76, height: 76)),
+ ("rect", .accessoryRectangular, CGSize(width: 172, height: 76)),
+ ("inline", .accessoryInline, CGSize(width: 260, height: 26)),
+ ]
+ let teamSizes: [(String, WidgetFamily, CGSize)] = [
+ ("medium", .systemMedium, CGSize(width: 364, height: 170)),
+ ("large", .systemLarge, CGSize(width: 364, height: 382)),
+ ]
+ for (tag, state) in [("live", live), ("asking", asking)] {
+ for (name, family, size) in agentSizes {
+ for pick in ["ray", "noodle", "stretch", "peeps"] where pick == "ray" || family == .systemSmall {
+ let e = await ChumsEntry.make(state, pick: pick, family: family, size: size)
+ shot(AgentWidgetView(entry: e, shownAs: family), size, family, dir.appendingPathComponent("agent-\(name)-\(tag)\(pick == "ray" ? "" : "-" + pick).png"))
+ }
+ }
+ for (name, family, size) in teamSizes {
+ let e = ChumsEntry(date: .now, state: state, pick: nil)
+ shot(TeamWidgetView(entry: e, shownAs: family), size, family, dir.appendingPathComponent("team-\(name)-\(tag).png"), margins: true)
+ }
+ }
+ hubLog("widget shots written: \(dir.path)")
+ }
+
+ private static func shot(_ view: some View, _ size: CGSize, _ family: WidgetFamily, _ url: URL, margins: Bool = false) {
+ let home = [.systemSmall, .systemMedium, .systemLarge].contains(family)
+ let framed = view
+ .padding(home && margins ? 16 : 0) // the Agent widget draws to its edges
+ .frame(width: size.width, height: size.height)
+ .background(home ? Color.black : Color(white: 0.22)) // the Lock Screen ones on a gray, to see them
+ .clipShape(RoundedRectangle(cornerRadius: home ? 24 : 8, style: .continuous))
+ .padding(12)
+ .background(Color(white: 0.35)) // a wallpaper behind, so the black edge shows
+ .environment(\.colorScheme, .dark)
+ let r = ImageRenderer(content: framed)
+ r.scale = 3
+ if let data = r.uiImage?.pngData() { try? data.write(to: url) }
+ }
+
+ private static func hubLog(_ s: String) { print(s) }
+}
+#endif
diff --git a/app/ChumsPhoneShared/Intents.swift b/app/ChumsPhoneShared/Intents.swift
new file mode 100644
index 0000000..3670085
--- /dev/null
+++ b/app/ChumsPhoneShared/Intents.swift
@@ -0,0 +1,61 @@
+import AppIntents
+import Foundation
+import WidgetKit
+
+// What the widgets, the Control and Siri can do: pick an agent, answer an approval, open Chums listening. In the app and
+// in the widget extension both (the app adds Siri's "Ask", PhoneShortcuts.swift).
+
+struct AgentEntity: AppEntity {
+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Agent"
+ static let defaultQuery = AgentQuery()
+ let id: String
+ let name: String
+ var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(name)") }
+}
+
+struct AgentQuery: EntityQuery {
+ func entities(for identifiers: [String]) async throws -> [AgentEntity] {
+ await all().filter { identifiers.contains($0.id) }
+ }
+ func suggestedEntities() async throws -> [AgentEntity] { await all() }
+ private func all() async -> [AgentEntity] {
+ let agents = await WidgetHub.state()?.agents ?? WidgetHub.sample.agents
+ return agents.map { AgentEntity(id: $0.id, name: $0.name) }
+ }
+}
+
+/// Which agent a widget shows: one you pick, or the one you last talked to.
+struct PickAgent: WidgetConfigurationIntent {
+ static let title: LocalizedStringResource = "Agent"
+ static let description = IntentDescription("The agent this widget shows. Without one, it shows the agent you last talked to.")
+ @Parameter(title: "Agent") var agent: AgentEntity?
+ init() {}
+}
+
+/// Allow or deny what an agent asks, right from the widget.
+struct AnswerApproval: AppIntent {
+ static let title: LocalizedStringResource = "Answer an approval"
+ static let isDiscoverable = false
+ @Parameter(title: "Request") var requestId: String
+ @Parameter(title: "Allow") var allow: Bool
+ init() {}
+ init(_ requestId: String, allow: Bool) { self.requestId = requestId; self.allow = allow }
+ func perform() async throws -> some IntentResult {
+ _ = await WidgetHub.verdict(requestId, allow: allow)
+ WidgetCenter.shared.reloadAllTimelines()
+ return .result()
+ }
+}
+
+/// Opens Chums listening to an agent (the Control, the Action Button, a widget's Talk, Siri).
+struct TalkToAgent: AppIntent {
+ static let title: LocalizedStringResource = "Talk to an agent"
+ static let description = IntentDescription("Opens Chums already listening: say what you want, then tap send.")
+ @Parameter(title: "Agent") var agent: AgentEntity?
+ init() {}
+ init(agent: AgentEntity?) { self.agent = agent }
+ func perform() async throws -> some IntentResult & OpensIntent {
+ let url = URL(string: "chums://talk" + (agent.map { "/\($0.id)" } ?? ""))!
+ return .result(opensIntent: OpenURLIntent(url))
+ }
+}
diff --git a/app/ChumsPhoneShared/WatchScreen.swift b/app/ChumsPhoneShared/WatchScreen.swift
new file mode 100644
index 0000000..0d3a025
--- /dev/null
+++ b/app/ChumsPhoneShared/WatchScreen.swift
@@ -0,0 +1,52 @@
+import SwiftUI
+import UIKit
+
+/// The watch's screen for one agent, as a picture: the same character, faces, status, caption and approval card the
+/// watch draws (Renderer, with its chrome), for the widgets, which can't animate. The rig runs a moment first, so the
+/// character has settled into its state.
+@MainActor enum WatchScreen {
+ static func image(_ agent: WAgent, in state: WState?, size: CGSize, scale: CGFloat = 3) async -> UIImage? {
+ guard size.width > 0, size.height > 0 else { return nil }
+ let r = Rig()
+ r.cardControls = false // the widget's own Deny and Allow answer it
+ if let k = CharacterKind(id: agent.character) { r.character = k }
+ let look = Self.look(agent, state)
+ if let a = state?.approval(for: agent.id) {
+ r.approvalTitle = a.summary ?? a.description
+ r.approvalDetail = a.tool == "Bash" ? a.description : a.tool
+ }
+ r.restState = look.state
+ r.setState(look.state)
+ r.label = look.label
+ r.caption = look.caption
+ r.faces = faces(agent, state)
+ for _ in 0..<45 { r.tick(1.0 / 30) }
+ let view = Canvas { ctx, sz in Renderer.draw(r, ctx, size: sz) }
+ .frame(width: size.width, height: size.height)
+ .environment(\.displayScale, scale)
+ func draw() -> UIImage? { let ir = ImageRenderer(content: view); ir.scale = scale; return ir.uiImage }
+ // Stretch's frames are decoded off the main thread: the first drawing asks for them, a second one has them
+ if r.character == .stretch { _ = draw(); try? await Task.sleep(for: .milliseconds(300)) }
+ return draw()
+ }
+
+ /// The watch's state, status and caption for an agent (Controller.restFor, from what the widgets get).
+ static func look(_ a: WAgent, _ s: WState?) -> (state: ChumsState, label: String, caption: String) {
+ guard let s else { return (.sleep, "HUB OFFLINE", "Can't reach your Mac") }
+ if let ap = s.approval(for: a.id) { return (.approval, ap.tool.uppercased(), "") }
+ switch a.status {
+ case "offline": return (.sleep, "NOT RUNNING", "\(a.name) isn't running on your Mac.")
+ case "blocked": return (.blocked, "BLOCKED", a.line ?? "It's stuck.")
+ case "limited": return (.blocked, "RATE LIMITED", "Rate limited. It resumes by itself.")
+ case "compacting": return (.thinking, "COMPACTING", "")
+ case "working": return (.working, "WORKING", "")
+ default: return a.needs || a.status == "waiting" ? (.needs, "ASKS", a.line ?? "It has a question.") : (.idle, "", "")
+ }
+ }
+
+ /// The faces at the top left, as on the watch: this agent, then at most two others, the ones that need you first.
+ static func faces(_ a: WAgent, _ s: WState?) -> [(character: String, needs: Bool)] {
+ let others = (s?.byUrgency ?? []).filter { $0.id != a.id }
+ return [(a.character, false)] + others.prefix(2).map { ($0.character, $0.needs) }
+ }
+}
diff --git a/app/ChumsPhoneShared/WidgetHub.swift b/app/ChumsPhoneShared/WidgetHub.swift
new file mode 100644
index 0000000..cfbf61d
--- /dev/null
+++ b/app/ChumsPhoneShared/WidgetHub.swift
@@ -0,0 +1,133 @@
+import Foundation
+
+// The hub, as the widgets, the Control and Siri reach it: one request at a time, from the extension or the app, with
+// the same address and token as the watch (HubConfig, generated by tools/gen-config.sh).
+
+struct WAgent: Codable, Identifiable, Hashable {
+ let id: String
+ let name: String
+ let character: String
+ let status: String
+ let line: String?
+ let needs: Bool
+}
+
+struct WApproval: Codable, Hashable {
+ let requestId: String
+ let session: String
+ let tool: String
+ let description: String
+ let summary: String?
+}
+
+struct WLine: Codable, Hashable {
+ let id: String
+ let text: String
+ let kind: String
+ let at: Double?
+ let agent: String?
+}
+
+struct WState: Codable {
+ let rev: Int
+ let agents: [WAgent]
+ let approvals: [WApproval]
+ let spoken: [WLine]
+ var focus: String? = nil // the agent you last talked to, or looked at on the iPhone
+
+ /// The agent a widget with none picked shows: the one you last talked to (or looked at on the iPhone).
+ var current: WAgent? { focus.flatMap { id in agents.first { $0.id == id } } ?? mostUrgent }
+ /// Without one: one asking or stuck, else one at work, else the first.
+ var mostUrgent: WAgent? {
+ func rank(_ a: WAgent) -> Int {
+ if a.needs { return 0 }
+ switch a.status { case "blocked": return 1; case "waiting", "limited": return 2; case "working", "compacting": return 3
+ case "offline": return 5; default: return 4 }
+ }
+ return agents.enumerated().min { (rank($0.element), $0.offset) < (rank($1.element), $1.offset) }?.element
+ }
+ func approval(for agent: String) -> WApproval? { approvals.first { $0.session == agent } }
+
+ /// Every agent in the app's order (SoulView.looks), the ones that need you first, then the ones at work.
+ var byUrgency: [WAgent] {
+ func rank(_ a: WAgent) -> Int { a.needs ? 0 : a.status == "blocked" ? 1 : a.status == "working" || a.status == "compacting" ? 2 : 3 }
+ func place(_ a: WAgent) -> Int { WidgetHub.order.firstIndex(of: a.character) ?? WidgetHub.order.count }
+ return agents.sorted { (rank($0), place($0)) < (rank($1), place($1)) }
+ }
+}
+
+enum WidgetHub {
+ /// The characters in the app's order (SoulView.looks, which the widgets can't see).
+ static let order = ["noodle", "squint", "ray", "tangle", "peeps", "stretch", "crunch", "nana"]
+
+ /// What a widget shows before the hub has answered once (the gallery, a placeholder).
+ static let sample = WState(rev: 0, agents: [
+ WAgent(id: "noodle", name: "Noodle", character: "noodle", status: "working", line: "Running the tests", needs: false),
+ WAgent(id: "squint", name: "Squint", character: "squint", status: "waiting", line: "Send the invoice now?", needs: true),
+ WAgent(id: "ray", name: "Ray", character: "ray", status: "idle", line: "Done. All ten tests pass.", needs: false),
+ ], approvals: [], spoken: [])
+
+ private static func request(_ host: String, _ path: String, method: String = "GET", body: Data? = nil, timeout: Double = 10) -> URLRequest? {
+ guard let url = URL(string: host + path) else { return nil }
+ var r = URLRequest(url: url, timeoutInterval: timeout)
+ r.httpMethod = method
+ r.setValue("Bearer \(HubConfig.token)", forHTTPHeaderField: "Authorization")
+ if let body { r.httpBody = body; r.setValue("application/json", forHTTPHeaderField: "Content-Type") }
+ return r
+ }
+ /// The hub's addresses: 127.0.0.1 is the Mac only in the Simulator; on an iPhone it's the iPhone itself, and the token
+ /// would go there in the clear.
+ private static let hosts: [String] = {
+#if targetEnvironment(simulator)
+ HubConfig.hosts
+#else
+ HubConfig.hosts.filter { !$0.contains("127.0.0.1") && !$0.contains("localhost") }
+#endif
+ }()
+ /// The first address that answers (the internet one on a device, the Mac's own in the Simulator).
+ private static func send(_ path: String, method: String = "GET", body: Data? = nil, timeout: Double = 10) async -> Data? {
+ for host in hosts {
+ guard let r = request(host, path, method: method, body: body, timeout: timeout),
+ let (data, resp) = try? await URLSession.shared.data(for: r),
+ (resp as? HTTPURLResponse)?.statusCode == 200 else { continue }
+ return data
+ }
+ return nil
+ }
+
+ static func state() async -> WState? {
+ guard let d = await send("/v1/state?since=0") else { return nil }
+ return try? JSONDecoder().decode(WState.self, from: d)
+ }
+ static func verdict(_ requestId: String, allow: Bool) async -> Bool {
+ let body = try? JSONSerialization.data(withJSONObject: ["requestId": requestId, "behavior": allow ? "allow" : "deny"])
+ return await send("/v1/verdict", method: "POST", body: body) != nil
+ }
+ /// Words to an agent, as if said on the iPhone (its answer is spoken there).
+ static func say(_ text: String, agent: String) async -> Bool {
+ let body = try? JSONSerialization.data(withJSONObject: ["text": text, "agent": agent, "device": "phone"])
+ return await send("/v1/say", method: "POST", body: body, timeout: 20) != nil
+ }
+ /// The agent's answer to something said at `after` (ms since 1970): its first line after that, waited for.
+ static func reply(agent: String, after: Double, timeout: Double) async -> String? {
+ let end = Date().addingTimeInterval(timeout)
+ while Date() < end {
+ if let s = await state(),
+ let l = s.spoken.last(where: { $0.agent == agent && $0.kind != "echo" && ($0.at ?? 0) > after }) { return l.text }
+ try? await Task.sleep(for: .seconds(1.5))
+ }
+ return nil
+ }
+}
+
+/// Words for an agent's status, the same as the watch's.
+func statusWords(_ a: WAgent) -> String {
+ switch a.status {
+ case "offline": return "Not running on your Mac"
+ case "working": return a.line.map { "Working · \($0)" } ?? "Working"
+ case "compacting": return "Tidying its memory"
+ case "limited": return "Rate limited"
+ case "blocked": return a.line.map { "Stuck: \($0)" } ?? "Stuck"
+ default: return a.needs ? (a.line.map { "Needs you: \($0)" } ?? "Needs you") : (a.line ?? "Idle")
+ }
+}
diff --git a/app/ChumsPhoneShared/WidgetViews.swift b/app/ChumsPhoneShared/WidgetViews.swift
new file mode 100644
index 0000000..eccd1f7
--- /dev/null
+++ b/app/ChumsPhoneShared/WidgetViews.swift
@@ -0,0 +1,256 @@
+import AppIntents
+import SwiftUI
+import UIKit
+import WidgetKit
+
+// What the widgets draw (ChumsPhoneWidgets), here so the app can draw them too: its debug build renders every size to
+// pictures (-widgetShots), to check them without putting them on a Home Screen.
+
+struct ChumsEntry: TimelineEntry {
+ let date: Date
+ let state: WState?
+ let pick: String? // the agent chosen in the widget's settings; nil: the one you last talked to
+ var screen: UIImage? = nil // the watch's screen for the agent (WatchScreen), on the Home Screen sizes
+ var agent: WAgent? { pick.flatMap { id in state?.agents.first { $0.id == id } } ?? state?.current }
+
+ /// An entry with the watch's screen drawn for a Home Screen widget of this family and size.
+ static func make(_ state: WState?, pick: String?, family: WidgetFamily, size: CGSize) async -> ChumsEntry {
+ var e = ChumsEntry(date: .now, state: state, pick: pick)
+ guard let a = e.agent, family == .systemSmall || family == .systemMedium else { return e }
+ let h = size.height, sz = family == .systemMedium ? CGSize(width: (h * DESIGN.width / DESIGN.height).rounded(), height: h) : size
+ e.screen = await WatchScreen.image(a, in: state, size: sz)
+ return e
+ }
+}
+
+/// What an agent is doing, in a word or two.
+func shortStatus(_ a: WAgent) -> String {
+ if a.needs { return "Needs you" }
+ switch a.status {
+ case "offline": return "Not running"
+ case "working": return "Working"
+ case "compacting": return "Tidying its memory"
+ case "limited": return "Rate limited"
+ case "blocked": return "Stuck"
+ default: return "Idle"
+ }
+}
+
+struct AgentWidgetView: View {
+ let entry: ChumsEntry
+ var shownAs: WidgetFamily? // set by the app's pictures; in a widget, the widget's own size
+ @Environment(\.widgetFamily) private var widgetFamily
+ private var family: WidgetFamily { shownAs ?? widgetFamily }
+
+ var body: some View {
+ if let a = entry.agent {
+ switch family {
+ case .accessoryCircular: circular(a)
+ case .accessoryRectangular: rectangular(a)
+ case .accessoryInline: Text("\(a.name) · \(a.needs ? "Needs you" : statusWords(a))")
+ case .systemMedium: medium(a)
+ default: small(a)
+ }
+ } else {
+ VStack(spacing: 4) {
+ Image(systemName: "wifi.exclamationmark").font(.title3)
+ Text("Can't reach your Mac").font(.caption).multilineTextAlignment(.center)
+ }
+ .foregroundStyle(.secondary)
+ .padding(12)
+ }
+ }
+
+ /// The watch's screen, as on the wrist; its face on a dark circle until it's drawn.
+ @ViewBuilder private func screen(_ a: WAgent) -> some View {
+ if let img = entry.screen {
+ Image(uiImage: img).resizable().scaledToFit()
+ } else {
+ WidgetFace(character: a.character, size: 64).frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+
+ /// Talk (the microphone), or Deny and Allow when it asks: round buttons over the screen's bottom right corner.
+ @ViewBuilder private func cornerButtons(_ a: WAgent) -> some View {
+ if let ap = entry.state?.approval(for: a.id) {
+ HStack(spacing: 6) {
+ Button(intent: AnswerApproval(ap.requestId, allow: false)) { RoundIcon(symbol: "xmark", light: false) }
+ Button(intent: AnswerApproval(ap.requestId, allow: true)) { RoundIcon(symbol: "checkmark", light: true) }
+ }
+ .buttonStyle(.plain)
+ } else {
+ Link(destination: URL(string: "chums://talk/\(a.id)")!) { RoundIcon(symbol: "mic.fill", light: true) }
+ .accessibilityLabel("Talk to \(a.name)")
+ }
+ }
+
+ /// The watch's screen, edge to edge, with the corner buttons.
+ private func small(_ a: WAgent) -> some View {
+ screen(a)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .overlay(alignment: .bottomTrailing) { cornerButtons(a).padding(10) }
+ .widgetURL(URL(string: "chums://agent/\(a.id)"))
+ }
+
+ /// The watch's screen on the left; its name, what it's doing and its last line on the right, the buttons along the
+ /// bottom of that column.
+ private func medium(_ a: WAgent) -> some View {
+ let ap = entry.state?.approval(for: a.id)
+ return HStack(spacing: 0) {
+ screen(a).frame(maxHeight: .infinity)
+ VStack(alignment: .leading, spacing: 0) {
+ Text(a.name).font(.system(size: 17, weight: .bold)).foregroundStyle(.white)
+ Text(ap.map { "Asks to use \($0.tool)" } ?? shortStatus(a))
+ .font(.system(size: 12, weight: .medium)).foregroundStyle(a.needs || ap != nil ? Pal.amber : Color(white: 0.55))
+ Text(ap.map { $0.summary ?? $0.description } ?? a.line ?? "")
+ .font(.system(size: 13)).foregroundStyle(Color(white: 0.8)).lineLimit(3)
+ .padding(.top, 6)
+ Spacer(minLength: 8)
+ HStack(spacing: 8) {
+ if let ap {
+ Button(intent: AnswerApproval(ap.requestId, allow: false)) { WideButton(symbol: "xmark", text: "Deny", light: false) }
+ Button(intent: AnswerApproval(ap.requestId, allow: true)) { WideButton(symbol: "checkmark", text: "Allow", light: true) }
+ } else {
+ Link(destination: URL(string: "chums://talk/\(a.id)")!) { WideButton(symbol: "mic.fill", text: "Talk", light: true) }
+ }
+ }
+ .buttonStyle(.plain)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .padding(.vertical, 14).padding(.leading, 6).padding(.trailing, 14)
+ }
+ .widgetURL(URL(string: "chums://agent/\(a.id)"))
+ }
+
+ private func circular(_ a: WAgent) -> some View {
+ ZStack {
+ AccessoryWidgetBackground()
+ WidgetFace(character: a.character, size: 46, plate: false)
+ if a.needs { Circle().strokeBorder(lineWidth: 3).widgetAccentable() }
+ }
+ .widgetURL(URL(string: "chums://agent/\(a.id)"))
+ }
+
+ private func rectangular(_ a: WAgent) -> some View {
+ HStack(spacing: 8) {
+ WidgetFace(character: a.character, size: 34, plate: false)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(a.name).font(.headline).widgetAccentable()
+ Text(statusWords(a)).font(.caption).lineLimit(2)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .widgetURL(URL(string: "chums://agent/\(a.id)"))
+ }
+}
+
+// MARK: every agent
+
+struct TeamWidgetView: View {
+ let entry: ChumsEntry
+ var shownAs: WidgetFamily? // set by the app's pictures; in a widget, the widget's own size
+ @Environment(\.widgetFamily) private var widgetFamily
+ private var family: WidgetFamily { shownAs ?? widgetFamily }
+
+ var body: some View {
+ let agents = entry.state?.byUrgency ?? []
+ let cols = family == .systemLarge ? 3 : 5
+ VStack(alignment: .leading, spacing: 10) {
+ if family == .systemLarge {
+ HStack {
+ Text("Chums").font(.system(size: 17, weight: .bold)).foregroundStyle(.white)
+ Spacer()
+ let n = agents.filter(\.needs).count, working = agents.filter { $0.status == "working" }.count
+ Text(entry.state == nil ? "Can't reach your Mac" : n > 0 ? "\(n) need\(n == 1 ? "s" : "") you" : working > 0 ? "\(working) working" : "All idle")
+ .font(.system(size: 12, weight: .medium)).foregroundStyle(n > 0 ? Pal.amber : Color(white: 0.55))
+ }
+ }
+ LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: cols), spacing: family == .systemLarge ? 12 : 6) {
+ ForEach(agents.prefix(family == .systemLarge ? 9 : 5)) { a in
+ Link(destination: URL(string: "chums://agent/\(a.id)")!) {
+ VStack(spacing: 4) {
+ WidgetFace(character: a.character, size: family == .systemLarge ? 52 : 44)
+ .overlay(alignment: .bottomTrailing) { WidgetDot(agent: a).offset(x: 2, y: 2) }
+ Text(a.name).font(.system(size: 11, weight: .medium)).foregroundStyle(.white).lineLimit(1)
+ if family == .systemLarge {
+ Text(a.needs ? "Needs you" : a.status == "working" ? "Working" : a.status == "offline" ? "Off" : "Idle")
+ .font(.system(size: 10)).foregroundStyle(a.needs ? Pal.amber : Color(white: 0.5))
+ }
+ }
+ }
+ }
+ }
+ if family == .systemLarge, let ap = entry.state?.approvals.first,
+ let who = agents.first(where: { $0.id == ap.session }) {
+ Spacer(minLength: 0)
+ HStack(spacing: 8) {
+ WidgetFace(character: who.character, size: 28)
+ Text("\(who.name): \(ap.summary ?? ap.description)").font(.system(size: 12)).foregroundStyle(Color(white: 0.85)).lineLimit(2)
+ Spacer(minLength: 4)
+ Button(intent: AnswerApproval(ap.requestId, allow: false)) { Image(systemName: "xmark") }.tint(Color(white: 0.25))
+ Button(intent: AnswerApproval(ap.requestId, allow: true)) { Text("Allow").bold() }.tint(.white).foregroundStyle(.black)
+ }
+ .buttonStyle(.borderedProminent).buttonBorderShape(.capsule).controlSize(.small)
+ }
+ }
+ }
+}
+
+// MARK: parts
+
+/// An agent's face, as in the app: the character on a dark circle (on the Lock Screen, without the circle).
+struct WidgetFace: View {
+ let character: String
+ var size = 40.0
+ var plate = true
+ var body: some View {
+ ZStack {
+ if plate { Circle().fill(.black) }
+ Image("avatar-\(character)").resizable()
+ .interpolation(AgentFace.fullBleed.contains(character) ? .high : .none)
+ .scaledToFit()
+ .padding(AgentFace.fullBleed.contains(character) ? 0 : size * 0.1)
+ }
+ .frame(width: size, height: size).clipShape(Circle())
+ }
+}
+
+/// Amber: needs you. White: working. Red: stuck. Gray: idle. Dim: not running.
+struct WidgetDot: View {
+ let agent: WAgent
+ var body: some View {
+ let c: Color = agent.needs ? Pal.amber : agent.status == "working" || agent.status == "compacting" ? .white
+ : agent.status == "blocked" ? .red : agent.status == "offline" ? Color(white: 0.25) : Color(white: 0.5)
+ Circle().fill(c).frame(width: 10, height: 10).overlay(Circle().strokeBorder(.black, lineWidth: 2))
+ }
+}
+
+/// A round button for a widget's corner: white with a black symbol, or dark with a white one.
+struct RoundIcon: View {
+ let symbol: String
+ let light: Bool
+ var body: some View {
+ Image(systemName: symbol)
+ .font(.system(size: 14, weight: .bold))
+ .foregroundStyle(light ? .black : .white)
+ .frame(width: 34, height: 34)
+ .background(light ? Color.white : Color(white: 0.22), in: Circle())
+ }
+}
+
+/// A full-width capsule button for the wide widget.
+struct WideButton: View {
+ let symbol: String
+ let text: String
+ let light: Bool
+ var body: some View {
+ HStack(spacing: 6) {
+ Image(systemName: symbol).font(.system(size: 13, weight: .bold))
+ Text(text).font(.system(size: 15, weight: .semibold))
+ }
+ .foregroundStyle(light ? .black : .white)
+ .frame(maxWidth: .infinity).frame(height: 36)
+ .background(light ? Color.white : Color(white: 0.2), in: Capsule())
+ }
+}
+
diff --git a/app/ChumsPhoneUITests/ChumsPhoneUITests.swift b/app/ChumsPhoneUITests/ChumsPhoneUITests.swift
new file mode 100644
index 0000000..71f5ddc
--- /dev/null
+++ b/app/ChumsPhoneUITests/ChumsPhoneUITests.swift
@@ -0,0 +1,486 @@
+import XCTest
+
+/// The iPhone app driven by real touches in the Simulator, against the hub on this Mac. Nothing here sends an order.
+/// Run: xcodebuild test -project Chums.xcodeproj -scheme Chums -destination 'platform=iOS Simulator,name=iPhone 17 Pro'
+/// With TEST_RUNNER_SHOTS_DIR=<folder>, each test leaves screenshots there; with TEST_RUNNER_VIEWER_ID=<artifact id>,
+/// the viewer test opens that picture.
+final class ChumsPhoneUITests: XCTestCase {
+ private var app: XCUIApplication!
+ private let env = ProcessInfo.processInfo.environment
+
+ override func setUp() {
+ continueAfterFailure = false
+ app = XCUIApplication()
+ }
+
+ private func launch(_ args: [String] = []) {
+ app.launchArguments = ["-agent", "ray"] + args
+ app.launch()
+ }
+ private func shot(_ name: String) {
+ guard let dir = env["SHOTS_DIR"] else { return }
+ try? XCUIScreen.main.screenshot().pngRepresentation.write(to: URL(fileURLWithPath: dir).appendingPathComponent("\(name).png"))
+ }
+ private func element(_ id: String) -> XCUIElement { app.descendants(matching: .any)[id].firstMatch }
+ private func gone(_ e: XCUIElement, _ seconds: Double = 4) -> Bool {
+ let p = NSPredicate(format: "exists == false")
+ return XCTWaiter().wait(for: [XCTNSPredicateExpectation(predicate: p, object: e)], timeout: seconds) == .completed
+ }
+
+ func testTheGearOpensTheAppSettings() {
+ launch()
+ app.buttons["Settings"].firstMatch.tap()
+ XCTAssert(element("Read replies aloud").waitForExistence(timeout: 5), "the app's settings show")
+ XCTAssert(app.staticTexts["Answers in"].exists)
+ sleep(2); shot("settings")
+ app.swipeDown(velocity: .fast)
+ XCTAssert(gone(element("Read replies aloud")), "dragged down, the card goes away")
+ }
+
+ func testATapOutsideThePutsTheKeyboardAway() {
+ launch()
+ let field = element("message")
+ XCTAssert(field.waitForExistence(timeout: 5))
+ field.tap()
+ XCTAssert(app.keyboards.firstMatch.waitForExistence(timeout: 4), "typing shows the keyboard")
+ shot("keyboard")
+ element("state-lane").tap() // beside the character: the conversation, never a photo
+ XCTAssert(gone(app.keyboards.firstMatch), "a tap on the conversation puts it away")
+ }
+
+ func testTheConversationStaysAtTheBottomAfterTheKeyboard() {
+ launch(["-demoConversation", "24"]) // long enough to scroll, whatever the hub has
+ let last = element("last-line"), field = element("message"), mic = element("mic")
+ XCTAssert(last.waitForExistence(timeout: 6) && field.exists && mic.exists)
+ sleep(2)
+ // the gap between the newest line and the box (the mic sits at a fixed place in it)
+ let gap = { mic.frame.minY - last.frame.maxY }
+ let gap0 = gap()
+ shot("kb-0-rest")
+ field.tap()
+ XCTAssert(app.keyboards.firstMatch.waitForExistence(timeout: 4))
+ sleep(1)
+ let gapUp = gap()
+ shot("kb-1-up")
+ element("state-lane").tap()
+ XCTAssert(gone(app.keyboards.firstMatch))
+ sleep(1)
+ let gap1 = gap()
+ shot("kb-2-down")
+ XCTAssert(abs(gapUp - gap0) < 6, "with the keyboard up, the newest line still sits on the box (\(gap0) → \(gapUp))")
+ XCTAssert(abs(gap1 - gap0) < 6, "after the keyboard, the newest line is back on the box (\(gap0) → \(gap1))")
+ }
+
+ func testAHoldWithoutADragLeavesNothingLifted() {
+ launch()
+ app.buttons["Agents"].tap()
+ let row = element("agent-noodle")
+ XCTAssert(row.waitForExistence(timeout: 4))
+ row.press(forDuration: 1.0) // lifted, then let go where it is
+ sleep(1)
+ XCTAssertEqual(row.value as? String ?? "", "", "the tile settles back down")
+ let rows = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'agent-' AND value == 'Lifted'"))
+ XCTAssertEqual(rows.count, 0, "no tile stays lifted")
+ }
+
+ func testThePlusMenuMovesNothing() {
+ launch()
+ let last = element("last-line"), character = element("character")
+ XCTAssert(last.waitForExistence(timeout: 6))
+ sleep(2)
+ let y0 = last.frame.maxY, c0 = character.frame
+ app.buttons["Add photos or files"].tap()
+ XCTAssert(app.buttons["Files"].waitForExistence(timeout: 3))
+ sleep(1)
+ XCTAssertEqual(last.frame.maxY, y0, accuracy: 2, "the conversation stays where it is")
+ XCTAssertEqual(character.frame.minY, c0.minY, accuracy: 2, "and so does the character")
+ app.swipeDown() // a scroll behind it closes it, like a tap
+ XCTAssert(gone(app.buttons["Files"]), "a scroll closes the menu")
+ }
+
+ func testAMessagesMenuCopiesAndMutes() {
+ launch()
+ let last = app.staticTexts["Done, the test file is removed."].firstMatch
+ guard last.waitForExistence(timeout: 6) else { return } // that line is in this Mac's conversation
+ last.press(forDuration: 0.8)
+ XCTAssert(app.buttons["Copy"].waitForExistence(timeout: 3), "press and hold: Copy")
+ let mute = app.buttons["Mute replies"], unmute = app.buttons["Read replies aloud"]
+ XCTAssert(mute.exists || unmute.exists, "and mute")
+ sleep(1); shot("message-menu")
+ if mute.exists {
+ mute.tap()
+ last.press(forDuration: 0.8)
+ XCTAssert(app.buttons["Read replies aloud"].waitForExistence(timeout: 3), "muted: it offers reading aloud again")
+ app.buttons["Read replies aloud"].tap() // put it back
+ } else { unmute.tap() }
+ }
+
+ func testTappingTheMicListensUntilSendOrCancel() {
+ launch(["-quiet", "YES"])
+ let mic = element("mic")
+ XCTAssert(mic.waitForExistence(timeout: 5))
+ mic.tap()
+ XCTAssert(element("cancel-talk").waitForExistence(timeout: 3), "a tap starts listening: × shows")
+ XCTAssert(app.buttons["Send"].exists || mic.label == "Send", "and the mic is now send")
+ sleep(2)
+ shot("listening-tap")
+ element("cancel-talk").tap()
+ XCTAssert(gone(element("cancel-talk")), "× stops it")
+ mic.tap()
+ XCTAssert(element("cancel-talk").waitForExistence(timeout: 3))
+ sleep(1)
+ mic.tap() // ↑: sends what it heard
+ XCTAssert(gone(element("cancel-talk")), "↑ sends it")
+ }
+
+ func testHoldingTheMicListensAndSlidingLeftCancels() {
+ launch(["-quiet", "YES"]) // the Simulator's stand-in microphone
+ let mic = element("mic")
+ XCTAssert(mic.waitForExistence(timeout: 5))
+ let start = mic.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
+ start.press(forDuration: 1.0, thenDragTo: start.withOffset(CGVector(dx: -150, dy: 0)), withVelocity: .slow, thenHoldForDuration: 0.6)
+ sleep(1)
+ XCTAssert(mic.exists, "the microphone is back once you let go")
+ shot("after-cancel")
+ }
+
+ func testAfterACancelTheLaneStopsSayingListening() {
+ launch(["-quiet", "YES"])
+ let mic = element("mic"), lane = element("state-lane"), field = element("message")
+ XCTAssert(mic.waitForExistence(timeout: 5) && element("character").waitForExistence(timeout: 8))
+ sleep(2)
+ // the keyboard up first: the hold puts it away as listening starts, so the screen has redrawn with Listening in
+ // the lane before the cancel
+ field.tap()
+ XCTAssert(app.keyboards.firstMatch.waitForExistence(timeout: 4))
+ sleep(1)
+ let start = mic.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
+ start.press(forDuration: 1.5, thenDragTo: start.withOffset(CGVector(dx: -150, dy: 0)), withVelocity: .slow, thenHoldForDuration: 0.3)
+ let end = Date().addingTimeInterval(0.5)
+ var listening = true
+ repeat { listening = lane.exists && lane.label.contains("Listening") } while listening && Date() < end
+ shot("lane-after-cancel")
+ XCTAssertFalse(listening, "let go on ×: within half a second the lane no longer says Listening (\(lane.exists ? lane.label : "no lane"))")
+ }
+
+ func testTheAgentsReorderAndOpenTheirSettings() {
+ launch()
+ app.buttons["Agents"].tap()
+ XCTAssert(element("agent-ray").waitForExistence(timeout: 4))
+ sleep(1)
+ let rows = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'agent-'")).allElementsBoundByIndex
+ .sorted { $0.frame.minY < $1.frame.minY }
+ XCTAssert(rows.count >= 3)
+ let first = element(rows[0].identifier), third = rows[2]
+ let y0 = first.frame.midY
+ shot("agents")
+ first.press(forDuration: 0.8, thenDragTo: third, withVelocity: .slow, thenHoldForDuration: 0.3)
+ sleep(1)
+ XCTAssert(first.frame.midY > y0 + 40, "\(rows[0].identifier) moved down to the third place (\(y0) → \(first.frame.midY))")
+ shot("agents-reordered")
+ element("settings-ray").tap()
+ XCTAssert(element("part-voice").waitForExistence(timeout: 5), "… opens Ray's card")
+ shot("agent-settings")
+ }
+
+ func testTheNameAtTheTopOpensItsCard() {
+ launch()
+ let name = element("name-button")
+ XCTAssert(name.waitForExistence(timeout: 8), "the bar shows the agent's name")
+ name.tap()
+ XCTAssert(element("part-voice").waitForExistence(timeout: 5), "a tap on it opens its card")
+ }
+
+ func testTheNewestLineSitsJustAboveTheCharacter() {
+ launch(["-demoConversation", "24"]) // long enough to scroll, whatever the hub has
+ let last = element("last-line"), character = element("character")
+ XCTAssert(last.waitForExistence(timeout: 8) && character.exists)
+ sleep(2)
+ let gap = character.frame.minY - last.frame.maxY
+ XCTAssert(gap > -4 && gap < 40, "the newest line ends just above the character (gap \(gap))")
+ let field = element("message")
+ XCTAssert(character.frame.minX < 20 && character.frame.maxY <= field.frame.minY, "which stands at the bottom left, above the box (\(character.frame), the field \(field.frame))")
+ shot("dock")
+ }
+
+ func testTheCharacterScrollsWithTheConversation() {
+ launch(["-demoConversation", "24"]) // long enough to scroll, whatever the hub has
+ let character = element("character"), last = element("last-line")
+ XCTAssert(character.waitForExistence(timeout: 8) && last.exists)
+ sleep(2)
+ let y0 = character.frame.minY
+ app.swipeDown(velocity: .slow) // back up the conversation
+ sleep(1)
+ XCTAssert(!character.exists || character.frame.minY > y0 + 100 || !character.isHittable,
+ "it's the conversation's last row: it goes down with it (\(y0) → \(character.exists ? character.frame.minY : -1))")
+ shot("scrolled-back")
+ app.swipeUp(velocity: .fast); app.swipeUp(velocity: .fast)
+ sleep(1)
+ XCTAssert(character.waitForExistence(timeout: 3) && abs(character.frame.minY - y0) < 4, "and comes back at the end")
+ }
+
+ /// The left edge: a swipe in opens the agents; a vertical scroll or a tap there is the conversation's.
+ func testTheLeftEdgeOpensTheAgentsAndLetsTheRestThrough() {
+ launch(["-demoConversation", "24"]) // long enough to scroll, whatever the hub has
+ let last = element("last-line"), character = element("character")
+ XCTAssert(last.waitForExistence(timeout: 8))
+ sleep(2)
+ let y0 = last.frame.minY
+ app.coordinate(withNormalizedOffset: CGVector(dx: 0.01, dy: 0.4))
+ .press(forDuration: 0.05, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.02, dy: 0.75)), withVelocity: .slow, thenHoldForDuration: 0.1)
+ sleep(1)
+ XCTAssert(last.frame.minY > y0 + 60, "a scroll from the edge scrolls the conversation (\(y0) → \(last.frame.minY))")
+ XCTAssert(!element("agent-noodle").isHittable, "and doesn't open the agents")
+ app.swipeUp(velocity: .fast); app.swipeUp(velocity: .fast); sleep(1)
+ let c = character.frame
+ app.coordinate(withNormalizedOffset: .zero).withOffset(CGVector(dx: c.minX + 8, dy: c.midY)).tap()
+ sleep(1)
+ XCTAssert(character.frame.height > c.height * 2, "a tap on the character's left edge brings it in front")
+ app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.9)).tap(); sleep(1)
+ app.coordinate(withNormalizedOffset: CGVector(dx: 0.0, dy: 0.5))
+ .press(forDuration: 0.05, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.7, dy: 0.5)), withVelocity: .fast, thenHoldForDuration: 0.05)
+ XCTAssert(element("agent-noodle").waitForExistence(timeout: 3) && element("agent-noodle").isHittable, "a swipe in from the edge opens the agents")
+ shot("edge-agents")
+ }
+
+ /// Each agent's conversation opens at its end: its newest line, and the character under it, above the box.
+ func testSwitchingAgentsOpensOnTheNewestLine() {
+ launch(["-demoConversation", "24"]) // long enough to scroll, whatever the hub has
+ let character = element("character"), field = element("message")
+ XCTAssert(character.waitForExistence(timeout: 8))
+ for id in ["noodle", "ray", "noodle"] {
+ app.buttons["Agents"].tap()
+ XCTAssert(element("agent-\(id)").waitForExistence(timeout: 4))
+ element("agent-\(id)").tap()
+ sleep(2)
+ XCTAssert(character.waitForExistence(timeout: 4) && character.isHittable, "\(id): the character is on screen")
+ XCTAssert(abs(character.frame.maxY - (field.frame.minY - 8)) < 30, "\(id): at the end, just above the box (\(character.frame.maxY), the field at \(field.frame.minY))")
+ let gap = character.frame.minY - element("last-line").frame.maxY
+ XCTAssert(gap > -4 && gap < 40, "\(id): under its newest line (gap \(gap))")
+ shot("switched-\(id)")
+ }
+ }
+
+ func testWhileItWorksTheLaneShowsItsStep() {
+ launch(["-working", "YES"])
+ let lane = element("state-lane")
+ XCTAssert(lane.waitForExistence(timeout: 8))
+ sleep(2)
+ XCTAssert(lane.label.contains("Running tests") && lane.label.contains("npm test") && !lane.label.contains("Bash"),
+ "beside it: what it's doing in words, and exactly what on (\(lane.label))")
+ XCTAssert(lane.frame.minX >= element("character").frame.maxX - 4, "to the right of the character (\(lane.frame), \(element("character").frame))")
+ shot("working-lane")
+ }
+
+ /// Opens the page only (a pick would restart a real agent): how it asks before acting, its runtime's setting first.
+ func testThePermissionsPageShowsHowItAsks() {
+ launch(["-sheet", "ray"])
+ let row = element("permission-row")
+ XCTAssert(row.waitForExistence(timeout: 6), "the card has a Permissions row")
+ row.tap()
+ XCTAssert(element("permission-own").waitForExistence(timeout: 6), "it opens the modes: its runtime's setting first")
+ for id in ["permission-default", "permission-acceptEdits", "permission-auto"] { XCTAssert(element(id).exists, "and \(id)") }
+ XCTAssert(app.staticTexts["Asks first"].exists, "Asks first, in words")
+ shot("permissions")
+ }
+
+ /// Opens the page only: a pick would restart a real agent (the hub's tests switch a stand-in's model).
+ func testTheModelPageShowsWhatItRunsOn() {
+ launch(["-sheet", "ray"])
+ let row = element("model-row")
+ XCTAssert(row.waitForExistence(timeout: 6), "the card has a Model row")
+ sleep(2)
+ shot("model-row")
+ row.tap()
+ XCTAssert(element("model-own").waitForExistence(timeout: 5), "it opens the models: the default first")
+ XCTAssert(element("model-opus").exists && element("model-sonnet").exists && element("model-fable").exists, "and each model Claude Code offers")
+ XCTAssert(element("model-own").isSelected, "Ray has no model of its own: the default is the one picked")
+ shot("models")
+ }
+
+ /// Opened before the models come back, the page waits for them: it never says the Mac can't be reached.
+ func testTheModelPageAsksBeforeItSaysTheMacIsOutOfReach() {
+ launch(["-sheet", "ray"])
+ let row = element("model-row")
+ XCTAssert(row.waitForExistence(timeout: 6))
+ row.tap() // at once, while the card is still asking
+ let unreachable = app.staticTexts["Can't reach your Mac"]
+ let deadline = Date().addingTimeInterval(5)
+ while !element("model-own").exists && Date() < deadline {
+ XCTAssertFalse(unreachable.exists, "it says it's asking, not that the Mac is out of reach")
+ }
+ XCTAssert(element("model-own").exists, "and the models come")
+ }
+
+ /// Back on the Model and Voice pages is a plain chevron; the swipe from the left edge goes back too. Opens the
+ /// pages only: a pick would change a real agent.
+ func testTheCardsPagesGoBackByTheChevronAndTheEdge() {
+ launch(["-sheet", "ray"])
+ let row = element("model-row")
+ XCTAssert(row.waitForExistence(timeout: 6))
+ row.tap()
+ XCTAssert(element("model-own").waitForExistence(timeout: 5))
+ sleep(1); shot("models-page")
+ element("back").tap()
+ XCTAssert(gone(element("model-own")) && row.waitForExistence(timeout: 2), "the chevron goes back to the card")
+ row.tap()
+ XCTAssert(element("model-own").waitForExistence(timeout: 5))
+ let edge = app.coordinate(withNormalizedOffset: CGVector(dx: 0.005, dy: 0.5))
+ edge.press(forDuration: 0.05, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.85, dy: 0.5)))
+ XCTAssert(gone(element("model-own")), "a swipe from the left edge goes back")
+ let voice = app.buttons.matching(NSPredicate(format: "label BEGINSWITH 'Voice'")).firstMatch
+ XCTAssert(voice.waitForExistence(timeout: 2))
+ voice.tap()
+ XCTAssert(element("back").waitForExistence(timeout: 3))
+ XCTAssert(app.staticTexts["British"].waitForExistence(timeout: 6) || app.staticTexts["BRITISH"].exists, "the voices come")
+ sleep(1); shot("voices-page")
+ element("back").tap()
+ XCTAssert(row.waitForExistence(timeout: 3), "back on the card")
+ }
+
+ func testTheMicClosesThePlusMenu() {
+ launch(["-quiet", "YES"])
+ let mic = element("mic")
+ XCTAssert(mic.waitForExistence(timeout: 5))
+ app.buttons["Add photos or files"].tap()
+ XCTAssert(app.buttons["Files"].waitForExistence(timeout: 3))
+ mic.tap()
+ XCTAssert(gone(app.buttons["Files"], 2), "the menu goes the moment the mic is touched")
+ XCTAssert(element("cancel-talk").waitForExistence(timeout: 3), "and it listens")
+ shot("mic-after-menu")
+ element("cancel-talk").tap()
+ XCTAssert(gone(element("cancel-talk")))
+ }
+
+ func testASoulPartEditsInPlaceAboveTheKeyboard() {
+ launch(["-sheet", "ray"])
+ let part = element("part-voice")
+ XCTAssert(part.waitForExistence(timeout: 6))
+ part.tap()
+ let field = app.textViews.firstMatch.exists ? app.textViews.firstMatch : app.textFields.firstMatch
+ XCTAssert(field.waitForExistence(timeout: 3), "the part turns into a field")
+ XCTAssert(app.keyboards.firstMatch.waitForExistence(timeout: 4))
+ sleep(1)
+ let kb = app.keyboards.firstMatch.frame
+ XCTAssert(field.frame.maxY < kb.minY, "the field sits above the keyboard (\(field.frame.maxY) < \(kb.minY))")
+ XCTAssert(app.buttons["Save"].frame.maxY < kb.minY, "and so does Save")
+ shot("soul-editing")
+ app.buttons["Cancel"].firstMatch.tap()
+ XCTAssert(gone(app.buttons["Save"]))
+ }
+
+ func testTheCharacterComesToTheFrontAndGoesBack() {
+ launch()
+ let character = element("character")
+ XCTAssert(character.waitForExistence(timeout: 5))
+ let small = character.frame.height
+ character.tap()
+ sleep(1)
+ XCTAssert(character.frame.height > small * 2, "a tap brings it in front, big")
+ shot("front")
+ app.coordinate(withNormalizedOffset: CGVector(dx: 0.12, dy: 0.9)).tap()
+ sleep(1)
+ XCTAssert(character.frame.height < small * 1.2, "a tap outside puts it back")
+ }
+
+ func testThePlusOffersPhotosAndFiles() {
+ launch()
+ app.buttons["Add photos or files"].tap()
+ XCTAssert(app.buttons["Photo Library"].waitForExistence(timeout: 3) && app.buttons["Files"].exists)
+ sleep(1); shot("plus")
+ app.buttons["Close"].firstMatch.tap()
+ XCTAssert(gone(app.buttons["Photo Library"]))
+ }
+
+ func testAPictureZoomsAndCloses() throws {
+ let id = try XCTUnwrap(env["VIEWER_ID"], "set TEST_RUNNER_VIEWER_ID to an artifact id")
+ launch(["-viewer", id])
+ let view = app.scrollViews["viewer-scroll"]
+ XCTAssert(view.waitForExistence(timeout: 8))
+ sleep(2)
+ view.pinch(withScale: 3, velocity: 3)
+ sleep(1)
+ let z = Double(String((view.value as? String ?? "zoom 1").dropFirst(5))) ?? 1
+ XCTAssert(z > 1.8, "pinching zooms in (zoom \(z))")
+ shot("viewer-zoomed")
+ view.doubleTap()
+ sleep(1)
+ XCTAssert((view.value as? String) == "zoom 1.0", "a double tap zooms back out")
+ app.swipeDown(velocity: .fast)
+ XCTAssert(gone(view), "dragged down, the card goes away")
+ }
+}
+
+/// Every screen and state, as screenshots in TEST_RUNNER_SHOTS_DIR, for reviewing the design. Sends no orders.
+final class ChumsPhoneTour: XCTestCase {
+ private let env = ProcessInfo.processInfo.environment
+ private func shot(_ name: String) {
+ guard let dir = env["SHOTS_DIR"] else { return }
+ try? XCUIScreen.main.screenshot().pngRepresentation.write(to: URL(fileURLWithPath: dir).appendingPathComponent("tour-\(name).png"))
+ }
+ private func run(_ agent: String, _ args: [String] = []) -> XCUIApplication {
+ let app = XCUIApplication()
+ app.launchArguments = ["-agent", agent] + args
+ app.launch()
+ sleep(3)
+ return app
+ }
+
+ func testTour() {
+ var app = run("ray")
+ shot("01-conversation")
+ app.descendants(matching: .any)["message"].firstMatch.tap(); sleep(1)
+ shot("02-typing")
+ app.descendants(matching: .any)["state-lane"].firstMatch.tap(); sleep(1)
+ app.buttons["Add photos or files"].tap(); sleep(1)
+ shot("03-plus")
+ app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.2)).tap(); sleep(1)
+ app.descendants(matching: .any)["character"].firstMatch.tap(); sleep(2)
+ shot("04-front")
+ app.coordinate(withNormalizedOffset: CGVector(dx: 0.12, dy: 0.9)).tap(); sleep(1)
+ app.buttons["Agents"].tap(); sleep(1)
+ shot("05-agents")
+ app.descendants(matching: .any)["settings-ray"].firstMatch.tap(); sleep(2)
+ shot("06-agent-settings")
+ app.swipeUp(); sleep(1)
+ shot("07-agent-settings-scrolled")
+ let ask = app.textFields.firstMatch.exists ? app.textFields.firstMatch : app.textViews.firstMatch
+ if ask.exists { ask.tap(); sleep(1); shot("08-soul-typing") }
+ app.terminate()
+
+ app = run("ray", ["-settings", "YES"])
+ shot("09-app-settings")
+ app.terminate()
+
+ app = run("stretch")
+ shot("10-empty-agent")
+ app.terminate()
+
+ app = run("ray", ["-approval", "YES"])
+ shot("13-approval")
+ app.terminate()
+
+ app = run("ray", ["-attach", "YES"])
+ shot("14-attachments")
+ app.terminate()
+
+ app = run("ray", ["-quiet", "YES", "-listen", "YES"])
+ sleep(1)
+ shot("15-listening")
+ app.terminate()
+
+ app = run("ray", ["-working", "YES"])
+ sleep(2)
+ shot("16-working")
+ app.terminate()
+
+ if let id = env["VIEWER_ID"] {
+ app = run("ray", ["-viewer", id])
+ sleep(2)
+ shot("11-viewer")
+ app.buttons["Share"].firstMatch.tap(); sleep(2)
+ shot("12-share")
+ app.terminate()
+ }
+ }
+}
diff --git a/app/ChumsPhoneWidgets/Widgets.swift b/app/ChumsPhoneWidgets/Widgets.swift
new file mode 100644
index 0000000..5179d59
--- /dev/null
+++ b/app/ChumsPhoneWidgets/Widgets.swift
@@ -0,0 +1,86 @@
+import AppIntents
+import SwiftUI
+import WidgetKit
+
+// Chums on the Home Screen, the Lock Screen and in Control Center. All black; the agents' faces; amber when one needs
+// you. A tap opens Chums on that agent; Allow and Deny answer an approval without opening it; Talk (and the Control,
+// which the Action Button can run) opens Chums already listening.
+
+@main
+struct ChumsWidgets: WidgetBundle {
+ var body: some Widget {
+ AgentWidget()
+ TeamWidget()
+ TalkControl()
+ }
+}
+
+struct AgentProvider: AppIntentTimelineProvider {
+ func placeholder(in context: Context) -> ChumsEntry { ChumsEntry(date: .now, state: WidgetHub.sample, pick: nil) }
+ func snapshot(for config: PickAgent, in context: Context) async -> ChumsEntry {
+ let s = context.isPreview ? WidgetHub.sample : (await WidgetHub.state() ?? WidgetHub.sample)
+ return await ChumsEntry.make(s, pick: config.agent?.id, family: context.family, size: context.displaySize)
+ }
+ func timeline(for config: PickAgent, in context: Context) async -> Timeline<ChumsEntry> {
+ let s = await WidgetHub.state()
+ // sooner while something's happening; the app refreshes them too whenever it sees a change
+ let busy = s?.agents.contains { $0.needs || $0.status == "working" } ?? false
+ let e = await ChumsEntry.make(s, pick: config.agent?.id, family: context.family, size: context.displaySize)
+ return Timeline(entries: [e], policy: .after(.now.addingTimeInterval(busy ? 300 : 900)))
+ }
+}
+
+struct TeamProvider: TimelineProvider {
+ func placeholder(in context: Context) -> ChumsEntry { ChumsEntry(date: .now, state: WidgetHub.sample, pick: nil) }
+ func getSnapshot(in context: Context, completion: @escaping (ChumsEntry) -> Void) {
+ Task { completion(ChumsEntry(date: .now, state: context.isPreview ? WidgetHub.sample : (await WidgetHub.state() ?? WidgetHub.sample), pick: nil)) }
+ }
+ func getTimeline(in context: Context, completion: @escaping (Timeline<ChumsEntry>) -> Void) {
+ Task {
+ let s = await WidgetHub.state()
+ let busy = s?.agents.contains { $0.needs || $0.status == "working" } ?? false
+ completion(Timeline(entries: [ChumsEntry(date: .now, state: s, pick: nil)], policy: .after(.now.addingTimeInterval(busy ? 300 : 900))))
+ }
+ }
+}
+
+// MARK: one agent
+
+struct AgentWidget: Widget {
+ var body: some WidgetConfiguration {
+ AppIntentConfiguration(kind: "chums.agent", intent: PickAgent.self, provider: AgentProvider()) { e in
+ AgentWidgetView(entry: e).containerBackground(.black, for: .widget)
+ }
+ .contentMarginsDisabled() // the watch's screen goes to the edges
+ .configurationDisplayName("Agent")
+ .description("One agent: what it's doing, Allow or Deny what it asks, and Talk.")
+ .supportedFamilies([.systemSmall, .systemMedium, .accessoryCircular, .accessoryRectangular, .accessoryInline])
+ }
+}
+
+// MARK: every agent
+
+struct TeamWidget: Widget {
+ var body: some WidgetConfiguration {
+ StaticConfiguration(kind: "chums.team", provider: TeamProvider()) { e in
+ TeamWidgetView(entry: e).containerBackground(.black, for: .widget)
+ }
+ .configurationDisplayName("Agents")
+ .description("Every agent at a glance; a tap opens one. What needs you comes first.")
+ .supportedFamilies([.systemLarge, .systemMedium])
+ }
+}
+
+// MARK: the Control: Control Center, the Lock Screen, the Action Button
+
+struct TalkControl: ControlWidget {
+ var body: some ControlWidgetConfiguration {
+ StaticControlConfiguration(kind: "chums.talk") {
+ ControlWidgetButton(action: TalkToAgent()) {
+ Label("Talk to Chums", systemImage: "waveform")
+ }
+ }
+ .displayName("Talk to Chums")
+ .description("Opens Chums listening to the agent you talk to.")
+ }
+}
diff --git a/app/ChumsWatch/AgentFace.swift b/app/ChumsWatch/AgentFace.swift
new file mode 100644
index 0000000..0ec16d0
--- /dev/null
+++ b/app/ChumsWatch/AgentFace.swift
@@ -0,0 +1,20 @@
+import SwiftUI
+
+/// An agent's face: its character, small, on a black disc with a hairline ring. Black, because several avatars are
+/// pictures on black (the pixel ones are a sprite in a black square): on black, there's no square to see.
+struct AgentFace: View {
+ let character: String
+ var size = 34.0
+ var body: some View {
+ ZStack {
+ Circle().fill(.black)
+ Image("avatar-\(Self.asset(character))").resizable().interpolation(Self.fullBleed.contains(Self.asset(character)) ? .high : .none).scaledToFit()
+ .padding(Self.fullBleed.contains(Self.asset(character)) ? 0 : size * 0.08)
+ }
+ .frame(width: size, height: size).clipShape(Circle())
+ .overlay(Circle().strokeBorder(.white.opacity(0.16), lineWidth: max(0.5, size / 80)))
+ }
+ /// Avatars that are pictures to the edge (rendered), not pixel art in the middle of the circle.
+ static let fullBleed: Set<String> = ["stretch", "squint", "ray", "tangle", "noodle"]
+ static func asset(_ c0: String) -> String { let c = CharacterKind.legacy[c0] ?? c0; return CharacterKind(rawValue: c) != nil ? c : CharacterKind.fallback.rawValue }
+}
diff --git a/app/ChumsWatch/Agents.swift b/app/ChumsWatch/Agents.swift
new file mode 100644
index 0000000..7ebbde8
--- /dev/null
+++ b/app/ChumsWatch/Agents.swift
@@ -0,0 +1,142 @@
+import SwiftUI
+
+/// The agents: every character is its own agent on the Mac (Claude Code or Codex), with its own soul, thread and
+/// conversation. The one on screen is the one you talk to; the others keep working and come to you when they're done
+/// or need you.
+enum Agents {
+ /// Lines from before there were agents were the first agent's.
+ static let fallback = "noodle"
+ /// Until the hub has said who's there: one per character.
+ static let known = SoulView.looks.map { AgentInfo(id: $0, name: CharacterKind(id: $0)?.name ?? $0, character: $0, status: "offline", line: nil, needs: false) }
+
+ /// What it's doing, in a few words, for its row and its pill.
+ static func status(_ a: AgentInfo) -> String {
+ switch a.status {
+ case "offline": return "Not running on your Mac"
+ case "working": return "Working"
+ case "compacting": return "Tidying its memory"
+ case "limited": return "Rate limited, resumes by itself"
+ case "blocked": return a.line.map { "Stuck: \($0)" } ?? "Stuck"
+ default: return a.needs ? (a.line.map { "Needs you: \($0)" } ?? "Needs you") : (a.line ?? "Idle")
+ }
+ }
+ /// Its color dot: amber needs you, white working, gray idle, dim not running, red stuck.
+ static func dot(_ a: AgentInfo) -> Color {
+ if a.needs { return Pal.amber }
+ switch a.status {
+ case "working", "compacting": return Pal.white
+ case "blocked": return Pal.red
+ case "offline": return Pal.dim
+ default: return Pal.gray
+ }
+ }
+}
+
+/// Who you talk to, then the settings. Opened from the faces at the top left. A tap on an agent talks to it; swiping
+/// its row left (Edit) opens its soul.
+struct AgentsView: View {
+ let agents: [AgentInfo]
+ @Binding var active: String
+ let settings: AnyView
+ let soul: (AgentInfo) -> AnyView
+ @Environment(\.dismiss) private var dismiss
+ /// The order you put them in (press and hold one, then drag it up or down), kept.
+ @AppStorage("characterOrder") private var orderRaw = ""
+ private var order: [String] {
+ let saved = orderRaw.split(separator: ",").map(String.init).filter { SoulView.looks.contains($0) }
+ return saved + SoulView.looks.filter { !saved.contains($0) }
+ }
+ @State private var path: [String] = (UserDefaults.standard.string(forKey: "openSoul")).map { [$0] } ?? [] // -openSoul <id>
+
+ var body: some View {
+ NavigationStack(path: $path) {
+ ScrollViewReader { proxy in
+ List {
+ // every character is its own agent: a tap talks to it, swiping its row left (Edit) opens its soul
+ Section {
+ ForEach(order, id: \.self) { c in
+ if let a = agents.first(where: { $0.id == c }) {
+ row(c, a).contentShape(Rectangle()).onTapGesture { active = a.id; Haptics.play(.click); dismiss() }
+ .swipeActions(edge: .trailing) {
+ Button { path.append(a.id) } label: { Label("Edit", systemImage: "pencil") }.tint(Color(white: 0.3))
+ }
+ .id(a.id)
+ } else {
+ row(c, nil).id(c) // a hub from before every character had an agent
+ }
+ }
+ .onMove { from, to in
+ var o = order; o.move(fromOffsets: from, toOffset: to)
+ orderRaw = o.joined(separator: ","); Haptics.play(.click)
+ }
+ } header: { Text("Characters") }
+ Section {
+ NavigationLink { settings } label: { Label("Settings", systemImage: "gearshape") }.id("settings")
+ }
+ }
+ .defaultScrollAnchor(UserDefaults.standard.bool(forKey: "listBottom") ? .bottom : .top) // Simulator captures
+ // Simulator captures: the scene driver scrolls, picks and opens as a finger would
+ .onChange(of: Capture.shared.listScroll) { _, id in
+ guard let id else { return }
+ withAnimation(.easeInOut(duration: 0.9)) { proxy.scrollTo(id, anchor: id == agents.first?.id ? .bottom : .center) }
+ }
+ .onChange(of: Capture.shared.pick) { _, id in
+ guard let id else { return }
+ active = id; Haptics.play(.click); dismiss(); Capture.shared.pick = nil
+ }
+ .onChange(of: Capture.shared.openSoul) { _, id in
+ guard let id else { return }
+ path.append(id); Capture.shared.openSoul = nil
+ }
+ }
+ .navigationDestination(for: String.self) { id in
+ if let a = agents.first(where: { $0.id == id }) { soul(a) }
+ }
+ }
+ .overlay { if ScreenModel.fakeVoice { TouchSpot(show: Capture.shared.touch).ignoresSafeArea() } }
+ }
+
+ /// An agent's row: its face and name, its status (and its dot), what it runs on, a check if it's the one you talk to.
+ private func row(_ c: String, _ a: AgentInfo?) -> some View {
+ HStack(spacing: 10) {
+ AgentFace(character: c, size: 34)
+ .overlay(alignment: .bottomTrailing) {
+ if let a { Circle().fill(Agents.dot(a)).frame(width: 9, height: 9).overlay(Circle().strokeBorder(.black, lineWidth: 1.5)) }
+ }
+ VStack(alignment: .leading, spacing: 1) {
+ Text(CharacterKind(id: c)?.name ?? c).font(.system(size: 15, weight: .semibold)).foregroundStyle(Pal.white)
+ if let a { Text(Agents.status(a)).font(.system(size: 12)).foregroundStyle(a.needs ? Pal.amber : Pal.gray).lineLimit(2) }
+ else { Text("Not on your Mac yet: update the hub").font(.system(size: 12)).foregroundStyle(Pal.dim).lineLimit(2) }
+ }
+ Spacer(minLength: 0)
+ if let a, a.id == active { Image(systemName: "checkmark").font(.system(size: 13, weight: .bold)).foregroundStyle(Pal.clay) }
+ }
+ .padding(.vertical, 2)
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// Another agent finished, asked, needs an approval or showed you something: its face, name and line, above the
+/// handle. A tap goes to that agent (and opens what it showed you); it goes away by itself after a while.
+struct AgentNotice: View {
+ let agent: AgentInfo
+ let line: String
+ let open: () -> Void
+ var body: some View {
+ HStack(spacing: 9) {
+ AgentFace(character: agent.character, size: 40)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(agent.name).font(.system(size: 14, weight: .semibold)).foregroundStyle(Pal.white).lineLimit(1)
+ Text(line).font(.system(size: 12)).foregroundStyle(Color(white: 0.75)).lineLimit(2)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(5).padding(.trailing, 10)
+ .background(Color(white: 0.13).opacity(0.96), in: RoundedRectangle(cornerRadius: 25, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 25, style: .continuous).strokeBorder(.white.opacity(0.1), lineWidth: 0.5))
+ .shadow(color: .black.opacity(0.5), radius: 8, y: 2)
+ .contentShape(RoundedRectangle(cornerRadius: 25, style: .continuous))
+ .onTapGesture { open() }
+ .accessibilityElement(children: .combine).accessibilityAddTraits(.isButton)
+ }
+}
diff --git a/app/ChumsWatch/Alerts.swift b/app/ChumsWatch/Alerts.swift
new file mode 100644
index 0000000..387bbdb
--- /dev/null
+++ b/app/ChumsWatch/Alerts.swift
@@ -0,0 +1,47 @@
+import UserNotifications
+#if os(watchOS)
+import WatchKit
+#else
+import UIKit
+#endif
+
+/// When Chums isn't in front (after a crown press, say), what needs you arrives as a notification: watchOS taps your
+/// wrist and shows it over the watch face, and tapping it opens Chums. While Chums is in front, even dimmed, the
+/// notification is dropped: the character and Chums's own haptics do the job. Local notifications need no push
+/// service, so they work with a free developer account.
+@MainActor
+enum Alerts {
+ private static let delegate = Delegate()
+
+ static func setUp() {
+ let c = UNUserNotificationCenter.current()
+ c.delegate = delegate
+ c.requestAuthorization(options: [.alert, .sound]) { _, _ in }
+ }
+
+ static func post(_ title: String, _ body: String) {
+#if os(watchOS)
+ guard WKApplication.shared().applicationState != .active else { return }
+#else
+ guard UIApplication.shared.applicationState != .active else { return }
+#endif
+ let content = UNMutableNotificationContent()
+ content.title = title
+ content.body = body
+ content.sound = .default
+ content.threadIdentifier = "chums"
+ UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil))
+ }
+
+ private final class Delegate: NSObject, UNUserNotificationCenterDelegate {
+ /// Chums is in front but dimmed. With keyring mode running, Chums taps your wrist itself, so the notification
+ /// would be a second tap; without it Chums can't tap you, so the notification shows and sounds.
+ func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
+#if os(watchOS)
+ await MainActor.run { KeepOn.shared.running } ? [] : [.banner, .sound]
+#else
+ [.banner, .sound]
+#endif
+ }
+ }
+}
diff --git a/app/ChumsWatch/Artifacts.swift b/app/ChumsWatch/Artifacts.swift
new file mode 100644
index 0000000..a98aa39
--- /dev/null
+++ b/app/ChumsWatch/Artifacts.swift
@@ -0,0 +1,266 @@
+import SwiftUI
+import ImageIO
+
+/// Something a session showed you, or you sent: a screenshot of the Mac's screen or an app window, a web page, an HTML
+/// page an agent made, an image, a PDF, a document, text or code, a table, a video. The hub keeps two pictures of it (a
+/// 160 px square for the pill, and the whole thing; the watch has no web engine, so it gets pictures), and, for the
+/// iPhone, what to open live (`view`: the page's address, or the original file).
+struct ArtifactView: Decodable, Equatable {
+ let type: String // url, html, pdf, video, doc, image, text
+ var name: String? = nil // the original file's name
+ var url: String? = nil // a web page's address
+ var ext: String? = nil
+ var size: Int? = nil
+}
+struct Artifact: Decodable, Equatable, Identifiable {
+ let id: String
+ let kind: String // screenshot, page, image, pdf, doc, text, table, video
+ let title: String
+ let from: String? // the app a screenshot was taken of
+ let w: Double, h: Double // the viewer picture's pixels
+ var view: ArtifactView? = nil // what the iPhone opens live (older artifacts have none: their picture)
+
+ /// What it is, under its title: "Screenshot · Safari", "Web page", "Image", "PDF".
+ var label: String {
+ switch kind {
+ case "screenshot": return from.map { $0 == "screen" ? "Screenshot · Screen" : "Screenshot · \($0)" } ?? "Screenshot"
+ case "page": return view?.type == "html" ? "Page" : "Web page"
+ case "pdf": return "PDF"
+ case "doc": return view?.ext.map { "Document · \($0.uppercased())" } ?? "Document"
+ case "text": return view?.ext.map { "Text · \($0)" } ?? "Text"
+ case "table": return "Table"
+ case "video": return "Video"
+ default: return "Image"
+ }
+ }
+ var symbol: String {
+ switch kind {
+ case "page": "safari"
+ case "pdf": "doc.richtext"
+ case "screenshot": "macwindow"
+ case "doc": "doc.text"
+ case "text": "text.alignleft"
+ case "table": "tablecells"
+ case "video": "play.rectangle"
+ default: "photo"
+ }
+ }
+}
+
+/// Fetches an artifact's pictures from the hub and decodes them off the main thread. Thumbnails are kept; a whole
+/// picture is decoded no larger than 8000 px on its long side (a long page is tall) and only the latest is kept.
+@MainActor
+final class ArtifactImages {
+ static let shared = ArtifactImages()
+ var hub: HubClient?
+ private var thumbs: [String: CGImage] = [:]
+ private var full: (id: String, image: CGImage)?
+
+ func cachedThumb(_ a: Artifact) -> CGImage? { thumbs[a.id] }
+ func thumb(_ a: Artifact) async -> CGImage? {
+ if let t = thumbs[a.id] { return t }
+ guard let data = await hub?.speech("/v1/artifact/\(a.id)/thumb"), let im = await Self.decode(data, max: 320) else { return nil }
+ thumbs[a.id] = im
+ if thumbs.count > 40 { thumbs.removeValue(forKey: thumbs.keys.first!) }
+ return im
+ }
+ func whole(_ a: Artifact) async -> CGImage? {
+ if let f = full, f.id == a.id { return f.image }
+ guard let data = await hub?.speech("/v1/artifact/\(a.id)/full"), let im = await Self.decode(data, max: 8000) else { return nil }
+ full = (a.id, im)
+ return im
+ }
+ nonisolated static func decode(_ data: Data, max: Int) async -> CGImage? {
+ await Task.detached(priority: .userInitiated) {
+ guard let src = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
+ let o: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: max,
+ kCGImageSourceShouldCacheImmediately: true, kCGImageSourceCreateThumbnailWithTransform: true]
+ return CGImageSourceCreateThumbnailAtIndex(src, 0, o as CFDictionary)
+ }.value
+ }
+}
+
+/// Its small picture: rounded, with a hairline edge; the kind's symbol until the picture arrives.
+struct ArtifactThumb: View {
+ let a: Artifact
+ var size = 38.0
+ @State private var image: CGImage?
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: size * 0.24, style: .continuous)
+ ZStack {
+ shape.fill(Color(white: 0.24))
+ if let image { Image(decorative: image, scale: 2).resizable().scaledToFill() }
+ else { Image(systemName: a.symbol).font(.system(size: size * 0.38, weight: .semibold)).foregroundStyle(Pal.gray) }
+ }
+ .frame(width: size, height: size).clipShape(shape)
+ .overlay(shape.strokeBorder(.white.opacity(0.14), lineWidth: 0.5))
+ .onAppear { image = ArtifactImages.shared.cachedThumb(a) }
+ .task(id: a.id) { if image == nil { image = await ArtifactImages.shared.thumb(a) } }
+ }
+}
+
+/// In the conversation: a pill with its picture, title and what it is. A tap opens it.
+struct ArtifactPill: View {
+ let a: Artifact
+ let open: () -> Void
+ var body: some View {
+ HStack(spacing: 9) {
+ ArtifactThumb(a: a, size: 42)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(a.title).font(.system(size: 14, weight: .semibold)).foregroundStyle(Pal.white).lineLimit(2)
+ .fixedSize(horizontal: false, vertical: true)
+ Text(a.label).font(.system(size: 11.5)).foregroundStyle(Pal.gray).lineLimit(1)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(5).padding(.trailing, 8)
+ .background(Color(white: 0.17).opacity(0.94), in: RoundedRectangle(cornerRadius: 24, style: .continuous))
+ .contentShape(RoundedRectangle(cornerRadius: 24, style: .continuous))
+ .onTapGesture { open() }
+ .accessibilityElement(children: .combine).accessibilityAddTraits(.isButton).accessibilityHint("Opens it")
+ }
+}
+
+/// On the main screen when one arrives: the same pill, raised, above the handle (the line that came with it is spoken
+/// and in the conversation). It goes away by itself after a while; a tap opens it.
+struct ArtifactToast: View {
+ let a: Artifact
+ let line: String
+ let open: () -> Void
+ var body: some View {
+ HStack(spacing: 9) {
+ ArtifactThumb(a: a, size: 42)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(a.title).font(.system(size: 14, weight: .semibold)).foregroundStyle(Pal.white).lineLimit(2)
+ .fixedSize(horizontal: false, vertical: true)
+ Text(a.label).font(.system(size: 11.5)).foregroundStyle(Color(white: 0.72)).lineLimit(1)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(5).padding(.trailing, 10)
+ .background(Color(white: 0.13).opacity(0.96), in: RoundedRectangle(cornerRadius: 25, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 25, style: .continuous).strokeBorder(.white.opacity(0.1), lineWidth: 0.5))
+ .shadow(color: .black.opacity(0.5), radius: 8, y: 2)
+ .contentShape(RoundedRectangle(cornerRadius: 25, style: .continuous))
+ .onTapGesture { open() }
+ .accessibilityElement(children: .combine).accessibilityAddTraits(.isButton).accessibilityHint("Opens it")
+ }
+}
+
+/// The whole artifact, full screen. It opens fitted to the width; the crown or a drag scrolls it; a double tap zooms in
+/// where you tapped (and back out); a drag down from the top, or the × at the top left, closes it. Its title shows for
+/// a moment at the bottom; a hairline on the right shows where you are in a long one.
+struct ArtifactViewer: View {
+ let a: Artifact
+ let close: () -> Void
+ @State private var image: CGImage?
+ @State private var zoom = 1.0
+ @State private var offset = CGPoint.zero // the picture's top left, in screen points
+ @State private var start = CGPoint.zero
+ @State private var dragging = false
+ @State private var pull = 0.0 // dragged down past the top: closes past 60 pt
+ @State private var crown = 0.0
+ @State private var titleShown = true
+ @State private var indicator = false
+ @State private var hideIndicator: Task<Void, Never>?
+ @FocusState private var focused: Bool
+ private static let zoomIn = 2.6
+
+ var body: some View {
+ GeometryReader { g in
+ let S = g.size, fitW = S.width, fitH = fitW * a.h / max(1, a.w)
+ let cw = fitW * zoom, ch = fitH * zoom
+ let maxY = max(0, ch - S.height)
+ ZStack(alignment: .topLeading) {
+ Color.black
+ picture(cw, ch)
+ .offset(x: offset.x, y: (ch < S.height ? (S.height - ch) / 2 : offset.y) + pull)
+ .scaleEffect(1 - min(pull, 120) / 900, anchor: .top)
+ // where you are in a long one
+ if maxY > 40 {
+ let k = S.height / ch, top = -offset.y / ch * S.height
+ Capsule().fill(.white.opacity(0.55))
+ .frame(width: 2.5, height: max(14, S.height * k))
+ .offset(x: S.width - 5, y: top)
+ .opacity(indicator || dragging ? 1 : 0)
+ .animation(.easeOut(duration: 0.3), value: indicator || dragging)
+ }
+ // the title, for a moment
+ VStack { Spacer()
+ Text(a.title).font(.system(size: 12, weight: .semibold)).foregroundStyle(Pal.white).lineLimit(1)
+ .padding(.horizontal, 10).padding(.vertical, 5)
+ .background(.black.opacity(0.62), in: Capsule())
+ .padding(.bottom, 10)
+ }
+ .frame(maxWidth: .infinity).opacity(titleShown ? 1 : 0).allowsHitTesting(false)
+ // close
+ Button(action: close) {
+ Image(systemName: "xmark").font(.system(size: 13, weight: .bold)).foregroundStyle(Pal.white)
+ .frame(width: 30, height: 30).background(.black.opacity(0.6), in: Circle())
+ .overlay(Circle().strokeBorder(.white.opacity(0.18), lineWidth: 0.5))
+ .frame(width: 50, height: 50).contentShape(Rectangle())
+ }
+ .buttonStyle(.plain).padding(.leading, 2).padding(.top, 2)
+ .accessibilityLabel("Close")
+ if image == nil { ProgressView().tint(Pal.white).frame(maxWidth: .infinity, maxHeight: .infinity) }
+ }
+ .contentShape(Rectangle())
+ .gesture(DragGesture(minimumDistance: 3)
+ .onChanged { v in
+ if !dragging { dragging = true; start = offset }
+ var o = CGPoint(x: start.x + v.translation.width, y: start.y + v.translation.height)
+ // pulled down from the top: the picture follows and shrinks a little, to close
+ if start.y >= -0.5 && v.translation.height > 0 && abs(v.translation.width) < v.translation.height { pull = v.translation.height; o.y = 0 } else { pull = 0 }
+ offset = clamp(o, cw, ch, S); crown = -offset.y / 100; scrolled()
+ }
+ .onEnded { v in
+ dragging = false
+ if pull > 60 { close(); return }
+ let fling = CGPoint(x: start.x + v.predictedEndTranslation.width, y: start.y + v.predictedEndTranslation.height)
+ withAnimation(.smooth(duration: 0.45)) { pull = 0; offset = clamp(fling, cw, ch, S) }
+ crown = -offset.y / 100; scrolled()
+ })
+ .onTapGesture(count: 2) { p in
+ // zoom in around the finger, or back out to the width
+ let z2 = zoom > 1.01 ? 1.0 : Self.zoomIn
+ let base = CGPoint(x: offset.x, y: ch < S.height ? (S.height - ch) / 2 : offset.y)
+ let o = CGPoint(x: p.x - (p.x - base.x) * z2 / zoom, y: p.y - (p.y - base.y) * z2 / zoom)
+ Haptics.play(.click)
+ withAnimation(.smooth(duration: 0.32)) { zoom = z2; offset = clamp(o, fitW * z2, fitH * z2, S) }
+ crown = -offset.y / 100
+ }
+#if os(watchOS)
+ .focusable().focused($focused)
+ .digitalCrownRotation($crown, from: 0, through: max(0.01, maxY / 100), by: nil, sensitivity: .medium,
+ isContinuous: false, isHapticFeedbackEnabled: true)
+#endif
+ .onChange(of: crown) { _, c in
+ guard !dragging else { return }
+ offset.y = clamp(CGPoint(x: offset.x, y: -c * 100), cw, ch, S).y; scrolled()
+ }
+ }
+ .ignoresSafeArea()
+ .task(id: a.id) {
+ focused = true
+ image = await ArtifactImages.shared.whole(a)
+ try? await Task.sleep(for: .seconds(2.2))
+ withAnimation(.easeOut(duration: 0.4)) { titleShown = false }
+ }
+ }
+
+ /// The position hairline shows while it scrolls and a moment after.
+ private func scrolled() {
+ indicator = true; hideIndicator?.cancel()
+ hideIndicator = Task { try? await Task.sleep(for: .seconds(1.2)); if !Task.isCancelled { indicator = false } }
+ }
+
+ @ViewBuilder private func picture(_ cw: Double, _ ch: Double) -> some View {
+ if let image { Image(decorative: image, scale: 1).resizable().interpolation(.high).frame(width: cw, height: ch) }
+ else { ArtifactThumb(a: a, size: min(cw, ch)).blur(radius: 6).opacity(0.6).frame(width: cw, height: ch, alignment: .top) }
+ }
+
+ /// Never past the picture's edges; a picture shorter than the screen stays centered (see the y in body).
+ private func clamp(_ o: CGPoint, _ cw: Double, _ ch: Double, _ S: CGSize) -> CGPoint {
+ CGPoint(x: min(0, max(S.width - cw, o.x)), y: min(0, max(min(0, S.height - ch), o.y)))
+ }
+}
diff --git a/app/ChumsWatch/Assets.xcassets/AppIcon.appiconset/Contents.json b/app/ChumsWatch/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 0000000..3bd45bd
--- /dev/null
+++ b/app/ChumsWatch/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,14 @@
+{
+ "images": [
+ {
+ "filename": "icon-1024.png",
+ "idiom": "universal",
+ "platform": "watchos",
+ "size": "1024x1024"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ }
+}
\ No newline at end of file
diff --git a/app/ChumsWatch/Assets.xcassets/AppIcon.appiconset/icon-1024.png b/app/ChumsWatch/Assets.xcassets/AppIcon.appiconset/icon-1024.png
new file mode 100644
index 0000000..4aec82b
Binary files /dev/null and b/app/ChumsWatch/Assets.xcassets/AppIcon.appiconset/icon-1024.png differ
diff --git a/app/ChumsWatch/Assets.xcassets/Contents.json b/app/ChumsWatch/Assets.xcassets/Contents.json
new file mode 100644
index 0000000..fe97fb1
--- /dev/null
+++ b/app/ChumsWatch/Assets.xcassets/Contents.json
@@ -0,0 +1 @@
+{"info": {"author": "xcode", "version": 1}}
\ No newline at end of file
diff --git a/app/ChumsWatch/Chat.swift b/app/ChumsWatch/Chat.swift
new file mode 100644
index 0000000..3ff32bd
--- /dev/null
+++ b/app/ChumsWatch/Chat.swift
@@ -0,0 +1,143 @@
+import SwiftUI
+
+/// One line of the conversation: what you said, what Chums said, or a note (an approval answered, an action Claude
+/// Code's auto mode refused).
+struct ChatLine: Identifiable, Equatable {
+ enum Who { case you, chums, note }
+ let id: String
+ let who: Who
+ let text: String
+ let artifact: Artifact?
+ var refused = false // Claude Code's auto mode refused an action, without asking you
+
+ init(_ s: Spoken) {
+ id = s.id; artifact = s.artifact; refused = s.kind == "refused"
+ switch s.kind {
+ case "echo":
+ who = .you
+ // the hub echoes an order as “what you said” (with the session's name first when there are several)
+ text = s.text.replacingOccurrences(of: "“", with: "").replacingOccurrences(of: "”", with: "")
+ case "verdict", "refused": who = .note; text = s.text
+ default: who = .chums; text = s.text
+ }
+ }
+}
+
+/// The conversation as a card of Liquid Glass that slides up from the handle at the bottom of the screen: the
+/// character stays visible through it, blurred. It opens at the newest message; the crown scrolls back. Dragging its
+/// top edge down puts it away. The balloons are nearly solid so the text reads over anything behind the glass.
+struct ChatPanel: View {
+ let lines: [ChatLine]
+ var open: (Artifact) -> Void = { _ in }
+ /// Simulator captures: scroll to a line (or "end"), as a finger would, over that many seconds.
+ var scroll: (id: String, seconds: Double)? = nil
+ @FocusState private var focused: Bool
+
+ static let card = UnevenRoundedRectangle(topLeadingRadius: 22, topTrailingRadius: 22)
+
+ var body: some View {
+ // the messages fill the whole card and scroll all the way to its top edge; the grabber floats over them
+ ZStack(alignment: .top) {
+ ScrollViewReader { proxy in
+ ScrollView {
+ VStack(spacing: 8) {
+ Color.clear.frame(height: 14).id("top") // at rest, the first message starts below the grabber
+ if lines.isEmpty {
+ Text("Hold the screen and talk; the conversation shows up here.")
+ .font(.system(size: 14)).foregroundStyle(Pal.gray).multilineTextAlignment(.center).padding(.top, 16)
+ }
+ ForEach(lines) { l in bubble(l).id(l.id) }
+ Color.clear.frame(height: 6).id("end")
+ }
+ .padding(.horizontal, 6)
+ }
+ .focusable().focused($focused)
+ .onAppear { proxy.scrollTo("end", anchor: .bottom); focused = true }
+ .onChange(of: lines.count) { withAnimation { proxy.scrollTo("end", anchor: .bottom) } }
+ .onChange(of: scroll?.id) { _, id in
+ guard let id, let s = scroll else { return }
+ withAnimation(.easeInOut(duration: s.seconds)) { proxy.scrollTo(id, anchor: id == "end" ? .bottom : .top) } // "top": the very start
+ }
+ }
+ Grabber().padding(.top, 6)
+ }
+ .clipShape(Self.card) // only the card's own edge clips
+ .glassEffect(.regular.tint(.black.opacity(0.32)), in: Self.card)
+ }
+
+ @ViewBuilder private func bubble(_ l: ChatLine) -> some View {
+ switch l.who {
+ case .you:
+ HStack {
+ Spacer(minLength: 24)
+ Text(l.text).font(.system(size: 15)).foregroundStyle(Pal.white).fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 10).padding(.vertical, 7)
+ .background(Color(hex: 0x3A3D42).opacity(0.92), in: RoundedRectangle(cornerRadius: 14))
+ }
+ case .chums:
+ VStack(alignment: .leading, spacing: 4) {
+ if l.artifact.map({ $0.title != l.text }) ?? true {
+ HStack {
+ Text(l.text).font(.system(size: 15)).foregroundStyle(Pal.white).fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 10).padding(.vertical, 7)
+ .background(Color(white: 0.17).opacity(0.94), in: RoundedRectangle(cornerRadius: 14))
+ Spacer(minLength: 24)
+ }
+ }
+ // something it showed you: a pill that opens it
+ if let a = l.artifact { ArtifactPill(a: a) { open(a) } }
+ }
+ case .note:
+ Text(l.text).font(.system(size: 11, weight: .medium)).foregroundStyle(Pal.white.opacity(0.75)).frame(maxWidth: .infinity)
+ .shadow(color: .black.opacity(0.6), radius: 2)
+ }
+ }
+}
+
+/// Simulator captures: what the scene driver asks screens it can't reach directly (the agents list, a soul) to do,
+/// as a finger would: scroll to a row, pick an agent, open a soul, press and let go of its button, save.
+@Observable final class Capture {
+ static let shared = Capture()
+ let touch = TouchShow()
+ var listScroll: String? // a row of the agents list ("settings" for the Settings row)
+ var pick: String? // an agent tapped in the list
+ var openSoul: String? // its soul opened (the Edit in its row)
+ var soulScroll: String? // "top" or "end"
+ var soulPress: Bool? // the soul's hold-to-change button: pressed (true), let go (false)
+ var soulSave = false // Save tapped
+}
+
+/// Simulator captures: where a finger is on the screen, drawn as a fingertip on the glass (a soft disc that presses in,
+/// holds, slides and lifts off), so a recording shows what was touched.
+@Observable final class TouchShow {
+ var at: CGPoint = .zero
+ var down = false
+ var visible = false
+}
+
+struct TouchSpot: View {
+ let show: TouchShow
+ var body: some View {
+ Circle()
+ .fill(RadialGradient(colors: [.white.opacity(0.42), .white.opacity(0.22)], center: .center, startRadius: 0, endRadius: 17))
+ .overlay(Circle().strokeBorder(.white.opacity(0.6), lineWidth: 1))
+ .frame(width: 34, height: 34)
+ .shadow(color: .black.opacity(0.35), radius: 5, y: 1)
+ .scaleEffect(show.visible ? (show.down ? 0.92 : 1.0) : 1.35)
+ .opacity(show.visible ? 1 : 0)
+ .position(show.at)
+ .animation(.easeOut(duration: 0.22), value: show.visible)
+ .animation(.spring(duration: 0.25, bounce: 0.3), value: show.down)
+ .allowsHitTesting(false)
+ }
+}
+
+/// The handle: on the screen's bottom edge to pull the conversation up, and on the card's top edge to put it away.
+struct Grabber: View {
+ /// Under the character: gray and short, so it doesn't read as a mouth under the eyes.
+ var quiet = false
+ var body: some View {
+ Capsule().fill(Color(white: quiet ? 0.4 : 0.86)).frame(width: quiet ? 28 : 46, height: quiet ? 4 : 5)
+ .shadow(color: .black.opacity(0.45), radius: 1.5, y: 0.5)
+ }
+}
diff --git a/app/ChumsWatch/ChumsWatch.entitlements b/app/ChumsWatch/ChumsWatch.entitlements
new file mode 100644
index 0000000..e10f430
--- /dev/null
+++ b/app/ChumsWatch/ChumsWatch.entitlements
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.developer.healthkit</key>
+ <true/>
+</dict>
+</plist>
diff --git a/app/ChumsWatch/ChumsWatchApp.swift b/app/ChumsWatch/ChumsWatchApp.swift
new file mode 100644
index 0000000..1e810a6
--- /dev/null
+++ b/app/ChumsWatch/ChumsWatchApp.swift
@@ -0,0 +1,516 @@
+import SwiftUI
+import WatchKit
+import CoreMotion
+
+@main
+struct ChumsWatchApp: App {
+ @WKApplicationDelegateAdaptor(ChumsAppDelegate.self) private var delegate
+ @State private var hub = HubClient()
+ @State private var keepOn = KeepOn.shared
+ @Environment(\.scenePhase) private var phase
+
+ init() { CharacterKind.migrate() }
+
+ var body: some Scene {
+ WindowGroup {
+ ChumsScreen(hub: hub, keepOn: keepOn)
+ .onChange(of: phase, initial: true) { old, p in
+ if keepOn.onEvent == nil { keepOn.onEvent = { [hub] in hub.event($0) } }
+ // in keyring mode the app keeps running with the screen dimmed, so it keeps listening to the hub
+ if p == .active || keepOn.running { hub.start() } else { hub.stop() }
+ if p == .active { Task { await keepOn.start() } }
+ hub.event(old == p ? "launch, build \(HubConfig.build), keyring \(keepOn.enabled ? "on" : "off")" : "app \(p == .active ? "active" : p == .inactive ? "inactive" : "background")")
+ }
+ .onChange(of: keepOn.running, initial: true) { _, r in hub.keyring = r; if r { hub.start() } }
+ }
+ }
+}
+
+/// The whole app is one screen: the character, drawn every frame, and the gestures on it.
+/// hold anywhere to talk · tap the character to poke it · stroke it to pet it
+/// drag and throw it (Physics) · hold the card to allow · tap × to deny · the faces at the top left: the agents
+/// shake the watch: the character is shaken, thrown or dizzied, each in its own way
+/// a pixel level is a game: turn the crown to walk, tap to jump
+/// just after the dimmed screen wakes, a touch held anywhere talks
+struct ChumsScreen: View {
+ let hub: HubClient
+ let keepOn: KeepOn
+ @State private var model: ScreenModel
+ @AppStorage("character") private var character = CharacterKind.fallback.rawValue
+ @AppStorage("agent") private var agent = Agents.fallback // who you talk to (its character is `character`)
+ @State private var notice: (agent: AgentInfo, line: Spoken)? // another agent has news: its pill above the handle
+ @State private var noticeHide: Task<Void, Never>?
+ @AppStorage("mode") private var mode = "world"
+ @AppStorage("demo") private var demo = false
+ @AppStorage("voice") private var voice = true
+ @AppStorage("stayOn") private var stayOn = true
+ @State private var crown = 0.0
+ @State private var showSettings = false
+ @State private var chatOpen = false // the conversation card is up
+ private static let chatTop = 30.0
+ @State private var chatPull = 0.0
+ @State private var chatDrop = 0.0
+ @State private var pulling = false
+ @State private var viewing: Artifact? // open full screen
+ @State private var toast: (artifact: Artifact, line: String)? // just arrived: a pill above the handle
+ @State private var toastHide: Task<Void, Never>?
+ @Environment(\.isLuminanceReduced) private var reduced
+ @State private var calm = false
+ private var touches: TouchShow { Capture.shared.touch } // Simulator captures: the fingertip drawn over the screen
+ @State private var chatScroll: (id: String, seconds: Double)? // a staged character holding still: 30 frames a second will do
+
+ init(hub: HubClient, keepOn: KeepOn) {
+ self.hub = hub
+ self.keepOn = keepOn
+ _model = State(initialValue: ScreenModel(hub: hub))
+ }
+
+ var body: some View {
+ GeometryReader { geo in
+ // the character keeps going behind the conversation card, at 30 frames a second (the glass over it blurs every
+ // frame); it holds still only under the settings and a picture, which cover it. Noodle's frames and Pix's
+ // pixels change at most 24 times a second, so they draw at 30; so do the Eyes when nothing moves fast
+ TimelineView(.animation(minimumInterval: reduced ? 1 : CharacterKind(id: character)?.framed == true || calm || chatOpen || pulling ? 1.0 / 30 : nil,
+ paused: showSettings || viewing != nil)) { tl in
+ Canvas { ctx, size in
+ let t0 = CFAbsoluteTimeGetCurrent()
+ model.frame(tl.date)
+ Renderer.draw(model.rig, ctx, size: size)
+ model.perf.drew((CFAbsoluteTimeGetCurrent() - t0) * 1000, at: tl.date)
+ }
+ }
+ .contentShape(Rectangle())
+ .accessibilityElement()
+ .accessibilityLabel(model.rig.label.isEmpty ? (CharacterKind(id: character)?.name ?? "Character") : model.rig.label)
+ .accessibilityHint("Hold the screen to talk")
+ .gesture(
+ DragGesture(minimumDistance: 0)
+ .onChanged { v in
+ if calm { calm = false }
+ if pulling { chatPull = max(0, -v.translation.height); return }
+ model.drag(v.location, in: geo.size)
+ // up from the handle at the bottom, before a hold turned into talking: the conversation follows the finger
+ if model.onHandle && v.translation.height < -10 && !model.talking {
+ model.cancelTouch(); pulling = true; chatPull = -v.translation.height
+ }
+ }
+ .onEnded { v in
+ if pulling {
+ pulling = false
+ withAnimation(.snappy(duration: 0.28)) { chatOpen = chatPull > 50 || v.predictedEndTranslation.height < -120; chatPull = 0 }
+ return
+ }
+ switch model.dragEnd(v.location, in: geo.size) {
+ case .settings: showSettings = true
+ case .chat: withAnimation(.snappy(duration: 0.28)) { chatOpen = true }
+ case .none: break
+ }
+ }
+ )
+ }
+ .overlay(alignment: .bottom) {
+ // the handle: always there; pull it up for the conversation
+ Grabber(quiet: true).padding(.bottom, 5)
+ .opacity(reduced || chatOpen ? 0 : 1).allowsHitTesting(false)
+ }
+ .overlay(alignment: .bottom) {
+ // another agent's news: a tap goes to that agent, and opens what it showed you
+ if let n = notice, toast == nil, !chatOpen, !reduced {
+ AgentNotice(agent: n.agent, line: n.line.artifact.map { "Showed you: \($0.title)" } ?? n.line.text) {
+ let a = n.line.artifact
+ withAnimation(.snappy(duration: 0.3)) { notice = nil; agent = n.agent.id }
+ if let a { open(a) }
+ }
+ .padding(.horizontal, 8).padding(.bottom, 16)
+ .transition(.move(edge: .bottom).combined(with: .opacity))
+ }
+ }
+ .overlay(alignment: .bottom) {
+ // something it showed you, just arrived: a tap opens it
+ if let t = toast, !chatOpen, !reduced {
+ ArtifactToast(a: t.artifact, line: t.line) { open(t.artifact) }
+ .padding(.horizontal, 8).padding(.bottom, 16)
+ .transition(.move(edge: .bottom).combined(with: .opacity))
+ }
+ }
+ .overlay {
+ if chatOpen || chatPull > 0 {
+ GeometryReader { g in
+ // the card stops under the clock (watchOS draws the time over everything)
+ ChatPanel(lines: model.conversation, open: open, scroll: chatScroll)
+ .frame(height: g.size.height - Self.chatTop)
+ .offset(y: chatOpen ? Self.chatTop + chatDrop : max(Self.chatTop, g.size.height - chatPull))
+ .overlay(alignment: .top) {
+ // the card's top edge: drag it down to put the card away. The zone is wider than the grabber: the
+ // whole band above the card (under the clock, where a finger reaching for it often lands) and a
+ // little into it
+ Color.clear.frame(height: Self.chatTop + 36).contentShape(Rectangle())
+ .offset(y: (chatOpen ? Self.chatTop + chatDrop : max(Self.chatTop, g.size.height - chatPull)) - Self.chatTop)
+ .gesture(DragGesture()
+ .onChanged { chatDrop = max(0, $0.translation.height) }
+ .onEnded { v in
+ withAnimation(.snappy(duration: 0.25)) {
+ if chatDrop > 50 || v.predictedEndTranslation.height > 120 { chatOpen = false }
+ chatDrop = 0
+ }
+ })
+ }
+ }
+ .transition(.move(edge: .bottom))
+ }
+ }
+ .overlay {
+ if let a = viewing {
+ ArtifactViewer(a: a) { withAnimation(.snappy(duration: 0.25)) { viewing = nil } }
+ .transition(.scale(scale: 0.86).combined(with: .opacity))
+ }
+ }
+ .overlay { if ScreenModel.fakeVoice { TouchSpot(show: touches) } }
+ .ignoresSafeArea()
+ .focusable(!chatOpen && viewing == nil)
+ // a small range that wraps around: a range of ±1,000,000 detents ran the watch out of memory on the first turn
+ .digitalCrownRotation($crown, from: 0, through: 60, by: 1, sensitivity: .medium,
+ isContinuous: true, isHapticFeedbackEnabled: true)
+ .onChange(of: crown) { old, new in
+ var d = new - old
+ if d > 30 { d -= 60 } else if d < -30 { d += 60 } // across the wrap
+ if calm { calm = false }
+ model.crown(d)
+ }
+ // switching agents: its character, its thread, its state (a recording already going keeps its agent)
+ .onChange(of: agent, initial: true) { _, id in
+ model.setAgent(id)
+ let c = model.controller.info(id).character
+ if c != character { character = c }
+ if notice?.agent.id == id { notice = nil }
+ }
+ .onChange(of: hub.state?.agents?.first(where: { $0.id == agent })?.character) { _, c in if let c, c != character { character = c } }
+ // the agent you talk to is gone from the Mac (an id from before every character was its own agent): talk to
+ // the one for the character on screen
+ .onChange(of: hub.state?.agents?.map(\.id)) { _, ids in
+ if let ids, !ids.isEmpty, !ids.contains(agent) { agent = ids.contains(character) ? character : (ids.contains(Agents.fallback) ? Agents.fallback : ids[0]) }
+ }
+ .onChange(of: character, initial: true) { _, v in
+ // a test launch (-testCharacter noodle) shows that character whoever you talk to, for this launch only
+ let k = CharacterKind(id: UserDefaults.standard.volatileDomain(forName: UserDefaults.argumentDomain)["testCharacter"] as? String ?? v) ?? .fallback
+ model.rig.character = k
+ }
+ .onChange(of: mode, initial: true) { _, v in model.rig.mode = StageMode(rawValue: v) ?? .world }
+ .onChange(of: demo, initial: true) { _, v in model.setDemo(v) }
+ .onChange(of: reduced, initial: true) { _, v in model.setDimmed(v) }
+ .onChange(of: chatOpen) { _, open in if open { model.controller.seen() } }
+ // the screen stays on while you hold the watch and look at it, and sleeps when it's put down (StayOn)
+ .onChange(of: stayOn, initial: true) { _, v in StayOn.shared.enabled = v }
+ .onChange(of: keepOn.problem, initial: true) { _, v in model.controller.notice = v }
+ .sheet(isPresented: $showSettings) {
+ AgentsView(agents: hub.state?.agents ?? Agents.known, active: $agent,
+ settings: AnyView(SettingsView(character: $character, mode: $mode, demo: $demo, voice: $voice, stayOn: $stayOn, keepOn: keepOn, report: { hub.event($0) })),
+ soul: { a in AnyView(SoulView(agent: a, model: model, hub: hub)) })
+ }
+#if targetEnvironment(simulator)
+ .task { // offline frames for recordings (OfflineRender)
+ if let spec = UserDefaults.standard.string(forKey: "render") { await OfflineRender.run(spec); exit(0) }
+ }
+#endif
+ .task {
+ // the frame rate follows the staged character: full while something moves fast, 30 when it's still
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .milliseconds(200))
+ let c = model.rig.staged?.calm ?? false
+ if c != calm { calm = c }
+ }
+ }
+ .task {
+ await model.prepare()
+ if UserDefaults.standard.bool(forKey: "openChat") { try? await Task.sleep(for: .seconds(8)); chatOpen = true } // for Simulator captures
+ if UserDefaults.standard.bool(forKey: "openSettings") { try? await Task.sleep(for: .seconds(3)); showSettings = true }
+ // another agent finished, asked, needs an approval or showed you something: its pill, and a tap on the wrist
+ model.controller.onBackground = { a, line in
+ Haptics.play(["question", "blocked"].contains(line.kind) ? .notification : .success)
+ withAnimation(.spring(duration: 0.4, bounce: 0.25)) { notice = (a, line) }
+ noticeHide?.cancel()
+ noticeHide = Task { try? await Task.sleep(for: .seconds(14)); if !Task.isCancelled { withAnimation(.easeOut(duration: 0.3)) { notice = nil } } }
+ }
+ model.onArtifact = { a, line in
+ toastHide?.cancel()
+ toastHide = Task {
+ // the pill sits where the words of a reply do: it waits until the reply has been said (and a moment more)
+ var quiet = 0.0, waited = 0.0
+ while quiet < 0.6 && waited < 20 {
+ try? await Task.sleep(for: .milliseconds(100)); waited += 0.1
+ quiet = model.rig.state == .speaking ? 0 : quiet + 0.1
+ }
+ guard !Task.isCancelled else { return }
+ withAnimation(.spring(duration: 0.4, bounce: 0.25)) { toast = (a, line) }
+ try? await Task.sleep(for: .seconds(14)); if !Task.isCancelled { withAnimation(.easeOut(duration: 0.3)) { toast = nil } }
+ }
+ }
+ // Simulator captures: open the newest artifact in the conversation (-openArtifact YES)
+ if UserDefaults.standard.bool(forKey: "openArtifact") {
+ try? await Task.sleep(for: .seconds(6))
+ if let a = model.conversation.last(where: { $0.artifact != nil })?.artifact { open(a) }
+ }
+ if UserDefaults.standard.bool(forKey: "selftest") { await model.selfTest(size: WKInterfaceDevice.current().screenBounds.size) { showSettings = $0 } }
+ if UserDefaults.standard.bool(forKey: "shakeDemo") { await model.shakeDemo() } // Simulator captures: no sensors there
+ if UserDefaults.standard.bool(forKey: "playDemo") { await model.playDemo(size: WKInterfaceDevice.current().screenBounds.size) }
+ if let scene = UserDefaults.standard.string(forKey: "scene") { await playScene(scene) }
+ if UserDefaults.standard.bool(forKey: "crownDemo") { await model.crownDemo() } // Simulator captures
+ }
+ }
+
+ /// Simulator captures (-scene <agent id> | switch | chat | soul, against a stand-in hub given with -hub): one agent's session
+ /// played through the real screen, as a person would: hold to talk, watch it work, hold to allow, open what it showed
+ /// you, look over the conversation. The hub side (what it says and does) is the stand-in's script.
+ private func playScene(_ name: String) async {
+ Recorder.fake = ScreenModel.fakeVoice
+ let size = WKInterfaceDevice.current().screenBounds.size
+ func pt(_ x: Double, _ y: Double) -> CGPoint { let f = Renderer.fit(size); return CGPoint(x: f.ox + x * f.s, y: f.oy + y * f.s) }
+ func wait(_ s: Double) async { try? await Task.sleep(for: .milliseconds(Int(s * 1000))) }
+ func until(_ limit: Double = 40, _ ok: () -> Bool) async {
+ let end = Date().addingTimeInterval(limit)
+ while !ok() && Date() < end { await wait(0.1) }
+ }
+ // the fingertip: it comes down, slides (eased) and lifts off; `each` runs at every step of a slide
+ func down(_ p: CGPoint) async { touches.at = p; touches.visible = true; await wait(0.06); touches.down = true }
+ func slide(to p: CGPoint, over t: Double, _ each: (CGPoint, Double) -> Void = { _, _ in }) async {
+ let from = touches.at, n = max(1, Int(t * 60))
+ for i in 1...n {
+ let u = Double(i) / Double(n), e = u * u * (3 - 2 * u)
+ touches.at = CGPoint(x: from.x + (p.x - from.x) * e, y: from.y + (p.y - from.y) * e)
+ each(touches.at, e); await wait(t / Double(n))
+ }
+ }
+ func up() async { touches.down = false; await wait(0.05); touches.visible = false }
+ func tap(_ p: CGPoint, _ action: () -> Void) async { await down(p); await wait(0.14); action(); await up() }
+
+ // a flick: the finger comes down, moves (the screen scrolls along with it), lifts
+ func swipe(from a: CGPoint, to b: CGPoint, over t: Double, _ start: () -> Void) async {
+ await down(a); start(); await slide(to: b, over: t); await up()
+ }
+ // the agents' faces at the top left: the list
+ func openList() async {
+ let p = pt(26, 24)
+ await down(p); model.drag(p, in: size); await wait(0.12)
+ if model.dragEnd(p, in: size) == .settings { showSettings = true }
+ await up()
+ }
+ // hold to talk: the finger rests, the talk bar comes, it's held while "you" speak, and lifts to send
+ func talk(_ seconds: Double) async {
+ let p = pt(104, 176)
+ await down(p); model.drag(p, in: size)
+ await until(8) { model.controller.talk == .listening }; await wait(seconds)
+ _ = model.dragEnd(p, in: size); await up()
+ }
+ // an approval: read the card, then hold it until it's allowed
+ func allow() async {
+ await until { model.rig.state == .approval }; await wait(2.2)
+ let p = pt(99, 152)
+ await down(p); model.drag(p, in: size); await wait(1.45); _ = model.dragEnd(p, in: size); await up()
+ }
+ func quiet() async { await until(30) { model.rig.state != .speaking && model.rig.state != .done } }
+ // what it showed you: tap its pill, look, close it with the × at the top left
+ func show() async {
+ await until(30) { toast != nil }; await wait(1.4)
+ guard let a = toast?.artifact else { return }
+ await tap(pt(99, 196)) { open(a) }
+ await wait(4.2)
+ await tap(pt(16, 18)) { withAnimation(.snappy(duration: 0.25)) { viewing = nil } }
+ }
+ // the conversation: pull the handle up, scroll back to the start with a finger, back down, and drag it away
+ func conversation() async {
+ await wait(1.2)
+ let h = pt(99, 232)
+ await down(h); model.drag(h, in: size)
+ model.cancelTouch(); pulling = true
+ await slide(to: pt(99, 120), over: 0.45) { p, _ in chatPull = max(0, h.y - p.y) }
+ pulling = false
+ withAnimation(.snappy(duration: 0.28)) { chatOpen = chatPull > 50; chatPull = 0 }
+ await up(); await wait(2.0)
+ if !model.conversation.isEmpty {
+ await down(pt(99, 80)); chatScroll = ("top", 1.3)
+ await slide(to: pt(99, 205), over: 1.3); await up(); await wait(3.2)
+ await down(pt(99, 205)); chatScroll = ("end", 1.3)
+ await slide(to: pt(99, 80), over: 1.3); await up(); await wait(2.4)
+ chatScroll = nil
+ }
+ let top = pt(99, Self.chatTop / Renderer.fit(size).s + 8)
+ await down(top)
+ await slide(to: pt(99, 170), over: 0.4) { p, _ in chatDrop = max(0, p.y - top.y) }
+ withAnimation(.snappy(duration: 0.25)) { chatOpen = false; chatDrop = 0 }
+ await up(); await wait(1.5)
+ }
+
+ await wait(1.0)
+ model.hub.event("scene: start")
+ await wait(1.5)
+ switch name {
+ case "code":
+ await talk(3.6) // the checkout tests are failing: find out why and fix it
+ await allow() // git push
+ await show() // the fix
+ await quiet(); await conversation()
+ case "noodle":
+ await talk(3.2) // send last month's Figma invoice to accounting
+ await until(45) { model.rig.state == .needs }; await quiet(); await wait(1.4) // which invoice?
+ await talk(1.5) // the team plan
+ await allow() // send the email
+ await show() // the email it sent
+ await quiet(); await conversation()
+ case "switch": // the agents list: scroll it, switch to Noodle, then to Eyes
+ await wait(1.5)
+ await openList(); await wait(1.3)
+ await swipe(from: pt(99, 205), to: pt(99, 95), over: 0.5) { Capture.shared.listScroll = "settings" }
+ await wait(1.6)
+ await swipe(from: pt(99, 80), to: pt(99, 200), over: 0.5) { Capture.shared.listScroll = Agents.fallback }
+ await wait(1.4)
+ await tap(pt(99, 160)) { Capture.shared.pick = "noodle" }
+ await wait(3.6)
+ await openList(); await wait(1.4)
+ await tap(pt(99, 216)) { Capture.shared.pick = "pix" }
+ await wait(3.6)
+ case "chat": // at work, then the conversation behind it
+ await wait(7.5)
+ await conversation()
+ case "soul": // Eyes' soul: open it, read it, say what changes, save
+ await wait(1.5)
+ await openList(); await wait(1.3)
+ // swiped left on Eyes' row: its Edit (a capture can't reveal a list's swipe action, so it opens the soul)
+ await down(pt(150, 216)); await slide(to: pt(60, 216), over: 0.35); await up()
+ Capture.shared.openSoul = "pix"
+ await wait(2.6)
+ await swipe(from: pt(99, 200), to: pt(99, 90), over: 0.55) { Capture.shared.soulScroll = "end" }
+ await wait(1.6)
+ let hold = pt(99, 186)
+ await down(hold); Capture.shared.soulPress = true
+ await wait(3.4)
+ Capture.shared.soulPress = false; await up()
+ await wait(4.2) // writing the change, then the proposal
+ await swipe(from: pt(99, 80), to: pt(99, 200), over: 0.55) { Capture.shared.soulScroll = "top" }
+ await wait(3.4)
+ await swipe(from: pt(99, 200), to: pt(99, 90), over: 0.55) { Capture.shared.soulScroll = "end" }
+ await wait(1.3)
+ await tap(pt(148, 186)) { Capture.shared.soulSave = true }
+ await wait(1.6)
+ await swipe(from: pt(99, 80), to: pt(99, 200), over: 0.55) { Capture.shared.soulScroll = "top" }
+ await wait(3.2)
+ case "eyes":
+ await talk(3.4) // three cover options for the case study
+ await show() // the covers, and a question
+ await until(20) { model.rig.state == .needs || model.rig.state == .idle }; await wait(1.2)
+ await talk(1.5) // just the eyes
+ await until(20) { model.rig.state == .done }; await quiet(); await conversation()
+ default: break
+ }
+ model.hub.event("scene: end")
+ }
+
+ private func open(_ a: Artifact) {
+ hub.event("artifact opened: \(a.kind) \(Int(a.w))x\(Int(a.h))")
+ withAnimation(.snappy(duration: 0.3)) { viewing = a; toast = nil }
+ }
+}
+
+struct SettingsView: View {
+ @Binding var character: String
+ @Binding var mode: String
+ @Binding var demo: Bool
+ @Binding var voice: Bool
+ @Binding var stayOn: Bool
+ let keepOn: KeepOn
+ var report: (String) -> Void = { _ in }
+ @AppStorage("watchVoice") private var watchVoice: String?
+
+ var body: some View {
+ list.navigationTitle("Settings") // pushed from the agents list
+ }
+
+ private static func scene(_ k: CharacterKind) -> String {
+ switch k {
+ case .peeps: return "Peeps fill the screen on their own. Touch the screen and they follow your finger; tap an eye and it winces. Turn the crown up for bubbles (tap one to pop it), down for a wind that pushes them down. Shake the watch and they get dizzy."
+ default: return "\(k.name) fills the screen with its own scene, so it has no stage to choose."
+ }
+ }
+
+ private var list: some View {
+ let kind = CharacterKind(id: character) ?? .fallback
+ return List {
+ // each agent is its own character; only a gridded one has stages to choose from, the others fill the screen their own way
+ if kind.staged {
+ Section {} footer: { Text(Self.scene(kind)) }
+ }
+ if !kind.staged {
+ Section {
+ ForEach(StageMode.allCases) { m in row(m.name(for: kind), selected: mode == m.rawValue) { mode = m.rawValue } }
+ } header: { Text("Stage") } footer: {
+ Text((StageMode(rawValue: mode) ?? .world).about(for: kind))
+ }
+ }
+ Section {
+ Toggle("Voice: read replies aloud", isOn: $voice)
+ NavigationLink { WatchVoices(report: report) } label: {
+ HStack { Text("Watch voice"); Spacer(); Text(Speaker.voice(watchVoice)?.name ?? "").foregroundStyle(Pal.gray) }
+ }
+ } footer: {
+ Text("With the voice off, replies are text and a tap on the wrist.")
+ }
+ Section {
+ Toggle("Stay on while held", isOn: $stayOn)
+ } footer: {
+ Text("While you hold the watch facing you, the screen stays on, up to 10 minutes without a touch. Put down, hanging from your keys or in a pocket, it sleeps after 20 seconds.")
+ }
+ Section {
+ Toggle("Keyring: stay on", isOn: Binding(get: { keepOn.enabled }, set: { keepOn.enabled = $0 }))
+ } footer: {
+ Text(keepOn.problem ?? "Keeps this app running, so a tap on the dark screen lands here and a touch held as it wakes talks. Off the wrist, also turn off Wrist Detection in Settings › Passcode. For the screen to stay lit longer after a tap: Settings › Display & Brightness › Wake Duration › Wake for 70 Seconds.")
+ }
+ Section {
+ Toggle("Demo: play every state", isOn: $demo)
+ }
+ }
+ }
+
+ private func row(_ title: String, selected: Bool, _ action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ HStack { Text(title); Spacer(); if selected { Image(systemName: "checkmark").foregroundStyle(Pal.clay) } }
+ }
+ }
+}
+
+/// The voices installed on the watch, for the replies it reads itself (when the Mac doesn't render them): a tap plays a
+/// sample line in that voice and picks it. The list goes to the hub's log too.
+struct WatchVoices: View {
+ let report: (String) -> Void
+ @AppStorage("watchVoice") private var picked: String?
+ @State private var speaker = Speaker()
+ private let voices = Speaker.englishVoices
+ static let sample = "Two tests failed in the cart. Want me to fix them?"
+
+ var body: some View {
+ List {
+ Section {
+ ForEach(voices, id: \.identifier) { v in
+ Button {
+ picked = v.identifier; Haptics.play(.click)
+ speaker.speak(Self.sample, voice: v.identifier)
+ } label: {
+ HStack {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(v.name)
+ Text("\(Speaker.qualityName(v)) · \(v.language)").font(.system(size: 12)).foregroundStyle(Pal.gray)
+ }
+ Spacer()
+ if (picked ?? Speaker.voice(nil)?.identifier) == v.identifier { Image(systemName: "checkmark").foregroundStyle(Pal.clay) }
+ }
+ }
+ }
+ } footer: {
+ Text(voices.isEmpty ? "No English voices on this watch." : "Tap one to hear it; it reads the replies the Mac doesn't voice.")
+ }
+ }
+ .navigationTitle("Watch voice")
+ .onAppear {
+ report("watch voices: " + voices.map { "\($0.name) (\(Speaker.qualityName($0)), \($0.language))" }.joined(separator: ", "))
+ }
+ }
+}
+
diff --git a/app/ChumsWatch/Controller.swift b/app/ChumsWatch/Controller.swift
new file mode 100644
index 0000000..e11e649
--- /dev/null
+++ b/app/ChumsWatch/Controller.swift
@@ -0,0 +1,323 @@
+import SwiftUI
+#if os(watchOS)
+import WatchKit
+#else
+import UIKit
+#endif
+
+/// Turns what the hub says (sessions, approvals, spoken lines, tool calls) and what you're doing
+/// (holding to talk, waiting for a reply, hearing one) into the character's state, labels and captions.
+/// Observable: a screen that shows `talk`, `agent` or `lines` redraws when they change. Everything `update()` keeps
+/// for itself is ignored, so a frame never makes a view redraw.
+@MainActor @Observable
+final class Controller {
+ let rig: Rig
+ let hub: HubClient
+ enum Talk { case none, listening, sending, speaking }
+ var talk: Talk = .none
+ @ObservationIgnored var demo: DemoDriver?
+ /// The agent on screen: everything here (state, approvals, tool calls, replies) is that agent's. The others' lines
+ /// go to `onBackground` (a tap on the wrist and a pill to go to them).
+ var agent = Agents.fallback
+ @ObservationIgnored var onBackground: ((AgentInfo, Spoken) -> Void)?
+ @ObservationIgnored private var lastLineTap = -10.0 // rig time of the last line's tap on the wrist
+ func info(_ id: String) -> AgentInfo {
+ hub.state?.agents?.first { $0.id == id } ?? Agents.known.first { $0.id == id } ?? AgentInfo(id: id, name: id.capitalized, character: CharacterKind.fallback.rawValue, status: "offline", line: nil, needs: false)
+ }
+
+
+ @ObservationIgnored private var seenTools = Set<String>()
+ @ObservationIgnored private var primed = false
+ @ObservationIgnored private var asking = false // an approval of this agent's was up on the last pass
+ @ObservationIgnored private var lastDoneAt = -99.0
+ @ObservationIgnored private var echo = ""
+ @ObservationIgnored private var echoUntil = 0.0
+ /// A reply stays on screen at least this long, even if speech ends sooner (or is muted).
+ @ObservationIgnored private var speakUntil = 0.0
+ @ObservationIgnored private var speechDone = false
+ @ObservationIgnored private var speechKind: String?
+ @ObservationIgnored private var speechLabel = ""
+ /// A problem worth showing while nothing else is (keyring mode failed, say).
+ @ObservationIgnored var notice: String?
+ /// Every line since launch, newest last: what you said, replies, answered approvals (the chat card).
+ private(set) var lines: [Spoken] = []
+#if DEBUG
+ /// Screenshots for the README: a made-up conversation with `agent`, its last reply showing `chart`.
+ func readmeDemo(_ agent: String, chart: Artifact?) {
+ let said: [(Bool, String, Artifact?)] = [
+ (true, "Rename the checkout button to Pay now.", nil),
+ (false, "Renamed in all 3 places and pushed. The tests pass.", nil),
+ (true, "Why did checkout drop last week?", nil),
+ (false, "Discount codes with lowercase letters were rejected from October 3. I fixed it on the 8th. Here is checkout since then.", chart),
+ (true, "Run the whole suite again before we ship.", nil),
+ ]
+ let start = Date().timeIntervalSince1970 * 1000 - 600_000
+ for (i, l) in said.enumerated() {
+ lines.append(Spoken(id: "readme-\(i)", session: agent, text: l.1, kind: l.0 ? "echo" : (l.2 == nil ? "done" : "artifact"),
+ audio: nil, at: start + Double(i) * 30_000, artifact: l.2, agent: agent))
+ }
+ }
+ /// UI tests: a conversation of `n` made-up lines for each agent, an hour old, kept here only (nothing reaches the hub).
+ func demoConversation(_ n: Int, agents: [String]) {
+ let start = Date().timeIntervalSince1970 * 1000 - 3_600_000
+ for a in agents {
+ for i in 0..<n {
+ let you = i % 2 == 0
+ lines.append(Spoken(id: "demo-\(a)-\(i)", session: a,
+ text: you ? "Line \(i): what is the state of the project today?" : "Line \(i): the tests pass and the build is green on every target.",
+ kind: you ? "echo" : "done", audio: nil, at: start + Double(i) * 1000, artifact: nil, agent: a))
+ }
+ }
+ }
+#endif
+ /// Tool calls since you last spoke: a reply or a finished turn is celebrated (done) only after real work, not
+ /// after "Yes, I hear you."
+ @ObservationIgnored private var toolsSinceOrder = 0
+ func orderSent() { toolsSinceOrder = 0 }
+ /// Set when you answer an approval on the watch; nil when it was answered some other way.
+ @ObservationIgnored var verdictAllowed: Bool?
+ /// The blocked line you've read (you opened the conversation): it stops holding the character in its blocked pose.
+ @ObservationIgnored private var seenBlock: String?
+ func seen() { if let b = hub.state?.sessions.first(where: { $0.name == agent && $0.status == "blocked" }) { seenBlock = b.lastLine } }
+ /// A word on screen for a moment (talking canceled), where replies go.
+ func note(_ text: String, seconds: Double = 2) { echo = text; echoUntil = rig.t + seconds }
+
+ init(rig: Rig, hub: HubClient) { self.rig = rig; self.hub = hub }
+
+ /// Called every frame before drawing.
+ func update() {
+ if let demo { demo.update(rig); return }
+ let s = hub.state
+ feedTools(s)
+ let (rest, variant, label, caption, sub) = restFor(s)
+ rig.restState = rest; rig.restVariant = variant
+
+ // interactions and interruptions come first (this agent's; another's approval is its pill and the badge)
+ if let a = s?.approvals.first(where: { $0.session == agent }) {
+ rig.approvalTitle = a.summary ?? a.description
+ rig.approvalDetail = a.tool == "Bash" ? a.description : a.tool
+ rig.label = a.tool.uppercased()
+ // the iPhone draws its own card under the character: there it stays full size and asks (needs)
+ let asks: ChumsState = rig.chrome ? .approval : .needs
+ if rig.state != asks { rig.setState(asks) } // the tap comes from HubClient.onApproval
+ asking = true
+ return
+ }
+ switch talk {
+ case .listening:
+ if rig.state != .listening { rig.setState(.listening) }
+ // the talk bar at the top (× · your voice · ✓) says the rest: no caption
+ rig.label = "TO \(info(agent).name.uppercased())"; rig.caption = ""; return
+ case .sending:
+ if rig.state != .thinking { rig.setState(.thinking) }
+ rig.label = "THINKING"; rig.caption = ""; return
+ case .speaking:
+ if rig.state != .speaking { rig.setState(.speaking) }
+ rig.label = speechLabel // an approval may have borrowed the label
+ if speechDone && rig.t >= speakUntil { finishSpeaking() }
+ return
+ case .none: break
+ }
+ if asking || rig.state == .approval {
+ asking = false
+ let allowed = verdictAllowed ?? echo.hasPrefix("Allowed")
+ verdictAllowed = nil
+ if allowed { rig.setState(.done, variant: true); rig.caption = echo.hasPrefix("Allowed") ? echo : "Allowed."; return }
+ rig.settle()
+ }
+ if rig.inOneShot { return }
+ if rig.state != rest || rig.variant != variant { rig.setState(rest, variant: variant) }
+ rig.label = label
+ rig.caption = rig.t < echoUntil ? echo : caption
+ rig.subCaption = sub
+ if let notice, rest == .idle || rest == .sleep { rig.caption = notice }
+ }
+
+ /// The resting state: what this agent's session is doing when nothing else is going on.
+ private func restFor(_ all: HubState?) -> (ChumsState, Bool, String, String, String) {
+ if !hub.connected && hub.lastError == nil { return (.sleep, false, "CONNECTING", "Looking for your Mac", "") }
+ guard hub.connected, let all else { return (.sleep, true, "HUB OFFLINE", hub.lastError ?? "Can't reach your Mac", "") }
+ let mine = all.sessions.filter { $0.name == agent }
+ if mine.isEmpty { return (.sleep, false, "NOT RUNNING", "\(info(agent).name) isn't running on your Mac.", "") }
+ if let b = mine.first(where: { $0.status == "blocked" && !(seenBlock != nil && $0.lastLine == seenBlock) }) {
+ return (.blocked, false, "BLOCKED", b.lastLine ?? "It's stuck.", "Details on your Mac")
+ }
+ if let q = mine.first(where: { $0.status == "waiting" }) {
+ return (.needs, true, "ASKS", q.lastLine ?? "It has a question.", "")
+ }
+ // rate limited: it resumes by itself. The watch rig has no waiting state yet, so it shows as blocked
+ if mine.contains(where: { $0.status == "limited" }) {
+ return (.blocked, false, "RATE LIMITED", "Rate limited. It resumes by itself.", "")
+ }
+ // compacting the context: shown as thinking until the watch rig gets the compacting state
+ if mine.contains(where: { $0.status == "compacting" }) {
+ return (.thinking, false, "COMPACTING", "", "")
+ }
+ if let w = mine.first(where: { $0.status == "working" && ($0.subagents ?? 0) > 0 }) {
+ let n = w.subagents ?? 0
+ return (.subagents, false, "\(n) SUBAGENT\(n == 1 ? "" : "S")", "", "")
+ }
+ if mine.contains(where: { $0.status == "working" }) {
+ return (.working, false, "WORKING", "", "")
+ }
+ return (.idle, false, "", "", "")
+ }
+ /// What the hub calls itself on the lines it says on its own (an answered approval, which session to ask).
+ static let hub = "Chums"
+
+ private func feedTools(_ s: HubState?) {
+ guard let tools = s?.tools else { return }
+ for t in tools {
+ if let ok = t.ok { rig.worlds.results[t.id] = ok }
+ guard !seenTools.contains(t.id) else { continue }
+ seenTools.insert(t.id)
+ guard primed, t.session == agent else { continue } // no history from before launch; only this agent's work
+ if t.type == "stop" {
+ if toolsSinceOrder > 0 && rig.t - lastDoneAt > 3 && talk == .none {
+ toolsSinceOrder = 0; lastDoneAt = rig.t; rig.caption = "Done."; rig.setState(.done); haptic(.success)
+ }
+ continue
+ }
+ toolsSinceOrder += 1
+ rig.push(ToolCall(id: t.id, kind: ToolCall.Kind(rawValue: t.type) ?? .bash, text: t.text))
+ }
+ primed = true
+ }
+
+ // MARK: events from the hub and the talk flow
+
+ /// A line that arrived while you were talking waits until you let go; it never takes over the microphone.
+ @ObservationIgnored private var held: [(Spoken, (String) -> Void)] = []
+ func flushHeld() {
+ let lines = held; held = []
+ for (l, s) in lines { spoken(l, speak: s) }
+ }
+
+ func spoken(_ line: Spoken, speak: @escaping (String) -> Void) {
+ if !lines.contains(where: { $0.id == line.id }) { lines.append(line); if lines.count > 90 { lines.removeFirst() } }
+ // said more than a minute ago (the app was closed, or the Mac out of reach): it joins the conversation quietly,
+ // so reopening the app after a long talk on the iPhone isn't a tap for every line
+ if let at = line.at, Date().timeIntervalSince1970 * 1000 - at > 60_000 { return }
+ // another agent's: it doesn't take over this one; a tap on the wrist and its pill (what you told it isn't news)
+ if line.owner != agent {
+ if !["echo", "verdict", "refused"].contains(line.kind) {
+ onBackground?(info(line.owner), line)
+ if ["done", "question", "blocked"].contains(line.kind) { Alerts.post(alertTitle(line), line.text) }
+ }
+ return
+ }
+ if talk == .listening || talk == .sending, !["echo", "verdict", "refused"].contains(line.kind) {
+ held.append((line, speak)); if held.count > 5 { held.removeFirst() }
+ if ["done", "question", "blocked"].contains(line.kind) {
+ Alerts.post(alertTitle(line), line.text)
+ }
+ return
+ }
+ switch line.kind {
+ case "echo":
+ echo = line.text; echoUntil = rig.t + 15; return // what you said, in quotes, until the reply comes
+ case "verdict", "refused": // a note, shown a moment: not a reply, never read aloud
+ echo = line.text; echoUntil = rig.t + 3; return
+ default: break
+ }
+ rig.caption = line.artifact == nil ? line.text : "" // something it showed you: its pill says it instead
+ echoUntil = 0
+ if line.kind == "done" { lastDoneAt = rig.t }
+ if ["done", "question", "blocked"].contains(line.kind) { Alerts.post(alertTitle(line), line.text) }
+#if os(watchOS)
+ // (the iPhone taps once for a new line itself, HomeView's soft tap); lines that land together tap once
+ if rig.t - lastLineTap > 1.5 { lastLineTap = rig.t; haptic(line.kind == "blocked" ? .failure : line.kind == "question" ? .notification : .success) }
+#endif
+ talk = .speaking; speechDone = false; speechKind = line.kind
+ speakUntil = rig.t + max(3, Double(line.text.count) / 24 + 2.5) // typed at 24 characters a second, then read
+ speechLabel = ""
+ rig.label = speechLabel
+ rig.setState(.speaking)
+ speak(line.text)
+ }
+
+ /// A notification's title: which agent, and what happened.
+ private func alertTitle(_ line: Spoken) -> String {
+ let what = line.kind == "question" ? "asks" : line.kind == "blocked" ? "is stuck" : "is done"
+ return "\(info(line.owner).name) \(what)"
+ }
+
+ func speechFinished(kind: String?) {
+ guard talk == .speaking else { return }
+ speechDone = true
+ if rig.t >= speakUntil { finishSpeaking() }
+ }
+ private func finishSpeaking() {
+ talk = .none; speechDone = false
+ if speechKind == "done" && toolsSinceOrder > 0 { toolsSinceOrder = 0; lastDoneAt = rig.t; rig.setState(.done) } else { rig.settle() }
+ }
+
+ func haptic(_ h: Rig.Haptic) { Haptics.play(h) }
+}
+
+enum Haptics {
+ private static var last = 0.0
+ static func play(_ h: Rig.Haptic) {
+#if !os(watchOS)
+ guard UserDefaults.standard.object(forKey: "haptics") as? Bool ?? true else { return } // the iPhone's settings
+#endif
+ let now = Date().timeIntervalSinceReferenceDate
+ if h == .click && now - last < 0.06 { return } // a burst of impacts is one tap, not a buzz
+ last = now
+#if os(watchOS)
+ let type: WKHapticType
+ switch h {
+ case .click, .settle: type = .click
+ case .strong: type = .directionDown
+ case .success: type = .success
+ case .failure: type = .failure
+ case .notification: type = .notification
+ case .start: type = .start
+ }
+ WKInterfaceDevice.current().play(type)
+#else
+ switch h {
+ case .click: UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ case .strong: UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
+ case .start: UIImpactFeedbackGenerator(style: .medium).impactOccurred()
+ case .settle: UIImpactFeedbackGenerator(style: .rigid).impactOccurred(intensity: 0.7)
+ case .success: UINotificationFeedbackGenerator().notificationOccurred(.success)
+ case .failure: UINotificationFeedbackGenerator().notificationOccurred(.error)
+ case .notification: UINotificationFeedbackGenerator().notificationOccurred(.warning)
+ }
+#endif
+ }
+}
+
+/// Plays every state in turn with made-up tool calls, for trying it out without a session.
+@MainActor
+final class DemoDriver {
+ private var i = -1, t = 0.0, last = Date()
+ private let script: [(ChumsState, Bool, Double, String, String)] = [
+ (.idle, false, 3, "", ""),
+ (.listening, false, 2.6, "LISTENING", ""),
+ (.thinking, false, 1.8, "THINKING", ""),
+ (.working, false, 9, "WORKING", ""),
+ (.subagents, false, 6, "3 SUBAGENTS", ""),
+ (.approval, false, 3.5, "BASH", ""),
+ (.done, true, 3, "ALLOWED", "Allowed."),
+ (.working, false, 6, "WORKING", ""),
+ (.speaking, false, 6, "", "All ten tests pass now. Nothing waits on you."),
+ (.done, false, 4, "DONE", "Done."),
+ (.needs, true, 4, "ASKS", "Which branch, main or dev?"),
+ (.blocked, false, 4, "BLOCKED", "Signing failed twice."),
+ (.sleep, false, 4, "", ""),
+ ]
+ func update(_ rig: Rig) {
+ let now = Date(); t += now.timeIntervalSince(last); last = now
+ rig.worlds.demo = true
+ if i < 0 || (t > script[i].2 && !rig.W.busy) {
+ i = (i + 1) % script.count; t = 0
+ let s = script[i]
+ rig.restState = s.0 == .done ? .working : s.0; rig.restVariant = false
+ rig.label = s.3; rig.caption = s.4; rig.subCaption = s.0 == .blocked ? "Details on your Mac" : ""
+ rig.approvalTitle = "rm -rf build"; rig.approvalDetail = "Clean the build folder"
+ rig.setState(s.0, variant: s.1)
+ }
+ }
+}
diff --git a/app/ChumsWatch/HubClient.swift b/app/ChumsWatch/HubClient.swift
new file mode 100644
index 0000000..87da1b7
--- /dev/null
+++ b/app/ChumsWatch/HubClient.swift
@@ -0,0 +1,462 @@
+import Foundation
+import Observation
+#if os(watchOS)
+import WatchKit
+#else
+import UIKit
+#endif
+
+struct SessionInfo: Decodable, Identifiable, Equatable {
+ let id: String
+ let name: String
+ let status: String
+ let lastLine: String?
+ let subagents: Int?
+}
+
+/// One tool call a session made, from the Claude Code hooks: type is read, edit, bash, test, agent or stop.
+struct ToolInfo: Decodable, Identifiable, Equatable {
+ let id: String
+ let session: String
+ let type: String
+ let text: String
+ let ok: Bool?
+ var at: Double? = nil // when (ms since 1970)
+}
+
+struct Approval: Decodable, Identifiable, Equatable {
+ let requestId: String
+ let session: String
+ let tool: String
+ let description: String
+ let preview: String
+ let summary: String?
+ var id: String { requestId }
+}
+
+struct Spoken: Decodable, Identifiable, Equatable {
+ let id: String
+ let session: String
+ let text: String
+ let kind: String
+ let audio: String? // the reply's voice, rendered on the Mac (GET it from the hub)
+ var audioData: String? = nil // the same, in the answer that brought the line (base64 m4a): no second trip
+ var device: String? = nil // the device whose order this answers: it speaks it (none: the watch)
+ /// Whether this device reads the line aloud: the one the order came from (lines with none are the watch's).
+ var speaksHere: Bool { (device ?? "watch") == HubClient.device }
+ let at: Double? // when it was said (ms since 1970), to keep the conversation in order
+ let artifact: Artifact? // something it showed you (a screenshot, a page, an image)
+ let agent: String? // whose line it is (lines from before agents have none: they were the first agent's)
+ /// The agent it belongs to.
+ var owner: String { agent ?? Agents.fallback }
+}
+
+/// An agent: a character with its own Claude Code session and thread on the Mac (~/.chums/agents.json).
+struct AgentInfo: Decodable, Identifiable, Equatable {
+ let id: String
+ let name: String
+ let character: String
+ let status: String // idle, working, waiting, blocked, compacting, limited, offline
+ let line: String? // the last thing it said
+ let needs: Bool // it asks you something, or waits on an approval
+ var owns: String? = nil // what it looks after (its soul)
+ var runtime: String? = nil // claude or codex: what it runs on, switched on its soul screen
+ var voice: String? = nil // its voice on the Mac (a Kokoro voice id), chosen on its soul screen
+ var model: String? = nil // its model (an alias or a slug); nil: what its runtime is set to use
+ var permission: String? = nil // how it asks before acting (a mode id for its runtime); nil: its runtime's setting
+}
+
+/// How an agent may act, for a runtime: the modes it offers (Asks first, …) and what it uses when an agent has none.
+struct PermissionChoices: Decodable, Equatable {
+ let `default`: String?
+ let modes: [ModelChoices.Model]
+}
+
+/// The models a runtime offers, and what it uses when an agent has none of its own ("Opus, 1M context").
+struct ModelChoices: Decodable, Equatable {
+ struct Model: Decodable, Identifiable, Equatable { let id: String; let name: String; var about: String? = nil }
+ let `default`: String?
+ let models: [Model]
+}
+
+/// One of the voices the Mac can speak in (Kokoro's English ones).
+struct VoiceInfo: Decodable, Identifiable, Equatable {
+ let id: String
+ let name: String
+ let grade: String
+ let accent: String
+ let gender: String
+}
+
+struct HubState: Decodable {
+ let rev: Int
+ let sessions: [SessionInfo]
+ let approvals: [Approval]
+ let spoken: [Spoken]
+ let tools: [ToolInfo]?
+ let agents: [AgentInfo]?
+ var runtimes: [String]? = nil // what an agent can be switched to on this Mac
+}
+
+/// An agent's soul as the watch shows it: who it is, what it looks after, what it refers to the others, its voice.
+struct SoulCard: Decodable, Equatable {
+ let id: String?
+ let name: String
+ let owns: String?
+ let refers: String?
+ let voice: String?
+ var body: String? = nil
+ let canUndo: Bool?
+}
+
+/// What you said on a soul screen, as a change to see before saving (or a question back, or why it failed).
+struct SoulProposal: Decodable {
+ let transcript: String?
+ let proposal: String?
+ let summary: String?
+ let soul: SoulCard?
+ let clarify: String?
+ let error: String?
+}
+
+/// The hub's reason, when it says no.
+struct HubFailure: Decodable { let error: String? }
+
+struct RouteResult: Decodable {
+ let transcript: String?
+ let kind: String
+ let echo: String?
+ let target: String?
+}
+
+/// HTTP only: watchOS allows WebSockets only while streaming audio (TN3135), so state comes from a
+/// long-poll that runs while Chums is on screen.
+@MainActor @Observable
+final class HubClient {
+ private(set) var state: HubState?
+ private(set) var connected = false
+ private(set) var lastError: String?
+
+ /// Fired for lines that arrive after the first load, so old lines are never re-spoken.
+ var onSpoken: ((Spoken) -> Void)?
+ var onApproval: ((Approval) -> Void)?
+
+ private var rev = 0
+ /// The first state since launch is in. Lines and approvals after it are news, those that came while the poll was
+ /// stopped too (the app in the background, the Mac out of reach): a restarted poll doesn't mark them seen.
+ @ObservationIgnored private var loaded = false
+ private var seenSpoken = Set<String>()
+ private var seenApprovals = Set<String>()
+ private var pollTask: Task<Void, Never>?
+ private var hostIndex = 0
+ private var failingSince: Date? // the first failure since the last success
+ /// The hub's addresses to try. 127.0.0.1 is the Mac only in the Simulator; on a real watch it's the watch itself.
+ private static let hosts: [String] = {
+#if targetEnvironment(simulator)
+ // Simulator captures: a stand-in hub playing a scripted session (-hub http://127.0.0.1:7799)
+ if let h = UserDefaults.standard.string(forKey: "hub") { return [h] }
+ return HubConfig.hosts
+#else
+ HubConfig.hosts.filter { !$0.contains("127.0.0.1") && !$0.contains("localhost") }
+#endif
+ }()
+ private let urlSession: URLSession = {
+ let c = URLSessionConfiguration.default
+ c.timeoutIntervalForRequest = 30
+ c.timeoutIntervalForResource = 40
+ c.waitsForConnectivity = true // watchOS brings a network path up on demand; wait for it instead of failing
+ return URLSession(configuration: c)
+ }()
+
+ private var base: String { Self.hosts[hostIndex % Self.hosts.count] }
+
+ /// Pings every address at once (4 s each) and keeps the first in the list that answers: the public one (Tailscale
+ /// Funnel), then 127.0.0.1 (the Simulator's hub; a real watch or iPhone drops it). Asked again whenever requests
+ /// start failing.
+ private func pickHost() async {
+ let hosts = Self.hosts
+ let ok = await withTaskGroup(of: (Int, Bool).self) { g -> Set<Int> in
+ for (i, h) in hosts.enumerated() { g.addTask { (i, await Self.ping(h)) } }
+ var s = Set<Int>()
+ for await (i, good) in g where good { s.insert(i) }
+ return s
+ }
+ if let best = ok.min() { hostIndex = best } else { hostIndex = (hostIndex + 1) % hosts.count }
+ let now = ok.isEmpty ? "none answered" : hosts[hostIndex]
+ if now != route { route = now; if !ok.isEmpty { event("network: using \(now) (\(ok.count) of \(hosts.count) answered)") } }
+ }
+ /// Which address answered last, for the event log.
+ private(set) var route = ""
+ private nonisolated static let probeSession: URLSession = {
+ let c = URLSessionConfiguration.ephemeral
+ c.timeoutIntervalForRequest = 4; c.timeoutIntervalForResource = 4
+ return URLSession(configuration: c)
+ }()
+ private nonisolated static func ping(_ host: String) async -> Bool {
+ guard let url = URL(string: host + "/v1/ping") else { return false }
+ var r = URLRequest(url: url, timeoutInterval: 4)
+ r.setValue("Bearer \(HubConfig.token)", forHTTPHeaderField: "Authorization")
+ guard let (_, resp) = try? await probeSession.data(for: r) else { return false }
+ return (resp as? HTTPURLResponse)?.statusCode == 200
+ }
+
+ /// Sent with each poll so the hub can log what keyring mode costs (~/.chums/watch-battery.csv).
+ @ObservationIgnored var screen = "on"
+ @ObservationIgnored var keyring = false
+ private var deviceQuery: String {
+#if os(watchOS)
+ let d = WKInterfaceDevice.current()
+ d.isBatteryMonitoringEnabled = true
+ let charging = d.batteryState == .charging || d.batteryState == .full
+ return "&battery=\(String(format: "%.2f", d.batteryLevel))&charging=\(charging ? 1 : 0)&screen=\(screen)&keyring=\(keyring ? 1 : 0)&device=watch"
+#else
+ return "&device=phone"
+#endif
+ }
+ /// Which device this is, for the hub: a reply is spoken on the device the order came from.
+#if os(watchOS)
+ nonisolated static let device = "watch"
+#else
+ nonisolated static let device = "phone"
+#endif
+
+ func start() {
+ guard pollTask == nil else { return }
+ pollTask = Task { await pollLoop() }
+ }
+
+ func stop() {
+ pollTask?.cancel()
+ pollTask = nil
+ }
+
+ private func request(_ path: String, method: String = "GET", body: Data? = nil,
+ contentType: String = "application/json", timeout: TimeInterval = 30) -> URLRequest {
+ var r = URLRequest(url: URL(string: base + path)!, timeoutInterval: timeout)
+ r.httpMethod = method
+ r.setValue("Bearer \(HubConfig.token)", forHTTPHeaderField: "Authorization")
+ if let body {
+ r.httpBody = body
+ r.setValue(contentType, forHTTPHeaderField: "Content-Type")
+ }
+ return r
+ }
+
+ private func pollLoop() async {
+ var first = true, failures = 0 // first: this poll's first request asks for the whole state at once
+ await pickHost()
+ while !Task.isCancelled {
+ do {
+ let (data, resp) = try await urlSession.data(for: request("/v1/state?since=\(first ? 0 : rev)\(deviceQuery)", timeout: 28))
+ let code = (resp as? HTTPURLResponse)?.statusCode ?? 0
+ guard code == 200 else { throw code == 401 ? URLError(.userAuthenticationRequired) : URLError(.badServerResponse) }
+ apply(try JSONDecoder().decode(HubState.self, from: data), initial: !loaded)
+ first = false; loaded = true
+ connected = true
+ lastError = nil
+ failingSince = nil
+ failures = 0
+ } catch {
+ if Task.isCancelled { break }
+ // A request fails every time the watch sleeps and wakes, so one failure says nothing. Stay on the
+ // address that worked and retry it; only say the Mac is unreachable after 8 s of failing, and only
+ // move to the next address after a couple of failures in a row on this one.
+ let now = Date(), since = failingSince ?? now
+ failingSince = since
+ let refused = (error as? URLError)?.code == .userAuthenticationRequired
+ if refused || now.timeIntervalSince(since) > 8 {
+ connected = false
+ lastError = refused ? "Hub refused the token" : "Can't reach your Mac"
+ }
+ failures += 1
+ if failures >= 2 { failures = 0; await pickHost() } // the path changed: find the address that answers now
+ else { try? await Task.sleep(for: .seconds(1)) }
+ }
+ }
+ }
+
+ private func apply(_ s: HubState, initial: Bool) {
+ rev = s.rev
+ state = s
+ for line in s.spoken where !seenSpoken.contains(line.id) {
+ seenSpoken.insert(line.id)
+ if !initial { onSpoken?(line) }
+ }
+ for a in s.approvals where !seenApprovals.contains(a.requestId) {
+ seenApprovals.insert(a.requestId)
+ if !initial { onApproval?(a) }
+ }
+ // the hub only ever sends the last few lines and the open approvals, so older ids can go
+ if seenSpoken.count > 300 { seenSpoken = Set(s.spoken.map(\.id)) }
+ if seenApprovals.count > 100 { seenApprovals = Set(s.approvals.map(\.requestId)) }
+ }
+
+ /// `approval` is the approval card that was on screen while you spoke: a spoken yes or no answers that one.
+ /// What you said, for the agent you were talking to when you started (and the approval card that was on screen).
+ func send(audio url: URL, approval: String?, agent: String) async -> RouteResult? {
+ guard let data = try? Data(contentsOf: url) else { return nil }
+ var h = ["X-Chums-Agent": agent, "X-Chums-Device": Self.device]
+ if let approval { h["X-Chums-Approval"] = approval }
+ return await post("/v1/utterance", body: data, contentType: "audio/m4a", headers: h)
+ }
+
+ /// One line for the hub's log (~/.chums/watch-events.log): what the watch did, so it can be checked from the Mac.
+ func event(_ text: String) {
+#if targetEnvironment(simulator)
+ let text = "[sim] " + text // the Simulator reports to the same hub
+#endif
+ guard let body = try? JSONSerialization.data(withJSONObject: ["text": text]) else { return }
+ let r = request("/v1/event", method: "POST", body: body, timeout: 5)
+ Task { _ = try? await urlSession.data(for: r) }
+ }
+
+ /// The voices the Mac can speak in; nil when it can't say.
+ func voices() async -> [VoiceInfo]? {
+ struct R: Decodable { let voices: [VoiceInfo] }
+ let r: (R?, String?) = await exchange(request("/v1/voices", timeout: 10))
+ return r.0?.voices
+ }
+ /// The models each runtime offers ("claude", "codex").
+ func models() async -> [String: ModelChoices]? {
+ await exchange(request("/v1/models", timeout: 10)).0
+ }
+ /// The permission modes each runtime offers ("claude", "codex").
+ func permissions() async -> [String: PermissionChoices]? {
+ await exchange(request("/v1/permissions", timeout: 10)).0
+ }
+ /// An agent's permission mode (nil: its runtime's own): it restarts with it. nil once it has, else why not.
+ func setPermission(_ agent: String, mode: String?) async -> String? {
+ let body = try? JSONSerialization.data(withJSONObject: ["mode": mode.map { $0 as Any } ?? NSNull()])
+ let req = request("/v1/agents/\(agent)/permission", method: "POST", body: body, timeout: 90)
+ guard let (data, resp) = try? await urlSession.data(for: req) else { return "Can't reach your Mac" }
+ if (resp as? HTTPURLResponse)?.statusCode == 200 { return nil }
+ return (try? JSONDecoder().decode([String: String].self, from: data))?["error"] ?? "Couldn't change it"
+ }
+ /// An agent's model (nil: its runtime's own): it restarts on it. nil once it has, else why not.
+ func setModel(_ agent: String, model: String?) async -> String? {
+ let body = try? JSONSerialization.data(withJSONObject: ["model": model.map { $0 as Any } ?? NSNull()])
+ let req = request("/v1/agents/\(agent)/model", method: "POST", body: body, timeout: 90)
+ guard let (data, resp) = try? await urlSession.data(for: req) else { return "Can't reach your Mac" }
+ if (resp as? HTTPURLResponse)?.statusCode == 200 { return nil }
+ return (try? JSONDecoder().decode([String: String].self, from: data))?["error"] ?? "Couldn't change it"
+ }
+ /// An agent's voice; nil once the hub has it, else why not.
+ func setVoice(_ agent: String, voice: String) async -> String? {
+ let req = request("/v1/agents/\(agent)/voice", method: "POST", body: try? JSONEncoder().encode(["voice": voice]), timeout: 10)
+ guard let (data, resp) = try? await urlSession.data(for: req) else { return "Can't reach your Mac" }
+ if (resp as? HTTPURLResponse)?.statusCode == 200 { return nil }
+ return (try? JSONDecoder().decode([String: String].self, from: data))?["error"] ?? "Couldn't change it"
+ }
+
+ /// A reply's voice from the hub, nil when there's none or it can't be fetched.
+ /// A file from the hub (an artifact's original, for the iPhone's viewers): nil when it can't be had. Big files take time.
+ func fetch(_ path: String, timeout: Double = 90) async -> Data? {
+ guard let (data, resp) = try? await urlSession.data(for: request(path, timeout: timeout)),
+ (resp as? HTTPURLResponse)?.statusCode == 200 else { return nil }
+ return data
+ }
+ func speech(_ path: String) async -> Data? {
+ guard let (data, resp) = try? await urlSession.data(for: request(path, timeout: 8)),
+ (resp as? HTTPURLResponse)?.statusCode == 200 else { return nil }
+ return data
+ }
+
+ // MARK: souls
+
+ func soul(_ agent: String) async -> SoulCard? { await exchange(request("/v1/agents/\(agent)/soul", timeout: 10)).0 }
+ /// What you said about an agent's soul: the hub transcribes it and proposes a change (nothing is saved yet).
+ func sendSoul(audio url: URL, agent: String) async -> SoulProposal? {
+ guard let data = try? Data(contentsOf: url) else { return nil }
+ var r = request("/v1/utterance", method: "POST", body: data, contentType: "audio/m4a", timeout: 90)
+ r.setValue(agent, forHTTPHeaderField: "X-Chums-Soul")
+ return await exchange(r).0
+ }
+ /// Typed words to an agent, as if said (the iPhone's composer, Siri, the widget).
+ func say(_ text: String, agent: String, approval: String? = nil, files: [String] = []) async -> RouteResult? {
+ var body: [String: Any] = ["text": text, "agent": agent, "device": Self.device]
+ if let approval { body["approval"] = approval }
+ if !files.isEmpty { body["files"] = files }
+ return await exchange(request("/v1/say", method: "POST", body: try? JSONSerialization.data(withJSONObject: body), timeout: 30)).0
+ }
+
+ /// A picture or a file, to the Mac (the hub keeps it in ~/.chums/uploads); its path there goes with the next order.
+ struct Upload: Decodable { let path: String; let name: String; let artifact: Artifact? }
+ func upload(_ data: Data, name: String, type: String) async -> Upload? {
+ let q = name.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "file"
+ let req = request("/v1/upload?name=\(q)", method: "POST", body: data, contentType: type, timeout: 120)
+ guard let (d, resp) = try? await urlSession.data(for: req), (resp as? HTTPURLResponse)?.statusCode == 200 else { return nil }
+ return try? JSONDecoder().decode(Upload.self, from: d)
+ }
+
+ /// The agent the iPhone shows now: the widgets show it too, when no agent is picked in them.
+ func focus(_ agent: String) async {
+ let body = try? JSONEncoder().encode(["agent": agent])
+ _ = try? await urlSession.data(for: request("/v1/focus", method: "POST", body: body, timeout: 10))
+ }
+
+ /// The address the hub answers at now, and how long it takes to answer (ms; nil: it didn't).
+ var address: String { base }
+ func ping() async -> Double? {
+ let t0 = Date()
+ guard let (_, resp) = try? await urlSession.data(for: request("/v1/ping", timeout: 10)),
+ (resp as? HTTPURLResponse)?.statusCode == 200 else { return nil }
+ return Date().timeIntervalSince(t0) * 1000
+ }
+
+ /// The same with typed words (Simulator captures: -soulSay "…").
+ func soulFromText(_ text: String, agent: String) async -> SoulProposal? {
+ await exchange(request("/v1/say", method: "POST", body: try? JSONEncoder().encode(["soul": agent, "text": text]), timeout: 90)).0
+ }
+ func saveSoul(_ agent: String, proposal: String) async -> (SoulCard?, String?) {
+ await exchange(request("/v1/agents/\(agent)/soul/save", method: "POST", body: try? JSONEncoder().encode(["proposal": proposal]), timeout: 20))
+ }
+ /// Switches an agent to Claude Code ("claude") or Codex ("codex"); nil once it runs on it, else why not.
+ func setRuntime(_ agent: String, runtime: String) async -> String? {
+ let req = request("/v1/agents/\(agent)/runtime", method: "POST", body: try? JSONEncoder().encode(["runtime": runtime]), timeout: 150)
+ guard let (data, resp) = try? await urlSession.data(for: req) else { return "Can't reach your Mac" }
+ if (resp as? HTTPURLResponse)?.statusCode == 200 { return nil }
+ return (try? JSONDecoder().decode([String: String].self, from: data))?["error"] ?? "Couldn't switch it"
+ }
+ /// One part of a soul (name, owns, refers, voice, body), written as given.
+ func setSoul(_ agent: String, field: String, value: String) async -> (SoulCard?, String?) {
+ await exchange(request("/v1/agents/\(agent)/soul/set", method: "POST",
+ body: try? JSONEncoder().encode(["field": field, "value": value]), timeout: 20))
+ }
+ func undoSoul(_ agent: String) async -> (SoulCard?, String?) {
+ await exchange(request("/v1/agents/\(agent)/soul/undo", method: "POST", body: Data("{}".utf8), timeout: 20))
+ }
+ /// A request whose failure has a reason worth showing (the hub's error message).
+ private func exchange<T: Decodable>(_ r: URLRequest) async -> (T?, String?) {
+ guard let (data, resp) = try? await urlSession.data(for: r) else { return (nil, "Can't reach your Mac") }
+ let code = (resp as? HTTPURLResponse)?.statusCode ?? 0
+ if code == 200, let v = try? JSONDecoder().decode(T.self, from: data) { return (v, nil) }
+ return (nil, (try? JSONDecoder().decode(HubFailure.self, from: data))?.error ?? "Something went wrong (\(code))")
+ }
+
+ /// True once the hub has the verdict.
+ func verdict(_ requestId: String, allow: Bool) async -> Bool {
+ let body = try? JSONEncoder().encode(["requestId": requestId, "behavior": allow ? "allow" : "deny"])
+ let r: RouteResult? = await post("/v1/verdict", body: body ?? Data())
+ return r != nil
+ }
+
+ /// The screen woke or you touched it while the Mac was out of reach: look again now instead of after the timeout.
+ func nudge() {
+ guard pollTask != nil, !connected || lastError != nil else { return }
+ stop(); start()
+ }
+
+ private func post<T: Decodable>(_ path: String, body: Data, contentType: String = "application/json", headers: [String: String] = [:]) async -> T? {
+ var r = request(path, method: "POST", body: body, contentType: contentType)
+ for (k, v) in headers { r.setValue(v, forHTTPHeaderField: k) }
+ do {
+ let (data, resp) = try await urlSession.data(for: r)
+ let code = (resp as? HTTPURLResponse)?.statusCode ?? 0
+ if code == 401 { lastError = "Hub refused the token"; return nil }
+ guard code == 200 else { return nil }
+ return try JSONDecoder().decode(T.self, from: data)
+ } catch {
+ return nil
+ }
+ }
+}
diff --git a/app/ChumsWatch/KeepOn.swift b/app/ChumsWatch/KeepOn.swift
new file mode 100644
index 0000000..caec71c
--- /dev/null
+++ b/app/ChumsWatch/KeepOn.swift
@@ -0,0 +1,119 @@
+import Foundation
+import HealthKit
+import WatchKit
+
+/// Keyring mode: keeps Chums on screen and running, like a Tamagotchi hanging from your keys.
+///
+/// watchOS sends any app back to the watch face after a while, and suspends it when the screen dims. The one thing
+/// that keeps an app frontmost and running indefinitely is a workout session, so Chums runs one and never saves it:
+/// no workout shows up in Health or Fitness. While it runs, waking the screen shows Chums, not the watch face; the
+/// app keeps polling the hub when the screen dims (the character shows its always-on look) and can still tap your wrist.
+/// If Chums crashes or is killed while the session runs, watchOS relaunches it (see `ChumsAppDelegate`).
+/// Off the wrist, also turn off Wrist Detection (Settings › Passcode), or the watch locks and hides Chums.
+@MainActor @Observable
+final class KeepOn: NSObject {
+ static let key = "keyring"
+ static let shared = KeepOn()
+ private(set) var running = false
+ private(set) var problem: String?
+ /// Reports what happens to the session (the hub logs it), so it can be checked without looking at the watch.
+ var onEvent: ((String) -> Void)?
+ private let store = HKHealthStore()
+ private var session: HKWorkoutSession?
+ private var starting = false
+ /// Another app started a workout: watchOS ended Chums's session. Don't take it back until Chums is opened again.
+ private var yielded = false
+
+ var enabled: Bool {
+ get { UserDefaults.standard.object(forKey: Self.key) as? Bool ?? true }
+ set { UserDefaults.standard.set(newValue, forKey: Self.key); Task { newValue ? await start() : stop() } }
+ }
+
+ /// Called each time Chums comes to the front.
+ func start() async {
+ yielded = false
+ guard enabled, session == nil, !starting else { return }
+ guard HKHealthStore.isHealthDataAvailable() else { problem = "Keyring mode needs Health, which this watch doesn't have."; return }
+ starting = true; defer { starting = false }
+ let type = HKObjectType.workoutType()
+ do {
+ // Only permission to write workouts is needed to run a session; Chums never saves one. Ask every time:
+ // it's a no-op once answered, and watchOS can report "denied" for an app that was in fact allowed, so
+ // the status is logged but never trusted; starting the session is the real test.
+ let request = try await store.statusForAuthorizationRequest(toShare: [type], read: [])
+ onEvent?("keyring health: request \(request == .shouldRequest ? "will show the sheet" : request == .unnecessary ? "already answered" : "unknown"), status \(Self.name(store.authorizationStatus(for: type)))")
+ try await store.requestAuthorization(toShare: [type], read: [])
+ onEvent?("keyring health after asking: \(Self.name(store.authorizationStatus(for: type)))")
+ let config = HKWorkoutConfiguration()
+ config.activityType = .other
+ config.locationType = .indoor
+ let s = try HKWorkoutSession(healthStore: store, configuration: config)
+ begin(s)
+ s.startActivity(with: Date())
+ onEvent?("keyring starting")
+ } catch {
+ problem = "Keyring mode failed: \(error.localizedDescription)"
+ onEvent?("keyring error: \(error.localizedDescription)")
+ session = nil
+ }
+ }
+
+ private static func name(_ s: HKAuthorizationStatus) -> String {
+ switch s { case .sharingAuthorized: "allowed"; case .sharingDenied: "denied"; case .notDetermined: "not asked"; @unknown default: "unknown" }
+ }
+
+ /// watchOS relaunched Chums after it quit with a session running: take the session back.
+ func recover() async {
+ starting = true; defer { starting = false } // start() waits while the old session is taken back
+ do {
+ if let s = try await store.recoverActiveWorkoutSession() { begin(s); running = s.state == .running; onEvent?("keyring recovered after relaunch") }
+ } catch { onEvent?("keyring recovery failed: \(error.localizedDescription)") }
+ }
+
+ private func begin(_ s: HKWorkoutSession) {
+ s.delegate = self
+ session = s
+ problem = nil
+ }
+
+ func stop() {
+ session?.end() // ending without a workout builder saves nothing
+ session = nil
+ running = false
+ onEvent?("keyring stopped")
+ }
+}
+
+extension KeepOn: HKWorkoutSessionDelegate {
+ nonisolated func workoutSession(_ s: HKWorkoutSession, didChangeTo to: HKWorkoutSessionState, from: HKWorkoutSessionState, date: Date) {
+ Task { @MainActor in
+ running = to == .running
+ onEvent?("keyring \(to == .running ? "running" : to == .ended ? "ended" : to == .stopped ? "stopped" : to == .paused ? "paused" : "state \(to.rawValue)")")
+ if to == .ended || to == .stopped {
+ session = nil
+ if enabled && !yielded { try? await Task.sleep(for: .seconds(2)); if !yielded { await start() } }
+ }
+ }
+ }
+
+ nonisolated func workoutSession(_ s: HKWorkoutSession, didFailWithError error: Error) {
+ Task { @MainActor in
+ // a workout started in another app wins; Chums takes the session back the next time it's opened
+ if (error as? HKError)?.code == .errorAnotherWorkoutSessionStarted {
+ yielded = true; problem = "Another workout is running. Keyring mode resumes when you open this app again."
+ onEvent?("keyring yielded to another workout")
+ } else {
+ problem = "Keyring mode failed: \(error.localizedDescription)"
+ onEvent?("keyring failed: \(error.localizedDescription)")
+ }
+ session = nil; running = false
+ }
+ }
+}
+
+/// Relaunched by watchOS because a workout session was running when Chums quit: recover it, so Chums stays in front.
+final class ChumsAppDelegate: NSObject, WKApplicationDelegate {
+ func handleActiveWorkoutRecovery() {
+ Task { @MainActor in await KeepOn.shared.recover() }
+ }
+}
diff --git a/app/ChumsWatch/Noodle/approval_allow.heics b/app/ChumsWatch/Noodle/approval_allow.heics
new file mode 100644
index 0000000..6652478
Binary files /dev/null and b/app/ChumsWatch/Noodle/approval_allow.heics differ
diff --git a/app/ChumsWatch/Noodle/approval_deny.heics b/app/ChumsWatch/Noodle/approval_deny.heics
new file mode 100644
index 0000000..6d62c47
Binary files /dev/null and b/app/ChumsWatch/Noodle/approval_deny.heics differ
diff --git a/app/ChumsWatch/Noodle/approval_hold.heics b/app/ChumsWatch/Noodle/approval_hold.heics
new file mode 100644
index 0000000..179514d
Binary files /dev/null and b/app/ChumsWatch/Noodle/approval_hold.heics differ
diff --git a/app/ChumsWatch/Noodle/approval_in.heics b/app/ChumsWatch/Noodle/approval_in.heics
new file mode 100644
index 0000000..3f5fa44
Binary files /dev/null and b/app/ChumsWatch/Noodle/approval_in.heics differ
diff --git a/app/ChumsWatch/Noodle/approval_rest.heics b/app/ChumsWatch/Noodle/approval_rest.heics
new file mode 100644
index 0000000..cdd2fce
Binary files /dev/null and b/app/ChumsWatch/Noodle/approval_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/approval_wobble.heics b/app/ChumsWatch/Noodle/approval_wobble.heics
new file mode 100644
index 0000000..7da3a9c
Binary files /dev/null and b/app/ChumsWatch/Noodle/approval_wobble.heics differ
diff --git a/app/ChumsWatch/Noodle/blocked_in.heics b/app/ChumsWatch/Noodle/blocked_in.heics
new file mode 100644
index 0000000..b3b7623
Binary files /dev/null and b/app/ChumsWatch/Noodle/blocked_in.heics differ
diff --git a/app/ChumsWatch/Noodle/blocked_rest.heics b/app/ChumsWatch/Noodle/blocked_rest.heics
new file mode 100644
index 0000000..b3e6bc9
Binary files /dev/null and b/app/ChumsWatch/Noodle/blocked_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/blocked_try.heics b/app/ChumsWatch/Noodle/blocked_try.heics
new file mode 100644
index 0000000..0605c27
Binary files /dev/null and b/app/ChumsWatch/Noodle/blocked_try.heics differ
diff --git a/app/ChumsWatch/Noodle/bump.heics b/app/ChumsWatch/Noodle/bump.heics
new file mode 100644
index 0000000..c3315d5
Binary files /dev/null and b/app/ChumsWatch/Noodle/bump.heics differ
diff --git a/app/ChumsWatch/Noodle/compact_out.heics b/app/ChumsWatch/Noodle/compact_out.heics
new file mode 100644
index 0000000..59a825e
Binary files /dev/null and b/app/ChumsWatch/Noodle/compact_out.heics differ
diff --git a/app/ChumsWatch/Noodle/compacting_in.heics b/app/ChumsWatch/Noodle/compacting_in.heics
new file mode 100644
index 0000000..c8e9772
Binary files /dev/null and b/app/ChumsWatch/Noodle/compacting_in.heics differ
diff --git a/app/ChumsWatch/Noodle/compacting_rest.heics b/app/ChumsWatch/Noodle/compacting_rest.heics
new file mode 100644
index 0000000..d461156
Binary files /dev/null and b/app/ChumsWatch/Noodle/compacting_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/dizzy.heics b/app/ChumsWatch/Noodle/dizzy.heics
new file mode 100644
index 0000000..d3fe397
Binary files /dev/null and b/app/ChumsWatch/Noodle/dizzy.heics differ
diff --git a/app/ChumsWatch/Noodle/done_hop.heics b/app/ChumsWatch/Noodle/done_hop.heics
new file mode 100644
index 0000000..0d32369
Binary files /dev/null and b/app/ChumsWatch/Noodle/done_hop.heics differ
diff --git a/app/ChumsWatch/Noodle/done_in.heics b/app/ChumsWatch/Noodle/done_in.heics
new file mode 100644
index 0000000..ace9176
Binary files /dev/null and b/app/ChumsWatch/Noodle/done_in.heics differ
diff --git a/app/ChumsWatch/Noodle/done_rest.heics b/app/ChumsWatch/Noodle/done_rest.heics
new file mode 100644
index 0000000..9480639
Binary files /dev/null and b/app/ChumsWatch/Noodle/done_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/done_wiggle.heics b/app/ChumsWatch/Noodle/done_wiggle.heics
new file mode 100644
index 0000000..051ffe5
Binary files /dev/null and b/app/ChumsWatch/Noodle/done_wiggle.heics differ
diff --git a/app/ChumsWatch/Noodle/idle_hum.heics b/app/ChumsWatch/Noodle/idle_hum.heics
new file mode 100644
index 0000000..d895636
Binary files /dev/null and b/app/ChumsWatch/Noodle/idle_hum.heics differ
diff --git a/app/ChumsWatch/Noodle/idle_look.heics b/app/ChumsWatch/Noodle/idle_look.heics
new file mode 100644
index 0000000..37e498f
Binary files /dev/null and b/app/ChumsWatch/Noodle/idle_look.heics differ
diff --git a/app/ChumsWatch/Noodle/idle_peek.heics b/app/ChumsWatch/Noodle/idle_peek.heics
new file mode 100644
index 0000000..c9c62a9
Binary files /dev/null and b/app/ChumsWatch/Noodle/idle_peek.heics differ
diff --git a/app/ChumsWatch/Noodle/idle_rest.heics b/app/ChumsWatch/Noodle/idle_rest.heics
new file mode 100644
index 0000000..f115dea
Binary files /dev/null and b/app/ChumsWatch/Noodle/idle_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/idle_shake.heics b/app/ChumsWatch/Noodle/idle_shake.heics
new file mode 100644
index 0000000..898549a
Binary files /dev/null and b/app/ChumsWatch/Noodle/idle_shake.heics differ
diff --git a/app/ChumsWatch/Noodle/idle_sideeye.heics b/app/ChumsWatch/Noodle/idle_sideeye.heics
new file mode 100644
index 0000000..6d2d3a0
Binary files /dev/null and b/app/ChumsWatch/Noodle/idle_sideeye.heics differ
diff --git a/app/ChumsWatch/Noodle/idle_yawn.heics b/app/ChumsWatch/Noodle/idle_yawn.heics
new file mode 100644
index 0000000..e9c8926
Binary files /dev/null and b/app/ChumsWatch/Noodle/idle_yawn.heics differ
diff --git a/app/ChumsWatch/Noodle/interrupted.heics b/app/ChumsWatch/Noodle/interrupted.heics
new file mode 100644
index 0000000..9995d4b
Binary files /dev/null and b/app/ChumsWatch/Noodle/interrupted.heics differ
diff --git a/app/ChumsWatch/Noodle/listen_blink.heics b/app/ChumsWatch/Noodle/listen_blink.heics
new file mode 100644
index 0000000..e3b4193
Binary files /dev/null and b/app/ChumsWatch/Noodle/listen_blink.heics differ
diff --git a/app/ChumsWatch/Noodle/listen_lean.heics b/app/ChumsWatch/Noodle/listen_lean.heics
new file mode 100644
index 0000000..a14c778
Binary files /dev/null and b/app/ChumsWatch/Noodle/listen_lean.heics differ
diff --git a/app/ChumsWatch/Noodle/listen_mhm.heics b/app/ChumsWatch/Noodle/listen_mhm.heics
new file mode 100644
index 0000000..90eb97b
Binary files /dev/null and b/app/ChumsWatch/Noodle/listen_mhm.heics differ
diff --git a/app/ChumsWatch/Noodle/listen_nod.heics b/app/ChumsWatch/Noodle/listen_nod.heics
new file mode 100644
index 0000000..f4020d4
Binary files /dev/null and b/app/ChumsWatch/Noodle/listen_nod.heics differ
diff --git a/app/ChumsWatch/Noodle/listen_oh.heics b/app/ChumsWatch/Noodle/listen_oh.heics
new file mode 100644
index 0000000..55ee966
Binary files /dev/null and b/app/ChumsWatch/Noodle/listen_oh.heics differ
diff --git a/app/ChumsWatch/Noodle/listen_tilt_l.heics b/app/ChumsWatch/Noodle/listen_tilt_l.heics
new file mode 100644
index 0000000..bd75547
Binary files /dev/null and b/app/ChumsWatch/Noodle/listen_tilt_l.heics differ
diff --git a/app/ChumsWatch/Noodle/listen_tilt_r.heics b/app/ChumsWatch/Noodle/listen_tilt_r.heics
new file mode 100644
index 0000000..b2c3d37
Binary files /dev/null and b/app/ChumsWatch/Noodle/listen_tilt_r.heics differ
diff --git a/app/ChumsWatch/Noodle/listening_in.heics b/app/ChumsWatch/Noodle/listening_in.heics
new file mode 100644
index 0000000..754d14b
Binary files /dev/null and b/app/ChumsWatch/Noodle/listening_in.heics differ
diff --git a/app/ChumsWatch/Noodle/listening_rest.heics b/app/ChumsWatch/Noodle/listening_rest.heics
new file mode 100644
index 0000000..8641812
Binary files /dev/null and b/app/ChumsWatch/Noodle/listening_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/needs_in.heics b/app/ChumsWatch/Noodle/needs_in.heics
new file mode 100644
index 0000000..828e3e6
Binary files /dev/null and b/app/ChumsWatch/Noodle/needs_in.heics differ
diff --git a/app/ChumsWatch/Noodle/needs_rest.heics b/app/ChumsWatch/Noodle/needs_rest.heics
new file mode 100644
index 0000000..e756fc7
Binary files /dev/null and b/app/ChumsWatch/Noodle/needs_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/needs_slide.heics b/app/ChumsWatch/Noodle/needs_slide.heics
new file mode 100644
index 0000000..b77b3f3
Binary files /dev/null and b/app/ChumsWatch/Noodle/needs_slide.heics differ
diff --git a/app/ChumsWatch/Noodle/needs_tap.heics b/app/ChumsWatch/Noodle/needs_tap.heics
new file mode 100644
index 0000000..16077ea
Binary files /dev/null and b/app/ChumsWatch/Noodle/needs_tap.heics differ
diff --git a/app/ChumsWatch/Noodle/noodle.json b/app/ChumsWatch/Noodle/noodle.json
new file mode 100644
index 0000000..9609038
--- /dev/null
+++ b/app/ChumsWatch/Noodle/noodle.json
@@ -0,0 +1 @@
+{"fps":24,"w":396,"h":484,"beat_chance":{"idle":0.45,"listening":0.5,"thinking":0.6,"working":0.35,"subagents":0.45,"speaking":0.85,"done":0.5,"needs":0.35,"approval":0.3,"blocked":0.35,"waiting":0.4,"sleep":0.15},"clips":{"idle_rest":{"n":144,"loop":true,"role":"rest","state":"idle","events":{},"frames":[[120.3,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.5,96.3,120.5,-0.1,0.0,0.0],[119.5,37.3,96.6,120.3,-0.1,0.0,0.0],[119.9,37.0,96.7,120.2,-0.1,0.0,0.0],[119.0,36.8,96.8,120.1,0.0,0.0,0.0],[119.4,36.5,96.9,120.0,-0.1,0.0,0.0],[118.9,36.3,97.1,119.8,-0.1,0.0,0.0],[118.9,36.1,97.2,119.7,0.0,0.0,0.0],[119.2,35.8,97.3,119.6,0.0,0.0,0.0],[119.2,35.6,97.4,119.5,0.0,0.0,0.0],[118.8,35.5,97.5,119.4,0.0,0.0,0.0],[118.9,35.3,97.6,119.3,0.0,0.0,0.0],[118.9,35.1,97.7,119.2,0.0,0.0,0.0],[118.9,35.0,97.8,119.2,-0.1,0.0,0.0],[118.9,34.9,97.8,119.1,0.0,0.0,0.0],[119.0,34.8,97.7,119.0,-0.1,0.0,0.0],[118.9,34.7,97.5,119.0,0.0,0.0,0.0],[119.0,34.7,97.5,119.0,0.0,0.0,0.0],[119.7,34.6,97.3,119.0,0.0,0.0,0.0],[120.1,34.6,97.1,119.0,0.0,0.0,0.0],[120.5,34.6,96.9,119.0,0.0,0.0,0.0],[120.5,34.6,96.7,119.0,0.1,0.0,0.0],[120.6,34.7,96.5,119.1,0.0,0.0,0.0],[120.7,34.7,96.2,119.2,0.1,0.0,0.0],[120.9,34.8,96.0,119.2,0.0,0.0,0.0],[121.6,34.9,95.8,119.3,0.0,0.0,0.0],[121.3,35.1,95.7,119.4,0.0,0.0,0.0],[122.0,35.2,95.5,119.5,0.0,0.0,0.0],[122.0,35.4,95.5,119.6,0.0,0.0,0.0],[122.0,35.6,95.5,119.7,0.0,0.0,0.0],[121.7,35.9,95.3,119.8,0.1,0.0,0.0],[121.9,36.1,95.3,120.0,0.1,0.0,0.0],[122.0,36.4,95.3,120.1,0.0,0.0,0.0],[121.6,36.7,95.3,120.2,0.1,0.0,0.0],[121.6,37.0,95.2,120.4,0.0,0.0,0.0],[121.9,37.2,95.2,120.5,0.1,0.0,0.0],[122.0,37.5,95.2,120.7,0.0,0.0,0.0],[122.0,37.8,95.2,120.8,0.1,0.0,0.0],[121.9,38.1,95.2,121.0,0.1,0.0,0.0],[121.6,38.4,95.2,121.2,0.1,0.0,0.0],[121.3,38.7,95.1,121.2,0.1,0.0,0.0],[121.9,38.9,95.1,121.4,0.0,0.0,0.0],[121.3,39.2,95.1,121.5,0.1,0.0,0.0],[120.7,39.5,95.2,121.7,0.1,0.0,0.0],[121.1,39.7,95.2,121.8,0.0,0.0,0.0],[121.3,39.9,95.2,121.9,0.0,0.0,0.0],[120.9,40.1,95.3,122.0,0.0,0.0,0.0],[120.8,40.3,95.4,122.1,0.0,0.0,0.0],[120.7,40.5,95.5,122.2,0.1,0.0,0.0],[120.8,40.7,95.5,122.2,0.0,0.0,0.0],[120.7,40.8,95.7,122.3,0.0,0.0,0.0],[120.7,40.9,95.8,122.3,0.0,0.0,0.0],[120.4,41.0,95.9,122.3,0.1,0.0,0.0],[119.7,41.1,96.0,122.4,0.0,0.0,0.0],[119.6,41.1,96.2,122.4,0.0,0.0,0.0],[119.6,41.1,96.3,122.4,0.0,0.0,0.0],[119.5,41.1,96.6,122.3,0.1,0.0,0.0],[119.3,41.1,96.8,122.3,0.0,0.0,0.0],[119.3,41.0,96.9,122.3,0.0,0.0,0.0],[118.9,41.0,97.2,122.2,0.0,0.0,0.0],[118.9,40.9,97.3,122.2,0.0,0.0,0.0],[118.6,40.8,97.6,122.1,0.0,0.0,0.0],[118.5,40.6,97.8,122.0,0.0,0.0,0.0],[118.2,40.5,98.0,121.9,0.0,0.0,0.0],[118.2,40.3,98.2,121.8,0.0,0.0,0.0],[118.1,40.1,98.4,121.7,0.0,0.0,0.0],[117.7,39.9,98.7,121.5,0.0,0.0,0.0],[117.6,39.7,98.9,121.4,0.0,0.0,0.0],[116.9,39.5,99.2,121.3,0.0,0.0,0.0],[116.9,39.2,99.4,121.1,0.0,0.0,0.0],[116.7,39.0,99.6,121.0,0.0,0.0,0.0],[116.6,38.7,99.8,120.8,0.0,0.0,0.0],[116.5,38.5,100.0,120.7,0.0,0.0,0.0],[116.5,38.2,100.2,120.5,0.0,0.0,0.0],[116.5,37.9,100.4,120.4,0.0,0.0,0.0],[116.1,37.7,100.6,120.2,0.0,0.0,0.0],[116.0,37.4,100.8,120.1,0.0,0.0,0.0],[116.1,37.2,100.9,120.0,0.0,0.0,0.0],[115.8,37.0,101.1,119.8,0.0,0.0,0.0],[115.9,36.7,101.2,119.7,0.0,0.0,0.0],[115.8,36.5,101.3,119.6,0.0,0.0,0.0],[115.8,36.3,101.5,119.5,0.0,0.0,0.0],[115.8,36.1,101.5,119.4,0.0,0.0,0.0],[115.2,36.0,101.6,119.3,0.0,0.0,0.0],[115.5,35.8,101.7,119.2,0.0,0.0,0.0],[115.3,35.7,101.8,119.1,0.0,0.0,0.0],[115.1,35.6,101.8,119.1,0.0,0.0,0.0],[115.4,35.5,101.8,119.0,0.0,0.0,0.0],[115.6,35.4,101.8,119.0,0.0,0.0,0.0],[115.4,35.4,101.8,119.0,0.0,0.0,0.0],[115.7,35.3,101.8,119.0,0.0,0.0,0.0],[115.6,35.3,101.8,119.0,0.0,0.0,0.0],[115.6,35.4,101.8,119.0,0.0,0.0,0.0],[115.6,35.4,101.7,119.0,-0.1,0.0,0.0],[115.5,35.5,101.7,119.1,0.0,0.0,0.0],[115.6,35.6,101.6,119.2,-0.1,0.0,0.0],[115.6,35.7,101.5,119.2,0.0,0.0,0.0],[115.9,35.8,101.5,119.3,0.0,0.0,0.0],[115.8,36.0,101.3,119.4,0.0,0.0,0.0],[115.9,36.2,101.2,119.5,0.0,0.0,0.0],[115.8,36.4,101.2,119.6,0.0,0.0,0.0],[115.9,36.6,101.0,119.7,0.0,0.0,0.0],[115.9,36.8,100.8,119.8,-0.1,0.0,0.0],[116.2,37.0,100.7,120.0,-0.1,0.0,0.0],[116.8,37.2,100.3,120.1,0.0,0.0,0.0],[116.7,37.5,100.1,120.2,-0.1,0.0,0.0],[117.1,37.7,99.8,120.3,-0.1,0.0,0.0],[116.8,38.0,99.5,120.5,-0.1,0.0,0.0],[117.4,38.2,99.2,120.7,-0.1,0.0,0.0],[117.5,38.4,98.8,120.8,-0.1,0.0,0.0],[118.0,38.6,98.5,121.0,-0.1,0.0,0.0],[118.1,38.9,98.1,121.2,-0.1,0.0,0.0],[118.3,39.1,97.7,121.2,-0.1,0.0,0.0],[118.3,39.3,97.3,121.4,-0.3,0.0,0.0],[118.8,39.5,96.9,121.5,-0.1,0.0,0.0],[119.4,39.7,96.5,121.7,-0.1,0.0,0.0],[119.7,39.8,96.2,121.8,-0.3,0.0,0.0],[119.7,40.0,95.8,121.9,-0.3,0.0,0.0],[120.3,40.1,95.5,122.0,-0.3,0.0,0.0],[119.9,40.3,95.3,122.1,-0.3,0.0,0.0],[120.4,40.4,95.0,122.2,-0.3,0.0,0.0],[120.9,40.5,94.9,122.2,-0.3,0.0,0.0],[121.0,40.6,94.7,122.3,-0.3,0.0,0.0],[121.0,40.6,94.6,122.3,-0.3,0.0,0.0],[121.1,40.7,94.5,122.4,-0.3,0.0,0.0],[121.1,40.7,94.4,122.4,-0.3,0.0,0.0],[121.1,40.7,94.4,122.4,-0.3,0.0,0.0],[121.1,40.7,94.4,122.4,-0.3,0.0,0.0],[121.2,40.7,94.4,122.4,-0.3,0.0,0.0],[121.1,40.7,94.5,122.3,-0.3,0.0,0.0],[121.1,40.6,94.6,122.3,-0.3,0.0,0.0],[121.0,40.5,94.7,122.2,-0.3,0.0,0.0],[120.5,40.4,94.8,122.2,-0.3,0.0,0.0],[120.1,40.3,94.8,122.1,-0.3,0.0,0.0],[120.6,40.1,94.9,122.0,-0.3,0.0,0.0],[120.6,39.9,95.1,121.9,-0.3,0.0,0.0],[120.1,39.8,95.2,121.8,-0.3,0.0,0.0],[120.1,39.6,95.3,121.7,-0.1,0.0,0.0],[120.2,39.3,95.4,121.5,-0.1,0.0,0.0],[120.2,39.1,95.6,121.4,-0.3,0.0,0.0],[120.2,38.9,95.7,121.2,-0.1,0.0,0.0],[120.2,38.6,95.8,121.2,-0.1,0.0,0.0],[120.2,38.3,95.9,121.0,-0.1,0.0,0.0],[120.3,38.1,96.1,120.8,-0.1,0.0,0.0]],"scrub":false},"idle_look":{"n":96,"loop":false,"role":"beat","state":"idle","events":{},"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.6,96.2,120.5,-0.1,0.0,0.0],[120.1,37.4,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.9,96.2,120.2,-0.1,0.0,0.0],[120.1,36.7,96.2,120.2,-0.1,0.0,0.0],[120.2,36.5,96.2,120.0,-0.1,0.0,0.0],[120.2,36.3,96.2,120.0,-0.1,0.0,0.0],[120.2,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[122.4,33.8,94.0,119.2,-0.3,0.0,0.0],[126.9,29.9,89.3,118.0,-0.7,0.0,0.0],[126.6,27.2,85.6,117.2,-1.3,0.0,0.0],[125.5,24.5,82.8,116.5,-1.5,0.0,0.0],[124.7,22.8,80.7,116.0,-2.0,0.0,0.0],[124.5,22.1,79.2,115.5,-2.3,0.0,0.0],[123.9,21.4,78.2,115.2,-2.6,0.0,0.0],[122.9,21.3,77.5,114.9,-2.9,0.0,0.0],[122.0,21.7,77.2,114.8,-3.0,0.0,0.0],[122.0,22.3,77.0,114.7,-3.0,0.01,0.0],[122.8,23.0,77.0,114.7,-2.7,0.01,0.0],[123.3,23.5,77.3,114.7,-2.7,0.01,0.0],[123.7,23.8,77.5,114.7,-2.9,0.01,0.0],[123.7,23.9,77.8,114.8,-2.6,0.02,0.0],[123.8,23.8,78.2,114.8,-2.8,0.02,0.0],[123.5,23.5,78.4,114.8,-2.5,0.02,0.0],[123.2,23.0,78.5,114.8,-2.5,0.03,0.0],[123.8,22.5,78.5,114.8,-2.5,0.03,0.0],[124.4,22.0,78.5,114.8,-2.5,0.03,0.0],[124.5,21.7,78.5,114.8,-2.5,0.04,0.0],[124.4,21.5,78.5,114.8,-2.5,0.04,0.0],[124.5,21.5,78.5,114.9,-2.5,0.05,0.0],[124.5,21.6,78.6,114.9,-2.5,0.05,0.0],[124.6,21.8,78.7,115.1,-2.3,0.06,0.0],[124.7,22.2,78.8,115.2,-2.2,0.06,0.0],[124.4,22.7,79.0,115.3,-2.4,0.07,0.0],[124.4,23.2,79.2,115.5,-2.2,0.07,0.0],[124.5,23.7,79.5,115.7,-2.2,0.08,0.0],[124.9,24.2,79.7,116.0,-2.0,0.08,0.0],[124.9,24.7,80.0,116.2,-2.1,0.09,0.0],[125.3,25.2,80.3,116.5,-1.9,0.09,0.0],[125.4,25.8,80.7,116.8,-1.9,0.1,0.0],[125.6,26.3,81.0,117.0,-1.7,0.1,0.0],[125.8,26.8,81.4,117.3,-1.5,0.1,0.0],[125.9,27.4,81.9,117.7,-1.5,0.11,0.0],[126.1,27.9,82.2,118.0,-1.4,0.11,0.0],[126.2,28.5,82.7,118.3,-1.3,0.12,0.0],[126.3,29.0,83.1,118.6,-1.2,0.12,0.0],[126.7,29.6,83.5,118.9,-1.2,0.12,0.0],[126.8,30.1,83.8,119.2,-1.1,0.12,0.0],[126.9,30.6,84.1,119.4,-1.1,0.13,0.0],[126.6,31.0,84.5,119.7,-0.9,0.13,0.0],[127.0,31.5,84.7,119.9,-1.0,0.13,0.0],[127.0,31.8,84.9,120.2,-1.0,0.13,0.0],[127.0,32.2,85.1,120.3,-1.0,0.13,0.0],[127.0,32.5,85.2,120.5,-0.9,0.13,0.0],[126.9,32.8,85.3,120.7,-0.9,0.13,0.0],[126.8,33.0,85.3,120.8,-0.9,0.13,0.0],[126.8,33.2,85.4,120.9,-0.9,0.13,0.0],[126.8,33.4,85.4,121.0,-0.9,0.13,0.0],[126.9,33.5,85.4,121.1,-0.9,0.13,0.0],[126.8,33.7,85.4,121.2,-0.7,0.13,0.0],[126.7,33.9,85.3,121.2,-0.7,0.13,0.0],[126.9,34.0,85.3,121.3,-0.9,0.13,0.0],[126.9,34.2,85.3,121.3,-0.7,0.13,0.0],[126.9,34.3,85.3,121.5,-0.7,0.13,0.0],[127.0,34.4,85.3,121.5,-0.7,0.13,0.0],[127.0,34.5,85.3,121.5,-0.9,0.13,0.0],[127.0,34.6,85.3,121.5,-0.7,0.13,0.0],[126.8,34.6,85.3,121.5,-0.7,0.13,0.0],[126.8,34.7,85.3,121.6,-0.9,0.13,0.0],[126.7,34.8,85.5,121.7,-0.7,0.13,0.0],[126.9,35.2,86.0,121.7,-0.7,0.13,0.0],[126.6,35.9,86.9,121.8,-0.7,0.11,0.0],[125.5,36.8,88.2,121.8,-0.6,0.1,0.0],[124.3,37.9,89.8,121.9,-0.6,0.08,0.0],[122.0,39.0,91.4,121.9,-0.4,0.06,0.0],[120.1,40.0,93.1,122.1,-0.3,0.04,0.0],[118.4,40.7,94.4,122.1,-0.3,0.02,0.0],[118.0,41.0,95.4,122.2,-0.1,0.01,0.0],[117.9,41.0,96.0,122.2,-0.1,0.0,0.0],[118.7,40.7,96.2,122.2,-0.1,0.0,0.0],[119.4,40.3,96.2,122.0,-0.1,0.0,0.0],[119.9,40.0,96.2,122.0,-0.1,0.0,0.0],[120.0,39.7,96.2,121.8,-0.1,0.0,0.0],[120.1,39.5,96.2,121.8,-0.1,0.0,0.0],[120.3,39.3,96.2,121.8,-0.1,0.0,0.0],[120.6,39.2,96.2,121.7,-0.1,0.0,0.0],[120.9,39.1,96.2,121.5,-0.1,0.0,0.0],[120.8,39.0,96.2,121.5,-0.1,0.0,0.0],[120.3,38.9,96.2,121.3,-0.1,0.0,0.0],[120.3,38.8,96.2,121.2,-0.1,0.0,0.0],[119.6,38.7,96.2,121.2,-0.1,0.0,0.0],[119.3,38.5,96.2,121.0,-0.1,0.0,0.0],[119.3,38.3,96.2,121.0,-0.1,0.0,0.0],[119.3,38.1,96.2,120.8,-0.3,0.0,0.0]],"scrub":false},"idle_shake":{"n":77,"loop":false,"role":"beat","state":"idle","events":{},"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.5,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.2,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.1,0.0,0.0],[120.1,36.5,96.2,120.0,-0.1,0.0,0.0],[120.2,36.2,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.5,96.2,119.5,-0.1,0.0,0.0],[120.2,35.2,96.3,119.5,-0.1,0.0,0.0],[120.8,38.2,98.0,122.5,-0.1,0.0,0.0],[117.1,45.8,102.3,127.8,-0.3,0.0,0.0],[114.9,51.6,106.7,129.9,-0.4,0.0,0.0],[112.9,50.8,112.3,127.4,-0.5,0.0,0.0],[113.4,48.9,121.3,124.6,-0.4,0.0,0.0],[109.3,44.1,121.4,122.0,0.0,0.0,0.0],[95.7,38.2,100.4,119.4,0.0,0.0,0.0],[85.2,38.0,77.5,117.7,-0.7,0.0,0.0],[99.5,29.5,77.8,115.8,-0.9,0.0,0.0],[131.9,16.7,100.1,114.0,0.1,0.0,0.0],[134.8,13.9,118.8,113.0,1.0,0.0,0.0],[126.1,14.5,116.8,111.8,1.0,0.0,0.0],[120.8,9.9,94.2,110.6,-0.3,0.0,0.0],[106.2,13.1,80.0,110.2,-1.2,0.0,0.0],[118.6,9.7,83.3,109.5,-1.1,0.0,0.0],[122.5,12.6,103.5,109.0,0.3,0.0,0.0],[120.5,14.3,113.6,108.9,1.0,0.0,0.0],[117.1,15.1,109.8,108.7,0.6,0.0,0.0],[112.7,11.9,95.1,108.7,-0.1,0.0,0.0],[107.8,12.6,89.5,108.8,-0.6,0.0,0.0],[114.6,11.2,92.5,109.0,-0.3,0.0,0.0],[120.3,11.9,100.8,109.2,0.1,0.0,0.0],[121.7,12.8,103.2,109.6,0.3,0.0,0.0],[121.8,13.1,102.0,110.0,0.1,0.0,0.0],[122.2,13.3,99.5,110.3,0.1,0.0,0.0],[121.6,14.3,99.0,110.8,0.0,0.0,0.0],[121.6,15.4,99.0,111.2,0.0,0.0,0.0],[121.6,16.4,99.0,111.6,0.0,0.0,0.0],[121.7,17.4,99.0,112.0,0.0,0.0,0.0],[121.3,18.2,99.0,112.3,0.0,0.0,0.0],[121.2,18.8,99.0,112.6,0.0,0.0,0.0],[121.3,19.2,99.0,112.7,0.0,0.0,0.0],[121.5,19.4,99.0,112.9,0.0,0.0,0.0],[121.6,19.6,99.0,113.0,0.0,0.0,0.0],[121.6,19.8,99.0,113.1,0.0,0.0,0.0],[121.1,20.0,99.0,113.3,0.0,0.0,0.0],[120.7,20.2,99.0,113.4,0.0,0.0,0.0],[121.0,20.4,99.0,113.5,0.0,0.0,0.0],[121.3,20.6,99.0,113.6,0.0,0.0,0.0],[121.4,20.8,99.0,113.7,0.0,0.0,0.0],[121.4,21.0,99.0,113.8,0.0,0.0,0.0],[121.3,21.2,99.0,113.8,0.0,0.0,0.0],[121.3,21.3,99.0,113.9,0.0,0.0,0.0],[121.3,21.4,99.0,114.0,0.0,0.0,0.0],[121.3,21.5,99.0,114.0,0.0,0.0,0.0],[121.3,21.7,99.0,114.1,0.0,0.0,0.0],[120.6,23.2,98.8,114.9,0.0,0.0,0.0],[120.1,26.4,98.2,116.5,0.0,0.0,0.0],[119.0,31.0,97.5,118.7,-0.1,0.0,0.0],[118.7,35.7,96.8,120.6,0.0,0.0,0.0],[118.7,39.4,96.4,121.8,-0.1,0.0,0.0],[118.8,41.4,96.2,122.2,-0.1,0.0,0.0],[119.0,42.2,96.2,122.2,-0.1,0.0,0.0],[119.6,42.4,96.2,122.2,-0.1,0.0,0.0],[120.2,42.0,96.2,122.0,-0.1,0.0,0.0],[120.4,41.3,96.2,122.0,-0.1,0.0,0.0],[120.4,40.4,96.2,122.0,-0.1,0.0,0.0],[120.4,39.7,96.2,121.8,-0.1,0.0,0.0],[120.5,39.1,96.2,121.8,-0.1,0.0,0.0],[120.4,38.8,96.2,121.5,-0.1,0.0,0.0],[119.8,38.7,96.2,121.5,-0.1,0.0,0.0],[120.1,38.6,96.2,121.3,-0.1,0.0,0.0],[119.5,38.7,96.2,121.2,-0.1,0.0,0.0],[120.0,38.6,96.2,121.0,-0.1,0.0,0.0],[120.0,38.5,96.2,121.0,-0.1,0.0,0.0],[120.0,38.3,96.2,120.8,-0.3,0.0,0.0]],"scrub":false},"idle_sideeye":{"n":86,"loop":false,"role":"beat","state":"idle","events":{},"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.5,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.3,0.0,0.0],[120.1,36.6,96.2,120.0,-0.1,0.0,0.0],[120.1,36.3,96.2,120.0,-0.1,0.0,0.0],[120.0,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.5,96.2,119.5,-0.1,0.0,0.0],[120.1,35.4,96.3,119.5,-0.1,0.0,0.0],[119.2,35.4,96.7,119.3,-0.1,0.0,0.0],[118.7,35.5,97.3,119.3,0.0,0.0,0.0],[117.2,35.8,98.3,119.2,0.0,0.0,0.0],[115.8,36.2,99.7,119.2,0.0,0.0,0.0],[114.0,36.6,101.3,119.2,0.1,0.0,0.0],[112.7,37.1,103.2,119.1,0.3,0.0,0.0],[111.8,37.5,105.2,119.1,0.4,0.0,0.0],[111.1,37.9,107.1,119.1,0.6,0.0,0.0],[110.3,37.8,108.8,119.0,0.7,0.0,0.0],[109.7,37.7,110.5,119.1,0.9,0.0,0.0],[109.3,37.6,111.6,119.1,0.9,0.0,0.0],[108.8,37.6,112.6,119.2,1.1,0.0,0.0],[108.7,37.5,113.1,119.2,1.1,0.0,0.0],[108.9,37.2,113.5,119.2,1.3,0.0,0.0],[108.6,36.9,113.5,119.2,1.1,0.0,0.0],[108.8,36.8,113.5,119.2,1.1,0.0,0.0],[109.3,36.8,113.5,119.3,1.1,0.0,0.0],[109.1,37.0,113.5,119.3,1.1,0.0,0.0],[109.1,37.3,113.5,119.4,1.1,0.0,0.0],[109.3,37.6,113.5,119.6,1.1,0.0,0.0],[109.4,37.9,113.5,119.6,1.3,0.0,0.0],[109.5,38.3,113.5,119.7,1.1,0.0,0.0],[109.2,38.6,113.5,119.8,1.1,0.0,0.0],[108.9,38.9,113.5,119.8,1.1,0.0,0.0],[109.0,39.1,113.5,119.9,1.1,0.0,0.0],[108.7,39.4,113.6,120.1,1.1,0.0,0.0],[108.7,39.6,113.6,120.2,1.1,0.0,0.0],[108.8,39.7,113.6,120.3,1.1,0.0,0.0],[108.9,39.9,113.6,120.4,1.1,0.0,0.0],[108.9,40.1,113.6,120.6,1.1,0.0,0.0],[109.0,40.3,113.6,120.7,1.1,0.0,0.0],[109.1,40.5,113.6,120.8,1.0,0.0,0.0],[109.1,40.7,113.6,120.9,1.1,0.0,0.0],[109.3,40.9,113.6,121.1,1.1,0.0,0.0],[109.4,41.1,113.6,121.2,1.1,0.0,0.0],[109.0,41.4,113.6,121.3,1.0,0.0,0.0],[109.2,41.6,113.6,121.4,1.0,0.0,0.0],[109.3,41.8,113.7,121.5,0.9,0.0,0.0],[109.0,42.1,113.7,121.6,0.9,0.0,0.0],[109.0,42.3,113.7,121.8,1.1,0.0,0.0],[108.9,42.5,113.7,121.8,1.1,0.0,0.0],[108.9,42.7,113.7,121.9,0.9,0.0,0.0],[109.1,42.8,113.7,122.0,0.9,0.0,0.0],[108.9,43.0,113.7,122.1,0.9,0.0,0.0],[109.1,43.1,113.7,122.2,0.9,0.0,0.0],[108.8,43.3,113.7,122.2,1.1,0.0,0.0],[108.8,43.4,113.7,122.3,0.9,0.0,0.0],[108.8,43.5,113.7,122.4,0.9,0.0,0.0],[108.8,43.6,113.7,122.4,0.9,0.0,0.0],[109.1,43.6,113.7,122.4,1.1,0.0,0.0],[108.9,43.7,113.7,122.5,0.9,0.0,0.0],[109.1,43.7,113.7,122.5,0.9,0.0,0.0],[109.1,43.7,113.7,122.5,0.9,0.0,0.0],[108.8,43.8,113.7,122.5,0.9,0.0,0.0],[109.4,43.5,113.2,122.5,0.9,0.0,0.0],[110.5,42.5,110.9,122.5,0.7,0.0,0.0],[114.2,41.1,107.1,122.4,0.6,0.0,0.0],[116.5,39.8,102.5,122.3,0.3,0.0,0.0],[122.1,39.0,98.7,122.3,0.0,0.0,0.0],[123.9,38.7,96.7,122.2,-0.1,0.0,0.0],[122.1,39.2,96.2,122.2,-0.1,0.0,0.0],[122.2,39.8,96.2,122.0,-0.1,0.0,0.0],[120.1,40.5,96.2,122.0,-0.1,0.0,0.0],[118.3,40.9,96.2,122.0,-0.1,0.0,0.0],[117.0,41.1,96.2,121.8,-0.1,0.0,0.0],[116.3,41.1,96.2,121.8,-0.1,0.0,0.0],[116.4,40.8,96.2,121.7,-0.1,0.0,0.0],[116.2,40.5,96.2,121.5,-0.1,0.0,0.0],[117.2,40.0,96.2,121.5,-0.1,0.0,0.0],[118.2,39.5,96.2,121.3,-0.1,0.0,0.0],[118.8,39.0,96.2,121.2,-0.1,0.0,0.0],[119.8,38.6,96.2,121.2,-0.1,0.0,0.0],[119.8,38.2,96.2,121.0,-0.1,0.0,0.0],[120.6,37.8,96.2,120.8,-0.1,0.0,0.0]],"scrub":false},"idle_yawn":{"n":86,"loop":false,"role":"beat","state":"idle","events":{},"frames":[[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.9,96.2,120.8,-0.1,0.0,0.0],[120.4,38.6,96.3,121.3,0.0,0.0,0.0],[120.6,39.7,96.6,122.2,-0.1,0.0,0.0],[120.7,41.4,96.8,123.2,0.0,0.0,0.01],[119.9,43.5,97.1,124.4,0.0,0.0,0.01],[119.9,45.7,97.5,125.4,0.0,0.0,0.02],[119.5,47.6,97.8,126.0,0.1,0.0,0.02],[118.8,49.1,98.1,126.2,0.0,0.0,0.03],[118.0,49.9,98.2,125.8,0.1,0.0,0.04],[116.7,50.2,98.3,124.8,0.1,0.0,0.05],[115.3,50.0,98.4,123.5,0.1,0.0,0.06],[114.7,49.5,98.5,122.0,0.0,0.0,0.07],[113.9,48.3,98.5,120.0,0.0,0.0,0.09],[113.7,45.8,98.7,117.3,0.0,0.0,0.1],[114.9,42.1,98.7,113.9,0.0,0.0,0.11],[113.8,37.4,98.8,109.8,0.0,0.0,0.12],[112.6,32.0,98.8,105.3,0.0,0.0,0.13],[110.3,26.0,98.9,100.5,-0.1,0.0,0.14],[109.0,19.6,98.9,95.5,-0.1,0.0,0.15],[109.1,13.2,98.9,90.8,0.0,0.0,0.16],[109.1,7.2,98.9,86.5,0.0,0.0,0.17],[108.9,1.9,98.9,82.7,0.0,0.0,0.17],[108.9,-2.5,99.0,79.7,0.0,0.0,0.18],[108.9,-5.7,99.0,77.6,0.0,0.0,0.18],[108.9,-7.7,99.0,76.2,0.0,0.0,0.18],[108.8,-8.5,99.0,75.6,0.0,0.0,0.18],[108.8,-8.5,99.0,75.5,0.0,0.0,0.18],[108.6,-8.1,99.0,75.5,0.0,0.0,0.18],[108.7,-7.7,99.0,75.5,0.0,0.0,0.18],[108.6,-7.2,99.0,75.5,0.0,0.0,0.18],[108.5,-6.9,99.0,75.5,0.0,0.0,0.18],[108.5,-6.8,99.0,75.5,0.0,0.0,0.18],[108.6,-6.9,99.0,75.5,0.0,0.0,0.18],[108.5,-7.1,99.0,75.5,0.0,0.0,0.18],[108.6,-7.3,99.0,75.5,0.0,0.0,0.18],[108.6,-7.5,99.0,75.5,0.0,0.0,0.18],[108.6,-7.6,99.0,75.5,0.0,0.0,0.18],[108.6,-7.4,99.0,75.5,0.0,0.0,0.18],[109.6,9.2,99.0,96.3,0.0,0.0,0.11],[109.9,26.0,99.0,112.1,0.0,0.0,0.06],[114.4,39.0,98.9,123.2,0.0,0.0,0.02],[115.1,48.9,98.9,130.3,0.0,0.0,-0.01],[120.5,54.4,98.8,134.0,0.0,0.0,-0.02],[121.0,57.4,98.8,135.1,0.0,0.0,-0.02],[121.7,56.9,98.7,134.4,0.0,0.0,-0.02],[121.7,54.7,98.6,132.6,0.0,0.0,-0.01],[122.4,50.6,98.4,130.5,0.0,0.0,-0.01],[124.2,46.5,98.3,128.8,0.0,0.0,-0.0],[125.4,44.1,98.2,128.2,0.0,0.0,0.0],[125.2,43.4,98.0,128.1,-0.1,0.0,0.0],[120.7,43.6,97.8,127.8,-0.1,0.0,0.0],[118.5,44.1,97.7,127.2,-0.1,0.0,0.0],[117.2,44.4,97.4,126.5,0.0,0.0,0.0],[117.6,44.3,97.2,125.7,-0.1,0.0,0.0],[117.8,43.8,97.0,124.7,-0.1,0.0,0.0],[118.8,42.8,96.8,123.7,-0.1,0.0,0.0],[118.8,41.5,96.6,122.7,-0.1,0.0,0.0],[120.2,40.0,96.5,121.8,-0.1,0.0,0.0],[121.8,38.6,96.3,121.2,-0.1,0.0,0.0],[121.4,37.6,96.3,120.8,-0.1,0.0,0.0],[121.1,37.0,96.2,120.8,-0.1,0.0,0.0],[121.3,36.8,96.2,120.7,-0.1,0.0,0.0],[120.4,37.0,96.2,120.7,-0.1,0.0,0.0],[120.2,37.2,96.2,120.7,-0.1,0.0,0.0],[119.9,37.6,96.2,120.7,-0.1,0.0,0.0],[119.7,37.9,96.2,120.7,-0.1,0.0,0.0],[119.5,38.1,96.2,120.7,-0.1,0.0,0.0],[119.9,38.1,96.2,120.7,-0.1,0.0,0.0],[120.0,38.1,96.2,120.7,-0.1,0.0,0.0],[120.0,38.0,96.2,120.7,-0.1,0.0,0.0],[120.2,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.6,96.2,120.7,-0.1,0.0,0.0],[120.2,37.6,96.2,120.7,-0.1,0.0,0.0],[120.2,37.6,96.2,120.7,-0.1,0.0,0.0]],"scrub":false},"idle_hum":{"n":86,"loop":false,"role":"beat","state":"idle","events":{},"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.6,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.3,0.0,0.0],[120.1,36.6,96.2,120.0,-0.1,0.0,0.0],[120.1,36.3,96.2,120.0,-0.1,0.0,0.0],[120.0,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.5,96.2,119.5,-0.1,0.0,0.0],[120.4,35.3,96.5,119.5,-0.1,0.0,0.0],[120.4,35.2,97.4,119.3,-0.1,0.0,0.0],[120.5,35.2,98.9,119.3,0.0,0.0,0.0],[119.6,35.3,100.8,119.2,0.1,0.0,0.0],[118.5,35.5,103.0,119.2,0.3,0.0,0.0],[116.7,35.7,104.8,119.2,0.4,0.0,0.0],[114.4,36.0,106.2,119.2,0.4,0.0,0.0],[111.9,36.3,106.9,119.1,0.4,0.0,0.0],[110.6,36.5,107.0,119.1,0.4,0.0,0.0],[109.6,36.6,107.0,119.1,0.4,0.0,0.0],[109.1,36.6,106.7,119.1,0.4,0.0,0.0],[109.3,36.5,105.7,119.1,0.4,0.0,0.0],[109.8,36.3,104.1,119.0,0.3,0.0,0.0],[110.4,36.1,102.0,119.0,0.1,0.0,0.0],[112.9,35.7,99.5,119.0,0.0,0.0,0.0],[115.4,35.3,97.0,119.0,-0.1,0.0,0.0],[119.3,34.8,94.7,119.1,-0.3,0.0,0.0],[121.2,34.3,92.9,119.2,-0.3,0.0,0.0],[124.7,33.8,91.7,119.2,-0.4,0.0,0.0],[126.4,33.5,91.1,119.3,-0.4,0.0,0.0],[126.9,33.4,91.0,119.4,-0.6,0.0,0.0],[126.9,33.5,91.0,119.5,-0.6,0.0,0.0],[127.0,33.8,91.3,119.6,-0.4,0.0,0.0],[126.8,34.2,92.3,119.7,-0.4,0.0,0.0],[125.4,34.7,93.9,119.7,-0.3,0.0,0.0],[123.7,35.4,96.0,119.8,-0.1,0.0,0.0],[122.2,36.1,98.5,120.0,-0.1,0.0,0.0],[119.3,36.9,101.1,120.0,0.1,0.0,0.0],[116.3,37.7,103.3,120.2,0.3,0.0,0.0],[113.5,38.4,105.2,120.3,0.3,0.0,0.0],[111.3,39.0,106.4,120.4,0.4,0.0,0.0],[110.1,39.4,107.0,120.6,0.4,0.0,0.0],[108.8,39.8,107.1,120.7,0.4,0.0,0.0],[108.6,40.1,107.1,120.8,0.4,0.0,0.0],[108.7,40.2,106.8,120.9,0.4,0.0,0.0],[109.6,40.4,105.9,121.1,0.4,0.0,0.0],[110.3,40.4,104.5,121.2,0.3,0.0,0.0],[111.4,40.3,102.7,121.2,0.1,0.0,0.0],[113.6,40.2,100.5,121.4,0.0,0.0,0.0],[115.5,40.1,98.3,121.5,0.0,0.0,0.0],[118.2,39.8,96.3,121.6,0.0,0.0,0.0],[119.9,39.6,94.7,121.7,-0.3,0.0,0.0],[122.6,39.3,93.6,121.8,-0.3,0.0,0.0],[123.5,39.2,93.1,121.9,-0.3,0.0,0.0],[124.6,39.2,93.0,122.0,-0.3,0.0,0.0],[124.9,39.3,93.0,122.1,-0.3,0.0,0.0],[124.6,39.5,93.2,122.1,-0.3,0.0,0.0],[123.8,39.7,93.5,122.2,-0.3,0.0,0.0],[123.0,40.1,94.0,122.2,-0.1,0.0,0.0],[121.6,40.4,94.6,122.3,-0.3,0.0,0.0],[120.8,40.7,95.2,122.3,-0.1,0.0,0.0],[120.1,40.9,95.7,122.3,-0.1,0.0,0.0],[118.9,41.1,96.1,122.3,-0.1,0.0,0.0],[118.5,41.2,96.2,122.3,-0.1,0.0,0.0],[118.1,41.3,96.2,122.3,-0.1,0.0,0.0],[118.1,41.3,96.2,122.3,-0.1,0.0,0.0],[118.5,41.2,96.2,122.3,-0.1,0.0,0.0],[118.7,41.1,96.2,122.3,-0.1,0.0,0.0],[118.8,41.0,96.2,122.3,-0.1,0.0,0.0],[120.1,40.8,96.2,122.2,-0.1,0.0,0.0],[120.3,40.7,96.2,122.2,-0.1,0.0,0.0],[120.3,40.5,96.2,122.2,-0.1,0.0,0.0],[120.2,40.4,96.2,122.0,-0.1,0.0,0.0],[120.2,40.3,96.2,122.0,-0.1,0.0,0.0],[120.3,40.2,96.2,122.0,-0.1,0.0,0.0],[120.1,40.0,96.2,121.8,-0.1,0.0,0.0],[120.1,39.8,96.2,121.8,-0.1,0.0,0.0],[119.8,39.7,96.2,121.7,-0.1,0.0,0.0],[119.8,39.5,96.2,121.5,-0.1,0.0,0.0],[119.8,39.3,96.2,121.5,-0.1,0.0,0.0],[120.1,39.0,96.2,121.3,-0.1,0.0,0.0],[120.1,38.8,96.2,121.2,-0.1,0.0,0.0],[120.1,38.6,96.2,121.2,-0.1,0.0,0.0],[120.1,38.3,96.2,121.0,-0.1,0.0,0.0],[120.1,38.1,96.2,120.8,-0.1,0.0,0.0]],"scrub":false},"idle_peek":{"n":86,"loop":false,"role":"beat","state":"idle","events":{},"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.5,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.3,0.0,0.0],[120.1,36.6,96.2,120.0,-0.1,0.0,0.0],[120.1,36.3,96.2,120.0,-0.1,0.0,0.0],[120.0,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.5,96.2,119.5,-0.1,0.0,0.0],[120.1,35.3,96.2,119.5,-0.1,0.0,0.0],[120.3,34.9,96.2,119.7,-0.3,0.0,0.0],[120.3,34.4,96.2,120.2,-0.1,0.01,0.0],[121.1,33.6,96.3,120.8,-0.3,0.02,0.0],[123.6,32.6,96.3,121.8,-0.1,0.03,0.0],[126.0,31.3,96.3,122.8,-0.1,0.04,0.0],[126.0,29.9,96.4,124.2,-0.1,0.05,0.0],[126.1,28.5,96.5,125.5,0.0,0.07,0.0],[126.5,27.4,96.6,126.8,-0.1,0.08,0.0],[126.3,26.5,96.7,127.8,-0.1,0.09,0.0],[126.4,25.9,96.7,128.6,-0.1,0.09,0.0],[126.7,25.5,96.8,129.1,-0.1,0.1,0.0],[126.7,25.3,96.8,129.3,0.0,0.1,0.0],[126.7,25.3,96.8,129.4,-0.1,0.1,0.0],[126.4,25.7,96.7,127.8,-0.1,0.09,0.0],[126.1,26.2,96.6,126.5,-0.1,0.07,0.0],[125.8,27.1,96.5,125.5,-0.1,0.06,0.0],[126.0,28.0,96.4,124.5,0.0,0.05,0.0],[126.0,29.2,96.4,123.7,0.0,0.05,0.0],[125.8,30.5,96.3,123.0,-0.1,0.04,0.0],[125.7,31.7,96.3,122.5,-0.1,0.03,0.0],[125.1,32.8,96.3,122.0,-0.1,0.03,0.0],[123.4,33.6,96.3,121.7,-0.1,0.02,0.0],[120.9,34.3,96.3,121.2,-0.1,0.02,0.0],[120.8,34.7,96.2,121.0,-0.1,0.01,0.0],[120.9,35.1,96.3,120.8,-0.1,0.01,0.0],[121.1,35.4,96.3,120.8,-0.1,0.01,0.0],[121.3,35.7,96.2,120.7,-0.1,0.01,0.0],[121.5,36.0,96.2,120.7,-0.1,0.01,0.0],[121.9,36.3,96.2,120.7,-0.1,0.0,0.0],[121.1,36.7,96.2,120.7,-0.1,0.0,0.0],[120.7,37.1,96.2,120.8,-0.1,0.0,0.0],[120.2,37.5,96.2,120.8,-0.1,0.0,0.0],[120.2,37.8,96.2,120.8,-0.1,0.0,0.0],[120.1,38.2,96.2,121.0,-0.1,0.0,0.0],[120.1,38.5,96.2,121.0,-0.1,0.0,0.0],[120.1,38.7,96.2,121.2,-0.1,0.0,0.0],[119.7,39.0,96.2,121.2,-0.1,0.0,0.0],[119.8,39.2,96.2,121.3,-0.1,0.0,0.0],[119.8,39.4,96.2,121.5,-0.1,0.0,0.0],[120.1,39.5,96.2,121.7,-0.1,0.0,0.0],[120.1,39.7,96.2,121.8,-0.1,0.0,0.0],[120.1,39.9,96.2,121.8,-0.3,0.0,0.0],[120.0,40.1,96.2,121.8,-0.1,0.0,0.0],[120.1,40.2,96.2,122.0,-0.1,0.0,0.0],[119.8,40.4,96.2,122.0,-0.1,0.0,0.0],[120.1,40.5,96.2,122.2,-0.1,0.0,0.0],[119.7,40.7,96.2,122.2,-0.1,0.0,0.0],[119.7,40.8,96.2,122.2,-0.1,0.0,0.0],[119.7,40.9,96.2,122.2,-0.1,0.0,0.0],[120.1,40.9,96.2,122.3,-0.1,0.0,0.0],[119.8,41.0,96.2,122.3,-0.1,0.0,0.0],[120.1,41.0,96.2,122.3,-0.1,0.0,0.0],[119.7,41.1,96.2,122.3,-0.1,0.0,0.0],[119.7,41.1,96.2,122.3,-0.1,0.0,0.0],[119.2,41.1,96.2,122.3,-0.1,0.0,0.0],[120.1,41.0,96.2,122.3,-0.1,0.0,0.0],[119.7,41.0,96.2,122.3,-0.1,0.0,0.0],[119.8,40.9,96.2,122.3,-0.1,0.0,0.0],[120.1,40.8,96.2,122.2,-0.1,0.0,0.0],[120.1,40.7,96.2,122.2,-0.1,0.0,0.0],[120.1,40.6,96.2,122.2,-0.1,0.0,0.0],[119.8,40.5,96.2,122.0,-0.1,0.0,0.0],[119.7,40.4,96.2,122.0,-0.1,0.0,0.0],[120.1,40.2,96.2,122.0,-0.1,0.0,0.0],[120.1,40.0,96.2,121.8,-0.1,0.0,0.0],[120.1,39.8,96.2,121.8,-0.1,0.0,0.0],[119.8,39.7,96.2,121.7,-0.1,0.0,0.0],[120.1,39.4,96.2,121.5,-0.1,0.0,0.0],[120.1,39.2,96.2,121.5,-0.1,0.0,0.0],[120.1,39.0,96.2,121.3,-0.1,0.0,0.0],[120.1,38.8,96.2,121.2,-0.1,0.0,0.0],[120.1,38.6,96.2,121.2,-0.1,0.0,0.0],[120.1,38.3,96.2,121.0,-0.1,0.0,0.0],[120.1,38.1,96.2,120.8,-0.1,0.0,0.0]],"scrub":false},"listening_in":{"n":19,"loop":false,"role":"enter","state":"listening","events":{},"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.4,35.8,96.5,122.5,-0.1,0.03,0.0],[121.8,36.2,97.2,125.8,-0.1,0.05,0.0],[124.8,38.5,97.9,130.0,0.0,0.07,0.0],[130.6,40.8,98.8,133.4,0.0,0.08,0.0],[132.0,41.6,99.1,134.8,0.0,0.09,0.0],[127.4,32.1,99.2,127.2,0.0,0.09,0.0],[125.5,20.4,99.2,120.0,0.0,0.09,0.0],[125.1,12.9,99.2,116.0,0.0,0.09,0.0],[126.8,5.7,99.1,114.5,0.0,0.09,0.0],[129.0,1.3,99.1,114.5,0.0,0.09,0.0],[130.6,0.2,99.0,115.3,0.0,0.09,0.0],[131.2,1.6,99.0,116.1,0.0,0.08,0.0],[130.7,3.8,99.0,116.2,0.0,0.08,0.0],[129.7,7.2,99.0,116.5,0.0,0.08,0.0],[128.7,11.5,99.0,117.4,0.0,0.08,0.0],[127.8,15.8,99.0,118.5,0.0,0.08,0.0],[127.2,19.3,99.0,119.6,0.0,0.08,0.0],[126.7,21.2,99.0,120.3,0.0,0.08,0.0]],"scrub":false},"listening_rest":{"n":115,"loop":true,"role":"rest","state":"listening","events":{},"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.1,99.0,120.4,0.0,0.08,0.0],[127.6,18.9,99.0,120.3,0.0,0.08,0.0],[127.6,18.8,99.0,120.3,0.0,0.08,0.0],[127.6,18.6,99.0,120.2,0.0,0.08,0.0],[127.6,18.4,99.0,120.1,0.0,0.08,0.0],[127.6,18.3,99.0,120.1,0.0,0.08,0.0],[127.6,18.1,99.0,120.0,0.0,0.08,0.0],[127.6,18.0,99.0,119.9,0.0,0.08,0.0],[127.6,17.9,99.0,119.8,0.0,0.08,0.0],[127.6,17.7,99.0,119.8,0.0,0.08,0.0],[127.6,17.6,99.0,119.7,0.0,0.08,0.0],[127.7,17.5,99.0,119.7,0.0,0.08,0.0],[127.6,17.3,99.0,119.7,0.0,0.08,0.0],[127.6,17.2,99.0,119.7,0.0,0.08,0.0],[127.7,17.1,99.0,119.7,0.0,0.08,0.0],[127.7,16.9,99.0,119.8,0.0,0.08,0.0],[127.7,16.8,99.0,120.0,0.0,0.08,0.0],[127.8,16.6,99.0,120.1,0.0,0.08,0.0],[127.8,16.4,99.0,120.3,0.0,0.08,0.0],[127.9,16.2,99.0,120.5,0.0,0.08,0.0],[127.9,16.0,99.0,120.8,0.0,0.08,0.0],[128.0,15.9,99.0,121.0,0.0,0.08,0.0],[128.1,15.7,99.0,121.3,0.0,0.08,0.0],[128.1,15.5,99.0,121.6,0.0,0.08,0.0],[128.2,15.4,99.0,121.8,0.0,0.08,0.0],[128.2,15.3,99.0,122.1,0.0,0.08,0.0],[128.3,15.2,99.0,122.3,0.0,0.08,0.0],[128.3,15.1,99.0,122.6,0.0,0.08,0.0],[128.4,15.1,99.0,122.8,0.0,0.08,0.0],[128.4,15.0,99.0,122.9,0.0,0.08,0.0],[128.4,15.0,99.0,123.1,0.0,0.08,0.0],[128.5,15.0,99.0,123.2,0.0,0.08,0.0],[128.5,15.0,99.0,123.3,0.0,0.08,0.0],[128.5,15.1,99.0,123.3,0.0,0.08,0.0],[128.5,15.1,99.0,123.3,0.0,0.08,0.0],[128.5,15.2,99.0,123.4,0.0,0.08,0.0],[128.5,15.3,99.0,123.4,0.0,0.08,0.0],[128.5,15.3,99.0,123.3,0.0,0.08,0.0],[128.4,15.4,99.0,123.2,0.0,0.08,0.0],[128.4,15.5,99.0,122.9,0.0,0.08,0.0],[128.3,15.6,99.0,122.6,0.0,0.08,0.0],[128.2,15.8,99.0,122.1,0.0,0.08,0.0],[128.1,16.1,99.0,121.6,0.0,0.08,0.0],[128.0,16.3,99.0,121.2,0.0,0.08,0.0],[127.9,16.7,99.0,120.7,0.0,0.08,0.0],[127.8,17.1,99.0,120.4,0.0,0.08,0.0],[127.7,17.4,99.0,120.1,0.0,0.08,0.0],[127.7,17.8,99.0,119.9,0.0,0.08,0.0],[127.6,18.1,99.0,119.9,0.0,0.08,0.0],[127.6,18.3,99.0,119.9,0.0,0.08,0.0],[127.6,18.5,99.0,120.0,0.0,0.08,0.0],[127.6,18.6,99.0,120.1,0.0,0.08,0.0],[127.6,18.7,99.0,120.1,0.0,0.08,0.0],[127.6,18.7,99.0,120.2,0.0,0.08,0.0],[127.6,18.8,99.0,120.3,0.0,0.08,0.0],[127.6,18.9,99.0,120.4,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.4,99.0,120.6,0.0,0.08,0.0],[127.6,19.5,99.0,120.7,0.0,0.08,0.0],[127.6,19.7,99.0,120.7,0.0,0.08,0.0],[127.6,19.9,99.0,120.8,0.0,0.08,0.0],[127.6,20.1,99.0,120.9,0.0,0.08,0.0],[127.6,20.2,99.0,120.9,0.0,0.08,0.0],[127.6,20.4,99.0,121.0,0.0,0.08,0.0],[127.6,20.5,99.0,121.1,0.0,0.08,0.0],[127.6,20.7,99.0,121.1,0.0,0.08,0.0],[127.6,20.8,99.0,121.2,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,21.0,99.0,121.3,0.0,0.08,0.0],[127.6,21.1,99.0,121.4,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,21.4,99.0,121.5,0.0,0.08,0.0],[127.6,21.5,99.0,121.5,0.0,0.08,0.0],[127.6,21.6,99.0,121.6,0.0,0.08,0.0],[127.6,21.6,99.0,121.6,0.0,0.08,0.0],[127.6,21.7,99.0,121.7,0.0,0.08,0.0],[127.6,21.8,99.0,121.7,0.0,0.08,0.0],[127.6,21.9,99.0,121.7,0.0,0.08,0.0],[127.6,21.9,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,21.9,99.0,121.8,0.0,0.08,0.0],[127.6,21.9,99.0,121.7,0.0,0.08,0.0],[127.6,21.8,99.0,121.7,0.0,0.08,0.0],[127.6,21.7,99.0,121.7,0.0,0.08,0.0],[127.6,21.6,99.0,121.6,0.0,0.08,0.0],[127.6,21.5,99.0,121.6,0.0,0.08,0.0],[127.6,21.4,99.0,121.5,0.0,0.08,0.0],[127.6,21.3,99.0,121.5,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,21.1,99.0,121.4,0.0,0.08,0.0],[127.6,21.0,99.0,121.3,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,20.7,99.0,121.2,0.0,0.08,0.0],[127.6,20.6,99.0,121.1,0.0,0.08,0.0],[127.6,20.5,99.0,121.1,0.0,0.08,0.0],[127.6,20.3,99.0,121.0,0.0,0.08,0.0],[127.6,20.2,99.0,120.9,0.0,0.08,0.0],[127.6,20.0,99.0,120.9,0.0,0.08,0.0],[127.6,19.9,99.0,120.8,0.0,0.08,0.0],[127.6,19.7,99.0,120.7,0.0,0.08,0.0],[127.6,19.6,99.0,120.6,0.0,0.08,0.0],[127.6,19.4,99.0,120.6,0.0,0.08,0.0]],"scrub":false},"listen_nod":{"n":58,"loop":false,"role":"beat","state":"listening","events":{},"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.3,0.0,0.08,0.0],[127.6,18.7,99.0,120.2,0.0,0.08,0.0],[127.6,18.4,99.0,120.1,0.0,0.08,0.0],[127.6,18.1,99.0,119.9,0.0,0.08,0.0],[127.6,17.8,99.0,119.8,0.0,0.08,0.0],[127.7,17.5,99.0,119.7,0.0,0.08,0.0],[127.6,17.2,99.0,119.5,0.0,0.08,0.0],[127.7,17.0,99.0,119.4,0.0,0.08,0.0],[127.7,16.8,99.0,119.4,0.0,0.08,0.0],[127.9,17.0,99.0,120.6,0.0,0.08,0.0],[128.4,17.7,99.0,123.5,0.0,0.08,0.0],[128.8,18.5,99.0,126.1,0.0,0.08,0.0],[129.2,19.2,99.0,128.4,0.0,0.08,0.0],[129.5,19.9,99.0,130.3,0.0,0.08,0.0],[129.8,20.6,99.0,131.8,0.0,0.08,0.0],[130.1,21.3,99.0,132.9,0.0,0.08,0.0],[130.2,21.9,99.0,133.6,0.0,0.08,0.0],[130.4,22.3,99.0,133.8,0.0,0.08,0.0],[130.4,22.2,99.0,133.6,0.0,0.08,0.0],[130.1,21.2,99.0,131.9,0.0,0.08,0.0],[129.6,19.5,99.0,128.8,0.0,0.08,0.0],[129.0,17.8,99.0,125.2,0.0,0.08,0.0],[128.4,16.8,99.0,122.0,0.0,0.08,0.0],[128.0,16.8,99.0,120.3,0.0,0.08,0.0],[127.8,17.7,99.0,119.9,0.0,0.08,0.0],[128.0,18.9,99.0,121.9,0.0,0.08,0.0],[128.2,19.8,99.0,124.1,0.0,0.08,0.0],[128.4,19.9,99.0,125.9,0.0,0.08,0.0],[128.5,19.5,99.0,127.5,0.0,0.08,0.0],[128.8,19.1,99.0,128.7,0.0,0.08,0.0],[129.1,19.0,99.0,129.6,0.0,0.08,0.0],[129.3,19.1,99.0,130.0,0.0,0.08,0.0],[129.5,19.4,99.0,130.2,0.0,0.08,0.0],[129.6,19.5,99.0,129.8,0.0,0.08,0.0],[129.5,19.4,99.0,128.7,0.0,0.08,0.0],[129.2,19.2,99.0,127.0,0.0,0.08,0.0],[128.8,19.3,99.0,125.1,0.0,0.08,0.0],[128.4,19.8,99.0,123.4,0.0,0.08,0.0],[127.9,20.7,99.0,122.3,0.0,0.08,0.0],[127.6,21.9,99.0,121.8,0.0,0.08,0.0],[127.5,23.1,99.0,121.8,0.0,0.08,0.0],[126.3,23.8,99.0,121.8,0.0,0.08,0.0],[125.7,24.0,99.0,121.8,0.0,0.08,0.0],[127.4,23.7,99.0,121.8,0.0,0.08,0.0],[127.5,23.1,99.0,121.8,0.0,0.08,0.0],[127.5,22.5,99.0,121.8,0.0,0.08,0.0],[127.6,21.9,99.0,121.7,0.0,0.08,0.0],[127.6,21.5,99.0,121.7,0.0,0.08,0.0],[127.7,21.1,99.0,121.6,0.0,0.08,0.0],[127.7,20.9,99.0,121.5,0.0,0.08,0.0],[127.7,20.7,99.0,121.4,0.0,0.08,0.0],[127.7,20.5,99.0,121.3,0.0,0.08,0.0],[127.6,20.4,99.0,121.1,0.0,0.08,0.0],[127.6,20.3,99.0,121.0,0.0,0.08,0.0],[127.6,20.1,99.0,120.9,0.0,0.08,0.0],[127.6,19.9,99.0,120.7,0.0,0.08,0.0],[127.6,19.6,99.0,120.6,0.0,0.08,0.0]],"scrub":false},"listen_tilt_l":{"n":72,"loop":false,"role":"beat","state":"listening","events":{},"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,18.8,99.0,120.2,0.0,0.08,0.0],[127.6,18.6,99.0,120.1,0.0,0.08,0.0],[127.6,18.3,99.0,120.0,0.0,0.08,0.0],[127.6,18.0,99.0,119.9,0.0,0.08,0.0],[127.6,17.8,99.0,119.8,0.0,0.08,0.0],[127.6,17.5,99.0,119.7,0.0,0.08,0.0],[127.6,17.3,99.0,119.6,0.0,0.08,0.0],[127.7,17.2,99.0,119.5,0.0,0.08,0.0],[127.6,17.0,99.0,119.4,0.0,0.08,0.0],[127.6,16.8,98.8,119.4,0.0,0.08,0.0],[127.5,16.6,98.4,119.3,0.0,0.08,0.0],[127.3,16.4,97.4,119.2,0.1,0.08,0.0],[126.9,16.0,95.9,119.2,0.3,0.08,0.0],[126.6,15.7,94.1,119.2,0.4,0.08,0.0],[126.1,15.3,92.0,119.2,0.7,0.08,0.0],[125.7,14.9,89.7,119.2,0.7,0.08,0.0],[125.4,14.6,87.5,119.2,1.0,0.08,0.0],[124.9,14.3,85.5,119.1,1.2,0.08,0.0],[124.3,14.0,84.0,119.2,1.4,0.08,0.0],[123.8,13.9,82.8,119.2,1.6,0.08,0.0],[123.3,13.9,82.2,119.2,1.6,0.08,0.0],[123.0,13.9,81.8,119.2,1.8,0.08,0.0],[122.9,14.1,81.8,119.3,1.8,0.08,0.0],[122.9,14.2,81.8,119.3,1.8,0.08,0.0],[123.1,14.4,81.8,119.5,1.8,0.08,0.0],[123.0,14.5,81.8,119.5,1.8,0.08,0.0],[123.1,14.7,81.8,119.7,1.8,0.08,0.0],[123.1,14.9,81.8,119.8,1.8,0.08,0.0],[123.1,15.2,81.8,119.8,1.8,0.08,0.0],[123.1,15.4,81.8,120.0,1.8,0.08,0.0],[123.1,15.6,81.8,120.0,1.8,0.08,0.0],[123.1,15.9,81.8,120.2,1.8,0.08,0.0],[123.1,16.1,81.8,120.2,1.8,0.08,0.0],[123.2,16.4,81.7,120.3,1.8,0.08,0.0],[123.1,16.6,81.7,120.5,1.8,0.08,0.0],[123.1,16.9,81.8,120.6,1.9,0.08,0.0],[123.1,17.2,81.8,120.7,1.9,0.08,0.0],[123.1,17.4,81.8,120.8,1.8,0.08,0.0],[123.1,17.7,81.8,121.0,1.8,0.08,0.0],[123.1,17.9,81.7,121.0,1.8,0.08,0.0],[123.1,18.1,81.7,121.2,1.8,0.08,0.0],[123.1,18.4,81.7,121.2,1.8,0.08,0.0],[123.1,18.6,81.7,121.3,1.8,0.08,0.0],[123.1,18.8,81.7,121.5,1.8,0.08,0.0],[123.1,18.9,81.7,121.5,1.9,0.08,0.0],[123.1,19.1,81.7,121.6,1.9,0.08,0.0],[123.1,19.2,81.7,121.7,1.8,0.08,0.0],[123.2,19.4,81.8,121.7,1.9,0.08,0.0],[123.7,19.6,82.7,121.8,1.7,0.08,0.0],[124.8,19.9,84.5,121.8,1.5,0.08,0.0],[126.4,20.4,87.3,121.8,1.2,0.08,0.0],[128.2,21.0,90.7,121.8,0.7,0.08,0.0],[129.3,21.5,94.0,121.8,0.4,0.08,0.0],[129.4,21.8,96.7,121.8,0.1,0.08,0.0],[128.5,22.0,98.3,121.8,0.0,0.08,0.0],[127.0,22.0,98.9,121.8,0.0,0.08,0.0],[125.8,21.9,99.0,121.8,0.0,0.08,0.0],[124.9,21.8,99.0,121.7,0.0,0.08,0.0],[124.8,21.6,99.0,121.7,0.0,0.08,0.0],[125.4,21.5,99.0,121.6,0.0,0.08,0.0],[126.1,21.4,99.0,121.5,0.0,0.08,0.0],[127.0,21.2,99.0,121.4,0.0,0.08,0.0],[127.7,21.1,99.0,121.4,0.0,0.08,0.0],[128.2,20.9,99.0,121.3,0.0,0.08,0.0],[128.4,20.7,99.0,121.2,0.0,0.08,0.0],[128.5,20.5,99.0,121.1,0.0,0.08,0.0],[128.3,20.2,99.0,120.9,0.0,0.08,0.0],[128.1,20.0,99.0,120.8,0.0,0.08,0.0],[127.9,19.7,99.0,120.7,0.0,0.08,0.0],[127.6,19.5,99.0,120.6,0.0,0.08,0.0]],"scrub":false},"listen_tilt_r":{"n":72,"loop":false,"role":"beat","state":"listening","events":{},"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,18.8,99.0,120.2,0.0,0.08,0.0],[127.6,18.6,99.0,120.1,0.0,0.08,0.0],[127.6,18.3,99.0,120.0,0.0,0.08,0.0],[127.6,18.0,99.0,119.9,0.0,0.08,0.0],[127.6,17.8,99.0,119.8,0.0,0.08,0.0],[127.6,17.5,99.0,119.7,0.0,0.08,0.0],[127.6,17.3,99.0,119.6,0.0,0.08,0.0],[127.7,17.2,99.0,119.5,0.0,0.08,0.0],[127.6,17.0,99.0,119.4,0.0,0.08,0.0],[127.7,16.9,99.2,119.4,0.0,0.08,0.0],[127.7,16.8,99.6,119.3,0.0,0.08,0.0],[128.1,16.9,100.6,119.2,-0.1,0.08,0.0],[128.2,17.0,102.1,119.2,-0.3,0.08,0.0],[126.1,17.2,103.9,119.2,-0.4,0.08,0.0],[125.8,17.5,106.0,119.2,-0.7,0.08,0.0],[123.7,17.7,108.3,119.2,-0.7,0.08,0.0],[121.9,18.0,110.5,119.2,-1.0,0.08,0.0],[120.8,18.3,112.5,119.1,-1.2,0.08,0.0],[119.6,18.4,114.0,119.2,-1.4,0.08,0.0],[118.1,18.5,115.2,119.2,-1.6,0.08,0.0],[116.7,18.6,115.8,119.2,-1.6,0.08,0.0],[115.3,18.7,116.2,119.2,-1.8,0.08,0.0],[116.4,18.7,116.2,119.3,-1.8,0.08,0.0],[115.8,18.9,116.2,119.3,-1.8,0.08,0.0],[115.1,19.1,116.2,119.5,-1.8,0.08,0.0],[115.4,19.3,116.2,119.5,-1.8,0.08,0.0],[115.1,19.6,116.2,119.7,-1.8,0.08,0.0],[115.9,19.8,116.2,119.8,-1.8,0.08,0.0],[115.4,20.1,116.2,119.8,-1.8,0.08,0.0],[115.5,20.3,116.2,120.0,-1.8,0.08,0.0],[115.7,20.5,116.2,120.0,-1.8,0.08,0.0],[116.2,20.7,116.2,120.2,-1.8,0.08,0.0],[115.0,21.0,116.2,120.2,-1.8,0.08,0.0],[115.3,21.2,116.3,120.3,-1.8,0.08,0.0],[115.4,21.4,116.3,120.5,-1.8,0.08,0.0],[115.5,21.6,116.2,120.6,-1.9,0.08,0.0],[115.2,21.9,116.2,120.7,-1.9,0.08,0.0],[115.2,22.1,116.2,120.8,-1.8,0.08,0.0],[115.0,22.4,116.2,121.0,-1.8,0.08,0.0],[115.3,22.6,116.3,121.0,-1.8,0.08,0.0],[115.4,22.8,116.3,121.2,-1.8,0.08,0.0],[115.4,23.0,116.3,121.2,-1.8,0.08,0.0],[115.5,23.2,116.3,121.3,-1.8,0.08,0.0],[115.5,23.4,116.3,121.5,-1.8,0.08,0.0],[115.3,23.6,116.3,121.5,-1.9,0.08,0.0],[115.5,23.7,116.3,121.6,-1.9,0.08,0.0],[115.5,23.9,116.3,121.7,-1.8,0.08,0.0],[115.7,23.9,116.2,121.7,-1.9,0.08,0.0],[116.9,23.9,115.3,121.8,-1.7,0.08,0.0],[118.0,23.6,113.5,121.8,-1.5,0.08,0.0],[117.9,23.3,110.7,121.8,-1.2,0.08,0.0],[120.7,22.9,107.3,121.8,-0.7,0.08,0.0],[121.9,22.6,104.0,121.8,-0.4,0.08,0.0],[124.7,22.3,101.3,121.8,-0.1,0.08,0.0],[126.5,22.1,99.7,121.8,0.0,0.08,0.0],[128.2,22.0,99.1,121.8,0.0,0.08,0.0],[129.2,22.0,99.0,121.8,0.0,0.08,0.0],[129.7,21.9,99.0,121.7,0.0,0.08,0.0],[129.7,21.8,99.0,121.7,0.0,0.08,0.0],[129.4,21.7,99.0,121.6,0.0,0.08,0.0],[128.8,21.5,99.0,121.5,0.0,0.08,0.0],[128.1,21.3,99.0,121.4,0.0,0.08,0.0],[127.5,21.1,99.0,121.4,0.0,0.08,0.0],[127.0,20.9,99.0,121.3,0.0,0.08,0.0],[126.7,20.6,99.0,121.2,0.0,0.08,0.0],[126.7,20.4,99.0,121.1,0.0,0.08,0.0],[126.8,20.2,99.0,120.9,0.0,0.08,0.0],[127.1,20.0,99.0,120.8,0.0,0.08,0.0],[127.3,19.7,99.0,120.7,0.0,0.08,0.0],[127.6,19.5,99.0,120.6,0.0,0.08,0.0]],"scrub":false},"listen_lean":{"n":77,"loop":false,"role":"beat","state":"listening","events":{},"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,18.8,99.0,120.3,0.0,0.08,0.0],[127.6,18.6,99.0,120.2,0.0,0.08,0.0],[127.6,18.3,99.0,120.1,0.0,0.08,0.0],[127.6,18.1,99.0,119.9,0.0,0.08,0.0],[127.6,17.9,99.0,119.8,0.0,0.08,0.0],[127.6,17.6,99.0,119.8,0.0,0.08,0.0],[127.6,17.4,99.0,119.7,0.0,0.08,0.0],[127.7,17.3,99.0,119.6,0.0,0.08,0.0],[127.6,17.1,99.0,119.5,0.0,0.08,0.0],[127.7,16.9,99.0,119.4,0.0,0.08,0.0],[127.7,16.6,99.0,119.4,0.0,0.09,0.0],[127.8,16.1,99.0,119.4,0.0,0.1,0.0],[127.9,15.5,99.0,119.4,0.0,0.11,0.0],[128.2,14.6,99.0,119.4,0.0,0.13,0.0],[128.4,13.6,99.0,119.5,0.0,0.15,0.0],[128.8,12.4,99.0,119.6,0.0,0.17,0.0],[129.1,11.1,99.0,119.7,0.0,0.19,0.0],[129.5,9.8,99.0,119.9,0.0,0.22,0.0],[129.8,8.6,99.0,120.0,0.0,0.24,0.0],[130.1,7.5,99.0,120.2,0.0,0.26,0.0],[130.4,6.6,99.0,120.3,0.0,0.27,0.0],[130.5,6.0,99.0,120.4,0.0,0.29,0.0],[130.7,5.6,99.0,120.5,0.0,0.29,0.0],[130.7,5.5,99.0,120.6,0.0,0.3,0.0],[130.8,5.5,99.0,120.7,0.0,0.3,0.0],[130.8,5.7,99.0,120.8,0.0,0.3,0.0],[130.7,5.9,99.0,120.8,0.0,0.3,0.0],[130.7,6.1,99.0,120.9,0.0,0.3,0.0],[130.7,6.3,99.0,121.0,0.0,0.3,0.0],[130.7,6.6,99.0,121.1,0.0,0.3,0.0],[130.7,6.8,99.0,121.2,0.0,0.3,0.0],[130.7,7.1,99.0,121.3,0.0,0.3,0.0],[130.7,7.3,99.0,121.4,0.0,0.3,0.0],[130.7,7.5,99.0,121.5,0.0,0.3,0.0],[130.7,7.8,99.0,121.6,0.0,0.3,0.0],[130.7,8.0,99.0,121.8,0.0,0.3,0.0],[130.7,8.3,99.0,121.9,0.0,0.3,0.0],[130.7,8.5,99.0,122.0,0.0,0.3,0.0],[130.7,8.8,99.0,122.1,0.0,0.3,0.0],[130.7,9.0,99.0,122.2,0.0,0.3,0.0],[130.7,9.3,99.0,122.3,0.0,0.3,0.0],[130.7,9.5,99.0,122.5,0.0,0.3,0.0],[130.7,9.8,99.0,122.6,0.0,0.3,0.0],[130.7,10.0,99.0,122.7,0.0,0.3,0.0],[130.7,10.2,99.0,122.8,0.0,0.3,0.0],[130.6,10.4,99.0,122.9,0.0,0.3,0.0],[130.6,10.6,99.0,122.9,0.0,0.3,0.0],[130.6,10.8,99.0,123.0,0.0,0.3,0.0],[130.6,11.0,99.0,123.1,0.0,0.3,0.0],[130.6,11.1,99.0,123.2,0.0,0.3,0.0],[130.6,11.2,99.0,123.2,0.0,0.3,0.0],[130.6,11.3,99.0,123.3,0.0,0.3,0.0],[130.6,11.6,99.0,123.3,0.0,0.3,0.0],[130.4,12.3,99.0,123.2,0.0,0.28,0.0],[130.0,13.7,99.0,123.0,0.0,0.25,0.0],[129.4,15.5,99.0,122.7,0.0,0.22,0.0],[128.8,17.5,99.0,122.4,0.0,0.17,0.0],[128.3,19.3,99.0,122.2,0.0,0.14,0.0],[127.9,20.8,99.0,121.9,0.0,0.11,0.0],[127.7,21.7,99.0,121.8,0.0,0.09,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.7,0.0,0.08,0.0],[127.6,22.0,99.0,121.7,0.0,0.08,0.0],[127.6,21.9,99.0,121.6,0.0,0.08,0.0],[127.6,21.7,99.0,121.5,0.0,0.08,0.0],[127.6,21.4,99.0,121.5,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,20.7,99.0,121.2,0.0,0.08,0.0],[127.6,20.4,99.0,121.1,0.0,0.08,0.0],[127.6,20.2,99.0,121.0,0.0,0.08,0.0],[127.6,20.0,99.0,120.9,0.0,0.08,0.0],[127.6,19.8,99.0,120.8,0.0,0.08,0.0],[127.6,19.6,99.0,120.7,0.0,0.08,0.0],[127.6,19.4,99.0,120.6,0.0,0.08,0.0]],"scrub":false},"listen_oh":{"n":62,"loop":false,"role":"beat","state":"listening","events":{},"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.3,0.0,0.08,0.0],[127.6,18.8,99.0,120.2,0.0,0.08,0.0],[127.6,18.5,99.0,120.1,0.0,0.08,0.0],[127.6,18.2,99.0,120.0,0.0,0.08,0.0],[127.6,17.9,99.0,119.8,0.0,0.08,0.0],[127.6,17.6,99.0,119.7,0.0,0.08,0.0],[127.6,17.3,99.0,119.6,0.0,0.08,0.0],[127.7,17.1,99.0,119.5,0.0,0.08,0.0],[127.7,16.9,99.0,119.4,0.0,0.08,0.0],[127.7,13.9,99.0,116.9,0.0,0.08,0.0],[127.7,8.9,99.0,112.7,0.0,0.08,0.0],[128.0,6.1,99.0,110.4,0.0,0.08,0.0],[128.4,4.9,99.0,109.4,0.0,0.08,0.0],[126.7,4.7,99.0,109.1,0.0,0.08,0.0],[122.7,5.1,99.0,109.0,0.0,0.08,0.0],[121.3,5.7,99.0,109.0,0.0,0.08,0.0],[120.6,6.2,99.0,109.0,0.0,0.08,0.0],[121.2,6.5,99.0,109.0,0.0,0.08,0.0],[121.1,6.7,99.0,109.1,0.0,0.08,0.0],[122.5,6.7,99.0,109.1,0.0,0.08,0.0],[123.9,6.6,99.0,109.2,0.0,0.08,0.0],[126.3,6.4,99.0,109.3,0.0,0.08,0.0],[127.0,6.3,99.0,109.4,0.0,0.08,0.0],[127.7,6.3,99.0,109.5,0.0,0.08,0.0],[127.8,6.3,99.0,109.6,0.0,0.08,0.0],[126.6,6.5,99.0,109.7,0.0,0.08,0.0],[126.6,6.8,99.0,109.9,0.0,0.08,0.0],[125.6,7.3,99.0,110.0,0.0,0.08,0.0],[124.2,7.7,99.0,110.1,0.0,0.08,0.0],[124.1,8.2,99.0,110.3,0.0,0.08,0.0],[124.1,8.6,99.0,110.4,0.0,0.08,0.0],[123.7,9.0,99.0,110.6,0.0,0.08,0.0],[124.2,9.3,99.0,110.7,0.0,0.08,0.0],[124.0,9.5,99.0,110.9,0.0,0.08,0.0],[124.2,9.9,99.0,111.1,0.0,0.08,0.0],[124.2,10.4,99.0,111.5,0.0,0.08,0.0],[125.4,11.1,99.0,112.2,0.0,0.08,0.0],[125.5,12.2,99.0,113.1,0.0,0.08,0.0],[125.4,13.6,99.0,114.2,0.0,0.08,0.0],[126.4,15.1,99.0,115.5,0.0,0.08,0.0],[127.4,16.7,99.0,116.9,0.0,0.08,0.0],[127.9,18.3,99.0,118.3,0.0,0.08,0.0],[127.8,19.6,99.0,119.5,0.0,0.08,0.0],[127.6,20.8,99.0,120.5,0.0,0.08,0.0],[127.5,21.6,99.0,121.2,0.0,0.08,0.0],[127.4,22.1,99.0,121.6,0.0,0.08,0.0],[127.4,22.2,99.0,121.8,0.0,0.08,0.0],[127.4,22.1,99.0,121.8,0.0,0.08,0.0],[127.5,21.9,99.0,121.8,0.0,0.08,0.0],[127.6,21.7,99.0,121.8,0.0,0.08,0.0],[127.6,21.6,99.0,121.7,0.0,0.08,0.0],[127.7,21.5,99.0,121.7,0.0,0.08,0.0],[127.7,21.4,99.0,121.6,0.0,0.08,0.0],[127.6,21.3,99.0,121.5,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,21.1,99.0,121.3,0.0,0.08,0.0],[127.6,20.9,99.0,121.2,0.0,0.08,0.0],[127.6,20.6,99.0,121.1,0.0,0.08,0.0],[127.6,20.3,99.0,120.9,0.0,0.08,0.0],[127.6,20.0,99.0,120.8,0.0,0.08,0.0],[127.6,19.6,99.0,120.7,0.0,0.08,0.0]],"scrub":false},"listen_mhm":{"n":67,"loop":false,"role":"beat","state":"listening","events":{},"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,18.8,99.0,120.2,0.0,0.08,0.0],[127.6,18.5,99.0,120.1,0.0,0.08,0.0],[127.6,18.2,99.0,120.0,0.0,0.08,0.0],[127.6,18.0,99.0,119.9,0.0,0.08,0.0],[127.6,17.7,99.0,119.8,0.0,0.08,0.0],[127.6,17.4,99.0,119.7,0.0,0.08,0.0],[127.7,17.2,99.0,119.6,0.0,0.08,0.0],[127.7,17.0,99.0,119.5,0.0,0.08,0.0],[127.7,16.9,99.0,119.4,0.0,0.08,0.0],[127.7,16.8,99.0,119.4,0.0,0.08,0.0],[127.7,16.8,99.0,119.8,0.0,0.08,0.0],[127.9,17.0,99.0,120.6,0.0,0.08,0.0],[128.1,17.3,99.0,121.8,0.0,0.08,0.0],[128.4,17.9,99.0,123.4,0.0,0.08,0.0],[128.7,18.6,99.0,125.5,0.0,0.08,0.0],[129.1,19.6,99.0,127.7,0.0,0.08,0.0],[129.5,20.8,99.0,130.1,0.0,0.08,0.0],[130.0,22.1,99.0,132.4,0.0,0.08,0.0],[130.3,23.6,99.0,134.5,0.0,0.08,0.0],[130.7,25.1,99.0,136.2,0.0,0.08,0.0],[130.9,26.4,99.0,137.6,0.0,0.08,0.0],[131.1,27.4,99.0,138.4,0.0,0.08,0.0],[131.2,28.0,99.0,138.9,0.0,0.08,0.0],[131.3,28.3,99.0,139.0,0.0,0.08,0.0],[131.3,28.3,99.0,139.1,0.0,0.08,0.0],[131.3,28.4,99.0,139.2,0.0,0.08,0.0],[131.3,28.4,99.0,139.3,0.0,0.08,0.0],[131.3,28.5,99.0,139.4,0.0,0.08,0.0],[131.3,28.7,99.0,139.5,0.0,0.08,0.0],[131.2,28.9,99.0,139.6,0.0,0.08,0.0],[131.2,29.2,99.0,139.7,0.0,0.08,0.0],[131.1,29.5,99.0,139.8,0.0,0.08,0.0],[131.1,29.8,99.0,139.9,0.0,0.08,0.0],[131.1,30.2,99.0,140.0,0.0,0.08,0.0],[131.1,30.5,99.0,140.1,0.0,0.08,0.0],[131.2,30.7,99.0,140.2,0.0,0.08,0.0],[131.2,31.0,99.0,140.3,0.0,0.08,0.0],[131.2,31.2,99.0,140.4,0.0,0.08,0.0],[131.1,31.1,99.0,139.9,0.0,0.08,0.0],[130.9,30.4,99.0,138.5,0.0,0.08,0.0],[130.5,29.3,99.0,136.1,0.0,0.08,0.0],[129.9,28.0,99.0,133.0,0.0,0.08,0.0],[129.3,26.7,99.0,129.9,0.0,0.08,0.0],[128.7,25.9,99.0,127.1,0.0,0.08,0.0],[128.1,25.3,99.0,124.9,0.0,0.08,0.0],[127.8,25.1,99.0,123.6,0.0,0.08,0.0],[127.6,25.0,99.0,122.9,0.0,0.08,0.0],[127.5,24.7,99.0,122.5,0.0,0.08,0.0],[125.9,24.2,99.0,122.1,0.0,0.08,0.0],[126.4,23.6,99.0,121.9,0.0,0.08,0.0],[127.7,22.9,99.0,121.8,0.0,0.08,0.0],[127.7,22.3,99.0,121.8,0.0,0.08,0.0],[127.7,21.8,99.0,121.8,0.0,0.08,0.0],[127.7,21.5,99.0,121.7,0.0,0.08,0.0],[127.6,21.3,99.0,121.7,0.0,0.08,0.0],[127.6,21.2,99.0,121.6,0.0,0.08,0.0],[127.6,21.1,99.0,121.5,0.0,0.08,0.0],[127.6,21.0,99.0,121.4,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,20.8,99.0,121.2,0.0,0.08,0.0],[127.6,20.6,99.0,121.1,0.0,0.08,0.0],[127.6,20.4,99.0,121.0,0.0,0.08,0.0],[127.6,20.2,99.0,120.9,0.0,0.08,0.0],[127.6,19.9,99.0,120.8,0.0,0.08,0.0],[127.6,19.7,99.0,120.6,0.0,0.08,0.0]],"scrub":false},"listen_blink":{"n":38,"loop":false,"role":"beat","state":"listening","events":{},"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,18.8,99.0,120.3,0.0,0.08,0.0],[127.5,18.4,99.0,120.1,0.0,0.08,0.0],[127.6,18.0,99.0,119.8,0.0,0.08,0.0],[127.6,17.6,99.0,119.7,0.0,0.08,0.0],[127.6,17.2,99.0,119.5,0.0,0.08,0.0],[127.7,16.8,99.0,119.4,0.0,0.08,0.0],[127.7,16.5,99.0,119.3,0.0,0.08,0.0],[127.7,16.3,99.0,119.2,0.0,0.08,0.0],[127.7,16.2,99.0,119.1,0.0,0.08,0.0],[127.7,16.2,99.0,119.1,0.0,0.08,0.0],[127.7,16.3,99.0,119.2,0.0,0.08,0.0],[127.7,16.5,99.0,119.2,0.0,0.08,0.0],[127.7,16.7,99.0,119.3,0.0,0.08,0.0],[127.7,17.0,99.0,119.5,0.0,0.08,0.0],[127.7,17.4,99.0,119.6,0.0,0.08,0.0],[127.7,17.8,99.0,119.8,0.0,0.08,0.0],[127.7,18.2,99.0,120.0,0.0,0.08,0.0],[127.6,18.6,99.0,120.2,0.0,0.08,0.0],[127.6,19.1,99.0,120.4,0.0,0.08,0.0],[127.6,19.6,99.0,120.7,0.0,0.08,0.0],[127.6,20.0,99.0,120.9,0.0,0.08,0.0],[127.6,20.5,99.0,121.1,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,21.3,99.0,121.4,0.0,0.08,0.0],[127.6,21.6,99.0,121.6,0.0,0.08,0.0],[127.6,21.8,99.0,121.7,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,21.8,99.0,121.7,0.0,0.08,0.0],[127.6,21.5,99.0,121.5,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,20.8,99.0,121.2,0.0,0.08,0.0],[127.6,20.4,99.0,121.0,0.0,0.08,0.0],[127.6,19.9,99.0,120.8,0.0,0.08,0.0]],"scrub":false},"thinking_in":{"n":24,"loop":false,"role":"enter","state":"thinking","events":{},"frames":[[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.8,96.5,120.7,-0.1,0.0,0.0],[119.9,38.0,97.0,120.5,-0.1,0.0,0.0],[119.3,38.2,97.8,120.2,0.0,0.0,0.0],[118.7,38.6,98.8,119.8,-0.1,0.0,0.0],[117.3,39.2,99.8,119.5,0.1,0.0,0.0],[115.6,40.0,100.9,119.0,0.0,0.0,0.0],[113.3,40.8,101.9,118.5,0.1,0.0,0.0],[111.1,41.7,102.8,118.1,0.3,0.0,0.0],[109.7,42.7,103.7,117.7,0.6,0.0,0.0],[108.6,43.4,104.3,117.2,0.7,0.0,0.0],[107.5,43.9,105.1,116.8,0.7,0.0,0.0],[106.5,44.3,105.8,116.4,1.0,0.0,0.0],[105.3,44.8,106.4,116.1,1.2,0.0,0.0],[104.4,45.2,107.1,115.8,1.4,0.0,0.0],[103.1,45.7,107.7,115.5,1.7,0.0,0.0],[101.8,46.1,108.2,115.2,2.0,0.0,0.0],[100.6,46.4,108.7,114.9,2.1,0.0,0.0],[99.4,46.7,109.1,114.8,2.3,0.0,0.0],[98.7,46.9,109.3,114.7,2.5,0.0,0.0],[98.2,47.1,109.5,114.6,2.7,0.0,0.0],[97.6,47.3,109.7,114.6,2.8,0.0,0.0],[97.0,47.3,109.7,114.5,2.7,0.0,0.0]],"scrub":false},"thinking_rest":{"n":120,"loop":true,"role":"rest","state":"thinking","events":{},"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.8,0.0,0.0],[97.8,46.9,109.7,114.4,2.7,0.0,0.0],[97.9,46.8,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.6,109.7,114.2,2.7,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.9,46.3,109.7,114.1,2.8,0.0,0.0],[97.9,46.2,109.7,114.0,2.7,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.8,46.0,109.7,113.8,2.9,0.0,0.0],[97.8,45.9,109.7,113.8,2.9,0.0,0.0],[97.8,45.8,109.7,113.8,2.9,0.0,0.0],[97.9,45.7,109.7,113.7,2.7,0.0,0.0],[97.8,45.6,109.7,113.7,2.9,0.0,0.0],[97.7,45.5,109.7,113.7,2.9,0.0,0.0],[97.8,45.5,109.7,113.6,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.9,45.3,109.7,113.4,2.9,0.0,0.0],[97.7,45.2,109.7,113.4,2.9,0.0,0.0],[97.8,45.2,109.7,113.4,3.0,0.0,0.0],[97.8,45.1,109.7,113.3,2.9,0.0,0.0],[97.8,45.1,109.8,113.3,2.9,0.0,0.0],[97.7,45.0,109.8,113.3,2.9,0.0,0.0],[97.8,45.0,109.8,113.3,3.0,0.0,0.0],[97.7,44.9,109.8,113.2,2.9,0.0,0.0],[97.6,44.9,109.8,113.2,2.9,0.0,0.0],[97.6,44.9,109.8,113.2,2.9,0.0,0.0],[97.7,44.9,109.8,113.2,2.9,0.0,0.0],[97.7,44.9,109.9,113.2,2.9,0.0,0.0],[97.6,44.9,109.9,113.2,2.9,0.0,0.0],[97.5,44.9,109.9,113.2,2.9,0.0,0.0],[97.5,44.9,109.9,113.2,2.9,0.0,0.0],[97.5,44.9,110.0,113.3,3.1,0.0,0.0],[97.5,44.9,110.0,113.3,3.1,0.0,0.0],[97.6,45.0,110.0,113.3,3.1,0.0,0.0],[97.5,45.0,110.0,113.3,3.1,0.0,0.0],[97.5,45.1,110.1,113.3,3.1,0.0,0.0],[97.4,45.1,110.2,113.4,3.1,0.0,0.0],[97.4,45.2,110.2,113.4,3.1,0.0,0.0],[97.4,45.2,110.2,113.4,3.1,0.0,0.0],[97.3,45.3,110.2,113.5,3.3,0.0,0.0],[97.4,45.3,110.2,113.5,3.1,0.0,0.0],[97.4,45.4,110.2,113.5,3.3,0.0,0.0],[97.3,45.5,110.3,113.6,3.1,0.0,0.0],[97.3,45.6,110.3,113.7,3.3,0.0,0.0],[97.3,45.7,110.3,113.7,3.1,0.0,0.0],[97.2,45.8,110.3,113.8,3.3,0.0,0.0],[97.2,45.9,110.3,113.8,3.1,0.0,0.0],[97.2,46.0,110.3,113.8,3.3,0.0,0.0],[97.2,46.1,110.3,113.9,3.1,0.0,0.0],[97.2,46.2,110.3,114.0,3.3,0.0,0.0],[97.2,46.3,110.4,114.0,3.1,0.0,0.0],[97.1,46.4,110.4,114.1,3.1,0.0,0.0],[97.1,46.5,110.4,114.2,3.3,0.0,0.0],[97.2,46.6,110.4,114.2,3.1,0.0,0.0],[97.2,46.7,110.4,114.3,3.1,0.0,0.0],[97.2,46.9,110.4,114.3,3.3,0.0,0.0],[97.2,47.0,110.4,114.4,3.1,0.0,0.0],[97.1,47.1,110.4,114.5,3.1,0.0,0.0],[97.1,47.2,110.4,114.5,3.3,0.0,0.0],[97.2,47.3,110.4,114.6,3.1,0.0,0.0],[97.2,47.5,110.4,114.7,3.1,0.0,0.0],[97.2,47.6,110.3,114.8,2.9,0.0,0.0],[97.2,47.7,110.3,114.8,3.1,0.0,0.0],[97.4,47.8,110.3,114.9,3.1,0.0,0.0],[97.3,47.9,110.2,114.9,2.9,0.0,0.0],[97.4,48.0,110.2,115.0,3.1,0.0,0.0],[97.3,48.2,110.2,115.1,2.9,0.0,0.0],[97.4,48.3,110.2,115.2,2.9,0.0,0.0],[97.4,48.4,110.1,115.2,2.9,0.0,0.0],[97.7,48.4,110.0,115.2,2.9,0.0,0.0],[97.7,48.5,110.0,115.3,2.7,0.0,0.0],[97.7,48.6,109.9,115.3,2.8,0.0,0.0],[97.7,48.7,109.9,115.4,2.7,0.0,0.0],[97.7,48.8,109.8,115.4,2.8,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[97.9,48.9,109.8,115.5,2.7,0.0,0.0],[97.9,49.0,109.8,115.6,2.7,0.0,0.0],[97.7,49.1,109.8,115.6,2.7,0.0,0.0],[97.9,49.1,109.8,115.6,2.7,0.0,0.0],[97.8,49.2,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.5,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.9,49.4,109.8,115.8,2.7,0.0,0.0],[97.6,49.5,109.8,115.8,2.7,0.0,0.0],[97.6,49.5,109.8,115.8,2.7,0.0,0.0],[97.7,49.5,109.8,115.8,2.7,0.0,0.0],[97.6,49.5,109.8,115.8,2.7,0.0,0.0],[97.7,49.5,109.8,115.8,2.7,0.0,0.0],[97.9,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.5,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.8,49.2,109.8,115.7,2.7,0.0,0.0],[97.7,49.2,109.8,115.6,2.7,0.0,0.0],[97.7,49.1,109.8,115.6,2.7,0.0,0.0],[97.9,49.0,109.8,115.6,2.7,0.0,0.0],[97.7,49.0,109.8,115.5,2.7,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[97.7,48.8,109.8,115.4,2.7,0.0,0.0],[97.8,48.7,109.8,115.4,2.7,0.0,0.0],[97.9,48.6,109.8,115.3,2.7,0.0,0.0],[97.9,48.5,109.8,115.3,2.7,0.0,0.0],[97.9,48.4,109.8,115.2,2.7,0.0,0.0],[97.9,48.3,109.8,115.2,2.7,0.0,0.0],[97.9,48.2,109.8,115.1,2.7,0.0,0.0],[97.9,48.1,109.8,115.1,2.8,0.0,0.0],[97.9,48.0,109.8,115.0,2.7,0.0,0.0],[97.8,47.9,109.8,114.9,2.7,0.0,0.0],[97.8,47.8,109.8,114.8,2.8,0.0,0.0],[97.8,47.6,109.8,114.8,2.7,0.0,0.0],[97.8,47.5,109.7,114.7,2.7,0.0,0.0],[97.9,47.4,109.7,114.7,2.8,0.0,0.0],[97.9,47.3,109.7,114.6,2.7,0.0,0.0]],"scrub":false},"think_swap":{"n":91,"loop":false,"role":"beat","state":"thinking","events":{},"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.8,0.0,0.0],[97.9,46.9,109.7,114.3,2.8,0.0,0.0],[97.8,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.6,109.7,114.2,2.8,0.0,0.0],[97.8,46.4,109.7,114.1,2.8,0.0,0.0],[97.8,46.2,109.7,114.0,2.7,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.8,45.9,109.7,113.8,2.9,0.0,0.0],[97.8,45.8,109.7,113.8,2.9,0.0,0.0],[97.8,45.7,109.7,113.7,2.7,0.0,0.0],[97.9,45.6,109.5,113.6,2.7,0.0,0.0],[98.2,45.6,109.0,113.5,2.6,0.0,0.0],[98.4,45.7,107.8,113.4,2.2,0.0,0.0],[99.5,45.8,106.0,113.2,1.8,0.0,0.0],[101.5,45.9,103.5,113.1,1.0,0.0,0.0],[103.9,45.8,100.8,112.8,0.4,0.0,0.0],[108.0,45.5,97.7,112.7,-0.3,0.0,0.0],[113.1,45.1,94.8,112.6,-0.9,0.0,0.0],[117.2,44.6,92.2,112.5,-1.7,0.0,0.0],[123.7,43.9,90.2,112.5,-2.3,0.0,0.0],[129.9,43.4,88.8,112.5,-2.7,0.0,0.0],[133.4,41.4,88.0,112.5,-3.1,0.0,0.0],[137.1,39.7,87.6,112.5,-3.4,0.0,0.0],[139.5,39.0,87.6,112.5,-3.4,0.0,0.0],[139.7,39.2,87.6,112.5,-3.2,0.0,0.0],[136.6,40.1,87.6,112.5,-3.4,0.0,0.0],[134.0,41.4,87.6,112.5,-3.4,0.0,0.0],[132.1,42.8,87.6,112.5,-3.4,0.0,0.0],[130.8,43.6,87.6,112.6,-3.2,0.0,0.0],[129.6,43.8,87.6,112.7,-3.4,0.0,0.0],[129.1,43.9,87.6,112.7,-3.4,0.0,0.0],[129.2,44.0,87.6,112.8,-3.4,0.0,0.0],[129.4,44.0,87.6,112.8,-3.2,0.0,0.0],[130.3,44.1,87.5,112.8,-3.4,0.0,0.0],[130.9,44.1,87.5,112.9,-3.2,0.0,0.0],[131.3,44.2,87.5,113.0,-3.2,0.0,0.0],[131.5,44.1,87.5,113.0,-3.3,0.0,0.0],[131.8,44.1,87.5,113.2,-3.3,0.0,0.0],[131.5,44.3,87.5,113.2,-3.2,0.0,0.0],[131.4,44.5,87.5,113.3,-3.2,0.0,0.0],[131.2,44.8,87.5,113.4,-3.2,0.0,0.0],[131.2,45.1,87.5,113.5,-3.3,0.0,0.0],[131.2,45.2,87.5,113.5,-3.3,0.0,0.0],[131.2,45.4,87.5,113.7,-3.3,0.0,0.0],[131.1,45.6,87.5,113.7,-3.2,0.0,0.0],[130.9,45.7,87.5,113.8,-3.2,0.0,0.0],[131.1,45.9,87.5,113.9,-3.2,0.0,0.0],[131.0,46.1,87.5,114.0,-3.2,0.0,0.0],[131.1,46.2,87.5,114.1,-3.2,0.0,0.0],[131.2,46.4,87.5,114.2,-3.2,0.0,0.0],[131.3,46.5,87.5,114.3,-3.2,0.0,0.0],[131.3,46.6,87.5,114.3,-3.2,0.0,0.0],[131.3,46.8,87.4,114.4,-3.2,0.0,0.0],[131.3,46.9,87.4,114.5,-3.2,0.0,0.0],[131.2,47.1,87.4,114.6,-3.2,0.0,0.0],[131.2,47.2,87.4,114.6,-3.2,0.0,0.0],[131.2,47.3,87.4,114.7,-3.2,0.0,0.0],[131.3,47.4,87.4,114.8,-3.0,0.0,0.0],[131.3,47.5,87.5,114.8,-3.1,0.0,0.0],[130.9,47.6,87.8,114.8,-2.9,0.0,0.0],[130.7,47.6,88.2,114.9,-2.7,0.0,0.0],[130.3,47.5,89.0,115.0,-2.5,0.0,0.0],[129.7,47.5,90.2,115.0,-2.2,0.0,0.0],[128.3,47.8,91.7,115.0,-1.7,0.0,0.0],[126.7,48.1,93.5,115.1,-1.2,0.0,0.0],[123.6,48.3,95.6,115.2,-0.7,0.0,0.0],[119.5,48.5,97.8,115.2,-0.3,0.0,0.0],[114.1,48.7,100.2,115.3,0.3,0.0,0.0],[109.3,48.9,102.4,115.4,0.9,0.0,0.0],[107.3,49.1,104.5,115.5,1.2,0.0,0.0],[102.9,49.3,106.2,115.5,1.7,0.0,0.0],[100.0,49.5,107.5,115.7,2.0,0.0,0.0],[98.3,49.6,108.6,115.7,2.2,0.0,0.0],[96.3,49.7,109.2,115.7,2.4,0.0,0.0],[95.6,49.7,109.6,115.7,2.6,0.0,0.0],[95.5,49.7,109.8,115.6,2.7,0.0,0.0],[95.6,49.5,109.8,115.6,2.7,0.0,0.0],[96.1,49.3,109.8,115.5,2.7,0.0,0.0],[97.3,49.1,109.8,115.5,2.7,0.0,0.0],[97.8,48.8,109.8,115.4,2.7,0.0,0.0],[97.9,48.6,109.8,115.3,2.8,0.0,0.0],[98.3,48.4,109.8,115.3,2.7,0.0,0.0],[99.0,48.2,109.8,115.2,2.7,0.0,0.0],[98.8,48.1,109.8,115.1,2.7,0.0,0.0],[98.2,48.0,109.8,115.1,2.8,0.0,0.0],[98.1,47.9,109.8,115.0,2.7,0.0,0.0],[97.9,47.8,109.8,114.9,2.7,0.0,0.0],[97.8,47.7,109.8,114.8,2.7,0.0,0.0],[97.7,47.6,109.7,114.7,2.7,0.0,0.0],[97.7,47.4,109.7,114.6,2.7,0.0,0.0]],"scrub":false},"think_squint":{"n":82,"loop":false,"role":"beat","state":"thinking","events":{},"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.9,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.9,46.0,109.7,113.8,2.9,0.0,0.0],[97.9,45.8,109.7,113.8,2.9,0.0,0.0],[97.8,45.7,109.7,113.7,2.9,0.0,0.0],[97.7,45.5,109.7,113.7,2.9,0.0,0.0],[98.0,45.3,109.7,113.7,2.7,0.0,0.0],[98.6,44.9,109.7,114.2,2.3,0.01,0.0],[100.0,44.1,109.6,115.2,1.8,0.01,0.0],[101.9,43.0,109.2,116.9,1.1,0.02,0.0],[104.9,41.9,108.5,119.2,0.4,0.04,0.0],[107.7,40.9,107.3,122.2,-0.3,0.06,0.0],[111.6,39.2,105.7,125.5,-0.5,0.07,0.0],[120.4,37.3,103.8,128.8,-0.5,0.09,0.0],[127.4,36.1,101.9,131.8,-0.4,0.1,0.0],[129.1,35.8,100.3,133.9,-0.1,0.11,0.0],[130.4,35.9,99.4,135.3,0.0,0.11,0.0],[130.7,36.3,99.1,135.9,-0.1,0.12,0.0],[130.7,36.4,99.0,135.9,0.0,0.12,0.0],[130.8,36.4,99.0,135.9,0.0,0.12,0.0],[130.8,36.1,99.0,136.0,0.0,0.12,0.0],[130.8,36.0,99.0,136.0,0.0,0.12,0.0],[130.3,35.9,99.0,136.1,0.0,0.12,0.0],[129.6,36.0,99.0,136.1,0.0,0.12,0.0],[129.1,36.2,99.0,136.2,0.0,0.12,0.0],[128.8,36.4,99.0,136.2,0.0,0.12,0.0],[128.7,36.6,99.0,136.3,0.0,0.12,0.0],[128.8,36.8,99.0,136.4,0.0,0.12,0.0],[129.2,37.0,99.0,136.4,0.0,0.12,0.0],[129.4,37.2,99.0,136.5,0.0,0.12,0.0],[129.6,37.3,99.0,136.6,0.0,0.12,0.0],[129.8,37.5,99.0,136.7,0.0,0.12,0.0],[129.9,37.7,99.0,136.8,0.0,0.12,0.0],[129.9,37.8,99.0,136.9,0.0,0.12,0.0],[129.9,38.0,99.0,137.0,0.0,0.12,0.0],[129.8,38.2,99.0,137.1,0.0,0.12,0.0],[129.7,38.4,99.0,137.1,0.0,0.12,0.0],[129.6,38.7,99.0,137.2,0.0,0.12,0.0],[129.6,38.9,99.0,137.3,0.0,0.12,0.0],[129.5,39.1,99.0,137.4,0.0,0.12,0.0],[129.5,39.3,99.0,137.5,0.0,0.12,0.0],[129.5,39.5,99.0,137.6,0.0,0.12,0.0],[129.5,39.7,99.0,137.7,0.0,0.12,0.0],[129.6,39.9,99.0,137.8,0.0,0.12,0.0],[129.6,40.0,99.0,137.9,0.0,0.12,0.0],[129.6,40.2,99.0,137.9,0.0,0.12,0.0],[129.6,40.3,99.0,138.0,0.0,0.12,0.0],[129.7,40.5,99.2,137.9,-0.1,0.12,0.0],[129.9,40.5,99.7,137.2,-0.1,0.11,0.0],[130.1,40.5,100.4,136.2,-0.3,0.11,0.0],[130.1,40.4,101.6,134.6,-0.4,0.1,0.0],[127.9,40.4,103.1,132.4,-0.5,0.09,0.0],[125.5,40.5,104.6,129.9,-0.7,0.08,0.0],[123.2,41.0,106.1,127.3,-0.4,0.07,0.0],[119.8,42.0,107.4,124.8,-0.3,0.06,0.0],[111.7,43.6,108.4,122.5,0.1,0.04,0.0],[107.2,45.7,109.1,120.4,0.6,0.03,0.0],[103.8,47.2,109.5,118.7,1.2,0.02,0.0],[101.3,48.1,109.7,117.5,1.8,0.01,0.0],[98.4,48.9,109.8,116.6,2.1,0.01,0.0],[97.8,49.5,109.8,116.0,2.5,0.0,0.0],[97.4,49.9,109.8,115.8,2.7,0.0,0.0],[97.2,50.0,109.8,115.7,2.7,0.0,0.0],[97.4,49.8,109.8,115.6,2.7,0.0,0.0],[97.4,49.6,109.8,115.6,2.7,0.0,0.0],[97.1,49.2,109.8,115.5,2.7,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[98.1,48.7,109.8,115.4,2.7,0.0,0.0],[98.6,48.4,109.8,115.3,2.7,0.0,0.0],[98.7,48.2,109.8,115.2,2.7,0.0,0.0],[98.6,48.1,109.8,115.2,2.8,0.0,0.0],[98.4,48.0,109.8,115.1,2.8,0.0,0.0],[98.1,47.8,109.8,115.0,2.7,0.0,0.0],[97.9,47.7,109.8,114.9,2.7,0.0,0.0],[97.7,47.6,109.8,114.8,2.7,0.0,0.0],[97.6,47.5,109.7,114.7,2.7,0.0,0.0],[97.6,47.4,109.7,114.6,2.7,0.0,0.0]],"scrub":false},"think_hm":{"n":67,"loop":false,"role":"beat","state":"thinking","events":{},"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.9,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.8,109.7,114.2,2.8,0.0,0.0],[97.9,46.6,109.7,114.2,2.8,0.0,0.0],[97.9,46.4,109.7,114.1,2.8,0.0,0.0],[97.9,46.2,109.7,113.9,2.9,0.0,0.0],[97.8,45.9,109.7,113.8,2.9,0.0,0.0],[97.7,45.7,109.7,113.8,2.9,0.0,0.0],[97.8,45.6,109.7,113.7,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.6,45.0,109.5,113.2,2.9,0.0,0.0],[97.4,44.6,109.4,112.9,2.9,0.0,0.0],[97.9,44.8,109.2,113.2,2.9,0.0,0.0],[97.5,45.9,109.2,113.8,2.8,0.0,0.0],[97.8,47.5,109.2,114.8,2.7,0.0,0.0],[98.1,49.3,109.2,115.8,2.6,0.0,0.0],[98.6,51.0,109.2,116.5,2.5,0.0,0.0],[99.2,52.1,109.2,117.0,2.5,0.0,0.0],[99.1,52.5,109.2,117.0,2.5,0.0,0.0],[97.3,42.8,108.7,107.8,3.3,0.0,0.0],[97.5,35.7,108.6,103.0,3.8,0.0,0.0],[99.1,30.6,108.5,101.3,3.9,0.0,0.0],[99.7,27.4,108.5,101.5,3.9,0.0,0.0],[100.2,26.3,108.5,102.5,3.9,0.0,0.0],[100.4,26.3,108.6,103.2,3.7,0.0,0.0],[100.5,27.0,108.6,103.2,3.7,0.0,0.0],[100.1,28.6,108.6,103.3,3.7,0.0,0.0],[99.9,30.3,108.7,103.5,3.7,0.0,0.0],[98.5,31.9,108.7,103.5,3.7,0.0,0.0],[98.4,32.9,108.7,103.7,3.7,0.0,0.0],[98.4,33.4,108.6,103.8,3.7,0.0,0.0],[98.5,33.4,108.6,104.0,3.7,0.0,0.0],[99.5,33.1,108.6,104.0,3.7,0.0,0.0],[99.6,32.7,108.6,104.2,3.5,0.0,0.0],[99.9,32.5,108.7,104.3,3.7,0.0,0.0],[99.9,32.4,108.7,104.5,3.7,0.0,0.0],[99.9,32.5,108.7,104.6,3.5,0.0,0.0],[99.9,32.8,108.7,104.7,3.5,0.0,0.0],[99.6,33.3,108.7,104.8,3.7,0.0,0.0],[99.6,33.7,108.7,105.0,3.7,0.0,0.0],[99.6,34.2,108.7,105.2,3.5,0.0,0.0],[99.6,34.9,108.7,105.6,3.5,0.0,0.0],[99.4,35.9,108.8,106.3,3.5,0.0,0.0],[99.0,37.2,108.9,107.3,3.4,0.0,0.0],[99.2,38.7,109.0,108.5,3.3,0.0,0.0],[98.5,40.6,109.2,109.8,3.1,0.0,0.0],[98.6,42.5,109.3,111.2,3.0,0.0,0.0],[97.8,44.5,109.4,112.5,3.0,0.0,0.0],[97.9,46.4,109.5,113.7,2.9,0.0,0.0],[97.5,47.9,109.7,114.6,2.7,0.0,0.0],[97.7,49.0,109.7,115.3,2.7,0.0,0.0],[97.8,49.7,109.8,115.6,2.7,0.0,0.0],[98.1,49.9,109.8,115.8,2.7,0.0,0.0],[98.1,49.8,109.8,115.8,2.7,0.0,0.0],[97.9,49.6,109.8,115.7,2.7,0.0,0.0],[97.9,49.3,109.8,115.7,2.7,0.0,0.0],[97.9,49.1,109.8,115.6,2.7,0.0,0.0],[97.8,48.9,109.8,115.6,2.7,0.0,0.0],[97.8,48.7,109.8,115.5,2.7,0.0,0.0],[97.7,48.6,109.8,115.4,2.7,0.0,0.0],[97.6,48.5,109.8,115.3,2.7,0.0,0.0],[97.7,48.4,109.8,115.2,2.7,0.0,0.0],[97.7,48.3,109.8,115.1,2.7,0.0,0.0],[97.8,48.1,109.8,115.0,2.7,0.0,0.0],[97.9,47.9,109.8,114.9,2.7,0.0,0.0],[97.9,47.7,109.8,114.8,2.7,0.0,0.0],[97.9,47.5,109.7,114.7,2.8,0.0,0.0]],"scrub":false},"think_count":{"n":82,"loop":false,"role":"beat","state":"thinking","events":{},"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.9,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.9,46.0,109.7,113.8,2.9,0.0,0.0],[97.9,45.8,109.7,113.8,2.9,0.0,0.0],[97.9,45.7,109.7,113.7,2.9,0.0,0.0],[98.7,45.1,110.2,114.4,2.7,0.0,0.0],[100.3,44.1,111.2,116.3,2.0,0.0,0.0],[102.2,43.3,112.2,118.0,1.5,0.0,0.0],[104.4,42.7,113.1,119.7,1.0,0.0,0.0],[105.5,42.4,113.7,121.2,0.5,0.0,0.0],[107.8,41.2,114.2,122.4,0.3,0.0,0.0],[110.2,40.1,114.6,123.4,0.0,0.0,0.0],[110.7,39.2,115.0,124.2,-0.2,0.0,0.0],[112.3,38.8,115.1,124.7,-0.5,0.0,0.0],[112.7,38.5,115.2,124.8,-0.5,0.0,0.0],[112.1,38.4,115.0,124.1,-0.3,0.0,0.0],[108.5,39.0,113.2,119.8,0.8,0.0,0.0],[103.9,41.1,110.7,115.0,2.3,0.0,0.0],[100.2,43.4,109.7,113.2,2.9,0.0,0.0],[101.3,42.9,111.4,116.3,1.8,0.0,0.0],[104.1,42.5,113.3,120.2,0.8,0.0,0.0],[106.4,42.6,114.5,123.1,0.0,0.0,0.0],[107.7,42.5,115.1,124.7,-0.3,0.0,0.0],[108.5,42.6,115.2,124.9,-0.5,0.0,0.0],[108.6,41.1,114.0,122.1,0.3,0.0,0.0],[105.9,41.3,111.7,117.0,1.7,0.0,0.0],[102.5,42.9,109.8,114.0,2.7,0.0,0.0],[101.9,43.3,110.5,115.1,2.3,0.0,0.0],[103.6,43.2,112.7,119.2,1.2,0.0,0.0],[106.4,42.9,114.1,122.6,0.3,0.0,0.0],[107.9,43.1,115.0,124.8,-0.3,0.0,0.0],[108.2,43.5,115.2,125.6,-0.5,0.0,0.0],[109.1,42.5,114.8,124.3,-0.2,0.0,0.0],[106.9,42.3,112.7,119.8,1.2,0.0,0.0],[103.0,44.0,110.4,115.5,2.3,0.0,0.0],[100.7,45.5,109.7,114.4,2.8,0.0,0.0],[102.5,45.1,112.0,118.5,1.5,0.0,0.0],[105.1,44.5,113.7,122.2,0.5,0.0,0.0],[107.3,44.6,114.8,124.8,-0.2,0.0,0.0],[108.5,44.9,115.3,126.2,-0.5,0.0,0.0],[108.9,44.4,115.2,126.1,-0.5,0.0,0.0],[108.7,43.5,113.8,122.6,0.5,0.0,0.0],[104.7,44.5,111.2,117.7,1.8,0.0,0.0],[101.9,46.3,109.8,115.3,2.7,0.0,0.0],[100.0,47.5,109.8,115.3,2.7,0.0,0.0],[99.2,48.2,109.8,115.4,2.7,0.0,0.0],[97.7,48.6,109.8,115.4,2.7,0.0,0.0],[99.1,49.2,109.8,115.5,2.7,0.0,0.0],[99.8,49.7,109.8,115.6,2.7,0.0,0.0],[99.6,50.0,109.8,115.6,2.7,0.0,0.0],[100.0,50.0,109.8,115.7,2.7,0.0,0.0],[98.8,49.9,109.8,115.7,2.7,0.0,0.0],[98.3,49.7,109.8,115.7,2.7,0.0,0.0],[97.8,49.5,109.8,115.8,2.7,0.0,0.0],[98.1,49.4,109.8,115.8,2.7,0.0,0.0],[98.2,49.3,109.8,115.8,2.7,0.0,0.0],[98.0,49.2,109.8,115.8,2.7,0.0,0.0],[98.2,49.2,109.8,115.8,2.7,0.0,0.0],[98.2,49.2,109.8,115.8,2.7,0.0,0.0],[97.8,49.3,109.8,115.8,2.7,0.0,0.0],[97.8,49.3,109.8,115.8,2.7,0.0,0.0],[97.6,49.3,109.8,115.7,2.7,0.0,0.0],[97.6,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.6,2.7,0.0,0.0],[97.7,49.2,109.8,115.6,2.7,0.0,0.0],[97.7,49.0,109.8,115.5,2.7,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[97.8,48.7,109.8,115.4,2.7,0.0,0.0],[97.8,48.6,109.8,115.3,2.7,0.0,0.0],[97.8,48.4,109.8,115.2,2.7,0.0,0.0],[97.8,48.3,109.8,115.2,2.8,0.0,0.0],[97.9,48.1,109.8,115.1,2.8,0.0,0.0],[98.0,47.9,109.8,115.0,2.7,0.0,0.0],[97.8,47.8,109.8,114.9,2.7,0.0,0.0],[97.9,47.6,109.8,114.8,2.7,0.0,0.0],[97.8,47.5,109.7,114.7,2.7,0.0,0.0],[97.8,47.3,109.7,114.6,2.7,0.0,0.0]],"scrub":false},"think_sigh":{"n":82,"loop":false,"role":"beat","state":"thinking","events":{},"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.9,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.9,46.0,109.7,113.8,2.9,0.0,0.0],[97.8,45.8,109.7,113.8,2.9,0.0,0.0],[97.8,45.7,109.7,113.7,2.9,0.0,0.0],[97.7,45.5,109.7,113.7,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.8,45.1,109.7,113.3,2.9,0.0,0.0],[97.9,44.5,109.6,112.9,2.9,0.0,0.0],[97.8,43.8,109.5,112.4,2.9,0.0,0.0],[97.9,42.7,109.5,111.8,3.0,0.0,0.0],[97.9,41.4,109.5,111.0,3.0,0.0,0.0],[98.2,39.8,109.4,110.1,3.1,0.0,0.0],[98.4,38.1,109.5,109.2,2.9,0.0,0.0],[98.4,36.2,109.4,108.2,3.1,0.0,0.0],[98.5,34.4,109.3,107.2,3.1,0.0,0.0],[98.8,32.7,109.3,106.3,2.9,0.0,0.0],[99.2,31.1,109.3,105.6,3.1,0.0,0.0],[99.2,29.8,109.2,104.9,2.9,0.0,0.0],[99.5,28.7,109.3,104.6,2.9,0.0,0.0],[99.6,28.0,109.3,104.3,2.8,0.0,0.0],[99.7,27.6,109.4,104.2,2.6,0.0,0.0],[99.8,27.4,109.4,104.2,2.6,0.0,0.0],[99.8,27.3,109.4,104.4,2.4,0.0,0.0],[99.9,27.3,109.5,104.6,2.2,0.0,0.0],[99.9,27.6,109.6,104.9,2.0,0.0,0.0],[100.3,28.1,109.7,105.5,1.9,0.0,0.0],[100.5,29.0,109.7,106.2,1.7,0.0,0.0],[100.3,30.4,109.8,107.2,1.5,0.0,0.0],[100.1,32.3,109.8,108.5,1.3,0.0,0.0],[100.1,34.6,109.9,110.0,1.0,0.0,0.0],[100.0,37.3,110.0,111.8,0.8,0.0,0.0],[100.2,40.3,110.1,113.5,0.7,0.0,0.0],[100.5,43.6,110.2,115.4,0.3,0.0,0.0],[100.3,46.9,110.2,117.3,0.2,0.0,0.0],[100.3,50.2,110.3,119.2,-0.2,0.0,0.0],[100.5,53.3,110.4,121.0,-0.3,0.0,0.0],[100.2,56.1,110.5,122.7,-0.5,0.0,0.0],[99.9,58.5,110.5,124.0,-0.8,0.0,0.0],[99.9,60.5,110.6,125.2,-0.8,0.0,0.0],[99.8,62.1,110.6,126.2,-0.9,0.0,0.0],[99.9,63.2,110.7,126.8,-1.1,0.0,0.0],[99.8,63.9,110.7,127.3,-0.9,0.0,0.0],[99.9,64.2,110.7,127.5,-0.9,0.0,0.0],[99.8,64.4,110.7,127.7,-1.1,0.0,0.0],[99.8,64.4,110.7,127.7,-0.9,0.0,0.0],[99.8,64.4,110.7,127.8,-1.1,0.0,0.0],[99.8,64.4,110.7,127.8,-1.1,0.0,0.0],[99.8,64.5,110.7,127.8,-1.1,0.0,0.0],[99.8,64.6,110.7,128.0,-1.1,0.0,0.0],[99.8,64.7,110.7,128.0,-1.1,0.0,0.0],[99.8,64.8,110.7,128.1,-1.1,0.0,0.0],[99.8,64.9,110.7,128.1,-1.1,0.0,0.0],[99.8,65.0,110.7,128.1,-1.1,0.0,0.0],[99.8,65.0,110.7,128.2,-1.1,0.0,0.0],[99.8,65.0,110.7,128.2,-1.1,0.0,0.0],[99.8,64.7,110.7,127.8,-1.1,0.0,0.0],[99.6,63.2,110.7,126.3,-0.5,0.0,0.0],[99.7,60.2,110.5,123.6,0.3,0.0,0.0],[99.5,56.4,110.3,120.4,1.1,0.0,0.0],[98.9,52.8,110.0,117.7,2.0,0.0,0.0],[98.6,50.0,109.8,116.2,2.5,0.0,0.0],[97.9,48.6,109.8,115.7,2.7,0.0,0.0],[98.1,47.9,109.8,115.6,2.7,0.0,0.0],[98.1,47.7,109.8,115.6,2.7,0.0,0.0],[98.1,47.9,109.8,115.5,2.7,0.0,0.0],[98.0,48.3,109.8,115.5,2.7,0.0,0.0],[97.3,48.7,109.8,115.4,2.7,0.0,0.0],[97.5,48.9,109.8,115.3,2.7,0.0,0.0],[97.7,49.0,109.8,115.2,2.7,0.0,0.0],[97.9,48.9,109.8,115.2,2.8,0.0,0.0],[97.8,48.6,109.8,115.1,2.8,0.0,0.0],[98.0,48.2,109.8,115.0,2.7,0.0,0.0],[98.0,47.8,109.8,114.9,2.7,0.0,0.0],[97.9,47.5,109.8,114.8,2.7,0.0,0.0],[98.0,47.2,109.7,114.7,2.7,0.0,0.0],[97.8,47.0,109.7,114.6,2.7,0.0,0.0]],"scrub":false},"think_roll":{"n":86,"loop":false,"role":"beat","state":"thinking","events":{},"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.8,0.0,0.0],[97.9,46.9,109.7,114.3,2.8,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.8,46.5,109.7,114.2,2.8,0.0,0.0],[97.9,46.4,109.7,114.1,2.8,0.0,0.0],[97.8,46.2,109.7,113.9,2.9,0.0,0.0],[97.8,46.0,109.7,113.9,2.7,0.0,0.0],[97.8,45.9,109.7,113.8,2.7,0.0,0.0],[97.7,45.7,109.7,113.8,2.9,0.0,0.0],[97.8,45.6,109.7,113.7,2.9,0.0,0.0],[97.9,45.5,109.7,113.6,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.9,45.3,109.7,113.4,2.9,0.0,0.0],[97.8,45.2,109.7,113.4,2.9,0.0,0.0],[97.7,45.1,109.7,113.3,2.9,0.0,0.0],[97.8,45.1,109.7,113.3,2.9,0.0,0.0],[97.9,45.0,109.7,113.2,2.9,0.0,0.0],[97.9,44.9,109.7,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.9,44.9,109.7,113.2,2.9,0.0,0.0],[97.8,45.0,109.7,113.2,2.9,0.0,0.0],[97.9,45.0,109.7,113.3,2.9,0.0,0.0],[97.8,45.1,109.7,113.3,2.9,0.0,0.0],[97.8,45.2,109.7,113.4,2.9,0.0,0.0],[97.8,45.3,109.7,113.4,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.8,45.5,109.7,113.6,2.9,0.0,0.0],[97.8,45.6,109.7,113.7,2.9,0.0,0.0],[97.8,45.7,109.7,113.8,2.9,0.0,0.0],[97.9,45.9,109.7,113.8,2.7,0.0,0.0],[97.8,46.0,109.7,113.8,2.9,0.0,0.0],[97.9,46.2,109.7,113.9,2.9,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.6,109.7,114.2,2.8,0.0,0.0],[97.9,46.8,109.7,114.3,2.7,0.0,0.0],[97.9,47.0,109.7,114.4,2.7,0.0,0.0],[97.8,47.1,109.7,114.5,2.7,0.0,0.0],[97.9,47.3,109.7,114.6,2.7,0.0,0.0],[97.8,47.5,109.7,114.7,2.7,0.0,0.0],[97.8,47.6,109.8,114.8,2.7,0.0,0.0],[97.9,47.8,109.8,114.9,2.7,0.0,0.0],[97.8,48.0,109.8,114.9,2.8,0.0,0.0],[97.9,48.1,109.8,115.1,2.8,0.0,0.0],[97.8,48.3,109.8,115.1,2.7,0.0,0.0],[97.9,48.4,109.8,115.2,2.7,0.0,0.0],[97.9,48.5,109.8,115.3,2.7,0.0,0.0],[97.7,48.7,109.8,115.4,2.7,0.0,0.0],[97.7,48.8,109.8,115.4,2.7,0.0,0.0],[97.8,48.9,109.8,115.5,2.7,0.0,0.0],[97.8,49.0,109.8,115.6,2.7,0.0,0.0],[97.8,49.1,109.8,115.6,2.7,0.0,0.0],[97.7,49.2,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.8,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.8,49.4,109.8,115.8,2.7,0.0,0.0],[97.9,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.5,109.8,115.8,2.7,0.0,0.0],[97.6,49.5,109.8,115.8,2.7,0.0,0.0],[97.7,49.5,109.8,115.8,2.7,0.0,0.0],[97.9,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.9,49.2,109.8,115.7,2.7,0.0,0.0],[97.7,49.2,109.8,115.6,2.7,0.0,0.0],[97.7,49.1,109.8,115.6,2.7,0.0,0.0],[97.7,49.0,109.8,115.5,2.7,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[97.9,48.7,109.8,115.4,2.7,0.0,0.0],[97.9,48.6,109.8,115.3,2.7,0.0,0.0],[97.8,48.5,109.8,115.3,2.7,0.0,0.0],[97.9,48.3,109.8,115.2,2.7,0.0,0.0],[97.9,48.2,109.8,115.1,2.7,0.0,0.0],[97.9,48.0,109.8,115.0,2.7,0.0,0.0],[97.9,47.9,109.8,114.9,2.7,0.0,0.0],[97.9,47.7,109.8,114.8,2.8,0.0,0.0],[97.8,47.6,109.7,114.8,2.8,0.0,0.0],[97.9,47.4,109.7,114.7,2.8,0.0,0.0]],"scrub":false},"think_down":{"n":82,"loop":false,"role":"beat","state":"thinking","events":{},"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.9,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.9,46.0,109.7,113.8,2.9,0.0,0.0],[97.9,45.8,109.7,113.8,2.9,0.0,0.0],[97.8,45.7,109.7,113.7,2.9,0.0,0.0],[97.7,45.5,109.7,113.7,2.9,0.0,0.0],[98.0,45.3,109.7,113.7,2.9,0.0,0.0],[98.4,44.8,109.7,114.0,2.5,0.0,0.0],[99.6,44.0,109.5,114.6,2.1,0.0,0.0],[101.1,42.7,109.3,115.6,1.6,0.0,0.0],[103.9,41.2,108.7,117.2,0.9,0.0,0.0],[106.4,39.6,107.8,119.2,0.4,0.0,0.0],[109.0,37.6,106.5,121.5,-0.1,0.0,0.0],[115.8,34.8,104.8,124.0,-0.3,0.0,0.0],[123.3,32.4,103.0,126.3,-0.4,0.0,0.0],[126.9,31.0,101.5,128.5,-0.3,0.0,0.0],[128.1,30.5,100.2,130.1,-0.1,0.0,0.0],[128.6,30.5,99.4,131.1,-0.1,0.0,0.0],[128.7,30.7,99.1,131.5,0.0,0.0,0.0],[129.0,30.9,99.0,131.6,0.0,0.0,0.0],[129.0,30.9,99.0,131.6,0.0,0.0,0.0],[128.6,30.9,99.1,131.6,0.0,0.0,0.0],[128.3,30.8,99.1,131.6,0.0,0.0,0.0],[128.1,30.8,99.2,131.6,0.0,0.0,0.0],[127.7,30.9,99.2,131.5,0.0,0.0,0.0],[127.3,31.1,99.4,131.4,-0.1,0.0,0.0],[127.2,31.3,99.7,131.1,-0.1,0.0,0.0],[127.3,31.5,99.9,130.9,0.0,0.0,0.0],[127.5,31.7,100.2,130.6,-0.1,0.0,0.0],[127.8,31.9,100.6,130.2,-0.3,0.0,0.0],[128.0,32.2,101.0,129.8,-0.1,0.0,0.0],[128.1,32.5,101.5,129.2,-0.3,0.0,0.0],[127.5,32.8,102.0,128.7,-0.3,0.0,0.0],[127.0,33.2,102.5,128.1,-0.4,0.0,0.0],[126.2,33.6,103.1,127.4,-0.3,0.0,0.0],[124.3,34.1,103.7,126.8,-0.4,0.0,0.0],[123.8,34.8,104.3,126.0,-0.3,0.0,0.0],[122.3,35.5,104.8,125.3,-0.3,0.0,0.0],[121.3,36.3,105.4,124.5,-0.1,0.0,0.0],[119.5,37.2,106.0,123.8,-0.3,0.0,0.0],[117.4,38.2,106.5,123.0,-0.1,0.0,0.0],[113.2,39.2,107.0,122.4,0.0,0.0,0.0],[111.3,40.2,107.5,121.7,0.1,0.0,0.0],[109.8,41.3,107.8,121.0,0.3,0.0,0.0],[108.6,42.3,108.2,120.3,0.4,0.0,0.0],[107.5,43.3,108.6,119.8,0.6,0.0,0.0],[105.7,44.4,108.8,119.2,0.8,0.0,0.0],[105.2,45.1,109.1,118.8,1.1,0.0,0.0],[104.4,45.7,109.2,118.2,1.1,0.0,0.0],[103.4,46.2,109.4,117.8,1.4,0.0,0.0],[102.5,46.8,109.5,117.5,1.6,0.0,0.0],[101.4,47.3,109.5,117.2,1.8,0.0,0.0],[100.9,47.8,109.7,116.9,1.9,0.0,0.0],[100.2,48.2,109.7,116.7,2.1,0.0,0.0],[99.4,48.6,109.8,116.4,2.3,0.0,0.0],[98.6,48.9,109.8,116.2,2.5,0.0,0.0],[98.4,49.1,109.8,116.1,2.3,0.0,0.0],[98.0,49.3,109.8,116.0,2.5,0.0,0.0],[97.8,49.4,109.8,115.9,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.6,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.2,109.8,115.6,2.7,0.0,0.0],[97.7,49.1,109.8,115.6,2.7,0.0,0.0],[97.8,49.0,109.8,115.5,2.7,0.0,0.0],[97.9,48.8,109.8,115.5,2.7,0.0,0.0],[97.8,48.7,109.8,115.4,2.7,0.0,0.0],[97.8,48.6,109.8,115.3,2.7,0.0,0.0],[97.9,48.4,109.8,115.2,2.7,0.0,0.0],[97.8,48.3,109.8,115.2,2.8,0.0,0.0],[97.9,48.1,109.8,115.1,2.8,0.0,0.0],[97.8,48.0,109.8,115.0,2.7,0.0,0.0],[97.9,47.8,109.8,114.9,2.7,0.0,0.0],[97.8,47.6,109.8,114.8,2.7,0.0,0.0],[97.8,47.5,109.7,114.7,2.7,0.0,0.0],[97.9,47.3,109.7,114.6,2.7,0.0,0.0]],"scrub":false},"working_in":{"n":19,"loop":false,"role":"enter","state":"working","events":{},"frames":[[120.2,37.8,96.2,120.7,-0.1,0.0,0.0],[120.4,41.5,96.7,129.0,0.0,0.0,-0.11],[121.8,46.9,97.2,137.5,0.0,0.0,-0.2],[126.8,53.8,97.7,146.1,0.1,0.0,-0.27],[128.5,60.9,98.1,153.6,0.1,0.0,-0.34],[128.9,67.2,98.5,159.3,0.0,0.0,-0.39],[128.0,71.6,98.8,163.0,0.0,0.0,-0.43],[126.2,71.3,99.1,162.7,0.0,0.0,-0.46],[125.6,69.8,99.3,162.4,-0.1,0.0,-0.48],[126.1,66.9,99.5,161.9,0.0,0.0,-0.5],[126.9,63.2,99.4,161.3,0.0,0.0,-0.5],[128.2,59.4,99.5,160.6,0.0,0.0,-0.5],[128.8,56.3,99.5,159.9,0.0,0.0,-0.5],[129.4,54.3,99.4,159.2,0.0,0.0,-0.5],[129.4,53.5,99.3,158.4,-0.1,0.0,-0.49],[129.1,53.7,99.2,157.8,0.0,0.0,-0.48],[128.6,54.5,99.2,157.2,0.0,0.0,-0.47],[128.1,55.5,99.1,156.8,0.0,0.0,-0.46],[127.6,56.4,99.0,156.4,-0.1,0.0,-0.45]],"scrub":false},"work_read":{"n":144,"loop":true,"role":"rest","state":"working","events":{},"frames":[[127.6,56.0,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.2,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.8,54.8,99.0,155.7,0.0,0.0,-0.45],[125.8,53.9,97.7,155.7,0.0,0.0,-0.45],[123.3,53.1,96.1,155.6,0.1,0.0,-0.45],[123.2,53.0,95.7,155.6,0.1,0.0,-0.45],[123.8,53.3,95.7,155.6,0.1,0.0,-0.45],[124.8,53.7,95.8,155.6,0.1,0.0,-0.45],[125.6,54.1,96.1,155.5,0.0,0.0,-0.45],[126.3,54.4,96.2,155.4,0.1,0.0,-0.45],[126.8,54.6,96.4,155.4,0.1,0.0,-0.45],[127.2,54.7,96.7,155.4,0.1,0.0,-0.45],[127.3,54.7,96.9,155.4,0.1,0.0,-0.45],[127.2,54.6,97.2,155.5,0.0,0.0,-0.45],[127.3,54.6,97.4,155.5,0.0,0.0,-0.45],[127.3,54.5,97.6,155.5,0.0,0.0,-0.45],[127.3,54.5,97.8,155.6,0.1,0.0,-0.45],[127.2,54.5,98.0,155.6,0.0,0.0,-0.45],[127.3,54.5,98.3,155.6,0.0,0.0,-0.45],[127.4,54.6,98.5,155.7,0.0,0.0,-0.45],[127.5,54.7,98.8,155.7,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.9,55.0,99.2,155.8,0.0,0.0,-0.45],[128.1,55.2,99.5,155.9,0.0,0.0,-0.45],[128.3,55.4,99.7,155.9,-0.1,0.0,-0.45],[128.6,55.6,99.8,156.0,0.0,0.0,-0.45],[128.8,55.8,100.0,156.1,0.0,0.0,-0.45],[129.0,56.0,100.3,156.1,-0.1,0.0,-0.45],[129.2,56.2,100.5,156.2,-0.1,0.0,-0.45],[129.3,56.4,100.8,156.3,0.0,0.0,-0.45],[129.5,56.6,101.0,156.4,-0.1,0.0,-0.45],[129.7,56.8,101.2,156.4,-0.1,0.0,-0.45],[129.8,56.9,101.5,156.6,-0.1,0.0,-0.45],[130.0,57.1,101.7,156.6,-0.1,0.0,-0.45],[130.1,57.3,101.9,156.6,-0.1,0.0,-0.45],[130.3,57.4,102.1,156.8,-0.1,0.0,-0.45],[130.5,57.6,102.3,156.8,-0.1,0.0,-0.45],[125.8,56.0,99.5,156.9,-0.1,0.0,-0.45],[122.9,55.2,97.2,156.9,0.1,0.0,-0.45],[122.1,55.2,96.2,157.0,0.0,0.0,-0.45],[122.4,55.7,95.7,157.1,0.1,0.0,-0.45],[123.4,56.4,95.6,157.1,0.1,0.0,-0.45],[124.4,57.1,95.6,157.1,0.1,0.0,-0.45],[125.7,57.8,95.8,157.2,0.1,0.0,-0.45],[126.6,58.3,96.0,157.2,0.1,0.0,-0.45],[127.3,58.6,96.2,157.4,0.1,0.0,-0.45],[125.8,58.7,96.5,157.4,0.1,0.0,-0.45],[126.0,58.7,96.7,157.4,0.1,0.0,-0.45],[127.5,58.5,96.9,157.4,0.0,0.0,-0.45],[127.4,58.4,97.2,157.4,0.0,0.0,-0.45],[127.2,58.1,97.3,157.4,0.0,0.0,-0.45],[127.1,57.9,97.6,157.4,0.0,0.0,-0.45],[127.0,57.8,97.8,157.4,0.0,0.0,-0.45],[127.0,57.6,98.0,157.4,0.0,0.0,-0.45],[127.0,57.5,98.3,157.4,0.0,0.0,-0.45],[127.2,57.4,98.5,157.4,0.1,0.0,-0.45],[127.4,57.3,98.7,157.3,0.0,0.0,-0.45],[127.6,57.3,99.0,157.3,0.0,0.0,-0.45],[127.9,57.2,99.2,157.3,0.0,0.0,-0.45],[128.2,57.2,99.4,157.2,0.0,0.0,-0.45],[128.5,57.1,99.7,157.2,0.0,0.0,-0.45],[128.7,57.0,99.8,157.1,-0.1,0.0,-0.45],[129.0,56.9,100.1,157.1,0.0,0.0,-0.45],[129.2,56.8,100.3,157.1,-0.1,0.0,-0.45],[129.4,56.7,100.5,157.0,0.0,0.0,-0.45],[129.6,56.6,100.8,156.9,-0.1,0.0,-0.45],[129.7,56.4,101.0,156.9,0.0,0.0,-0.45],[129.9,56.3,101.2,156.9,-0.1,0.0,-0.45],[129.9,56.1,101.5,156.8,0.0,0.0,-0.45],[130.2,56.0,101.8,156.8,-0.1,0.0,-0.45],[130.4,55.9,102.0,156.8,-0.1,0.0,-0.45],[130.5,55.8,102.2,156.6,-0.1,0.0,-0.45],[130.7,55.7,102.4,156.6,-0.1,0.0,-0.45],[126.1,53.8,99.5,156.6,0.0,0.0,-0.45],[122.9,52.7,97.2,156.6,0.1,0.0,-0.45],[122.0,52.5,96.1,156.6,0.1,0.0,-0.45],[122.6,52.8,95.7,156.6,0.1,0.0,-0.45],[123.5,53.4,95.6,156.5,0.3,0.0,-0.45],[124.6,53.9,95.6,156.4,0.1,0.0,-0.45],[125.7,54.5,95.7,156.4,0.1,0.0,-0.45],[126.6,54.9,96.0,156.4,0.1,0.0,-0.45],[127.1,55.1,96.2,156.5,0.0,0.0,-0.45],[127.5,55.2,96.4,156.5,0.0,0.0,-0.45],[127.6,55.2,96.7,156.6,0.1,0.0,-0.45],[127.6,55.1,96.8,156.6,0.1,0.0,-0.45],[127.4,54.9,97.1,156.6,0.0,0.0,-0.45],[127.2,54.8,97.3,156.6,0.1,0.0,-0.45],[127.2,54.7,97.5,156.6,0.1,0.0,-0.45],[127.1,54.6,97.8,156.7,0.0,0.0,-0.45],[127.1,54.6,98.0,156.8,0.0,0.0,-0.45],[127.2,54.7,98.2,156.9,0.1,0.0,-0.45],[127.3,54.8,98.5,156.9,0.0,0.0,-0.45],[127.6,54.9,98.7,157.0,0.0,0.0,-0.45],[127.8,55.1,99.0,157.1,0.0,0.0,-0.45],[128.1,55.3,99.2,157.1,0.0,0.0,-0.45],[128.4,55.5,99.4,157.2,0.0,0.0,-0.45],[128.5,55.7,99.7,157.3,0.0,0.0,-0.45],[128.9,56.0,99.9,157.4,0.0,0.0,-0.45],[129.2,56.2,100.1,157.5,0.0,0.0,-0.45],[129.4,56.4,100.3,157.6,0.0,0.0,-0.45],[129.6,56.6,100.5,157.6,-0.1,0.0,-0.45],[129.8,56.8,100.8,157.8,-0.1,0.0,-0.45],[129.8,56.9,101.0,157.9,-0.1,0.0,-0.45],[130.0,57.1,101.2,157.9,-0.1,0.0,-0.45],[130.3,57.3,101.5,158.1,-0.1,0.0,-0.45],[130.4,57.5,101.8,158.1,-0.1,0.0,-0.45],[130.4,57.6,102.0,158.2,-0.1,0.0,-0.45],[130.6,57.8,102.2,158.4,-0.1,0.0,-0.45],[130.9,58.0,102.5,158.4,-0.3,0.0,-0.45],[130.8,58.0,102.5,158.4,-0.1,0.0,-0.45],[130.7,58.0,102.5,158.4,-0.1,0.0,-0.45],[130.3,58.0,102.3,158.4,-0.1,0.0,-0.45],[129.9,57.9,102.1,158.4,-0.1,0.0,-0.45],[129.5,57.8,101.8,158.2,-0.1,0.0,-0.45],[128.9,57.7,101.4,158.1,-0.1,0.0,-0.45],[128.4,57.6,100.9,157.9,-0.1,0.0,-0.45],[128.0,57.6,100.5,157.8,0.0,0.0,-0.45],[127.7,57.5,100.0,157.6,0.0,0.0,-0.45],[127.4,57.6,99.6,157.4,0.0,0.0,-0.45],[127.4,57.6,99.3,157.3,0.0,0.0,-0.45],[127.5,57.7,99.2,157.2,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.9,58.0,99.0,157.1,0.0,0.0,-0.45],[128.0,58.0,99.0,157.1,0.0,0.0,-0.45],[128.1,58.0,99.0,157.1,0.0,0.0,-0.45],[128.2,57.9,99.0,157.0,0.0,0.0,-0.45],[128.1,57.8,99.0,157.0,0.0,0.0,-0.45],[128.0,57.6,99.0,156.9,0.0,0.0,-0.45],[127.9,57.5,99.0,156.9,0.0,0.0,-0.45],[127.8,57.3,99.0,156.8,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.6,56.9,99.0,156.7,0.0,0.0,-0.45],[127.6,56.8,99.0,156.7,0.0,0.0,-0.45],[127.6,56.6,99.0,156.6,0.0,0.0,-0.45],[127.6,56.5,99.0,156.5,0.0,0.0,-0.45],[127.6,56.3,99.0,156.4,0.0,0.0,-0.45],[127.6,56.2,99.0,156.4,0.0,0.0,-0.45]],"scrub":false},"work_edit":{"n":125,"loop":true,"role":"rest","state":"working","events":{},"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,56.0,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.1,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.5,99.0,156.1,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,155.9,0.0,0.0,-0.45],[127.9,55.8,99.0,156.8,0.0,0.0,-0.45],[128.2,57.2,99.0,158.7,0.0,0.0,-0.45],[128.5,58.3,99.0,160.1,0.0,0.0,-0.45],[128.6,59.2,99.0,161.0,0.0,0.0,-0.45],[128.6,59.8,99.0,161.4,0.0,0.0,-0.45],[128.5,60.0,99.0,161.3,0.0,0.0,-0.45],[128.3,59.2,99.0,160.2,0.0,0.0,-0.45],[127.9,57.5,99.0,158.1,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,54.8,99.0,155.6,0.0,0.0,-0.45],[128.2,55.5,99.0,157.3,0.0,0.0,-0.45],[128.6,56.6,99.0,159.0,0.0,0.0,-0.45],[128.7,57.7,99.0,160.2,0.0,0.0,-0.45],[128.7,58.5,99.0,161.0,0.0,0.0,-0.45],[128.6,59.1,99.0,161.2,0.0,0.0,-0.45],[128.4,59.2,99.0,160.8,0.0,0.0,-0.45],[128.0,58.2,99.0,159.2,0.0,0.0,-0.45],[127.7,56.6,99.0,157.0,0.0,0.0,-0.45],[127.6,55.2,99.0,155.7,0.0,0.0,-0.45],[127.8,54.8,99.0,155.9,0.0,0.0,-0.45],[128.4,55.8,99.0,157.9,0.0,0.0,-0.45],[128.7,56.8,99.0,159.5,0.0,0.0,-0.45],[128.8,57.8,99.0,160.5,0.0,0.0,-0.45],[128.8,58.6,99.0,161.0,0.0,0.0,-0.45],[128.6,59.1,99.0,161.1,0.0,0.0,-0.45],[128.3,58.8,99.0,160.3,0.0,0.0,-0.45],[127.9,57.5,99.0,158.3,0.0,0.0,-0.45],[127.6,56.0,99.0,156.4,0.0,0.0,-0.45],[127.6,54.9,99.0,155.6,0.0,0.0,-0.45],[128.0,55.3,99.0,156.9,0.0,0.0,-0.45],[128.5,56.4,99.0,158.7,0.0,0.0,-0.45],[128.7,57.5,99.0,160.0,0.0,0.0,-0.45],[128.8,58.4,99.0,160.9,0.0,0.0,-0.45],[128.7,59.1,99.0,161.3,0.0,0.0,-0.45],[128.5,59.4,99.0,161.1,0.0,0.0,-0.45],[128.2,58.8,99.0,159.8,0.0,0.0,-0.45],[127.8,57.3,99.0,157.6,0.0,0.0,-0.45],[127.6,55.9,99.0,156.1,0.0,0.0,-0.45],[127.7,55.2,99.0,155.8,0.0,0.0,-0.45],[128.2,56.3,99.0,157.9,0.0,0.0,-0.45],[128.6,57.4,99.0,159.5,0.0,0.0,-0.45],[128.8,58.5,99.0,160.7,0.0,0.0,-0.45],[128.8,59.4,99.0,161.4,0.0,0.0,-0.45],[128.6,60.0,99.0,161.6,0.0,0.0,-0.45],[128.4,60.0,99.0,161.0,0.0,0.0,-0.45],[128.0,58.9,99.0,159.3,0.0,0.0,-0.45],[127.6,57.4,99.0,157.2,0.0,0.0,-0.45],[127.6,56.3,99.0,156.2,0.0,0.0,-0.45],[127.8,55.9,99.0,156.3,0.0,0.0,-0.45],[128.0,56.0,99.0,156.9,0.0,0.0,-0.45],[128.1,56.3,99.0,157.4,0.0,0.0,-0.45],[128.2,56.7,99.0,157.9,0.0,0.0,-0.45],[128.2,57.3,99.0,158.3,0.0,0.0,-0.45],[128.1,58.0,99.0,158.8,0.0,0.0,-0.45],[128.1,58.6,99.0,159.2,0.0,0.0,-0.45],[128.1,59.2,99.0,159.6,0.0,0.0,-0.45],[128.1,59.6,99.0,160.0,0.0,0.0,-0.45],[128.2,60.0,99.0,160.3,0.0,0.0,-0.45],[128.3,60.3,99.0,160.6,0.0,0.0,-0.45],[128.4,60.6,99.0,160.9,0.0,0.0,-0.45],[128.5,60.8,99.0,161.2,0.0,0.0,-0.45],[128.5,61.0,99.0,161.5,0.0,0.0,-0.45],[128.6,61.2,99.0,161.7,0.0,0.0,-0.45],[128.6,61.4,99.0,161.9,0.0,0.0,-0.45],[128.6,61.6,99.0,162.0,0.0,0.0,-0.45],[128.6,61.9,99.0,162.2,0.0,0.0,-0.45],[128.6,62.1,99.0,162.3,0.0,0.0,-0.45],[128.6,62.2,99.0,162.4,0.0,0.0,-0.45],[128.6,62.3,99.0,162.5,0.0,0.0,-0.45],[128.6,62.4,99.0,162.5,0.0,0.0,-0.45],[128.6,62.3,99.0,162.3,0.0,0.0,-0.45],[128.3,61.3,99.0,161.0,0.0,0.0,-0.45],[127.9,59.6,99.0,158.9,0.0,0.0,-0.45],[127.7,58.2,99.0,157.4,0.0,0.0,-0.45],[127.7,57.7,99.0,157.0,0.0,0.0,-0.45],[128.2,59.0,99.0,159.1,0.0,0.0,-0.45],[128.5,60.2,99.0,160.8,0.0,0.0,-0.45],[128.6,61.3,99.0,161.9,0.0,0.0,-0.45],[128.6,62.2,99.0,162.5,0.0,0.0,-0.45],[128.5,62.7,99.0,162.7,0.0,0.0,-0.45],[128.3,62.7,99.0,162.1,0.0,0.0,-0.45],[127.9,61.5,99.0,160.4,0.0,0.0,-0.45],[127.6,59.8,99.0,158.3,0.0,0.0,-0.45],[127.6,58.6,99.0,157.2,0.0,0.0,-0.45],[127.9,58.6,99.0,158.0,0.0,0.0,-0.45],[128.4,59.6,99.0,159.9,0.0,0.0,-0.45],[128.7,60.6,99.0,161.3,0.0,0.0,-0.45],[128.7,61.6,99.0,162.2,0.0,0.0,-0.45],[128.6,62.3,99.0,162.7,0.0,0.0,-0.45],[128.5,62.7,99.0,162.6,0.0,0.0,-0.45],[128.2,62.1,99.0,161.5,0.0,0.0,-0.45],[127.8,60.7,99.0,159.4,0.0,0.0,-0.45],[127.5,59.1,99.0,157.6,0.0,0.0,-0.45],[127.6,58.1,99.0,157.0,0.0,0.0,-0.45],[127.8,57.6,99.0,157.0,0.0,0.0,-0.45],[127.9,57.2,99.0,157.0,0.0,0.0,-0.45],[127.9,57.1,99.0,157.0,0.0,0.0,-0.45],[127.8,57.1,99.0,157.0,0.0,0.0,-0.45],[127.8,57.2,99.0,156.9,0.0,0.0,-0.45],[127.7,57.3,99.0,156.9,0.0,0.0,-0.45],[127.6,57.4,99.0,156.9,0.0,0.0,-0.45],[127.6,57.4,99.0,156.8,0.0,0.0,-0.45],[127.6,57.4,99.0,156.8,0.0,0.0,-0.45],[127.6,57.3,99.0,156.8,0.0,0.0,-0.45],[127.6,57.1,99.0,156.7,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.7,0.0,0.0,-0.45],[127.7,56.7,99.0,156.6,0.0,0.0,-0.45],[127.7,56.6,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.5,0.0,0.0,-0.45],[127.7,56.3,99.0,156.4,0.0,0.0,-0.45],[127.7,56.3,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.3,0.0,0.0,-0.45]],"scrub":false},"work_run":{"n":144,"loop":true,"role":"rest","state":"working","events":{},"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.8,99.0,155.7,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.6,99.0,155.6,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.7,54.4,99.0,155.6,0.0,0.0,-0.45],[127.7,54.3,99.0,155.5,0.0,0.0,-0.45],[127.7,54.3,99.0,155.5,0.0,0.0,-0.45],[127.7,54.2,99.0,155.5,0.0,0.0,-0.45],[127.7,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.1,99.0,155.6,0.0,0.0,-0.45],[127.8,54.1,99.0,155.6,0.0,0.01,-0.45],[127.8,54.2,99.0,155.6,0.0,0.01,-0.45],[127.8,54.2,99.0,155.7,0.0,0.01,-0.45],[127.8,54.2,99.0,155.8,0.0,0.01,-0.45],[127.9,54.2,99.0,155.8,0.0,0.01,-0.45],[127.9,54.3,99.0,155.9,0.0,0.01,-0.45],[127.9,54.3,99.0,156.0,0.0,0.02,-0.45],[127.9,54.4,99.0,156.1,0.0,0.02,-0.45],[128.0,54.4,99.0,156.2,0.0,0.02,-0.45],[128.0,54.5,99.0,156.3,0.0,0.02,-0.45],[128.1,54.6,99.0,156.4,0.0,0.03,-0.45],[128.1,54.6,99.0,156.6,0.0,0.03,-0.45],[128.1,54.7,99.0,156.7,0.0,0.03,-0.45],[128.2,54.7,99.0,156.8,0.0,0.04,-0.45],[128.2,54.8,99.0,157.0,0.0,0.04,-0.45],[128.3,54.9,99.0,157.1,0.0,0.05,-0.45],[128.3,54.9,99.0,157.3,0.0,0.05,-0.45],[128.4,55.0,99.0,157.4,0.0,0.05,-0.45],[128.4,55.0,99.0,157.6,0.0,0.06,-0.45],[128.5,55.1,99.0,157.7,0.0,0.06,-0.45],[128.5,55.1,99.0,157.9,0.0,0.07,-0.45],[128.6,55.1,99.0,158.0,0.0,0.07,-0.45],[128.7,55.1,99.0,158.2,0.0,0.08,-0.45],[128.7,55.1,99.0,158.3,0.0,0.08,-0.45],[128.8,55.1,99.0,158.5,0.0,0.09,-0.45],[128.9,55.1,99.0,158.6,0.0,0.09,-0.45],[128.9,55.1,99.0,158.8,0.0,0.1,-0.45],[129.0,55.0,99.0,158.9,0.0,0.1,-0.45],[129.0,55.0,99.0,159.0,0.0,0.1,-0.45],[129.1,54.9,99.0,159.2,0.0,0.11,-0.45],[129.1,54.8,99.0,159.3,0.0,0.11,-0.45],[129.2,54.7,99.0,159.4,0.0,0.12,-0.45],[129.3,54.6,99.0,159.5,0.0,0.12,-0.45],[129.3,54.5,99.0,159.6,0.0,0.13,-0.45],[129.4,54.4,99.0,159.7,0.0,0.13,-0.45],[129.5,54.2,99.0,159.8,0.0,0.14,-0.45],[129.5,54.1,99.0,159.8,0.0,0.14,-0.45],[129.6,53.9,99.0,159.9,0.0,0.15,-0.45],[129.7,53.7,99.0,160.0,0.0,0.15,-0.45],[129.7,53.5,99.0,160.0,0.0,0.15,-0.45],[129.8,53.3,99.0,160.1,0.0,0.16,-0.45],[129.8,53.1,99.0,160.1,0.0,0.16,-0.45],[129.9,52.9,99.0,160.1,0.0,0.17,-0.45],[129.9,52.7,99.0,160.1,0.0,0.17,-0.45],[130.0,52.5,99.0,160.1,0.0,0.17,-0.45],[130.0,52.2,99.0,160.1,0.0,0.18,-0.45],[130.1,52.0,99.0,160.1,0.0,0.18,-0.45],[130.1,51.8,99.0,160.1,0.0,0.18,-0.45],[130.1,51.5,99.0,160.1,0.0,0.18,-0.45],[130.2,51.3,99.0,160.1,0.0,0.19,-0.45],[130.2,51.1,99.0,160.0,0.0,0.19,-0.45],[130.2,50.8,99.0,160.0,0.0,0.19,-0.45],[130.3,50.6,99.0,160.0,0.0,0.19,-0.45],[130.3,50.4,99.0,159.9,0.0,0.19,-0.45],[130.3,50.2,99.0,159.9,0.0,0.19,-0.45],[130.3,50.0,99.0,159.8,0.0,0.2,-0.45],[130.3,49.8,99.0,159.8,0.0,0.2,-0.45],[130.4,49.6,99.0,159.7,0.0,0.2,-0.45],[130.4,49.5,99.0,159.7,0.0,0.2,-0.45],[130.4,49.3,99.0,159.6,0.0,0.2,-0.45],[130.4,49.2,99.0,159.6,0.0,0.2,-0.45],[130.4,49.0,99.0,159.5,0.0,0.2,-0.45],[130.4,48.9,99.0,159.5,0.0,0.2,-0.45],[130.4,48.8,99.0,159.4,0.0,0.2,-0.45],[130.4,48.8,99.0,159.4,0.0,0.2,-0.45],[130.4,48.7,99.0,159.4,0.0,0.2,-0.45],[130.4,48.6,99.0,159.4,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.7,99.0,159.3,0.0,0.2,-0.45],[130.4,48.7,99.0,159.3,0.0,0.2,-0.45],[130.4,48.8,99.0,159.2,0.0,0.2,-0.45],[130.4,48.8,99.0,159.2,0.0,0.2,-0.45],[130.3,48.9,99.0,159.2,0.0,0.2,-0.45],[130.3,49.0,99.0,159.2,0.0,0.2,-0.45],[130.3,49.1,99.0,159.1,0.0,0.2,-0.45],[130.3,49.2,99.0,159.1,0.0,0.2,-0.45],[130.3,49.4,99.0,159.1,0.0,0.2,-0.45],[130.3,49.5,99.0,159.1,0.0,0.2,-0.45],[130.2,49.6,99.0,159.0,0.0,0.2,-0.45],[130.2,49.8,99.0,159.0,0.0,0.2,-0.45],[130.2,49.9,99.0,158.9,0.0,0.2,-0.45],[130.2,50.1,99.0,158.9,0.0,0.2,-0.45],[130.1,50.2,99.0,158.9,0.0,0.2,-0.45],[130.1,50.4,99.0,158.8,0.0,0.2,-0.45],[130.1,50.5,99.0,158.8,0.0,0.2,-0.45],[129.2,53.0,99.0,158.2,0.0,0.13,-0.45],[128.3,55.6,99.0,157.7,0.0,0.04,-0.45],[127.8,57.1,99.0,157.3,0.0,-0.0,-0.45],[127.6,57.7,99.0,157.2,0.0,-0.02,-0.45],[127.5,57.8,99.0,157.2,0.0,-0.02,-0.45],[127.6,57.7,99.0,157.2,0.0,-0.01,-0.45],[127.7,57.5,99.0,157.2,0.0,-0.0,-0.45],[127.7,57.5,99.0,157.2,0.0,0.0,-0.45],[127.7,57.6,99.0,157.2,0.0,0.0,-0.45],[127.7,57.7,99.0,157.2,0.0,0.0,-0.45],[127.7,57.7,99.0,157.2,0.0,0.0,-0.45],[127.7,57.8,99.0,157.2,0.0,0.0,-0.45],[127.7,57.8,99.0,157.2,0.0,0.0,-0.45],[127.7,57.9,99.0,157.2,0.0,0.0,-0.45],[127.7,57.9,99.0,157.2,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.6,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.7,99.0,157.1,0.0,0.0,-0.45],[127.7,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,156.9,0.0,0.0,-0.45],[127.7,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.2,99.0,156.8,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.7,0.0,0.0,-0.45],[127.7,56.7,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.4,0.0,0.0,-0.45]],"scrub":false},"work_search":{"n":144,"loop":true,"role":"rest","state":"working","events":{},"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.8,99.0,155.7,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.4,54.4,98.8,155.6,0.0,0.0,-0.45],[126.9,54.1,98.4,155.6,0.1,0.0,-0.45],[126.2,53.9,97.9,155.5,0.0,0.0,-0.45],[125.3,53.5,97.1,155.5,0.0,0.0,-0.45],[124.1,53.2,96.1,155.4,0.1,0.0,-0.45],[122.8,52.9,94.8,155.4,0.1,0.0,-0.45],[121.3,52.6,93.5,155.4,0.1,0.0,-0.45],[119.9,52.4,92.0,155.5,0.3,0.0,-0.45],[118.7,52.2,90.3,155.4,0.4,0.0,-0.45],[117.3,52.1,88.8,155.4,0.4,0.0,-0.45],[116.1,52.2,87.3,155.5,0.6,0.0,-0.45],[115.0,52.2,85.8,155.5,0.6,0.0,-0.45],[113.9,52.4,84.6,155.5,0.6,0.0,-0.45],[113.2,52.6,83.5,155.6,0.7,0.0,-0.45],[112.6,52.9,82.5,155.6,0.7,0.0,-0.45],[112.3,53.2,81.8,155.7,0.7,0.0,-0.45],[112.2,53.5,81.4,155.7,0.7,0.0,-0.45],[112.2,53.8,81.1,155.7,0.9,0.0,-0.45],[112.4,54.0,81.0,155.8,0.7,0.0,-0.45],[112.2,54.3,80.9,155.8,0.7,0.0,-0.45],[112.3,54.4,80.9,155.9,0.9,0.0,-0.45],[112.2,54.5,80.9,155.9,0.7,0.0,-0.45],[112.2,54.5,81.0,156.1,0.7,0.0,-0.45],[111.9,54.6,81.0,156.1,0.9,0.0,-0.45],[111.7,54.6,81.0,156.2,0.9,0.0,-0.45],[111.5,54.7,81.0,156.2,0.7,0.0,-0.45],[111.4,54.8,81.0,156.3,0.9,0.0,-0.45],[111.3,54.9,80.9,156.4,0.9,0.0,-0.45],[111.2,55.0,80.9,156.5,0.9,0.0,-0.45],[111.2,55.2,80.9,156.5,0.9,0.0,-0.45],[111.3,55.3,80.9,156.6,0.9,0.0,-0.45],[111.3,55.5,80.9,156.7,0.7,0.0,-0.45],[111.4,55.7,80.9,156.7,0.9,0.0,-0.45],[111.4,55.8,80.9,156.8,0.9,0.0,-0.45],[111.5,55.9,80.9,156.8,0.9,0.0,-0.45],[111.6,56.1,80.9,156.9,0.9,0.0,-0.45],[111.5,56.1,80.9,156.9,0.9,0.0,-0.45],[111.5,56.2,80.9,156.9,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.6,56.4,80.9,157.0,0.9,0.0,-0.45],[111.5,56.4,80.9,157.0,0.9,0.0,-0.45],[111.5,56.4,80.9,157.0,0.9,0.0,-0.45],[111.5,56.4,80.9,157.0,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.6,56.2,81.0,156.9,0.9,0.0,-0.45],[112.1,56.3,81.3,156.9,0.9,0.0,-0.45],[113.1,56.4,82.0,156.9,0.9,0.0,-0.45],[114.7,56.7,83.0,156.8,0.7,0.0,-0.45],[116.8,57.1,84.5,156.8,0.6,0.0,-0.45],[119.4,57.5,86.4,156.8,0.6,0.0,-0.45],[122.3,57.9,88.8,156.8,0.4,0.0,-0.45],[120.5,58.4,91.5,156.7,0.3,0.0,-0.45],[118.8,58.7,94.5,156.6,0.1,0.0,-0.45],[119.5,59.0,97.7,156.6,0.0,0.0,-0.45],[121.1,59.2,100.9,156.6,-0.1,0.0,-0.45],[122.3,59.2,104.1,156.4,-0.1,0.0,-0.45],[123.9,59.1,107.0,156.3,-0.4,0.0,-0.45],[125.7,58.9,109.7,156.2,-0.4,0.0,-0.45],[127.3,58.6,112.0,156.2,-0.6,0.0,-0.45],[128.8,58.2,113.8,156.1,-0.7,0.0,-0.45],[130.1,57.8,115.2,155.9,-0.7,0.0,-0.45],[132.5,57.3,116.2,155.9,-0.9,0.0,-0.45],[135.6,56.9,116.8,155.8,-0.7,0.0,-0.45],[135.5,56.5,117.0,155.8,-0.7,0.0,-0.45],[136.7,56.2,117.1,155.7,-0.9,0.0,-0.45],[136.8,56.1,117.1,155.7,-0.7,0.0,-0.45],[135.6,56.1,117.1,155.6,-0.9,0.0,-0.45],[136.0,56.2,117.1,155.6,-0.7,0.0,-0.45],[133.7,56.4,117.1,155.5,-0.9,0.0,-0.45],[131.9,56.6,117.1,155.4,-0.7,0.0,-0.45],[130.8,56.7,117.1,155.4,-0.7,0.0,-0.45],[130.8,56.8,117.1,155.4,-0.9,0.0,-0.45],[130.6,56.9,117.1,155.4,-0.9,0.0,-0.45],[130.7,56.9,117.1,155.3,-0.7,0.0,-0.45],[130.3,56.9,117.1,155.3,-0.7,0.0,-0.45],[130.8,56.8,117.1,155.3,-0.7,0.0,-0.45],[131.0,56.8,117.1,155.3,-0.7,0.0,-0.45],[130.7,56.7,117.1,155.3,-0.7,0.0,-0.45],[130.8,56.7,117.1,155.4,-0.9,0.0,-0.45],[131.1,56.7,117.1,155.4,-0.9,0.0,-0.45],[131.1,56.7,117.1,155.4,-0.7,0.0,-0.45],[131.0,56.8,117.1,155.4,-0.7,0.0,-0.45],[131.0,56.8,117.1,155.5,-0.9,0.0,-0.45],[131.2,56.9,117.1,155.6,-0.7,0.0,-0.45],[131.0,57.0,117.1,155.6,-0.9,0.0,-0.45],[131.1,57.2,117.1,155.7,-0.7,0.0,-0.45],[131.1,57.3,117.1,155.7,-0.9,0.0,-0.45],[130.9,57.5,117.1,155.8,-0.7,0.0,-0.45],[131.0,57.7,117.1,155.8,-0.7,0.0,-0.45],[128.0,53.1,107.9,156.0,-0.3,0.0,-0.45],[121.3,51.5,101.8,156.1,-0.1,0.0,-0.45],[120.7,52.0,99.5,156.2,0.0,0.0,-0.45],[123.1,53.3,99.0,156.2,0.0,0.0,-0.45],[125.8,54.9,99.0,156.3,0.0,0.0,-0.45],[128.3,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,57.5,99.0,156.4,0.0,0.0,-0.45],[122.6,58.3,99.0,156.5,0.0,0.0,-0.45],[121.9,58.6,99.0,156.6,0.0,0.0,-0.45],[122.2,58.6,99.0,156.7,0.0,0.0,-0.45],[124.2,58.4,99.0,156.7,0.0,0.0,-0.45],[127.2,58.1,99.0,156.8,0.0,0.0,-0.45],[128.8,57.8,99.0,156.8,0.0,0.0,-0.45],[128.0,57.6,99.0,156.9,0.0,0.0,-0.45],[127.5,57.4,99.0,156.9,0.0,0.0,-0.45],[127.1,57.3,99.0,157.0,0.0,0.0,-0.45],[126.9,57.2,99.0,157.0,0.0,0.0,-0.45],[126.9,57.3,99.0,157.1,0.0,0.0,-0.45],[126.9,57.4,99.0,157.1,0.0,0.0,-0.45],[127.1,57.5,99.0,157.1,0.0,0.0,-0.45],[127.3,57.6,99.0,157.1,0.0,0.0,-0.45],[127.4,57.7,99.0,157.1,0.0,0.0,-0.45],[127.6,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.8,57.9,99.0,157.1,0.0,0.0,-0.45],[127.8,57.9,99.0,157.1,0.0,0.0,-0.45],[127.8,57.9,99.0,157.1,0.0,0.0,-0.45],[127.8,57.8,99.0,157.1,0.0,0.0,-0.45],[127.8,57.7,99.0,157.0,0.0,0.0,-0.45],[127.8,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,156.9,0.0,0.0,-0.45],[127.7,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.2,99.0,156.8,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.7,0.0,0.0,-0.45],[127.7,56.7,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.4,0.0,0.0,-0.45]],"scrub":false},"work_nod":{"n":58,"loop":false,"role":"beat","state":"working","events":{},"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.1,0.0,0.0,-0.45],[127.7,55.5,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.8,99.0,155.7,0.0,0.0,-0.45],[127.7,54.6,99.0,155.7,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.7,54.4,99.0,155.6,0.0,0.0,-0.45],[127.8,54.4,99.0,155.8,0.0,0.0,-0.45],[127.9,54.6,99.0,156.5,0.0,0.0,-0.45],[128.0,54.9,99.0,157.8,0.0,0.0,-0.45],[128.2,55.4,99.0,159.4,0.0,0.0,-0.45],[128.5,56.0,99.0,161.0,0.0,0.0,-0.45],[128.7,56.6,99.0,162.2,0.0,0.0,-0.45],[128.9,57.1,99.0,162.8,0.0,0.0,-0.45],[129.1,57.4,99.0,162.9,0.0,0.0,-0.45],[129.1,57.6,99.0,162.7,0.0,0.0,-0.45],[129.1,57.2,99.0,161.6,0.0,0.0,-0.45],[128.8,56.3,99.0,159.4,0.0,0.0,-0.45],[128.4,55.3,99.0,156.9,0.0,0.0,-0.45],[127.9,54.6,99.0,154.8,0.0,0.0,-0.45],[127.6,54.5,99.0,153.5,0.0,0.0,-0.45],[127.2,55.1,99.0,153.3,0.0,0.0,-0.45],[127.0,55.7,99.0,153.4,0.0,0.0,-0.45],[127.0,56.4,99.0,153.9,0.0,0.0,-0.45],[127.0,56.8,99.0,155.0,0.0,0.0,-0.45],[127.2,57.1,99.0,156.3,0.0,0.0,-0.45],[127.5,57.3,99.0,157.7,0.0,0.0,-0.45],[127.8,57.4,99.0,158.6,0.0,0.0,-0.45],[128.1,57.4,99.0,159.1,0.0,0.0,-0.45],[128.2,57.6,99.0,159.3,0.0,0.0,-0.45],[128.3,57.8,99.0,159.3,0.0,0.0,-0.45],[128.3,57.9,99.0,159.1,0.0,0.0,-0.45],[128.2,57.9,99.0,158.6,0.0,0.0,-0.45],[128.1,57.7,99.0,158.0,0.0,0.0,-0.45],[127.9,57.6,99.0,157.5,0.0,0.0,-0.45],[127.8,57.7,99.0,157.2,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.6,57.9,99.0,157.1,0.0,0.0,-0.45],[127.5,58.1,99.0,157.1,0.0,0.0,-0.45],[127.5,58.1,99.0,157.1,0.0,0.0,-0.45],[127.5,58.1,99.0,157.1,0.0,0.0,-0.45],[127.6,58.0,99.0,157.1,0.0,0.0,-0.45],[127.6,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.7,99.0,157.1,0.0,0.0,-0.45],[127.7,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,157.0,0.0,0.0,-0.45],[127.7,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.2,99.0,156.9,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,56.9,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.6,0.0,0.0,-0.45],[127.7,56.6,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.4,0.0,0.0,-0.45]],"scrub":false},"work_squint":{"n":72,"loop":false,"role":"beat","state":"working","events":{},"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.5,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.6,99.0,155.7,0.0,0.0,-0.45],[127.7,54.5,99.0,155.7,0.0,0.0,-0.45],[127.8,54.2,99.0,155.8,0.0,0.01,-0.45],[128.0,53.8,99.0,156.0,0.0,0.02,-0.45],[128.3,53.1,99.0,156.3,0.0,0.05,-0.45],[128.6,52.3,99.0,156.8,0.0,0.07,-0.45],[129.1,51.4,99.0,157.4,0.0,0.11,-0.45],[129.5,50.4,99.0,158.1,0.0,0.14,-0.45],[130.0,49.4,99.0,158.8,0.0,0.17,-0.45],[130.5,48.4,99.0,159.4,0.0,0.21,-0.45],[130.9,47.7,99.0,160.0,0.0,0.23,-0.45],[131.2,47.1,99.0,160.4,0.0,0.25,-0.45],[131.4,46.8,99.0,160.7,0.0,0.26,-0.45],[131.5,46.7,99.0,160.9,0.0,0.27,-0.45],[131.5,46.8,99.0,160.9,0.0,0.27,-0.45],[131.5,46.9,99.0,161.0,0.0,0.27,-0.45],[131.5,47.0,99.0,161.0,0.0,0.27,-0.45],[131.5,47.1,99.0,161.1,0.0,0.27,-0.45],[131.5,47.3,99.0,161.1,0.0,0.27,-0.45],[131.4,47.4,99.0,161.2,0.0,0.27,-0.45],[131.4,47.6,99.0,161.2,0.0,0.27,-0.45],[131.4,47.7,99.0,161.3,0.0,0.27,-0.45],[131.4,47.9,99.0,161.4,0.0,0.27,-0.45],[131.4,48.1,99.0,161.5,0.0,0.27,-0.45],[131.4,48.2,99.0,161.5,0.0,0.27,-0.45],[131.4,48.4,99.0,161.6,0.0,0.27,-0.45],[131.4,48.6,99.0,161.7,0.0,0.27,-0.45],[131.4,48.8,99.0,161.8,0.0,0.27,-0.45],[131.4,48.9,99.0,161.9,0.0,0.27,-0.45],[131.4,49.1,99.0,161.9,0.0,0.27,-0.45],[131.4,49.3,99.0,162.0,0.0,0.27,-0.45],[131.4,49.5,99.0,162.1,0.0,0.27,-0.45],[131.4,49.6,99.0,162.1,0.0,0.27,-0.45],[131.4,49.8,99.0,162.2,0.0,0.27,-0.45],[131.4,49.9,99.0,162.3,0.0,0.27,-0.45],[131.4,50.0,99.0,162.3,0.0,0.27,-0.45],[131.4,50.2,99.0,162.4,0.0,0.27,-0.45],[131.4,50.3,99.0,162.4,0.0,0.27,-0.45],[131.4,50.4,99.0,162.5,0.0,0.27,-0.45],[131.4,50.4,99.0,162.5,0.0,0.27,-0.45],[131.4,50.5,99.0,162.5,0.0,0.27,-0.45],[131.4,50.6,99.0,162.5,0.0,0.27,-0.45],[131.1,51.2,99.0,162.1,0.0,0.25,-0.45],[130.4,52.6,99.0,161.1,0.0,0.2,-0.45],[129.5,54.4,99.0,159.7,0.0,0.13,-0.45],[128.6,56.1,99.0,158.4,0.0,0.07,-0.45],[128.0,57.3,99.0,157.5,0.0,0.02,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.6,57.8,99.0,157.1,0.0,0.0,-0.45],[127.6,57.8,99.0,157.1,0.0,0.0,-0.45],[127.6,57.7,99.0,157.0,0.0,0.0,-0.45],[127.6,57.7,99.0,157.0,0.0,0.0,-0.45],[127.6,57.5,99.0,156.9,0.0,0.0,-0.45],[127.6,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.3,99.0,156.8,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.7,0.0,0.0,-0.45],[127.7,56.7,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.4,0.0,0.0,-0.45]],"scrub":false},"work_ponder":{"n":77,"loop":false,"role":"beat","state":"working","events":{},"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.1,0.0,0.0,-0.45],[127.7,55.5,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.2,99.0,155.9,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.8,99.0,155.7,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.8,54.6,99.1,155.5,0.0,0.0,-0.45],[127.9,54.4,99.5,154.9,-0.3,0.0,-0.45],[128.0,54.2,100.2,153.8,-0.4,0.0,-0.45],[127.9,54.1,101.0,152.2,-0.7,0.0,-0.45],[127.4,54.0,102.1,150.4,-1.1,0.0,-0.45],[126.4,54.2,103.1,148.4,-1.5,0.0,-0.45],[124.8,54.7,104.0,146.7,-1.7,0.0,-0.45],[121.5,55.7,104.7,145.2,-1.9,0.0,-0.45],[119.0,56.9,105.2,144.2,-2.1,0.0,-0.45],[113.6,58.2,105.4,143.6,-2.1,0.0,-0.45],[111.0,59.1,105.5,143.4,-2.3,0.0,-0.45],[109.3,59.6,105.5,143.4,-2.3,0.0,-0.45],[109.3,59.7,105.5,143.4,-2.3,0.0,-0.45],[109.8,59.5,105.5,143.4,-2.1,0.0,-0.45],[111.3,59.1,105.5,143.4,-2.1,0.0,-0.45],[112.5,58.7,105.6,143.5,-2.3,0.0,-0.45],[114.4,58.3,105.6,143.6,-2.1,0.0,-0.45],[116.0,58.0,105.6,143.6,-2.3,0.0,-0.45],[117.1,57.9,105.6,143.7,-2.1,0.0,-0.45],[116.7,58.0,105.6,143.7,-2.3,0.0,-0.45],[116.4,58.2,105.6,143.8,-2.1,0.0,-0.45],[116.0,58.4,105.6,143.8,-2.3,0.0,-0.45],[115.3,58.7,105.6,143.8,-2.1,0.0,-0.45],[114.7,59.0,105.6,143.9,-2.1,0.0,-0.45],[113.8,59.3,105.6,144.0,-2.3,0.0,-0.45],[113.6,59.5,105.6,144.1,-2.3,0.0,-0.45],[113.7,59.6,105.6,144.2,-2.1,0.0,-0.45],[113.8,59.7,105.6,144.2,-2.3,0.0,-0.45],[114.0,59.8,105.5,144.3,-2.2,0.0,-0.45],[114.1,59.9,105.5,144.4,-2.2,0.0,-0.45],[114.0,60.0,105.5,144.4,-2.1,0.0,-0.45],[114.0,60.1,105.5,144.5,-2.2,0.0,-0.45],[114.3,60.2,105.5,144.6,-2.2,0.0,-0.45],[114.6,60.3,105.5,144.7,-2.1,0.0,-0.45],[114.6,60.4,105.5,144.8,-2.2,0.0,-0.45],[114.4,60.5,105.5,145.1,-2.1,0.0,-0.45],[114.9,60.5,105.2,145.4,-2.1,0.0,-0.45],[115.8,60.4,105.1,146.1,-2.1,0.0,-0.45],[117.1,60.2,104.8,146.8,-1.9,0.0,-0.45],[118.8,59.8,104.3,147.7,-1.9,0.0,-0.45],[120.9,59.4,103.8,148.8,-1.8,0.0,-0.45],[121.8,58.9,103.2,149.9,-1.5,0.0,-0.45],[124.4,58.4,102.5,151.1,-1.3,0.0,-0.45],[125.4,58.0,101.9,152.3,-1.1,0.0,-0.45],[126.1,57.8,101.2,153.4,-0.9,0.0,-0.45],[126.9,57.7,100.7,154.5,-0.5,0.0,-0.45],[127.3,57.7,100.1,155.4,-0.5,0.0,-0.45],[127.7,57.7,99.7,156.1,-0.3,0.0,-0.45],[128.0,57.8,99.3,156.6,-0.1,0.0,-0.45],[128.1,57.9,99.1,156.9,0.0,0.0,-0.45],[128.1,57.9,99.0,157.1,0.0,0.0,-0.45],[128.2,57.8,99.0,157.1,0.0,0.0,-0.45],[128.0,57.8,99.0,157.1,0.0,0.0,-0.45],[127.9,57.7,99.0,157.0,0.0,0.0,-0.45],[127.8,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,156.9,0.0,0.0,-0.45],[127.6,57.4,99.0,156.9,0.0,0.0,-0.45],[127.5,57.3,99.0,156.9,0.0,0.0,-0.45],[127.5,57.1,99.0,156.8,0.0,0.0,-0.45],[127.5,57.0,99.0,156.7,0.0,0.0,-0.45],[127.6,56.9,99.0,156.7,0.0,0.0,-0.45],[127.6,56.8,99.0,156.6,0.0,0.0,-0.45],[127.7,56.6,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.8,56.3,99.0,156.4,0.0,0.0,-0.45],[127.8,56.2,99.0,156.4,0.0,0.0,-0.45]],"scrub":false},"work_blink":{"n":38,"loop":false,"role":"beat","state":"working","events":{},"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.7,54.3,99.0,155.6,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.7,54.2,99.0,155.5,0.0,0.0,-0.45],[127.7,54.3,99.0,155.5,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.7,99.0,156.1,0.0,0.0,-0.45],[127.7,56.0,99.0,156.3,0.0,0.0,-0.45],[127.7,56.3,99.0,156.4,0.0,0.0,-0.45],[127.7,56.6,99.0,156.5,0.0,0.0,-0.45],[127.7,56.9,99.0,156.7,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.7,99.0,157.0,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.7,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,156.9,0.0,0.0,-0.45],[127.7,57.3,99.0,156.9,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45]],"scrub":false},"bump":{"n":24,"loop":false,"role":"react","state":"working","events":{"land":6,"launch":10},"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.6,55.8,99.0,155.5,0.0,0.0,-0.45],[127.4,55.2,99.0,152.4,0.0,0.0,-0.45],[127.0,55.1,99.0,148.9,0.0,0.0,-0.45],[126.5,55.7,99.0,147.5,0.0,0.0,-0.45],[126.3,68.7,99.0,160.7,0.0,0.0,-0.48],[124.2,84.3,99.0,173.9,0.0,0.0,-0.51],[124.4,91.8,99.0,179.3,0.0,0.0,-0.52],[122.8,70.1,99.0,156.4,0.0,0.0,-0.44],[123.9,46.2,99.0,135.9,0.0,0.0,-0.37],[123.7,33.5,99.0,124.4,0.0,0.0,-0.33],[123.9,29.8,99.0,121.7,0.0,0.0,-0.32],[127.3,26.7,99.0,124.1,0.0,0.0,-0.33],[117.5,38.2,99.0,131.6,0.0,0.0,-0.37],[111.7,51.4,99.0,140.7,0.0,0.0,-0.42],[110.8,58.2,99.0,146.2,0.0,0.0,-0.45],[113.5,59.7,99.0,148.2,0.0,0.0,-0.45],[113.0,65.2,99.0,150.0,0.0,0.0,-0.45],[115.6,67.2,99.0,151.8,0.0,0.0,-0.45],[122.4,65.1,99.0,153.4,0.0,0.0,-0.45],[123.3,63.8,99.0,154.6,0.0,0.0,-0.45],[125.0,61.8,99.0,155.5,0.0,0.0,-0.45],[126.9,58.3,99.0,156.1,0.0,0.0,-0.45],[128.6,55.3,99.0,156.3,0.0,0.0,-0.45]],"scrub":false},"oops":{"n":26,"loop":false,"role":"react","state":"working","events":{},"frames":[[127.8,56.6,99.0,156.3,0.0,0.0,-0.45],[113.7,68.6,83.2,173.6,1.3,0.02,-0.45],[105.6,75.2,79.5,177.4,1.8,0.04,-0.45],[105.1,80.2,79.2,177.8,1.8,0.06,-0.45],[106.4,84.3,79.8,177.4,1.7,0.07,-0.45],[111.2,85.1,82.7,175.1,1.3,0.08,-0.45],[104.9,81.2,87.7,171.0,0.8,0.09,-0.45],[106.7,73.6,93.2,166.4,0.4,0.09,-0.45],[110.1,64.8,97.2,162.9,0.1,0.1,-0.45],[115.5,57.4,98.8,161.2,0.0,0.1,-0.45],[125.3,50.6,99.0,160.7,0.0,0.1,-0.45],[133.9,45.7,99.0,160.2,0.0,0.1,-0.45],[130.6,43.7,99.0,159.8,0.0,0.1,-0.45],[128.2,44.1,99.0,159.3,0.0,0.1,-0.45],[126.5,45.9,99.0,158.8,0.0,0.1,-0.45],[125.5,48.3,99.0,158.4,0.0,0.1,-0.45],[125.3,50.5,99.0,158.1,0.0,0.1,-0.45],[125.7,52.2,99.0,157.7,0.0,0.1,-0.45],[126.5,53.2,99.0,157.4,0.0,0.09,-0.45],[127.3,53.8,99.0,157.1,0.0,0.08,-0.45],[128.0,54.2,99.0,156.9,0.0,0.06,-0.45],[128.5,54.4,99.0,156.7,0.0,0.04,-0.45],[128.9,54.7,99.0,156.5,0.0,0.03,-0.45],[129.1,55.1,99.0,156.4,0.0,0.02,-0.45],[128.9,55.5,99.0,156.4,0.0,0.01,-0.45],[128.5,55.8,99.0,156.3,0.0,0.0,-0.45]],"scrub":false},"interrupted":{"n":29,"loop":false,"role":"react","state":"working","events":{},"frames":[[127.8,55.8,99.0,156.3,0.0,0.0,-0.45],[121.3,45.8,99.0,129.1,0.0,-0.09,-0.45],[122.0,42.2,99.0,127.8,0.0,-0.1,-0.45],[122.2,41.2,99.0,127.8,0.0,-0.1,-0.45],[112.3,43.3,99.0,127.8,0.0,-0.1,-0.45],[109.5,43.2,99.0,127.8,0.0,-0.1,-0.45],[108.4,44.0,99.0,127.8,0.0,-0.1,-0.45],[108.3,44.9,99.0,127.8,0.0,-0.1,-0.45],[108.1,45.5,99.0,127.8,0.0,-0.1,-0.45],[111.0,46.0,99.0,127.8,0.0,-0.1,-0.45],[112.4,46.4,99.0,127.8,0.0,-0.1,-0.45],[112.8,45.8,99.0,127.8,0.0,-0.1,-0.45],[114.5,44.7,99.0,127.8,0.0,-0.1,-0.45],[116.3,43.8,99.0,127.8,0.0,-0.1,-0.45],[116.7,43.2,99.0,127.8,0.0,-0.1,-0.45],[116.5,42.9,99.0,127.7,0.0,-0.1,-0.44],[115.6,42.9,98.9,127.5,0.0,-0.1,-0.43],[114.4,43.1,98.8,127.1,0.0,-0.09,-0.41],[113.7,43.3,98.5,126.6,0.0,-0.08,-0.37],[112.8,43.4,98.3,126.0,0.0,-0.07,-0.33],[112.8,43.1,98.0,125.2,0.0,-0.06,-0.28],[113.1,42.5,97.7,124.4,0.0,-0.05,-0.23],[114.4,41.6,97.4,123.5,0.0,-0.04,-0.17],[115.4,40.5,97.1,122.7,0.0,-0.03,-0.12],[116.8,39.5,96.8,122.0,0.0,-0.02,-0.08],[119.1,38.5,96.5,121.5,-0.1,-0.01,-0.04],[120.7,37.7,96.4,121.0,-0.1,-0.0,-0.02],[122.1,37.2,96.2,120.8,-0.1,-0.0,-0.01],[124.2,36.9,96.2,120.7,-0.3,-0.0,-0.0]],"scrub":false},"subagents_in":{"n":58,"loop":false,"role":"enter","state":"subagents","events":{},"frames":[[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.8,96.3,120.7,-0.1,-0.0,0.0],[120.8,37.9,97.1,120.3,-0.1,-0.02,0.01],[121.9,38.2,98.6,119.7,-0.1,-0.05,0.03],[122.3,38.6,100.7,118.7,-0.3,-0.09,0.05],[124.3,38.8,103.0,117.7,-0.1,-0.14,0.08],[125.9,39.0,105.2,116.7,-0.1,-0.19,0.11],[127.2,39.0,106.9,115.9,-0.3,-0.23,0.13],[127.8,38.9,108.0,115.5,-0.2,-0.26,0.14],[128.0,38.7,108.3,115.2,-0.2,-0.27,0.15],[128.2,37.8,108.3,114.8,-0.2,-0.27,0.15],[128.1,36.1,108.3,113.5,-0.2,-0.27,0.15],[128.1,34.5,108.3,112.5,-0.3,-0.27,0.15],[127.9,33.1,108.3,111.6,-0.3,-0.27,0.15],[127.9,31.7,108.3,110.8,-0.3,-0.27,0.15],[128.7,30.4,108.3,110.2,-0.2,-0.27,0.15],[127.9,29.4,108.3,109.6,-0.3,-0.27,0.15],[128.4,28.5,108.3,109.1,-0.3,-0.27,0.15],[128.4,27.8,108.3,108.8,-0.3,-0.27,0.15],[128.9,27.2,108.3,108.5,-0.2,-0.27,0.15],[128.4,26.9,108.3,108.2,-0.3,-0.27,0.15],[128.8,26.6,108.4,108.0,-0.3,-0.27,0.15],[128.8,26.4,108.4,107.9,-0.3,-0.27,0.15],[128.7,26.3,108.4,107.8,-0.2,-0.27,0.15],[128.7,26.2,108.3,107.7,-0.3,-0.27,0.15],[128.7,26.1,108.3,107.6,-0.3,-0.27,0.15],[128.5,26.1,108.3,107.6,-0.3,-0.27,0.15],[128.7,26.0,108.3,107.6,-0.3,-0.27,0.15],[128.4,26.0,108.3,107.5,-0.3,-0.27,0.15],[128.7,25.9,108.3,107.5,-0.3,-0.27,0.15],[128.7,25.9,108.3,107.5,-0.3,-0.27,0.15],[128.7,25.9,108.3,107.5,-0.3,-0.27,0.15],[128.7,25.9,108.3,107.5,-0.3,-0.27,0.15],[128.7,26.0,108.3,107.6,-0.3,-0.27,0.15],[128.8,26.5,108.4,107.9,-0.3,-0.27,0.15],[128.4,27.9,108.4,108.9,-0.3,-0.27,0.15],[128.7,30.1,108.3,110.4,-0.3,-0.27,0.15],[128.2,32.9,108.3,112.1,-0.3,-0.27,0.15],[128.3,35.6,108.3,113.7,-0.2,-0.27,0.15],[128.2,37.9,108.3,114.8,-0.2,-0.27,0.15],[128.4,39.2,108.3,115.2,-0.3,-0.27,0.15],[127.9,39.8,108.3,115.2,-0.2,-0.27,0.15],[127.6,40.0,108.3,115.2,-0.2,-0.27,0.15],[127.7,39.9,108.3,115.2,-0.2,-0.27,0.15],[127.8,39.6,108.3,115.2,-0.2,-0.27,0.15],[128.0,39.2,108.3,115.2,-0.2,-0.27,0.15],[128.3,38.9,108.3,115.2,-0.2,-0.27,0.15],[128.3,38.7,108.3,115.2,-0.2,-0.27,0.15],[128.4,38.6,108.3,115.2,-0.2,-0.27,0.15],[128.3,38.7,108.3,115.2,-0.2,-0.27,0.15],[128.3,38.8,108.3,115.2,-0.2,-0.27,0.15],[127.9,39.0,108.3,115.2,-0.2,-0.27,0.15],[128.1,39.1,108.3,115.2,-0.2,-0.27,0.15],[128.4,39.1,108.3,115.2,-0.2,-0.27,0.15],[128.0,39.2,108.3,115.2,-0.2,-0.27,0.15],[128.0,39.2,108.3,115.2,-0.2,-0.27,0.15],[128.0,39.1,108.3,115.2,-0.2,-0.27,0.15],[127.9,39.1,108.3,115.2,-0.2,-0.27,0.15]],"scrub":false},"subagents_rest":{"n":115,"loop":true,"role":"rest","state":"subagents","events":{},"frames":[[128.4,38.9,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.9,108.3,115.2,-0.3,-0.27,0.15],[128.2,38.8,108.3,115.2,-0.2,-0.27,0.15],[128.2,38.7,108.3,115.1,-0.3,-0.27,0.15],[128.3,38.6,108.3,115.0,-0.2,-0.27,0.15],[128.4,38.5,108.3,115.0,-0.3,-0.27,0.15],[128.4,38.4,108.3,115.0,-0.2,-0.27,0.15],[128.4,38.3,108.3,114.9,-0.3,-0.27,0.15],[128.4,38.2,108.3,114.8,-0.2,-0.27,0.15],[128.4,38.1,108.3,114.8,-0.3,-0.27,0.15],[128.0,38.1,108.3,114.8,-0.2,-0.27,0.15],[128.4,37.9,108.3,114.7,-0.3,-0.27,0.15],[129.1,37.7,108.2,114.7,-0.3,-0.27,0.15],[129.2,37.5,107.9,114.7,-0.2,-0.27,0.15],[129.8,37.2,107.6,114.6,-0.3,-0.27,0.15],[129.9,36.9,107.2,114.6,-0.3,-0.27,0.15],[130.3,36.6,106.7,114.6,-0.5,-0.27,0.15],[130.9,36.3,106.1,114.6,-0.5,-0.27,0.15],[131.2,36.1,105.6,114.5,-0.6,-0.27,0.15],[131.2,36.0,105.2,114.4,-0.5,-0.27,0.15],[131.4,36.0,104.7,114.4,-0.6,-0.27,0.15],[131.2,36.1,104.5,114.4,-0.6,-0.27,0.15],[131.1,36.3,104.2,114.4,-0.6,-0.27,0.15],[130.5,36.5,104.2,114.4,-0.6,-0.27,0.15],[130.6,36.6,104.2,114.3,-0.8,-0.27,0.15],[130.1,36.8,104.2,114.3,-0.8,-0.27,0.15],[129.9,36.8,104.2,114.3,-0.8,-0.27,0.15],[130.4,36.7,104.2,114.3,-0.8,-0.27,0.15],[130.2,36.7,104.2,114.3,-0.8,-0.27,0.15],[130.5,36.6,104.2,114.3,-0.8,-0.27,0.15],[130.5,36.5,104.2,114.3,-0.8,-0.27,0.15],[130.7,36.4,104.2,114.3,-0.8,-0.27,0.15],[131.1,36.3,104.2,114.3,-0.8,-0.27,0.15],[131.0,36.3,104.2,114.3,-0.8,-0.27,0.15],[131.2,36.3,104.2,114.3,-0.8,-0.27,0.15],[131.1,36.3,104.2,114.4,-0.6,-0.27,0.15],[131.0,36.4,104.2,114.4,-0.6,-0.27,0.15],[131.2,36.4,104.2,114.5,-0.8,-0.27,0.15],[131.1,36.5,104.2,114.5,-0.8,-0.27,0.15],[130.5,36.6,104.2,114.5,-0.6,-0.27,0.15],[131.3,36.6,104.2,114.5,-0.6,-0.27,0.15],[130.9,36.7,104.2,114.5,-0.8,-0.27,0.15],[130.5,36.9,104.2,114.6,-0.6,-0.27,0.15],[129.9,37.4,104.8,114.6,-0.6,-0.27,0.15],[127.3,38.2,105.8,114.7,-0.5,-0.27,0.15],[125.2,38.9,106.8,114.7,-0.5,-0.27,0.15],[124.5,39.3,107.8,114.7,-0.3,-0.27,0.15],[124.8,39.2,108.2,114.8,-0.2,-0.27,0.15],[126.2,38.8,108.3,114.8,-0.3,-0.27,0.15],[127.6,38.4,108.3,114.8,-0.2,-0.27,0.15],[129.2,38.0,108.3,114.8,-0.2,-0.27,0.15],[129.4,37.9,108.3,115.0,-0.2,-0.27,0.15],[129.6,37.8,108.3,115.0,-0.2,-0.27,0.15],[129.4,37.9,108.3,115.0,-0.2,-0.27,0.15],[129.7,38.0,108.3,115.0,-0.2,-0.27,0.15],[129.4,38.3,108.3,115.2,-0.2,-0.27,0.15],[129.3,38.5,108.3,115.2,-0.3,-0.27,0.15],[128.7,38.8,108.3,115.2,-0.2,-0.27,0.15],[128.3,39.0,108.3,115.3,-0.3,-0.27,0.15],[128.2,39.2,108.3,115.3,-0.2,-0.27,0.15],[127.4,39.4,108.3,115.4,-0.3,-0.27,0.15],[127.5,39.5,108.3,115.5,-0.2,-0.27,0.15],[127.5,39.6,108.3,115.5,-0.3,-0.27,0.15],[127.5,39.7,108.3,115.5,-0.2,-0.27,0.15],[127.4,39.8,108.3,115.6,-0.3,-0.27,0.15],[127.3,39.9,108.3,115.7,-0.2,-0.27,0.15],[128.0,39.9,108.3,115.7,-0.3,-0.27,0.15],[127.9,40.0,108.3,115.8,-0.2,-0.27,0.15],[127.9,40.1,108.4,115.8,-0.3,-0.27,0.15],[127.0,40.4,108.8,115.8,-0.2,-0.27,0.15],[125.5,41.1,109.6,115.8,-0.2,-0.27,0.15],[123.5,41.9,110.6,115.9,0.0,-0.27,0.15],[122.8,42.4,111.7,116.0,0.2,-0.27,0.15],[122.8,42.5,112.3,116.0,0.3,-0.27,0.15],[123.0,42.2,112.5,116.0,0.3,-0.27,0.15],[123.8,41.7,112.6,116.0,0.2,-0.27,0.15],[125.2,41.3,112.6,116.1,0.3,-0.27,0.15],[126.0,41.0,112.6,116.1,0.3,-0.27,0.15],[126.5,40.9,112.6,116.2,0.2,-0.27,0.15],[126.4,40.9,112.6,116.2,0.2,-0.27,0.15],[126.5,40.9,112.6,116.2,0.3,-0.27,0.15],[126.2,41.1,112.6,116.2,0.3,-0.27,0.15],[126.0,41.2,112.6,116.2,0.3,-0.27,0.15],[125.8,41.4,112.6,116.2,0.3,-0.27,0.15],[125.6,41.5,112.6,116.2,0.3,-0.27,0.15],[125.1,41.7,112.6,116.2,0.2,-0.27,0.15],[124.7,41.8,112.6,116.2,0.2,-0.27,0.15],[124.8,41.8,112.6,116.2,0.2,-0.27,0.15],[124.7,41.8,112.6,116.2,0.2,-0.27,0.15],[124.7,41.8,112.6,116.2,0.3,-0.27,0.15],[125.1,41.7,112.5,116.2,0.3,-0.27,0.15],[125.0,41.6,112.4,116.2,0.3,-0.27,0.15],[125.8,41.3,112.0,116.2,0.2,-0.27,0.15],[126.7,40.9,111.5,116.2,0.2,-0.27,0.15],[128.5,40.5,111.0,116.2,0.2,-0.27,0.15],[128.8,40.2,110.3,116.1,0.0,-0.27,0.15],[129.0,39.9,109.6,116.1,0.0,-0.27,0.15],[129.2,39.8,109.1,116.0,-0.2,-0.27,0.15],[129.2,39.9,108.7,116.0,-0.2,-0.27,0.15],[129.4,40.0,108.4,116.0,-0.2,-0.27,0.15],[128.2,40.3,108.3,116.0,-0.2,-0.27,0.15],[127.5,40.5,108.3,116.0,-0.2,-0.27,0.15],[126.8,40.7,108.3,115.9,-0.3,-0.27,0.15],[126.6,40.7,108.3,115.8,-0.2,-0.27,0.15],[126.7,40.6,108.3,115.8,-0.2,-0.27,0.15],[126.6,40.5,108.3,115.8,-0.2,-0.27,0.15],[126.9,40.3,108.3,115.8,-0.2,-0.27,0.15],[127.5,40.1,108.3,115.7,-0.3,-0.27,0.15],[127.5,39.9,108.3,115.7,-0.2,-0.27,0.15],[128.0,39.7,108.3,115.6,-0.3,-0.27,0.15],[128.4,39.5,108.3,115.5,-0.2,-0.27,0.15],[128.1,39.4,108.3,115.5,-0.3,-0.27,0.15],[128.6,39.2,108.3,115.5,-0.2,-0.27,0.15],[128.6,39.1,108.3,115.4,-0.3,-0.27,0.15],[128.3,39.0,108.3,115.3,-0.2,-0.27,0.15]],"scrub":false},"subagents_hop":{"n":58,"loop":false,"role":"beat","state":"subagents","events":{},"frames":[[128.3,39.0,108.3,115.2,-0.2,-0.27,0.15],[128.4,38.8,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.7,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.5,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.3,108.3,114.8,-0.2,-0.27,0.15],[128.3,38.0,108.3,114.8,-0.2,-0.27,0.15],[128.1,37.9,108.3,114.7,-0.2,-0.27,0.15],[128.3,37.7,108.3,114.6,-0.3,-0.27,0.15],[128.3,37.5,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.4,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.3,108.3,114.4,-0.3,-0.27,0.15],[128.3,37.2,108.3,114.3,-0.2,-0.27,0.15],[128.3,37.2,108.3,114.3,-0.2,-0.27,0.15],[128.3,37.1,108.3,114.3,-0.3,-0.27,0.15],[128.3,37.1,108.3,114.3,-0.3,-0.27,0.15],[128.3,37.1,108.3,114.3,-0.3,-0.27,0.15],[128.3,37.1,108.3,114.3,-0.3,-0.27,0.15],[128.3,37.2,108.3,114.3,-0.2,-0.27,0.15],[128.3,37.2,108.3,114.3,-0.2,-0.27,0.15],[128.3,37.3,108.3,114.4,-0.3,-0.27,0.15],[128.3,37.4,108.3,114.5,-0.2,-0.27,0.15],[128.3,37.6,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.7,108.3,114.6,-0.3,-0.27,0.15],[128.3,37.9,108.3,114.7,-0.3,-0.27,0.15],[128.1,38.1,108.3,114.8,-0.3,-0.27,0.15],[128.3,38.2,108.3,114.8,-0.2,-0.27,0.15],[128.4,38.4,108.3,115.0,-0.2,-0.27,0.15],[128.4,38.6,108.3,115.0,-0.2,-0.27,0.15],[127.9,38.9,108.3,115.2,-0.3,-0.27,0.15],[128.1,39.1,108.3,115.3,-0.3,-0.27,0.15],[128.1,39.3,108.3,115.4,-0.3,-0.27,0.15],[128.1,39.5,108.3,115.5,-0.3,-0.27,0.15],[128.1,39.7,108.3,115.6,-0.3,-0.27,0.15],[127.9,39.9,108.3,115.7,-0.3,-0.27,0.15],[127.9,40.1,108.3,115.8,-0.3,-0.27,0.15],[128.1,40.2,108.3,115.8,-0.2,-0.27,0.15],[127.9,40.4,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.5,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.6,108.3,116.1,-0.3,-0.27,0.15],[128.1,40.7,108.3,116.2,-0.2,-0.27,0.15],[128.1,40.8,108.3,116.2,-0.2,-0.27,0.15],[127.9,40.9,108.3,116.2,-0.3,-0.27,0.15],[128.1,40.9,108.3,116.2,-0.2,-0.27,0.15],[128.1,40.9,108.3,116.2,-0.2,-0.27,0.15],[128.1,40.9,108.3,116.2,-0.2,-0.27,0.15],[128.1,40.9,108.3,116.2,-0.3,-0.27,0.15],[127.9,40.9,108.3,116.2,-0.3,-0.27,0.15],[127.9,40.8,108.3,116.2,-0.2,-0.27,0.15],[127.9,40.7,108.3,116.1,-0.3,-0.27,0.15],[127.9,40.6,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.4,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.3,108.3,115.9,-0.3,-0.27,0.15],[128.1,40.1,108.3,115.8,-0.2,-0.27,0.15],[128.4,39.9,108.3,115.8,-0.2,-0.27,0.15],[127.9,39.8,108.3,115.7,-0.2,-0.27,0.15],[127.9,39.6,108.3,115.5,-0.2,-0.27,0.15],[127.9,39.4,108.3,115.5,-0.2,-0.27,0.15],[127.9,39.2,108.3,115.3,-0.2,-0.27,0.15]],"scrub":false},"subagents_sigh":{"n":58,"loop":false,"role":"beat","state":"subagents","events":{},"frames":[[128.3,39.0,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.9,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.7,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.5,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.3,108.3,114.8,-0.2,-0.27,0.15],[128.1,38.1,108.3,114.8,-0.2,-0.27,0.15],[128.1,37.9,108.3,114.7,-0.2,-0.27,0.15],[128.3,37.7,108.3,114.6,-0.3,-0.27,0.15],[128.3,37.5,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.4,108.3,114.5,-0.2,-0.27,0.15],[128.3,37.3,108.3,114.4,-0.3,-0.27,0.15],[128.4,37.0,108.3,114.2,-0.2,-0.27,0.15],[128.4,36.1,108.3,113.8,-0.2,-0.27,0.15],[128.3,34.6,108.3,112.9,-0.3,-0.27,0.15],[129.2,32.4,108.3,111.7,-0.3,-0.27,0.15],[129.4,29.8,108.3,110.4,-0.3,-0.27,0.15],[129.5,26.9,108.4,109.1,-0.3,-0.27,0.15],[129.7,24.3,108.4,108.0,-0.3,-0.27,0.15],[130.3,22.2,108.3,107.2,-0.3,-0.27,0.15],[130.8,20.8,108.4,106.8,-0.3,-0.27,0.15],[130.9,20.3,108.4,106.7,-0.3,-0.27,0.15],[130.7,20.4,108.4,106.8,-0.3,-0.27,0.15],[130.6,21.1,108.4,107.0,-0.3,-0.27,0.15],[130.5,22.6,108.3,107.7,-0.3,-0.27,0.15],[129.9,25.0,108.3,108.8,-0.3,-0.27,0.15],[130.0,28.2,108.3,110.4,-0.3,-0.27,0.15],[129.7,32.2,108.3,112.4,-0.3,-0.27,0.15],[128.8,36.8,108.3,114.7,-0.3,-0.27,0.15],[128.3,41.6,108.3,117.0,-0.1,-0.27,0.15],[127.4,46.3,108.3,119.3,-0.1,-0.27,0.15],[127.0,50.6,108.3,121.5,-0.1,-0.27,0.15],[126.2,54.2,108.3,123.2,-0.1,-0.27,0.15],[126.3,56.8,108.2,124.3,-0.1,-0.27,0.15],[126.1,58.5,108.2,125.1,0.0,-0.27,0.15],[126.1,59.2,108.2,125.5,-0.1,-0.27,0.15],[126.2,59.3,108.2,125.5,-0.1,-0.27,0.15],[126.2,59.2,108.2,125.6,0.0,-0.27,0.15],[126.4,59.0,108.2,125.7,-0.1,-0.27,0.15],[126.6,58.8,108.2,125.8,-0.1,-0.27,0.15],[126.7,58.7,108.2,125.8,-0.1,-0.27,0.15],[126.7,58.4,108.2,125.7,0.0,-0.27,0.15],[126.1,54.3,108.2,123.0,-0.1,-0.27,0.15],[126.2,46.9,108.3,118.2,-0.1,-0.27,0.15],[127.1,42.7,108.3,116.2,-0.2,-0.27,0.15],[128.0,41.0,108.3,116.2,-0.2,-0.27,0.15],[128.4,39.8,108.3,116.2,-0.3,-0.27,0.15],[128.6,39.2,108.3,116.2,-0.3,-0.27,0.15],[128.7,39.1,108.3,116.2,-0.2,-0.27,0.15],[128.5,39.4,108.3,116.1,-0.3,-0.27,0.15],[128.3,39.9,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.4,108.3,116.0,-0.2,-0.27,0.15],[127.9,40.7,108.3,115.9,-0.3,-0.27,0.15],[127.7,40.8,108.3,115.8,-0.2,-0.27,0.15],[127.9,40.6,108.3,115.8,-0.2,-0.27,0.15],[127.8,40.3,108.3,115.7,-0.2,-0.27,0.15],[128.0,39.8,108.3,115.5,-0.2,-0.27,0.15],[128.1,39.4,108.3,115.5,-0.2,-0.27,0.15],[128.1,39.0,108.3,115.3,-0.2,-0.27,0.15]],"scrub":false},"subagents_lean":{"n":58,"loop":false,"role":"beat","state":"subagents","events":{},"frames":[[128.3,39.0,108.3,115.2,-0.2,-0.27,0.15],[128.4,38.8,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.7,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.5,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.3,108.3,114.8,-0.2,-0.27,0.15],[128.3,38.0,108.3,114.8,-0.2,-0.27,0.15],[128.1,37.9,108.3,114.7,-0.2,-0.27,0.15],[128.3,37.7,108.3,114.6,-0.3,-0.27,0.15],[128.3,37.5,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.4,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.3,108.3,114.4,-0.3,-0.27,0.15],[128.6,37.0,108.2,114.3,-0.2,-0.26,0.15],[130.0,36.1,107.6,114.3,-0.3,-0.25,0.15],[130.8,34.7,106.5,114.3,-0.5,-0.23,0.15],[133.9,32.8,104.8,114.4,-0.6,-0.2,0.15],[135.8,30.7,102.8,114.5,-0.8,-0.17,0.15],[135.8,28.7,100.6,114.6,-0.9,-0.13,0.15],[135.4,27.1,98.6,114.8,-1.1,-0.1,0.15],[134.4,26.0,97.1,114.8,-1.1,-0.08,0.15],[132.1,25.7,96.2,114.9,-1.1,-0.07,0.15],[132.2,26.1,96.0,115.0,-1.2,-0.07,0.15],[133.2,26.7,96.0,115.1,-1.2,-0.07,0.15],[133.9,27.2,96.0,115.2,-1.2,-0.07,0.15],[134.1,27.7,96.0,115.3,-1.2,-0.07,0.15],[134.3,28.0,95.9,115.4,-1.2,-0.07,0.15],[134.2,28.3,95.9,115.5,-1.2,-0.07,0.15],[134.0,28.4,95.9,115.6,-1.2,-0.07,0.15],[133.7,28.5,95.9,115.7,-1.2,-0.07,0.15],[133.3,28.6,95.9,115.8,-1.2,-0.07,0.15],[133.0,28.6,95.9,115.9,-1.2,-0.07,0.15],[132.7,28.7,95.9,116.1,-1.1,-0.07,0.15],[132.5,28.8,95.9,116.2,-1.1,-0.07,0.15],[132.4,28.9,95.9,116.2,-1.1,-0.07,0.15],[132.3,29.1,95.9,116.3,-1.1,-0.07,0.15],[132.4,29.3,95.9,116.4,-1.1,-0.07,0.15],[132.4,29.5,95.9,116.6,-1.1,-0.07,0.15],[132.5,29.7,95.9,116.7,-1.1,-0.07,0.15],[132.6,29.9,95.9,116.7,-1.2,-0.07,0.15],[132.7,30.1,95.9,116.8,-1.2,-0.07,0.15],[132.8,30.3,95.9,116.8,-1.1,-0.07,0.15],[132.9,30.4,95.9,116.9,-1.2,-0.07,0.15],[132.8,30.6,96.0,116.9,-1.2,-0.07,0.15],[127.8,37.6,102.8,116.5,-0.6,-0.17,0.15],[123.1,43.3,108.2,116.2,-0.2,-0.27,0.15],[123.3,43.5,108.3,116.2,-0.2,-0.27,0.15],[123.6,42.6,108.3,116.2,-0.3,-0.27,0.15],[125.4,41.8,108.3,116.2,-0.3,-0.27,0.15],[126.5,41.1,108.3,116.2,-0.2,-0.27,0.15],[127.9,40.5,108.3,116.1,-0.3,-0.27,0.15],[128.8,40.0,108.3,116.0,-0.2,-0.27,0.15],[129.2,39.6,108.3,116.0,-0.2,-0.27,0.15],[129.6,39.4,108.3,115.9,-0.3,-0.27,0.15],[129.4,39.2,108.3,115.8,-0.2,-0.27,0.15],[129.7,39.1,108.3,115.8,-0.2,-0.27,0.15],[130.0,39.1,108.3,115.7,-0.2,-0.27,0.15],[129.5,39.2,108.3,115.5,-0.2,-0.27,0.15],[128.8,39.2,108.3,115.5,-0.2,-0.27,0.15],[128.1,39.2,108.3,115.3,-0.2,-0.27,0.15]],"scrub":false},"speak_a":{"n":77,"loop":false,"role":"beat","state":"speaking","events":{},"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.7,43.6,98.2,118.3,0.1,0.03,0.0],[117.8,42.7,97.1,118.1,0.0,0.03,0.0],[121.3,41.5,95.4,117.5,-0.1,0.03,0.0],[123.1,40.6,94.3,116.4,-0.4,0.03,0.0],[123.3,40.4,94.2,115.2,-0.4,0.03,0.0],[123.1,40.4,94.5,113.8,-0.4,0.03,0.0],[122.2,40.8,94.7,112.4,-0.4,0.03,0.0],[120.7,40.4,94.8,111.4,-0.4,0.03,0.0],[118.3,40.2,94.9,110.8,-0.4,0.03,0.0],[117.1,40.2,95.0,110.4,-0.4,0.03,0.0],[116.2,40.4,95.0,110.3,-0.4,0.03,0.0],[114.1,40.9,94.8,111.7,-0.4,0.03,0.0],[113.4,42.4,94.1,115.8,-0.4,0.03,0.0],[115.2,43.5,93.7,118.3,-0.4,0.03,0.0],[118.9,43.5,93.8,117.7,-0.4,0.03,0.0],[120.1,41.2,94.6,112.6,-0.4,0.03,0.0],[120.3,39.9,95.0,110.3,-0.4,0.03,0.0],[122.3,40.2,94.8,111.7,-0.4,0.03,0.0],[121.6,41.7,94.1,115.8,-0.4,0.03,0.0],[120.7,42.5,93.7,118.3,-0.4,0.03,0.0],[121.8,41.9,94.0,116.8,-0.4,0.03,0.0],[122.7,37.2,95.7,107.3,-0.4,0.03,0.0],[122.8,36.3,96.5,103.3,-0.3,0.03,0.0],[118.0,36.5,96.0,105.6,-0.3,0.03,0.0],[112.9,39.9,94.6,113.3,-0.3,0.03,0.0],[111.9,43.0,93.7,118.2,-0.4,0.03,0.0],[112.7,43.0,93.8,117.7,-0.4,0.03,0.0],[119.5,41.7,94.6,112.6,-0.4,0.03,0.0],[120.8,41.3,95.0,110.3,-0.4,0.03,0.0],[121.0,41.4,94.8,111.7,-0.4,0.03,0.0],[120.9,42.4,94.1,115.8,-0.4,0.03,0.0],[120.9,43.2,93.7,118.3,-0.4,0.03,0.0],[120.8,42.7,93.8,118.2,-0.4,0.03,0.0],[120.8,41.1,94.2,115.4,-0.4,0.03,0.0],[120.6,39.7,94.7,111.8,-0.4,0.03,0.0],[121.9,39.6,95.0,110.3,-0.4,0.03,0.0],[121.0,40.2,94.8,111.1,-0.4,0.03,0.0],[117.8,41.2,94.2,114.8,-0.4,0.03,0.0],[116.4,42.7,93.8,118.2,-0.4,0.03,0.0],[118.1,43.0,93.8,118.2,-0.4,0.03,0.0],[120.8,41.9,94.5,113.7,-0.4,0.03,0.0],[120.9,40.8,95.0,110.4,-0.6,0.03,0.0],[120.8,41.0,94.8,111.1,-0.4,0.03,0.0],[119.7,41.8,94.2,114.8,-0.4,0.03,0.0],[119.0,42.8,93.8,118.2,-0.4,0.03,0.0],[120.0,43.1,93.7,118.4,-0.6,0.03,0.0],[121.0,43.2,93.7,118.4,-0.6,0.03,0.0],[121.7,42.7,93.7,118.4,-0.6,0.03,0.0],[120.1,42.3,93.7,118.4,-0.6,0.03,0.0],[120.2,42.1,93.7,118.4,-0.6,0.03,0.0],[120.9,41.9,93.7,118.4,-0.6,0.03,0.0],[120.3,41.9,93.7,118.4,-0.6,0.03,0.0],[120.3,41.9,93.7,118.4,-0.6,0.03,0.0],[119.3,42.5,94.3,118.4,-0.3,0.03,0.0],[114.7,44.0,96.5,118.3,-0.1,0.03,0.0],[113.8,44.4,98.2,118.3,0.1,0.03,0.0],[113.7,44.3,98.3,118.3,0.1,0.03,0.0],[113.3,44.2,98.3,118.3,0.1,0.03,0.0],[113.1,44.1,98.3,118.3,0.1,0.03,0.0],[113.4,44.0,98.3,118.3,0.1,0.03,0.0],[114.1,43.6,98.3,118.3,0.1,0.03,0.0],[115.5,43.3,98.3,118.3,0.1,0.03,0.0],[116.1,43.1,98.3,118.3,0.1,0.03,0.0],[116.6,43.0,98.3,118.3,0.1,0.03,0.0],[116.7,43.0,98.3,118.3,0.1,0.03,0.0],[115.7,43.1,98.3,118.3,0.1,0.03,0.0],[114.7,43.3,98.3,118.3,0.1,0.03,0.0],[114.0,43.4,98.3,118.3,0.1,0.03,0.0],[113.7,43.6,98.3,118.3,0.1,0.03,0.0]],"scrub":false},"speak_b":{"n":91,"loop":false,"role":"beat","state":"speaking","events":{},"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.3,43.8,98.5,118.3,0.1,0.03,0.0],[112.3,44.1,99.7,118.1,0.3,0.03,0.0],[111.4,44.3,101.4,117.4,0.4,0.03,0.0],[109.7,44.2,102.6,116.5,0.7,0.03,0.0],[109.1,43.5,102.8,115.2,0.7,0.03,0.0],[108.8,42.6,102.8,113.8,0.9,0.03,0.0],[108.3,41.9,102.7,112.4,1.0,0.03,0.0],[108.1,41.3,102.6,111.4,1.0,0.03,0.0],[108.4,40.9,102.5,110.8,1.0,0.03,0.0],[106.7,40.8,102.5,110.4,1.0,0.03,0.0],[106.5,40.9,102.5,110.3,1.0,0.03,0.0],[106.0,41.3,102.6,111.7,1.0,0.03,0.0],[106.7,42.9,102.9,115.8,0.7,0.03,0.0],[108.5,44.0,103.0,118.3,0.6,0.03,0.0],[109.6,44.0,102.9,117.3,0.7,0.03,0.0],[108.3,42.6,102.6,111.8,1.0,0.03,0.0],[108.0,42.0,102.5,110.4,1.2,0.03,0.0],[108.5,42.1,102.7,112.4,1.0,0.03,0.0],[109.4,43.0,103.0,116.7,0.7,0.03,0.0],[110.0,43.6,103.0,118.4,0.6,0.03,0.0],[109.4,43.0,102.9,116.2,0.7,0.03,0.0],[108.3,41.6,102.6,110.9,1.0,0.03,0.0],[108.4,41.4,102.5,110.6,1.0,0.03,0.0],[109.1,42.0,102.7,113.4,1.0,0.03,0.0],[109.1,43.4,102.9,117.5,0.7,0.03,0.0],[110.1,44.0,103.0,118.3,0.7,0.03,0.0],[109.0,43.0,102.8,114.8,0.9,0.03,0.0],[108.0,41.9,102.5,110.4,1.0,0.03,0.0],[108.4,41.7,102.6,110.9,1.0,0.03,0.0],[109.3,42.4,102.8,114.5,0.9,0.03,0.0],[110.4,43.5,103.0,118.0,0.7,0.03,0.0],[110.3,43.7,103.0,118.2,0.7,0.03,0.0],[109.1,41.5,102.7,113.3,0.9,0.03,0.0],[107.6,38.6,102.2,105.6,1.5,0.03,0.0],[107.3,37.2,102.0,103.3,1.5,0.03,0.0],[106.5,37.3,102.2,105.6,1.5,0.03,0.0],[107.1,40.8,102.7,113.3,0.9,0.03,0.0],[107.6,43.8,103.0,118.2,0.7,0.03,0.0],[107.5,43.7,102.9,117.3,0.7,0.03,0.0],[108.3,42.3,102.6,111.8,1.0,0.03,0.0],[108.2,42.2,102.5,110.4,1.2,0.03,0.0],[108.6,42.6,102.7,112.4,1.0,0.03,0.0],[109.6,43.7,103.0,116.7,0.7,0.03,0.0],[109.9,44.2,103.0,118.4,0.6,0.03,0.0],[109.2,43.5,103.0,116.7,0.7,0.03,0.0],[108.2,41.8,102.6,111.6,1.0,0.03,0.0],[108.1,41.3,102.5,110.4,1.2,0.03,0.0],[108.6,41.4,102.7,112.4,1.0,0.03,0.0],[110.0,42.7,103.0,116.7,0.7,0.03,0.0],[109.6,43.6,103.0,118.4,0.6,0.03,0.0],[109.5,43.5,103.0,117.0,0.8,0.03,0.0],[108.6,42.3,102.7,112.2,1.0,0.03,0.0],[108.3,41.8,102.5,110.3,1.0,0.03,0.0],[108.3,41.8,102.6,111.7,1.0,0.03,0.0],[109.9,42.9,102.9,115.8,0.7,0.03,0.0],[110.1,43.8,103.0,118.3,0.6,0.03,0.0],[110.0,44.0,103.0,118.4,0.6,0.03,0.0],[109.9,44.3,103.0,118.4,0.6,0.03,0.0],[109.5,44.5,103.0,118.4,0.6,0.03,0.0],[109.6,44.4,103.0,118.4,0.6,0.03,0.0],[109.6,44.2,103.0,118.4,0.6,0.03,0.0],[109.6,44.0,103.0,118.4,0.6,0.03,0.0],[109.6,44.0,103.0,118.4,0.6,0.03,0.0],[109.8,44.0,103.0,118.4,0.6,0.03,0.0],[109.9,44.1,102.8,118.4,0.6,0.03,0.0],[110.4,43.9,102.2,118.4,0.6,0.03,0.0],[111.6,43.6,101.2,118.3,0.4,0.03,0.0],[115.4,43.1,100.0,118.4,0.3,0.03,0.0],[117.7,42.9,99.0,118.3,0.1,0.03,0.0],[118.3,43.0,98.4,118.3,0.1,0.03,0.0],[116.8,43.3,98.3,118.3,0.1,0.03,0.0],[114.7,43.6,98.3,118.3,0.1,0.03,0.0],[113.6,43.8,98.3,118.3,0.1,0.03,0.0],[113.6,44.0,98.3,118.3,0.1,0.03,0.0],[113.4,44.1,98.3,118.3,0.1,0.03,0.0],[113.2,44.1,98.3,118.3,0.1,0.03,0.0],[113.1,44.1,98.3,118.3,0.1,0.03,0.0],[113.4,44.0,98.3,118.3,0.1,0.03,0.0],[113.2,43.9,98.3,118.3,0.1,0.03,0.0],[113.1,43.9,98.3,118.3,0.1,0.03,0.0],[113.3,43.8,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.6,43.6,98.3,118.3,0.1,0.03,0.0]],"scrub":false},"speak_c":{"n":62,"loop":false,"role":"beat","state":"speaking","events":{},"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.3,43.8,98.5,118.3,0.1,0.03,0.0],[112.3,44.1,99.7,118.1,0.3,0.03,0.0],[111.4,44.3,101.4,117.4,0.4,0.03,0.0],[109.7,44.2,102.6,116.5,0.7,0.03,0.0],[109.1,43.5,102.8,115.2,0.7,0.03,0.0],[108.8,42.6,102.8,113.8,0.9,0.03,0.0],[108.3,41.9,102.7,112.4,1.0,0.03,0.0],[108.1,41.3,102.6,111.4,1.0,0.03,0.0],[108.4,40.9,102.5,110.8,1.0,0.03,0.0],[106.7,40.8,102.5,110.4,1.0,0.03,0.0],[106.5,40.9,102.5,110.3,1.0,0.03,0.0],[106.0,41.3,102.6,111.7,1.0,0.03,0.0],[106.7,42.9,102.9,115.8,0.7,0.03,0.0],[108.5,44.0,103.0,118.3,0.6,0.03,0.0],[109.7,44.1,102.9,117.7,0.7,0.03,0.0],[108.3,42.9,102.7,112.6,0.9,0.03,0.0],[108.1,41.9,102.5,110.3,1.0,0.03,0.0],[108.4,41.9,102.6,111.7,1.0,0.03,0.0],[109.2,42.7,102.9,115.8,0.7,0.03,0.0],[110.0,43.5,103.0,118.3,0.6,0.03,0.0],[109.6,43.6,103.0,118.0,0.7,0.03,0.0],[109.2,42.6,102.8,114.5,0.9,0.03,0.0],[108.1,41.8,102.6,110.9,1.0,0.03,0.0],[108.2,41.4,102.5,110.4,1.2,0.03,0.0],[108.8,41.8,102.7,112.6,0.9,0.03,0.0],[108.6,43.2,103.0,116.8,0.7,0.03,0.0],[109.3,43.9,103.0,118.4,0.6,0.03,0.0],[108.9,42.8,102.8,114.6,0.9,0.03,0.0],[108.2,41.7,102.5,110.3,1.0,0.03,0.0],[108.6,41.8,102.6,111.7,1.0,0.03,0.0],[109.5,42.9,102.9,115.8,0.7,0.03,0.0],[110.3,43.8,103.0,118.3,0.6,0.03,0.0],[109.7,44.0,103.0,118.4,0.6,0.03,0.0],[109.9,44.3,103.0,118.4,0.6,0.03,0.0],[109.7,44.5,103.0,118.4,0.6,0.03,0.0],[109.7,44.4,103.0,118.4,0.6,0.03,0.0],[109.7,44.2,103.0,118.4,0.6,0.03,0.0],[109.6,44.1,103.0,118.4,0.6,0.03,0.0],[109.7,44.1,103.0,118.4,0.6,0.03,0.0],[109.7,44.2,103.0,118.4,0.6,0.03,0.0],[114.2,42.8,100.7,118.3,0.4,0.03,0.0],[118.7,41.8,98.4,118.3,0.1,0.03,0.0],[118.6,42.3,98.3,118.3,0.1,0.03,0.0],[118.2,42.9,98.3,118.3,0.1,0.03,0.0],[116.0,43.4,98.3,118.3,0.1,0.03,0.0],[114.1,43.9,98.3,118.3,0.1,0.03,0.0],[113.4,44.1,98.3,118.3,0.1,0.03,0.0],[113.7,44.2,98.3,118.3,0.1,0.03,0.0],[113.5,44.2,98.3,118.3,0.1,0.03,0.0],[113.3,44.2,98.3,118.3,0.1,0.03,0.0],[113.0,44.2,98.3,118.3,0.1,0.03,0.0],[113.3,44.0,98.3,118.3,0.1,0.03,0.0],[113.2,43.9,98.3,118.3,0.1,0.03,0.0],[113.1,43.8,98.3,118.3,0.1,0.03,0.0]],"scrub":false},"speak_d":{"n":106,"loop":false,"role":"beat","state":"speaking","events":{},"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.7,43.6,98.2,118.3,0.1,0.03,0.0],[117.8,42.7,97.1,118.1,0.0,0.03,0.0],[121.3,41.5,95.4,117.5,-0.1,0.03,0.0],[123.1,40.6,94.3,116.4,-0.4,0.03,0.0],[123.3,40.4,94.2,115.2,-0.4,0.03,0.0],[123.1,40.4,94.5,113.8,-0.4,0.03,0.0],[122.2,40.8,94.7,112.4,-0.4,0.03,0.0],[120.7,40.4,94.8,111.4,-0.4,0.03,0.0],[118.3,40.2,94.9,110.8,-0.4,0.03,0.0],[117.1,40.2,95.0,110.4,-0.4,0.03,0.0],[116.2,40.4,95.0,110.3,-0.4,0.03,0.0],[114.1,40.9,94.8,111.7,-0.4,0.03,0.0],[113.4,42.4,94.1,115.8,-0.4,0.03,0.0],[115.2,43.5,93.7,118.3,-0.4,0.03,0.0],[118.9,43.4,93.8,117.4,-0.6,0.03,0.0],[120.1,40.9,94.7,111.8,-0.4,0.03,0.0],[120.2,40.0,95.0,110.3,-0.4,0.03,0.0],[121.8,40.6,94.7,112.4,-0.4,0.03,0.0],[121.7,42.1,94.0,116.7,-0.4,0.03,0.0],[121.2,42.6,93.7,118.4,-0.6,0.03,0.0],[122.1,41.0,94.2,115.1,-0.4,0.03,0.0],[122.9,36.4,96.0,105.4,-0.3,0.03,0.0],[122.3,36.1,96.5,103.3,-0.3,0.03,0.0],[116.9,37.0,95.7,107.1,-0.3,0.03,0.0],[112.6,41.0,94.2,115.1,-0.4,0.03,0.0],[111.9,43.1,93.7,118.4,-0.6,0.03,0.0],[114.4,42.9,93.9,117.1,-0.4,0.03,0.0],[120.0,41.8,94.7,112.2,-0.4,0.03,0.0],[120.8,41.2,95.0,110.3,-0.4,0.03,0.0],[121.1,41.3,94.8,111.7,-0.4,0.03,0.0],[120.7,42.3,94.1,115.8,-0.4,0.03,0.0],[120.8,43.1,93.7,118.3,-0.4,0.03,0.0],[121.0,42.8,93.7,118.3,-0.4,0.03,0.0],[121.5,42.0,93.8,117.4,-0.4,0.03,0.0],[120.5,41.0,94.2,115.4,-0.4,0.03,0.0],[120.8,40.2,94.5,113.2,-0.4,0.03,0.0],[121.9,39.9,94.8,111.2,-0.4,0.03,0.0],[121.2,40.1,95.0,110.4,-0.4,0.03,0.0],[119.7,40.0,95.0,110.4,-0.4,0.03,0.0],[116.1,40.8,94.5,113.2,-0.4,0.03,0.0],[113.0,42.5,93.9,117.2,-0.4,0.03,0.0],[116.2,43.3,93.7,118.4,-0.6,0.03,0.0],[119.7,42.5,94.2,115.3,-0.4,0.03,0.0],[120.7,40.9,94.9,110.6,-0.4,0.03,0.0],[120.9,40.8,94.9,110.8,-0.4,0.03,0.0],[121.0,41.7,94.3,114.2,-0.4,0.03,0.0],[119.8,42.7,93.8,117.8,-0.4,0.03,0.0],[120.8,42.9,93.7,118.3,-0.4,0.03,0.0],[121.0,41.6,94.2,115.2,-0.4,0.03,0.0],[121.3,39.9,94.9,110.8,-0.4,0.03,0.0],[120.9,40.1,95.0,110.4,-0.4,0.03,0.0],[119.9,40.9,94.5,113.2,-0.4,0.03,0.0],[118.3,42.3,93.9,117.2,-0.4,0.03,0.0],[118.3,43.0,93.7,118.4,-0.6,0.03,0.0],[120.4,41.2,94.4,114.4,-0.4,0.03,0.0],[122.2,37.2,96.0,105.5,-0.3,0.03,0.0],[121.6,36.5,96.5,103.3,-0.3,0.03,0.0],[117.4,36.9,95.8,106.6,-0.3,0.03,0.0],[112.8,40.5,94.3,114.6,-0.4,0.03,0.0],[112.0,42.9,93.7,118.3,-0.4,0.03,0.0],[115.4,42.5,94.0,116.7,-0.4,0.03,0.0],[120.4,41.2,94.8,111.2,-0.4,0.03,0.0],[120.9,41.1,95.0,110.4,-0.4,0.03,0.0],[120.9,41.8,94.5,113.2,-0.4,0.03,0.0],[120.7,42.9,93.9,117.2,-0.4,0.03,0.0],[121.2,43.3,93.7,118.4,-0.6,0.03,0.0],[120.8,40.0,94.8,111.4,-0.4,0.03,0.0],[121.6,39.8,94.9,110.8,-0.4,0.03,0.0],[121.2,41.1,94.3,113.9,-0.4,0.03,0.0],[119.5,42.4,93.8,117.8,-0.4,0.03,0.0],[119.9,42.9,93.7,118.4,-0.6,0.03,0.0],[120.8,43.2,93.7,118.4,-0.6,0.03,0.0],[120.7,43.3,93.7,118.4,-0.6,0.03,0.0],[121.2,42.9,93.7,118.4,-0.6,0.03,0.0],[119.7,42.5,93.7,118.4,-0.6,0.03,0.0],[120.1,42.3,93.7,118.4,-0.6,0.03,0.0],[120.4,42.0,93.7,118.4,-0.6,0.03,0.0],[120.1,41.9,93.7,118.4,-0.6,0.03,0.0],[120.3,42.0,93.7,118.4,-0.6,0.03,0.0],[119.6,42.4,94.2,118.4,-0.3,0.03,0.0],[116.3,43.2,95.1,118.4,-0.3,0.03,0.0],[115.2,43.9,96.2,118.3,-0.1,0.03,0.0],[114.2,44.2,97.3,118.4,0.0,0.03,0.0],[113.6,44.3,98.1,118.3,0.1,0.03,0.0],[113.3,44.3,98.3,118.3,0.1,0.03,0.0],[113.2,44.2,98.3,118.3,0.1,0.03,0.0],[113.1,44.0,98.3,118.3,0.1,0.03,0.0],[113.8,43.6,98.3,118.3,0.1,0.03,0.0],[115.3,43.3,98.3,118.3,0.1,0.03,0.0],[115.9,43.1,98.3,118.3,0.1,0.03,0.0],[116.4,43.0,98.3,118.3,0.1,0.03,0.0],[116.2,43.1,98.3,118.3,0.1,0.03,0.0],[115.4,43.2,98.3,118.3,0.1,0.03,0.0],[114.7,43.3,98.3,118.3,0.1,0.03,0.0],[114.4,43.5,98.3,118.3,0.1,0.03,0.0],[113.7,43.6,98.3,118.3,0.1,0.03,0.0],[113.5,43.8,98.3,118.3,0.1,0.03,0.0],[113.4,43.8,98.3,118.3,0.1,0.03,0.0]],"scrub":false},"speaking_rest":{"n":43,"loop":true,"role":"rest","state":"speaking","events":{},"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.5,43.4,98.3,118.2,0.1,0.03,0.0],[113.6,43.1,98.3,118.0,0.1,0.03,0.0],[113.6,42.8,98.3,118.0,0.1,0.03,0.0],[113.5,42.6,98.3,117.8,0.0,0.03,0.0],[113.4,42.4,98.3,117.7,0.1,0.03,0.0],[113.6,42.1,98.4,117.5,0.1,0.03,0.0],[113.7,42.0,98.3,117.5,0.1,0.03,0.0],[113.7,41.8,98.3,117.4,0.0,0.03,0.0],[113.5,41.8,98.3,117.3,0.1,0.03,0.0],[113.7,41.7,98.3,117.3,0.1,0.03,0.0],[113.7,41.7,98.3,117.3,0.1,0.03,0.0],[113.7,41.7,98.3,117.3,0.1,0.03,0.0],[113.7,41.8,98.3,117.3,0.1,0.03,0.0],[113.7,41.9,98.3,117.5,0.1,0.03,0.0],[113.7,42.0,98.3,117.5,0.0,0.03,0.0],[113.7,42.2,98.3,117.6,0.0,0.03,0.0],[113.6,42.4,98.3,117.8,0.1,0.03,0.0],[113.5,42.7,98.3,117.8,0.1,0.03,0.0],[113.6,42.9,98.3,118.0,0.1,0.03,0.0],[113.6,43.2,98.3,118.2,0.1,0.03,0.0],[113.5,43.5,98.3,118.2,0.1,0.03,0.0],[113.5,43.8,98.3,118.5,0.1,0.03,0.0],[113.4,44.1,98.3,118.6,0.0,0.03,0.0],[113.4,44.4,98.3,118.8,0.1,0.03,0.0],[113.5,44.6,98.3,118.8,0.1,0.03,0.0],[113.4,44.9,98.3,119.0,0.0,0.03,0.0],[113.3,45.1,98.3,119.2,0.1,0.03,0.0],[113.3,45.3,98.3,119.2,0.1,0.03,0.0],[113.4,45.4,98.3,119.3,0.0,0.03,0.0],[113.5,45.5,98.3,119.3,0.1,0.03,0.0],[113.4,45.6,98.3,119.5,0.1,0.03,0.0],[113.3,45.7,98.3,119.5,0.1,0.03,0.0],[113.3,45.7,98.3,119.5,0.1,0.03,0.0],[113.4,45.6,98.3,119.4,0.0,0.03,0.0],[113.4,45.5,98.3,119.3,0.1,0.03,0.0],[113.4,45.4,98.3,119.3,0.0,0.03,0.0],[113.5,45.2,98.3,119.2,0.0,0.03,0.0],[113.4,45.0,98.3,119.1,0.0,0.03,0.0],[113.5,44.8,98.3,119.0,0.1,0.03,0.0],[113.4,44.6,98.3,118.8,0.1,0.03,0.0],[113.5,44.3,98.3,118.7,0.0,0.03,0.0],[113.5,44.0,98.3,118.5,0.1,0.03,0.0]],"scrub":false},"done_in":{"n":53,"loop":false,"role":"enter","state":"done","events":{"apex":17,"land":36},"frames":[[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.7,38.3,96.4,120.3,-0.1,0.0,-0.0],[120.7,41.2,96.7,121.8,-0.1,0.0,-0.01],[119.7,47.1,97.0,125.7,0.0,0.0,-0.03],[118.0,55.8,97.5,131.2,0.0,0.0,-0.06],[116.2,65.5,97.9,137.2,0.0,0.0,-0.09],[115.0,74.3,98.3,142.2,0.0,0.0,-0.12],[113.5,80.5,98.6,145.1,0.0,0.0,-0.14],[112.4,83.6,98.8,145.8,0.0,0.0,-0.14],[111.1,69.4,98.8,132.5,0.0,0.0,-0.05],[112.9,44.4,98.9,113.3,0.0,0.0,0.07],[112.6,24.1,98.9,97.6,0.0,0.0,0.18],[111.5,8.7,99.0,85.0,0.0,0.0,0.27],[111.3,-8.6,99.0,75.3,0.0,0.0,0.35],[110.0,-25.6,99.0,68.4,0.0,0.0,0.4],[110.1,-31.9,99.0,64.0,0.0,0.0,0.43],[110.0,-33.6,99.0,62.0,0.0,0.0,0.45],[110.0,-32.7,99.1,61.9,0.0,0.0,0.45],[110.4,-30.5,100.0,62.1,1.0,0.0,0.45],[110.8,-23.9,101.6,62.8,2.6,0.0,0.44],[101.3,-15.2,103.2,64.0,4.3,0.0,0.43],[97.8,-11.1,103.9,65.7,5.2,0.0,0.41],[95.9,-10.6,104.1,67.8,5.0,0.0,0.39],[99.2,-11.9,103.4,70.3,3.9,0.0,0.36],[119.5,-16.2,101.2,73.0,1.8,0.0,0.33],[120.6,-27.2,98.1,75.8,-0.6,0.0,0.29],[119.9,-29.7,95.4,78.5,-2.5,0.0,0.26],[127.1,-28.0,94.2,81.2,-3.3,0.0,0.24],[139.3,-21.4,94.0,83.2,-3.3,0.0,0.22],[137.3,-5.6,94.9,84.8,-2.5,0.0,0.2],[117.7,4.7,97.2,86.0,-1.0,0.0,0.19],[111.3,12.3,99.7,86.7,0.5,0.0,0.18],[97.7,13.9,100.8,87.0,1.0,0.0,0.18],[112.1,12.9,100.8,88.4,0.9,0.0,0.18],[112.5,17.2,100.6,95.7,0.6,0.0,0.14],[115.8,29.4,100.1,109.5,0.3,0.0,0.09],[111.3,57.6,99.0,130.0,0.0,0.0,0.0],[119.3,36.2,99.0,111.6,0.0,0.0,0.0],[122.0,15.7,99.0,100.6,0.0,0.0,0.0],[123.4,5.8,99.0,95.2,0.0,0.0,0.0],[121.4,4.0,99.0,93.8,0.0,0.0,0.0],[120.4,1.1,99.0,94.9,0.0,0.0,0.0],[118.5,-2.9,99.0,96.8,0.0,0.0,0.0],[113.1,-1.0,99.0,98.2,0.0,0.0,0.0],[113.7,-0.6,99.0,98.4,0.0,0.0,0.0],[114.8,-0.2,99.0,98.6,0.0,0.0,0.0],[115.1,4.0,99.0,99.0,0.0,0.0,0.0],[114.9,8.1,99.0,99.4,0.0,0.0,0.0],[113.4,11.2,99.0,99.8,0.0,0.0,0.0],[113.0,12.9,99.0,100.2,0.0,0.0,0.0],[113.5,13.2,99.0,100.6,0.0,0.0,0.0],[114.3,12.5,99.0,100.8,0.0,0.0,0.0],[115.5,11.2,99.0,100.9,0.0,0.0,0.0]],"scrub":false},"done_rest":{"n":86,"loop":true,"role":"rest","state":"done","events":{},"frames":[[116.1,9.7,99.0,100.9,0.0,0.0,0.0],[115.2,9.6,99.2,100.8,0.0,0.0,0.0],[114.6,9.4,99.5,100.7,0.3,0.0,0.0],[114.1,9.2,99.8,100.6,0.3,0.0,0.0],[113.6,9.0,100.0,100.5,0.3,0.0,0.0],[113.3,8.8,100.2,100.4,0.3,0.0,0.0],[112.6,8.7,100.4,100.3,0.5,0.0,0.0],[112.3,8.5,100.6,100.2,0.5,0.0,0.0],[112.0,8.3,100.8,100.1,0.6,0.0,0.0],[111.8,8.2,101.0,100.0,0.8,0.0,0.0],[111.5,7.8,101.0,99.8,0.6,0.0,0.0],[111.3,7.2,101.2,99.2,0.8,0.0,0.01],[111.1,6.5,101.2,98.8,0.8,0.0,0.01],[110.9,5.7,101.3,98.2,0.9,0.0,0.01],[110.7,4.9,101.3,97.8,0.8,0.0,0.02],[110.6,4.1,101.3,97.3,1.0,0.0,0.02],[110.6,3.3,101.3,96.8,0.8,0.0,0.02],[110.6,2.7,101.3,96.5,0.8,0.0,0.02],[110.8,2.1,101.2,96.0,0.8,0.0,0.03],[110.8,1.6,101.2,95.7,1.0,0.0,0.03],[110.9,1.2,101.2,95.4,1.0,0.0,0.03],[111.0,0.8,101.0,95.0,0.8,0.0,0.03],[111.6,0.4,101.0,94.8,0.8,0.0,0.04],[111.6,0.1,100.8,94.5,0.8,0.0,0.04],[112.0,-0.2,100.8,94.3,0.8,0.0,0.04],[112.0,-0.4,100.7,94.2,0.8,0.0,0.04],[112.6,-0.7,100.5,94.0,0.6,0.0,0.04],[113.1,-0.9,100.4,93.8,0.6,0.0,0.04],[112.9,-1.0,100.3,93.7,0.6,0.0,0.05],[113.1,-1.1,100.2,93.7,0.5,0.0,0.05],[113.6,-1.2,100.0,93.6,0.5,0.0,0.05],[113.8,-1.2,100.0,93.5,0.3,0.0,0.05],[114.1,-1.2,99.8,93.5,0.3,0.0,0.05],[114.0,-1.1,99.8,93.5,0.3,0.0,0.05],[114.2,-1.0,99.7,93.5,0.2,0.0,0.05],[114.6,-0.9,99.5,93.6,0.3,0.0,0.05],[114.7,-0.7,99.5,93.7,0.2,0.0,0.05],[114.8,-0.3,99.4,94.0,0.2,0.0,0.05],[115.1,0.5,99.3,94.7,0.2,0.0,0.05],[114.9,2.0,99.2,95.8,0.0,0.0,0.04],[115.6,4.0,99.2,97.3,0.0,0.0,0.03],[115.3,6.8,99.2,99.2,0.2,0.0,0.03],[115.5,10.3,99.1,101.6,0.0,0.0,0.02],[115.9,14.4,99.0,104.3,0.0,0.0,0.0],[115.7,16.7,98.9,105.0,0.0,0.0,0.0],[115.6,17.7,98.8,104.7,0.0,0.0,0.0],[115.5,17.4,98.8,104.0,0.0,0.0,0.0],[115.3,16.1,98.8,103.1,0.0,0.0,0.0],[115.5,14.1,98.7,102.2,-0.2,0.0,0.0],[116.2,12.1,98.7,101.7,0.0,0.0,0.0],[117.1,10.6,98.5,101.5,-0.2,0.0,0.0],[116.9,9.7,98.5,101.7,-0.2,0.0,0.0],[117.1,9.5,98.3,101.8,-0.2,0.0,0.0],[117.6,9.7,98.2,101.8,-0.3,0.0,0.0],[117.8,10.3,98.2,101.9,-0.3,0.0,0.0],[117.7,11.0,98.0,102.0,-0.3,0.0,0.0],[117.7,11.7,98.0,102.0,-0.3,0.0,0.0],[117.7,12.1,97.8,102.1,-0.3,0.0,0.0],[118.0,12.3,97.7,102.2,-0.5,0.0,0.0],[118.1,12.3,97.5,102.2,-0.5,0.0,0.0],[118.2,12.1,97.4,102.2,-0.5,0.0,0.0],[118.7,11.9,97.3,102.2,-0.5,0.0,0.0],[119.4,11.7,97.2,102.3,-0.6,0.0,0.0],[119.6,11.5,97.0,102.3,-0.6,0.0,0.0],[119.8,11.4,97.0,102.3,-0.6,0.0,0.0],[120.2,11.4,96.8,102.3,-0.6,0.0,0.0],[120.3,11.4,96.7,102.3,-0.6,0.0,0.0],[120.4,11.5,96.7,102.3,-0.6,0.0,0.0],[120.4,11.5,96.6,102.2,-0.8,0.0,0.0],[120.5,11.5,96.6,102.2,-0.8,0.0,0.0],[120.6,11.5,96.6,102.2,-0.8,0.0,0.0],[120.4,11.4,96.6,102.2,-0.8,0.0,0.0],[120.4,11.4,96.6,102.2,-0.8,0.0,0.0],[119.9,11.3,96.6,102.0,-0.8,0.0,0.0],[119.6,11.2,96.7,102.0,-0.8,0.0,0.0],[119.6,11.1,96.8,102.0,-0.8,0.0,0.0],[119.6,11.0,96.8,101.9,-0.6,0.0,0.0],[119.6,10.9,97.0,101.8,-0.6,0.0,0.0],[119.5,10.8,97.2,101.7,-0.6,0.0,0.0],[119.0,10.7,97.3,101.7,-0.5,0.0,0.0],[118.9,10.6,97.5,101.6,-0.5,0.0,0.0],[118.7,10.5,97.7,101.4,-0.5,0.0,0.0],[118.2,10.4,97.9,101.3,-0.5,0.0,0.0],[118.1,10.2,98.2,101.2,-0.2,0.0,0.0],[117.7,10.1,98.4,101.2,-0.2,0.0,0.0],[116.9,9.9,98.7,101.0,-0.2,0.0,0.0]],"scrub":false},"done_wiggle":{"n":67,"loop":false,"role":"beat","state":"done","events":{},"frames":[[116.5,9.6,99.0,100.9,0.0,0.0,0.0],[116.5,9.4,99.0,100.8,0.0,0.0,0.0],[116.5,9.2,99.0,100.6,0.0,0.0,0.0],[116.3,9.0,99.0,100.5,0.0,0.0,0.0],[116.5,8.7,99.0,100.4,0.0,0.0,0.0],[116.5,8.4,99.0,100.3,0.0,0.0,0.0],[116.7,8.1,99.0,100.2,0.0,0.0,0.0],[116.6,7.9,99.0,100.1,0.0,0.0,0.0],[116.2,7.6,99.0,100.0,0.0,0.0,0.0],[116.6,7.5,99.0,99.9,0.0,0.0,0.0],[116.2,7.3,99.0,99.8,0.0,0.0,0.0],[116.4,7.1,99.5,99.7,0.3,0.0,0.0],[115.7,6.9,100.9,99.7,0.8,0.0,0.0],[114.9,6.8,102.7,99.7,1.4,0.0,0.0],[113.2,6.9,104.1,99.6,2.0,0.0,0.0],[110.2,7.2,104.8,99.6,2.3,0.0,0.0],[106.1,7.7,104.8,99.6,2.3,0.0,0.0],[103.9,8.1,104.4,99.6,2.1,0.0,0.0],[102.8,8.5,103.2,99.6,1.6,0.0,0.0],[103.2,8.7,101.0,99.5,0.8,0.0,0.0],[105.4,8.6,98.5,99.5,-0.2,0.0,0.0],[109.6,8.1,96.0,99.7,-1.1,0.0,0.0],[116.3,7.4,94.2,99.8,-1.8,0.0,0.0],[120.9,6.4,93.3,99.8,-2.1,0.0,0.0],[129.6,3.8,93.2,99.9,-2.3,0.0,0.0],[136.3,2.1,93.3,100.0,-2.3,0.0,0.0],[138.3,1.3,94.2,100.0,-1.8,0.0,0.0],[137.2,1.4,96.0,100.2,-1.1,0.0,0.0],[136.0,2.5,98.5,100.2,-0.3,0.0,0.0],[127.2,4.6,101.1,100.3,0.8,0.0,0.0],[116.6,7.5,103.2,100.5,1.6,0.0,0.0],[110.8,9.2,104.5,100.7,2.1,0.0,0.0],[103.6,10.5,104.8,100.8,2.3,0.0,0.0],[99.7,11.6,104.8,100.9,2.3,0.0,0.0],[98.0,11.9,104.4,101.1,2.1,0.0,0.0],[98.1,12.1,103.2,101.1,1.6,0.0,0.0],[100.4,12.6,101.4,101.2,0.8,0.0,0.0],[104.1,12.3,99.3,101.3,0.2,0.0,0.0],[109.3,11.7,97.3,101.5,-0.6,0.0,0.0],[116.7,11.1,96.0,101.7,-1.1,0.0,0.0],[121.8,9.8,95.4,101.7,-1.3,0.0,0.0],[128.3,7.9,95.3,101.8,-1.4,0.0,0.0],[132.3,6.9,95.5,101.9,-1.3,0.0,0.0],[133.5,6.8,95.9,102.1,-1.1,0.0,0.0],[131.3,7.5,96.8,102.0,-0.8,0.0,0.0],[126.7,8.7,97.7,102.2,-0.5,0.0,0.0],[120.9,10.4,98.5,102.2,-0.2,0.0,0.0],[116.9,12.0,98.9,102.2,0.0,0.0,0.0],[114.2,12.6,99.0,102.3,0.0,0.0,0.0],[112.4,12.9,99.0,102.3,0.0,0.0,0.0],[110.7,13.1,99.0,102.3,0.0,0.0,0.0],[110.8,13.1,99.0,102.3,0.0,0.0,0.0],[112.4,12.9,99.0,102.3,0.0,0.0,0.0],[113.8,12.7,99.0,102.3,0.0,0.0,0.0],[115.0,12.4,99.0,102.2,0.0,0.0,0.0],[116.4,12.1,99.0,102.2,0.0,0.0,0.0],[116.9,11.8,99.0,102.1,0.0,0.0,0.0],[116.8,11.6,99.0,102.0,0.0,0.0,0.0],[116.9,11.5,99.0,102.0,0.0,0.0,0.0],[116.9,11.3,99.0,101.9,0.0,0.0,0.0],[116.8,11.2,99.0,101.8,0.0,0.0,0.0],[116.4,11.1,99.0,101.7,0.0,0.0,0.0],[116.5,10.9,99.0,101.6,0.0,0.0,0.0],[115.8,10.7,99.0,101.4,0.0,0.0,0.0],[115.7,10.5,99.0,101.3,0.0,0.0,0.0],[115.3,10.3,99.0,101.2,0.0,0.0,0.0],[115.7,10.0,99.0,101.1,0.0,0.0,0.0]],"scrub":false},"done_hop":{"n":58,"loop":false,"role":"beat","state":"done","events":{},"frames":[[116.5,9.6,99.0,100.9,0.0,0.0,0.0],[116.5,9.4,99.0,100.8,0.0,0.0,0.0],[116.6,9.1,99.0,100.6,0.0,0.0,0.0],[116.3,8.9,99.0,100.5,0.0,0.0,0.0],[116.7,8.5,99.0,100.3,0.0,0.0,0.0],[116.5,8.2,99.0,100.2,0.0,0.0,0.0],[116.6,7.9,99.0,100.1,0.0,0.0,0.0],[116.2,7.6,99.0,99.9,0.0,0.0,0.0],[116.6,7.4,99.0,99.8,0.0,0.0,0.0],[116.2,7.2,99.0,99.7,0.0,0.0,0.0],[116.6,7.4,99.0,99.8,0.0,0.0,-0.0],[116.2,11.8,99.0,104.1,0.0,0.0,-0.01],[116.4,24.3,99.0,114.4,0.0,0.0,-0.03],[117.0,41.5,99.0,124.7,0.0,0.0,-0.05],[117.9,49.9,99.0,129.2,0.0,0.0,-0.06],[112.9,46.1,99.0,119.2,0.0,0.0,0.01],[115.0,24.9,99.0,104.7,0.0,0.0,0.11],[115.2,8.9,99.0,93.4,0.0,0.0,0.18],[114.5,-2.1,99.0,85.0,0.0,0.0,0.24],[113.7,-10.6,99.0,79.6,0.0,0.0,0.28],[114.0,-24.3,99.0,77.1,0.0,0.0,0.3],[111.8,-26.4,99.0,77.4,0.0,0.0,0.3],[110.1,-21.7,99.0,80.4,0.0,0.0,0.28],[110.3,-13.3,99.0,86.0,0.0,0.0,0.24],[112.5,-1.2,99.0,94.2,0.0,0.0,0.19],[114.7,14.8,99.0,105.1,0.0,0.0,0.12],[116.8,35.0,99.0,118.8,0.0,0.0,0.04],[113.1,38.7,99.0,114.6,0.0,0.0,0.0],[116.2,19.3,99.0,103.7,0.0,0.0,0.0],[116.7,11.4,99.0,98.9,0.0,0.0,0.0],[114.9,11.1,99.0,98.2,0.0,0.0,0.0],[114.4,11.5,99.0,99.6,0.0,0.0,0.0],[115.4,5.2,99.0,101.2,0.0,0.0,0.0],[114.5,4.0,99.0,101.5,0.0,0.0,0.0],[114.4,4.3,99.0,101.7,0.0,0.0,0.0],[114.5,4.5,99.0,101.8,0.0,0.0,0.0],[115.9,7.0,99.0,101.9,0.0,0.0,0.0],[115.9,10.9,99.0,102.0,0.0,0.0,0.0],[114.8,14.1,99.0,102.1,0.0,0.0,0.0],[114.4,15.9,99.0,102.2,0.0,0.0,0.0],[114.3,16.3,99.0,102.2,0.0,0.0,0.0],[114.6,15.6,99.0,102.3,0.0,0.0,0.0],[114.9,14.2,99.0,102.3,0.0,0.0,0.0],[115.7,12.8,99.0,102.3,0.0,0.0,0.0],[116.2,11.6,99.0,102.3,0.0,0.0,0.0],[116.1,10.9,99.0,102.3,0.0,0.0,0.0],[115.9,10.7,99.0,102.2,0.0,0.0,0.0],[116.0,10.9,99.0,102.2,0.0,0.0,0.0],[116.0,11.3,99.0,102.1,0.0,0.0,0.0],[116.2,11.8,99.0,102.0,0.0,0.0,0.0],[116.3,12.0,99.0,101.9,0.0,0.0,0.0],[115.6,12.1,99.0,101.8,0.0,0.0,0.0],[115.6,11.9,99.0,101.7,0.0,0.0,0.0],[115.9,11.5,99.0,101.6,0.0,0.0,0.0],[116.1,11.0,99.0,101.4,0.0,0.0,0.0],[116.2,10.5,99.0,101.3,0.0,0.0,0.0],[116.3,10.0,99.0,101.1,0.0,0.0,0.0],[116.4,9.6,99.0,101.0,0.0,0.0,0.0]],"scrub":false},"needs_in":{"n":19,"loop":false,"role":"enter","state":"needs","events":{"contact":11},"frames":[[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.6,39.3,96.2,122.2,-0.1,0.01,-0.01],[121.9,44.7,96.2,127.5,-0.1,0.04,-0.04],[123.3,50.2,96.3,133.0,0.0,0.1,-0.09],[123.6,53.2,96.5,136.7,0.0,0.17,-0.16],[124.3,55.2,96.8,140.6,0.1,0.27,-0.25],[125.0,56.3,97.0,144.9,0.1,0.39,-0.35],[128.2,55.8,97.3,150.1,0.1,0.53,-0.48],[129.8,53.6,97.8,156.1,0.1,0.69,-0.63],[131.2,49.2,98.3,163.4,0.1,0.88,-0.8],[132.3,43.0,99.0,172.9,0.0,1.08,-0.98],[134.2,73.3,99.0,198.6,0.0,1.08,-1.0],[134.9,88.5,99.0,207.8,0.0,1.07,-1.0],[129.8,80.4,99.0,196.1,0.0,1.07,-1.0],[127.2,74.8,99.0,189.0,0.0,1.07,-1.0],[127.8,69.4,99.0,185.4,0.0,1.07,-1.0],[127.8,66.3,99.0,184.4,0.0,1.07,-1.0],[129.4,62.7,99.0,184.9,0.0,1.07,-1.0],[130.4,60.4,99.0,186.1,0.0,1.07,-1.0]],"scrub":false},"needs_rest":{"n":96,"loop":true,"role":"rest","state":"needs","events":{"contact":[15,22]},"frames":[[130.9,63.3,99.0,186.9,0.0,1.07,-1.0],[130.9,63.2,99.0,186.8,0.0,1.07,-1.0],[130.9,63.1,99.0,186.8,0.0,1.07,-1.0],[130.9,63.0,99.0,186.7,0.0,1.07,-1.0],[130.4,62.9,99.0,186.6,0.0,1.07,-1.0],[130.9,62.7,99.0,186.6,0.0,1.07,-1.0],[130.9,62.6,99.0,186.5,0.0,1.07,-1.0],[131.0,62.5,99.0,186.4,0.0,1.07,-1.0],[132.0,62.2,98.5,181.2,0.0,1.0,-1.0],[131.5,62.0,98.1,176.4,0.1,0.92,-1.0],[128.5,62.0,97.8,173.1,0.1,0.87,-1.0],[125.2,62.2,97.4,171.2,0.1,0.84,-1.0],[122.6,62.6,97.2,170.6,0.2,0.83,-1.0],[122.1,64.8,96.8,173.7,0.3,0.86,-1.0],[122.4,70.1,96.4,183.3,0.4,0.94,-1.0],[125.4,81.4,95.8,201.3,0.6,1.07,-1.0],[125.6,77.6,95.8,188.8,0.5,0.99,-1.0],[127.1,72.5,96.0,177.6,0.4,0.9,-1.0],[126.9,68.8,95.9,171.8,0.4,0.86,-1.0],[127.1,66.0,95.8,170.8,0.3,0.85,-1.0],[127.1,66.2,95.7,175.7,0.5,0.89,-1.0],[127.6,71.6,95.2,187.4,0.5,0.98,-1.0],[130.2,83.0,94.7,204.1,0.8,1.09,-1.0],[132.2,82.7,94.6,203.0,0.8,1.09,-1.0],[134.0,80.7,94.7,198.9,0.8,1.08,-1.0],[137.0,76.2,94.7,193.2,0.7,1.07,-1.0],[136.3,70.6,94.8,188.2,0.6,1.07,-1.0],[136.7,65.8,94.8,186.1,0.6,1.07,-1.0],[138.6,62.3,94.8,185.8,0.6,1.07,-1.0],[140.2,59.3,94.8,185.9,0.5,1.07,-1.0],[139.1,57.6,94.8,185.9,0.6,1.07,-1.0],[135.5,57.2,94.8,185.9,0.6,1.07,-1.0],[133.8,57.8,94.7,185.9,0.6,1.07,-1.0],[133.5,59.1,94.7,186.1,0.6,1.07,-1.0],[133.1,60.6,94.8,186.1,0.6,1.07,-1.0],[132.5,61.8,94.8,186.2,0.6,1.07,-1.0],[132.1,62.7,94.8,186.2,0.6,1.07,-1.0],[133.9,63.0,94.8,186.2,0.6,1.07,-1.0],[134.4,62.9,94.8,186.2,0.6,1.07,-1.0],[135.5,62.5,94.8,186.3,0.6,1.07,-1.0],[135.5,62.0,94.8,186.3,0.6,1.07,-1.0],[135.7,61.6,94.8,186.4,0.6,1.07,-1.0],[135.9,61.4,94.8,186.4,0.6,1.07,-1.0],[135.3,61.4,94.8,186.6,0.6,1.07,-1.0],[135.9,61.5,94.8,186.7,0.6,1.07,-1.0],[135.4,61.8,94.8,186.7,0.6,1.07,-1.0],[121.6,65.8,97.9,186.8,0.2,1.07,-1.0],[111.0,67.3,102.1,186.8,-0.4,1.07,-1.0],[112.6,67.5,103.2,186.8,-0.6,1.07,-1.0],[117.3,67.6,103.3,186.9,-0.6,1.07,-1.0],[120.2,66.2,103.3,187.1,-0.6,1.07,-1.0],[126.0,64.6,103.3,187.1,-0.6,1.07,-1.0],[127.9,63.4,103.2,187.2,-0.6,1.07,-1.0],[129.9,62.7,103.2,187.2,-0.6,1.07,-1.0],[129.6,62.4,103.2,187.2,-0.6,1.07,-1.0],[129.6,62.5,103.2,187.3,-0.6,1.07,-1.0],[130.2,62.8,103.2,187.4,-0.7,1.07,-1.0],[129.3,63.4,103.2,187.4,-0.6,1.07,-1.0],[128.0,64.0,103.2,187.5,-0.7,1.07,-1.0],[127.9,64.7,103.2,187.6,-0.6,1.07,-1.0],[127.0,65.2,103.2,187.7,-0.6,1.07,-1.0],[132.4,62.3,100.2,187.7,-0.2,1.07,-1.0],[133.1,62.1,99.2,187.7,0.0,1.07,-1.0],[133.9,63.0,99.0,187.8,0.0,1.07,-1.0],[133.0,64.0,99.0,187.8,0.0,1.07,-1.0],[131.0,65.0,99.0,187.8,0.0,1.07,-1.0],[129.8,65.6,99.0,187.9,0.0,1.07,-1.0],[128.4,66.0,99.0,187.9,0.0,1.07,-1.0],[127.6,66.2,99.0,187.9,0.0,1.07,-1.0],[127.5,66.2,99.0,187.9,0.0,1.07,-1.0],[128.2,66.1,99.0,187.9,0.0,1.07,-1.0],[129.0,65.9,99.0,187.9,0.0,1.07,-1.0],[130.7,65.6,99.0,187.9,0.0,1.07,-1.0],[130.4,65.4,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.7,64.9,99.0,187.9,0.0,1.07,-1.0],[130.8,64.8,99.0,187.9,0.0,1.07,-1.0],[130.9,64.7,99.0,187.9,0.0,1.07,-1.0],[130.9,64.7,99.0,187.9,0.0,1.07,-1.0],[130.7,64.7,99.0,187.8,0.0,1.07,-1.0],[130.6,64.7,99.0,187.8,0.0,1.07,-1.0],[130.7,64.7,99.0,187.8,0.0,1.07,-1.0],[130.8,64.7,99.0,187.7,0.0,1.07,-1.0],[130.9,64.7,99.0,187.7,0.0,1.07,-1.0],[131.0,64.6,99.0,187.6,0.0,1.07,-1.0],[130.7,64.6,99.0,187.6,0.0,1.07,-1.0],[131.1,64.5,99.0,187.5,0.0,1.07,-1.0],[131.1,64.4,99.0,187.5,0.0,1.07,-1.0],[131.1,64.3,99.0,187.4,0.0,1.07,-1.0],[130.7,64.2,99.0,187.4,0.0,1.07,-1.0],[130.5,64.1,99.0,187.3,0.0,1.07,-1.0],[131.0,63.9,99.0,187.2,0.0,1.07,-1.0],[130.9,63.8,99.0,187.2,0.0,1.07,-1.0],[130.9,63.7,99.0,187.1,0.0,1.07,-1.0],[130.9,63.5,99.0,187.0,0.0,1.07,-1.0],[130.9,63.4,99.0,187.0,0.0,1.07,-1.0]],"scrub":false},"needs_slide":{"n":77,"loop":false,"role":"beat","state":"needs","events":{},"frames":[[130.9,63.3,99.0,186.9,0.0,1.07,-1.0],[130.9,63.2,99.0,186.8,0.0,1.07,-1.0],[130.9,63.1,99.0,186.7,0.0,1.07,-1.0],[130.9,62.9,99.0,186.7,0.0,1.07,-1.0],[130.9,62.8,99.0,186.6,0.0,1.07,-1.0],[130.9,62.6,99.0,186.5,0.0,1.07,-1.0],[130.9,62.5,99.0,186.4,0.0,1.07,-1.0],[131.0,62.3,99.0,186.3,0.0,1.07,-1.0],[131.0,62.2,99.0,186.3,0.0,1.07,-1.0],[131.0,62.2,99.0,186.3,0.0,1.07,-1.0],[130.5,62.5,99.0,186.6,0.0,1.07,-1.01],[131.1,63.0,99.0,187.1,0.0,1.07,-1.01],[131.1,64.0,99.0,188.0,0.0,1.07,-1.02],[131.2,65.5,99.0,189.2,0.0,1.07,-1.04],[131.2,67.5,99.0,190.7,0.0,1.07,-1.06],[130.6,70.1,99.0,192.6,0.0,1.07,-1.08],[130.1,73.1,99.0,194.7,0.0,1.07,-1.1],[130.2,76.5,99.0,197.0,0.0,1.07,-1.13],[129.7,80.2,99.0,199.6,0.0,1.07,-1.16],[128.7,84.1,99.0,202.2,0.0,1.07,-1.19],[127.9,88.0,99.0,204.8,0.0,1.07,-1.22],[127.4,91.9,99.0,207.4,0.0,1.07,-1.26],[127.0,95.5,99.0,209.9,0.0,1.07,-1.28],[125.3,98.9,99.0,212.2,0.0,1.07,-1.31],[124.4,101.9,99.0,214.3,0.0,1.07,-1.33],[123.6,104.5,99.0,216.1,0.0,1.07,-1.36],[123.3,106.6,99.0,217.5,0.0,1.07,-1.37],[123.3,108.2,99.0,218.6,0.0,1.07,-1.38],[123.3,109.3,99.0,219.4,0.0,1.07,-1.39],[123.3,110.0,99.0,219.9,0.0,1.07,-1.4],[123.3,110.3,99.0,220.2,0.0,1.07,-1.4],[123.6,110.4,99.0,220.3,0.0,1.07,-1.4],[123.4,110.3,99.0,220.3,0.0,1.07,-1.4],[123.7,110.3,99.0,220.4,0.0,1.07,-1.4],[123.5,110.2,99.0,220.5,0.0,1.07,-1.4],[123.5,110.2,99.0,220.6,0.0,1.07,-1.4],[123.8,110.3,99.0,220.7,0.0,1.07,-1.4],[123.5,110.4,99.0,220.7,0.0,1.07,-1.4],[123.7,110.6,99.0,220.8,0.0,1.07,-1.4],[123.7,110.8,99.0,220.9,0.0,1.07,-1.4],[123.7,111.0,99.0,221.0,0.0,1.07,-1.4],[123.7,111.2,99.0,221.1,0.0,1.07,-1.4],[123.7,111.3,99.0,221.2,0.0,1.07,-1.4],[123.8,111.2,99.0,221.2,0.0,1.07,-1.4],[122.1,101.0,99.0,210.1,0.0,1.07,-1.27],[121.1,89.0,99.0,199.5,0.0,1.07,-1.14],[122.0,77.9,99.0,192.1,0.0,1.07,-1.05],[124.6,67.9,99.0,187.3,0.0,1.07,-1.0],[130.0,59.9,99.0,184.7,0.0,1.07,-0.96],[135.2,54.8,99.0,183.7,0.0,1.07,-0.95],[140.6,52.8,99.0,184.0,0.0,1.07,-0.95],[140.7,53.8,99.0,185.0,0.0,1.07,-0.97],[140.1,56.7,99.0,186.3,0.0,1.07,-0.98],[138.9,60.5,99.0,187.4,0.0,1.07,-0.99],[137.8,63.9,99.0,187.9,0.0,1.07,-1.0],[134.0,66.3,99.0,187.9,0.0,1.07,-1.0],[130.0,67.7,99.0,187.9,0.0,1.07,-1.0],[129.0,68.1,99.0,187.9,0.0,1.07,-1.0],[128.8,67.8,99.0,187.9,0.0,1.07,-1.0],[128.8,66.9,99.0,187.9,0.0,1.07,-1.0],[129.6,65.9,99.0,187.9,0.0,1.07,-1.0],[129.9,65.0,99.0,187.9,0.0,1.07,-1.0],[130.3,64.3,99.0,187.9,0.0,1.07,-1.0],[131.4,64.0,99.0,187.8,0.0,1.07,-1.0],[131.6,64.0,99.0,187.8,0.0,1.07,-1.0],[131.7,64.2,99.0,187.8,0.0,1.07,-1.0],[133.4,64.4,99.0,187.7,0.0,1.07,-1.0],[132.0,64.6,99.0,187.6,0.0,1.07,-1.0],[131.3,64.7,99.0,187.6,0.0,1.07,-1.0],[130.8,64.7,99.0,187.5,0.0,1.07,-1.0],[130.8,64.5,99.0,187.5,0.0,1.07,-1.0],[130.9,64.3,99.0,187.4,0.0,1.07,-1.0],[130.4,64.1,99.0,187.3,0.0,1.07,-1.0],[130.4,63.9,99.0,187.2,0.0,1.07,-1.0],[130.5,63.7,99.0,187.1,0.0,1.07,-1.0],[131.0,63.5,99.0,187.1,0.0,1.07,-1.0],[130.5,63.4,99.0,187.0,0.0,1.07,-1.0]],"scrub":false},"needs_tap":{"n":58,"loop":false,"role":"beat","state":"needs","events":{"contact":[13,19,25]},"frames":[[130.9,63.3,99.0,186.9,0.0,1.07,-1.0],[130.9,63.2,99.0,186.8,0.0,1.07,-1.0],[130.9,63.0,99.0,186.7,0.0,1.07,-1.0],[130.9,62.8,99.0,186.6,0.0,1.07,-1.0],[130.9,62.6,99.0,186.5,0.0,1.07,-1.0],[130.9,62.4,99.0,186.4,0.0,1.07,-1.0],[130.9,62.2,99.0,186.3,0.0,1.07,-1.0],[130.4,62.1,99.0,186.2,0.0,1.07,-1.0],[129.7,64.2,99.0,184.5,0.0,1.0,-1.0],[128.9,66.0,99.0,183.1,0.0,0.94,-1.0],[128.4,66.9,99.0,182.3,0.0,0.91,-1.0],[128.3,67.1,99.0,182.1,0.0,0.9,-1.0],[128.8,65.9,99.0,182.9,0.0,0.94,-1.0],[130.4,62.8,99.0,185.0,0.0,1.03,-1.0],[130.4,62.8,99.0,185.0,0.0,1.03,-1.0],[129.5,65.3,99.0,183.2,0.0,0.95,-1.0],[128.5,66.7,99.0,182.3,0.0,0.91,-1.0],[128.8,67.0,99.0,182.1,0.0,0.9,-1.0],[129.3,65.9,99.0,182.9,0.0,0.94,-1.0],[130.4,63.0,99.0,185.1,0.0,1.03,-1.0],[130.4,63.1,99.0,185.1,0.0,1.03,-1.0],[129.5,65.7,99.0,183.4,0.0,0.95,-1.0],[128.5,67.2,99.0,182.6,0.0,0.91,-1.0],[128.8,67.6,99.0,182.5,0.0,0.9,-1.0],[128.8,66.7,99.0,183.4,0.0,0.94,-1.0],[130.1,63.9,99.0,185.6,0.0,1.03,-1.0],[131.3,62.1,99.0,187.1,0.0,1.09,-1.0],[131.2,62.4,99.0,187.2,0.0,1.08,-1.0],[130.9,62.7,99.0,187.1,0.0,1.08,-1.0],[131.0,63.2,99.0,187.1,0.0,1.07,-1.0],[131.0,63.5,99.0,187.1,0.0,1.07,-1.0],[130.9,63.8,99.0,187.1,0.0,1.07,-1.0],[130.9,63.9,99.0,187.3,0.0,1.07,-1.0],[130.9,64.1,99.0,187.4,0.0,1.07,-1.0],[130.9,64.3,99.0,187.5,0.0,1.07,-1.0],[130.9,64.5,99.0,187.6,0.0,1.07,-1.0],[130.9,64.6,99.0,187.6,0.0,1.07,-1.0],[130.9,64.7,99.0,187.7,0.0,1.07,-1.0],[130.9,64.9,99.0,187.8,0.0,1.07,-1.0],[130.9,65.0,99.0,187.8,0.0,1.07,-1.0],[130.9,65.0,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.0,99.0,187.9,0.0,1.07,-1.0],[130.9,64.9,99.0,187.8,0.0,1.07,-1.0],[130.9,64.8,99.0,187.7,0.0,1.07,-1.0],[130.9,64.7,99.0,187.7,0.0,1.07,-1.0],[130.9,64.5,99.0,187.6,0.0,1.07,-1.0],[130.9,64.4,99.0,187.5,0.0,1.07,-1.0],[130.9,64.2,99.0,187.4,0.0,1.07,-1.0],[130.9,64.0,99.0,187.3,0.0,1.07,-1.0],[130.9,63.8,99.0,187.2,0.0,1.07,-1.0],[130.9,63.6,99.0,187.1,0.0,1.07,-1.0],[130.9,63.4,99.0,187.0,0.0,1.07,-1.0]],"scrub":false},"approval_in":{"n":22,"loop":false,"role":"enter","state":"approval","events":{"land":8},"frames":[[120.1,38.0,96.2,120.7,-0.1,0.0,0.0],[122.1,46.5,97.0,127.0,-0.1,0.0,-0.1],[121.8,56.0,97.5,132.8,-0.1,0.0,-0.18],[118.2,66.2,98.0,138.1,0.0,0.0,-0.26],[115.2,76.3,98.4,142.8,0.0,0.0,-0.33],[113.6,85.5,98.7,147.0,0.0,0.0,-0.39],[112.9,93.2,98.8,150.5,0.0,0.0,-0.44],[111.8,98.8,99.0,153.4,0.0,0.0,-0.48],[111.0,102.8,99.1,155.6,0.0,0.0,-0.51],[109.9,105.2,99.1,157.2,0.0,0.0,-0.53],[110.0,106.3,99.2,158.1,-0.1,0.0,-0.55],[110.1,106.2,99.2,158.2,0.0,0.0,-0.55],[110.2,105.9,99.2,159.5,0.0,0.0,-0.6],[110.5,106.0,99.2,164.0,0.0,0.0,-0.76],[111.6,106.5,99.2,170.7,0.0,0.0,-0.99],[113.0,107.3,99.2,176.9,0.0,0.0,-1.21],[111.8,108.6,99.1,180.2,0.0,0.0,-1.32],[111.5,109.4,99.1,179.9,0.0,0.0,-1.32],[111.5,108.4,99.1,177.1,0.0,0.0,-1.26],[111.5,107.7,99.0,176.1,0.0,0.0,-1.24],[111.7,106.9,99.0,176.1,0.0,0.0,-1.24],[112.0,106.2,99.0,176.6,0.0,0.0,-1.25]],"scrub":false},"approval_rest":{"n":101,"loop":true,"role":"rest","state":"approval","events":{},"frames":[[111.8,105.5,99.0,176.7,0.0,0.0,-1.25],[111.5,105.4,99.2,176.6,0.0,0.0,-1.25],[111.3,105.3,99.3,176.6,-0.1,0.0,-1.25],[111.0,105.2,99.5,176.4,-0.1,0.0,-1.25],[110.5,105.1,99.7,176.4,-0.3,0.0,-1.25],[110.2,105.0,99.8,176.4,-0.1,0.0,-1.25],[110.0,104.8,100.0,176.3,-0.3,0.0,-1.25],[109.7,104.7,100.2,176.2,-0.3,0.0,-1.25],[109.5,104.6,100.3,176.2,-0.4,0.0,-1.25],[109.3,104.5,100.5,176.1,-0.4,0.0,-1.25],[109.1,104.3,100.5,176.2,-0.4,0.01,-1.25],[109.0,104.1,100.7,176.3,-0.6,0.03,-1.25],[108.7,103.8,100.8,176.4,-0.4,0.04,-1.25],[108.6,103.6,100.9,176.6,-0.6,0.06,-1.25],[108.4,103.3,100.9,176.7,-0.6,0.07,-1.25],[108.3,103.1,101.0,176.8,-0.6,0.08,-1.25],[108.3,103.0,101.1,176.9,-0.6,0.09,-1.25],[108.2,102.8,101.2,176.9,-0.7,0.1,-1.25],[108.2,102.7,101.2,177.0,-0.6,0.11,-1.25],[108.1,102.6,101.2,177.1,-0.7,0.11,-1.25],[108.1,102.5,101.2,177.1,-0.6,0.12,-1.25],[108.2,102.4,101.2,177.1,-0.6,0.12,-1.25],[108.4,102.3,101.2,177.2,-0.7,0.12,-1.25],[108.3,102.3,101.2,177.2,-0.7,0.13,-1.25],[108.6,102.2,101.2,177.2,-0.6,0.13,-1.25],[108.7,102.2,101.0,177.2,-0.6,0.13,-1.25],[108.7,102.2,101.0,177.2,-0.6,0.13,-1.25],[108.8,102.2,100.9,177.2,-0.6,0.13,-1.25],[109.0,102.2,100.9,177.2,-0.4,0.13,-1.25],[109.0,102.3,100.8,177.2,-0.4,0.13,-1.25],[109.1,102.3,100.8,177.3,-0.5,0.13,-1.25],[109.3,102.3,100.7,177.3,-0.5,0.13,-1.25],[109.4,102.4,100.6,177.3,-0.4,0.13,-1.25],[109.7,102.4,100.4,177.3,-0.4,0.13,-1.25],[109.8,102.5,100.4,177.4,-0.4,0.13,-1.25],[109.9,102.6,100.3,177.4,-0.4,0.13,-1.25],[110.2,102.6,100.2,177.5,-0.3,0.13,-1.25],[110.3,102.7,100.0,177.6,-0.4,0.13,-1.25],[110.4,102.8,100.0,177.6,-0.3,0.13,-1.25],[110.6,102.9,99.9,177.6,-0.3,0.13,-1.25],[110.7,103.0,99.8,177.7,-0.3,0.13,-1.25],[110.9,103.1,99.7,177.8,-0.1,0.13,-1.25],[111.0,103.2,99.7,177.9,-0.1,0.13,-1.25],[111.2,103.3,99.6,177.9,-0.1,0.13,-1.25],[111.3,103.4,99.5,177.9,-0.1,0.13,-1.25],[111.4,103.6,99.4,178.1,-0.1,0.13,-1.25],[111.5,103.7,99.3,178.1,0.0,0.13,-1.25],[111.6,103.8,99.2,178.1,-0.1,0.13,-1.25],[111.7,103.9,99.2,178.2,0.0,0.13,-1.25],[111.9,104.0,99.1,178.3,0.0,0.13,-1.25],[112.0,104.2,99.0,178.4,0.0,0.13,-1.25],[112.1,104.3,99.0,178.4,0.0,0.13,-1.25],[112.2,104.4,98.9,178.5,0.0,0.13,-1.25],[112.3,104.5,98.8,178.6,0.0,0.13,-1.25],[112.4,104.6,98.7,178.6,0.1,0.13,-1.25],[112.5,104.7,98.7,178.8,0.1,0.13,-1.25],[112.6,105.7,98.6,177.6,0.1,0.05,-1.25],[112.5,106.2,98.5,177.2,0.1,0.01,-1.25],[112.6,106.4,98.4,177.1,0.1,0.0,-1.25],[113.1,106.5,98.3,177.2,0.1,0.0,-1.25],[113.1,106.6,98.2,177.3,0.3,0.0,-1.25],[113.1,106.6,98.2,177.4,0.1,0.0,-1.25],[113.5,106.7,98.1,177.4,0.3,0.0,-1.25],[114.0,106.8,98.1,177.5,0.3,0.0,-1.25],[114.1,106.9,97.9,177.5,0.3,0.0,-1.25],[114.2,106.9,97.8,177.6,0.4,0.0,-1.25],[114.4,107.0,97.8,177.6,0.3,0.0,-1.25],[114.8,107.1,97.7,177.7,0.4,0.0,-1.25],[114.6,107.1,97.6,177.7,0.4,0.0,-1.25],[115.1,107.2,97.5,177.7,0.4,0.0,-1.25],[115.2,107.2,97.4,177.7,0.6,0.0,-1.25],[115.4,107.2,97.3,177.8,0.4,0.0,-1.25],[115.5,107.2,97.2,177.8,0.4,0.0,-1.25],[115.7,107.3,97.2,177.8,0.4,0.0,-1.25],[115.7,107.3,97.1,177.8,0.6,0.0,-1.25],[115.8,107.3,97.0,177.8,0.6,0.0,-1.25],[115.8,107.3,97.0,177.8,0.6,0.0,-1.25],[116.0,107.3,97.0,177.8,0.7,0.0,-1.25],[116.1,107.3,96.8,177.8,0.7,0.0,-1.25],[116.1,107.2,96.8,177.8,0.7,0.0,-1.25],[116.2,107.2,96.8,177.7,0.6,0.0,-1.25],[116.1,107.2,96.8,177.7,0.6,0.0,-1.25],[116.2,107.1,96.8,177.7,0.6,0.0,-1.25],[116.1,107.1,96.8,177.7,0.7,0.0,-1.25],[115.8,107.0,96.9,177.6,0.6,0.0,-1.25],[115.9,107.0,97.0,177.6,0.6,0.0,-1.25],[115.6,106.9,97.0,177.6,0.7,0.0,-1.25],[115.5,106.9,97.0,177.5,0.6,0.0,-1.25],[115.5,106.8,97.2,177.4,0.4,0.0,-1.25],[115.3,106.7,97.2,177.4,0.6,0.0,-1.25],[115.1,106.6,97.3,177.3,0.4,0.0,-1.25],[114.6,106.5,97.5,177.3,0.6,0.0,-1.25],[114.8,106.5,97.6,177.2,0.4,0.0,-1.25],[114.2,106.4,97.7,177.2,0.3,0.0,-1.25],[114.0,106.3,97.8,177.1,0.3,0.0,-1.25],[113.5,106.2,98.0,177.1,0.3,0.0,-1.25],[113.1,106.1,98.2,177.0,0.3,0.0,-1.25],[112.9,106.0,98.3,176.9,0.1,0.0,-1.25],[112.7,105.8,98.5,176.9,0.1,0.0,-1.25],[112.4,105.7,98.7,176.8,0.0,0.0,-1.25],[112.0,105.6,98.8,176.7,0.0,0.0,-1.25]],"scrub":false},"approval_wobble":{"n":58,"loop":false,"role":"beat","state":"approval","events":{},"frames":[[111.7,105.5,99.0,176.7,0.0,0.0,-1.25],[111.7,105.3,99.0,176.6,0.0,0.0,-1.25],[111.7,105.2,99.0,176.4,0.0,0.0,-1.25],[111.7,105.0,99.0,176.3,0.0,0.0,-1.25],[111.7,104.7,99.0,176.2,0.0,0.0,-1.25],[111.8,104.5,99.0,176.1,0.0,0.0,-1.25],[111.8,104.3,99.0,176.0,0.0,0.0,-1.25],[111.7,104.1,99.0,175.9,0.0,0.0,-1.25],[111.7,104.0,99.0,175.8,0.0,0.0,-1.25],[111.8,103.9,99.0,175.8,0.0,0.0,-1.25],[111.7,103.8,99.0,175.7,0.0,0.0,-1.25],[111.5,103.7,99.2,175.6,-0.1,0.0,-1.25],[111.9,103.5,99.8,175.6,-0.3,0.0,-1.25],[111.6,103.4,100.8,175.6,-0.4,0.0,-1.25],[111.5,103.3,101.8,175.6,-0.7,0.0,-1.25],[109.0,103.4,102.5,175.6,-0.7,0.0,-1.25],[106.5,103.6,102.8,175.6,-0.9,0.0,-1.25],[105.2,103.8,102.8,175.6,-0.9,0.0,-1.25],[104.8,104.0,102.7,175.6,-0.9,0.0,-1.25],[104.6,104.3,102.1,175.7,-0.7,0.0,-1.25],[105.2,104.6,100.8,175.8,-0.4,0.0,-1.25],[107.0,104.8,99.2,175.9,-0.1,0.0,-1.25],[109.9,104.8,97.5,175.9,0.3,0.0,-1.25],[113.0,104.8,96.2,176.0,0.6,0.0,-1.25],[115.4,104.6,95.6,176.1,0.9,0.0,-1.25],[120.5,104.3,95.4,176.2,0.9,0.0,-1.25],[123.7,103.6,95.4,176.3,0.9,0.0,-1.25],[124.3,103.3,95.6,176.4,0.7,0.0,-1.25],[124.4,103.4,96.1,176.6,0.7,0.0,-1.25],[123.0,103.7,96.8,176.7,0.4,0.0,-1.25],[121.5,104.3,97.5,176.8,0.3,0.0,-1.25],[118.6,105.1,98.2,176.9,0.1,0.0,-1.25],[114.2,106.0,98.8,177.1,-0.1,0.0,-1.25],[110.6,106.4,99.2,177.1,-0.1,0.0,-1.25],[109.6,106.8,99.3,177.2,-0.1,0.0,-1.25],[108.8,107.0,99.4,177.4,-0.1,0.0,-1.25],[108.7,107.2,99.4,177.4,-0.1,0.0,-1.25],[109.1,107.3,99.3,177.6,-0.1,0.0,-1.25],[109.8,107.4,99.2,177.6,0.0,0.0,-1.25],[110.5,107.4,99.0,177.7,0.0,0.0,-1.25],[111.1,107.4,99.0,177.7,0.0,0.0,-1.25],[112.6,107.3,99.0,177.7,0.0,0.0,-1.25],[113.5,107.3,99.0,177.8,0.0,0.0,-1.25],[114.2,107.3,99.0,177.8,0.0,0.0,-1.25],[113.7,107.3,99.0,177.8,0.0,0.0,-1.25],[113.4,107.3,99.0,177.8,0.0,0.0,-1.25],[112.9,107.3,99.0,177.7,0.0,0.0,-1.25],[112.2,107.2,99.0,177.7,0.0,0.0,-1.25],[111.3,107.2,99.0,177.6,0.0,0.0,-1.25],[111.2,107.1,99.0,177.6,0.0,0.0,-1.25],[111.1,107.0,99.0,177.5,0.0,0.0,-1.25],[111.3,106.8,99.0,177.4,0.0,0.0,-1.25],[111.1,106.7,99.0,177.3,0.0,0.0,-1.25],[111.3,106.5,99.0,177.2,0.0,0.0,-1.25],[111.7,106.3,99.0,177.1,0.0,0.0,-1.25],[111.7,106.0,99.0,177.0,0.0,0.0,-1.25],[111.7,105.8,99.0,176.9,0.0,0.0,-1.25],[111.7,105.6,99.0,176.7,0.0,0.0,-1.25]],"scrub":false},"approval_hold":{"n":13,"loop":false,"role":"scrub","state":"approval","events":{},"frames":[[111.9,105.5,98.8,176.7,0.0,0.0,-1.25],[111.2,102.7,99.2,174.1,-0.1,0.0,-1.22],[111.8,99.9,98.8,171.4,0.0,0.0,-1.2],[110.3,97.2,99.3,168.8,0.0,0.0,-1.17],[111.6,94.4,98.6,166.1,0.1,0.0,-1.14],[109.9,91.7,99.5,163.6,-0.1,0.0,-1.12],[111.6,88.9,98.4,160.9,0.1,0.0,-1.09],[109.5,86.2,99.5,158.4,-0.1,0.0,-1.06],[112.0,83.4,98.3,155.7,0.0,0.0,-1.04],[109.2,80.8,99.7,153.1,0.0,0.0,-1.01],[112.0,78.0,98.2,150.5,0.0,0.0,-0.98],[108.9,75.4,99.8,147.9,0.0,0.0,-0.96],[112.2,72.6,98.1,145.3,0.0,0.0,-0.93]],"scrub":true},"approval_allow":{"n":24,"loop":false,"role":"react","state":"approval","events":{"launch":7},"frames":[[111.9,72.8,98.1,145.3,0.0,0.0,-0.93],[113.2,78.4,98.1,151.4,0.2,0.0,-0.98],[114.5,98.9,98.0,170.0,0.3,0.0,-1.13],[114.6,127.2,97.8,192.2,0.4,0.0,-1.29],[111.5,95.5,98.0,158.9,0.1,0.0,-0.96],[110.9,65.8,98.0,135.0,0.0,0.0,-0.72],[110.3,47.6,98.0,120.2,-0.2,0.0,-0.56],[110.1,40.4,98.0,114.3,-0.3,0.0,-0.5],[111.2,33.8,97.8,115.0,-0.2,0.0,-0.5],[109.7,32.5,97.8,119.2,-0.2,0.0,-0.54],[110.0,41.9,97.5,127.8,-0.2,0.0,-0.62],[111.9,54.2,97.4,139.0,0.0,0.0,-0.72],[115.0,65.5,97.2,149.6,0.0,0.0,-0.82],[116.6,72.3,97.0,156.9,0.1,0.0,-0.88],[115.8,80.0,96.9,159.8,0.1,0.0,-0.9],[117.2,82.1,96.8,160.4,0.3,0.0,-0.9],[120.2,79.7,96.7,159.6,0.3,0.0,-0.87],[120.4,75.7,96.5,156.3,0.3,0.0,-0.79],[120.5,69.9,96.4,150.4,0.1,0.0,-0.65],[120.7,63.0,96.4,142.9,0.1,0.0,-0.49],[122.3,52.3,96.3,135.1,0.0,0.0,-0.31],[123.4,42.3,96.3,128.2,0.0,0.0,-0.16],[123.0,35.2,96.2,123.3,-0.1,0.0,-0.06],[122.7,32.6,96.2,121.0,-0.1,0.0,-0.01]],"scrub":false},"approval_deny":{"n":24,"loop":false,"role":"react","state":"approval","events":{"drop":4},"frames":[[111.3,105.9,99.0,176.7,0.0,0.0,-1.25],[113.8,127.1,99.0,199.3,0.0,0.0,-1.5],[114.2,135.8,99.0,206.6,0.0,0.0,-1.59],[113.5,139.6,99.0,207.9,0.0,0.0,-1.6],[112.4,142.0,98.9,208.1,0.0,0.0,-1.6],[112.1,143.1,98.8,208.0,0.0,0.0,-1.59],[111.8,142.5,98.8,207.4,0.1,0.0,-1.58],[111.9,140.2,98.7,206.1,0.0,0.0,-1.55],[112.6,136.7,98.6,204.4,0.1,0.0,-1.52],[114.0,132.6,98.4,202.8,0.1,0.0,-1.49],[114.9,128.6,98.2,201.3,0.3,0.0,-1.46],[116.4,125.1,98.1,200.4,0.3,0.0,-1.45],[118.0,122.3,97.8,199.9,0.4,0.0,-1.45],[119.6,119.6,97.7,199.2,0.4,0.0,-1.44],[120.5,115.9,97.4,196.3,0.4,0.0,-1.4],[121.1,110.3,97.2,190.8,0.4,0.0,-1.3],[121.3,102.2,97.0,182.2,0.4,0.0,-1.15],[121.5,91.8,96.8,171.4,0.3,0.0,-0.95],[120.7,79.7,96.6,159.4,0.3,0.0,-0.72],[121.5,66.9,96.5,147.4,0.1,0.0,-0.5],[121.8,54.8,96.3,136.9,0.0,0.0,-0.3],[121.6,44.7,96.3,128.6,-0.1,0.0,-0.15],[122.4,37.6,96.2,123.5,-0.1,0.0,-0.05],[122.4,34.0,96.2,121.0,-0.1,0.0,-0.01]],"scrub":false},"blocked_in":{"n":29,"loop":false,"role":"enter","state":"blocked","events":{"bonk":12},"frames":[[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[121.0,37.0,96.3,117.5,-0.1,0.0,0.04],[122.3,38.6,96.8,115.8,-0.3,0.0,0.08],[120.8,42.9,97.3,115.4,-0.3,0.0,0.11],[117.9,48.6,97.8,115.7,-0.4,0.0,0.14],[116.5,53.7,97.9,115.3,-0.5,0.0,0.17],[112.1,55.5,97.9,114.1,-0.5,0.0,0.19],[108.4,45.4,97.8,103.0,-0.7,0.0,0.21],[105.6,34.3,97.8,94.4,-1.0,0.0,0.22],[104.7,26.6,97.5,88.6,-1.5,0.0,0.23],[104.3,19.0,97.1,85.4,-1.9,0.0,0.24],[104.8,23.1,96.6,96.6,-2.4,0.0,0.2],[104.7,68.3,96.4,133.8,-2.2,0.0,0.06],[104.1,69.0,95.9,138.6,-2.8,0.0,0.04],[114.0,63.8,95.4,138.2,-3.5,0.0,0.04],[114.0,63.0,94.8,136.0,-4.4,0.0,0.03],[111.9,53.9,94.2,132.7,-5.5,0.0,0.02],[109.4,46.3,93.5,129.7,-6.7,0.0,0.01],[107.0,41.4,92.9,128.2,-7.9,0.0,0.0],[104.5,39.8,92.5,128.6,-9.0,0.0,0.0],[105.1,31.7,92.3,129.7,-10.2,0.0,0.0],[104.3,26.4,92.2,130.7,-11.3,0.0,0.0],[101.7,26.7,92.0,131.5,-12.3,0.0,0.0],[99.1,26.9,92.0,132.2,-13.2,0.0,0.0],[97.9,27.4,92.0,132.8,-14.1,0.0,0.0],[96.5,30.6,92.0,133.2,-14.6,0.0,0.0],[96.5,33.5,92.0,133.6,-15.1,0.0,0.0],[95.1,35.6,92.0,133.7,-15.3,0.0,0.0],[94.3,36.4,92.0,133.8,-15.3,0.0,0.0]],"scrub":false},"blocked_rest":{"n":134,"loop":true,"role":"rest","state":"blocked","events":{},"frames":[[94.2,32.8,92.0,133.8,-15.3,0.0,0.0],[94.1,32.9,92.0,133.8,-15.3,0.0,0.0],[94.2,32.9,92.0,133.8,-15.3,0.0,0.0],[94.2,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.2,0.0,0.0],[94.3,32.8,92.0,133.6,-15.2,0.0,0.0],[94.3,32.6,92.0,133.4,-15.2,0.0,0.0],[94.4,32.3,92.0,133.1,-15.1,0.0,0.0],[94.5,31.9,92.0,132.7,-15.0,0.0,0.0],[94.6,31.3,92.0,131.9,-14.7,0.0,0.0],[94.7,30.6,91.9,131.2,-14.5,0.0,0.0],[95.0,29.8,91.9,130.1,-13.9,0.0,0.0],[95.4,28.8,92.0,129.0,-13.6,0.0,0.0],[95.8,27.9,92.0,127.8,-13.2,0.0,0.0],[96.1,26.8,91.9,126.3,-12.7,0.0,0.0],[96.8,25.9,91.9,124.8,-12.2,0.0,0.0],[97.6,24.9,92.0,123.3,-11.7,0.0,0.0],[98.2,24.1,92.1,121.8,-11.2,0.0,0.0],[99.1,23.3,92.2,120.2,-10.6,0.0,0.0],[99.9,22.7,92.2,118.6,-10.0,0.0,0.0],[101.0,22.2,92.3,117.1,-9.5,0.0,0.0],[102.2,21.8,92.5,115.6,-8.9,0.0,0.0],[103.2,21.5,92.7,114.3,-8.4,0.0,0.0],[103.9,21.2,92.8,113.0,-8.0,0.0,0.0],[104.5,21.1,93.0,111.9,-7.6,0.0,0.0],[104.0,21.1,93.1,111.0,-7.2,0.0,0.0],[103.7,21.1,93.2,110.1,-6.8,0.0,0.0],[103.7,21.1,93.3,109.4,-6.8,0.0,0.0],[103.6,21.2,93.5,108.8,-6.4,0.0,0.0],[103.6,21.3,93.5,108.4,-6.2,0.0,0.0],[102.9,21.4,93.5,108.1,-6.2,0.0,0.0],[103.1,21.4,93.6,108.0,-6.1,0.0,0.0],[103.3,21.5,93.6,107.8,-6.1,0.0,0.0],[103.1,21.5,93.6,107.8,-5.9,0.0,0.0],[103.0,21.4,93.6,107.8,-5.9,0.0,0.0],[103.0,21.4,93.6,107.8,-6.1,0.0,0.0],[102.8,21.3,93.6,108.0,-6.1,0.0,0.0],[103.5,21.4,93.6,108.2,-6.2,0.0,0.0],[103.5,21.6,93.5,108.6,-6.2,0.0,0.0],[103.5,22.0,93.4,109.3,-6.5,0.0,0.0],[103.4,22.5,93.3,110.2,-6.8,0.0,0.0],[103.4,23.1,93.2,111.3,-7.2,0.0,0.0],[103.7,24.0,93.0,112.8,-7.6,0.0,0.0],[103.7,25.0,92.8,114.5,-8.1,0.0,0.0],[103.9,26.2,92.7,116.5,-8.8,0.0,0.0],[103.3,27.6,92.6,118.8,-9.4,0.0,0.0],[101.6,29.2,92.5,121.2,-10.2,0.0,0.0],[100.7,31.0,92.4,123.9,-10.9,0.0,0.0],[99.3,33.0,92.4,126.7,-12.0,0.0,0.0],[98.2,35.4,92.5,129.7,-12.8,0.0,0.0],[97.2,37.9,92.5,132.6,-13.8,0.0,0.0],[96.5,40.7,92.7,135.6,-14.8,0.0,0.0],[97.5,43.6,93.0,138.6,-15.6,0.0,0.0],[98.0,46.6,93.2,141.4,-16.5,0.0,0.0],[97.5,49.5,93.5,144.1,-17.4,0.0,0.0],[97.8,52.3,93.8,146.6,-18.3,0.0,0.0],[98.3,55.0,94.2,148.9,-18.9,0.0,0.0],[99.7,57.4,94.4,150.9,-19.6,0.0,0.0],[99.4,59.6,94.7,152.6,-20.2,0.0,0.0],[99.7,61.4,94.9,153.9,-20.6,0.0,0.0],[100.0,62.8,95.2,155.0,-21.0,0.0,0.0],[100.2,63.9,95.2,155.8,-21.2,0.0,0.0],[100.6,64.6,95.3,156.3,-21.4,0.0,0.0],[100.9,64.9,95.4,156.6,-21.5,0.0,0.0],[100.9,65.0,95.4,156.7,-21.5,0.0,0.0],[101.0,64.9,95.4,156.7,-21.7,0.0,0.0],[101.0,64.8,95.4,156.7,-21.7,0.0,0.0],[100.5,64.7,95.4,156.7,-21.7,0.0,0.0],[100.4,64.7,95.4,156.7,-21.7,0.0,0.0],[100.4,64.7,95.4,156.7,-21.7,0.0,0.0],[100.3,64.7,95.4,156.7,-21.7,0.0,0.0],[100.3,64.7,95.4,156.7,-21.7,0.0,0.0],[100.2,64.7,95.4,156.7,-21.7,0.0,0.0],[100.4,64.8,95.4,156.7,-21.7,0.0,0.0],[100.2,64.8,95.4,156.7,-21.7,0.0,0.0],[100.3,64.8,95.4,156.7,-21.7,0.0,0.0],[100.3,64.8,95.4,156.7,-21.7,0.0,0.0],[100.3,64.8,95.4,156.7,-21.7,0.0,0.0],[100.2,64.8,95.4,156.7,-21.7,0.0,0.0],[100.4,64.8,95.4,156.7,-21.7,0.0,0.0],[100.3,64.8,95.4,156.7,-21.6,0.0,0.0],[99.0,64.9,94.8,156.7,-22.2,0.0,0.0],[96.4,65.4,93.3,156.7,-23.5,0.0,0.0],[93.1,66.1,91.2,156.8,-25.4,0.0,0.0],[88.7,66.7,89.0,156.8,-27.2,0.0,0.0],[85.3,66.9,87.5,156.7,-28.7,0.0,0.0],[83.7,66.0,86.8,156.4,-29.1,0.0,0.0],[84.3,64.4,86.8,155.9,-29.2,0.0,0.0],[84.7,62.3,87.6,155.2,-28.2,0.0,0.0],[89.1,59.5,90.1,154.1,-25.7,0.0,0.0],[96.8,56.8,94.1,153.0,-21.7,0.0,0.0],[104.3,55.1,98.2,152.1,-17.5,0.0,0.0],[111.4,53.7,101.3,151.3,-14.1,0.0,0.0],[113.6,52.4,102.8,150.5,-12.4,0.0,0.0],[111.4,51.7,102.8,149.5,-11.9,0.0,0.0],[113.9,51.1,102.4,148.3,-11.9,0.0,0.0],[113.6,50.5,101.2,147.1,-12.8,0.0,0.0],[111.2,49.8,99.2,145.8,-14.4,0.0,0.0],[107.0,48.8,97.0,144.6,-16.5,0.0,0.0],[102.6,47.2,95.1,143.4,-18.2,0.0,0.0],[99.0,45.0,94.1,142.4,-18.9,0.0,0.0],[96.6,42.5,93.8,141.4,-19.1,0.0,0.0],[94.6,40.1,93.8,140.5,-18.9,0.0,0.0],[92.7,38.0,93.7,139.6,-18.7,0.0,0.0],[95.0,36.2,93.5,138.7,-18.5,0.0,0.0],[94.9,34.7,93.3,137.8,-18.0,0.0,0.0],[95.8,33.6,93.0,136.8,-17.4,0.0,0.0],[96.3,32.8,92.8,136.0,-17.0,0.0,0.0],[95.8,32.3,92.6,135.2,-16.4,0.0,0.0],[95.7,32.1,92.3,134.7,-16.0,0.0,0.0],[96.3,32.2,92.2,134.2,-15.6,0.0,0.0],[95.9,32.5,92.1,133.9,-15.4,0.0,0.0],[94.6,32.8,92.1,133.8,-15.4,0.0,0.0],[94.5,33.1,92.0,133.8,-15.3,0.0,0.0],[95.1,33.4,92.0,133.8,-15.3,0.0,0.0],[95.3,33.5,92.0,133.8,-15.3,0.0,0.0],[95.3,33.5,92.0,133.8,-15.3,0.0,0.0],[95.1,33.4,92.0,133.8,-15.3,0.0,0.0],[94.9,33.2,92.0,133.8,-15.3,0.0,0.0],[94.7,33.1,92.0,133.8,-15.3,0.0,0.0],[94.5,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.8,92.0,133.8,-15.3,0.0,0.0],[94.2,32.8,92.0,133.8,-15.3,0.0,0.0],[94.2,32.7,92.0,133.8,-15.3,0.0,0.0],[94.1,32.7,92.0,133.8,-15.3,0.0,0.0],[94.0,32.8,92.0,133.8,-15.3,0.0,0.0],[94.0,32.8,92.0,133.8,-15.3,0.0,0.0]],"scrub":false},"blocked_try":{"n":77,"loop":false,"role":"beat","state":"blocked","events":{"bonk":24},"frames":[[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.4,32.4,92.0,133.1,-15.1,0.0,0.0],[94.9,30.8,92.0,130.8,-14.1,0.0,0.01],[96.0,28.0,92.1,126.6,-12.7,0.0,0.03],[97.9,24.3,92.4,120.7,-10.6,0.0,0.05],[100.5,20.2,93.2,113.7,-8.3,0.0,0.08],[104.1,16.5,94.2,106.3,-5.9,0.0,0.11],[108.6,14.2,95.5,99.8,-3.6,0.0,0.14],[111.3,13.9,96.9,94.4,-2.1,0.0,0.17],[112.0,15.2,98.0,90.7,-0.9,0.0,0.19],[106.0,15.0,98.8,88.7,-0.2,0.0,0.2],[107.4,16.3,99.0,88.0,0.0,0.0,0.2],[110.0,31.6,99.0,102.3,0.0,0.0,0.16],[112.3,61.4,99.0,126.7,0.0,0.0,0.08],[112.7,68.0,99.0,134.7,0.0,0.0,0.06],[112.5,69.1,99.0,134.7,0.0,0.0,0.06],[111.8,70.4,98.9,134.4,-0.1,0.0,0.06],[115.2,66.8,98.8,133.5,-0.3,0.0,0.05],[117.0,63.5,98.7,132.2,-0.4,0.0,0.05],[117.1,59.8,98.5,130.4,-0.5,0.0,0.04],[118.3,55.5,98.3,128.6,-0.7,0.0,0.03],[121.3,47.7,98.2,126.7,-0.9,0.0,0.02],[122.4,41.4,97.8,125.0,-1.2,0.0,0.01],[121.0,37.5,97.6,123.9,-1.6,0.0,0.01],[116.6,35.8,97.2,123.3,-1.9,0.0,0.0],[114.9,35.7,97.0,123.3,-2.5,0.0,0.0],[113.8,36.6,96.5,123.6,-3.0,0.0,0.0],[113.1,37.6,96.2,124.0,-3.4,0.0,0.0],[114.4,38.4,95.9,124.5,-4.1,0.0,0.0],[113.1,38.7,95.6,125.0,-4.7,0.0,0.0],[111.8,38.4,95.2,125.5,-5.3,0.0,0.0],[110.5,37.7,94.9,126.1,-6.0,0.0,0.0],[109.5,36.6,94.6,126.7,-6.6,0.0,0.0],[108.7,35.4,94.2,127.3,-7.4,0.0,0.0],[107.4,34.3,94.0,127.9,-8.1,0.0,0.0],[106.2,33.5,93.7,128.5,-8.7,0.0,0.0],[104.7,33.0,93.5,129.1,-9.4,0.0,0.0],[103.3,32.9,93.2,129.7,-10.2,0.0,0.0],[102.0,33.0,93.0,130.2,-10.9,0.0,0.0],[100.6,33.2,92.9,130.8,-11.6,0.0,0.0],[99.4,33.3,92.7,131.2,-12.1,0.0,0.0],[98.3,33.4,92.6,131.8,-12.7,0.0,0.0],[97.4,33.4,92.5,132.2,-13.2,0.0,0.0],[96.8,33.4,92.3,132.5,-13.7,0.0,0.0],[96.1,33.2,92.3,132.8,-14.1,0.0,0.0],[95.6,33.0,92.2,133.1,-14.5,0.0,0.0],[95.1,32.8,92.2,133.3,-14.8,0.0,0.0],[94.8,32.7,92.2,133.5,-15.1,0.0,0.0],[94.6,32.6,92.1,133.6,-15.1,0.0,0.0],[94.3,32.6,92.1,133.7,-15.4,0.0,0.0],[94.2,32.7,92.1,133.8,-15.2,0.0,0.0],[94.1,32.7,92.0,133.8,-15.3,0.0,0.0],[94.1,32.8,92.0,133.8,-15.3,0.0,0.0],[94.2,32.8,92.0,133.8,-15.3,0.0,0.0],[94.1,32.9,92.0,133.8,-15.3,0.0,0.0],[94.1,32.9,92.0,133.8,-15.3,0.0,0.0],[94.2,32.9,92.0,133.8,-15.3,0.0,0.0],[94.2,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0]],"scrub":false},"compacting_in":{"n":19,"loop":false,"role":"enter","state":"compacting","events":{},"frames":[[120.2,37.6,96.2,120.7,-0.1,0.0,0.0],[118.8,30.3,96.3,114.5,-0.3,0.0,-0.0],[118.9,26.8,96.3,112.6,-0.3,0.0,-0.0],[119.8,25.2,96.5,112.5,-0.1,0.0,-0.01],[119.8,24.9,96.8,112.8,-0.1,0.0,-0.02],[119.1,26.6,97.1,113.8,-0.1,0.0,-0.03],[118.9,31.6,97.3,116.5,-0.1,0.0,-0.04],[117.1,40.4,97.7,121.3,-0.1,0.0,-0.06],[115.9,52.2,98.0,127.8,0.0,0.0,-0.07],[114.3,65.8,98.3,135.1,0.0,0.0,-0.09],[113.2,79.5,98.5,142.4,0.0,0.0,-0.1],[112.9,91.4,98.8,148.8,0.0,0.0,-0.11],[113.3,100.3,98.9,153.4,0.0,0.0,-0.12],[112.9,105.6,99.0,155.9,0.0,0.0,-0.12],[112.2,107.6,99.0,156.7,0.0,0.0,-0.12],[112.4,107.5,99.0,156.6,0.0,0.0,-0.12],[112.6,105.7,99.0,155.8,0.0,0.0,-0.12],[112.9,102.5,99.0,154.2,0.0,0.0,-0.12],[112.8,99.3,99.0,152.8,0.0,0.0,-0.12]],"scrub":false},"compacting_rest":{"n":86,"loop":true,"role":"rest","state":"compacting","events":{},"frames":[[113.9,97.8,99.0,152.3,0.0,0.0,-0.12],[113.5,97.9,99.8,152.4,-0.1,0.0,-0.12],[112.7,98.0,100.5,152.4,-0.1,0.0,-0.12],[112.0,98.1,101.0,152.4,-0.1,0.0,-0.12],[111.7,98.2,101.5,152.4,-0.1,0.0,-0.12],[111.1,98.2,101.7,152.4,-0.1,0.0,-0.12],[110.6,98.2,101.6,152.4,-0.1,0.0,-0.12],[110.6,98.2,101.4,152.4,-0.1,0.0,-0.12],[111.1,98.2,101.0,152.4,-0.1,0.0,-0.12],[111.6,98.2,100.3,152.4,-0.1,0.0,-0.12],[111.8,98.1,99.6,152.3,0.0,0.0,-0.12],[112.7,98.1,98.8,152.3,0.0,0.0,-0.12],[113.3,98.0,98.1,152.4,0.1,0.0,-0.12],[113.9,97.9,97.5,152.4,0.1,0.0,-0.12],[114.3,97.8,96.8,152.4,0.1,0.0,-0.12],[115.1,97.8,96.5,152.4,0.1,0.0,-0.12],[115.3,97.7,96.3,152.4,0.1,0.0,-0.12],[115.3,97.7,96.4,152.4,0.1,0.0,-0.12],[115.3,97.7,96.7,152.4,0.1,0.0,-0.12],[115.1,97.7,97.2,152.4,0.1,0.0,-0.12],[114.8,97.8,97.8,152.4,0.1,0.0,-0.12],[114.1,97.8,98.5,152.3,0.0,0.0,-0.12],[113.7,97.9,99.3,152.3,0.0,0.0,-0.12],[113.1,98.0,100.0,152.4,-0.1,0.0,-0.12],[112.5,98.1,100.8,152.4,-0.1,0.0,-0.12],[111.6,98.1,101.2,152.4,-0.1,0.0,-0.12],[111.5,98.2,101.5,152.4,-0.1,0.0,-0.12],[111.1,98.2,101.7,152.4,-0.1,0.0,-0.12],[110.7,98.0,101.5,152.2,-0.1,0.0,-0.12],[110.6,97.4,101.2,151.9,-0.1,0.0,-0.12],[110.8,96.4,100.7,151.2,-0.1,0.0,-0.12],[110.9,94.9,100.0,150.4,-0.1,0.0,-0.12],[111.4,93.1,99.3,149.5,0.0,0.0,-0.12],[112.0,91.1,98.5,148.5,0.0,0.0,-0.12],[113.2,89.2,97.8,147.6,0.1,0.0,-0.12],[113.9,87.5,97.2,146.8,0.1,0.0,-0.12],[114.8,86.2,96.8,146.2,0.0,0.0,-0.12],[115.3,85.5,96.5,145.9,0.1,0.0,-0.12],[115.9,85.2,96.5,145.9,0.1,0.0,-0.12],[116.1,85.2,96.6,145.9,0.1,0.0,-0.12],[115.9,85.7,97.0,146.1,0.0,0.0,-0.12],[115.2,86.9,97.4,146.7,0.0,0.0,-0.12],[114.8,89.0,98.2,147.8,0.0,0.0,-0.12],[114.4,91.8,98.8,149.3,0.0,0.0,-0.12],[113.3,95.1,99.6,151.1,-0.1,0.0,-0.12],[112.8,98.6,100.3,152.9,0.0,0.0,-0.12],[112.4,101.9,101.0,154.6,-0.1,0.0,-0.12],[112.1,104.6,101.4,156.1,-0.1,0.0,-0.12],[111.7,106.6,101.7,157.1,-0.2,0.0,-0.12],[111.5,107.7,101.8,157.6,-0.2,0.0,-0.12],[111.9,108.1,101.5,157.8,-0.2,0.0,-0.12],[112.0,108.1,101.2,157.8,-0.1,0.0,-0.12],[112.1,107.9,100.5,157.8,-0.1,0.0,-0.12],[112.5,107.6,99.8,157.7,0.0,0.0,-0.12],[113.1,107.3,99.0,157.6,0.0,0.0,-0.12],[113.8,106.9,98.2,157.5,0.0,0.0,-0.12],[114.4,106.5,97.5,157.4,0.1,0.0,-0.12],[114.8,106.0,96.9,157.1,0.1,0.0,-0.12],[115.1,105.5,96.5,156.8,0.1,0.0,-0.12],[115.4,104.9,96.2,156.4,0.2,0.0,-0.12],[115.5,104.3,96.3,156.1,0.1,0.0,-0.12],[115.4,103.6,96.5,155.6,0.1,0.0,-0.12],[115.1,102.9,97.0,155.2,0.1,0.0,-0.12],[114.9,102.2,97.7,154.8,0.0,0.0,-0.12],[114.5,101.5,98.4,154.4,0.0,0.0,-0.12],[114.0,100.8,99.2,154.0,0.0,0.0,-0.12],[113.2,100.2,99.9,153.6,0.0,0.0,-0.12],[112.6,99.7,100.6,153.2,-0.1,0.0,-0.12],[112.1,99.2,101.2,152.9,-0.1,0.0,-0.12],[111.7,98.9,101.5,152.8,-0.1,0.0,-0.12],[111.2,98.6,101.7,152.6,-0.1,0.0,-0.12],[111.0,98.4,101.6,152.4,-0.1,0.0,-0.12],[111.0,98.3,101.3,152.4,-0.1,0.0,-0.12],[111.2,98.2,100.8,152.4,-0.1,0.0,-0.12],[111.4,98.1,100.2,152.4,-0.1,0.0,-0.12],[112.2,98.1,99.5,152.3,0.0,0.0,-0.12],[112.6,98.0,98.7,152.3,0.0,0.0,-0.12],[113.4,98.0,98.0,152.4,0.1,0.0,-0.12],[114.0,97.9,97.2,152.4,0.1,0.0,-0.12],[114.5,97.8,96.8,152.4,0.1,0.0,-0.12],[115.1,97.8,96.5,152.4,0.1,0.0,-0.12],[115.3,97.7,96.3,152.4,0.1,0.0,-0.12],[115.3,97.7,96.5,152.4,0.1,0.0,-0.12],[115.3,97.7,96.8,152.4,0.1,0.0,-0.12],[115.1,97.7,97.2,152.4,0.1,0.0,-0.12],[114.8,97.8,98.0,152.4,0.1,0.0,-0.12]],"scrub":false},"compact_out":{"n":19,"loop":false,"role":"react","state":"compacting","events":{},"frames":[[113.3,97.6,99.0,152.3,0.0,0.0,-0.12],[111.3,67.6,99.0,131.5,0.0,0.0,-0.05],[114.5,38.9,98.9,114.7,0.0,0.0,0.01],[115.6,16.5,98.9,101.7,0.0,0.0,0.06],[115.3,-0.6,98.8,92.6,0.0,0.0,0.09],[117.1,-20.5,98.8,87.2,-0.2,0.0,0.11],[115.6,-28.0,98.6,85.5,-0.2,0.0,0.12],[114.9,-25.8,98.4,87.0,-0.2,0.0,0.12],[115.1,-14.3,98.2,94.0,-0.2,0.0,0.09],[116.4,5.0,98.0,105.8,-0.1,0.0,0.06],[120.7,24.5,97.6,117.5,0.0,0.0,0.03],[120.7,37.1,97.3,124.8,-0.1,0.0,0.0],[119.0,49.4,97.1,126.3,-0.1,0.0,0.0],[121.9,49.6,96.8,126.5,-0.1,0.0,0.0],[122.7,49.1,96.5,125.9,0.0,0.0,0.0],[122.1,47.8,96.4,124.7,-0.1,0.0,0.0],[120.4,46.1,96.3,123.2,-0.1,0.0,0.0],[120.3,41.9,96.2,121.8,-0.1,0.0,0.0],[122.0,36.1,96.2,121.0,-0.1,0.0,0.0]],"scrub":false},"waiting_rest":{"n":106,"loop":true,"role":"rest","state":"waiting","events":{},"frames":[[120.0,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.6,96.3,120.7,-0.1,0.0,0.0],[119.9,37.5,96.6,120.5,-0.1,0.0,0.0],[119.8,37.4,96.7,120.5,-0.1,0.0,0.0],[119.2,37.3,96.8,120.3,-0.1,0.0,0.0],[119.0,37.2,96.9,120.3,-0.1,0.0,0.0],[119.0,37.1,97.1,120.2,-0.1,0.0,0.0],[119.1,36.9,97.2,120.2,-0.1,0.0,0.0],[119.1,36.8,97.2,120.1,0.0,0.0,0.0],[118.9,36.7,97.3,120.0,-0.1,0.0,0.0],[118.9,36.6,97.4,120.0,-0.1,0.0,0.0],[118.9,36.5,97.6,119.8,0.0,0.0,0.0],[118.9,36.5,97.8,119.5,0.0,0.0,0.0],[118.6,36.7,98.2,118.8,-0.1,0.0,0.0],[117.4,37.2,98.7,118.0,0.0,0.0,0.0],[116.1,38.0,99.3,116.9,0.0,0.0,0.0],[114.4,39.3,100.0,115.7,0.0,0.0,0.0],[111.8,41.0,100.6,114.5,0.1,0.0,0.0],[110.7,42.4,101.1,113.3,0.3,0.0,0.0],[110.0,43.6,101.6,112.3,0.4,0.0,0.0],[107.3,44.8,101.8,111.6,0.6,0.0,0.0],[105.6,46.0,102.1,111.0,0.6,0.0,0.0],[105.2,46.8,102.2,110.7,0.6,0.0,0.0],[105.1,47.4,102.2,110.5,0.7,0.0,0.0],[104.9,47.6,102.2,110.5,0.7,0.0,0.0],[105.0,47.5,102.1,110.5,0.6,0.0,0.0],[105.1,47.3,102.1,110.5,0.6,0.0,0.0],[105.2,47.0,102.1,110.5,0.6,0.0,0.0],[105.2,46.7,102.0,110.5,0.6,0.0,0.0],[105.4,46.5,101.9,110.5,0.6,0.0,0.0],[105.4,46.4,101.9,110.5,0.6,0.0,0.0],[105.6,46.4,101.8,110.5,0.7,0.0,0.0],[105.5,46.4,101.8,110.5,0.7,0.0,0.0],[105.6,46.5,101.8,110.6,0.6,0.0,0.0],[105.6,46.6,101.7,110.6,0.6,0.0,0.0],[105.6,46.8,101.7,110.7,0.6,0.0,0.0],[105.5,46.9,101.6,110.7,0.6,0.0,0.0],[105.6,47.1,101.6,110.8,0.7,0.0,0.0],[105.6,47.2,101.5,110.8,0.6,0.0,0.0],[105.7,47.3,101.5,110.8,0.6,0.0,0.0],[105.8,47.4,101.5,110.9,0.6,0.0,0.0],[105.7,47.4,101.5,111.0,0.6,0.0,0.0],[105.8,47.5,101.5,111.0,0.6,0.0,0.0],[105.9,47.6,101.4,111.1,0.6,0.0,0.0],[105.9,47.7,101.4,111.2,0.6,0.0,0.0],[105.8,47.8,101.4,111.2,0.6,0.0,0.0],[105.9,47.9,101.4,111.3,0.6,0.0,0.0],[105.9,48.0,101.4,111.4,0.6,0.0,0.0],[106.0,48.2,101.4,111.4,0.4,0.0,0.0],[106.0,48.3,101.3,111.6,0.6,0.0,0.0],[106.3,48.0,101.2,112.2,0.4,0.0,0.0],[106.9,47.3,100.8,113.2,0.3,0.0,0.0],[107.7,46.3,100.0,114.9,0.0,0.0,0.0],[109.4,45.2,99.1,117.0,0.0,0.0,0.0],[112.6,44.5,98.1,119.3,-0.1,0.0,0.0],[112.4,44.3,97.3,121.5,-0.1,0.0,0.0],[116.1,43.2,96.8,123.2,-0.1,0.0,0.0],[121.9,42.9,96.6,124.5,0.0,0.0,0.0],[126.3,43.3,96.7,125.5,0.0,0.0,0.0],[126.4,44.5,96.8,126.6,0.0,0.0,0.0],[126.3,46.2,96.9,127.7,0.0,0.0,0.0],[124.7,48.1,97.1,128.8,0.0,0.0,0.0],[124.6,50.1,97.1,129.9,0.1,0.0,0.0],[124.5,52.0,97.2,130.9,0.1,0.0,0.0],[121.4,53.8,97.3,131.9,0.1,0.0,0.0],[119.8,55.3,97.3,132.6,0.1,0.0,0.0],[118.4,56.5,97.4,133.4,0.1,0.0,0.0],[118.5,57.3,97.4,133.9,0.1,0.0,0.0],[119.8,57.8,97.4,134.4,0.3,0.0,0.0],[120.3,58.1,97.3,134.7,0.3,0.0,0.0],[120.7,58.2,97.3,134.9,0.3,0.0,0.0],[121.4,58.2,97.2,135.0,0.3,0.0,0.0],[122.9,58.1,97.1,135.1,0.1,0.0,0.0],[123.3,58.0,97.0,135.0,0.3,0.0,0.0],[123.2,57.5,96.8,134.6,0.3,0.0,0.0],[124.0,56.3,96.6,133.6,0.1,0.0,0.0],[123.7,54.5,96.3,132.2,0.1,0.0,0.0],[123.6,52.0,96.0,130.4,0.1,0.0,0.0],[122.6,49.3,95.8,128.4,0.0,0.0,0.0],[122.7,46.4,95.5,126.4,0.0,0.0,0.0],[121.6,43.8,95.2,124.7,-0.1,0.0,0.0],[121.3,41.6,95.1,123.2,-0.1,0.0,0.0],[120.6,40.2,95.0,122.4,-0.3,0.0,0.0],[120.6,39.4,94.8,122.0,-0.3,0.0,0.0],[120.5,39.3,94.8,121.9,-0.3,0.0,0.0],[120.6,39.3,94.8,121.9,-0.3,0.0,0.0],[120.6,39.5,94.8,121.9,-0.3,0.0,0.0],[120.5,39.7,94.8,121.8,-0.3,0.0,0.0],[120.7,39.8,94.8,121.8,-0.3,0.0,0.0],[120.9,39.8,94.8,121.8,-0.1,0.0,0.0],[120.9,39.7,94.8,121.7,-0.3,0.0,0.0],[121.0,39.6,94.8,121.7,-0.3,0.0,0.0],[121.1,39.4,94.8,121.6,-0.3,0.0,0.0],[121.1,39.2,94.8,121.6,-0.3,0.0,0.0],[121.2,39.0,94.9,121.5,-0.3,0.0,0.0],[120.6,38.9,95.0,121.5,-0.1,0.0,0.0],[120.7,38.8,95.1,121.4,-0.3,0.0,0.0],[120.7,38.7,95.2,121.3,-0.3,0.0,0.0],[120.2,38.7,95.2,121.2,-0.1,0.0,0.0],[120.2,38.6,95.3,121.2,-0.3,0.0,0.0],[120.2,38.5,95.6,121.1,-0.3,0.0,0.0],[120.2,38.4,95.7,121.0,-0.1,0.0,0.0],[120.2,38.3,95.8,121.0,-0.1,0.0,0.0],[120.2,38.2,95.8,120.9,-0.3,0.0,0.0],[120.2,38.0,96.1,120.8,-0.1,0.0,0.0],[120.3,37.9,96.2,120.8,-0.1,0.0,0.0]],"scrub":false},"waiting_tap":{"n":62,"loop":false,"role":"beat","state":"waiting","events":{},"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.5,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.1,0.0,0.0],[120.1,36.6,96.2,120.0,-0.1,0.0,0.0],[120.1,36.3,96.2,120.0,-0.1,0.0,0.0],[120.0,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.3,96.2,120.5,-0.1,0.0,0.0],[120.4,34.6,95.9,122.2,-0.1,0.0,0.0],[123.7,33.7,95.8,123.7,-0.1,0.0,0.0],[125.2,32.7,95.7,124.5,-0.1,0.0,0.0],[125.3,31.8,95.7,125.0,0.0,0.0,0.0],[125.4,31.1,95.7,124.8,-0.1,0.0,0.0],[125.4,31.0,95.9,122.7,-0.1,0.0,0.0],[125.6,31.8,96.2,120.2,-0.1,0.0,0.0],[125.4,32.6,96.2,119.5,-0.1,0.0,0.0],[125.4,33.0,95.9,122.0,-0.1,0.0,0.0],[123.9,33.6,95.8,124.0,-0.1,0.0,0.0],[123.6,33.8,95.7,125.0,-0.1,0.0,0.0],[125.3,33.5,95.7,125.2,0.0,0.0,0.0],[125.3,33.1,95.8,123.5,-0.1,0.0,0.0],[125.5,33.5,96.2,121.0,-0.1,0.0,0.0],[125.5,34.2,96.2,120.0,-0.1,0.0,0.0],[125.4,34.4,96.0,122.2,-0.1,0.0,0.0],[125.4,34.6,95.8,124.2,-0.1,0.0,0.0],[125.4,34.6,95.7,125.5,-0.1,0.0,0.0],[125.2,34.4,95.7,126.0,-0.1,0.0,0.0],[125.3,34.2,95.8,124.8,-0.1,0.0,0.0],[125.4,34.6,96.0,122.2,-0.1,0.0,0.0],[125.5,35.5,96.2,120.8,-0.1,0.0,0.0],[125.4,36.0,96.0,122.5,-0.1,0.0,0.0],[125.1,36.4,95.8,124.8,-0.1,0.0,0.0],[124.8,36.6,95.7,126.2,-0.1,0.0,0.0],[125.2,36.5,95.7,126.8,-0.1,0.0,0.0],[125.2,36.2,95.7,126.2,-0.1,0.0,0.0],[125.4,36.3,96.0,123.5,-0.1,0.0,0.0],[125.5,37.1,96.2,121.8,-0.1,0.0,0.0],[125.4,37.5,96.1,122.8,-0.1,0.0,0.0],[125.3,37.8,95.8,125.1,0.0,0.0,0.0],[124.7,37.9,95.8,126.7,0.0,0.0,0.0],[125.2,37.7,95.7,127.4,0.0,0.0,0.0],[125.2,37.3,95.7,127.0,0.0,0.0,0.0],[125.3,37.1,96.0,124.6,0.0,0.0,0.0],[125.4,37.7,96.2,122.3,-0.1,0.0,0.0],[125.4,38.3,96.2,122.0,-0.1,0.0,0.0],[125.5,39.1,96.2,122.0,-0.1,0.0,0.0],[120.9,39.9,96.2,122.0,-0.1,0.0,0.0],[118.6,40.5,96.2,121.8,-0.1,0.0,0.0],[117.2,40.9,96.2,121.8,-0.1,0.0,0.0],[116.5,41.0,96.2,121.8,-0.1,0.0,0.0],[116.8,40.8,96.2,121.8,-0.1,0.0,0.0],[117.5,40.4,96.2,121.7,-0.1,0.0,0.0],[118.6,39.9,96.2,121.5,-0.1,0.0,0.0],[119.5,39.4,96.2,121.5,-0.1,0.0,0.0],[120.3,38.9,96.2,121.3,-0.1,0.0,0.0],[120.7,38.6,96.2,121.2,-0.1,0.0,0.0],[121.0,38.3,96.2,121.2,-0.1,0.0,0.0],[121.2,38.0,96.2,121.0,-0.1,0.0,0.0],[120.8,37.8,96.2,120.8,-0.1,0.0,0.0]],"scrub":false},"dizzy":{"n":115,"loop":false,"role":"once","state":"dizzy","events":{},"frames":[[113.1,41.7,99.0,118.4,0.0,0.0,0.0],[112.2,43.1,107.0,118.4,0.9,0.0,0.0],[110.2,43.6,112.8,118.5,1.9,0.0,0.0],[106.4,44.3,115.8,118.7,2.5,0.0,0.0],[102.3,44.0,116.3,118.7,2.6,0.0,0.0],[98.8,43.0,114.7,118.6,2.2,0.0,0.0],[96.3,42.9,110.8,118.5,1.4,0.0,0.0],[94.9,43.5,105.2,118.4,0.6,0.0,0.0],[97.3,43.3,98.5,118.4,0.0,0.0,0.0],[103.8,42.9,92.6,118.5,-0.7,0.0,0.0],[116.7,41.3,88.2,118.5,-1.3,0.0,0.0],[131.7,37.3,85.8,118.5,-1.7,0.0,0.0],[131.1,35.3,85.4,118.5,-1.9,0.0,0.0],[126.4,35.1,87.0,118.5,-1.5,0.0,0.0],[125.3,36.4,90.2,118.4,-1.1,0.0,0.0],[123.6,38.6,94.7,118.4,-0.6,0.0,0.0],[120.8,41.7,99.7,118.3,0.1,0.0,0.0],[115.7,43.2,104.2,118.4,0.6,0.0,0.0],[110.0,44.4,107.4,118.4,1.0,0.0,0.0],[104.9,44.1,109.2,118.5,1.2,0.0,0.0],[99.7,43.0,109.5,118.5,1.2,0.0,0.0],[97.2,42.7,108.2,118.4,1.1,0.0,0.0],[96.0,43.2,105.5,118.5,0.7,0.0,0.0],[97.5,43.4,102.0,118.4,0.3,0.0,0.0],[101.2,42.8,98.3,118.3,-0.1,0.0,0.0],[111.7,41.6,94.9,118.3,-0.4,0.0,0.0],[122.6,39.2,92.4,118.5,-0.7,0.0,0.0],[132.0,37.2,91.1,118.4,-0.9,0.0,0.0],[132.3,36.4,91.0,118.4,-0.9,0.0,0.0],[131.0,36.8,92.1,118.5,-0.7,0.0,0.0],[128.0,38.1,94.2,118.4,-0.6,0.0,0.0],[122.1,40.0,96.8,118.4,-0.3,0.0,0.0],[116.7,42.3,99.7,118.3,0.1,0.0,0.0],[114.3,43.2,102.2,118.4,0.3,0.0,0.0],[110.7,43.8,104.1,118.4,0.6,0.0,0.0],[107.3,43.9,105.0,118.4,0.6,0.0,0.0],[104.5,43.5,105.0,118.4,0.6,0.0,0.0],[102.7,43.5,104.1,118.4,0.6,0.0,0.0],[102.8,43.3,102.5,118.3,0.4,0.0,0.0],[104.3,42.8,100.5,118.3,0.1,0.0,0.0],[107.8,41.9,98.3,118.3,-0.1,0.0,0.0],[115.0,40.7,96.4,118.4,-0.3,0.0,0.0],[120.3,39.6,95.1,118.3,-0.4,0.0,0.0],[124.4,38.7,94.4,118.4,-0.6,0.0,0.0],[126.4,38.5,94.5,118.4,-0.6,0.0,0.0],[125.6,38.9,95.2,118.3,-0.4,0.0,0.0],[122.7,39.7,96.4,118.4,-0.3,0.0,0.0],[118.7,40.9,98.0,118.3,-0.1,0.0,0.0],[115.4,42.1,99.6,118.3,0.1,0.0,0.0],[113.1,42.9,101.0,118.4,0.3,0.0,0.0],[111.1,43.2,102.0,118.4,0.3,0.0,0.0],[109.3,43.3,102.5,118.3,0.4,0.0,0.0],[107.6,43.3,102.5,118.4,0.3,0.0,0.0],[107.0,43.2,101.8,118.4,0.3,0.0,0.0],[107.2,42.7,100.9,118.3,0.1,0.0,0.0],[108.2,42.2,99.7,118.3,0.1,0.0,0.0],[111.3,41.5,98.5,118.4,0.0,0.0,0.0],[115.0,40.9,97.4,118.3,-0.1,0.0,0.0],[118.4,40.3,96.7,118.4,-0.3,0.0,0.0],[120.2,39.9,96.3,118.4,-0.3,0.0,0.0],[121.1,39.9,96.4,118.4,-0.3,0.0,0.0],[119.8,40.1,96.9,118.4,-0.3,0.0,0.0],[118.4,40.6,97.7,118.3,-0.1,0.0,0.0],[116.9,41.3,98.5,118.4,0.0,0.0,0.0],[114.5,41.9,99.5,118.4,0.0,0.0,0.0],[112.8,42.4,100.2,118.3,0.1,0.0,0.0],[111.3,42.7,100.8,118.3,0.1,0.0,0.0],[110.5,42.8,101.0,118.4,0.3,0.0,0.0],[109.7,42.7,100.9,118.4,0.3,0.0,0.0],[109.4,42.5,100.6,118.3,0.1,0.0,0.0],[109.5,42.2,100.0,118.3,0.1,0.0,0.0],[110.8,41.9,99.3,118.4,0.0,0.0,0.0],[112.6,41.5,98.7,118.4,0.0,0.0,0.0],[114.8,41.1,98.0,118.3,-0.1,0.0,0.0],[116.0,40.8,97.7,118.3,-0.1,0.0,0.0],[117.1,40.6,97.5,118.3,-0.1,0.0,0.0],[117.2,40.6,97.6,118.3,-0.1,0.0,0.0],[115.1,40.8,101.3,120.7,-0.3,0.0,0.0],[118.5,39.6,108.5,120.7,-0.4,0.0,0.0],[109.2,39.9,93.9,120.7,0.0,0.0,0.0],[108.1,39.2,88.2,120.7,0.0,0.0,0.0],[122.0,37.4,100.0,120.7,-0.3,0.0,0.0],[127.6,36.5,104.5,120.7,-0.3,0.0,0.0],[120.1,37.3,95.2,120.7,0.0,0.0,0.0],[118.6,37.5,92.2,120.7,0.0,0.0,0.0],[124.6,36.9,98.5,120.7,-0.1,0.0,0.0],[124.5,37.0,100.2,120.7,-0.3,0.0,0.0],[119.9,37.7,96.7,120.7,-0.1,0.0,0.0],[118.9,38.0,96.4,120.7,-0.1,0.0,0.0],[117.9,38.2,96.2,120.7,-0.1,0.0,0.0],[118.2,38.2,96.2,120.7,-0.1,0.0,0.0],[119.0,38.1,96.2,120.7,-0.1,0.0,0.0],[119.2,38.0,96.2,120.7,-0.1,0.0,0.0],[120.0,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.5,37.6,96.2,120.7,-0.1,0.0,0.0],[120.5,37.6,96.2,120.7,-0.1,0.0,0.0],[120.5,37.6,96.2,120.7,-0.1,0.0,0.0],[120.5,37.6,96.2,120.7,-0.1,0.0,0.0],[120.3,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0]],"scrub":false},"sleep_in":{"n":67,"loop":false,"role":"enter","state":"sleep","events":{},"frames":[[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.6,96.2,120.5,-0.1,0.0,0.0],[120.1,37.0,96.3,119.8,-0.1,0.0,0.0],[120.1,35.4,96.4,118.2,-0.1,0.0,0.01],[119.8,32.9,96.5,115.5,-0.1,0.0,0.02],[119.8,29.4,96.7,112.0,-0.1,0.0,0.03],[118.4,25.4,96.9,107.6,-0.3,0.0,0.04],[116.6,21.0,97.2,102.8,-0.3,0.0,0.06],[114.8,17.0,97.4,98.0,-0.3,0.0,0.07],[113.7,12.2,97.5,93.4,-0.5,0.0,0.09],[110.6,8.1,97.7,89.6,-0.3,0.0,0.1],[109.4,5.2,97.8,86.7,-0.5,0.0,0.11],[109.6,3.7,97.9,84.7,-0.3,0.0,0.12],[109.8,3.2,97.9,83.7,-0.3,0.0,0.12],[109.8,3.3,97.9,83.4,-0.5,0.0,0.12],[109.7,3.8,97.9,83.4,-0.5,0.0,0.12],[109.6,4.2,97.9,83.4,-0.5,0.0,0.12],[109.4,4.5,97.9,83.4,-0.5,0.0,0.12],[109.3,4.6,97.9,83.4,-0.5,0.0,0.12],[109.3,4.5,97.9,83.4,-0.5,0.0,0.12],[109.2,4.3,97.9,83.4,-0.5,0.0,0.12],[109.2,4.0,97.9,83.4,-0.5,0.0,0.12],[109.1,3.6,97.9,83.4,-0.5,0.0,0.12],[109.3,3.4,97.9,83.4,-0.5,0.0,0.12],[109.1,3.5,97.9,83.4,-0.5,0.0,0.12],[110.6,17.3,97.6,101.2,-0.1,0.0,0.12],[110.1,31.4,97.3,114.2,-0.3,0.0,0.12],[113.4,41.1,97.2,123.0,-0.1,0.0,0.11],[116.0,48.8,97.1,128.2,0.0,0.0,0.1],[123.4,52.5,97.0,131.0,0.0,0.0,0.08],[122.3,54.9,97.1,132.1,-0.1,0.0,0.06],[123.3,55.0,97.2,132.5,0.0,0.0,0.03],[123.5,54.2,97.2,132.9,0.0,0.0,-0.01],[124.9,52.7,97.2,134.1,-0.1,0.0,-0.06],[126.5,52.7,97.2,136.9,0.0,0.0,-0.12],[127.9,54.3,97.3,140.4,0.0,0.0,-0.19],[128.5,57.7,97.3,144.3,0.0,0.0,-0.26],[125.8,62.4,97.4,148.6,0.1,0.0,-0.34],[122.9,67.8,97.5,153.4,0.1,0.0,-0.43],[123.3,73.4,97.5,158.4,0.0,0.0,-0.53],[124.7,79.0,97.6,163.8,0.1,0.0,-0.63],[124.7,84.5,97.7,169.4,0.1,0.0,-0.74],[124.3,89.8,97.7,175.1,0.3,0.0,-0.86],[125.1,95.0,97.8,181.1,0.1,0.0,-0.97],[125.2,100.0,97.9,187.1,0.3,0.0,-1.09],[125.3,105.0,97.9,193.2,0.3,0.0,-1.22],[126.5,110.0,98.1,199.4,0.1,0.0,-1.34],[126.7,115.0,98.2,205.4,0.3,0.0,-1.46],[126.7,120.2,98.2,211.4,0.1,0.0,-1.58],[126.6,125.4,98.3,217.2,0.3,0.0,-1.7],[126.5,130.5,98.3,222.9,0.1,0.0,-1.81],[126.3,135.4,98.5,228.2,0.1,0.0,-1.92],[126.1,140.1,98.5,233.4,0.1,0.0,-2.03],[126.0,144.5,98.6,238.1,0.1,0.0,-2.13],[125.9,148.5,98.7,242.6,0.1,0.0,-2.22],[125.8,152.0,98.7,246.8,0.1,0.0,-2.3],[125.8,155.2,98.8,250.4,0.1,0.0,-2.38],[125.8,157.9,98.8,253.8,0.1,0.0,-2.45],[125.8,160.3,98.8,256.6,0.0,0.0,-2.51],[125.8,162.3,98.9,259.0,0.0,0.0,-2.56],[125.8,164.0,98.9,261.0,0.0,0.0,-2.6],[125.8,165.3,99.0,262.6,0.0,0.0,-2.63],[125.7,166.4,99.0,263.9,0.0,0.0,-2.66],[125.7,167.1,99.0,264.7,0.0,0.0,-2.68],[125.7,167.6,99.0,265.3,0.0,0.0,-2.69],[125.7,167.8,99.0,265.6,0.0,0.0,-2.7],[125.7,167.9,99.0,265.8,0.0,0.0,-2.7]],"scrub":false},"sleep_rest":{"n":96,"loop":true,"role":"rest","state":"sleep","events":{},"frames":[[125.9,167.6,99.0,265.8,0.0,0.0,-2.7],[125.9,167.0,99.0,265.3,0.0,0.0,-2.7],[125.9,166.4,99.0,264.9,0.0,0.0,-2.69],[125.9,165.8,99.0,264.4,0.0,0.0,-2.69],[125.9,165.1,99.0,263.9,0.0,0.0,-2.68],[125.9,164.5,99.0,263.5,0.0,0.0,-2.68],[125.9,163.9,99.0,263.1,0.0,0.0,-2.67],[125.9,163.3,99.0,262.6,0.0,0.0,-2.67],[125.9,162.8,99.0,262.2,0.0,0.0,-2.67],[126.0,162.2,99.0,261.8,0.0,0.0,-2.66],[126.0,161.7,99.0,261.4,0.0,0.0,-2.66],[126.0,161.2,99.0,261.1,0.0,0.0,-2.65],[126.0,160.7,99.0,260.7,0.0,0.0,-2.65],[126.0,160.3,99.0,260.4,0.0,0.0,-2.65],[126.0,159.9,99.0,260.1,0.0,0.0,-2.64],[126.0,159.5,99.0,259.8,0.0,0.0,-2.64],[126.0,159.1,99.0,259.6,0.0,0.0,-2.64],[126.0,158.8,99.0,259.4,0.0,0.0,-2.64],[126.0,158.6,99.0,259.2,0.0,0.0,-2.64],[126.0,158.3,99.0,259.0,0.0,0.0,-2.63],[126.0,158.2,99.0,258.9,0.0,0.0,-2.63],[126.0,158.0,99.0,258.8,0.0,0.0,-2.63],[126.0,157.9,99.0,258.7,0.0,0.0,-2.63],[126.0,157.8,99.0,258.7,0.0,0.0,-2.63],[126.0,157.8,99.0,258.6,0.0,0.0,-2.63],[126.0,157.8,99.0,258.7,0.0,0.0,-2.63],[126.0,157.9,99.0,258.7,0.0,0.0,-2.63],[126.0,158.0,99.0,258.8,0.0,0.0,-2.63],[126.0,158.2,99.0,258.9,0.0,0.0,-2.63],[126.0,158.3,99.0,259.0,0.0,0.0,-2.63],[126.0,158.6,99.0,259.2,0.0,0.0,-2.64],[126.0,158.8,99.0,259.4,0.0,0.0,-2.64],[126.0,159.1,99.0,259.6,0.0,0.0,-2.64],[126.0,159.5,99.0,259.8,0.0,0.0,-2.64],[126.0,159.9,99.0,260.1,0.0,0.0,-2.64],[126.0,160.3,99.0,260.4,0.0,0.0,-2.65],[126.0,160.7,99.0,260.7,0.0,0.0,-2.65],[126.0,161.2,99.0,261.1,0.0,0.0,-2.65],[126.0,161.7,99.0,261.4,0.0,0.0,-2.66],[126.0,162.2,99.0,261.8,0.0,0.0,-2.66],[126.0,162.7,99.0,262.2,0.0,0.0,-2.67],[125.9,163.3,99.0,262.6,0.0,0.0,-2.67],[125.9,163.9,99.0,263.1,0.0,0.0,-2.67],[125.9,164.5,99.0,263.5,0.0,0.0,-2.68],[125.9,165.1,99.0,263.9,0.0,0.0,-2.68],[125.9,165.7,99.0,264.4,0.0,0.0,-2.69],[125.9,166.4,99.0,264.9,0.0,0.0,-2.69],[125.9,167.0,99.0,265.3,0.0,0.0,-2.7],[125.9,167.6,99.0,265.8,0.0,0.0,-2.7],[125.9,168.3,99.0,266.3,0.0,0.0,-2.7],[125.9,168.9,99.0,266.7,0.0,0.0,-2.71],[125.9,169.6,99.0,267.2,0.0,0.0,-2.71],[125.9,170.2,99.0,267.7,0.0,0.0,-2.72],[125.8,170.8,99.0,268.1,0.0,0.0,-2.72],[125.8,171.4,99.0,268.5,0.0,0.0,-2.73],[125.8,172.0,99.0,269.0,0.0,0.0,-2.73],[125.8,172.5,99.0,269.4,0.0,0.0,-2.74],[125.8,173.1,99.0,269.8,0.0,0.0,-2.74],[125.8,173.6,99.0,270.2,0.0,0.0,-2.74],[125.8,174.1,99.0,270.5,0.0,0.0,-2.75],[125.8,174.6,99.0,270.9,0.0,0.0,-2.75],[125.8,175.0,99.0,271.2,0.0,0.0,-2.75],[125.8,175.4,99.0,271.5,0.0,0.0,-2.76],[125.8,175.8,99.0,271.8,0.0,0.0,-2.76],[125.8,176.1,99.0,272.0,0.0,0.0,-2.76],[125.8,176.4,99.0,272.2,0.0,0.0,-2.76],[125.8,176.6,99.0,272.4,0.0,0.0,-2.76],[125.2,173.7,99.0,267.8,0.0,0.0,-2.68],[125.4,172.9,99.0,267.3,0.0,0.0,-2.67],[125.7,172.5,99.0,267.5,0.0,0.0,-2.67],[126.1,172.9,99.0,268.7,0.0,0.0,-2.69],[126.4,174.2,99.0,270.7,0.0,0.0,-2.73],[126.4,175.6,99.0,272.4,0.0,0.0,-2.76],[126.2,176.6,99.0,273.0,0.0,0.0,-2.77],[125.8,177.3,99.0,272.9,0.0,0.0,-2.77],[125.5,177.7,99.0,272.8,0.0,0.0,-2.77],[125.4,177.9,99.0,272.7,0.0,0.0,-2.77],[125.4,177.7,99.0,272.6,0.0,0.0,-2.77],[125.5,177.3,99.0,272.4,0.0,0.0,-2.76],[125.6,176.7,99.0,272.2,0.0,0.0,-2.76],[125.8,176.2,99.0,272.0,0.0,0.0,-2.76],[125.9,175.6,99.0,271.8,0.0,0.0,-2.76],[125.9,175.1,99.0,271.5,0.0,0.0,-2.76],[125.9,174.7,99.0,271.2,0.0,0.0,-2.75],[125.9,174.4,99.0,270.9,0.0,0.0,-2.75],[125.9,174.0,99.0,270.5,0.0,0.0,-2.75],[125.8,173.6,99.0,270.2,0.0,0.0,-2.74],[125.8,173.2,99.0,269.8,0.0,0.0,-2.74],[125.8,172.7,99.0,269.4,0.0,0.0,-2.74],[125.8,172.1,99.0,269.0,0.0,0.0,-2.73],[125.8,171.5,99.0,268.5,0.0,0.0,-2.73],[125.8,170.9,99.0,268.1,0.0,0.0,-2.72],[125.8,170.2,99.0,267.7,0.0,0.0,-2.72],[125.9,169.5,99.0,267.2,0.0,0.0,-2.71],[125.9,168.9,99.0,266.7,0.0,0.0,-2.71],[125.9,168.3,99.0,266.3,0.0,0.0,-2.7]],"scrub":false},"sleep_twitch":{"n":58,"loop":false,"role":"beat","state":"sleep","events":{},"frames":[[125.9,167.6,99.0,265.8,0.0,0.0,-2.7],[125.8,167.2,99.0,265.4,0.0,0.0,-2.7],[125.8,166.6,99.0,265.1,0.0,0.0,-2.7],[125.8,165.9,99.0,264.7,0.0,0.0,-2.7],[125.8,165.2,99.0,264.4,0.0,0.0,-2.7],[125.9,164.5,99.0,264.0,0.0,0.0,-2.7],[126.0,163.8,99.0,263.7,0.0,0.0,-2.7],[126.0,163.1,99.0,263.5,0.0,0.0,-2.7],[127.1,161.8,99.0,263.2,0.0,0.0,-2.7],[127.8,160.6,99.0,263.0,0.0,0.0,-2.7],[128.1,159.7,99.0,262.8,0.0,0.0,-2.7],[128.4,159.2,99.0,262.6,0.0,0.0,-2.7],[128.6,158.8,99.0,262.5,0.0,0.0,-2.7],[129.0,158.5,99.0,262.4,0.0,0.0,-2.7],[129.1,158.4,99.0,262.4,0.0,0.0,-2.7],[129.1,158.4,99.0,262.4,0.0,0.0,-2.7],[129.1,158.4,99.0,262.5,0.0,0.0,-2.7],[129.1,158.5,99.0,262.5,0.0,0.0,-2.7],[129.2,158.8,99.0,262.7,0.0,0.0,-2.7],[129.2,159.1,99.0,262.8,0.0,0.0,-2.7],[129.2,159.5,99.0,263.0,0.0,0.0,-2.7],[128.9,160.1,99.0,263.2,0.0,0.0,-2.7],[128.2,161.1,99.0,263.5,0.0,0.0,-2.7],[127.7,162.4,99.0,263.8,0.0,0.0,-2.7],[126.9,163.7,99.0,264.1,0.0,0.0,-2.7],[126.2,164.9,99.0,264.4,0.0,0.0,-2.7],[126.0,165.7,99.0,264.8,0.0,0.0,-2.7],[125.9,166.4,99.0,265.1,0.0,0.0,-2.7],[125.9,167.1,99.0,265.5,0.0,0.0,-2.7],[125.9,167.8,99.0,265.9,0.0,0.0,-2.7],[125.9,168.5,99.0,266.2,0.0,0.0,-2.7],[125.9,169.2,99.0,266.6,0.0,0.0,-2.7],[125.8,169.8,99.0,267.0,0.0,0.0,-2.7],[125.8,170.5,99.0,267.3,0.0,0.0,-2.7],[125.8,171.1,99.0,267.6,0.0,0.0,-2.7],[125.8,171.7,99.0,267.9,0.0,0.0,-2.7],[125.8,172.2,99.0,268.2,0.0,0.0,-2.7],[125.8,172.6,99.0,268.4,0.0,0.0,-2.7],[125.8,173.0,99.0,268.7,0.0,0.0,-2.7],[125.8,173.4,99.0,268.8,0.0,0.0,-2.7],[125.7,173.7,99.0,269.0,0.0,0.0,-2.7],[125.7,173.9,99.0,269.1,0.0,0.0,-2.7],[125.7,174.0,99.0,269.2,0.0,0.0,-2.7],[125.7,174.1,99.0,269.2,0.0,0.0,-2.7],[125.7,174.0,99.0,269.2,0.0,0.0,-2.7],[125.7,173.9,99.0,269.1,0.0,0.0,-2.7],[125.7,173.8,99.0,269.0,0.0,0.0,-2.7],[125.8,173.5,99.0,268.9,0.0,0.0,-2.7],[125.8,173.2,99.0,268.7,0.0,0.0,-2.7],[125.8,172.8,99.0,268.5,0.0,0.0,-2.7],[125.8,172.4,99.0,268.3,0.0,0.0,-2.7],[125.8,171.9,99.0,268.0,0.0,0.0,-2.7],[125.8,171.4,99.0,267.7,0.0,0.0,-2.7],[125.8,170.8,99.0,267.4,0.0,0.0,-2.7],[125.8,170.1,99.0,267.1,0.0,0.0,-2.7],[125.8,169.5,99.0,266.7,0.0,0.0,-2.7],[125.8,168.8,99.0,266.4,0.0,0.0,-2.7],[125.9,168.1,99.0,266.0,0.0,0.0,-2.7]],"scrub":false},"popup":{"n":43,"loop":false,"role":"react","state":null,"events":{"land":12},"frames":[[126.9,239.0,96.2,343.1,2.4,0.0,-4.2],[121.1,189.3,96.3,283.5,1.7,0.0,-3.19],[119.8,139.1,96.4,232.3,1.1,0.0,-2.3],[119.2,96.8,96.4,189.1,0.6,0.0,-1.55],[119.3,62.9,96.5,153.8,0.1,0.0,-0.92],[122.6,30.3,96.5,125.8,-0.2,0.0,-0.42],[117.5,6.5,96.6,105.2,-0.5,0.0,-0.05],[115.1,-4.8,96.7,91.7,-0.6,0.0,0.19],[113.6,-10.7,96.7,85.3,-0.6,0.0,0.31],[113.4,-8.5,96.6,86.5,-0.6,0.0,0.31],[114.7,7.0,96.6,97.2,-0.4,0.0,0.24],[117.0,36.5,96.4,117.7,-0.3,0.0,0.1],[116.0,56.3,96.3,131.9,-0.1,0.0,0.0],[113.9,54.4,96.3,125.7,-0.3,0.0,0.0],[118.6,44.0,96.5,120.0,-0.3,0.0,0.0],[119.6,43.4,96.5,119.8,-0.1,0.0,0.0],[119.5,43.6,96.5,119.8,-0.1,0.0,0.0],[116.8,44.2,96.5,119.8,-0.1,0.0,0.0],[118.6,39.6,96.5,119.8,-0.1,0.0,0.0],[119.8,34.7,96.5,119.8,-0.1,0.0,0.0],[118.9,34.4,96.5,119.8,-0.1,0.0,0.0],[118.9,34.4,96.5,119.8,-0.1,0.0,0.0],[119.1,34.2,96.5,119.8,-0.1,0.0,0.0],[119.1,36.4,96.5,119.8,-0.1,0.0,0.0],[119.5,38.7,96.5,119.8,-0.1,0.0,0.0],[102.5,43.7,99.2,119.7,0.0,0.0,0.0],[103.9,44.8,99.5,119.7,0.0,0.0,0.0],[108.8,44.9,99.5,119.7,0.0,0.0,0.0],[111.1,44.2,99.5,119.7,0.0,0.0,0.0],[114.7,41.2,99.5,119.7,0.0,0.0,0.0],[119.3,38.6,99.5,119.7,0.0,0.0,0.0],[121.3,36.9,99.5,119.7,0.0,0.0,0.0],[123.8,36.1,99.5,119.8,0.1,0.0,0.0],[123.5,36.0,99.5,119.8,0.1,0.0,0.0],[122.4,36.4,99.3,119.8,0.0,0.0,0.0],[121.7,36.9,99.0,119.9,0.0,0.0,0.0],[120.6,37.3,98.6,120.0,0.0,0.0,0.0],[119.9,37.6,98.1,120.2,-0.1,0.0,0.0],[119.7,37.7,97.6,120.3,0.0,0.0,0.0],[118.9,37.7,97.1,120.5,-0.1,0.0,0.0],[119.8,37.7,96.7,120.5,-0.1,0.0,0.0],[120.5,37.7,96.4,120.7,-0.1,0.0,0.0],[119.3,37.9,96.2,120.7,-0.1,0.0,0.0]],"scrub":false},"poke":{"n":36,"loop":false,"role":"react","state":null,"events":{},"frames":[[119.9,38.3,96.2,120.7,-0.1,0.0,0.0],[116.4,71.8,96.0,140.1,0.0,-0.04,0.0],[117.7,58.7,96.2,131.8,0.0,-0.07,0.0],[120.3,38.3,96.3,118.3,-0.1,-0.09,0.0],[122.8,23.3,96.5,110.9,-0.3,-0.1,0.0],[122.5,20.1,96.5,109.1,-0.3,-0.1,0.0],[122.6,15.1,96.5,109.1,-0.3,-0.1,0.0],[122.5,10.2,96.4,109.3,-0.2,-0.1,0.0],[123.0,9.1,96.4,109.8,-0.3,-0.1,0.0],[122.9,10.5,96.5,110.5,-0.2,-0.09,0.0],[123.4,12.0,96.4,111.5,-0.1,-0.09,0.0],[123.0,16.2,96.4,112.7,-0.3,-0.08,0.0],[122.6,21.0,96.4,114.0,-0.1,-0.07,0.0],[122.2,25.4,96.3,115.2,-0.3,-0.06,0.0],[121.9,28.9,96.3,116.3,-0.1,-0.05,0.0],[121.8,31.1,96.3,117.3,-0.3,-0.04,0.0],[121.7,32.2,96.3,118.0,-0.1,-0.03,0.0],[122.2,32.3,96.3,118.5,-0.1,-0.03,0.0],[121.9,32.0,96.3,118.7,-0.1,-0.02,0.0],[122.2,31.4,96.2,118.7,-0.1,-0.01,0.0],[122.2,30.9,96.3,118.7,-0.1,-0.01,0.0],[122.1,30.8,96.2,118.6,-0.3,-0.0,0.0],[122.0,31.1,96.2,118.7,-0.1,-0.0,0.0],[121.8,31.7,96.2,118.8,-0.1,-0.0,0.0],[121.4,32.5,96.2,118.8,-0.1,0.0,0.0],[121.5,33.3,96.2,119.0,-0.1,0.0,0.0],[120.9,34.2,96.2,119.2,-0.1,0.0,0.0],[120.4,35.0,96.2,119.5,-0.1,0.0,0.0],[120.2,35.7,96.2,119.8,-0.1,0.0,0.0],[120.2,36.3,96.2,120.0,-0.1,0.0,0.0],[120.1,36.7,96.2,120.2,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.2,37.4,96.2,120.5,-0.3,0.0,0.0],[120.2,37.6,96.2,120.6,-0.3,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0]],"scrub":false},"pet":{"n":43,"loop":false,"role":"react","state":null,"events":{},"frames":[[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.3,38.0,97.2,120.8,-0.1,0.01,0.0],[121.5,39.2,101.5,121.3,0.0,0.03,0.0],[121.6,41.3,107.3,122.2,0.4,0.06,0.0],[116.8,44.2,111.5,122.9,1.1,0.09,0.0],[108.9,47.3,112.8,123.2,1.2,0.1,0.0],[104.1,49.4,112.8,123.2,1.2,0.1,0.0],[100.9,49.9,112.2,123.2,1.2,0.1,0.0],[99.0,49.8,110.9,123.1,1.0,0.1,0.0],[98.6,49.4,109.2,122.9,0.9,0.1,0.0],[100.0,48.7,107.5,122.6,0.8,0.1,0.0],[102.5,47.7,106.4,122.2,0.7,0.09,0.0],[106.2,46.2,106.2,121.8,0.6,0.09,0.0],[109.1,44.6,106.2,121.2,0.7,0.08,0.0],[111.5,42.6,107.1,120.7,0.9,0.08,0.0],[113.4,40.9,108.6,120.1,1.0,0.07,0.0],[112.9,39.8,110.1,119.3,1.2,0.07,0.0],[110.5,39.0,110.8,118.5,1.4,0.06,0.0],[107.9,38.5,110.7,117.8,1.4,0.05,0.0],[105.2,37.7,110.2,117.0,1.4,0.04,0.0],[103.1,36.6,108.8,116.2,1.2,0.04,0.0],[102.6,35.2,106.8,115.4,0.9,0.03,0.0],[102.9,34.1,104.8,114.7,0.7,0.02,0.0],[105.2,32.7,103.5,114.0,0.7,0.02,0.0],[108.0,31.3,103.0,113.5,0.6,0.01,0.0],[110.2,30.1,102.8,113.1,0.4,0.01,0.0],[113.0,28.8,102.3,112.7,0.4,0.01,0.0],[115.5,27.9,101.5,112.4,0.3,0.0,0.0],[116.8,27.3,100.5,112.2,0.3,0.0,0.0],[116.9,27.0,99.6,112.1,0.0,0.0,0.0],[116.9,26.9,99.1,112.1,0.0,0.0,0.0],[116.9,26.9,99.0,112.1,0.0,0.0,0.0],[116.9,27.1,99.0,112.1,0.0,0.0,0.0],[116.8,27.5,98.9,112.3,0.0,0.0,0.0],[116.4,28.3,98.8,112.8,0.0,0.0,0.0],[115.4,29.5,98.5,113.6,0.0,0.0,0.0],[115.3,30.9,98.2,114.8,-0.1,0.0,0.0],[115.3,32.5,97.8,116.0,-0.1,0.0,0.0],[115.5,34.2,97.4,117.3,-0.1,0.0,0.0],[116.3,35.7,97.0,118.5,-0.1,0.0,0.0],[118.0,36.8,96.7,119.6,-0.3,0.0,0.0],[119.6,37.6,96.4,120.2,-0.1,0.0,0.0],[120.6,37.9,96.2,120.7,-0.1,0.0,0.0]],"scrub":false}}}
\ No newline at end of file
diff --git a/app/ChumsWatch/Noodle/oops.heics b/app/ChumsWatch/Noodle/oops.heics
new file mode 100644
index 0000000..8437d09
Binary files /dev/null and b/app/ChumsWatch/Noodle/oops.heics differ
diff --git a/app/ChumsWatch/Noodle/pet.heics b/app/ChumsWatch/Noodle/pet.heics
new file mode 100644
index 0000000..eac905d
Binary files /dev/null and b/app/ChumsWatch/Noodle/pet.heics differ
diff --git a/app/ChumsWatch/Noodle/poke.heics b/app/ChumsWatch/Noodle/poke.heics
new file mode 100644
index 0000000..5383ed8
Binary files /dev/null and b/app/ChumsWatch/Noodle/poke.heics differ
diff --git a/app/ChumsWatch/Noodle/popup.heics b/app/ChumsWatch/Noodle/popup.heics
new file mode 100644
index 0000000..8125bf2
Binary files /dev/null and b/app/ChumsWatch/Noodle/popup.heics differ
diff --git a/app/ChumsWatch/Noodle/sleep_in.heics b/app/ChumsWatch/Noodle/sleep_in.heics
new file mode 100644
index 0000000..dde5098
Binary files /dev/null and b/app/ChumsWatch/Noodle/sleep_in.heics differ
diff --git a/app/ChumsWatch/Noodle/sleep_rest.heics b/app/ChumsWatch/Noodle/sleep_rest.heics
new file mode 100644
index 0000000..97db50a
Binary files /dev/null and b/app/ChumsWatch/Noodle/sleep_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/sleep_twitch.heics b/app/ChumsWatch/Noodle/sleep_twitch.heics
new file mode 100644
index 0000000..0961ae3
Binary files /dev/null and b/app/ChumsWatch/Noodle/sleep_twitch.heics differ
diff --git a/app/ChumsWatch/Noodle/speak_a.heics b/app/ChumsWatch/Noodle/speak_a.heics
new file mode 100644
index 0000000..fdda2fa
Binary files /dev/null and b/app/ChumsWatch/Noodle/speak_a.heics differ
diff --git a/app/ChumsWatch/Noodle/speak_b.heics b/app/ChumsWatch/Noodle/speak_b.heics
new file mode 100644
index 0000000..9b1bf10
Binary files /dev/null and b/app/ChumsWatch/Noodle/speak_b.heics differ
diff --git a/app/ChumsWatch/Noodle/speak_c.heics b/app/ChumsWatch/Noodle/speak_c.heics
new file mode 100644
index 0000000..f540b16
Binary files /dev/null and b/app/ChumsWatch/Noodle/speak_c.heics differ
diff --git a/app/ChumsWatch/Noodle/speak_d.heics b/app/ChumsWatch/Noodle/speak_d.heics
new file mode 100644
index 0000000..abdc9fa
Binary files /dev/null and b/app/ChumsWatch/Noodle/speak_d.heics differ
diff --git a/app/ChumsWatch/Noodle/speaking_rest.heics b/app/ChumsWatch/Noodle/speaking_rest.heics
new file mode 100644
index 0000000..a0673de
Binary files /dev/null and b/app/ChumsWatch/Noodle/speaking_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/subagents_hop.heics b/app/ChumsWatch/Noodle/subagents_hop.heics
new file mode 100644
index 0000000..3a71938
Binary files /dev/null and b/app/ChumsWatch/Noodle/subagents_hop.heics differ
diff --git a/app/ChumsWatch/Noodle/subagents_in.heics b/app/ChumsWatch/Noodle/subagents_in.heics
new file mode 100644
index 0000000..dbca5e7
Binary files /dev/null and b/app/ChumsWatch/Noodle/subagents_in.heics differ
diff --git a/app/ChumsWatch/Noodle/subagents_lean.heics b/app/ChumsWatch/Noodle/subagents_lean.heics
new file mode 100644
index 0000000..e02f28b
Binary files /dev/null and b/app/ChumsWatch/Noodle/subagents_lean.heics differ
diff --git a/app/ChumsWatch/Noodle/subagents_rest.heics b/app/ChumsWatch/Noodle/subagents_rest.heics
new file mode 100644
index 0000000..9db170f
Binary files /dev/null and b/app/ChumsWatch/Noodle/subagents_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/subagents_sigh.heics b/app/ChumsWatch/Noodle/subagents_sigh.heics
new file mode 100644
index 0000000..1876799
Binary files /dev/null and b/app/ChumsWatch/Noodle/subagents_sigh.heics differ
diff --git a/app/ChumsWatch/Noodle/think_count.heics b/app/ChumsWatch/Noodle/think_count.heics
new file mode 100644
index 0000000..fb1b9c0
Binary files /dev/null and b/app/ChumsWatch/Noodle/think_count.heics differ
diff --git a/app/ChumsWatch/Noodle/think_down.heics b/app/ChumsWatch/Noodle/think_down.heics
new file mode 100644
index 0000000..4f5129d
Binary files /dev/null and b/app/ChumsWatch/Noodle/think_down.heics differ
diff --git a/app/ChumsWatch/Noodle/think_hm.heics b/app/ChumsWatch/Noodle/think_hm.heics
new file mode 100644
index 0000000..a91c8b6
Binary files /dev/null and b/app/ChumsWatch/Noodle/think_hm.heics differ
diff --git a/app/ChumsWatch/Noodle/think_roll.heics b/app/ChumsWatch/Noodle/think_roll.heics
new file mode 100644
index 0000000..d20f1d3
Binary files /dev/null and b/app/ChumsWatch/Noodle/think_roll.heics differ
diff --git a/app/ChumsWatch/Noodle/think_sigh.heics b/app/ChumsWatch/Noodle/think_sigh.heics
new file mode 100644
index 0000000..9892e80
Binary files /dev/null and b/app/ChumsWatch/Noodle/think_sigh.heics differ
diff --git a/app/ChumsWatch/Noodle/think_squint.heics b/app/ChumsWatch/Noodle/think_squint.heics
new file mode 100644
index 0000000..5d00577
Binary files /dev/null and b/app/ChumsWatch/Noodle/think_squint.heics differ
diff --git a/app/ChumsWatch/Noodle/think_swap.heics b/app/ChumsWatch/Noodle/think_swap.heics
new file mode 100644
index 0000000..b387f16
Binary files /dev/null and b/app/ChumsWatch/Noodle/think_swap.heics differ
diff --git a/app/ChumsWatch/Noodle/thinking_in.heics b/app/ChumsWatch/Noodle/thinking_in.heics
new file mode 100644
index 0000000..96cfc36
Binary files /dev/null and b/app/ChumsWatch/Noodle/thinking_in.heics differ
diff --git a/app/ChumsWatch/Noodle/thinking_rest.heics b/app/ChumsWatch/Noodle/thinking_rest.heics
new file mode 100644
index 0000000..7ebd311
Binary files /dev/null and b/app/ChumsWatch/Noodle/thinking_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/waiting_rest.heics b/app/ChumsWatch/Noodle/waiting_rest.heics
new file mode 100644
index 0000000..b2a7641
Binary files /dev/null and b/app/ChumsWatch/Noodle/waiting_rest.heics differ
diff --git a/app/ChumsWatch/Noodle/waiting_tap.heics b/app/ChumsWatch/Noodle/waiting_tap.heics
new file mode 100644
index 0000000..6f06f73
Binary files /dev/null and b/app/ChumsWatch/Noodle/waiting_tap.heics differ
diff --git a/app/ChumsWatch/Noodle/work_blink.heics b/app/ChumsWatch/Noodle/work_blink.heics
new file mode 100644
index 0000000..0a53e14
Binary files /dev/null and b/app/ChumsWatch/Noodle/work_blink.heics differ
diff --git a/app/ChumsWatch/Noodle/work_edit.heics b/app/ChumsWatch/Noodle/work_edit.heics
new file mode 100644
index 0000000..2d7e906
Binary files /dev/null and b/app/ChumsWatch/Noodle/work_edit.heics differ
diff --git a/app/ChumsWatch/Noodle/work_nod.heics b/app/ChumsWatch/Noodle/work_nod.heics
new file mode 100644
index 0000000..874b4f5
Binary files /dev/null and b/app/ChumsWatch/Noodle/work_nod.heics differ
diff --git a/app/ChumsWatch/Noodle/work_ponder.heics b/app/ChumsWatch/Noodle/work_ponder.heics
new file mode 100644
index 0000000..3c8ad77
Binary files /dev/null and b/app/ChumsWatch/Noodle/work_ponder.heics differ
diff --git a/app/ChumsWatch/Noodle/work_read.heics b/app/ChumsWatch/Noodle/work_read.heics
new file mode 100644
index 0000000..e70aa02
Binary files /dev/null and b/app/ChumsWatch/Noodle/work_read.heics differ
diff --git a/app/ChumsWatch/Noodle/work_run.heics b/app/ChumsWatch/Noodle/work_run.heics
new file mode 100644
index 0000000..1e8994c
Binary files /dev/null and b/app/ChumsWatch/Noodle/work_run.heics differ
diff --git a/app/ChumsWatch/Noodle/work_search.heics b/app/ChumsWatch/Noodle/work_search.heics
new file mode 100644
index 0000000..1f3742f
Binary files /dev/null and b/app/ChumsWatch/Noodle/work_search.heics differ
diff --git a/app/ChumsWatch/Noodle/work_squint.heics b/app/ChumsWatch/Noodle/work_squint.heics
new file mode 100644
index 0000000..8d0f267
Binary files /dev/null and b/app/ChumsWatch/Noodle/work_squint.heics differ
diff --git a/app/ChumsWatch/Noodle/working_in.heics b/app/ChumsWatch/Noodle/working_in.heics
new file mode 100644
index 0000000..f8c804e
Binary files /dev/null and b/app/ChumsWatch/Noodle/working_in.heics differ
diff --git a/app/ChumsWatch/OfflineRender.swift b/app/ChumsWatch/OfflineRender.swift
new file mode 100644
index 0000000..25008cf
--- /dev/null
+++ b/app/ChumsWatch/OfflineRender.swift
@@ -0,0 +1,140 @@
+#if targetEnvironment(simulator)
+import SwiftUI
+import ImageIO
+import UniformTypeIdentifiers
+
+/// Simulator only: renders the character offline, in simulated time, frame by frame at any resolution, to PNG files
+/// in the app's Documents/render/<name>, for a recording script to turn into a sheet or a video.
+/// Launched with -render <base64 JSON>:
+/// name, character, mode (portrait|world), scale (pixels per point, default 6), fps (default 60), clock ("10:09"),
+/// ao (true: the dimmed, always-on look)
+/// sheet: ["idle", "[email protected]", …] one still per state (after its time in that state, default `settle` 1.6 s)
+/// or duration + events: a timeline; every frame is written
+/// {"t": 0, "state": "working"} {"t": 1, "tap": [x, y]} {"t": 2, "drag": [[x, y], …], "over": 1.2}
+/// {"t": 3, "crown": 12, "over": 0.8} {"t": 5, "shake": 2.5, "over": 1} {"t": 6, "voice": 0.7} {"t": 7, "voice": null}
+/// {"t": 7, "tool": "read Read cart.ts"} {"t": 8, "caption": "…"} {"t": 8, "label": "WORKING"}
+@MainActor
+enum OfflineRender {
+ struct Event: Decodable {
+ var t: Double
+ var state: String?, variant: Bool?
+ var tap: [Double]?, drag: [[Double]]?, over: Double?
+ var crown: Double?, shake: Double?
+ var voice: Double??, tool: String?, caption: String?, label: String?
+ }
+ struct Spec: Decodable {
+ var name: String, character: String
+ var mode: String?, scale: Double?, fps: Double?, clock: String?
+ var sheet: [String]?, settle: Double?
+ var duration: Double?, events: [Event]?
+ var faces: [String]?
+ var ao: Bool? // the dimmed (always on) look
+ }
+
+ static func run(_ base64: String) async {
+ guard let data = Data(base64Encoded: base64), let spec = try? JSONDecoder().decode(Spec.self, from: data) else {
+ print("render: bad spec"); return
+ }
+ let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
+ let dir = docs.appendingPathComponent("render/\(spec.name)")
+ try? FileManager.default.removeItem(at: dir)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+
+ StretchFrames.shared.waits = true // every one of Stretch's frames in the pictures
+ let rig = Rig()
+ rig.ao = spec.ao ?? false
+ rig.character = CharacterKind(id: spec.character) ?? .fallback
+ rig.mode = StageMode(rawValue: spec.mode ?? "portrait") ?? .portrait
+ rig.faces = (spec.faces ?? [spec.character]).map { ($0, false) }
+ rig.approvalTitle = "git push origin main"; rig.approvalDetail = "Push the fix to GitHub"
+ let fps = spec.fps ?? 60, dt = 1 / fps, scale = spec.scale ?? 6
+ var index = 0
+ func shoot(_ file: String) {
+ let view = Canvas { ctx, size in
+ Renderer.draw(rig, ctx, size: size)
+ if let clock = spec.clock {
+ ctx.draw(Text(clock).font(.system(size: 17, weight: .semibold)).foregroundColor(.white),
+ at: CGPoint(x: size.width - 14, y: 21), anchor: .trailing)
+ }
+ }
+ .frame(width: DESIGN.width, height: DESIGN.height)
+ let r = ImageRenderer(content: view); r.scale = scale
+ guard let img = r.cgImage,
+ let d = CGImageDestinationCreateWithURL(dir.appendingPathComponent(file) as CFURL, UTType.png.identifier as CFString, 1, nil) else { return }
+ CGImageDestinationAddImage(d, img, nil); CGImageDestinationFinalize(d)
+ }
+ func advance(_ seconds: Double) { var s = 0.0; while s < seconds - 1e-9 { rig.tick(dt); s += dt } }
+
+ if let sheet = spec.sheet {
+ for (i, item) in sheet.enumerated() {
+ let parts = item.split(separator: "@"), name = String(parts[0])
+ let hold = parts.count > 1 ? Double(parts[1]) ?? 1.6 : spec.settle ?? 1.6
+ guard let s = ChumsState(rawValue: name) else { continue }
+ rig.restState = s; rig.label = s == .idle || s == .sleep ? "" : name.uppercased()
+ rig.voiceInput = s == .listening ? 0.6 : nil
+ rig.setState(s)
+ advance(hold)
+ shoot(String(format: "%02d-%@.png", i, name))
+ }
+ } else if let duration = spec.duration {
+ let events = (spec.events ?? []).sorted { $0.t < $1.t }
+ var next = 0
+ var drags: [(Event, Double)] = [], crowns: [(Event, Double)] = [], shakes: [(Event, Double)] = []
+ var lastDrag: CGPoint?, tapUp: Double?
+ var t = 0.0
+ while t < duration {
+ while next < events.count && events[next].t <= t + 1e-9 {
+ let e = events[next]; next += 1
+ if let s = e.state.flatMap({ ChumsState(rawValue: $0) }) {
+ rig.restState = s; rig.setState(s, variant: e.variant ?? false)
+ rig.voiceInput = s == .listening ? 0.6 : nil // as the app does: your voice only while it listens
+ }
+ if let v = e.voice { rig.voiceInput = v }
+ if let c = e.caption { rig.caption = c }
+ if let l = e.label { rig.label = l }
+ if let tool = e.tool {
+ let w = tool.split(separator: " ", maxSplits: 1)
+ rig.push(ToolCall(id: UUID().uuidString, kind: ToolCall.Kind(rawValue: String(w[0])) ?? .bash, text: w.count > 1 ? String(w[1]) : tool))
+ }
+ if let p = e.tap {
+ let pt = CGPoint(x: p[0], y: p[1])
+ _ = rig.touchDown(pt); rig.staged?.touched(rig, at: pt)
+ if rig.worlds.onCharacter(rig, pt) { rig.poke() }
+ tapUp = t + 0.12
+ }
+ if e.drag != nil { drags.append((e, e.t)) }
+ if e.crown != nil { crowns.append((e, e.t)) }
+ if e.shake != nil { shakes.append((e, e.t)) }
+ }
+ if let u = tapUp, t >= u { rig.touchUp(); rig.staged?.released(rig); tapUp = nil }
+ // drags: along their points, eased; the finger comes down at the first and lifts at the last
+ for (i, (e, t0)) in drags.enumerated().reversed() {
+ let pts = e.drag!.map { CGPoint(x: $0[0], y: $0[1]) }, over = e.over ?? 1
+ let u = clamp((t - t0) / over, 0, 1), k = u * u * (3 - 2 * u), f = k * Double(pts.count - 1)
+ let j = min(pts.count - 2, Int(f)), w = f - Double(j)
+ let p = pts.count > 1 ? CGPoint(x: pts[j].x + (pts[j + 1].x - pts[j].x) * w, y: pts[j].y + (pts[j + 1].y - pts[j].y) * w) : pts[0]
+ if lastDrag == nil { _ = rig.touchDown(p); rig.staged?.touched(rig, at: p) }
+ else { rig.touchMoved(p); rig.staged?.dragged(rig, at: p) }
+ lastDrag = p
+ if u >= 1 { rig.touchUp(); rig.staged?.released(rig); lastDrag = nil; drags.remove(at: i) }
+ }
+ for (i, (e, t0)) in crowns.enumerated().reversed() {
+ let over = e.over ?? 1
+ rig.crown(e.crown! * dt / over)
+ if t - t0 >= over { crowns.remove(at: i) }
+ }
+ for (i, (e, t0)) in shakes.enumerated().reversed() {
+ let g = e.shake!, s = t - t0
+ rig.motion(g * sin(s * TAU * 4.5), g * 0.8 * sin(s * TAU * 3.7 + 1), g * 0.7 * sin(s * TAU * 5.3 + 2))
+ if s >= (e.over ?? 1) { rig.motion(0, 0, 0); shakes.remove(at: i) }
+ }
+ rig.tick(dt)
+ shoot(String(format: "f%05d.png", index)); index += 1
+ t += dt
+ }
+ }
+ try? Data("done".utf8).write(to: dir.appendingPathComponent("DONE"))
+ print("render: \(spec.name) done")
+ }
+}
+#endif
diff --git a/app/ChumsWatch/Rig/Chalk.swift b/app/ChumsWatch/Rig/Chalk.swift
new file mode 100644
index 0000000..661b53f
--- /dev/null
+++ b/app/ChumsWatch/Rig/Chalk.swift
@@ -0,0 +1,205 @@
+import SwiftUI
+
+/// A hand-drawn stroke, like a white paint marker (Posca) dragged over a dark board: an opaque round-tipped line,
+/// a little uneven in width, that presses in where it starts and lifts off where it ends (it thins out and fades),
+/// with the dry streaks and grain of chalk inside it, more of them toward its edges and its tail.
+/// Its texture is fixed to the line (by `seed` and the distance along it), so it never crawls or flickers as the line
+/// moves; `squash` reshapes the line (a blink) without stretching the texture or the pen's width.
+enum Chalk {
+ /// The dryness of the pen: 0 is a fresh marker (solid, a few streaks), 1 is chalk (broken up, grainy).
+ nonisolated(unsafe) static var dry = 0.55
+
+ /// A stroke, made: its pieces as paths, to draw now or keep and draw again while its line stays the same.
+ struct Stroke {
+ var body = Path(), joints = Path(), pits = Path(), splits = Path(), dot: Path? = nil
+ var tail: Path? = nil, fadeFrom = CGPoint.zero, fadeTo = CGPoint.zero
+ func draw(_ g: GraphicsContext, color: Color = .white) {
+ if let d = dot { g.fill(d, with: .color(color)); return }
+ // the tail first, so where a ring's tail comes back over its start, the start stays whole on top of it
+ if let t = tail {
+ let fade = Gradient(stops: [.init(color: color, location: 0), .init(color: color.opacity(0.97), location: 0.35),
+ .init(color: color.opacity(0.55), location: 0.7), .init(color: color.opacity(0.14), location: 0.9),
+ .init(color: color.opacity(0), location: 1)])
+ g.fill(t, with: .linearGradient(fade, startPoint: fadeFrom, endPoint: fadeTo))
+ if !splits.isEmpty { g.fill(splits, with: .color(.black.opacity(0.85))) }
+ }
+ g.fill(body, with: .color(color))
+ if !joints.isEmpty { g.fill(joints, with: .color(color)) }
+ if !pits.isEmpty { g.fill(pits, with: .color(.black.opacity(0.85))) }
+ }
+ }
+
+ static func draw(_ g: GraphicsContext, _ pts: [P2], width w: Double, seed: Double, color: Color = .white,
+ squash: ((P2) -> P2)? = nil) {
+ make(pts, width: w, seed: seed, squash: squash).draw(g, color: color)
+ }
+
+ /// The stroke through `pts`, `w` wide; `seed` picks its texture; `squash` moves each point of the line after its
+ /// texture is laid along it.
+ static func make(_ pts: [P2], width w: Double, seed: Double, squash: ((P2) -> P2)? = nil) -> Stroke {
+ var out = Stroke()
+ guard pts.count > 1 else { return out }
+ // the line, smooth and evenly sampled; `tex` is the distance along it before any squash
+ let line0 = smooth(pts)
+ var tex = [Double](repeating: 0, count: line0.count)
+ for i in 1..<line0.count { tex[i] = tex[i - 1] + simd_length(line0[i] - line0[i - 1]) }
+ let line = squash.map { f in line0.map(f) } ?? line0
+ let n = line.count
+ var arc = [Double](repeating: 0, count: n), nrm = [P2](repeating: P2(0, 1), count: n)
+ for i in 0..<n {
+ if i > 0 { arc[i] = arc[i - 1] + simd_length(line[i] - line[i - 1]) }
+ let d = line[min(n - 1, i + 1)] - line[max(0, i - 1)], l = simd_length(d)
+ nrm[i] = l > 1e-9 ? P2(-d.y / l, d.x / l) : (i > 0 ? nrm[i - 1] : P2(0, 1))
+ }
+ let L = arc[n - 1], h0 = w / 2
+ // a dot: too short to be a line
+ if L < w * 0.3 {
+ let c = line[n / 2], r = h0 * (0.9 + 0.1 * min(1, L / (w * 0.3)))
+ out.dot = Path(ellipseIn: CGRect(x: c.x - r, y: c.y - r, width: 2 * r, height: 2 * r))
+ return out
+ }
+
+ // its width: pressing in at the start, lifting off at the end, a slow wander between, each edge its own
+ let pressIn = min(w * 0.55, L * 0.22), liftOff = min(w * 2.1, L * 0.42)
+ let ph = Strokes.hash(seed, 1.7) * TAU, ph2 = Strokes.hash(seed, 2.9) * TAU
+ var hl = [Double](repeating: 0, count: n), hr = hl
+ for i in 0..<n {
+ let a = arc[i], s = tex[i]
+ var k = 1.0
+ if a < pressIn { k *= 0.84 + 0.16 * smooth01(a / pressIn) }
+ let e = L - a
+ if e < liftOff { let u = 1 - e / liftOff; k *= 1 - 0.62 * pow(u, 1.6) }
+ k *= 1 + 0.05 * sin(s / (w * 1.9) + ph) + 0.03 * sin(s / (w * 0.7) + ph2)
+ hl[i] = h0 * k * (1 + 0.07 * (vnoise(s / (w * 0.55), seed + 11) - 0.5))
+ hr[i] = h0 * k * (1 + 0.07 * (vnoise(s / (w * 0.55), seed + 23) - 0.5))
+ }
+
+ // the texture is cut out of it in the background's black: thin spindles along the line at a fraction `o` of its
+ // half-width, `th(u)` thick along their length
+ func spindle(_ path: inout Path, _ i: Int, _ j: Int, _ o: Double, _ th: (Double) -> Double) {
+ var left: [CGPoint] = [], right: [CGPoint] = []
+ for k in i...j {
+ let u = Double(k - i) / Double(max(1, j - i)), t = th(u)
+ let q = line[k] + nrm[k] * (o * (o > 0 ? hl[k] : hr[k]))
+ left.append(CGPoint(x: q.x + nrm[k].x * t, y: q.y + nrm[k].y * t))
+ right.append(CGPoint(x: q.x - nrm[k].x * t, y: q.y - nrm[k].y * t))
+ }
+ path.move(to: left[0]); for q in left.dropFirst() { path.addLine(to: q) }
+ for q in right.reversed() { path.addLine(to: q) }
+ path.closeSubpath()
+ }
+
+ // the tail first, where it lifts off: it thins, fades and, the pen running dry, splits into a few bristles.
+ // The body goes over it, so where a ring's tail comes back over its start the start stays whole.
+ let tailStart = L - liftOff * 0.95
+ var iT = n - 1
+ while iT > 1 && arc[iT - 1] > tailStart { iT -= 1 }
+ if iT < n - 1 {
+ let tail = ribbon(line, nrm, hl, hr, iT, n - 1, startCap: false, endCap: true)
+ let dir = line[n - 1] - line[n - 2], a = line[iT], b = line[n - 1] + dir / max(1e-9, simd_length(dir)) * hl[n - 1]
+ out.tail = tail; out.fadeFrom = CGPoint(x: a.x, y: a.y); out.fadeTo = CGPoint(x: b.x, y: b.y)
+ var splits = Path()
+ let count = 2 + Int((dry * 3).rounded())
+ for k in 0..<count {
+ let kk = Double(k)
+ let o = (-0.62 + 1.24 * (kk + 0.5) / Double(count)) + (Strokes.hash(seed + kk, 12.1) - 0.5) * 0.18
+ let from = L - liftOff * (0.85 - 0.6 * Strokes.hash(seed + kk, 13.3))
+ var i = n - 1
+ while i > 0 && arc[i - 1] >= from { i -= 1 }
+ guard i < n - 2 else { continue }
+ let mw = w * (0.045 + 0.06 * Strokes.hash(seed + kk, 14.7)) * (0.6 + 0.7 * dry)
+ spindle(&splits, i, n - 1, o, { u in mw * pow(u, 1.3) })
+ }
+ out.splits = splits
+ }
+ // the body, overlapping the tail by a sample, rounded off where it turns hard (the ribbon's outer side opens up)
+ let bEnd = min(n - 1, iT + 1)
+ out.body = ribbon(line, nrm, hl, hr, 0, bEnd, startCap: true, endCap: bEnd >= n - 1)
+ var joints = Path()
+ if bEnd >= 2 {
+ for i in 1..<bEnd where simd_dot(nrm[i - 1], nrm[i + 1]) < 0.6 {
+ let r = (hl[i] + hr[i]) / 2
+ joints.addEllipse(in: CGRect(x: line[i].x - r, y: line[i].y - r, width: 2 * r, height: 2 * r))
+ }
+ }
+ out.joints = joints
+ // the board's tooth in it: hairline pits running with the stroke, few in its middle, more at its edges (biting
+ // into its outline)
+ var pits = Path()
+ let lanes = 11, cl = w * 0.3
+ for b in 0..<lanes {
+ let lb = Double(b)
+ let o = -1.0 + 2.0 * lb / Double(lanes - 1) + (Strokes.hash(seed + lb, 5.1) - 0.5) * 0.08
+ let edge = min(1, abs(o)), shift = Strokes.hash(seed + lb, 2.2) * cl
+ var c = 0.0, i = 0
+ while c * cl < tex[bEnd] {
+ let r = Strokes.hash(seed * 1.3 + lb * 7.7, c * 0.917), r2 = Strokes.hash(c * 1.71 + lb, seed + 0.5)
+ let t0 = c * cl - shift + r2 * cl * 0.4
+ while i < bEnd && tex[i] < t0 { i += 1 }
+ if r < dry * (0.05 + 0.42 * pow(edge, 4)) {
+ let t1 = t0 + cl * (0.6 + 1.8 * r2)
+ var j = i
+ while j < bEnd && tex[j + 1] <= t1 { j += 1 }
+ let tw = w * (0.012 + 0.022 * Strokes.hash(seed + lb * 3.3, c * 1.13 + 0.4)) * (0.7 + 0.6 * edge)
+ if j > i { spindle(&pits, i, j, o, { u in tw * pow(sin(u * Double.pi), 0.6) }) }
+ }
+ c += 1
+ }
+ }
+ out.pits = pits
+ return out
+ }
+
+ // MARK: pieces
+
+ /// The outline of the stroke from sample `a` to `b`: its left edge, a round end, its right edge back.
+ private static func ribbon(_ line: [P2], _ nrm: [P2], _ hl: [Double], _ hr: [Double], _ a: Int, _ b: Int,
+ startCap: Bool, endCap: Bool) -> Path {
+ var p = Path()
+ func pt(_ v: P2) -> CGPoint { CGPoint(x: v.x, y: v.y) }
+ p.move(to: pt(line[a] + nrm[a] * hl[a]))
+ for i in (a + 1)...b { p.addLine(to: pt(line[i] + nrm[i] * hl[i])) }
+ if endCap { cap(&p, line[b], nrm[b], hl[b], hr[b], forward: true) } else { p.addLine(to: pt(line[b] - nrm[b] * hr[b])) }
+ for i in stride(from: b - 1, through: a, by: -1) { p.addLine(to: pt(line[i] - nrm[i] * hr[i])) }
+ if startCap { cap(&p, line[a], -nrm[a], hr[a], hl[a], forward: true) }
+ p.closeSubpath()
+ return p
+ }
+ /// A half-round end, from the side at +n to the side at -n, bulging along the line's direction.
+ private static func cap(_ p: inout Path, _ c: P2, _ n: P2, _ h1: Double, _ h2: Double, forward: Bool) {
+ let t = P2(n.y, -n.x) // the direction the line runs, out of this end
+ for k in 1...7 {
+ let a = Double(k) / 8 * Double.pi
+ let h = h1 + (h2 - h1) * Double(k) / 8
+ let v = c + n * (cos(a) * h) + t * (sin(a) * h * 0.92)
+ p.addLine(to: CGPoint(x: v.x, y: v.y))
+ }
+ let e = c - n * h2
+ p.addLine(to: CGPoint(x: e.x, y: e.y))
+ }
+
+ /// The points as a smooth line (Catmull-Rom), about every 0.6 pt.
+ static func smooth(_ pts: [P2]) -> [P2] {
+ let m = pts.count
+ var out: [P2] = [pts[0]]
+ for i in 0..<(m - 1) {
+ let p0 = pts[max(0, i - 1)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[min(m - 1, i + 2)]
+ let per = max(1, min(8, Int(simd_length(p2 - p1) / 0.6)))
+ for k in 1...per {
+ let u = Double(k) / Double(per), u2 = u * u, u3 = u2 * u
+ let a: P2 = p1 * 2, b: P2 = (p2 - p0) * u
+ let c1: P2 = p0 * 2 - p1 * 5, c2: P2 = p2 * 4 - p3, c: P2 = (c1 + c2) * u2
+ let d1: P2 = p1 * 3 - p0, d2: P2 = p3 - p2 * 3, d: P2 = (d1 + d2) * u3
+ out.append((a + b + c + d) * 0.5)
+ }
+ }
+ return out
+ }
+ @inline(__always) private static func smooth01(_ u: Double) -> Double { let v = clamp(u, 0, 1); return v * v * (3 - 2 * v) }
+ /// Smooth value noise in 0…1.
+ @inline(__always) static func vnoise(_ x: Double, _ seed: Double) -> Double {
+ let i = floor(x), f = x - i, u = f * f * (3 - 2 * f)
+ let a = Strokes.hash(seed, i * 0.618), b = Strokes.hash(seed, (i + 1) * 0.618)
+ return a + (b - a) * u
+ }
+}
diff --git a/app/ChumsWatch/Rig/Characters.swift b/app/ChumsWatch/Rig/Characters.swift
new file mode 100644
index 0000000..320e74b
--- /dev/null
+++ b/app/ChumsWatch/Rig/Characters.swift
@@ -0,0 +1,170 @@
+import SwiftUI
+
+/// The characters the rig draws itself (the others draw themselves: Staged). Each reads the same Pose.
+enum Characters {
+ static func draw(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose) {
+ switch r.character {
+ case .peeps: drawEyes(r, ctx, p)
+ case .stretch, .crunch, .nana, .squint, .ray, .tangle, .noodle: break // staged: they draw themselves (Renderer)
+ }
+ }
+
+ // MARK: eyes (Peeps')
+
+ struct EyeStyle { var y: Double, gap: Double, w: Double, h: Double, n: Double, color: Color, rx: Double, ry: Double, stroke: Bool, pulse: Double }
+
+ static func superellipse(_ a: Double, _ b: Double, _ n: Double) -> Path {
+ var p = Path()
+ for i in 0...72 {
+ let th = Double(i) / 72 * TAU, c = cos(th), s = sin(th)
+ let pt = CGPoint(x: (c < 0 ? -1 : 1) * pow(abs(c), 2 / n) * a, y: (s < 0 ? -1 : 1) * pow(abs(s), 2 / n) * b)
+ if i == 0 { p.move(to: pt) } else { p.addLine(to: pt) }
+ }
+ p.closeSubpath(); return p
+ }
+
+ /// Solid eyes with no pupils: lids make every expression (sleepy flattens the top, worried slants it,
+ /// intent narrows top and bottom, happy leaves an upward crescent).
+ static func drawEyePair(_ ctx: GraphicsContext, _ o: EyeStyle, _ E: EyePose) {
+ for side in [-1.0, 1.0] {
+ let ex = side * o.gap + E.gx * o.rx + E.tremorX * 0.5, ey = o.y + E.gy * o.ry + E.tremorY * 0.5
+ var c = ctx; c.translateBy(x: ex, y: ey)
+ drawEye(c, o, E, side: side)
+ }
+ }
+
+ /// One eye, centered on the context's origin; `side` is −1 for the left one, 1 for the right (lids slant and
+ /// spirals turn the other way).
+ static func drawEye(_ c0: GraphicsContext, _ o: EyeStyle, _ E: EyePose, side: Double) {
+ var c = c0
+ let a0 = o.w / 2 * (1 + 0.15 * E.wide) * (1 + o.pulse * 0.1), b0 = o.h / 2 * (1 + 0.15 * E.wide) * (1 + o.pulse * 0.12)
+ do {
+ if E.spiral {
+ let sr = max(a0 * 1.05, 6.5), rot = Date().timeIntervalSinceReferenceDate * TAU * 1.2 * side
+ var sp = Path()
+ for k in 0...60 {
+ let u = Double(k) / 60, th = u * 2.2 * TAU + rot, rr = u * sr
+ let pt = CGPoint(x: cos(th) * rr, y: sin(th) * rr); if k == 0 { sp.move(to: pt) } else { sp.addLine(to: pt) }
+ }
+ c.stroke(sp, with: .color(o.color), style: StrokeStyle(lineWidth: max(1.8, sr * 0.26), lineCap: .round, lineJoin: .round))
+ return
+ }
+ if E.closed > 0.5 || E.open < 0.12 {
+ let depth = a0 * 0.36, k = E.wince ? -1.0 : 1.0
+ var cp = Path(); cp.move(to: CGPoint(x: -a0 * 0.9, y: -depth * 0.3 * k))
+ cp.addQuadCurve(to: CGPoint(x: a0 * 0.9, y: -depth * 0.3 * k), control: CGPoint(x: 0, y: depth * 1.2 * k))
+ c.stroke(cp, with: .color(o.color), style: StrokeStyle(lineWidth: max(2.4, b0 * 0.2), lineCap: .round))
+ return
+ }
+ let b = b0 * clamp(E.open, 0.08, 1), a = a0 * (1 + 0.06 * (1 - E.open))
+ let topCover = b * 2 * (0.45 * E.sleepy + 0.22 * E.worried + 0.1 * E.intent)
+ let slope = tan(18 * DEG) * E.worried
+ let botY = b - b * 2 * 0.26 * E.intent
+ // lids are curved like real ones, the top arched and the bottom bowed: a little lid trims the eye's rounded
+ // corners instead of cutting a flat across it
+ let xl = -a * 1.4, xr = a * 1.4, yl = -b + topCover + slope * xl * side, yr = -b + topCover + slope * xr * side
+ var lid = Path()
+ lid.move(to: CGPoint(x: xl, y: yl))
+ lid.addQuadCurve(to: CGPoint(x: xr, y: yr), control: CGPoint(x: 0, y: (yl + yr) / 2 - b * 0.4))
+ lid.addLine(to: CGPoint(x: xr, y: botY))
+ lid.addQuadCurve(to: CGPoint(x: xl, y: botY), control: CGPoint(x: 0, y: botY + b * 0.36))
+ lid.closeSubpath()
+ c.clip(to: lid)
+ if E.happy > 0.01 {
+ // subtract an ellipse rising from below: at full happy only an upward crescent remains
+ var h = Path(CGRect(x: -a * 2, y: -b * 3, width: a * 4, height: b * 6))
+ let cy = lerp(2.2 * b, 0.75 * b, E.happy)
+ h.addEllipse(in: CGRect(x: -a * 1.15, y: cy - b, width: a * 2.3, height: b * 2))
+ c.clip(to: h, style: FillStyle(eoFill: true))
+ }
+ let shape = superellipse(a, b, o.n)
+ if o.stroke { c.stroke(shape, with: .color(o.color), lineWidth: 1.6) } else { c.fill(shape, with: .color(o.color)) }
+ }
+ }
+
+ static func ring(_ ctx: GraphicsContext, _ x: Double, _ y: Double, _ r: Double, _ amber: Double, _ t: Double) {
+ guard amber > 0.02 else { return }
+ ctx.faded(amber * (0.7 + 0.3 * sin(t * TAU * 1.2))).strokeCircle(x, y, r, Pal.amber, 3)
+ }
+
+ // MARK: Eyes
+
+ static func drawEyes(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose) {
+ let c = p.c, w = lerp(22, 26, c), h = lerp(34, 38, c), n = lerp(3, 2.2, c)
+ let gap = 30 * (1 - (p.sy - 1) * 0.5)
+ let col = p.amber > 0.5 ? Pal.amber : Pal.white
+ var g = p.ao ? ctx.faded(0.5) : ctx // dimmed (always on): its colors at half brightness
+ g.translateBy(x: p.cx, y: p.cy + h / 2 * p.scale); g.rotate(by: .radians(p.tilt)); g.scaleBy(x: p.scale / p.sy, y: p.scale * p.sy); g.translateBy(x: 0, y: -h / 2)
+ drawEyePair(g, EyeStyle(y: 0, gap: gap, w: w, h: h, n: n, color: p.tint ?? col, rx: 8, ry: 6, stroke: false, pulse: p.pulse), p.eye)
+ }
+
+
+ // MARK: props for Peeps (portrait)
+
+ static func dropPath(x: Double, y: Double, s: Double) -> Path {
+ var p = Path()
+ p.move(to: CGPoint(x: x, y: y - 6 * s))
+ p.addQuadCurve(to: CGPoint(x: x, y: y + 5.5 * s), control: CGPoint(x: x + 5.5 * s, y: y + 2.5 * s))
+ p.addQuadCurve(to: CGPoint(x: x, y: y - 6 * s), control: CGPoint(x: x - 5.5 * s, y: y + 2.5 * s))
+ return p
+ }
+
+ static func drawProps(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose) {
+ for q in r.particles {
+ let a = clamp(1 - q.age / q.life, 0, 1)
+ let x = p.cx + q.x, y = p.cy + q.y
+ switch q.kind {
+ case .spark:
+ var s = Path()
+ for i in 0..<8 { let rr = i % 2 == 1 ? 1.6 : 4.4, th = Double(i) * .pi / 4; let pt = CGPoint(x: x + cos(th) * rr, y: y + sin(th) * rr); if i == 0 { s.move(to: pt) } else { s.addLine(to: pt) } }
+ s.closeSubpath(); ctx.faded(a).fill(s, with: .color(Pal.amber))
+ case .heart:
+ var h = Path(); let k = 1.4
+ h.move(to: CGPoint(x: x, y: y + 4 * k))
+ h.addCurve(to: CGPoint(x: x, y: y - 4 * k), control1: CGPoint(x: x - 8 * k, y: y - 2.5 * k), control2: CGPoint(x: x - 4 * k, y: y - 8.5 * k))
+ h.addCurve(to: CGPoint(x: x, y: y + 4 * k), control1: CGPoint(x: x + 4 * k, y: y - 8.5 * k), control2: CGPoint(x: x + 8 * k, y: y - 2.5 * k))
+ ctx.faded(a).fill(h, with: .color(Pal.heart))
+ case .sweat: ctx.fill(dropPath(x: x, y: y, s: 1), with: .color(Pal.sweat))
+ case .ripple: let k = q.age / q.life; ctx.faded((1 - k) * 0.8).strokeCircle(x, y, 30 + k * 40, Pal.white, 1.4)
+ case .z: ctx.faded(a).draw(Text("z").font(.system(size: 10 + q.age * 2.4, weight: .semibold)).foregroundColor(Pal.gray), at: CGPoint(x: x, y: y))
+ }
+ }
+ if r.state == .thinking {
+ for i in 0..<3 { ctx.faded(0.3 + 0.7 * max(0, sin(p.t * 6 - Double(i) * 0.8))).fillCircle(144 + Double(i) * 9, 62, 2.6, Pal.white) }
+ }
+ if r.state == .needs {
+ ctx.draw(Text(r.variant ? "?" : "!").font(.system(size: 20, weight: .semibold)).foregroundColor(Pal.amber), at: CGPoint(x: 158, y: 60))
+ }
+ if r.state == .sleep && r.variant {
+ ctx.fillCircle(44, 58, 7, Pal.gray); ctx.fillCircle(47.5, 55.5, 6.2, .black)
+ }
+ }
+
+ // MARK: portrait working and subagents
+
+ static func drawTyping(_ r: Rig, _ ctx: GraphicsContext, pixel: Bool) {
+ let T = r.typing, D = r.DOC
+ for i in 0...min(T.line, 2) {
+ let full = D.w * T.widths[i], w = i < T.line ? full : full * T.prog
+ guard w >= 1 else { continue }
+ let y = D.y + Double(i) * D.gap, col = i == T.line ? Pal.gray : Pal.dim
+ if pixel {
+ var p = Path(); let s = 3.6
+ for k in 0..<Int(w / s) { p.addRect(CGRect(x: D.x + Double(k) * s, y: y, width: s - 0.6, height: s)) }
+ ctx.fill(p, with: .color(col))
+ } else { ctx.fillRoundRect(D.x, y, w, 3.4, 1.7, col) }
+ }
+ if T.line <= 2 && Int(r.t * 2.2) % 2 == 0 { ctx.fillRect(r.caretX() + 2, D.y + Double(T.line) * D.gap - 2.2, 1.8, 7.8, Pal.white) }
+ }
+
+ static func drawHelpers(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose) {
+ for (i, x) in [52.0, 99, 146].enumerated() {
+ let bob = max(0, sin(p.t * TAU * 1.5 + Double(i) * 2.1)) * 3
+ var m = p
+ m.cx = x; m.cy = 196 - bob; m.scale = r.character == .peeps ? 0.32 : 0.36; m.sy = 1; m.tilt = 0; m.amber = 0; m.pulse = 0
+ m.mini = true; m.unitScale = 0.36; m.phase = Double(i) * 0.7
+ m.eye = .neutral(gx: 0, gy: 0.5, intent: 0.7)
+ draw(r, ctx, m)
+ }
+ }
+}
diff --git a/app/ChumsWatch/Rig/NoodleRest.swift b/app/ChumsWatch/Rig/NoodleRest.swift
new file mode 100644
index 0000000..56deb45
--- /dev/null
+++ b/app/ChumsWatch/Rig/NoodleRest.swift
@@ -0,0 +1,13 @@
+import simd
+
+// Generated by design/characters/coil3d/export.py; do not edit by hand.
+// The colour model fitted to the reference: an albedo along the tube (tail to head) × a light of where its surface
+// faces (9 terms: 1, x, y, z, xy, xz, yz, x²−y², 3z²−1), plus a sheen. Coil's shapes and the changes between them are
+// in noodle-shapes.bin (design/characters/coil3d/bakeall.py).
+
+enum NoodleRest {
+ static let length = 461.749, radius = 14.500
+ static let albedo: [SIMD3<Double>] = [SIMD3(0.29726, 0.42719, 0.87854), SIMD3(0.61576, 0.46785, 0.87616), SIMD3(0.19151, 0.61922, 0.95174), SIMD3(0.19626, 0.68465, 0.95191), SIMD3(0.11870, 0.53001, 0.92171), SIMD3(0.20187, 0.38485, 0.90982), SIMD3(0.53575, 0.24933, 0.86741), SIMD3(0.69910, 0.15308, 0.67251), SIMD3(0.83687, 0.29390, 0.51923), SIMD3(0.78161, 0.31251, 0.70288), SIMD3(0.54595, 0.40696, 0.91386), SIMD3(0.53748, 0.34651, 0.90227), SIMD3(0.71375, 0.31993, 0.88333), SIMD3(0.88956, 0.46480, 0.77386), SIMD3(0.92825, 0.44527, 0.22190), SIMD3(0.92659, 0.47725, 0.18046)]
+ static let light: [Double] = [0.84488, -0.10194, 0.21310, 0.55242, -0.03921, 0.14323, -0.16665, 0.06919, -0.13055]
+ static let sheen: [Double] = [0.03846, 0.03785, -0.14596, -0.18758, -0.03766, -0.15785, 0.07060, -0.08013, 0.03057]
+}
diff --git a/app/ChumsWatch/Rig/NoodleStage.swift b/app/ChumsWatch/Rig/NoodleStage.swift
new file mode 100644
index 0000000..19a3ba4
--- /dev/null
+++ b/app/ChumsWatch/Rig/NoodleStage.swift
@@ -0,0 +1,898 @@
+import SwiftUI
+
+/// Noodle: a soft round tube, one width all along, its colour running from blue at the tail through purple and pink to a
+/// yellow-orange head with two cream eyes (lit from the reference, design/characters/coil3d).
+///
+/// It is a real 3D tube, a noodle: 64 points a fixed distance apart. It has a library of shapes (the zigzag, a tornado
+/// spiral, a tall spring, a sleep coil, a clump, a flat spiral, a lollipop, a slinky lying down, a knot), and changes
+/// between them along paths baked offline as a rope that keeps its length, never bends tighter than it can and never
+/// passes through itself (design/characters/coil3d/bakeall.py → noodle-shapes.bin). A change is a journey over one or
+/// more of those paths, played by distance at a steady pace (one ease-in, one ease-out, the corners at the shapes
+/// passed through rounded), so it never stalls on the way. On top, waves run along its body all the time as small
+/// sideways ripples (in two directions), so it's never still, without ever swinging it round. A soft self-collision
+/// keeps its parts apart, and after everything a bend limit keeps every joint rounder than the tube's own radius.
+/// Spirals spin; everything sways a little.
+///
+/// It is drawn as the union of spheres along its curve, back to front, in thin tiles that between them cover exactly
+/// that union (each disc's crescent beyond its nearer neighbour's disc; a disc nearer than both neighbours in strips),
+/// each tile one fill with one gradient across whose colours are what is really seen on that tile: the frontmost
+/// sphere there, its normal lit by a model fitted to the reference, darkened where another part of the tube is near
+/// (in 3D) or passes just in front (on screen). So a stretch running toward you reads as one smooth surface, not a
+/// stack of discs. The ends are rounded; the eyes sit on the head's end and are hidden by whatever is in front of
+/// them. Prototyped against a per-pixel truth in design/characters/coil3d/crescents/.
+/// Simulator measurements: NOODLE_DEBUG=1 prints the draw cost, NOODLE_DUMP=1 writes every frame's points.
+/// idle: the zigzag, flowing, and every 20 s or so off into another shape for a while and back · listening: up on its
+/// stick (the lollipop) · thinking: a flat spiral, turning slowly like a pinwheel · working: the tornado, turning,
+/// rippling on each tool call · subagents: the tall spring · speaking: the zigzag, flowing with its voice · done: pops
+/// up into the tall spring and spins · needs you: the lollipop, leaning in, knocking · blocked: winds up and ties
+/// itself in a knot, straining · dizzy: a clump, spinning · sleep: curled up in a coil, barely moving
+/// Every common change of state is one direct change of shape (no passing through others on the way).
+/// crown: spins it (the zigzag winds up into the tornado; the flat spiral turns); spun fast it's dizzy · drag: it
+/// leans toward your finger and looks at it · tap: a squeeze runs up it · shake: it bunches up and settles
+final class NoodleStage: Staged {
+ static let shared = NoodleStage()
+
+ let ownsApproval = false
+ let holds: [ChumsState: Double] = [.done: 3.6, .dizzy: 3.4]
+ func captionTop(_ r: Rig) -> Bool { false }
+ func ownsCaption(_ r: Rig) -> Bool { false }
+ var calm: Bool { t - busyAt > 1.2 }
+
+ typealias V3 = SIMD3<Double>
+ typealias P3 = SIMD3<Double>
+ static let N = 64
+ static let R = NoodleRest.radius
+ static let seg = NoodleRest.length / Double(N - 1)
+ static let ground = 70.0
+ static let cream = Color(red: 0.99, green: 0.915, blue: 0.83)
+
+ // MARK: maths
+
+ @inline(__always) static func unit(_ v: V3) -> V3 { let l = simd_length(v); return l > 1e-12 ? v / l : v }
+ @inline(__always) static func rotate(_ v: V3, _ axis: V3, _ a: Double) -> V3 {
+ let c = cos(a), s = sin(a)
+ let p: V3 = v * c + simd_cross(axis, v) * s
+ return p + axis * (simd_dot(axis, v) * (1 - c))
+ }
+ @inline(__always) static func ease(_ x: Double) -> Double { let v = clamp(x, 0, 1); return v * v * (3 - 2 * v) }
+
+ /// A frame at each point that doesn't twist along the tube (rotation minimising, by double reflection), starting
+ /// from `normal` when given (so it carries on smoothly from the last frame).
+ static func frames(_ P: [V3], normal: V3?) -> (m1: [V3], m2: [V3]) {
+ let n = P.count
+ var t = [V3](repeating: .zero, count: n)
+ for i in 0..<n { t[i] = unit(P[min(n - 1, i + 1)] - P[max(0, i - 1)]) }
+ var m1 = [V3](repeating: .zero, count: n), m2 = m1
+ var a: V3 = abs(t[0].z) < 0.9 ? V3(0, 0, 1) : V3(1, 0, 0)
+ if let g = normal, simd_length(g - t[0] * simd_dot(g, t[0])) > 0.2 { a = g }
+ m1[0] = unit(a - t[0] * simd_dot(a, t[0])); m2[0] = simd_cross(t[0], m1[0])
+ for i in 0..<(n - 1) {
+ let v1 = P[i + 1] - P[i], c1 = max(1e-12, simd_dot(v1, v1))
+ let rL: V3 = m1[i] - v1 * (2 / c1 * simd_dot(v1, m1[i]))
+ let tL: V3 = t[i] - v1 * (2 / c1 * simd_dot(v1, t[i]))
+ let v2 = t[i + 1] - tL, c2 = simd_dot(v2, v2)
+ m1[i + 1] = c2 > 1e-18 ? unit(rL - v2 * (2 / c2 * simd_dot(v2, rL))) : rL
+ m2[i + 1] = simd_cross(t[i + 1], m1[i + 1])
+ }
+ return (m1, m2)
+ }
+
+ // MARK: the shape library
+
+ enum Shape: Int, CaseIterable { case zigzag, tornado, spring, sleep, messy, shell, lolly, slinky, knot
+ /// What it spins round: 1 the upright, 2 the line of sight (a pinwheel), 0 it doesn't.
+ var axis: Int { switch self { case .tornado, .spring, .messy: return 1; case .shell: return 2; default: return 0 } }
+ }
+ struct Edge { let from: Int; let to: Int; let keys: [[V3]]; let secs: Double } // secs: the bake's own pace, unused now
+ static let library: (shapes: [[V3]], edges: [Edge]) = {
+ guard let url = Bundle.main.url(forResource: "noodle-shapes", withExtension: "bin"), let d = try? Data(contentsOf: url), d.count > 16
+ else { return ([[V3]](repeating: [V3](repeating: .zero, count: N), count: Shape.allCases.count), []) }
+ var o = 4
+ func i32() -> Int { let v = d.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: o, as: Int32.self) }; o += 4; return Int(v) }
+ func f32() -> Double { let v = d.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: o, as: Float.self) }; o += 4; return Double(v) }
+ func points(_ n: Int) -> [V3] { (0..<n).map { _ in let x = f32(), y = f32(), z = f32(); return V3(x, y, z) } }
+ let ns = i32(), n = i32(), ne = i32()
+ let shapes = (0..<ns).map { _ in points(n) }
+ var edges: [Edge] = []
+ for _ in 0..<ne {
+ let a = i32(), b = i32(), k = i32(), secs = f32()
+ edges.append(Edge(from: a, to: b, keys: (0..<k).map { _ in points(n) }, secs: secs))
+ }
+ return (shapes, edges)
+ }()
+
+ /// One edge of the graph, one way or the other.
+ struct Leg { var edge: Int; var forward: Bool
+ var from: Shape { let e = NoodleStage.library.edges[edge]; return Shape(rawValue: forward ? e.from : e.to)! }
+ var to: Shape { let e = NoodleStage.library.edges[edge]; return Shape(rawValue: forward ? e.to : e.from)! }
+ var keys: Int { NoodleStage.library.edges[edge].keys.count }
+ }
+ /// How far the tube travels (its fastest point's displacement) from each key of an edge to the next, summed: so a
+ /// change of shape can be played by distance, at a steady pace, however its keys are spaced.
+ static let travel: [[Double]] = library.edges.map { e in
+ var acc = [0.0]
+ for i in 1..<e.keys.count {
+ var d = 0.0
+ for j in 0..<N { d = max(d, simd_length(e.keys[i][j] - e.keys[i - 1][j])) }
+ acc.append(acc[i - 1] + d)
+ }
+ return acc
+ }
+ /// A change of shape under way: a route of legs, played by distance `s` along it (one ease-in at the start, one
+ /// ease-out at the end, the corners at the shapes passed through rounded), so it never stalls on the way.
+ struct Journey { var legs: [Leg]; var s = 0.0; var v = 0.0; var a = 0.0
+ var length: Double { legs.reduce(0) { $0 + NoodleStage.travel[$1.edge].last! } }
+ var to: Shape { legs.last!.to }
+ /// The pose at distance `d` along leg `i`.
+ func pose(leg i: Int, at d: Double) -> [V3] {
+ let g = legs[i], T = NoodleStage.travel[g.edge], n = g.keys
+ let dd = g.forward ? d : T.last! - d // distance in the edge's own direction
+ var k = 0
+ while k < n - 2 && T[k + 1] < dd { k += 1 }
+ let w = clamp((dd - T[k]) / max(1e-9, T[k + 1] - T[k]), 0, 1)
+ // a smooth curve through the keys (Catmull-Rom), so the motion has no corner at each key
+ let K = NoodleStage.library.edges[g.edge].keys
+ let a = K[max(0, k - 1)], b = K[k], c = K[k + 1], e = K[min(n - 1, k + 2)]
+ let w2 = w * w, w3 = w2 * w
+ let h0 = -0.5 * w3 + w2 - 0.5 * w, h1 = 1.5 * w3 - 2.5 * w2 + 1, h2 = -1.5 * w3 + 2 * w2 + 0.5 * w, h3 = 0.5 * w3 - 0.5 * w2
+ return (0..<NoodleStage.N).map { i in
+ let x: V3 = a[i] * h0 + b[i] * h1
+ return x + c[i] * h2 + e[i] * h3
+ }
+ }
+ /// The pose at `s`: on its leg, or, near a shape passed through, a blend of arriving and leaving (so the
+ /// motion rounds the corner instead of stopping on the shape and setting off again).
+ func pose() -> [V3] {
+ var start = 0.0
+ for i in 0..<legs.count {
+ let L = NoodleStage.travel[legs[i].edge].last!, end = start + L
+ if s <= end || i == legs.count - 1 {
+ let d = clamp(s - start, 0, L)
+ let r = 45.0 // how far before and after a corner the blend runs
+ if i + 1 < legs.count && s > end - r {
+ let a = Self.ease((s - (end - r)) / (2 * r))
+ let p1 = pose(leg: i, at: min(d, L)), p2 = pose(leg: i + 1, at: max(0, s - end))
+ return (0..<NoodleStage.N).map { p1[$0] * (1 - a) + p2[$0] * a }
+ }
+ if i > 0 && s < start + r {
+ let a = Self.ease((s - (start - r)) / (2 * r))
+ let p1 = pose(leg: i - 1, at: NoodleStage.travel[legs[i - 1].edge].last!), p2 = pose(leg: i, at: d)
+ return (0..<NoodleStage.N).map { p1[$0] * (1 - a) + p2[$0] * a }
+ }
+ return pose(leg: i, at: d)
+ }
+ start = end
+ }
+ return pose(leg: legs.count - 1, at: NoodleStage.travel[legs.last!.edge].last!)
+ }
+ static func ease(_ x: Double) -> Double { NoodleStage.ease(x) }
+ }
+
+ /// The quickest way from one shape to another, as legs.
+ static func route(_ a: Shape, _ b: Shape) -> [Leg] {
+ if a == b { return [] }
+ let E = library.edges, n = Shape.allCases.count
+ var dist = [Double](repeating: .infinity, count: n), via = [Int](repeating: -1, count: n), done = [Bool](repeating: false, count: n)
+ dist[b.rawValue] = 0 // from the goal back, so we know the first step
+ for _ in 0..<n {
+ var u = -1
+ for i in 0..<n where !done[i] && dist[i] < .infinity && (u < 0 || dist[i] < dist[u]) { u = i }
+ if u < 0 { break }
+ done[u] = true
+ for (k, e) in E.enumerated() {
+ let v = e.from == u ? e.to : e.to == u ? e.from : -1
+ if v >= 0 && dist[u] + e.secs < dist[v] { dist[v] = dist[u] + e.secs; via[v] = k }
+ }
+ }
+ var legs: [Leg] = [], u = a.rawValue
+ while u != b.rawValue {
+ let k = via[u]
+ guard k >= 0 else { return legs }
+ let g = Leg(edge: k, forward: E[k].from == u)
+ legs.append(g); u = g.to.rawValue
+ }
+ return legs
+ }
+
+ // MARK: state
+
+ private var at: Shape = .zigzag
+ private var journey: Journey?
+ private var world = NoodleStage.library.shapes[0] // as seen (turned, leaning)
+ private var delta = [V3](repeating: .zero, count: NoodleStage.N) // the self-collision's push, smoothed in time
+ private var spinY = (a: 0.0, v: 0.0, home: nil as Double?), spinZ = (a: 0.0, v: 0.0, home: nil as Double?)
+ private var sway = 0.0
+ private var flow = (amp: 0.05, phase1: 0.0, phase2: 0.0, kick: 0.0, kickWant: 0.0, speed: 0.45) // the waves running along it
+ private var nod = (a: 0.0, v: 0.0) // the head's nod, sprung so it never snaps
+ private var breath = (phase: 0.0, amp: 0.018, rate: 0.22), strainAmp = 0.0
+ private var lean = (x: 0.0, z: 0.0, vx: 0.0, vz: 0.0) // tipping toward you (x) and sideways (z)
+ private var wobble = (x: 0.0, z: 0.0, vx: 0.0, vz: 0.0)
+ private var stretch = (k: 1.0, v: 0.0)
+ private var crownIdle = 9.0, crownRate = 0.0, fastFor = 0.0
+ private var finger: CGPoint?
+ private var shakeFor = 0.0, energy = 0.0
+ private var reach = (p: P2.zero, v: P2.zero) // its head reaching toward your finger, on a spring
+ private var jig = (p: P2.zero, v: P2.zero) // flung about while the watch is shaken
+ private var hop = (y: 0.0, v: 0.0) // a tap: a hop
+ private var happyFor = 0.0, pokes: [Double] = []
+ private var knock = 0.0, nextTool = 0.8, minis = 0.0
+ private var wander = (shape: nil as Shape?, until: 0.0, next: 9.0, last: Shape.zigzag)
+ private var shown = (scale: 1.0, cy: 138.0)
+ private var state: ChumsState = .idle
+ private var t = 0.0, busyAt = 0.0
+
+ // MARK: Staged
+
+ func onState(_ r: Rig, _ s: ChumsState, prev: ChumsState?, variant: Bool) {
+ state = s
+ if s == .needs { knock = 0 }
+ if s != .idle { wander.shape = nil }
+ wander.next = max(wander.next, t + rnd(14, 20)) // not straight after a change of state
+ busyAt = t
+ }
+
+ /// What it should be shaped as now, how fast it spins, and how much it flows.
+ private func wanted(_ r: Rig) -> (shape: Shape, spin: Double, flow: Double, flowSpeed: Double) {
+ switch state {
+ case .listening: return (.lolly, 0, 0.03, 0.5)
+ case .thinking: return (.shell, 0.45, 0.035, 0.4)
+ case .working: return (.tornado, 1.5, 0.05, 0.75)
+ case .subagents: return (.spring, 0.6, 0.04, 0.5)
+ case .speaking: return (.zigzag, 0, 0.04 + voice * 0.03, 0.6)
+ case .done: return (.spring, 2.4, 0.05, 0.8) // pops up tall and spins
+ case .needs: return (.lolly, 0, 0.035, 0.55)
+ case .blocked: return (.knot, 0, 0.02, 0.3)
+ case .dizzy: return (.messy, 1.8, 0.06, 0.7)
+ case .sleep: return (.sleep, 0, 0.012, 0.18)
+ case .approval: return (.zigzag, 0, 0.03, 0.4)
+ default: return (wander.shape ?? .zigzag, wander.shape?.axis == 1 ? 0.5 : wander.shape?.axis == 2 ? 0.35 : 0, 0.04, 0.45)
+ }
+ }
+
+ /// The shape this frame, as points.
+ private func pose() -> [V3] { journey?.pose() ?? Self.library.shapes[at.rawValue] }
+
+ func step(_ r: Rig, _ dt0: Double) {
+ let dt = min(dt0, 0.04)
+ t += dt
+ guard !r.ao else { return }
+ let n = Self.N
+ crownIdle += dt; crownRate *= exp(-dt * 3)
+ voice += (r.voice - voice) * min(1, dt * 2.5) // the voice, eased (syllables would shake it)
+ fastFor = crownRate > 9 && crownIdle < 0.3 ? fastFor + dt : 0
+ if fastFor > 1 && state != .dizzy { fastFor = 0; r.setState(.dizzy) }
+ shakeFor = max(0, shakeFor - dt); energy *= exp(-dt * 4)
+ minis += ((state == .subagents ? 1 : 0) - minis) * min(1, dt * 3)
+ nextTool -= dt
+ if nextTool <= 0 && (!r.worlds.queue.isEmpty || state == .working), let c = r.worlds.nextEvent(r) {
+ nextTool = r.worlds.queue.isEmpty ? rnd(1.4, 2.4) : 0.5
+ if c.kind != .stop { flow.kickWant = max(flow.kickWant, 0.035) }
+ }
+ if state == .needs {
+ let was = knock; knock += dt; if knock >= 3.2 { knock = 0 }
+ if was < 0.25 && knock >= 0.25 { r.onHaptic?(.strong) }
+ }
+ // idle: now and then it goes off into another shape for a while, then comes back
+ if state == .idle && finger == nil {
+ if wander.shape == nil && t > wander.next {
+ let pick = [Shape.slinky, .spring, .shell, .lolly].filter { $0 != wander.last }
+ let s = pick[Int.random(in: 0..<pick.count)]
+ wander = (shape: s, until: t + rnd(6, 8), next: 0, last: s)
+ } else if let _ = wander.shape, t > wander.until, journey == nil {
+ wander.shape = nil; wander.next = t + rnd(16, 24)
+ }
+ }
+
+ // the shape: the journey under way, re-routed from the next shape on its way when what's wanted changes;
+ // played by distance at a steady pace, easing in at the start and out at the end (never stalling between)
+ var want = wanted(r)
+ let crowning = crownIdle < 1.6
+ if crowning && want.shape.axis == 0 && state != .blocked && state != .sleep { want.shape = .tornado } // the crown winds it up
+ if shakeFor > 0 && state != .blocked { want = (.messy, 1.5, 0.07, 0.8) }
+ if journey == nil && at != want.shape { let legs = Self.route(at, want.shape); if !legs.isEmpty { journey = Journey(legs: legs) } }
+ if var j = journey {
+ if j.to != want.shape {
+ // keep the leg under way, then go on from where it ends
+ var start = 0.0, i = 0
+ while i < j.legs.count - 1 && j.s > start + Self.travel[j.legs[i].edge].last! { start += Self.travel[j.legs[i].edge].last!; i += 1 }
+ let kept = Array(j.legs[0...i]), on = kept.last!.to
+ j.legs = kept + Self.route(on, want.shape)
+ }
+ let L = j.length, left = max(0, L - j.s)
+ let vmax = 85.0, acc = 150.0 // pt a second (its fastest point), and a second²
+ let vt = min(vmax, sqrt(2 * acc * 0.8 * left))
+ // the acceleration itself eases toward what's needed (limited jerk), so starts and stops are soft
+ let aWant = clamp((vt - j.v) * 3.5, -acc * 1.4, acc), jerk = 520.0
+ j.a += clamp(aWant - j.a, -jerk * dt, jerk * dt)
+ j.v = max(0, j.v + j.a * dt)
+ if left < 0.5 && j.v < 6 { j.s = L } else { j.s = min(L, j.s + j.v * dt) }
+ if j.s >= L - 1e-6 { at = j.to; journey = nil } else { journey = j }
+ }
+
+ // spinning: round the upright, or round the line of sight; anything that doesn't spin comes home to face you
+ let heading = journey?.to ?? at, from = journey?.legs.first?.from ?? at
+ func spinStep(_ s: inout (a: Double, v: Double, home: Double?), _ axis: Int, _ rate: Double) {
+ let spinning = heading.axis == axis && from.axis == axis
+ if spinning {
+ s.home = nil
+ if !(crowning && axis == 1) || heading.axis != 1 { s.v += (rate - s.v) * min(1, dt / 0.8) }
+ } else {
+ if s.home == nil { s.home = (s.a / TAU + clamp(s.v * 0.12, -0.45, 0.45)).rounded() * TAU }
+ let w = TAU * 0.7
+ s.v += (-w * w * (s.a - s.home!) - 2 * w * s.v) * dt
+ }
+ s.v = clamp(s.v, -10, 10); s.a += s.v * dt
+ }
+ spinStep(&spinY, 1, want.spin); spinStep(&spinZ, 2, want.spin)
+ sway = 0.3 * sin(t * TAU * 0.09) + 0.05 * sin(t * TAU * 0.23)
+
+ // leaning: toward you to listen or ask, toward your finger, a wobble when shaken
+ var lx = 0.0, lz = 0.0
+ if state == .listening { lx = 0.08 } else if state == .needs { lx = 0.12 }
+ if let f = finger {
+ let fx = Double(f.x), fy = Double(f.y)
+ lz = clamp((fx - 99) / 140, -0.3, 0.3); lx = clamp((shown.cy - 20 - fy) / 220, -0.1, 0.2)
+ }
+ let wl = TAU * 1.0
+ lean.vx += (-wl * wl * (lean.x - lx) - 2 * wl * lean.vx) * dt; lean.x += lean.vx * dt
+ lean.vz += (-wl * wl * (lean.z - lz) - 2 * wl * lean.vz) * dt; lean.z += lean.vz * dt
+ let ww = TAU * 1.2
+ wobble.vx += (-ww * ww * wobble.x - 2 * 0.6 * ww * wobble.vx) * dt; wobble.x += wobble.vx * dt
+ wobble.vz += (-ww * ww * wobble.z - 2 * 0.6 * ww * wobble.vz) * dt; wobble.z += wobble.vz * dt
+ var sk = 1.0
+ if let f = finger { let fy = Double(f.y); sk = clamp(1 + (fy - (shown.cy - 20)) / 900, 0.92, 1.06) }
+ let ws = TAU * 1.2
+ stretch.v += (-ws * ws * (stretch.k - sk) - 2 * ws * stretch.v) * dt; stretch.k += stretch.v * dt
+ let wantScale = state == .approval ? 0.48 : state == .subagents ? 0.86 : 1, wantCY = state == .approval ? 84.0 : 138
+ shown.scale += (wantScale - shown.scale) * min(1, dt * 3); shown.cy += (wantCY - shown.cy) * min(1, dt * 3)
+
+ // the waves along it: two, of different lengths and speeds, so it flows and never repeats exactly
+ flow.amp += (want.flow - flow.amp) * min(1, dt * 1.5)
+ flow.kickWant *= exp(-dt * 1.8); flow.kick += (flow.kickWant - flow.kick) * min(1, dt * 6)
+ flow.speed += (want.flowSpeed - flow.speed) * min(1, dt * 2)
+ let speed = flow.speed * (1 + flow.kick * 12)
+ flow.phase1 += dt * TAU * speed; flow.phase2 += dt * TAU * speed * 0.73
+ // breathing, eased between states (a sudden change in it would swing the tube)
+ let sleeping = state == .sleep
+ breath.amp += ((sleeping ? 0.012 : 0.018) - breath.amp) * min(1, dt * 1.5)
+ breath.rate += ((sleeping ? 0.15 : 0.22) - breath.rate) * min(1, dt * 1.5)
+ breath.phase += dt * TAU * breath.rate
+ strainAmp += ((state == .blocked && journey == nil ? 0.03 : 0) - strainAmp) * min(1, dt * 2)
+
+ // the shape, with the waves running along it as small sideways ripples (they don't add up along it, so they never
+ // swing the body round), breathing as a slight stretch upward, a nod of the head
+ let target = pose()
+ var P = target
+ let F = Self.frames(target, normal: rodNormal)
+ rodNormal = F.m1[0]
+ let breathe = breath.amp * sin(breath.phase) + strainAmp * sin(t * TAU * 0.9)
+ let amp = Self.off("RIPPLE") ? 0 : (flow.amp + flow.kick) * 130 // in pt
+ for i in 1..<n {
+ let u = Double(i) / Double(n - 1), root = Self.ease(u / 0.12)
+ let w1 = sin(u * TAU * 1.8 - flow.phase1), w2 = sin(u * TAU * 2.9 - flow.phase2 + 1.3)
+ let off: V3 = F.m1[i] * (w1 * amp) + F.m2[i] * (w2 * amp * 0.6)
+ P[i] += off * root
+ P[i].y = Self.ground + (P[i].y - Self.ground) * (1 + breathe) * stretch.k
+ }
+ // the head nods: the last stretch of it turns about where the neck starts; the knock starts from rest
+ let nodWant: Double = state == .needs ? 0.3 * max(0, sin(min(1, knock / 1.0) * 4 * .pi)) * Self.ease(knock / 0.15)
+ : state == .speaking ? voice * 0.15 : 0
+ let wn = TAU * 2.5
+ nod.v += (-wn * wn * (nod.a - nodWant) - 2 * wn * nod.v) * dt; nod.a += nod.v * dt
+ if abs(nod.a) > 1e-4 {
+ let k0 = Int(0.8 * Double(n - 1)), piv = P[k0], ax = F.m1[k0]
+ for i in (k0 + 1)..<n {
+ let w = Self.ease(Double(i - k0) / 4)
+ P[i] = piv + Self.rotate(P[i] - piv, ax, nod.a * w)
+ }
+ }
+ // its parts kept apart: a soft push, smoothed along the tube and in time
+ let need = Self.off("SEP") ? [V3](repeating: .zero, count: n) : separation(P)
+ let kk = min(1, dt * (finger != nil ? 16 : 10))
+ for i in 0..<n { delta[i] += (need[i] - delta[i]) * kk; P[i] += delta[i] }
+ if Self.timing {
+ var worst = 0.0
+ for i in 1..<(n - 1) { worst = max(worst, acos(clamp(simd_dot(Self.unit(P[i] - P[i - 1]), Self.unit(P[i + 1] - P[i])), -1, 1))) }
+ bendStat = max(bendStat, worst / Self.seg * Self.R)
+ }
+ if let d = Self.dumpStages {
+ var f = [Float](repeating: 0, count: 1 + Self.N * 6); f[0] = Float(t)
+ for i in 0..<Self.N { for c in 0..<3 { f[1 + 3 * i + c] = Float(target[i][c]); f[1 + 3 * Self.N + 3 * i + c] = Float(P[i][c]) } }
+ d.write(f.withUnsafeBufferPointer { Data(buffer: $0) })
+ }
+ // seen: spun round its middle (the upright, or the line of sight), swaying, leaning on its foot, on the ground
+ var mid = V3.zero
+ for p in P { mid += p }
+ mid /= Double(n)
+ let yaw = spinY.a + sway, cyw = cos(yaw), syw = sin(yaw)
+ let roll = spinZ.a, cr = cos(roll), sr = sin(roll)
+ let ax = lean.x + wobble.x, az = lean.z + wobble.z
+ var W = P
+ var lowest = -1e9
+ for i in 0..<n {
+ var a = P[i] - mid
+ a = V3(cyw * a.x + syw * a.z, a.y, -syw * a.x + cyw * a.z)
+ a = V3(cr * a.x - sr * a.y, sr * a.x + cr * a.y, a.z)
+ a = Self.rotate(a, V3(1, 0, 0), ax)
+ a = Self.rotate(a, V3(0, 0, 1), -az)
+ W[i] = a + mid
+ lowest = max(lowest, W[i].y)
+ }
+ // on the ground, eased (so a spin or a lean never jolts it up and down)
+ if started { groundShift += ((Self.ground - lowest) - groundShift) * min(1, dt * 8) } else { groundShift = Self.ground - lowest; started = true }
+ for i in 0..<n { W[i].y += groundShift }
+ // your finger: its head reaches for it (and swings a little past when you let go); shaken, it's flung about,
+ // its head whipping more than its foot; tapped, it hops
+ var toward = P2.zero
+ if let f = finger {
+ let fw = P2((Double(f.x) - 99) / shown.scale, (Double(f.y) - shown.cy) / shown.scale)
+ toward = fw - P2(W[n - 1].x, W[n - 1].y)
+ let l = simd_length(toward); if l > 34 { toward *= 34 / l }
+ }
+ let wr = TAU * 1.5, wj = TAU * 2.2
+ reach.v += ((toward - reach.p) * (wr * wr) - reach.v * (2 * 0.5 * wr)) * dt; reach.p += reach.v * dt
+ jig.v += (jig.p * (-wj * wj) - jig.v * (2 * 0.3 * wj)) * dt; jig.p += jig.v * dt
+ let jl = simd_length(jig.p); if jl > 26 { jig.p *= 26 / jl }
+ hop.v += 950 * dt; hop.y += hop.v * dt; if hop.y > 0 { if hop.v > 120 { flow.kickWant = max(flow.kickWant, 0.04) }; hop.y = 0; hop.v = 0 }
+ happyFor = max(0, happyFor - dt)
+ for i in 0..<n {
+ let u = Double(i) / Double(n - 1), a = clamp((u - 0.35) / 0.65, 0, 1), wR = a * a * (3 - 2 * a), wJ = pow(u, 1.5)
+ W[i].x += reach.p.x * wR + jig.p.x * wJ
+ W[i].y += reach.p.y * wR + jig.p.y * wJ + hop.y
+ }
+ world = W
+
+ // 30 frames a second are plenty for its own motion (it's soft and slow, and each frame is a lot of pixels); the
+ // full rate only while your finger or the crown moves it, so it keeps up with your hand
+ if finger != nil || crownIdle < 1.2 { busyAt = t }
+ }
+ private var groundShift = 0.0, started = false, voice = 0.0
+ private var rodNormal: V3?
+
+ /// How far each point must move so no two parts of the tube come closer than its width: pushes that ease in, the
+ /// head's side giving more than the foot's, smoothed along the tube so a push is a bump and never a kink.
+ private func separation(_ P: [V3]) -> [V3] {
+ let n = Self.N, R = Self.R, excl = Int(ceil(4.5 * R / Self.seg))
+ var Q = P
+ for _ in 0..<3 {
+ var corr = [V3](repeating: .zero, count: n), cnt = [Double](repeating: 0, count: n)
+ var any = false
+ for i in 0..<n {
+ var j = i + excl
+ while j < n {
+ let d = Q[j] - Q[i], dist = simd_length(d), rr = 2 * R, lim = rr * 1.3
+ if dist < lim && dist > 1e-9 {
+ let x = clamp((lim - dist) / (lim - rr), 0, 1), pen = x * x * (3 - 2 * x) * (lim - dist)
+ let wi = 0.15 + 0.85 * Double(i) / Double(n - 1), wj = 0.15 + 0.85 * Double(j) / Double(n - 1)
+ let push: V3 = d / dist * pen
+ corr[i] -= push * (wi / (wi + wj)); corr[j] += push * (wj / (wi + wj))
+ cnt[i] += 1; cnt[j] += 1; any = true
+ }
+ j += 1
+ }
+ }
+ if !any { break }
+ for i in 0..<n where cnt[i] > 0 { corr[i] /= cnt[i] }
+ for _ in 0..<4 {
+ let c = corr
+ for i in 1..<(n - 1) { corr[i] = c[i - 1] * 0.25 + c[i] * 0.5 + c[i + 1] * 0.25 }
+ }
+ for i in 0..<n { Q[i] += corr[i] }
+ }
+ return (0..<n).map { Q[$0] - P[$0] }
+ }
+
+ // MARK: input
+
+ func motion(_ r: Rig, _ ax: Double, _ ay: Double, _ az: Double) {
+ let e = max(0, sqrt(ax * ax + ay * ay + az * az) - 0.9)
+ energy += e * e * 0.05
+ // while you shake it, it's flung about with the watch and waves run wild along it
+ let jerk = sqrt(ax * ax + ay * ay + az * az)
+ if jerk > 0.6 {
+ jig.v += P2(ax, ay) * (55 * min(1.5, jerk)); flow.kickWant = max(flow.kickWant, min(0.13, 0.03 + jerk * 0.04)); busyAt = t
+ }
+ // shaken hard: it bunches up, spinning, dizzy
+ if energy > 0.35 && shakeFor <= 0 {
+ shakeFor = 2.2; energy = 0; spinY.v += 3
+ wobble.vx += rnd(-1, 1) * 1.6; wobble.vz += rnd(-1, 1) * 1.6
+ if state != .dizzy && state != .sleep { r.setState(.dizzy) }
+ }
+ }
+ func crown(_ r: Rig, _ delta: Double) {
+ if at.axis == 2 { spinZ.v = clamp(spinZ.v + delta * 0.6, -8, 8) } else { spinY.v = clamp(spinY.v + delta * 0.6, -8, 8) }
+ crownRate += abs(delta) * 3; crownIdle = 0; busyAt = t
+ }
+ func touched(_ r: Rig, at pt: CGPoint) { finger = pt; busyAt = t }
+ func dragged(_ r: Rig, at pt: CGPoint) { finger = pt; busyAt = t }
+ func released(_ r: Rig) { finger = nil }
+ /// A tap: it hops, a wave runs up it and its eyes smile; four in a row and it's dizzy.
+ func poke(_ r: Rig) {
+ pokes = pokes.filter { t - $0 < 3 } + [t]; finger = nil; busyAt = t
+ if pokes.count >= 4 && state != .dizzy && state != .sleep { pokes = []; spinY.v += 3; r.setState(.dizzy); return }
+ hop.v = min(hop.v, -175); flow.kickWant = max(flow.kickWant, 0.1); happyFor = 0.9
+ jig.v += P2(rnd(-1, 1) * 30, 0)
+ }
+ /// Stroked along: its eyes smile and a slow wave runs up it.
+ func pet(_ r: Rig) { happyFor = max(happyFor, 0.6); flow.kickWant = max(flow.kickWant, 0.04); busyAt = t }
+ func deny(_ r: Rig) {}
+ func hit(_ pt: CGPoint) -> Bool {
+ let q = P2(pt.x, pt.y)
+ return world.contains { simd_length(project($0).p - q) < Self.R * 1.4 * shown.scale }
+ }
+
+ // MARK: drawing
+
+ /// A point as seen: straight on (every part the same size), shrunk and placed as shown.
+ @inline(__always) private func project(_ p: V3) -> (p: P2, s: Double) {
+ let s = shown.scale
+ return (P2(99 + p.x * s, shown.cy + p.y * s), s)
+ }
+
+ @inline(__always) static func shs(_ c: [Double], _ x: Double, _ y: Double, _ z: Double) -> Double {
+ let a = c[0] + c[1] * x + c[2] * y + c[3] * z, b = c[4] * (x * y) + c[5] * (x * z) + c[6] * (y * z)
+ return a + b + c[7] * (x * x - y * y) + c[8] * (3 * z * z - 1)
+ }
+ static let H = unit(V3(-0.45, -0.62, 0.65))
+ static let tint = P3(0.42, 0.22, 0.48) // shade goes toward a deep magenta-purple
+
+ /// Its colour at `u` along it where the surface faces N (seen: y down, z toward you): the reference's colours lit by
+ /// the light fitted to it, a highlight, and the head's own yellow-orange.
+ static func shade(_ u: Double, _ N: V3) -> P3 {
+ let A = NoodleRest.albedo, kn = A.count
+ func albedo(_ u: Double) -> P3 {
+ let ua = min(1, u * NoodleRest.length / 373), f = ua * Double(kn - 1)
+ let k0 = min(kn - 2, Int(f)), w = f - Double(k0)
+ return A[k0] * (1 - w) + A[k0 + 1] * w
+ }
+ // the tail: one blue, deepening to its tip (the reference has a purple patch on its curl that reads as a flicker)
+ let tail = 0.11
+ var alb: P3 = u < tail ? A[0] * (1 - ease(u / tail)) + albedo(tail) * ease(u / tail) : albedo(u)
+ let hk = ease((u - 0.86) / 0.14) * 0.85
+ alb = alb * (1 - hk) + P3(1.0, 0.70, 0.13) * hk
+ let lit = shs(NoodleRest.light, N.x, N.y, N.z), sheen = shs(NoodleRest.sheen, N.x, N.y, N.z)
+ let x = max(0, simd_dot(N, H)), x2 = x * x, x4 = x2 * x2, spec = 0.2 * x4 * x4 * x2
+ return alb * lit + P3(sheen, sheen, sheen) + P3(1, 0.97, 0.92) * spec
+ }
+ static func color(_ c: P3) -> Color { Color(red: clamp(c.x, 0, 1), green: clamp(c.y, 0, 1), blue: clamp(c.z, 0, 1)) }
+
+ static let M = 6
+
+ // MARK: measurements (Simulator only): NOODLE_DEBUG prints the draw cost, NOODLE_DUMP writes every frame's points
+ private static let timing = ProcessInfo.processInfo.environment["NOODLE_DEBUG"] != nil
+ private static let dump: FileHandle? = {
+ guard ProcessInfo.processInfo.environment["NOODLE_DUMP"] != nil else { return nil }
+ let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("coil-dump.bin")
+ FileManager.default.createFile(atPath: url.path, contents: nil)
+ return try? FileHandle(forWritingTo: url)
+ }()
+ private static let dumpStages: FileHandle? = {
+ guard ProcessInfo.processInfo.environment["NOODLE_DUMP"] != nil else { return nil }
+ let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("coil-stages.bin")
+ FileManager.default.createFile(atPath: url.path, contents: nil)
+ return try? FileHandle(forWritingTo: url)
+ }()
+ /// Simulator measurements: NOODLE_OFF=SEP,BEND,RIPPLE turns those parts off.
+ private static let offList = ProcessInfo.processInfo.environment["NOODLE_OFF"] ?? ""
+ private static func off(_ k: String) -> Bool { offList.contains(k) }
+ private var cost = (sum: 0.0, max: 0.0, n: 0)
+ private var split = [Double](repeating: 0, count: 4) // geometry, sampling, sort, painting
+ private var bendStat = 0.0
+ private static func now() -> Double { Double(DispatchTime.now().uptimeNanoseconds) / 1e6 }
+
+ func draw(_ r: Rig, _ ctx: GraphicsContext) {
+ let t0 = Self.timing ? DispatchTime.now().uptimeNanoseconds : 0
+ if let d = Self.dump {
+ var f = [Float](repeating: 0, count: 1 + Self.N * 3); f[0] = Float(t)
+ for i in 0..<Self.N { f[1 + 3 * i] = Float(world[i].x); f[2 + 3 * i] = Float(world[i].y); f[3 + 3 * i] = Float(world[i].z) }
+ d.write(f.withUnsafeBufferPointer { Data(buffer: $0) })
+ }
+ drawBody(r, ctx)
+ if Self.timing {
+ let ms = Double(DispatchTime.now().uptimeNanoseconds - t0) / 1e6
+ cost.sum += ms; cost.max = max(cost.max, ms); cost.n += 1
+ if cost.n >= 120 { print(String(format: "coil draw: avg %.2f ms max %.2f ms (curve+shade table %.2f depth %.2f colour %.2f image %.2f) tightest bend R·k %.2f", cost.sum / Double(cost.n), cost.max, split[0] / 120, split[1] / 120, split[2] / 120, split[3] / 120, bendStat)); cost = (0, 0, 0); split = [0, 0, 0, 0]; bendStat = 0 }
+ }
+ }
+
+ /// How it's drawn: flat, its colours along it with no light or shade (the default), or lit like the reference
+ /// ("lit", from the `noodleLook` default: a launch argument, -noodleLook lit).
+ static let look = UserDefaults.standard.string(forKey: "noodleLook") ?? "flat"
+ /// Pixels it draws per screen pixel, each way (-noodleRes 0.625 for fewer).
+ static let res = UserDefaults.standard.object(forKey: "noodleRes") as? Double ?? 0.625
+ /// Buffers for the tube's picture, kept between frames.
+ private var zbuf: [Float] = [], ibuf: [Int32] = [], cbuf: [Float] = [], rgba: [UInt8] = []
+ /// The picture at a point on screen (pt): its depth there and how far along the tube (0…1) that surface is, for
+ /// hiding the eyes behind another part of the tube in front of them.
+ private var depthAt: (P2) -> (z: Double, u: Double) = { _ in (-1e9, -1) }
+
+ /// The tube, shaded pixel by pixel: the union of spheres along its curve, each pixel taking the nearest surface
+ /// (a depth buffer), its normal the tube's (the sphere's, less the part along the tube; the ends keep their own),
+ /// lit by the model fitted to the reference, shaded where other parts of the tube are near it in 3D, a little
+ /// darker the further back it is, its edge antialiased; drawn as one image. Smooth everywhere, however it turns.
+ private func drawBody(_ r: Rig, _ ctx: GraphicsContext) {
+ let g = r.ao ? ctx.faded(0.5) : ctx
+ let n = Self.N, R = Self.R, sc = shown.scale, m = 8
+ let tm0 = Self.timing ? Self.now() : 0
+ // the points smoothed along the tube first: changes of shape and the pushes that keep it apart leave small
+ // wiggles from point to point, which would show as rings and dents in a tube this smooth
+ var sm = world
+ for _ in 0..<2 {
+ let src = sm
+ func at(_ i: Int) -> V3 { i < 0 ? src[0] * 2 - src[-i] : i >= n ? src[n - 1] * 2 - src[2 * (n - 1) - i] : src[i] }
+ for i in 1..<(n - 1) {
+ let a: V3 = at(i - 2) + at(i + 2), b: V3 = (at(i - 1) + at(i + 1)) * 4
+ sm[i] = (a + b + src[i] * 6) / 16
+ }
+ }
+ // the curve: a smooth spline through the points, five samples a link
+ let sub = 5, cnt = (n - 1) * sub + 1
+ var q = [V3](repeating: .zero, count: cnt)
+ for i in 0..<cnt {
+ let f = Double(i) / Double(sub), j = min(n - 2, Int(f)), w = f - Double(j)
+ let p0 = sm[max(0, j - 1)], p1 = sm[j], p2 = sm[j + 1], p3 = sm[min(n - 1, j + 2)]
+ let w2 = w * w, w3 = w2 * w
+ let a: V3 = p1 * 2, b: V3 = (p2 - p0) * w
+ let c1: V3 = p0 * 2 - p1 * 5, c: V3 = (c1 + p2 * 4 - p3) * w2
+ let d1: V3 = p1 * 3 - p0, d: V3 = (d1 - p2 * 3 + p3) * w3
+ q[i] = (a + b + c + d) * 0.5
+ }
+ let tang: [V3] = (0..<cnt).map { Self.unit(q[min(cnt - 1, $0 + 4)] - q[max(0, $0 - 4)]) }
+ // shade where another part of the tube is near, in 3D: at each point, for directions across it (8, from the
+ // side in the picture's plane through facing you to the other side)
+ var ao = [Float](repeating: 0, count: n * m), nrmN = [V3](repeating: .zero, count: n), bnN = nrmN
+ let farNodes = Int(ceil(3.5 * R / Self.seg))
+ for i in 0..<n where Self.look == "lit" { // (flat has no shade)
+ let tg = Self.unit(world[min(n - 1, i + 1)] - world[max(0, i - 1)])
+ let lin = sqrt(tg.x * tg.x + tg.y * tg.y)
+ let nrm = lin < 0.05 ? V3(0, -1, 0) : V3(tg.y / lin, -tg.x / lin, 0)
+ var bn = Self.unit(simd_cross(nrm, tg)); if bn.z < 0 { bn = -bn }
+ nrmN[i] = nrm; bnN[i] = bn
+ var near: [Int] = []
+ for j in 0..<n where abs(i - j) > farNodes && simd_length(world[j] - world[i]) < 4.2 * R { near.append(j) }
+ if near.isEmpty { continue }
+ for k in 0..<m {
+ let s = 1 - 2 * Double(k) / Double(m - 1)
+ let N: V3 = nrm * s + bn * sqrt(max(0, 1 - s * s)), surf: V3 = world[i] + N * R
+ var keep = 1.0
+ for j in near {
+ let D = world[j] - surf, dd = simd_length(D)
+ if dd > 2.8 * R { continue }
+ let nd = simd_dot(D, N) / max(dd, 1e-6)
+ if nd <= 0 { continue }
+ let f = clamp(1 - (dd - R) / (1.8 * R), 0, 1)
+ keep *= 1 - nd * f * f
+ }
+ ao[i * m + k] = Float(min(0.85, 1 - keep))
+ }
+ }
+ let tm1 = Self.timing ? Self.now() : 0
+ // the picture: the tube's bounds on screen, at the screen's own pixels (more when rendering larger)
+ let rs = clamp(r.pixelScale * Self.res, 1, 6) // 1.25 pixels a point on the watch (its 2): the tube is smooth, and
+ // it's 40% of the pixels; the iPhone draws it bigger, so more
+ var lo = P2(1e9, 1e9), hi = P2(-1e9, -1e9)
+ for i in 0..<cnt { let p = project(q[i]).p; lo = simd_min(lo, p); hi = simd_max(hi, p) }
+ let pad = R * sc + 1
+ let x0 = floor(lo.x - pad), y0 = floor(lo.y - pad)
+ let W = max(1, Int(ceil((hi.x + pad - x0) * rs))), H = max(1, Int(ceil((hi.y + pad - y0) * rs)))
+ let size = W * H
+ if zbuf.count < size { zbuf = [Float](repeating: 0, count: size); ibuf = [Int32](repeating: 0, count: size); cbuf = zbuf; rgba = [UInt8](repeating: 0, count: size * 4) }
+ let rp = Float(R * sc * rs), rp2 = rp * rp, re = rp + 0.5, k2w = Float(1 / (sc * rs))
+ // how far a sphere's surface stands out toward you, by the squared distance from its centre (a table, not a root
+ // per pixel); inside `core` a pixel is fully covered, so only the rim needs its distance
+ let zt: [Float] = (0...(Int(rp2) + 1)).map { (max(0, rp2 - Float($0))).squareRoot() * k2w }
+ let core = max(0, rp - 0.5), core2 = core * core
+ zbuf.withUnsafeMutableBufferPointer { zb in
+ ibuf.withUnsafeMutableBufferPointer { ib in
+ cbuf.withUnsafeMutableBufferPointer { cb in
+ for i in 0..<size { zb[i] = -1e9; ib[i] = -1; cb[i] = 0 }
+ // the spheres, every third sample (they overlap so much the surface between them dips < 0.2 pt; the colour
+ // and light come from the true place along the tube, so nothing steps)
+ var j = 0
+ while j < cnt {
+ let pj = project(q[j]).p
+ let cx = Float((pj.x - x0) * rs), cy = Float((pj.y - y0) * rs), cz = Float(q[j].z), jj = Int32(j)
+ let ya = max(0, Int(cy - re)), yb = min(H - 1, Int(cy + re))
+ if ya <= yb {
+ for y in ya...yb {
+ let dy = Float(y) + 0.5 - cy, dy2 = dy * dy
+ if dy2 > re * re { continue }
+ let hw = (re * re - dy2).squareRoot()
+ let xa = max(0, Int(cx - hw)), xb = min(W - 1, Int(cx + hw))
+ if xa > xb { continue }
+ let row = y * W
+ zt.withUnsafeBufferPointer { zt in
+ for x in xa...xb {
+ let dx = Float(x) + 0.5 - cx, d2 = dx * dx + dy2, idx = row + x
+ let z: Float
+ if d2 < core2 { cb[idx] = 1; z = cz + zt[Int(d2)] } else {
+ let cov = min(1, max(0, rp - d2.squareRoot() + 0.5))
+ if cov > cb[idx] { cb[idx] = cov }
+ z = d2 < rp2 ? cz + zt[Int(d2)] : cz
+ }
+ if z > zb[idx] { zb[idx] = z; ib[idx] = jj }
+ }
+ }
+ }
+ }
+ j = j == cnt - 1 ? cnt : min(cnt - 1, j + 3)
+ }
+ }}}
+ let tm2 = Self.timing ? Self.now() : 0
+ // the colours: each pixel's surface, lit and shaded
+ let one = P3(1, 1, 1), dark: P3 = one - Self.tint
+ let invRs = 1 / rs
+ let flat = Self.look != "lit"
+ let flatCols: [P3] = flat ? (0...64).map { Self.shade(Double($0) / 64, V3(0, 0, 1)) } : []
+ var segLen = 0.0
+ for i in 1..<cnt { segLen += simd_length(q[i] - q[i - 1]) }
+ segLen /= Double(cnt - 1)
+ rgba.withUnsafeMutableBufferPointer { px in
+ zbuf.withUnsafeBufferPointer { zb in
+ ibuf.withUnsafeBufferPointer { ib in
+ cbuf.withUnsafeBufferPointer { cb in
+ for y in 0..<H {
+ for x in 0..<W {
+ let idx = y * W + x, cov = cb[idx], o = idx * 4
+ if cov <= 0 || ib[idx] < 0 { px[o] = 0; px[o + 1] = 0; px[o + 2] = 0; px[o + 3] = 0; continue }
+ let j = Int(ib[idx]), c = q[j]
+ // the point on the surface, in the tube's own units
+ let sxp = (Double(x) + 0.5) * invRs + x0, syp = (Double(y) + 0.5) * invRs + y0
+ let wx = (sxp - 99) / sc, wy = (syp - shown.cy) / sc
+ let off = V3(wx - c.x, wy - c.y, Double(zb[idx]) - c.z)
+ // where along the tube this surface really is (between the samples, so colour and light don't step)
+ let alongW = simd_dot(off, tang[j]), fj = clamp(Double(j) + alongW / segLen, 0, Double(cnt - 1))
+ if flat {
+ // flat: the colour along it as it looks facing you, nothing else
+ let fu = fj / Double(cnt - 1) * Double(flatCols.count - 1), f0 = min(flatCols.count - 2, Int(fu)), fw = fu - Double(f0)
+ let c: P3 = flatCols[f0] * (1 - fw) + flatCols[f0 + 1] * fw
+ let a = Double(cov) * 255
+ px[o] = UInt8(clamp(c.x, 0, 1) * a + 0.5)
+ px[o + 1] = UInt8(clamp(c.y, 0, 1) * a + 0.5)
+ px[o + 2] = UInt8(clamp(c.z, 0, 1) * a + 0.5)
+ px[o + 3] = UInt8(a + 0.5)
+ continue
+ }
+ let ja = min(cnt - 2, Int(fj)), wj = fj - Double(ja)
+ let cc: V3 = q[ja] * (1 - wj) + q[ja + 1] * wj, t3 = Self.unit(tang[ja] * (1 - wj) + tang[ja + 1] * wj)
+ var N = (V3(wx, wy, Double(zb[idx])) - cc) / R
+ let along = simd_dot(N, t3)
+ let cap = (j == cnt - 1 && alongW > 0) || (j == 0 && alongW < 0)
+ N = cap ? off / R : N - t3 * along
+ N = Self.unit(N)
+ let u = fj / Double(cnt - 1)
+ var col = Self.shade(u, N)
+ // shade from the parts near it (the table at the points either side, across by where it faces)
+ let fi = u * Double(n - 1), i0 = min(n - 2, Int(fi)), wi = fi - Double(i0)
+ func aoAt(_ i: Int) -> Double {
+ let s = clamp(simd_dot(N, nrmN[i]), -1, 1), fk = (1 - s) * 0.5 * Double(m - 1)
+ let k0 = min(m - 2, Int(fk)), wk = fk - Double(k0)
+ return Double(ao[i * m + k0]) * (1 - wk) + Double(ao[i * m + k0 + 1]) * wk
+ }
+ let sh = aoAt(i0) * (1 - wi) + aoAt(i0 + 1) * wi
+ let zc = clamp(Double(zb[idx]) / 60, -1, 1), cue = 1 - 0.25 * (0.5 - 0.5 * zc)
+ col = col * (one - dark * sh) * cue
+ let a = Double(cov)
+ px[o] = UInt8(clamp(col.x, 0, 1) * a * 255 + 0.5)
+ px[o + 1] = UInt8(clamp(col.y, 0, 1) * a * 255 + 0.5)
+ px[o + 2] = UInt8(clamp(col.z, 0, 1) * a * 255 + 0.5)
+ px[o + 3] = UInt8(a * 255 + 0.5)
+ }
+ }
+ }}}}
+ let tm3 = Self.timing ? Self.now() : 0
+ // hand the depth to the eyes, then draw: the small coils behind, the tube, the eyes, the extras
+ let zcopy = zbuf, icopy = ibuf, wW = W, hH = H, last = Double(cnt - 1)
+ depthAt = { p in
+ let x = Int((p.x - x0) * rs), y = Int((p.y - y0) * rs)
+ guard x >= 0 && y >= 0 && x < wW && y < hH, icopy[y * wW + x] >= 0 else { return (-1e9, -1) }
+ return (Double(zcopy[y * wW + x]), Double(icopy[y * wW + x]) / last)
+ }
+ drawMinis(g)
+ let image: CGImage? = rgba.withUnsafeMutableBytes { raw in
+ guard let cs = CGColorSpace(name: CGColorSpace.sRGB),
+ let cg = CGContext(data: raw.baseAddress, width: W, height: H, bitsPerComponent: 8, bytesPerRow: W * 4, space: cs,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
+ return cg.makeImage()
+ }
+ if let image {
+ g.draw(g.resolve(Image(decorative: image, scale: rs)), in: CGRect(x: x0, y: y0, width: Double(W) / rs, height: Double(H) / rs))
+ }
+ drawEyes(g, r: r, q: q, tang: tang)
+ drawExtras(g, r: r, head: project(q[cnt - 1]).p)
+ depthAt = { _ in (-1e9, -1) }
+ if Self.timing { let tm4 = Self.now(); split[0] += tm1 - tm0; split[1] += tm2 - tm1; split[2] += tm3 - tm2; split[3] += tm4 - tm3 }
+ }
+
+ func front(_ r: Rig, _ ctx: GraphicsContext) {}
+
+ /// The eyes: near the head's end, on the side facing you, foreshortened as it turns away, hidden on its back.
+ private func drawEyes(_ g: GraphicsContext, r: Rig, q: [V3], tang: [V3]) {
+ let E = q[q.count - 1], tE = tang[tang.count - 1], R = Self.R
+ let fd = Self.unit(V3(0, 0, 1) + tE * 0.12 + V3(0, -0.4, 0))
+ let right = Self.unit(simd_cross(V3(0, -1, 0), fd)), up = Self.unit(simd_cross(fd, right))
+ let p = r.pose(raw: true)
+ var gaze = P2(p.eye.gx, p.eye.gy)
+ if let f = finger {
+ let d = P2(f.x, f.y) - project(E).p, l = max(1, simd_length(d)); gaze = d / l
+ }
+ let line = StrokeStyle(lineWidth: 1.6, lineCap: .round)
+ for side in [-1.0, 1.0] {
+ let dir = Self.unit(fd + right * (side * 0.42) + up * 0.1)
+ if dir.z < 0.12 { continue }
+ let at: V3 = E - tE * (0.55 * R) + dir * R
+ let pp = project(at), s = pp.s
+ let seen = depthAt(pp.p) // another part of the tube in front of it
+ if seen.u >= 0 && seen.u < 0.9 && seen.z > at.z + 0.3 * R { continue }
+ let e: P2 = pp.p + gaze * (1.4 * s)
+ let fz = 0.6 + 0.4 * min(1, dir.z)
+ let rx = 3.7 * s * fz, ry = 5.0 * s
+ if happyFor > 0 && state != .sleep && state != .dizzy { // smiling: ∩
+ var l = Path(); l.move(to: CGPoint(x: e.x - 3.6 * s, y: e.y + 1.4 * s)); l.addQuadCurve(to: CGPoint(x: e.x + 3.6 * s, y: e.y + 1.4 * s), control: CGPoint(x: e.x, y: e.y - 4.2 * s))
+ g.stroke(l, with: .color(Self.cream), style: StrokeStyle(lineWidth: 1.9, lineCap: .round)); continue
+ }
+ switch state {
+ case .done:
+ var st = Path()
+ for j in 0..<10 {
+ let a = -Double.pi / 2 + Double(j) * Double.pi / 5, rr = (j % 2 == 0 ? 5.2 : 2.2) * s
+ let c = CGPoint(x: e.x + cos(a) * rr, y: e.y + sin(a) * rr)
+ if j == 0 { st.move(to: c) } else { st.addLine(to: c) }
+ }
+ st.closeSubpath(); g.fill(st, with: .color(Self.cream))
+ case .sleep:
+ var l = Path(); l.move(to: CGPoint(x: e.x - 3.4 * s, y: e.y)); l.addQuadCurve(to: CGPoint(x: e.x + 3.4 * s, y: e.y), control: CGPoint(x: e.x, y: e.y + 2.8 * s))
+ g.stroke(l, with: .color(Self.cream), style: line)
+ case .dizzy:
+ var sp = Path()
+ for j in 0...30 {
+ let u = Double(j) / 30, a = u * 2 * TAU + t * 6 * side, rr = (0.5 + u * 3.8) * s
+ let c = CGPoint(x: e.x + cos(a) * rr, y: e.y + sin(a) * rr)
+ if j == 0 { sp.move(to: c) } else { sp.addLine(to: c) }
+ }
+ g.stroke(sp, with: .color(Self.cream), style: StrokeStyle(lineWidth: 1.4, lineCap: .round))
+ default:
+ let open = clamp(p.eye.open, 0, 1)
+ if open < 0.3 {
+ var l = Path(); l.move(to: CGPoint(x: e.x - rx * 0.8, y: e.y)); l.addLine(to: CGPoint(x: e.x + rx * 0.8, y: e.y))
+ g.stroke(l, with: .color(Self.cream), style: line)
+ } else {
+ let big = state == .listening || state == .needs ? 1.12 : 1
+ let hh = ry * big * (state == .working ? 0.65 : 1) * open, w = rx * big
+ g.fill(Path(ellipseIn: CGRect(x: e.x - w - 0.6, y: e.y - hh - 0.6, width: 2 * w + 1.2, height: 2 * hh + 1.2)), with: .color(Self.cream.opacity(0.3)))
+ g.fill(Path(ellipseIn: CGRect(x: e.x - w, y: e.y - hh, width: 2 * w, height: 2 * hh)), with: .color(Self.cream))
+ }
+ }
+ }
+ }
+
+ /// The little strokes by its head (done, needs you).
+ private func drawExtras(_ g: GraphicsContext, r: Rig, head c: P2) {
+ if (state == .done && r.stateT < 1.4) || (state == .needs && knock < 0.6) {
+ let k = state == .done ? r.stateT / 1.4 : knock / 0.6
+ let base: P2 = c + P2(26, -26) * shown.scale
+ let tint = Color(red: 0.62, green: 0.66, blue: 0.78)
+ for j in 0..<3 {
+ let a = -Double.pi / 2 + Double(j) * 0.62 - 0.2, r0 = 4 + 5 * k
+ var l = Path()
+ l.move(to: CGPoint(x: base.x + cos(a) * r0, y: base.y + sin(a) * r0))
+ l.addLine(to: CGPoint(x: base.x + cos(a) * (r0 + 8), y: base.y + sin(a) * (r0 + 8)))
+ g.faded(1 - k * 0.8).stroke(l, with: .color(tint), style: StrokeStyle(lineWidth: 2.6, lineCap: .round))
+ }
+ }
+ }
+
+ /// Small coils going round behind it (subagents).
+ private func drawMinis(_ g: GraphicsContext) {
+ guard minis > 0.02 else { return }
+ let cols = [Self.color(P3(0.25, 0.5, 1)), Self.color(P3(0.6, 0.3, 0.95)), Self.color(P3(0.98, 0.3, 0.55)), Self.color(P3(1, 0.7, 0.15))]
+ for m in 0..<3 {
+ let a = t * 0.7 + Double(m) * TAU / 3
+ let ctr: P2 = P2(99, 140) + P2(cos(a) * 82, sin(a) * 58) * minis
+ let k = 0.2 * minis
+ let zig: [P2] = [P2(18, 70), P2(-30, 40), P2(30, 0), P2(-25, -35), P2(5, -55)].map { ctr + $0 * k }
+ g.stroke(Strokes.smoothOpen(zig), with: .linearGradient(Gradient(colors: cols), startPoint: CGPoint(x: zig[0].x, y: zig[0].y), endPoint: CGPoint(x: zig[4].x, y: zig[4].y)),
+ style: StrokeStyle(lineWidth: 26 * k, lineCap: .round, lineJoin: .round))
+ }
+ }
+}
diff --git a/app/ChumsWatch/Rig/PeepsStage.swift b/app/ChumsWatch/Rig/PeepsStage.swift
new file mode 100644
index 0000000..5c5cdcb
--- /dev/null
+++ b/app/ChumsWatch/Rig/PeepsStage.swift
@@ -0,0 +1,529 @@
+import SwiftUI
+
+/// Peeps: eyes, on their own, on black. Everything is in how they move.
+/// always: they move as a pair, the head following the gaze a little behind; a quick look stretches them along it; the
+/// eye on the side they look to is a little bigger; a blink squashes them; they breathe
+/// touch: they look at your finger and follow it while it's down · tap: one ripple of the glass runs out and bends
+/// them as it passes; they startle · tap an eye: it winces shut, the other widens; poke them too often and they move
+/// away, annoyed
+/// crown up: bubbles of liquid glass rise from the bottom edge, flow round them and magnify them as they pass; they watch
+/// them; tap one and it pops · crown down: a wind from the top pushes them down; they squint and flutter against it,
+/// and spring back when it drops
+/// shake: they slosh and squeeze; hard, dizzy: spiral eyes circling each other, swaying, under a ring of little glass
+/// beads; then woozy, each eye on its own; then they shake it off
+/// the screen's edges: pushed hard, they squash against them; left alone a while, they slip out past one and peek back
+/// thinking: up and aside, mulling · working: reading, line by line, a blink at each tool call · subagents: three
+/// little pairs of eyes circling them · done: a crouch, a hop, a landing · needs you: up close, knocking on the glass ·
+/// blocked: they sag · sleep: shut, sinking a little, breathing slowly
+/// Character rules: solid eyes, no pupils or shine, lids make every expression.
+/// Battery: 60 frames a second only while something moves fast (`calm`), else 30; it draws the two eyes and their glow.
+final class PeepsStage: Staged {
+ static let shared = PeepsStage()
+
+ let ownsApproval = false
+ let holds: [ChumsState: Double] = [.done: 2.2, .dizzy: 4.2]
+ func captionTop(_ r: Rig) -> Bool { false }
+ func ownsCaption(_ r: Rig) -> Bool { false }
+ /// Nothing moving fast for a second: 30 frames a second is enough.
+ var calm: Bool { t - busyAt > 1.2 }
+
+ private var off = (x: 0.0, y: 0.0, vx: 0.0, vy: 0.0) // pushed off their place: taps, shakes, a peek, moods
+ private var head = (x: 0.0, y: 0.0, vx: 0.0, vy: 0.0) // following their gaze, a little behind
+ private var gazeV = (x: 0.0, y: 0.0), lastGaze = (x: 0.0, y: 0.0) // how fast the gaze moves
+ private var squash = 0.0, squashAxisX = true // against an edge
+ private var wob = [0.0, 0.0], wobV = [0.0, 0.0] // each eye's give when something hits it
+ private var flinch = [0.0, 0.0]
+ private var finger: CGPoint?
+ private var look: CGPoint?, lookFor = 0.0 // something they watch: your finger, a tap
+ private var crownFor = 0.0, bubbleAcc = 0.0 // the crown: how lately it turned; turns toward the next bubble
+ private var wind = 0.0, windTo = 0.0, windPeak = 0.0 // the wind from the top, 0…1
+ private var lid = (s: 0.0, w: 0.0, i: 0.0), lidT = 0.0 // the lids as shown: sleepy, worried, intent
+ private struct Bubble { var x, y, r, vx, vy, phase: Double; var pop: Double? = nil }
+ private var bubbles: [Bubble] = []
+ private struct Drop { var x, y, vx, vy, t: Double }
+ private var drops: [Drop] = []
+ private var startle = 0.0, press = 0.0, pressBase = 0.0, knock = 0.0
+ private var orbit = 0.0, orbitA = 0.0, halo = 0.0, shakeOff = 0.0
+ private var pokes: [Double] = [], annoyed = 0.0, annoyedSide = 1.0, lastTouch = CGPoint(x: 99, y: 112)
+ private var peek: (side: Double, t: Double)?, idleFor = 0.0
+ private var doneT: Double?, dizzyT: Double?
+ private var nextTool = 0.6, readT = 0.0
+ private var minis = 0.0, minisA = 0.0
+ private struct Ring { var x, y, t: Double; var amp = 1.0; var passed = [false, false] }
+ private var rings: [Ring] = []
+ private var eyes = (l: CGPoint(x: 55, y: 112), r: CGPoint(x: 143, y: 112), w: 36.0, h: 54.0)
+ private var push = (x: 0.0, y: 0.0, z: 0.0), trauma = 0.0
+ private var t = 0.0, busyAt = 0.0
+ private var state: ChumsState = .idle
+
+ // MARK: Staged
+
+ func onState(_ r: Rig, _ s: ChumsState, prev: ChumsState?, variant: Bool) {
+ state = s; idleFor = 0; peek = nil
+ doneT = s == .done ? 0 : nil
+ dizzyT = s == .dizzy ? 0 : nil
+ if s == .dizzy { orbit = 1; halo = 1 } else { halo = 0 }
+ if s == .needs { knock = 0 }
+ readT = 0
+ }
+
+ func step(_ r: Rig, _ dt0: Double) {
+ let dt = min(dt0, 0.05)
+ t += dt
+ guard !r.ao else { return }
+ stepPair(r, dt)
+ stepActing(r, dt)
+ stepRings(dt)
+ stepBubbles(r, dt)
+ let busy = finger != nil || crownFor > 0 || trauma > 0.02 || !rings.isEmpty || dizzyT != nil || (doneT ?? 9) < 1.2
+ || abs(off.vx) + abs(off.vy) > 30 || peek != nil || minis > 0.02 || !bubbles.isEmpty || !drops.isEmpty || wind > 0.01
+ || state == .listening || state == .speaking
+ if busy { busyAt = t }
+ }
+
+ private func band(_ v: Double) -> Double { abs(v) < 0.12 ? 0 : v - (v > 0 ? 0.12 : -0.12) }
+ private func cross(_ now: Double, _ dt: Double, _ at: Double) -> Bool { now - dt < at && now >= at }
+
+ private func stepPair(_ r: Rig, _ dt: Double) {
+ // the crown's wind builds while it turns and dies down after; when a strong one drops, they blink it off
+ crownFor = max(0, crownFor - dt)
+ windTo *= exp(-dt * 1.3)
+ wind += (windTo - wind) * min(1, dt * 6)
+ windPeak = max(windPeak, wind)
+ if windPeak > 0.45 && wind < 0.12 { windPeak = 0; r.startBlink(true) }
+ if wind < 0.01 { windPeak = min(windPeak, wind) }
+ // the head follows the gaze, a little behind
+ let gx = r.gaze.x, gy = r.gaze.y, hw = TAU * 2.2
+ let ivx = (gx - lastGaze.x) / max(dt, 0.001), ivy = (gy - lastGaze.y) / max(dt, 0.001)
+ gazeV = (lerp(gazeV.x, ivx, min(1, dt * 30)), lerp(gazeV.y, ivy, min(1, dt * 30)))
+ lastGaze = (gx, gy)
+ head.vx += (-hw * hw * (head.x - gx * 7) - 2 * 0.55 * hw * head.vx) * dt
+ head.vy += (-hw * hw * (head.y - gy * 5) - 2 * 0.55 * hw * head.vy) * dt
+ head.x += head.vx * dt; head.y += head.vy * dt
+
+ startle = max(0, startle - dt * 2.5)
+ trauma = max(0, trauma - dt * 0.75)
+ press = max(0, press - dt * 2.2)
+ pressBase += ((state == .needs ? 0.4 : 0) - pressBase) * min(1, dt * 3)
+ annoyed = max(0, annoyed - dt)
+ lookFor = max(0, lookFor - dt)
+ shakeOff = max(0, shakeOff - dt * 2.2)
+ orbit = max(0, orbit - dt * 0.42)
+ orbitA += dt * TAU * 1.4 * orbit
+ for i in 0..<2 {
+ flinch[i] = max(0, flinch[i] - dt * 2.2)
+ let w = TAU * 4.2
+ wobV[i] += (-w * w * wob[i] - 2 * 0.22 * w * wobV[i]) * dt
+ wob[i] = clamp(wob[i] + wobV[i] * dt, -0.2, 0.2)
+ }
+
+ // where they want to be: their place, or past an edge, or away from your finger, a mood's place, a little downhill
+ var rx = clamp(r.W.padX, -1, 1) * 8, ry = 0.0
+ let span = Double(eyes.r.x - eyes.l.x) / 2 + eyes.w / 2
+ if let p = peek {
+ if p.t < 1.6 { rx = p.side * (99 + span + 10) } // out
+ else if p.t < 4.6 { rx = p.side * (99 + span - eyes.w * 0.95) } // one eye back in
+ }
+ switch state {
+ case .thinking: rx += sin(t * 0.7) * 4; ry = -4 + cos(t * 0.5) * 2 // mulling, drifting
+ case .blocked: ry = 7 // sagging
+ case .sleep: ry = 12 + sin(t * TAU / 5) * 1.5
+ default: break
+ }
+ if annoyed > 0 { rx = annoyedSide * 34; ry = 8 }
+ ry += wind * 26 // the wind pushes them down
+ if let d = dizzyT, orbit > 0 { rx += sin(d * 3.1) * 9 * orbit; ry += sin(d * 6.2) * 4 * orbit } // swaying, a figure of eight
+ let w = TAU * (peek == nil ? 1.4 : 1.1), z = 0.45
+ off.vx += (-w * w * (off.x - rx) - 2 * z * w * off.vx - band(push.x) * 1500) * dt
+ off.vy += (-w * w * (off.y - ry) - 2 * z * w * off.vy - band(push.y) * 1500) * dt
+ off.x += off.vx * dt; off.y += off.vy * dt
+ // the screen's edges: they squash against them and come back (not while peeking past one)
+ let maxX = 99 - span - 2, maxY = 112 - eyes.h * 0.62 - 30
+ if peek == nil {
+ if abs(off.x) > maxX { let v = abs(off.vx); off.x = off.x > 0 ? maxX : -maxX; off.vx = -off.vx * 0.3; if v > 140 { hitEdge(r, v, x: true) } }
+ if abs(off.y) > maxY { let v = abs(off.vy); off.y = off.y > 0 ? maxY : -maxY; off.vy = -off.vy * 0.3; if v > 140 { hitEdge(r, v, x: false) } }
+ }
+ squash = max(0, squash - dt * 2.6)
+ }
+
+ private func hitEdge(_ r: Rig, _ v: Double, x: Bool) {
+ squash = min(0.24, v / 1000); squashAxisX = x
+ if trauma < 0.15 { r.onHaptic?(v > 500 ? .strong : .click) }
+ }
+
+ /// What each state does beyond the rig's lids and gaze.
+ private func stepActing(_ r: Rig, _ dt: Double) {
+ if let d = doneT { doneT = d + dt }
+ if let d = dizzyT {
+ dizzyT = d + dt
+ if cross(d + dt, dt, 2.1) { halo = 0; r.startBlink() } // the spirals stop: woozy
+ if cross(d + dt, dt, 3.5) { shakeOff = 1; r.startBlink(true) } // and they shake it off
+ }
+ // needs you: up close against the glass, knocking every few seconds, with a tap on the wrist
+ if state == .needs {
+ let was = knock; knock += dt
+ if knock >= 3.2 { knock = 0 }
+ if was < 0.2 && knock >= 0.2 {
+ press = 1; off.vy -= 60
+ rings.append(Ring(x: Double(eyes.l.x + eyes.r.x) / 2, y: Double(eyes.l.y), t: 0, amp: 0.8)); r.onHaptic?(.strong)
+ }
+ } else { knock = 0 }
+ // working: reading, a line at a time; each tool call, a blink and a small nod
+ readT = state == .working ? readT + dt : 0
+ nextTool -= dt
+ if nextTool <= 0 && (!r.worlds.queue.isEmpty || state == .working), let call = r.worlds.nextEvent(r) {
+ nextTool = r.worlds.queue.isEmpty ? rnd(1.6, 2.6) : 0.6
+ if call.kind != .stop { r.startBlink(); off.vy += 70 }
+ }
+ // subagents: little eyes circling them
+ minis += ((state == .subagents ? 1 : 0) - minis) * min(1, dt * 2.5)
+ minisA += dt * 0.9
+ // left alone a while: out past an edge, then one eye peeks back in, looks around, and they come back
+ idleFor = state == .idle && finger == nil && crownFor <= 0 ? idleFor + dt : 0
+ if peek == nil && idleFor > 24 && Double.random(in: 0..<1) < dt * 0.2 { peek = (Bool.random() ? -1 : 1, 0); idleFor = 0 }
+ if var p = peek {
+ p.t += dt; peek = p.t > 6.4 ? nil : p
+ if cross(p.t, dt, 2.3) { r.saccade(-p.side * 0.9, 0.05); r.gaze.fixLeft = 1.3 }
+ if cross(p.t, dt, 3.5) { r.startBlink(true) }
+ if cross(p.t, dt, 4.1) { r.saccade(-p.side * 0.4, 0.3); r.gaze.fixLeft = 1 }
+ }
+ }
+
+ private func stepRings(_ dt: Double) {
+ for j in rings.indices {
+ rings[j].t += dt
+ let R = ringRadius(rings[j]), a = 1 - min(1, rings[j].t / 0.9)
+ for (i, c) in [eyes.l, eyes.r].enumerated() where rings[j].t > 0 && !rings[j].passed[i] && hypot(Double(c.x) - rings[j].x, Double(c.y) - rings[j].y) < R {
+ rings[j].passed[i] = true; wobV[i] += 1.6 * a * rings[j].amp
+ }
+ }
+ rings.removeAll { $0.t >= 0.9 }
+ }
+ private func ringRadius(_ g: Ring) -> Double { 6 + 140 * outC(clamp(g.t / 0.9, 0, 1)) }
+
+ // MARK: input
+
+ func motion(_ r: Rig, _ ax: Double, _ ay: Double, _ az: Double) {
+ push = (ax, ay, az)
+ let e = max(0, sqrt(ax * ax + ay * ay + az * az) - 0.9)
+ trauma = min(1, trauma + e * e * 0.03)
+ }
+
+ /// The crown: turned up, bubbles; turned down, wind.
+ func crown(_ r: Rig, _ delta: Double) {
+ crownFor = 1.2; idleFor = 0; peek = nil; busyAt = t
+ if delta > 0 {
+ bubbleAcc += delta
+ while bubbleAcc >= 2.2 { bubbleAcc -= 2.2; spawnBubble() }
+ } else {
+ bubbleAcc = 0
+ windTo = min(1, windTo - delta * 0.12)
+ }
+ }
+
+ // MARK: bubbles
+
+ /// A bubble comes up from below the bottom edge: a few, and big.
+ private func spawnBubble() {
+ guard bubbles.filter({ $0.pop == nil }).count < 5 else { return }
+ let u = Double.random(in: 0..<1), r = 15 + 11 * u * u
+ bubbles.append(Bubble(x: rnd(22, 176), y: 242 + r + rnd(0, 8), r: r, vx: 0, vy: -rise(r), phase: rnd(0, TAU)))
+ }
+ /// How fast a bubble of radius `r` rises: big ones faster.
+ private func rise(_ r: Double) -> Double { 26 + r * 2.2 }
+
+ private func stepBubbles(_ r: Rig, _ dt: Double) {
+ for i in bubbles.indices where bubbles[i].pop != nil { bubbles[i].pop! += dt }
+ bubbles.removeAll { ($0.pop ?? 0) > 0.18 }
+ for i in drops.indices { drops[i].t += dt; drops[i].x += drops[i].vx * dt; drops[i].y += drops[i].vy * dt; drops[i].vy += 240 * dt }
+ drops.removeAll { $0.t > 0.4 }
+ guard !bubbles.isEmpty else { return }
+ for i in bubbles.indices where bubbles[i].pop == nil {
+ var b = bubbles[i]
+ // rising with a sway, the wind holding them back or blowing them down
+ b.vx += (sin(t * 1.7 + b.phase) * 14 - b.vx) * min(1, dt * 2)
+ b.vy += (-rise(b.r) + wind * (rise(b.r) + 90) - b.vy) * min(1, dt * 2.5)
+ b.x += b.vx * dt; b.y += b.vy * dt
+ b.x = clamp(b.x, b.r * 0.6, 198 - b.r * 0.6)
+ bubbles[i] = b
+ }
+ // bubbles don't overlap: each pair pushed apart
+ for i in bubbles.indices where bubbles[i].pop == nil {
+ for j in (i + 1)..<bubbles.count where bubbles[j].pop == nil {
+ let dx = bubbles[j].x - bubbles[i].x, dy = bubbles[j].y - bubbles[i].y, d = hypot(dx, dy), m = bubbles[i].r + bubbles[j].r + 1
+ guard d < m, d > 0.0001 else { continue }
+ let k = (m - d) / d * 0.5
+ bubbles[i].x -= dx * k; bubbles[i].y -= dy * k; bubbles[j].x += dx * k; bubbles[j].y += dy * k
+ }
+ }
+ bubbles.removeAll { $0.y < -$0.r - 6 || $0.y > 262 + $0.r }
+ // they watch the biggest one near them
+ let c = CGPoint(x: Double(eyes.l.x + eyes.r.x) / 2, y: Double(eyes.l.y + eyes.r.y) / 2)
+ if let b = bubbles.filter({ $0.pop == nil && $0.y < 236 && $0.y > 20 }).max(by: { $0.r / (hypot($0.x - c.x, $0.y - c.y) + 40) < $1.r / (hypot($1.x - c.x, $1.y - c.y) + 40) }) {
+ look = CGPoint(x: b.x, y: b.y); lookFor = max(lookFor, 0.35)
+ }
+ }
+
+ /// A bubble bursts: it flashes out, and a few drops fly off.
+ private func burst(_ i: Int) {
+ let b = bubbles[i]
+ bubbles[i].pop = 0
+ for k in 0..<4 {
+ let a = rnd(0, TAU) + Double(k) * TAU / 4
+ drops.append(Drop(x: b.x + cos(a) * b.r, y: b.y + sin(a) * b.r, vx: cos(a) * rnd(40, 70), vy: sin(a) * rnd(40, 70) - 20, t: 0))
+ }
+ }
+
+ func touched(_ r: Rig, at pt: CGPoint) {
+ finger = pt; lastTouch = pt; busyAt = t
+ look = pt; lookFor = 0.6
+ idleFor = 0; peek = nil
+ // a bubble under the finger pops
+ if let i = bubbles.firstIndex(where: { $0.pop == nil && hypot($0.x - Double(pt.x), $0.y - Double(pt.y)) < $0.r + 8 }) {
+ burst(i); r.onHaptic?(.click); return
+ }
+ // on an eye: it winces shut (the rig taps the wrist when the finger lifts), the other one widens
+ for (i, c) in [eyes.l, eyes.r].enumerated() where abs(pt.x - c.x) < eyes.w * 0.8 && abs(pt.y - c.y) < eyes.h * 0.62 {
+ flinch[i] = 1; wob[i] = -0.14; wobV[i] = 0
+ return
+ }
+ // anywhere else: a ripple of the glass runs out and bends them as it passes; they startle, away from it
+ rings.append(Ring(x: pt.x, y: pt.y, t: 0))
+ startle = 1
+ let cx = Double(eyes.l.x + eyes.r.x) / 2, cy = Double(eyes.l.y + eyes.r.y) / 2
+ let dx = cx - Double(pt.x), dy = cy - Double(pt.y), d = max(20, hypot(dx, dy))
+ off.vx += dx / d * 4000 / (d + 60); off.vy += dy / d * 4000 / (d + 60)
+ r.onHaptic?(.click)
+ }
+ /// They follow your finger while it's down.
+ func dragged(_ r: Rig, at pt: CGPoint) { finger = pt; look = pt; lookFor = 0.6; busyAt = t }
+ func released(_ r: Rig) { finger = nil; lookFor = min(lookFor, 0.35) }
+ /// Poked: four times in three seconds and they move off to the other side, annoyed, for a few seconds.
+ func poke(_ r: Rig) {
+ pokes = pokes.filter { t - $0 < 3 } + [t]
+ if pokes.count >= 4 { pokes = []; annoyed = 3.2; annoyedSide = lastTouch.x < 99 ? 1 : -1; r.saccade(-annoyedSide * 0.7, 0) }
+ }
+ func pet(_ r: Rig) {}
+ func deny(_ r: Rig) {}
+
+ func hit(_ pt: CGPoint) -> Bool {
+ let lx = Double(eyes.l.x), rx = Double(eyes.r.x), ly = Double(eyes.l.y), ry = Double(eyes.r.y)
+ let hw = abs(rx - lx) / 2 + eyes.w * 0.6 + 8, hh = eyes.h * 0.6 + 10
+ return abs(Double(pt.x) - (lx + rx) / 2) < hw && abs(Double(pt.y) - (ly + ry) / 2) < hh
+ }
+
+ // MARK: drawing
+
+ /// One eye this frame: where, its pose, and what moves it, in the order it's applied.
+ private struct Eye {
+ var p: CGPoint, pose: EyePose, side: Double
+ var lens: (dx: Double, dy: Double, angle: Double, s: Double) // a ripple passing through it
+ var stretch: (angle: Double, s: Double) // a quick look
+ var rot: Double, sx: Double, sy: Double
+ }
+ private struct Frame { var eye: [Eye]; var style: Characters.EyeStyle; var w: Double, h: Double }
+
+ private func frame(_ r: Rig) -> Frame {
+ let p = r.pose(raw: true)
+ let pr = max(press, pressBase)
+ let s = p.scale * 1.32 * (1 + 0.16 * pr)
+ let w = 27 * s, h = 41 * s, sep = 33 * s
+
+ // done: a crouch, a hop, a landing, a smaller hop, a settle
+ var hopY = 0.0, hopS = 0.0 // hopS: + stretched tall, − squashed
+ if let d = doneT {
+ if d < 0.14 { hopS = -0.13 * sin(Double.pi * d / 0.28) }
+ else if d < 0.52 { let u = (d - 0.14) / 0.38; hopY = -22 * sin(Double.pi * u); hopS = 0.09 * cos(Double.pi * u) }
+ else if d < 0.68 { hopS = -0.11 * sin(Double.pi * (d - 0.52) / 0.16) }
+ else if d < 0.92 { let u = (d - 0.68) / 0.24; hopY = -8 * sin(Double.pi * u); hopS = 0.04 * cos(Double.pi * u) }
+ else if d < 1.04 { hopS = -0.05 * sin(Double.pi * (d - 0.92) / 0.12) }
+ }
+ let dz = dizzyT ?? 9
+ let wooze = dz < 2.1 ? 0 : clamp((dz - 2.1) / 0.3, 0, 1) * clamp((3.7 - dz) / 0.3, 0, 1)
+ let c = CGPoint(x: p.cx + off.x + head.x + sin(t * TAU * 8) * 5 * shakeOff, y: p.cy + off.y + head.y + hopY)
+ let rot = p.tilt + (dizzyT != nil ? sin(dz * 3.1) * 0.2 * orbit : 0) + sin(t * 1.6) * 0.12 * wooze
+ let ca = cos(rot), sa = sin(rot), R = 6 * orbit
+ var pos = [CGPoint(x: c.x - sep * ca + cos(orbitA) * R, y: c.y - sep * sa + sin(orbitA) * R),
+ CGPoint(x: c.x + sep * ca - cos(orbitA) * R, y: c.y + sep * sa - sin(orbitA) * R)]
+ pos[0].y += sin(t * 2.1) * 5 * wooze; pos[1].y += sin(t * 2.1 + 2.2) * 5 * wooze // woozy: out of step
+ eyes = (pos[0], pos[1], w, h)
+
+ var e = p.eye
+ // your finger, or a tap: they look at it
+ if let lk = look, lookFor > 0 {
+ let dx = Double(lk.x - c.x), dy = Double(lk.y - c.y), dd = max(1, hypot(dx, dy)), k = min(1, lookFor / 0.3), reach = min(1, dd / 50)
+ e.gx = lerp(e.gx, dx / dd * reach * 0.95, k); e.gy = lerp(e.gy, dy / dd * reach * 0.85, k)
+ }
+ // working: reading a line left to right, then back to the start of the next, a few lines down, again
+ if state == .working && readT > 0.6 {
+ let line = 1.25, u = (readT - 0.6).truncatingRemainder(dividingBy: line) / line, n = Int((readT - 0.6) / line) % 4
+ let x = u < 0.82 ? lerp(-0.55, 0.55, u / 0.82) : lerp(0.55, -0.55, (u - 0.82) / 0.18)
+ e.gx = lerp(e.gx, x, 0.85); e.gy = lerp(e.gy, 0.15 + Double(n) * 0.12, 0.85)
+ }
+ e.wide = max(e.wide, startle, pr * 0.5)
+ if trauma > 0.6 && state != .dizzy { e.intent = 1 } // shaken hard: squeezed, before the dizzy
+ if annoyed > 0 { e.worried = max(e.worried, 0.8); e.intent = max(e.intent, 0.4) }
+ e.sleepy = max(e.sleepy, 0.55 * wooze, 0.38 * wind) // squinting against the wind, looking up into it
+ e.intent = max(e.intent, 0.9 * wind)
+ // the lids, decisive as an animator would key them: each one off or clearly on, never a sliver (a sliver of lid
+ // reads as a flat on the eye), and a change takes a fifth of a second
+ let fdt = min(0.05, max(0, t - lidT)), kl = min(1, fdt * 14)
+ lidT = t
+ func snap(_ v: Double, _ off: Double, _ least: Double) -> Double { v < off ? 0 : max(v, least) }
+ lid.s += (snap(e.sleepy, 0.25, 0.42) - lid.s) * kl
+ lid.w += (snap(e.worried, 0.2, 0.4) - lid.w) * kl
+ lid.i += (snap(e.intent, 0.45, 0.65) - lid.i) * kl
+ e.sleepy = lid.s; e.worried = lid.w; e.intent = lid.i
+ if wind > 0.02 { e.gy = lerp(e.gy, -0.55, wind * 0.7); e.gx *= 1 - wind * 0.5 }
+
+ let flutter = wind * wind
+ let breath = state == .sleep ? 0.028 * sin(t * TAU / 5) : 0.012 * sin(t * TAU / 3.6)
+ let blinkS = 0.1 * (1 - clamp(e.open, 0, 1)) // a blink squashes them
+ let gSpeed = hypot(gazeV.x, gazeV.y), stretch = (angle: atan2(gazeV.y * 0.8, gazeV.x), s: min(0.14, gSpeed * 0.01))
+ let bx = squashAxisX ? 1 - squash : 1 + squash * 0.6, by = squashAxisX ? 1 + squash * 0.6 : 1 - squash
+ var out: [Eye] = []
+ for i in 0..<2 {
+ let side = i == 0 ? -1.0 : 1.0
+ var ei = e
+ if wooze > 0 { // woozy: each eye wandering its own way
+ ei.gx = lerp(e.gx, sin(t * (i == 0 ? 1.3 : 1.1) + Double(i) * 2) * 0.7, wooze)
+ ei.gy = lerp(e.gy, cos(t * (i == 0 ? 1.7 : 1.5) + Double(i)) * 0.45, wooze)
+ }
+ ei.open = min(ei.open, clamp(1 - flinch[i] / 0.55, 0, 1)) // shut tight, then opening
+ ei.wince = ei.wince || flinch[i] > 0.45
+ ei.wide = max(ei.wide, flinch[1 - i] * 0.8)
+ let persp = 1 + 0.06 * ei.gx * side // the eye on the side they look to, a bit bigger
+ let sx = bx * (1 + wob[i]) * persp * (1 + blinkS) * (1 - hopS * 0.6) * (1 + 0.05 * wind)
+ let sy = by * (1 - wob[i]) * persp * (1 + breath) * (1 + hopS) * (1 - 0.1 * wind + 0.025 * flutter * sin(t * TAU * 13 + Double(i) * 1.7))
+ out.append(Eye(p: pos[i], pose: ei, side: side, lens: lens(pos[i], (w + h) / 4), stretch: stretch, rot: rot, sx: sx, sy: sy))
+ }
+ let style = Characters.EyeStyle(y: 0, gap: 0, w: w, h: h, n: lerp(3, 2.2, p.c), color: p.amber > 0.5 ? Pal.amber : Pal.white,
+ rx: 9 * s, ry: 7 * s, stroke: false, pulse: p.pulse)
+ return Frame(eye: out, style: style, w: w, h: h)
+ }
+
+ /// What a ripple does to an eye at `p` (about `re` in radius): the ripple is a ridge in the glass running out from the
+ /// tap; at its crest, what's under it spreads out along the way it runs. The eye is moved and stretched by where the
+ /// ridge puts its near and far edges, so it bends smoothly however the ridge crosses it.
+ private func lens(_ p: CGPoint, _ re: Double) -> (dx: Double, dy: Double, angle: Double, s: Double) {
+ var dx = 0.0, dy = 0.0, angle = 0.0, s = 1.0
+ for g in rings where g.t > 0 {
+ let k = g.t / 0.9, a = 0.3 * pow(1 - k, 1.5) * g.amp, R = ringRadius(g), W = 12 + 10 * k
+ let vx = Double(p.x) - g.x, vy = Double(p.y) - g.y, d = max(0.001, hypot(vx, vy))
+ func disp(_ x: Double) -> Double { let u = x - R; return a * u * exp(-(u / W) * (u / W)) }
+ let d0 = d - re, d1 = d + re, m0 = disp(d0), m1 = disp(d1)
+ let mean = (m0 + m1) / 2, sr = ((d1 + m1) - (d0 + m0)) / (d1 - d0)
+ dx += vx / d * mean; dy += vy / d * mean
+ if abs(sr - 1) > abs(s - 1) { s = sr; angle = atan2(vy, vx) }
+ }
+ return (dx, dy, angle, s)
+ }
+
+ /// A context placed on eye `i`: moved, stretched and turned as this frame says, ready to draw at its center.
+ private func place(_ ctx: GraphicsContext, _ f: Frame, _ i: Int) -> GraphicsContext {
+ let e = f.eye[i]
+ var g = ctx
+ g.translateBy(x: e.p.x + e.lens.dx, y: e.p.y + e.lens.dy)
+ if abs(e.lens.s - 1) > 0.002 { g.rotate(by: .radians(e.lens.angle)); g.scaleBy(x: e.lens.s, y: 1); g.rotate(by: .radians(-e.lens.angle)) }
+ if e.stretch.s > 0.004 { g.rotate(by: .radians(e.stretch.angle)); g.scaleBy(x: 1 + e.stretch.s, y: 1 - e.stretch.s * 0.5); g.rotate(by: .radians(-e.stretch.angle)) }
+ g.rotate(by: .radians(e.rot)); g.scaleBy(x: e.sx, y: e.sy)
+ g.translateBy(x: e.pose.gx * f.style.rx + e.pose.tremorX * 0.5, y: e.pose.gy * f.style.ry + e.pose.tremorY * 0.5)
+ return g
+ }
+
+ func draw(_ r: Rig, _ ctx: GraphicsContext) {
+ let f = frame(r)
+ if r.ao { for i in 0..<2 { Characters.drawEye(place(ctx.faded(0.5), f, i), f.style, f.eye[i].pose, side: f.eye[i].side) }; return }
+ drawEyes(ctx, f)
+ // the crown's bubbles: liquid glass, passing over them as lenses; a popped one flashes out
+ var lenses = 0
+ for b in bubbles {
+ if let k = b.pop.map({ $0 / 0.18 }) {
+ let rr = b.r * (1 + 0.5 * k)
+ ctx.stroke(Path(ellipseIn: CGRect(x: b.x - rr, y: b.y - rr, width: 2 * rr, height: 2 * rr)), with: .color(.white.opacity(0.5 * (1 - k))), lineWidth: 1)
+ continue
+ }
+ let wv = 0.035 * sin(t * 6.5 + b.phase), sx = 1 + wv, sy = (1 - wv) * (1 + min(0.08, abs(b.vy) / 1500))
+ if lenses < 4, f.eye.contains(where: { abs(b.x - Double($0.p.x)) < b.r + f.w * 0.75 && abs(b.y - Double($0.p.y)) < b.r + f.h * 0.7 }) {
+ lenses += 1
+ magnify(ctx, f, x: b.x, y: b.y, r: b.r, sx: sx, sy: sy, mag: 1.25)
+ }
+ glassRim(ctx, x: b.x, y: b.y, r: b.r, sx: sx, sy: sy)
+ }
+ for d in drops { ctx.faded(1 - d.t / 0.4).fillCircle(d.x, d.y, 1.1, Color(white: 0.85)) }
+ // the ripple's crest, faint: what shows is how it bends them
+ for g in rings where g.t > 0 {
+ let k = g.t / 0.9, a = pow(1 - k, 2) * g.amp, rr = ringRadius(g)
+ ctx.stroke(Path(ellipseIn: CGRect(x: g.x - rr, y: g.y - rr, width: 2 * rr, height: 2 * rr)), with: .color(.white.opacity(0.16 * a)), lineWidth: 1)
+ }
+ // subagents: three little pairs of eyes circling them, the far side smaller and dimmer
+ if minis > 0.02 {
+ let c = CGPoint(x: Double(f.eye[0].p.x + f.eye[1].p.x) / 2, y: Double(f.eye[0].p.y + f.eye[1].p.y) / 2)
+ for k in 0..<3 {
+ let a = minisA + Double(k) * TAU / 3, depth = sin(a), x = c.x + cos(a) * 76 * minis, y = c.y + depth * 44 * minis
+ let size = (7 + 2 * depth) * minis
+ var g = ctx.faded(minis * (0.55 + 0.45 * (depth + 1) / 2)); g.translateBy(x: x, y: y)
+ let st = Characters.EyeStyle(y: 0, gap: size * 0.62, w: size * 0.75, h: size * 1.1, n: 2.6, color: Pal.white, rx: 1, ry: 1, stroke: false, pulse: 0)
+ Characters.drawEyePair(g, st, .neutral(gx: -cos(a) * 0.6, gy: -depth * 0.4))
+ }
+ }
+ // dizzy: a ring of little glass beads circling over them
+ if halo > 0, let d = dizzyT {
+ let k = clamp(d / 0.3, 0, 1)
+ let cx = Double(f.eye[0].p.x + f.eye[1].p.x) / 2, cy = max(34, Double(min(f.eye[0].p.y, f.eye[1].p.y)) - f.h * 0.55 - 10)
+ for i in 0..<5 {
+ let a = t * TAU * 1.1 + Double(i) * TAU / 5, depth = sin(a), x = cx + cos(a) * 28 * k, y = cy + depth * 6, rad = 3 + 1 * depth
+ bead(ctx.faded(k * (0.55 + 0.45 * (depth + 1) / 2)), x: x, y: y, r: rad)
+ }
+ }
+ }
+
+ func front(_ r: Rig, _ ctx: GraphicsContext) {}
+
+ /// Their glow (light from them, not shine on them), then the eyes.
+ private func drawEyes(_ ctx: GraphicsContext, _ f: Frame) {
+ let tint = f.style.color == Pal.amber ? Pal.amber : Color(hex: 0xD6E6FF), R = f.h * 0.9
+ for i in 0..<2 {
+ place(ctx, f, i).fill(Path(ellipseIn: CGRect(x: -R, y: -R, width: 2 * R, height: 2 * R)),
+ with: .radialGradient(Gradient(colors: [tint.opacity(0.16), tint.opacity(0.04), .clear]), center: .zero, startRadius: 0, endRadius: R))
+ }
+ for i in 0..<2 { Characters.drawEye(place(ctx, f, i), f.style, f.eye[i].pose, side: f.eye[i].side) }
+ }
+
+ /// Glass that magnifies what's under it: the eyes redrawn, scaled about its center, inside it.
+ private func magnify(_ ctx: GraphicsContext, _ f: Frame, x: Double, y: Double, r: Double, sx: Double, sy: Double, mag: Double) {
+ var c = ctx
+ let shape = Path(ellipseIn: CGRect(x: x - r * sx, y: y - r * sy, width: 2 * r * sx, height: 2 * r * sy))
+ c.clip(to: shape)
+ c.fill(shape, with: .color(.black))
+ c.translateBy(x: x, y: y); c.scaleBy(x: mag, y: mag); c.translateBy(x: -x, y: -y)
+ drawEyes(c, f)
+ }
+
+ /// A bubble's glass: clear in the middle, a little shade inside its edge, a bright edge with a faint split of colour
+ /// (glass bending light), a soft highlight high on the left and a small glint low on the right.
+ private func glassRim(_ ctx: GraphicsContext, x: Double, y: Double, r: Double, sx: Double, sy: Double) {
+ var c = ctx
+ c.translateBy(x: x, y: y); c.scaleBy(x: sx, y: sy)
+ let circle = Path(ellipseIn: CGRect(x: -r, y: -r, width: 2 * r, height: 2 * r))
+ c.fill(circle, with: .radialGradient(Gradient(stops: [.init(color: .white.opacity(0.025), location: 0), .init(color: .white.opacity(0.035), location: 0.62),
+ .init(color: .black.opacity(0.3), location: 0.88), .init(color: .white.opacity(0.42), location: 1)]),
+ center: .zero, startRadius: 0, endRadius: r))
+ c.stroke(circle, with: .color(.white.opacity(0.28)), lineWidth: 0.7)
+ if r > 6 {
+ c.stroke(Path(ellipseIn: CGRect(x: -r - 0.5, y: -r - 0.6, width: 2 * r, height: 2 * r)), with: .color(Color(hex: 0x8FE9FF).opacity(0.18)), lineWidth: 0.6)
+ c.stroke(Path(ellipseIn: CGRect(x: -r + 0.5, y: -r + 0.6, width: 2 * r, height: 2 * r)), with: .color(Color(hex: 0xFFA3D9).opacity(0.12)), lineWidth: 0.6)
+ }
+ var arc = Path(); arc.addArc(center: .zero, radius: r * 0.68, startAngle: .degrees(198), endAngle: .degrees(252), clockwise: false)
+ c.stroke(arc, with: .color(.white.opacity(0.6)), style: StrokeStyle(lineWidth: max(1, r * 0.12), lineCap: .round))
+ if r > 5 { c.fillCircle(cos(0.8) * r * 0.6, sin(0.8) * r * 0.6, max(0.6, r * 0.07), .white.opacity(0.35)) }
+ }
+
+ /// A little bead of glass: a bright rim, a highlight high on the left.
+ private func bead(_ ctx: GraphicsContext, x: Double, y: Double, r: Double) {
+ let circle = Path(ellipseIn: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))
+ ctx.fill(circle, with: .radialGradient(Gradient(stops: [.init(color: .white.opacity(0.06), location: 0), .init(color: .white.opacity(0.1), location: 0.7),
+ .init(color: .white.opacity(0.5), location: 1)]), center: CGPoint(x: x, y: y), startRadius: 0, endRadius: r))
+ ctx.fillCircle(x - r * 0.38, y - r * 0.38, max(0.6, r * 0.22), .white.opacity(0.75))
+ }
+}
diff --git a/app/ChumsWatch/Rig/Pix.swift b/app/ChumsWatch/Rig/Pix.swift
new file mode 100644
index 0000000..6f90151
--- /dev/null
+++ b/app/ChumsWatch/Rig/Pix.swift
@@ -0,0 +1,1147 @@
+import Foundation
+import CoreGraphics
+import CoreText
+
+/* Pix: a deadpan fruit sprite that knows it is a sprite. A port of design/pix/pix.js, frame for frame.
+ *
+ * `Pix.draw(cg, p)` is a pure function of its input, like PIX.draw(ctx, p) in the Lab. It draws into a bitmap
+ * CGContext made by `Pix.makeContext` (premultiplied RGBA, rows top-down): every hard-edged thing (cells, eyes,
+ * the pixel font, boxes) is written straight into the bitmap by a small rasterizer that snaps edges to device
+ * pixels exactly the way the JS `snapper` does, so neighbouring cells share an edge at any scale; the HD painting
+ * (paths, gradients, the badge) goes through CoreGraphics on the same bitmap; `atRes` (draw at full resolution,
+ * show at `block` pt per sample with hard edges) is done in software: a chain of bilinear halvings, a Mitchell
+ * cubic last step, alpha thresholded at 96/255, then nearest-neighbour back on screen, mirroring what a browser
+ * canvas does for drawImage with smoothing on / off. CoreGraphics works on watchOS and macOS alike, so
+ * tools/pix-render.swift renders the same frames on the Mac to compare with design/pix/reference.
+ *
+ * The context's user space is the 198 × 242 design space of the Lab: set its transform (scale, offset) before
+ * calling draw, exactly as the Lab does with ctx.scale(). Colours are memoized like the JS MEMO.
+ */
+enum Pix {
+ // MARK: - input
+
+ enum Species: String, CaseIterable { case apple, banana }
+ enum State: String, CaseIterable {
+ case idle, listening, thinking, compacting, working, subagents, speaking, done, needs, waiting, blocked, dizzy, sleep
+ }
+ enum EyeMode { case side, none, closed, happy, cam, up, cross, squint }
+ enum Mood: Int, CaseIterable { case apple, greenApple, golden, pinkLady, rot, banana, greenBanana, redBanana, ripe, gray, turning }
+
+ struct Params {
+ var species: Species = .apple
+ var cx = 99.0, cy = 118.0
+ var px = 7.0
+ var t = 0.0
+ var state: State = .idle
+ var stateT = 0.0
+ var look: Double? = nil // idle: force the side-eye direction
+ var voice: Double? = nil // listening: 0…1
+ var text: String? = nil // speaking
+ var tools: [String] = [] // working
+ var subagents: Int? = nil
+ var screen: CGRect? = nil // the area it may use (below the watch's status row)
+ var room: Double? = nil // needs: max height when it leans in
+ var bang = true // needs: false hides the !
+ var eyeMode: EyeMode? = nil // force the eyes (e.g. .cam)
+ var palette: Mood? = nil
+ var ripe: Ripe? = nil // the crown's ripeness, over the state's own colours
+ init() {}
+ }
+
+ /// A banana's ripeness, from the crown: its colours, its sugar spots, how brown it's gone.
+ struct Ripe { var mood: Mood; var spots: Double; var rot: Double }
+ static let RIPENESS: [Ripe] = [Ripe(mood: .greenBanana, spots: 0, rot: 0), Ripe(mood: .turning, spots: 0, rot: 0),
+ Ripe(mood: .banana, spots: 0, rot: 0), Ripe(mood: .banana, spots: 0.22, rot: 0),
+ Ripe(mood: .ripe, spots: 0.45, rot: 0), Ripe(mood: .ripe, spots: 0.68, rot: 0.1),
+ Ripe(mood: .ripe, spots: 0.8, rot: 0.38)]
+
+ // MARK: - colour (OKLab)
+
+ typealias V3 = SIMD3<Double>
+
+ static func hex(_ h: String) -> V3 {
+ let s = Array(h.utf8)
+ func b(_ i: Int) -> Double { Double(Int(String(bytes: s[i..<i + 2], encoding: .ascii)!, radix: 16)!) }
+ return V3(b(1), b(3), b(5))
+ }
+ @inline(__always) static func toLin(_ c: Double) -> Double { let c = c / 255; return c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4) }
+ @inline(__always) static func toSrgb(_ c: Double) -> Double { 255 * (c <= 0.0031308 ? 12.92 * c : 1.055 * pow(c, 1 / 2.4) - 0.055) }
+ static func oklab(_ c: V3) -> V3 {
+ let r = toLin(c.x), g = toLin(c.y), b = toLin(c.z)
+ let l = cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
+ let m = cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
+ let s = cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
+ return V3(0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s)
+ }
+ static func srgb(_ c: V3) -> V3 {
+ let l = pow(c.x + 0.3963377774 * c.y + 0.2158037573 * c.z, 3)
+ let m = pow(c.x - 0.1055613458 * c.y - 0.0638541728 * c.z, 3)
+ let s = pow(c.x - 0.0894841775 * c.y - 1.291485548 * c.z, 3)
+ let r = toSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s)
+ let g = toSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s)
+ let b = toSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s)
+ return V3(max(0, min(255, r)), max(0, min(255, g)), max(0, min(255, b)))
+ }
+
+ static let PAL: [[String]] = [ // indexed by Mood
+ ["#FFC27A", "#FF5A4E", "#E3243F", "#8E1240"], // apple
+ ["#F4FFA8", "#B8F05E", "#62C93C", "#2E8A3A"], // greenApple
+ ["#FFF6B0", "#FFDA4A", "#FFAF1F", "#E2701A"], // golden
+ ["#FFD9C8", "#FF8E8A", "#F0507A", "#A8306E"], // pinkLady
+ ["#C8A47C", "#9A6C45", "#6E462A", "#4B2D1C"], // rot
+ ["#FFF8B8", "#FFE65C", "#FFC928", "#E39A1A"], // banana
+ ["#EEFFB8", "#C2EC6E", "#86CB42", "#559C30"], // greenBanana
+ ["#FFC9A8", "#F07F5E", "#C2454C", "#7E2A44"], // redBanana
+ ["#FFE9A0", "#FFC94A", "#F2A42A", "#C8781E"], // ripe
+ ["#D5D8DD", "#A3A9B2", "#7A828D", "#59606B"], // gray
+ ["#F6FFB2", "#E4F062", "#BFD936", "#8AA82A"], // turning: a banana between green and yellow
+ ]
+ enum Part: Int { case leaf, stem, bstem, tip }
+ static let PART: [[String]] = [["#C2F57E", "#5CC94F", "#2F8F43"], ["#8A5A2E", "#5A3418"], ["#A8A04A", "#5E5524"], ["#5A3A20", "#3A2414"]]
+ static let LAB: [[V3]] = PAL.map { $0.map { oklab(hex($0)) } }
+ static let PLAB: [[V3]] = PART.map { $0.map { oklab(hex($0)) } }
+
+ @inline(__always) static func grad(_ stops: [V3], _ u0: Double) -> V3 {
+ let u = max(0, min(0.9999, u0)) * Double(stops.count - 1)
+ let i = Int(floor(u)), f = u - Double(i), a = stops[i], b = stops[i + 1]
+ return a + (b - a) * f
+ }
+ @inline(__always) static func mix(_ a: V3, _ b: V3, _ k: Double) -> V3 { a + (b - a) * k }
+ @inline(__always) static func hash(_ x: Double, _ y: Double, _ s: Double) -> Double {
+ let v = sin(x * 127.1 + y * 311.7 + s * 74.7) * 43758.5453
+ return v - floor(v)
+ }
+ @inline(__always) static func clamp01(_ v: Double) -> Double { max(0, min(1, v)) }
+ @inline(__always) static func ease(_ k0: Double) -> Double { let k = clamp01(k0); return k * k * (3 - 2 * k) }
+ @inline(__always) static func step(_ v: Double, _ n: Double) -> Double { floor(v * n) / n }
+ /// JS Math.round: halves go up (toward +∞), unlike Swift's rounded().
+ @inline(__always) static func jsRound(_ v: Double) -> Double { floor(v + 0.5) }
+ @inline(__always) static func fmod(_ a: Double, _ b: Double) -> Double { a.truncatingRemainder(dividingBy: b) }
+ /// JS Math.hypot as V8 computes it (normalize to the largest, Kahan-summed squares), not libm's correctly
+ /// rounded hypot: the last bit decides which way a `d <= seg` goes in the blocked path.
+ static func jsHypot(_ a: Double, _ b: Double) -> Double {
+ let aa = abs(a), ab = abs(b), mx = max(aa, ab)
+ if mx == 0 { return 0 }
+ var sum = 0.0, comp = 0.0
+ for v in [aa, ab] {
+ let n = v / mx, summand = n * n - comp, prelim = sum + summand
+ comp = (prelim - sum) - summand; sum = prelim
+ }
+ return sqrt(sum) * mx
+ }
+ /// A float to 8 bits the way a GPU render target stores it: round to nearest, ties to even.
+ @inline(__always) static func unorm8(_ v: Double) -> UInt8 { UInt8(max(0, min(255, v)).rounded(.toNearestOrEven)) }
+
+ /// An unpremultiplied 8-bit colour, like a canvas fillStyle.
+ struct RGBA: Hashable {
+ var r: UInt8, g: UInt8, b: UInt8, a: UInt8
+ init(_ r: Int, _ g: Int, _ b: Int, _ a: Int = 255) { self.r = UInt8(r); self.g = UInt8(g); self.b = UInt8(b); self.a = UInt8(a) }
+ /// `rgba(r,g,b,alpha)`: the alpha is rounded to 8 bits like a parsed CSS colour.
+ init(_ r: Int, _ g: Int, _ b: Int, alpha: Double) { self.init(r, g, b, Int(jsRound(alpha * 255))) }
+ init(hex h: UInt32) { self.init(Int((h >> 16) & 0xFF), Int((h >> 8) & 0xFF), Int(h & 0xFF)) }
+ var cg: CGColor { CGColor(colorSpace: deviceRGB, components: [CGFloat(r) / 255, CGFloat(g) / 255, CGFloat(b) / 255, CGFloat(a) / 255])! }
+ }
+ static let deviceRGB = CGColorSpaceCreateDeviceRGB()
+ /// `css(lab)`: rgb() with each channel truncated (`| 0`).
+ @inline(__always) static func css(_ lab: V3) -> RGBA { let c = srgb(lab); return RGBA(Int(c.x), Int(c.y), Int(c.z)) }
+ static let WHITE = RGBA(255, 255, 255), INK = RGBA(0x0A, 0x0A, 0x0C)
+
+ // MARK: - species
+
+ enum StemPose { case curl, antenna, droop }
+ enum LegPose { case stand, stepL, stepR }
+ enum PartKind: UInt8 { case body = 0, stem = 1, leaf = 2, nub = 3 } // S, L, N in the JS
+
+ final class SpeciesData {
+ let key: Species, name: String, W: Int, H: Int, pxScale: Double, visW: Int, blushDX: Double
+ let rows: [[UInt8]]
+ let parts: [StemPose: [(Int, Int, PartKind)]]
+ let stemKind: Part
+ let eyes: [Int], eyeY: Int, mouth: (Int, Int, Int)
+ let legs: [LegPose: [(Int, Int)]]
+ let legsHD: [(Double, Double, Double, Double)]
+ let shine: [(Int, Int)]
+ let tip: (Double, Double), bangX: Double, badge: (Double, Double)
+ let base: Mood, moods: [State: Mood], cycle: [Mood]
+ let cells: [(Int, Int, UInt8)]
+ let span: [(Int, Int)?]
+ let bodyMask: [Bool]
+ init(key: Species, name: String, W: Int, H: Int, pxScale: Double = 1, visW: Int? = nil, blushDX: Double = 1.45, rows: [String],
+ parts: [StemPose: [(Int, Int, PartKind)]], stemKind: Part, eyes: [Int], eyeY: Int, mouth: (Int, Int, Int),
+ legs: [LegPose: [(Int, Int)]], legsHD: [(Double, Double, Double, Double)], shine: [(Int, Int)], tip: (Double, Double),
+ bangX: Double, badge: (Double, Double), base: Mood, moods: [State: Mood], cycle: [Mood]) {
+ self.key = key; self.name = name; self.W = W; self.H = H; self.pxScale = pxScale; self.visW = visW ?? W; self.blushDX = blushDX
+ self.rows = rows.map { Array($0.utf8) }
+ self.parts = parts; self.stemKind = stemKind; self.eyes = eyes; self.eyeY = eyeY; self.mouth = mouth
+ self.legs = legs; self.legsHD = legsHD; self.shine = shine; self.tip = tip; self.bangX = bangX; self.badge = badge
+ self.base = base; self.moods = moods; self.cycle = cycle
+ var cells: [(Int, Int, UInt8)] = []
+ for (y, r) in self.rows.enumerated() { for (x, c) in r.enumerated() where c != UInt8(ascii: ".") { cells.append((x, y, c)) } }
+ self.cells = cells
+ self.span = self.rows.map { r in
+ guard let a = r.firstIndex(where: { $0 != UInt8(ascii: ".") }) else { return nil }
+ var b = r.count - 1; while r[b] == UInt8(ascii: ".") { b -= 1 }
+ return (a, b)
+ }
+ var mask = [Bool](repeating: false, count: W * self.rows.count)
+ for (y, r) in self.rows.enumerated() { for x in 0..<min(W, r.count) where r[x] != UInt8(ascii: ".") { mask[y * W + x] = true } }
+ self.bodyMask = mask
+ }
+ @inline(__always) func isBody(_ x: Int, _ y: Int) -> Bool { y >= 0 && y < rows.count && x >= 0 && x < W && bodyMask[y * W + x] }
+ }
+
+ static let APPLE = SpeciesData(
+ key: .apple, name: "CRUNCH", W: 15, H: 17,
+ rows: [
+ "...............", "...............", "...............",
+ "..XXXX...XXXX..", ".XXXXXXXXXXXXX.",
+ "XXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXX",
+ ".XXXXXXXXXXXXX.", ".XXXXXXXXXXXXX.", "..XXXXXXXXXXX..", "...XXXXXXXXX...", "....XXX.XXX....",
+ ],
+ parts: [ // S stem, L leaf
+ .curl: [(8, 0, .stem), (7, 1, .stem), (7, 2, .stem), (7, 3, .stem), (10, 0, .leaf), (11, 0, .leaf), (9, 1, .leaf), (10, 1, .leaf), (11, 1, .leaf), (12, 1, .leaf), (8, 2, .leaf), (9, 2, .leaf), (10, 2, .leaf)],
+ .antenna: [(7, 0, .stem), (7, 1, .stem), (7, 2, .stem), (7, 3, .stem), (8, 2, .leaf), (9, 2, .leaf), (9, 1, .leaf), (10, 1, .leaf), (10, 2, .leaf), (11, 1, .leaf)],
+ .droop: [(7, 3, .stem), (7, 2, .stem), (6, 2, .leaf), (5, 2, .leaf), (4, 2, .leaf), (3, 2, .leaf), (5, 1, .leaf), (4, 1, .leaf)],
+ ],
+ stemKind: .stem,
+ eyes: [4, 9], eyeY: 8, mouth: (6, 10, 3),
+ legs: [
+ .stand: [(5, 15), (5, 16), (4, 16), (9, 15), (9, 16), (8, 16)],
+ .stepL: [(5, 15), (4, 15), (3, 15), (9, 15), (9, 16), (8, 16)],
+ .stepR: [(5, 15), (5, 16), (4, 16), (9, 15), (8, 15), (7, 15)],
+ ],
+ legsHD: [(5.5, 14.6, 16.45, 4.3), (9.5, 14.6, 16.45, 8.3)],
+ shine: [(2, 5), (3, 5), (2, 6)],
+ tip: (7.5, 0.5), bangX: 7.5, badge: (2.2, 0.7),
+ base: .apple, moods: [.needs: .golden, .dizzy: .greenApple], cycle: [.apple, .greenApple, .golden, .pinkLady])
+
+ static let BANANA = SpeciesData(
+ // a ")" crescent: long tapered neck up to the stem, belly bowing right, blunt bottom with a dark nub
+ key: .banana, name: "NANA", W: 15, H: 23, pxScale: 6 / 7, visW: 13, blushDX: 1.1,
+ rows: [ // rasterized from the HD outline so both versions are the same banana
+ "...............", "...XX..........", "..XXXXX........", "...XXXXXX......", "....XXXXXX.....", "....XXXXXXX....",
+ ".....XXXXXXX...", ".....XXXXXXXX..", "......XXXXXXX..", "......XXXXXXXX.", "......XXXXXXXX.", "......XXXXXXXX.",
+ ".....XXXXXXXXX.", ".....XXXXXXXX..", ".....XXXXXXXX..", "....XXXXXXXXX..", "....XXXXXXXX...", "...XXXXXXXX....",
+ "...XXXXXXX.....", "..XXXXXXX......", "..TTXXX........",
+ ],
+ parts: [
+ .curl: [(3, 0, .stem), (2, 0, .nub)],
+ .antenna: [(3, 0, .stem), (2, 0, .nub)],
+ .droop: [(2, 1, .stem), (1, 1, .nub)],
+ ],
+ stemKind: .bstem,
+ eyes: [7, 11], eyeY: 11, mouth: (8, 13, 2),
+ legs: [
+ .stand: [(4, 21), (4, 22), (3, 22), (6, 21), (6, 22), (5, 22)],
+ .stepL: [(4, 21), (3, 21), (2, 21), (6, 21), (6, 22), (5, 22)],
+ .stepR: [(4, 21), (4, 22), (3, 22), (6, 21), (7, 21)],
+ ],
+ legsHD: [(4.5, 20.6, 22.45, 3.3), (6.5, 20.6, 22.45, 5.3)],
+ shine: [(6, 6), (7, 6), (6, 7)],
+ tip: (3.5, 0.5), bangX: 3.5, badge: (12.6, 4.2),
+ base: .banana, moods: [.needs: .ripe, .dizzy: .greenBanana], cycle: [.banana, .greenBanana, .redBanana, .ripe])
+
+ static func species(_ s: Species) -> SpeciesData { s == .apple ? APPLE : BANANA }
+
+ // the shade of one cell: gradient + per-pixel jitter + bevel + glint, then rot / spots
+ static func shadeBody(_ sp: SpeciesData, _ mood: Mood, _ x: Int, _ y: Int, _ boost: Double, _ rot: Double, _ spots: Double) -> V3 {
+ let st = LAB[mood.rawValue], W = Double(sp.W), H = Double(sp.H), ch = sp.rows[y][x]
+ let fx = Double(x), fy = Double(y)
+ if ch == UInt8(ascii: "T") { let c = grad(PLAB[Part.tip.rawValue], (fx + fy) / 30); return V3(c.x + boost * 0.5, c.y, c.z) }
+ var c = grad(st, (fx / W) * 0.42 + (fy / H) * 0.58)
+ if rot > 0 { c = mix(c, grad(LAB[Mood.rot.rawValue], (fx / W) * 0.42 + (fy / H) * 0.58), rot) }
+ var L = c.x + (hash(fx, fy, 3) - 0.5) * 0.035 + boost
+ if !sp.isBody(x + 1, y) || !sp.isBody(x, y + 1) { L -= 0.065 }
+ else if !sp.isBody(x - 1, y) || !sp.isBody(x, y - 1) { L += 0.045 }
+ if sp.shine.contains(where: { $0.0 == x && $0.1 == y }) { L += 0.12 }
+ if sp.key == .banana, let s = sp.span[y], y >= 5 && y <= 17 && x == s.1 - 2 { L -= 0.035 } // the banana's ridge
+ c = V3(L, c.y, c.z)
+ if spots > 0 && hash(fx, fy, 5) < spots * 0.32 { c = mix(c, grad(PLAB[Part.tip.rawValue], 0.3), 0.8) }
+ return c
+ }
+ static func shadePart(_ sp: SpeciesData, _ kind: PartKind, _ x: Int, _ y: Int, _ boost: Double, _ rot: Double) -> V3 {
+ let fx = Double(x), fy = Double(y)
+ if kind == .leaf {
+ var c = grad(PLAB[Part.leaf.rawValue], clamp01((fy + (fx - 8) * 0.25) / 3.2))
+ if rot > 0 { c = mix(c, grad(LAB[Mood.rot.rawValue], 0.5), rot * 0.8) }
+ return V3(c.x + boost + (hash(fx, fy, 9) - 0.5) * 0.03, c.y, c.z)
+ }
+ if kind == .nub { let c = grad(PLAB[Part.tip.rawValue], 0.4); return V3(c.x + boost, c.y, c.z) }
+ let c = grad(PLAB[sp.stemKind.rawValue], fy / 3); return V3(c.x + boost, c.y, c.z)
+ }
+
+ struct MemoKey: Hashable { var sp: UInt8, kind: UInt8, mood: Int8, x: Int8, y: Int8, b: Int16, rot: Int8, spots: Int8 }
+ nonisolated(unsafe) static var MEMO: [MemoKey: RGBA] = [:]
+ @inline(__always) static func color(_ key: MemoKey, _ f: () -> V3) -> RGBA {
+ if let c = MEMO[key] { return c }
+ let c = css(f()); if MEMO.count > 30000 { MEMO.removeAll(keepingCapacity: true) }; MEMO[key] = c; return c
+ }
+ nonisolated(unsafe) static var LEG_MEMO: [Int: RGBA] = [:]
+ static func legColor(_ sp: SpeciesData, _ mood: Mood) -> RGBA {
+ if let c = LEG_MEMO[mood.rawValue] { return c }
+ let c = grad(LAB[mood.rawValue], 0.9), out = css(V3(c.x * 0.7, c.y * 0.85, c.z * 0.85)); LEG_MEMO[mood.rawValue] = out; return out
+ }
+
+ // MARK: - the bitmap and the drawing context
+
+ /// Premultiplied RGBA, 8 bits per channel, rows top-down: the pixels of one canvas.
+ final class Raster {
+ let w: Int, h: Int
+ let data: UnsafeMutablePointer<UInt8>
+ private let owned: Bool
+ private var _cg: CGContext?
+ init(w: Int, h: Int) {
+ self.w = max(1, w); self.h = max(1, h); owned = true
+ data = UnsafeMutablePointer<UInt8>.allocate(capacity: self.w * self.h * 4)
+ data.initialize(repeating: 0, count: self.w * self.h * 4)
+ }
+ /// Over bytes owned by someone else (a bitmap CGContext's data).
+ init(borrowed: UnsafeMutablePointer<UInt8>, w: Int, h: Int) { self.w = w; self.h = h; data = borrowed; owned = false }
+ deinit { if owned { data.deallocate() } }
+ func clear() { data.update(repeating: 0, count: w * h * 4) }
+ func fill(_ c: RGBA) { // opaque background
+ var i = 0
+ for _ in 0..<(w * h) { data[i] = c.r; data[i + 1] = c.g; data[i + 2] = c.b; data[i + 3] = 255; i += 4 }
+ }
+ /// A CoreGraphics context on the same bytes, y flipped so user space is the canvas's (origin top-left).
+ var cg: CGContext {
+ if let c = _cg { return c }
+ let c = CGContext(data: data, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: deviceRGB,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)!
+ c.translateBy(x: 0, y: CGFloat(h)); c.scaleBy(x: 1, y: -1)
+ _cg = c
+ return c
+ }
+ /// A CGImage over the same bytes (no copy): valid as long as the raster lives and until it is drawn into again.
+ func image() -> CGImage? {
+ guard let provider = CGDataProvider(dataInfo: nil, data: data, size: w * h * 4, releaseData: { _, _, _ in }) else { return nil }
+ return CGImage(width: w, height: h, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: w * 4, space: deviceRGB,
+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue),
+ provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
+ }
+ }
+
+ /// A canvas transform: x' = a x + c y + e, y' = b x + d y + f.
+ struct Matrix {
+ var a = 1.0, b = 0.0, c = 0.0, d = 1.0, e = 0.0, f = 0.0
+ func concat(_ n: Matrix) -> Matrix {
+ Matrix(a: a * n.a + c * n.b, b: b * n.a + d * n.b, c: a * n.c + c * n.d, d: b * n.c + d * n.d,
+ e: a * n.e + c * n.f + e, f: b * n.e + d * n.f + f)
+ }
+ var cg: CGAffineTransform { CGAffineTransform(a: a, b: b, c: c, d: d, tx: e, ty: f) }
+ }
+ struct IRect { var x0: Int, y0: Int, x1: Int, y1: Int }
+
+ /// The canvas: a transform, a clip, a fill style and global alpha over a Raster. Mirrors the subset of
+ /// CanvasRenderingContext2D that pix.js uses.
+ final class G {
+ let r: Raster
+ var m = Matrix()
+ var clip: IRect
+ var alpha = 1.0
+ var fill = RGBA(0, 0, 0)
+ private var stack: [(Matrix, IRect, Double, RGBA)] = []
+ init(_ r: Raster) { self.r = r; clip = IRect(x0: 0, y0: 0, x1: r.w, y1: r.h) }
+
+ func save() { stack.append((m, clip, alpha, fill)) }
+ func restore() { if let s = stack.popLast() { (m, clip, alpha, fill) = s } }
+ func setTransform(_ a: Double, _ b: Double, _ c: Double, _ d: Double, _ e: Double, _ f: Double) { m = Matrix(a: a, b: b, c: c, d: d, e: e, f: f) }
+ func translate(_ x: Double, _ y: Double) { m = m.concat(Matrix(e: x, f: y)) }
+ func scale(_ x: Double, _ y: Double) { m = m.concat(Matrix(a: x, d: y)) }
+ func rotate(_ t: Double) { let c = cos(t), s = sin(t); m = m.concat(Matrix(a: c, b: s, c: -s, d: c)) }
+ func clipRect(_ x: Double, _ y: Double, _ w: Double, _ h: Double) {
+ let d = deviceRect(x, y, w, h)
+ clip = IRect(x0: max(clip.x0, Int(floor(d.x0))), y0: max(clip.y0, Int(floor(d.y0))), x1: min(clip.x1, Int(ceil(d.x1))), y1: min(clip.y1, Int(ceil(d.y1))))
+ }
+ /// Device-space bounding box of a user rect (axis-aligned transforms, and the hourglass's quarter turn).
+ func deviceRect(_ x: Double, _ y: Double, _ w: Double, _ h: Double) -> (x0: Double, y0: Double, x1: Double, y1: Double) {
+ if m.b == 0 && m.c == 0 {
+ let X0 = x * m.a + m.e, X1 = (x + w) * m.a + m.e, Y0 = y * m.d + m.f, Y1 = (y + h) * m.d + m.f
+ return (min(X0, X1), min(Y0, Y1), max(X0, X1), max(Y0, Y1))
+ }
+ var x0 = Double.infinity, y0 = Double.infinity, x1 = -Double.infinity, y1 = -Double.infinity
+ for (px, py) in [(x, y), (x + w, y), (x, y + h), (x + w, y + h)] {
+ let X = m.a * px + m.c * py + m.e, Y = m.b * px + m.d * py + m.f
+ x0 = min(x0, X); y0 = min(y0, Y); x1 = max(x1, X); y1 = max(y1, Y)
+ }
+ return (x0, y0, x1, y1)
+ }
+
+ /// The paint as the GPU sees it: the fill colour's alpha is 8-bit (a parsed CSS colour), globalAlpha is not,
+ /// the premultiplied source stays float until it is stored.
+ @inline(__always) func paint() -> (Double, Double, Double, Double) {
+ let a = Double(fill.a) / 255 * alpha
+ return (Double(fill.r) * a, Double(fill.g) * a, Double(fill.b) * a, a * 255)
+ }
+ /// Source-over of one premultiplied pixel (float, 0…255) with a coverage in 0…1, stored round-to-even.
+ @inline(__always) func blend(_ i: Int, _ sr: Double, _ sg: Double, _ sb: Double, _ sa: Double, _ cov: Double) {
+ let p = r.data + i
+ let k = 1 - sa * cov / 255
+ p[0] = unorm8(sr * cov + Double(p[0]) * k); p[1] = unorm8(sg * cov + Double(p[1]) * k)
+ p[2] = unorm8(sb * cov + Double(p[2]) * k); p[3] = unorm8(sa * cov + Double(p[3]) * k)
+ }
+ /// Fill an integer device rect [x0,x1) × [y0,y1) with the paint, clipped. Opaque paints are a plain store.
+ func fillDevice(_ x0: Int, _ y0: Int, _ x1: Int, _ y1: Int) {
+ let X0 = max(x0, clip.x0), Y0 = max(y0, clip.y0), X1 = min(x1, clip.x1), Y1 = min(y1, clip.y1)
+ guard X1 > X0 && Y1 > Y0 else { return }
+ let (sr, sg, sb, sa) = paint()
+ if sa >= 255 {
+ let r8 = fill.r, g8 = fill.g, b8 = fill.b
+ for y in Y0..<Y1 {
+ var p = r.data + (y * r.w + X0) * 4
+ for _ in X0..<X1 { p[0] = r8; p[1] = g8; p[2] = b8; p[3] = 255; p += 4 }
+ }
+ } else if sa > 0 {
+ for y in Y0..<Y1 { for x in X0..<X1 { blend((y * r.w + x) * 4, sr, sg, sb, sa, 1) } }
+ }
+ }
+ /// canvas fillRect: a fractional device edge is anti-aliased the way the GPU does a quad's edges:
+ /// coverage = the smallest edge coverage (distance from the pixel centre + ½, clamped), not the area.
+ func fillRect(_ x: Double, _ y: Double, _ w: Double, _ h: Double) {
+ let d = deviceRect(x, y, w, h)
+ let fx0 = d.x0, fy0 = d.y0, fx1 = d.x1, fy1 = d.y1
+ guard fx1 > fx0 && fy1 > fy0 else { return }
+ if fx0 == floor(fx0) && fy0 == floor(fy0) && fx1 == floor(fx1) && fy1 == floor(fy1) {
+ fillDevice(Int(fx0), Int(fy0), Int(fx1), Int(fy1)); return
+ }
+ let (sr, sg, sb, sa) = paint(); guard sa > 0 else { return }
+ let ix0 = max(clip.x0, Int(floor(fx0))), iy0 = max(clip.y0, Int(floor(fy0))), ix1 = min(clip.x1, Int(ceil(fx1))), iy1 = min(clip.y1, Int(ceil(fy1)))
+ guard ix1 > ix0 && iy1 > iy0 else { return }
+ for y in iy0..<iy1 {
+ let c = Double(y) + 0.5, cy = max(0, min(1, min(c - fy0, fy1 - c) + 0.5))
+ for x in ix0..<ix1 {
+ let cxx = Double(x) + 0.5, cov = min(cy, max(0, min(1, min(cxx - fx0, fx1 - cxx) + 0.5)))
+ if cov > 0 { blend((y * r.w + x) * 4, sr, sg, sb, sa, cov) }
+ }
+ }
+ }
+ /// The JS `snapper`: both edges rounded to device pixels (so neighbours share an edge at any scale).
+ @inline(__always) func snap(_ x: Double, _ y: Double, _ w: Double, _ h: Double) {
+ let sx = m.a == 0 ? 1 : m.a, sy = m.d == 0 ? 1 : m.d, ex = m.e, fy = m.f
+ let x0 = Int(jsRound(x * sx + ex)), x1 = Int(jsRound((x + w) * sx + ex)), y0 = Int(jsRound(y * sy + fy)), y1 = Int(jsRound((y + h) * sy + fy))
+ if x1 > x0 && y1 > y0 { fillDevice(x0, y0, x1, y1) }
+ }
+
+ /// canvas drawImage(src, sx, sy, sw, sh, dx, dy, dw, dh): every device pixel in the destination samples the
+ /// source at its centre, bilinear (smoothing on) or nearest (off); partial edge pixels are covered by area.
+ func drawImage(_ src: Raster, _ sx: Double, _ sy: Double, _ sw: Double, _ sh: Double, _ dx: Double, _ dy: Double, _ dw: Double, _ dh: Double, smooth: Bool) {
+ let d = deviceRect(dx, dy, dw, dh)
+ guard d.x1 > d.x0 && d.y1 > d.y0 else { return }
+ let flipX = m.a < 0, flipY = m.d < 0
+ let ix0 = max(clip.x0, Int(floor(d.x0))), iy0 = max(clip.y0, Int(floor(d.y0))), ix1 = min(clip.x1, Int(ceil(d.x1))), iy1 = min(clip.y1, Int(ceil(d.y1)))
+ guard ix1 > ix0 && iy1 > iy0 else { return }
+ let kx = sw / (d.x1 - d.x0), ky = sh / (d.y1 - d.y0)
+ for y in iy0..<iy1 {
+ let c = Double(y) + 0.5, cy = max(0, min(1, min(c - d.y0, d.y1 - c) + 0.5))
+ var v = (c - d.y0) * ky; if flipY { v = sh - v }; v += sy
+ for x in ix0..<ix1 {
+ let cxx = Double(x) + 0.5, cov = min(cy, max(0, min(1, min(cxx - d.x0, d.x1 - cxx) + 0.5)))
+ if cov <= 0 { continue }
+ var u = (cxx - d.x0) * kx; if flipX { u = sw - u }; u += sx
+ var sr: Double, sg: Double, sb: Double, sa: Double
+ if smooth { (sr, sg, sb, sa) = Pix.bilinear(src, u, v) } else {
+ // nearest: when a pixel centre lands exactly on a sample boundary (a 5.25 px block does, every
+ // other row) the GPU's interpolated texture coordinate comes out just under it: the lower sample
+ let eps = 1e-6
+ let px = min(src.w - 1, max(0, Int(floor(u - eps)))), py = min(src.h - 1, max(0, Int(floor(v - eps))))
+ let p = src.data + (py * src.w + px) * 4
+ sr = Double(p[0]); sg = Double(p[1]); sb = Double(p[2]); sa = Double(p[3])
+ }
+ if alpha < 1 { sr *= alpha; sg *= alpha; sb *= alpha; sa *= alpha }
+ if sa <= 0 { continue }
+ if sa >= 255 && cov >= 1 { let p = r.data + (y * r.w + x) * 4; p[0] = UInt8(sr); p[1] = UInt8(sg); p[2] = UInt8(sb); p[3] = 255; continue }
+ blend((y * r.w + x) * 4, sr, sg, sb, sa, cov)
+ }
+ }
+ }
+ }
+
+ // MARK: - resampling (what a canvas does for drawImage with smoothing)
+
+ /// How the canvas resampled, tuned against the Lab's reference frames (tools/pix-compare.sh): the halvings
+ /// happen on GPU canvases (hardware bilinear, 8-bit stores), the last step into the `lo` canvas on the CPU
+ /// (willReadFrequently), where Chrome's 'high' quality came out as plain bilinear, not a cubic.
+ enum Bilinear { case lowp, hw8, float } // lowp: Skia's 8-bit areas; hw8: 8-bit fractions, float sum; float: exact
+ nonisolated(unsafe) static var halveMode: Bilinear = .float
+ nonisolated(unsafe) static var halveTiesUp = false // the GPU's float → unorm8: ties to even (false) or up (true)
+ nonisolated(unsafe) static var lastMode: Bilinear = .float
+ nonisolated(unsafe) static var lastTiesUp = false // the CPU canvas stores: ties to even matched the Lab best
+ nonisolated(unsafe) static var unpremulTiesUp = false // getImageData's unpremultiply
+ nonisolated(unsafe) static var highIsCubic = false // imageSmoothingQuality 'high' as a Mitchell cubic (B = C = 1/3)
+ nonisolated(unsafe) static var highIsMip = true // … or as linear filtering over linear mipmaps (what Chrome did)
+ nonisolated(unsafe) static var subtexelBits = 8
+ nonisolated(unsafe) static var mipBias = 0.5 // Skia's sharpen bias on the mip level
+ nonisolated(unsafe) static var mipAxisMax = false // the level from the most shrunk axis (false, Skia) or the least
+ @inline(__always) static func store8(_ v: Double, tiesUp: Bool) -> UInt8 {
+ let c = max(0, min(255, v)); return UInt8(tiesUp ? floor(c + 0.5) : c.rounded(.toNearestOrEven))
+ }
+
+ /// Bilinear sample of a premultiplied raster at continuous pixel coords (u, v), clamped at the edges (0…255 floats).
+ @inline(__always) static func bilinear(_ s: Raster, _ u: Double, _ v: Double, _ bilinearMode: Bilinear = .float) -> (Double, Double, Double, Double) {
+ let fx0 = u - 0.5, fy0 = v - 0.5
+ let x0 = Int(floor(fx0)), y0 = Int(floor(fy0))
+ var tx = fx0 - Double(x0), ty = fy0 - Double(y0)
+ let xa = min(s.w - 1, max(0, x0)), xb = min(s.w - 1, max(0, x0 + 1)), ya = min(s.h - 1, max(0, y0)), yb = min(s.h - 1, max(0, y0 + 1))
+ let p00 = s.data + (ya * s.w + xa) * 4, p10 = s.data + (ya * s.w + xb) * 4, p01 = s.data + (yb * s.w + xa) * 4, p11 = s.data + (yb * s.w + xb) * 4
+ switch bilinearMode {
+ case .lowp:
+ let w00 = Int((1 - tx) * (1 - ty) * 256), w10 = Int(tx * (1 - ty) * 256), w01 = Int((1 - tx) * ty * 256)
+ let w11 = 256 - w00 - w10 - w01
+ @inline(__always) func ch(_ i: Int) -> Double { Double((Int(p00[i]) * w00 + Int(p10[i]) * w10 + Int(p01[i]) * w01 + Int(p11[i]) * w11 + 128) >> 8) }
+ return (ch(0), ch(1), ch(2), ch(3))
+ case .hw8:
+ let q = Double(1 << subtexelBits)
+ tx = floor(tx * q) / q; ty = floor(ty * q) / q
+ fallthrough
+ case .float:
+ let w00 = (1 - tx) * (1 - ty), w10 = tx * (1 - ty), w01 = (1 - tx) * ty, w11 = tx * ty
+ @inline(__always) func ch(_ i: Int) -> Double { Double(p00[i]) * w00 + Double(p10[i]) * w10 + Double(p01[i]) * w01 + Double(p11[i]) * w11 }
+ return (ch(0), ch(1), ch(2), ch(3))
+ }
+ }
+
+ /// Mitchell–Netravali (B = C = 1/3) weights, Skia's near/far split: taps at −1.5, −0.5, +0.5, +1.5 from the sample.
+ @inline(__always) static func cubicNear(_ t: Double) -> Double { t * (t * ((-21.0 / 18) * t + 27.0 / 18) + 9.0 / 18) + 1.0 / 18 }
+ @inline(__always) static func cubicFar(_ t: Double) -> Double { t * t * ((7.0 / 18) * t - 6.0 / 18) }
+
+ /// drawImage of a whole raster into a fresh `nw × nh` raster, as a canvas does with smoothing on.
+ /// Skia's next mipmap level: a 2×2 box, or a 1-2-1 tent along an odd side, integer-truncated.
+ static func mipLevel(_ src: Raster) -> Raster {
+ let w1 = max(1, src.w >> 1), h1 = max(1, src.h >> 1), oddW = src.w & 1 == 1 && src.w > 1, oddH = src.h & 1 == 1 && src.h > 1
+ let dst = surface("mip", w1, h1)
+ let wx: [Int] = oddW ? [1, 2, 1] : [1, 1], wy: [Int] = oddH ? [1, 2, 1] : [1, 1]
+ let shift = (oddW ? 1 : 0) + (oddH ? 1 : 0) + 2
+ for y in 0..<h1 { for x in 0..<w1 {
+ var acc = (0, 0, 0, 0)
+ for (j, wyj) in wy.enumerated() { for (i, wxi) in wx.enumerated() {
+ let p = src.data + ((2 * y + j) * src.w + 2 * x + i) * 4, w = wxi * wyj
+ acc.0 += Int(p[0]) * w; acc.1 += Int(p[1]) * w; acc.2 += Int(p[2]) * w; acc.3 += Int(p[3]) * w
+ } }
+ let o = dst.data + (y * w1 + x) * 4
+ o[0] = UInt8(acc.0 >> shift); o[1] = UInt8(acc.1 >> shift); o[2] = UInt8(acc.2 >> shift); o[3] = UInt8(acc.3 >> shift)
+ } }
+ return dst
+ }
+
+ static func resample(_ src: Raster, into dst: Raster, cubic: Bool, mode: Bilinear, tiesUp: Bool, mip: Bool = false) {
+ let nw = dst.w, nh = dst.h, sw = src.w, sh = src.h
+ let kx = Double(sw) / Double(nw), ky = Double(sh) / Double(nh)
+ dst.clear()
+ // linear mipmapping as Skia does it when the draw shrinks the image: level L = −log2(scale) − ½ (its GPU-style
+ // sharpen bias), the two nearest levels sampled bilinearly and mixed
+ var mip1: Raster? = nil, mipT = 0.0
+ if mip && !cubic {
+ let scale = mipAxisMax ? max(Double(nw) / Double(sw), Double(nh) / Double(sh)) : min(Double(nw) / Double(sw), Double(nh) / Double(sh))
+ let L = max(-log2(scale) - mipBias, 0)
+ if L > 0 { mip1 = mipLevel(src); mipT = min(1, L) }
+ }
+ for j in 0..<nh {
+ let cy = (Double(j) + 0.5) * ky
+ for i in 0..<nw {
+ let cx = (Double(i) + 0.5) * kx
+ let o = dst.data + (j * nw + i) * 4
+ if !cubic {
+ var (r, g, b, a) = bilinear(src, cx, cy, mode)
+ if let m = mip1 {
+ let (r1, g1, b1, a1) = bilinear(m, cx * Double(m.w) / Double(sw), cy * Double(m.h) / Double(sh), mode)
+ r += (r1 - r) * mipT; g += (g1 - g) * mipT; b += (b1 - b) * mipT; a += (a1 - a) * mipT
+ }
+ o[0] = store8(r, tiesUp: tiesUp); o[1] = store8(g, tiesUp: tiesUp); o[2] = store8(b, tiesUp: tiesUp); o[3] = store8(a, tiesUp: tiesUp); continue
+ }
+ let fx = cx + 0.5 - floor(cx + 0.5), fy = cy + 0.5 - floor(cy + 0.5)
+ let wx = SIMD4<Double>(cubicFar(1 - fx), cubicNear(1 - fx), cubicNear(fx), cubicFar(fx))
+ let wy = SIMD4<Double>(cubicFar(1 - fy), cubicNear(1 - fy), cubicNear(fy), cubicFar(fy))
+ var r = 0.0, g = 0.0, b = 0.0, a = 0.0
+ for yy in 0..<4 {
+ let py = min(sh - 1, max(0, Int(floor(cy - 1.5 + Double(yy)))))
+ for xx in 0..<4 {
+ let px = min(sw - 1, max(0, Int(floor(cx - 1.5 + Double(xx)))))
+ let w = wx[xx] * wy[yy], p = src.data + (py * sw + px) * 4
+ r += Double(p[0]) * w; g += Double(p[1]) * w; b += Double(p[2]) * w; a += Double(p[3]) * w
+ }
+ }
+ a = max(0, min(255, a))
+ o[0] = store8(min(a, r), tiesUp: tiesUp); o[1] = store8(min(a, g), tiesUp: tiesUp); o[2] = store8(min(a, b), tiesUp: tiesUp); o[3] = store8(a, tiesUp: tiesUp)
+ }
+ }
+ }
+
+ /// Pooled scratch surfaces (hi, half0, half1, lo), reused between frames like the JS `pool`.
+ nonisolated(unsafe) static var pool: [String: Raster] = [:]
+ static func surface(_ key: String, _ w: Int, _ h: Int) -> Raster {
+ if let r = pool[key], r.w == w, r.h == h { return r }
+ let r = Raster(w: w, h: h); pool[key] = r; return r
+ }
+
+ /// For the verification harness: sees every intermediate surface of atRes (name, raster).
+ nonisolated(unsafe) static var debugHook: ((String, Raster) -> Void)? = nil
+
+ /// Draw something at full resolution, then show it at `block` pt per sample, with hard pixel edges.
+ static func atRes(_ g: G, _ x: Double, _ y: Double, _ w: Double, _ h: Double, _ block: Double, _ draw: (G) -> Void) {
+ let s0 = jsHypot(g.m.a, g.m.b), s = s0 == 0 ? 1 : s0
+ let hi = surface("hi", Int(ceil(w * s)), Int(ceil(h * s)))
+ hi.clear()
+ let hg = G(hi); hg.setTransform(s, 0, 0, s, -x * s, -y * s); draw(hg)
+ debugHook?("hi", hi)
+ if block * s <= 1.01 { g.drawImage(hi, 0, 0, Double(hi.w), Double(hi.h), x, y, w, h, smooth: true); return }
+ let lw = max(1, Int(jsRound(w / block))), lh = max(1, Int(jsRound(h / block)))
+ var src = hi, sw = hi.w, sh = hi.h, k = 0
+ while Double(sw) / 2 >= Double(lw) && Double(sh) / 2 >= Double(lh) {
+ let nw = max(lw, Int(jsRound(Double(sw) / 2))), nh = max(lh, Int(jsRound(Double(sh) / 2)))
+ let c = surface("half\(k % 2)", nw, nh); k += 1
+ resample(src, into: c, cubic: false, mode: halveMode, tiesUp: halveTiesUp)
+ debugHook?("half\(k)", c)
+ src = c; sw = nw; sh = nh
+ }
+ let lo = surface("lo", lw, lh)
+ resample(src, into: lo, cubic: highIsCubic, mode: lastMode, tiesUp: lastTiesUp, mip: highIsMip)
+ debugHook?("lo", lo)
+ // getImageData (unpremultiplied) → alpha thresholded at 96 → putImageData
+ let n = lw * lh
+ for i in 0..<n {
+ let p = lo.data + i * 4, a = Int(p[3])
+ if a > 96 {
+ if a < 255 {
+ p[0] = store8(Double(p[0]) * 255 / Double(a), tiesUp: unpremulTiesUp)
+ p[1] = store8(Double(p[1]) * 255 / Double(a), tiesUp: unpremulTiesUp)
+ p[2] = store8(Double(p[2]) * 255 / Double(a), tiesUp: unpremulTiesUp)
+ }
+ p[3] = 255
+ } else { p[0] = 0; p[1] = 0; p[2] = 0; p[3] = 0 }
+ }
+ g.drawImage(lo, 0, 0, Double(lw), Double(lh), x, y, Double(lw) * block, Double(lh) * block, smooth: false)
+ }
+
+ // MARK: - pixel font, 3 × 5
+
+ static let FONT: [UInt8: [UInt8]] = {
+ let f: [Character: [UInt8]] = [
+ "A": [2, 5, 7, 5, 5], "B": [6, 5, 6, 5, 6], "C": [3, 4, 4, 4, 3], "D": [6, 5, 5, 5, 6], "E": [7, 4, 6, 4, 7], "F": [7, 4, 6, 4, 4], "G": [3, 4, 5, 5, 3],
+ "H": [5, 5, 7, 5, 5], "I": [7, 2, 2, 2, 7], "J": [1, 1, 1, 5, 2], "K": [5, 5, 6, 5, 5], "L": [4, 4, 4, 4, 7], "M": [5, 7, 7, 5, 5], "N": [6, 5, 5, 5, 5],
+ "O": [2, 5, 5, 5, 2], "P": [6, 5, 6, 4, 4], "Q": [2, 5, 5, 6, 3], "R": [6, 5, 6, 5, 5], "S": [3, 4, 2, 1, 6], "T": [7, 2, 2, 2, 2], "U": [5, 5, 5, 5, 7],
+ "V": [5, 5, 5, 5, 2], "W": [5, 5, 7, 7, 5], "X": [5, 5, 2, 5, 5], "Y": [5, 5, 2, 2, 2], "Z": [7, 1, 2, 4, 7],
+ "0": [7, 5, 5, 5, 7], "1": [2, 6, 2, 2, 7], "2": [6, 1, 2, 4, 7], "3": [6, 1, 2, 1, 6], "4": [5, 5, 7, 1, 1], "5": [7, 4, 6, 1, 6], "6": [3, 4, 6, 5, 2],
+ "7": [7, 1, 2, 2, 2], "8": [2, 5, 2, 5, 2], "9": [2, 5, 3, 1, 6], "+": [0, 2, 7, 2, 0], "-": [0, 0, 7, 0, 0], ".": [0, 0, 0, 0, 2], "!": [2, 2, 2, 0, 2],
+ "?": [6, 1, 2, 0, 2], ":": [0, 2, 0, 2, 0], "'": [2, 2, 0, 0, 0], "/": [1, 1, 2, 4, 4], ",": [0, 0, 0, 2, 4], "(": [1, 2, 2, 2, 1], ")": [4, 2, 2, 2, 4], " ": [0, 0, 0, 0, 0],
+ "$": [3, 6, 2, 3, 6], "%": [5, 1, 2, 4, 5],
+ ]
+ var out: [UInt8: [UInt8]] = [:]
+ for (k, v) in f { out[k.asciiValue!] = v }
+ return out
+ }()
+ enum Align { case left, center, right }
+ static func textWidth(_ str: String, _ s: Double) -> Double { max(0, Double(str.utf8.count) * 4 * s - s) }
+ static func text(_ g: G, _ str0: String, _ x: Double, _ y: Double, _ s: Double, _ col: RGBA, _ align: Align = .left) {
+ let str = str0.uppercased()
+ var cx = align == .center ? x - textWidth(str, s) / 2 : align == .right ? x - textWidth(str, s) : x
+ g.fill = col
+ let blank = FONT[32]!
+ for ch in str.utf8 {
+ let gl = FONT[ch] ?? blank
+ for r in 0..<5 { for c in 0..<3 where gl[r] & (4 >> c) != 0 { g.snap(cx + Double(c) * s, y + Double(r) * s, s, s) } }
+ cx += 4 * s
+ }
+ }
+
+ // MARK: - the sprite
+
+ /// What `paint` draws: the JS `o` object.
+ struct Sprite {
+ var sp: SpeciesData
+ var ox: Double, oy: Double, px: Double
+ var mood: Mood
+ var eyeMode: EyeMode? = nil // nil → side
+ var look = 1.0
+ var legs: LegPose = .stand
+ var dy = 0.0
+ var flip = false
+ var stem: StemPose = .curl
+ var mouth = 0 // 0 none, 1 thin, 2 open
+ var boost = 0.0, rot = 0.0, spots = 0.0
+ var by = 0.0 // HD: vertical float
+ var offset: ((Int, Int) -> (Double, Double))? = nil
+ }
+ static func base(_ sp: SpeciesData, _ px: Double, _ cx: Double, _ cy: Double, _ mood: Mood) -> Sprite {
+ Sprite(sp: sp, ox: jsRound(cx - Double(sp.W) * px / 2), oy: jsRound(cy - Double(sp.H) * px / 2), px: px, mood: mood)
+ }
+
+ static func paint(_ g: G, _ o: Sprite) {
+ let sp = o.sp, ox = o.ox, oy = o.oy, px = o.px, mood = o.mood, dy = o.dy, H = sp.H
+ let b = jsRound(o.boost * 200) / 200, rot = jsRound(o.rot * 20) / 20, spots = jsRound(o.spots * 20) / 20
+ let bq = Int16(jsRound(o.boost * 200)), rq = Int8(jsRound(o.rot * 20)), sq = Int8(jsRound(o.spots * 20))
+ @inline(__always) func Y(_ y: Int) -> Double { Double(o.flip ? H - 1 - y : y) }
+ let lift = dy * (o.flip ? -1 : 1)
+ @inline(__always) func cell(_ x: Int, _ y: Int, _ col: RGBA, _ lifted: Bool) {
+ let off = o.offset?(x, y) ?? (0, 0)
+ g.fill = col
+ g.snap(ox + (Double(x) + off.0) * px, oy + (Y(y) + off.1 + (lifted ? lift : 0)) * px, px, px)
+ }
+ let leg = legColor(sp, mood)
+ for (x, y) in sp.legs[o.legs]! { cell(x, y, leg, false) }
+ let spi = UInt8(sp.key == .apple ? 0 : 1)
+ for (x, y, k) in sp.parts[o.stem]! {
+ let key = MemoKey(sp: spi, kind: k.rawValue, mood: -1, x: Int8(x), y: Int8(y), b: bq, rot: rq, spots: 0)
+ cell(x, y, color(key) { shadePart(sp, k, x, y, b, rot) }, true)
+ }
+ let mi = Int8(mood.rawValue)
+ for (x, y, _) in sp.cells {
+ let key = MemoKey(sp: spi, kind: 0, mood: mi, x: Int8(x), y: Int8(y), b: bq, rot: rq, spots: sq)
+ cell(x, y, color(key) { shadeBody(sp, mood, x, y, b, rot, spots) }, true)
+ }
+ eyes(g, o, Y)
+ if o.mouth != 0 {
+ let (mx, my, mw) = sp.mouth, top = oy + (Y(my) + lift) * px, h = o.mouth == 1 ? px * 0.45 : px
+ g.fill = INK; g.snap(ox + Double(mx) * px, top + (px - h) / 2, px * Double(mw), h)
+ }
+ }
+
+ static func eyes(_ g: G, _ o: Sprite, _ Y: (Int) -> Double) {
+ let sp = o.sp, ox = o.ox, oy = o.oy, px = o.px, mode = o.eyeMode ?? .side, look = o.look, dy = o.dy * (o.flip ? -1 : 1), EY = sp.eyeY
+ if mode == .none { return }
+ func box(_ cx: Int, _ cy: Int, _ col: RGBA, _ fx: Double = 0, _ fy: Double = 0, _ fw: Double = 1, _ fh: Double = 1) {
+ g.fill = col; g.snap(ox + (Double(cx) + fx) * px, oy + (Y(cy) + dy + fy) * px, fw * px, fh * px)
+ }
+ for (i, ex) in sp.eyes.enumerated() {
+ if mode == .closed { box(ex, EY, RGBA(10, 10, 12, alpha: 0.82), 0, 0.55, 2, 0.3); continue }
+ if mode == .happy { box(ex, EY, WHITE, 0, 0, 2, 0.42); continue }
+ if mode == .cam { box(ex, EY, INK, 0, 0, 2, 1); box(ex, EY, WHITE, 0.18, 0.16, 0.32, 0.32); continue }
+ if mode == .up { box(ex, EY, WHITE, 0, 0, 2, 1); box(ex, EY - 1, WHITE, 0, 0, 2, 1); box(ex + (look > 0 ? 1 : 0), EY - 1, INK); continue }
+ var right = look > 0
+ if mode == .cross { right = i == 0 }
+ if mode == .squint { box(ex, EY, right ? WHITE : INK, 0, 0.5, 1, 0.5); box(ex + 1, EY, right ? INK : WHITE, 0, 0.5, 1, 0.5); continue }
+ box(ex, EY, right ? WHITE : INK); box(ex + 1, EY, right ? INK : WHITE)
+ }
+ }
+
+ // MARK: - HD: the same fruit as smooth shapes, with everything the pixels could not afford
+
+ /// A closed curve through the midpoints of a point list.
+ static func smooth(_ path: CGMutablePath, _ pts: [CGPoint]) {
+ let n = pts.count
+ func mid(_ a: CGPoint, _ b: CGPoint) -> CGPoint { CGPoint(x: (a.x + b.x) / 2, y: (a.y + b.y) / 2) }
+ path.move(to: mid(pts[n - 1], pts[0]))
+ for i in 0..<n { let p = pts[i], q = mid(pts[i], pts[(i + 1) % n]); path.addQuadCurve(to: q, control: p) }
+ path.closeSubpath()
+ }
+ static func ellipsePath(_ x: Double, _ y: Double, _ rx: Double, _ ry: Double, _ rot: Double) -> CGPath {
+ let p = CGMutablePath()
+ p.addEllipse(in: CGRect(x: -rx, y: -ry, width: 2 * rx, height: 2 * ry), transform: CGAffineTransform(translationX: x, y: y).rotated(by: rot))
+ return p
+ }
+ static func gradient(_ stops: [(Double, RGBA)]) -> CGGradient {
+ CGGradient(colorsSpace: deviceRGB, colors: stops.map { $0.1.cg } as CFArray, locations: stops.map { CGFloat($0.0) })!
+ }
+
+ struct BananaPoint { var x: Double, y: Double, nx: Double, ny: Double, w: Double }
+ static let BANANA_P: [(Double, Double)] = [(2.6, 1.7), (16.6, 10.6), (2.9, 20.9)]
+ /// centerline: a quadratic from the stem end (top left) bowing right to the blunt end (bottom left)
+ static func bananaAt(_ t: Double) -> BananaPoint {
+ let (a, b, c) = (BANANA_P[0], BANANA_P[1], BANANA_P[2]), u = 1 - t
+ let x = u * u * a.0 + 2 * u * t * b.0 + t * t * c.0, y = u * u * a.1 + 2 * u * t * b.1 + t * t * c.1
+ let dx = 2 * u * (b.0 - a.0) + 2 * t * (c.0 - b.0), dy = 2 * u * (b.1 - a.1) + 2 * t * (c.1 - b.1), l0 = jsHypot(dx, dy), l = l0 == 0 ? 1 : l0
+ var w = 1.5 + 6.6 * pow(sin(Double.pi * pow(min(t, 0.985), 1.18)), 0.62)
+ if t > 0.86 { w = max(w, 4.6 - (t - 0.86) * 7) } // the blunt end
+ return BananaPoint(x: x, y: y, nx: -dy / l, ny: dx / l, w: w) // n points to the concave (left) side
+ }
+
+ /// The HD painting goes through CoreGraphics on the same bitmap. `cg` carries the canvas transform.
+ static func paintHD(_ g: G, _ o: Sprite, _ t: Double) {
+ let sp = o.sp, ox = o.ox, oy = o.oy, px = o.px, mood = o.mood, P = PAL[mood.rawValue], look = o.look, by = o.by
+ let X: (Double) -> Double = { ox + $0 * px }, Y: (Double) -> Double = { oy + $0 * px + by }
+ let cg = g.r.cg
+ cg.saveGState()
+ cg.clip(to: CGRect(x: g.clip.x0, y: g.clip.y0, width: g.clip.x1 - g.clip.x0, height: g.clip.y1 - g.clip.y0)) // the canvas's clip, in pixels
+ cg.concatenate(g.m.cg) // then its transform
+ cg.setLineCap(.round); cg.setLineJoin(.round)
+ cg.setAlpha(CGFloat(g.alpha))
+ cg.setStrokeColor(legColor(sp, mood).cg); cg.setLineWidth(px * 0.78)
+ for (lx, y0, y1, fx) in sp.legsHD {
+ cg.beginPath(); cg.move(to: CGPoint(x: X(lx), y: Y(y0))); cg.addLine(to: CGPoint(x: X(lx), y: Y(y1))); cg.addLine(to: CGPoint(x: X(fx), y: Y(y1))); cg.strokePath()
+ }
+ let bounds: (Double, Double, Double, Double)
+ func body() -> CGPath {
+ let p = CGMutablePath()
+ if sp.key == .apple {
+ p.move(to: CGPoint(x: X(7.5), y: Y(4.1)))
+ p.addCurve(to: CGPoint(x: X(14.2), y: Y(5.2)), control1: CGPoint(x: X(8.6), y: Y(2.7)), control2: CGPoint(x: X(12.6), y: Y(2.4)))
+ p.addCurve(to: CGPoint(x: X(11.6), y: Y(14.5)), control1: CGPoint(x: X(15.5), y: Y(8.2)), control2: CGPoint(x: X(14.6), y: Y(12.8)))
+ p.addCurve(to: CGPoint(x: X(7.5), y: Y(14.8)), control1: CGPoint(x: X(10.2), y: Y(15.3)), control2: CGPoint(x: X(8.7), y: Y(14.7)))
+ p.addCurve(to: CGPoint(x: X(3.4), y: Y(14.5)), control1: CGPoint(x: X(6.3), y: Y(14.7)), control2: CGPoint(x: X(4.8), y: Y(15.3)))
+ p.addCurve(to: CGPoint(x: X(0.8), y: Y(5.2)), control1: CGPoint(x: X(0.4), y: Y(12.8)), control2: CGPoint(x: X(-0.5), y: Y(8.2)))
+ p.addCurve(to: CGPoint(x: X(7.5), y: Y(4.1)), control1: CGPoint(x: X(2.4), y: Y(2.4)), control2: CGPoint(x: X(6.4), y: Y(2.7)))
+ p.closeSubpath()
+ } else {
+ let N = 28; var L: [CGPoint] = [], R: [CGPoint] = []
+ for i in 0...N {
+ let q = bananaAt(Double(i) / Double(N))
+ L.append(CGPoint(x: X(q.x + q.nx * q.w / 2), y: Y(q.y + q.ny * q.w / 2))); R.append(CGPoint(x: X(q.x - q.nx * q.w / 2), y: Y(q.y - q.ny * q.w / 2)))
+ }
+ smooth(p, R + L.reversed())
+ }
+ return p
+ }
+ if sp.key == .apple {
+ bounds = (-0.6, 2.3, 15.6, 15.4)
+ // back: stem and leaf
+ cg.setStrokeColor(RGBA(hex: 0x5A3418).cg); cg.setLineWidth(px * 0.9)
+ cg.beginPath(); cg.move(to: CGPoint(x: X(7.5), y: Y(4.2))); cg.addQuadCurve(to: CGPoint(x: X(8.4), y: Y(0.5)), control: CGPoint(x: X(7.1), y: Y(2.0))); cg.strokePath()
+ let leaf = CGMutablePath()
+ leaf.move(to: CGPoint(x: X(8.2), y: Y(2.3))); leaf.addQuadCurve(to: CGPoint(x: X(13.1), y: Y(0.8)), control: CGPoint(x: X(9.4), y: Y(-0.3)))
+ leaf.addQuadCurve(to: CGPoint(x: X(8.2), y: Y(2.3)), control: CGPoint(x: X(11.6), y: Y(3.1)))
+ cg.saveGState(); cg.addPath(leaf); cg.clip()
+ cg.drawLinearGradient(gradient([(0, RGBA(hex: 0x2F8F43)), (1, RGBA(hex: 0xC2F57E))]), start: CGPoint(x: X(8), y: Y(2.4)), end: CGPoint(x: X(13), y: Y(0.6)), options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])
+ cg.restoreGState()
+ cg.beginPath(); cg.move(to: CGPoint(x: X(8.6), y: Y(2.1))); cg.addQuadCurve(to: CGPoint(x: X(12.4), y: Y(0.95)), control: CGPoint(x: X(10.4), y: Y(1.2)))
+ cg.setLineWidth(px * 0.16); cg.setStrokeColor(RGBA(20, 80, 30, alpha: 0.55).cg); cg.strokePath()
+ } else {
+ bounds = (0, 0, 15, 22)
+ cg.setStrokeColor(RGBA(hex: 0x5E5524).cg); cg.setLineWidth(px * 1.0); cg.setLineCap(.butt)
+ cg.beginPath(); cg.move(to: CGPoint(x: X(3.0), y: Y(2.4))); cg.addQuadCurve(to: CGPoint(x: X(1.0), y: Y(0.4)), control: CGPoint(x: X(2.1), y: Y(1.0))); cg.strokePath(); cg.setLineCap(.round)
+ cg.addPath(ellipsePath(X(1.0), Y(0.4), px * 0.5, px * 0.55, 0.5)); cg.setFillColor(RGBA(hex: 0x3A2414).cg); cg.fillPath()
+ }
+ let (bx0, by0, bx1, by1) = bounds
+ let bodyPath = body()
+ cg.saveGState(); cg.addPath(bodyPath); cg.clip()
+ cg.drawLinearGradient(gradient(P.enumerated().map { (Double($0.offset) / Double(P.count - 1), RGBA(hex: UInt32(P[$0.offset].dropFirst(), radix: 16)!)) }),
+ start: CGPoint(x: X(bx0), y: Y(by0)), end: CGPoint(x: X(bx0 + (bx1 - bx0) * 0.9), y: Y(by1 * 1.02)), options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])
+ cg.drawRadialGradient(gradient([(0, RGBA(255, 255, 255, alpha: 0.4)), (1, RGBA(255, 255, 255, alpha: 0))]),
+ startCenter: CGPoint(x: X(bx0 + 3.4), y: Y(by0 + 2.6)), startRadius: 0, endCenter: CGPoint(x: X(bx0 + 3.4), y: Y(by0 + 2.6)), endRadius: 9 * px, options: [.drawsBeforeStartLocation])
+ cg.drawLinearGradient(gradient([(0, RGBA(60, 0, 40, alpha: 0)), (1, RGBA(60, 0, 40, alpha: 0.3))]),
+ start: CGPoint(x: 0, y: Y(by0 + (by1 - by0) * 0.45)), end: CGPoint(x: 0, y: Y(by1)), options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])
+ cg.restoreGState()
+ cg.addPath(bodyPath); cg.setLineWidth(px * 0.14); cg.setStrokeColor(RGBA(255, 255, 255, alpha: 0.35).cg); cg.strokePath()
+ // front
+ if sp.key == .apple {
+ cg.addPath(ellipsePath(X(3.6), Y(5.8), px * 1.7, px * 0.7, -0.7)); cg.setFillColor(RGBA(255, 255, 255, alpha: 0.72).cg); cg.fillPath()
+ } else {
+ let e = bananaAt(1)
+ cg.addPath(ellipsePath(X(e.x), Y(e.y), px * 1.3, px * 0.75, atan2(e.ny, e.nx))); cg.setFillColor(RGBA(hex: 0x5A3A20).cg); cg.fillPath()
+ func line(_ t0: Double, _ t1: Double, _ off: Double, _ w: Double, _ col: RGBA) {
+ cg.beginPath()
+ for i in 0...20 {
+ let q = bananaAt(t0 + (t1 - t0) * Double(i) / 20), pt = CGPoint(x: X(q.x + q.nx * q.w * off), y: Y(q.y + q.ny * q.w * off))
+ if i == 0 { cg.move(to: pt) } else { cg.addLine(to: pt) }
+ }
+ cg.setLineWidth(px * w); cg.setStrokeColor(col.cg); cg.strokePath()
+ }
+ line(0.22, 0.9, -0.22, 0.2, RGBA(160, 100, 0, alpha: 0.22)) // the ridge on the back
+ line(0.3, 0.62, 0.3, 0.5, RGBA(255, 255, 255, alpha: 0.6)) // gloss
+ }
+ // face
+ let ec = sp.eyes.map { (Double($0) + 1, Double(sp.eyeY) + 0.5) }
+ let bdx = sp.blushDX
+ for (i, e) in ec.enumerated() {
+ cg.addPath(ellipsePath(X(e.0 + (i == 1 ? bdx : -bdx)), Y(e.1 + 2.0), px * 1.0, px * 0.48, 0)); cg.setFillColor(RGBA(255, 80, 130, alpha: 0.42).cg); cg.fillPath()
+ }
+ for e in ec {
+ cg.addPath(ellipsePath(X(e.0), Y(e.1), px * 1.05, px * 1.3, 0)); cg.setFillColor(WHITE.cg); cg.fillPath()
+ let pxp = X(e.0) + look * px * 0.32
+ cg.addPath(ellipsePath(pxp, Y(e.1) + px * 0.12, px * 0.66, px * 0.8, 0)); cg.setFillColor(INK.cg); cg.fillPath()
+ cg.addPath(ellipsePath(pxp - px * 0.24, Y(e.1) - px * 0.22, px * 0.26, px * 0.26, 0)); cg.setFillColor(WHITE.cg); cg.fillPath()
+ cg.addPath(ellipsePath(pxp + px * 0.24, Y(e.1) + px * 0.38, px * 0.11, px * 0.11, 0)); cg.fillPath()
+ }
+ let (mx, my, mw) = sp.mouth, mcx = Double(mx) + Double(mw) / 2
+ cg.beginPath(); cg.move(to: CGPoint(x: X(mcx - 0.9), y: Y(Double(my) + 0.35))); cg.addQuadCurve(to: CGPoint(x: X(mcx + 0.9), y: Y(Double(my) + 0.35)), control: CGPoint(x: X(mcx), y: Y(Double(my) + 1.1)))
+ cg.setLineWidth(px * 0.32); cg.setStrokeColor(INK.cg); cg.strokePath()
+ // sparkles
+ func spark(_ x: Double, _ y: Double, _ s: Double) {
+ if s <= 0 { return }
+ cg.beginPath(); cg.move(to: CGPoint(x: x, y: y - s))
+ cg.addQuadCurve(to: CGPoint(x: x + s, y: y), control: CGPoint(x: x, y: y)); cg.addQuadCurve(to: CGPoint(x: x, y: y + s), control: CGPoint(x: x, y: y))
+ cg.addQuadCurve(to: CGPoint(x: x - s, y: y), control: CGPoint(x: x, y: y)); cg.addQuadCurve(to: CGPoint(x: x, y: y - s), control: CGPoint(x: x, y: y))
+ cg.setFillColor(WHITE.cg); cg.fillPath()
+ }
+ for (sx, sy, ph) in [(-0.6, by0 + 1.5, 0.0), (bx1 + 0.2, by0 + 3, 1.3), (bx1 - 0.8, by0 - 1.2, 2.1), (-0.2, by1 - 2.5, 3.2), (bx1 + 0.6, by1 - 3.5, 0.7)] {
+ spark(X(sx), Y(sy), px * 0.9 * max(0, sin(t * 5 + ph)))
+ }
+ // badge
+ let bx = X(sp.badge.0), byy = Y(sp.badge.1)
+ cg.addPath(CGPath(roundedRect: CGRect(x: bx - px * 1.35, y: byy - px * 0.75, width: px * 2.7, height: px * 1.5), cornerWidth: px * 0.45, cornerHeight: px * 0.45, transform: nil))
+ cg.setFillColor(WHITE.cg); cg.fillPath()
+ badgeText(cg, "HD", bx, byy + px * 0.06, size: px * 1.15)
+ cg.restoreGState()
+ }
+
+ /// The HD badge's label: `800 ${px*1.15}px ui-rounded, system-ui`, centred, baseline middle.
+ nonisolated(unsafe) static var badgeFontCache: (size: Double, font: CTFont)? = nil
+ static func badgeText(_ cg: CGContext, _ s: String, _ x: Double, _ y: Double, size: Double) {
+ let font: CTFont
+ if let c = badgeFontCache, c.size == size { font = c.font } else {
+ let traits: [CFString: Any] = [kCTFontWeightTrait: 0.56] // heavy
+ let attrs: [CFString: Any] = [kCTFontFamilyNameAttribute: ".AppleSystemUIFont", kCTFontTraitsAttribute: traits]
+ let desc = CTFontDescriptorCreateWithAttributes(attrs as CFDictionary)
+ font = CTFontCreateWithFontDescriptor(desc, size, nil)
+ badgeFontCache = (size, font)
+ }
+ let attrs: [NSAttributedString.Key: Any] = [NSAttributedString.Key(kCTFontAttributeName as String): font,
+ NSAttributedString.Key(kCTForegroundColorAttributeName as String): INK.cg]
+ let line = CTLineCreateWithAttributedString(NSAttributedString(string: s, attributes: attrs))
+ let w = CTLineGetTypographicBounds(line, nil, nil, nil)
+ let asc = CTFontGetAscent(font), desc = CTFontGetDescent(font)
+ cg.saveGState()
+ cg.textMatrix = .identity
+ // the context is y-down: flip around the baseline so glyphs stand upright
+ cg.translateBy(x: x - w / 2, y: y + (asc - desc) / 2); cg.scaleBy(x: 1, y: -1)
+ cg.setFillColor(INK.cg)
+ CTLineDraw(line, cg)
+ cg.restoreGState()
+ }
+
+ // MARK: - states
+
+ @inline(__always) static func blinkAt(_ t: Double, _ seed: Double = 0) -> Bool { fmod(t + seed * 0.7, 3.7) < 0.11 }
+
+ /// Make a bitmap context Pix can draw into: premultiplied RGBA, origin top-left, user space in device pixels.
+ static func makeRaster(width: Int, height: Int) -> Raster { Raster(w: width, h: height) }
+
+ /// Draw one frame into a bitmap CGContext made by `Raster.cg` (or any premultiplied-RGBA, 32-bit, top-down bitmap
+ /// context whose current transform maps the 198 × 242 design space to its pixels, like ctx.scale() in the Lab).
+ static func draw(_ cg: CGContext, _ p: Params) {
+ guard let data = cg.data, cg.bitsPerPixel == 32 else { return }
+ let raster = Raster(borrowed: data.assumingMemoryBound(to: UInt8.self), w: cg.width, h: cg.height)
+ var m = cg.ctm
+ if m.d < 0 { m = m.concatenating(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: CGFloat(cg.height))) } // undo the y flip
+ let g = G(raster); g.setTransform(m.a, m.b, m.c, m.d, m.tx, m.ty)
+ draw(g, p)
+ }
+ /// Draw one frame into a Raster with a canvas transform (the fast path PixStage and the harness use).
+ static func draw(_ r: Raster, transform m: Matrix, _ p: Params) { let g = G(r); g.m = m; draw(g, p) }
+
+ static func draw(_ ctx: G, _ p: Params) {
+ let sp = species(p.species), W = sp.W, H = sp.H, Wd = Double(W), Hd = Double(H)
+ let st = p.state, T = p.stateT, t = p.t, px0 = jsRound(p.px * sp.pxScale)
+ let scr = p.screen ?? CGRect(x: 0, y: 0, width: 198, height: 242)
+ let sx = Double(scr.minX), sy = Double(scr.minY), sw = Double(scr.width), sh = Double(scr.height)
+ let mood0 = p.ripe?.mood ?? p.palette ?? sp.moods[st] ?? sp.base
+ func base(_ px: Double, _ cx: Double? = nil, _ cy: Double? = nil) -> Sprite {
+ var o = Pix.base(sp, px, cx ?? p.cx, cy ?? p.cy, mood0)
+ if let rp = p.ripe { o.spots = max(o.spots, rp.spots); o.rot = max(o.rot, rp.rot) }
+ return o
+ }
+ let idleBob = Double(Int(floor(t * 1.25)) % 2)
+ ctx.save()
+ defer { ctx.restore() }
+
+ switch st {
+ case .idle:
+ let ph = fmod(t, 8), look = p.look ?? (ph < 2.6 ? 1 : ph < 5.2 ? -1 : 1)
+ let mode = p.eyeMode ?? (blinkAt(t) ? .closed : (ph > 5.2 && ph < 6.5) ? .cam : .side)
+ var o = base(px0); o.dy = p.eyeMode != nil ? 0 : idleBob; o.eyeMode = mode; o.look = look
+ paint(ctx, o)
+
+ case .listening:
+ let v = clamp01(p.voice ?? (0.5 + 0.5 * sin(t * 9) * sin(t * 2.3)))
+ let px = px0 + 1
+ var o = base(px); o.stem = .antenna; o.boost = v * 0.05; o.eyeMode = blinkAt(t) ? .closed : .cam
+ paint(ctx, o)
+ // the stem is an antenna: ((( · ))) like a broadcast icon, one arc per loudness step
+ let c = max(3, jsRound(px * 0.5)), tipx = o.ox + sp.tip.0 * px, tipy = o.oy + sp.tip.1 * px, n = Int(ceil(v * 3))
+ ctx.fill = WHITE
+ for i in 0..<n {
+ ctx.alpha = 1 - Double(i) * 0.22
+ let hh = i + 1
+ for j in -hh...hh { for side in [-1.0, 1.0] {
+ let dx = (2 * Double(i) + 2.2 - (abs(j) == hh ? 1 : 0)) * c * side
+ ctx.fillRect(jsRound(tipx + dx - c / 2), jsRound(tipy + Double(j) * c - c / 2), c, c)
+ } }
+ }
+ ctx.alpha = 1
+
+ case .thinking:
+ let c = fmod(T, 4.6), block: Double = c < 0.45 ? 1 : c < 1.3 ? 2 : c < 2.4 ? 3 : c < 4.0 ? 4 : 1
+ let lk: Double = Int(floor(T / 1.15)) % 2 != 0 ? -1 : 1
+ var o = base(px0); o.eyeMode = .up; o.look = lk
+ if block == 1 { o.eyeMode = c >= 4.0 ? .cam : .up; paint(ctx, o) }
+ else {
+ atRes(ctx, o.ox, o.oy, Wd * o.px, Hd * o.px, o.px * block) { g in var q = o; q.eyeMode = EyeMode.none; paint(g, q) }
+ eyes(ctx, o) { Double($0) }
+ }
+
+ case .working:
+ let stepI = Int(floor(T / 0.2)), legs: LegPose = stepI % 2 != 0 ? .stepL : .stepR
+ var o = base(px0); o.legs = legs; o.dy = Double(stepI % 2); o.eyeMode = blinkAt(t) ? .closed : .squint; o.look = 1
+ paint(ctx, o)
+ let tools = (p.tools.isEmpty ? ["Read", "Edit", "Bash", "Grep", "Edit", "Test"] : p.tools).map { $0.uppercased() }
+ let every = 0.75, k0 = Int(floor(T / every))
+ for k in max(0, k0 - 2)...k0 {
+ let age = T - Double(k) * every; if age < 0 || age > 1.5 { continue }
+ let label = "+1 " + tools[k % tools.count], rise = step(age / 1.5, 10) * max(8, min(34, o.oy - 20 - sy))
+ let x = o.ox + Wd * o.px / 2 + (k % 2 != 0 ? 30 : -30), y = o.oy - 14 - rise
+ ctx.alpha = age > 1.1 ? 0.5 : 1
+ text(ctx, label, x + 1, y + 1, 2, RGBA(120, 40, 0, alpha: 0.9), .center); text(ctx, label, x, y, 2, RGBA(hex: 0xFFE66B), .center)
+ }
+ ctx.alpha = 1
+ if stepI % 4 == 1 { ctx.fill = RGBA(hex: 0x8FD8FF); let sx = o.ox + Wd * o.px + 2, sy = o.oy + 5 * o.px; ctx.fillRect(sx, sy, 3, 3); ctx.fillRect(sx, sy + 3, 2, 2) }
+
+ case .speaking:
+ let msg = (p.text ?? "All 14 tests pass. I also fixed a typo you made in 2019.").uppercased()
+ let bx = sx + 8, bw = sw - 16, bh = 82.0, by = sy + sh - bh - 8, cpl = Int(floor((bw - 18) / 8))
+ var lines: [String] = []; var line = ""
+ for w in msg.split(separator: " ", omittingEmptySubsequences: false).map(String.init) {
+ if (line + " " + w).trimmingCharacters(in: .whitespaces).count > cpl { lines.append(line.trimmingCharacters(in: .whitespaces)); line = w } else { line += " " + w }
+ }
+ if !line.trimmingCharacters(in: .whitespaces).isEmpty { lines.append(line.trimmingCharacters(in: .whitespaces)) }
+ let shown = Int(floor(T * 22)); var left = shown
+ let typed: [String] = lines.map { l in let n = max(0, min(l.count, left)); left -= l.count; return String(l.prefix(n)) }
+ let doneTyping = shown >= lines.joined().count
+ let lastCh = (typed.last(where: { !$0.isEmpty }) ?? " ").last ?? " "
+ let mouth = doneTyping ? 0 : ("AEIOU".contains(lastCh) ? 2 : Int(floor(T * 11)) % 2)
+ let px = jsRound(5 * sp.pxScale)
+ var o = base(px, sx + sw / 2, by - Hd * px / 2 - 8); o.dy = doneTyping ? idleBob : Double(Int(floor(T * 6)) % 2); o.mouth = mouth; o.eyeMode = blinkAt(t) ? .closed : .cam
+ paint(ctx, o)
+ ctx.fill = RGBA(hex: 0x0D0D1A); ctx.fillRect(bx, by, bw, bh)
+ ctx.fill = WHITE; ctx.fillRect(bx, by, bw, 2); ctx.fillRect(bx, by + bh - 2, bw, 2); ctx.fillRect(bx, by, 2, bh); ctx.fillRect(bx + bw - 2, by, 2, bh)
+ ctx.fill = RGBA(hex: 0x5B5BFF); ctx.fillRect(bx + 4, by + 4, bw - 8, 1); ctx.fillRect(bx + 4, by + bh - 5, bw - 8, 1)
+ let tw = textWidth(sp.name, 2) + 12, ty = by - 15; ctx.fill = RGBA(hex: 0x0D0D1A); ctx.fillRect(bx + 10, ty, tw, 17)
+ ctx.fill = WHITE; ctx.fillRect(bx + 10, ty, tw, 2); ctx.fillRect(bx + 10, ty, 2, 17); ctx.fillRect(bx + 10 + tw - 2, ty, 2, 17)
+ text(ctx, sp.name, bx + 16, ty + 5, 2, RGBA(hex: 0xFFE66B))
+ for (i, l) in typed.prefix(5).enumerated() { text(ctx, l, bx + 9, by + 12 + Double(i) * 13, 2, WHITE) }
+ if doneTyping && Int(floor(t * 2.5)) % 2 != 0 { ctx.fill = WHITE; let ax = bx + bw - 16, ay = by + bh - 14; ctx.fillRect(ax, ay, 8, 2); ctx.fillRect(ax + 2, ay + 2, 4, 2); ctx.fillRect(ax + 3, ay + 4, 2, 2) }
+
+ case .done:
+ let c = fmod(T, 4.2); var o = base(px0); o.mood = sp.base
+ let up = [0.14, 0.23, 0.32, 0.41], down = [2.55, 2.62, 2.69, 2.76], blocks = [1.0, 0.5, 0.25, 0.125]
+ func region(_ b: Double, _ g: (G) -> Void) { atRes(ctx, o.ox - o.px, o.oy - 3 * o.px, (Wd + 2) * o.px, (Hd + 3) * o.px, o.px * b, g) }
+ if c < 0.14 { var q = o; q.dy = -1; q.eyeMode = .happy; paint(ctx, q) }
+ else if c < 0.5 { let i = up.firstIndex(where: { c < $0 + 0.09 }) ?? -1; region(blocks[max(0, i)]) { g in paintHD(g, o, t) } }
+ else if c < 2.55 { var q = o; q.by = sin((c - 0.5) * 3.2) * 2.2; paintHD(ctx, q, t) }
+ else if c < 2.83 { let i = down.firstIndex(where: { c < $0 + 0.07 }) ?? -1; region(blocks[3 - max(0, i)]) { g in paintHD(g, o, t) } }
+ else { var q = o; q.dy = idleBob; q.eyeMode = c < 3.4 ? .happy : .side; q.look = 1; paint(ctx, q) }
+
+ case .needs:
+ let lean = max(0, min(3, min(floor((p.room ?? 172) / Hd) - px0, floor(max(0, T - 1.4) / 1.4))))
+ let px = px0 + lean, hop = T < 0.26 ? -jsRound(sin(T / 0.26 * Double.pi) * 2) : 0
+ var o = base(px, p.cx, p.cy + lean * 4); o.dy = hop; o.eyeMode = blinkAt(t, 2) && T > 1 ? .closed : .cam
+ paint(ctx, o)
+ if !p.bang { return }
+ let pop = T < 0.1 ? T / 0.1 : 1, bob = Double(Int(floor(t * 2)) % 2), s = max(2, jsRound(px * 0.62 * pop))
+ let ex = o.ox + sp.bangX * px - s, ey = o.oy - 1.5 * px + hop * px - bob * 2 - 7 * s
+ ctx.fill = WHITE; ctx.fillRect(ex - s / 2, ey - s / 2, s * 3, s * 5.5); ctx.fillRect(ex - s / 2, ey + 5.5 * s, s * 3, s * 2.5)
+ ctx.fill = RGBA(hex: 0xFF3B30); ctx.fillRect(ex, ey, s * 2, s * 4.5); ctx.fillRect(ex, ey + 6 * s, s * 2, s * 1.5)
+
+ case .blocked:
+ // dragged around like a frozen window: a stamp every frame, 15 pt apart, each one a bit more overripe
+ let c = fmod(T, 6.5), px = max(3, jsRound(4 * sp.pxScale)), frames = min(Int(floor(c * 9)), 26)
+ let pts: [(Double, Double)] = [(62, 96), (136, 104), (70, 160), (138, 178)]
+ let P: [(Double, Double)] = pts.map { (q: (Double, Double)) -> (Double, Double) in
+ let x: Double = sx + q.0 * sw / 198, y: Double = sy + q.1 * sh / 242
+ return (x, y)
+ }
+ var seg: [Double] = []; var tot = 0.0
+ for i in 1..<P.count { let l = jsHypot(P[i].0 - P[i - 1].0, P[i].1 - P[i - 1].1); seg.append(l); tot += l }
+ func path(_ k: Int) -> (Double, Double) {
+ var d = min(tot, Double(k) * 15)
+ for i in 0..<seg.count { if d <= seg[i] { let f = d / seg[i]; return (P[i].0 + (P[i + 1].0 - P[i].0) * f, P[i].1 + (P[i + 1].1 - P[i].1) * f) }; d -= seg[i] }
+ return P[P.count - 1]
+ }
+ for k in 0...frames {
+ let (cx, cy) = path(k), age = Double(k) / 26
+ var o = base(px, cx, cy); o.mood = sp.base; o.stem = k > 13 ? .droop : .curl
+ o.rot = sp.key == .apple ? age * 0.85 : age * 0.3; o.spots = sp.key == .banana ? age : 0; o.eyeMode = .side; o.look = 1
+ paint(ctx, o)
+ }
+ text(ctx, "NOT RESPONDING", sx + sw / 2, sy + 18, 2, Int(floor(t * 1.6)) % 2 != 0 ? WHITE : RGBA(hex: 0x9AA1AA), .center)
+
+ case .dizzy:
+ let c = fmod(T, 3.4), seed = 11.0
+ let scatter = c < 0.45 ? ease(c / 0.45) : c < 1.0 ? 1 - ease((c - 0.45) / 0.55) : 0
+ let flip = c >= 0.72 && c < 2.3
+ let offset: ((Int, Int) -> (Double, Double))? = scatter > 0 ? { x, y in
+ let a = hash(Double(x), Double(y), seed) * Double.pi * 2, r = (2 + hash(Double(y), Double(x), seed) * 5) * scatter
+ return (jsRound(cos(a) * r), jsRound(sin(a) * r))
+ } : nil
+ let look: Double = Int(floor(t * 8)) % 2 != 0 ? 1 : -1
+ let eyesMode: EyeMode = c < 1.0 ? .cross : flip ? (c > 1.6 && c < 1.75 ? .closed : .side) : c < 2.9 ? .cross : .side
+ if c >= 2.3 && c < 2.42 {
+ var o = base(px0); ctx.save(); ctx.translate(0, p.cy); ctx.scale(1, 0.45); ctx.translate(0, -p.cy)
+ o.eyeMode = .closed; paint(ctx, o); ctx.restore()
+ } else { var o = base(px0); o.flip = flip; o.offset = offset; o.eyeMode = eyesMode; o.look = look; paint(ctx, o) }
+
+ case .compacting:
+ // the context is being compacted, so it is: squashed flat under a press, its pixels JPEG'd into blocks
+ let c = fmod(T, 2.4), squeeze = 0.56 + 0.05 * sin(c / 2.4 * Double.pi * 2) - min(0.1, T * 0.12)
+ let o = base(px0), bottom = o.oy + Hd * px0
+ ctx.save(); ctx.translate(p.cx, bottom); ctx.scale(1 + (1 - squeeze) * 0.4, squeeze); ctx.translate(-p.cx, -bottom)
+ atRes(ctx, o.ox - px0 * 2, o.oy - px0, (Wd + 4) * px0, (Hd + 1) * px0, px0 * 2) { g in var q = o; q.eyeMode = EyeMode.none; paint(g, q) }
+ var e = o; e.eyeMode = .cam; eyes(ctx, e) { Double($0) }
+ ctx.restore()
+ // the press rests on its head
+ let top = bottom - Hd * px0 * squeeze - 3, plateW = sw - 24
+ ctx.fill = RGBA(hex: 0x3A3F46); ctx.fillRect(sx + 12, top - 9, plateW, 9)
+ ctx.fill = RGBA(hex: 0x5A6069); ctx.fillRect(sx + 12, top - 9, plateW, 2)
+ ctx.fill = RGBA(hex: 0x2A2E33); ctx.fillRect(sx + sw / 2 - 3, sy, 6, top - 9 - sy)
+ let pct = 40 + Int(floor(T * 9)) % 50
+ text(ctx, "-\(pct)%", sx + sw - 16, top - 22, 2, RGBA(hex: 0xFFE66B), .right)
+
+ case .waiting:
+ // rate limited: it waits, tapping a foot under an hourglass, and keeps looking up at the clock
+ let ph = fmod(T, 4), clock = ph > 1.2 && ph < 2.6
+ var o = base(px0); o.legs = Int(floor(T * 2.2)) % 2 != 0 ? .stepR : .stand; o.dy = 0
+ o.eyeMode = clock ? .up : blinkAt(t) ? .closed : .squint; o.look = 1
+ paint(ctx, o)
+ // the hourglass: 5 x 7 pixels, sand running down, turned over every 3 s
+ let hp = max(2, jsRound(px0 * 0.55)), hx = o.ox + (Wd + 1) * px0, hy = o.oy + 2 * px0
+ let run = fmod(T, 3) / 3, flip = fmod(T, 3) > 2.8
+ let GL = ["XXXXX", ".X.X.", "..X..", "..X..", ".X.X.", "X...X", "XXXXX"]
+ ctx.save(); if flip { ctx.translate(hx + 2.5 * hp, hy + 3.5 * hp); ctx.rotate(Double.pi / 2); ctx.translate(-(hx + 2.5 * hp), -(hy + 3.5 * hp)) }
+ ctx.fill = RGBA(hex: 0xC9CDD2)
+ for (j, r) in GL.enumerated() { for (i, ch) in r.enumerated() where ch == "X" { ctx.fillRect(hx + Double(i) * hp, hy + Double(j) * hp, hp, hp) } }
+ ctx.fill = RGBA(hex: 0xFFD23F)
+ let topN = jsRound((1 - run) * 3), botN = jsRound(run * 3)
+ if topN > 0 { ctx.fillRect(hx + hp, hy + hp, 3 * hp, hp * min(1, topN)) }
+ if topN > 1 { ctx.fillRect(hx + 2 * hp, hy + 2 * hp, hp, hp) }
+ if Int(floor(T * 6)) % 2 != 0 { ctx.fillRect(hx + 2 * hp, hy + 3 * hp, hp, hp) }
+ if botN > 0 { ctx.fillRect(hx + hp, hy + 5 * hp, 3 * hp, hp) }
+ if botN > 1 { ctx.fillRect(hx + 2 * hp, hy + 4 * hp, hp, hp) }
+ ctx.restore()
+ let left = max(0, 33 * 60 - 1 - Int(floor(T))), mm = String(format: "%02d", left / 60), ss = String(format: "%02d", left % 60)
+ text(ctx, "BACK IN \(mm):\(ss)", sx + sw / 2, o.oy + Hd * px0 + 10, 2, RGBA(hex: 0x9AA1AA), .center)
+
+ case .sleep:
+ let px = 4.0, swd = Wd * px, shd = Hd * px, m = 6.0, rx = sw - 2 * m - swd, ry = sh - 2 * m - shd
+ let vx = rx / 2.5, vy = ry / 3.75, TT = T + 1.2 // first corner hit at T = 6.3 s
+ func tri(_ d: Double, _ r: Double) -> (Double, Int) { let n = Int(floor(d / r)), f = d - Double(n) * r; return (n % 2 != 0 ? r - f : f, n) }
+ let (x, nx) = tri(TT * vx, rx), (y, ny) = tri(TT * vy, ry)
+ var corner: [Double] = []; for k in 1..<8 { let tc = 7.5 * Double(k) - 1.2; if T >= tc && T - tc < 1.6 { corner.append(T - tc) } }
+ var o = Sprite(sp: sp, ox: jsRound(sx + m + x), oy: jsRound(sy + m + y), px: px, mood: sp.cycle[(nx + ny) % sp.cycle.count])
+ o.eyeMode = !corner.isEmpty && corner[0] < 0.9 ? .cam : .closed; o.stem = .droop; o.boost = -0.06
+ paint(ctx, o)
+ if !corner.isEmpty { // it hit the corner. Everyone has waited years for this.
+ let a = corner[0]
+ for i in 0..<26 {
+ let fi = Double(i), ang = hash(fi, 3, 1) * Double.pi * 2, spd = 30 + hash(fi, 9, 2) * 70, r0 = 22.0
+ let gx = o.ox + swd / 2 + cos(ang) * (r0 + spd * a), gy = o.oy + shd / 2 + sin(ang) * (r0 + spd * a) + 40 * a * a
+ ctx.fill = css(grad(LAB[sp.cycle[i % sp.cycle.count].rawValue], 0.3)); ctx.fillRect(jsRound(gx), jsRound(gy), 4, 4)
+ }
+ text(ctx, "CORNER!", sx + sw / 2, sy + sh / 2 - 6, 3, Int(floor(a * 8)) % 2 != 0 ? WHITE : RGBA(hex: 0xFFE66B), .center)
+ } else {
+ let zt = fmod(T, 1.4)
+ ctx.alpha = 1 - zt / 1.4; text(ctx, "z", o.ox + swd - 2, o.oy - 4 - step(zt / 1.4, 6) * 16, 2, WHITE); ctx.alpha = 1
+ }
+
+ case .subagents:
+ let n = max(1, min(5, p.subagents ?? 3)), all = n + 1, c = T, o = base(px0)
+ if c < 0.5 {
+ let jit: Double = Int(floor(c * 24)) % 2 != 0 ? 1 : -1
+ var q = o; q.ox = o.ox + (c > 0.2 ? jit : 0); q.eyeMode = c > 0.2 ? .cam : .side; q.look = 1; paint(ctx, q)
+ } else {
+ let k = ease((c - 0.5) / 0.45), gap = (sw - 16) / Double(all), mpx = max(2, min(4, floor(gap / Double(sp.visW + 1))))
+ for i in 0..<all {
+ let fi = Double(i)
+ let qx = o.ox + (Double(i % 2) + 0.5) * Wd * px0 / 2, qy = o.oy + (Double((i / 2) % 2) + 0.5) * Hd * px0 / 2
+ let fx = sx + sw / 2 + (fi - Double(all - 1) / 2) * gap, fy = p.cy + 16
+ let cx = jsRound(qx + (fx - qx) * k), cy = jsRound(qy + (fy - qy) * k)
+ let walk = Int(floor(c * 5 + fi * 0.5)) % 2
+ var q = base(mpx, cx, cy); q.mood = sp.cycle[i % sp.cycle.count]
+ q.legs = k >= 1 ? (walk != 0 ? .stepL : .stepR) : .stand; q.dy = k >= 1 ? Double(walk) : 0
+ q.eyeMode = blinkAt(t, fi) ? .closed : .side; q.look = i == 0 ? 1 : -1
+ paint(ctx, q)
+ }
+ if k >= 1 { text(ctx, "X\(all)", sx + sw / 2, p.cy - 36, 2, RGBA(hex: 0xFFE66B), .center) }
+ }
+ }
+ }
+}
+
diff --git a/app/ChumsWatch/Rig/PixStage.swift b/app/ChumsWatch/Rig/PixStage.swift
new file mode 100644
index 0000000..d30c1fd
--- /dev/null
+++ b/app/ChumsWatch/Rig/PixStage.swift
@@ -0,0 +1,143 @@
+import SwiftUI
+
+/// Pix on the watch. The per-character runtime of the Character Lab's `pixChar` (the HTML prototype, not in the public
+/// repository): the poke hop, the
+/// reactions (a failed tool call glitches it, an interruption freezes the frame), the positions per state, and the
+/// offscreen bitmap it is drawn into. Pix stages every state itself: it draws its own full screen (no world), and
+/// the status label row goes on top of it.
+///
+/// let stage = PixStage(species: .apple)
+/// // each frame, inside the Canvas:
+/// stage.step(dt)
+/// stage.draw(ctx, size: size, scale: 2, PixStage.Scene(state: .working, stateT: rig.stateT, t: rig.t, tools: ["Read", "Edit"]))
+/// // on a tap / a hook event:
+/// stage.poke() // a hop, eyes on you, for 0.45 s
+/// stage.react(.fail, t: rig.t, stateT: rig.stateT) // glitch bands for 0.5 s
+/// stage.react(.interrupt, t: rig.t, stateT: rig.stateT) // the frame freezes for 0.7 s
+final class PixStage {
+ enum Reaction { case fail, interrupt }
+
+ /// What the character is told about the session, each frame.
+ struct Scene {
+ var state: Pix.State = .idle
+ var approval = false // the approval card is up: small, above it, as `needs` without the !
+ var stateT = 0.0, t = 0.0
+ var voice = 0.0 // listening: microphone level 0…1
+ var caption = "" // speaking: the reply being typed out
+ var tools: [String] = [] // working: recent tool names, oldest first (READ, EDIT, BASH …)
+ var subagents = 3
+ var ao = false // always on: half brightness
+ var free: CGPoint? = nil // physics / launch: where the body is; nil = Pix's own positions
+ var thumb = false // a settings thumbnail: no poke, no reaction, no bookkeeping
+ var ripe: Int? = nil // the crown's ripeness step (Pix.RIPENESS), nil = the state's own colours
+ var look: Double? = nil // a finger on the screen: −1 it's to the left, 1 to the right
+ var petted = false // stroked: a happy squint
+ init() {}
+ init(state: Pix.State, stateT: Double, t: Double) { self.state = state; self.stateT = stateT; self.t = t }
+ }
+
+ var species: Pix.Species
+ /// Where the body is, in design points, for hit tests.
+ private(set) var at = CGPoint(x: 99, y: 118)
+ private var pokeT = 9.0 // seconds since the last poke
+ private var re: (kind: Reaction, t: Double, at: (Double, Double))?
+ private var rasters: [Pix.Raster] = []
+ private var which = 0
+ private static let pokeable: Set<Pix.State> = [.idle, .thinking, .working, .needs, .listening]
+ private static let screen = CGRect(x: 0, y: 36, width: 198, height: 206)
+
+ init(species: Pix.Species) { self.species = species }
+
+ func poke() { pokeT = 0 }
+ /// A failed tool call glitches it; an interruption freezes it like a paused frame. `t` and `stateT` are the
+ /// rig's clocks at that moment (the frozen frame keeps showing them).
+ func react(_ kind: Reaction, t: Double, stateT: Double) { re = (kind, 0, (t, stateT)) }
+ func step(_ dt: Double) {
+ pokeT += dt
+ if re != nil { re!.t += dt; if re!.t > 1.2 { re = nil } }
+ }
+ /// The Lab's hit box: the apple is 53 pt wide and 60 pt up and down from `at`; the banana 45 and 69.
+ func hit(_ pt: CGPoint) -> Bool {
+ let (hx, top, bottom) = species == .apple ? (53.0, 60.0, 60.0) : (45.0, 69.0, 69.0)
+ return abs(pt.x - at.x) < hx + 6 && pt.y > at.y - top - 6 && pt.y < at.y + bottom + 6
+ }
+ /// waiting: when it looks up at the clock (the Lab's clockLook), for anything that wants to play along.
+ static func clockLook(_ stateT: Double) -> Bool { let p = stateT.truncatingRemainder(dividingBy: 4); return p > 1.2 && p < 2.6 }
+
+ /// Pix's inputs for this frame, as pixChar builds them.
+ private func params(_ s: Scene) -> (Pix.Params, cy: Double) {
+ let free = !s.thumb && s.free != nil
+ let cx = free ? Double(s.free!.x) : 99
+ var cy = free ? Double(s.free!.y) : 118, px = 7.0
+ if !free && s.state == .needs { cy = 146 } // room above the head for the !
+ if !free && s.state == .working { cy = 134 } // room above it for the tool calls rising
+ let approval = !free && s.approval
+ if approval { cy = 80; px = 3 } // small, above the card; the card is the request, so no !
+ let poking = !s.thumb && pokeT < 0.45 && Self.pokeable.contains(s.state)
+ let hop = poking ? Pix.jsRound(sin(pokeT / 0.45 * Double.pi) * 8) : 0
+ if !s.thumb { at = CGPoint(x: cx, y: cy - hop) }
+ let frozen = !s.thumb && re?.kind == .interrupt && re!.t < 0.7
+ var p = Pix.Params()
+ p.species = species; p.cx = cx; p.cy = cy - hop; p.px = px
+ p.t = frozen ? re!.at.0 : s.t
+ p.state = poking ? .idle : approval ? .needs : s.state
+ p.stateT = frozen ? re!.at.1 : s.stateT
+ p.voice = s.voice
+ p.text = s.caption.isEmpty ? nil : s.caption
+ p.tools = s.tools
+ p.subagents = s.subagents
+ p.screen = Self.screen
+ p.room = approval ? 60 : 150
+ p.bang = !approval
+ p.eyeMode = poking || (re?.kind == .fail && re!.t < 0.5) ? .cam : nil
+ if let k = s.ripe, k >= 0, k < Pix.RIPENESS.count {
+ p.ripe = Pix.RIPENESS[k]
+ // green it's alert, ripe it's pleased, overripe it's had enough
+ if p.eyeMode == nil { p.eyeMode = [Pix.EyeMode.cam, .cam, nil, nil, .happy, .happy, .squint][k] }
+ }
+ if s.petted { p.eyeMode = .happy }
+ if let l = s.look, !s.petted { p.look = l; if p.eyeMode == nil && p.state == .idle { p.eyeMode = .side } }
+ return (p, cy)
+ }
+
+ /// Render the frame into `r` with the design space mapped by `m` (design pt → pixels).
+ func render(_ s: Scene, into r: Pix.Raster, transform m: Pix.Matrix) {
+ let (p, cy) = params(s)
+ r.fill(Pix.RGBA(0, 0, 0))
+ let g = Pix.G(r); g.m = m
+ Pix.draw(g, p)
+ // glitch: three bands of rows tear sideways for half a second
+ if !s.thumb, let re, re.kind == .fail, re.t < 0.5 {
+ let seed = Int(floor(re.t * 20))
+ for i in 0..<3 {
+ let y0 = cy - 60 + Double((seed * 37 + i * 53) % 110), h = Double(6 + ((seed + i) % 3) * 5), dx = Double(((seed + i) % 2 != 0 ? 1 : -1) * (5 + i * 3))
+ g.save(); g.clipRect(0, y0, 198, h); g.fill = Pix.RGBA(0, 0, 0); g.fillRect(0, y0, 198, h)
+ g.translate(dx, 0); Pix.draw(g, p); g.restore()
+ }
+ }
+ if s.ao { Self.alwaysOn(r) }
+ }
+
+ /// Dimmed (always on): its own colors at half brightness.
+ static func alwaysOn(_ r: Pix.Raster) {
+ var i = 0
+ for _ in 0..<(r.w * r.h) {
+ let p = r.data + i
+ p[0] >>= 1; p[1] >>= 1; p[2] >>= 1
+ i += 4
+ }
+ }
+
+ /// Draw into a SwiftUI canvas of `size` points on a screen with `scale` pixels per point: the 198 × 242 design
+ /// space is fitted and centred like Renderer.fit, rendered at the screen's pixels, and shown 1:1.
+ func draw(_ ctx: GraphicsContext, size: CGSize, scale: Double, _ s: Scene) {
+ let pw = max(1, Int((size.width * scale).rounded())), ph = max(1, Int((size.height * scale).rounded()))
+ if rasters.count != 2 || rasters[0].w != pw || rasters[0].h != ph { rasters = [Pix.Raster(w: pw, h: ph), Pix.Raster(w: pw, h: ph)] }
+ which = (which + 1) % 2 // double buffered: the canvas may still read the last one
+ let r = rasters[which]
+ let fit = min(size.width / 198, size.height / 242), ox = (size.width - 198 * fit) / 2, oy = (size.height - 242 * fit) / 2
+ render(s, into: r, transform: Pix.Matrix(a: fit * scale, b: 0, c: 0, d: fit * scale, e: ox * scale, f: oy * scale))
+ guard let img = r.image() else { return }
+ ctx.draw(Image(decorative: img, scale: 1).resizable().interpolation(.none), in: CGRect(origin: .zero, size: size))
+ }
+}
diff --git a/app/ChumsWatch/Rig/PixStaged.swift b/app/ChumsWatch/Rig/PixStaged.swift
new file mode 100644
index 0000000..9779349
--- /dev/null
+++ b/app/ChumsWatch/Rig/PixStaged.swift
@@ -0,0 +1,68 @@
+import SwiftUI
+
+/// Pix (apple or banana) as a staged character: the rig's state, time, voice and caption go into PixStage, which
+/// renders design/pix/pix.js's frames at the screen's own pixels. Pix types replies out in its own dialog box, so it
+/// keeps the caption while speaking; the shared approval card is drawn over it (Pix shrinks above it).
+final class PixStaged: Staged {
+ static let apple = PixStaged(.apple), banana = PixStaged(.banana)
+ private let stage: PixStage
+ private var tools: [String] = [] // the latest tool names (READ, EDIT, BASH …), oldest first
+ private var ripe: Int?, ripeAcc = 0.0, crownIdle = 9.0, unripenT = 0.0 // the crown's ripeness, and its way back
+ private var finger: CGPoint?, petT = 0.0
+ private init(_ species: Pix.Species) { stage = PixStage(species: species) }
+
+ let ownsApproval = false
+ let holds: [ChumsState: Double] = [.done: 3.3]
+ func captionTop(_ r: Rig) -> Bool { false }
+ func ownsCaption(_ r: Rig) -> Bool { r.state == .speaking }
+ func onState(_ r: Rig, _ s: ChumsState, prev: ChumsState?, variant: Bool) {}
+
+ func step(_ r: Rig, _ dt: Double) {
+ stage.step(dt)
+ // a few seconds after the crown stops, it goes back to yellow a step at a time, then to its state's colours
+ crownIdle += dt; petT = max(0, petT - dt)
+ if let k = ripe, crownIdle > 3 {
+ unripenT -= dt
+ if unripenT <= 0 { unripenT = 0.32; ripe = k == 2 ? nil : k + (k < 2 ? 1 : -1) }
+ }
+ // tool calls float up as "+1 READ": take them as they arrive (the level world isn't running to take them)
+ while !r.worlds.queue.isEmpty {
+ let c = r.worlds.queue.removeFirst()
+ tools.append(String(c.text.split(separator: " ").first ?? "TOOL").uppercased())
+ if tools.count > 6 { tools.removeFirst() }
+ }
+ }
+
+ func draw(_ r: Rig, _ ctx: GraphicsContext) {
+ var s = PixStage.Scene(state: Pix.State(rawValue: r.state.rawValue) ?? .idle, stateT: r.stateT, t: r.t)
+ s.approval = r.state == .approval
+ s.voice = r.voice
+ s.caption = r.state == .speaking ? r.caption : ""
+ s.tools = tools.isEmpty ? ["READ", "EDIT", "BASH"] : tools
+ s.ao = r.ao
+ s.ripe = ripe
+ s.petted = petT > 0
+ if let f = finger { s.look = Double(f.x) < 99 ? -1 : 1 }
+ stage.draw(ctx, size: CGSize(width: 198, height: 242), scale: r.pixelScale, s)
+ }
+
+ func front(_ r: Rig, _ ctx: GraphicsContext) {}
+ func hit(_ pt: CGPoint) -> Bool { stage.hit(pt) }
+ func poke(_ r: Rig) { stage.poke() }
+ func touched(_ r: Rig, at pt: CGPoint) { finger = pt }
+ func dragged(_ r: Rig, at pt: CGPoint) { finger = pt }
+ func released(_ r: Rig) { finger = nil }
+ /// The crown ripens it (and back): a step every detent or so, a click at each.
+ func crown(_ r: Rig, _ delta: Double) {
+ if ripe == nil { ripe = 2 }
+ ripeAcc += delta; crownIdle = 0; unripenT = 0.6
+ while abs(ripeAcc) >= 1.1 {
+ let up = ripeAcc > 0; ripeAcc += up ? -1.1 : 1.1
+ let next = clamp(Double(ripe! + (up ? 1 : -1)), 0, Double(Pix.RIPENESS.count - 1))
+ if Int(next) != ripe { ripe = Int(next); r.onHaptic?(.click) } else { ripeAcc = 0 }
+ }
+ }
+ func motion(_ r: Rig, _ ax: Double, _ ay: Double, _ az: Double) {}
+ func pet(_ r: Rig) { petT = 0.8 }
+ func deny(_ r: Rig) {}
+}
diff --git a/app/ChumsWatch/Rig/RayStage.swift b/app/ChumsWatch/Rig/RayStage.swift
new file mode 100644
index 0000000..32ce0c8
--- /dev/null
+++ b/app/ChumsWatch/Rig/RayStage.swift
@@ -0,0 +1,626 @@
+import SwiftUI
+
+/// Ray: a flat golden sun with ten long wavy arms, traced one to one from its character sheet (design/characters, the
+/// squiggly sun): a small round middle, each arm its own S-curve, wide where it leaves the middle, narrowing to a slightly
+/// pointed round tip. Big cream eyes close together, black pupils and a black mouth, every face taken from the sheet.
+/// The arms are never still: a slow wave runs out along each one, its own phase, and the mood changes their shape (the
+/// sheet's jagged angry arms, its melting asleep arms, its pinwheel dizzy arms) and how fast they move.
+/// idle: ● ● ‿, a slow wave · listening: the surprised face, its O opening with your voice · thinking: tilted, eyes up
+/// and to the right, a small o, a ? · working: turning, eyes reading, an arm reaching out at each tool call ·
+/// subagents: three small suns going round it · speaking: its mouth opens with its voice · done: ◠ ◠ D, a hop, the arms
+/// shake and the sheet's motion strokes fly round it · needs you: the sad face, a knock · blocked: angry, the jagged
+/// arms, brows, a zigzag mouth · dizzy: spirals, a wavy mouth, the pinwheel arms · sleep: the arms melt down, — — and a
+/// small yawn that breathes
+/// tap: a wink with its tongue out, the arms snap in · poke it often: angry for a moment · drag: it follows your finger,
+/// the arms trailing · pet: ◠ ◠ ‿, the arms go slow · crown: it turns, the arms trailing; turned fast it gets dizzy ·
+/// shake: the arms flop about
+final class RayStage: Staged {
+ static let shared = RayStage()
+
+ let ownsApproval = false
+ let holds: [ChumsState: Double] = [.done: 2.6, .dizzy: 3.4]
+ func captionTop(_ r: Rig) -> Bool { false }
+ func ownsCaption(_ r: Rig) -> Bool { false }
+ var calm: Bool { t - busyAt > 1.2 }
+
+ // the sheet's colours
+ static let yellow = Color(red: 242 / 255, green: 174 / 255, blue: 8 / 255)
+ static let cream = Color(red: 249 / 255, green: 236 / 255, blue: 205 / 255)
+ static let ink = Color(red: 4 / 255, green: 2 / 255, blue: 1 / 255)
+ static let pink = Color(red: 230 / 255, green: 78 / 255, blue: 75 / 255)
+
+ /// The middle's radius in pt. Everything in SolArt is in these units, centred on the middle.
+ static let RC = 37.0
+ private static let K = SolArt.K
+
+ // MARK: how the arms move, per state
+
+ private struct Body {
+ var amp = 0.24, speed = 1.5, len = 0.0, turn = 0.0, tilt = 0.0
+ var shape = SIMD4<Double>(1, 0, 0, 0) // base, angry, melt, dizzy
+ // how the arms hold themselves: lifted toward you, curled one way, hanging down, shivering, the top ones waving
+ var up = 0.0, curl = 0.0, droop = 0.0, shiver = 0.0, wave = 0.0
+ }
+ private func body(_ s: ChumsState) -> Body {
+ switch s {
+ case .idle: return Body()
+ case .listening: return Body(amp: 0.2, speed: 2.4, len: 0.05, up: 0.4)
+ case .thinking: return Body(amp: 0.14, speed: 0.9, tilt: -9 * DEG, curl: 0.5)
+ case .working: return Body(amp: 0.42, speed: 4.2, turn: 0.45, curl: -0.3)
+ case .subagents: return Body(amp: 0.3, speed: 2)
+ case .speaking: return Body(amp: 0.26, speed: 2.2)
+ case .done: return Body(amp: 0.36, speed: 2.4, len: 0.03, up: 0.25)
+ case .needs: return Body(amp: 0.18, speed: 1.3, up: 0.15, wave: 1)
+ case .approval: return Body(amp: 0.22, speed: 1.6, droop: 0.4)
+ case .blocked: return Body(amp: 0.08, speed: 1.2, shape: SIMD4(0, 1, 0, 0), shiver: 1)
+ case .dizzy: return Body(amp: 0.3, speed: 2.6, shape: SIMD4(0, 0, 0, 1))
+ case .sleep: return Body(amp: 0.12, speed: 0.6, shape: SIMD4(0, 0, 1, 0), droop: 0.2)
+ }
+ }
+
+ // MARK: faces (every part a shape from the sheet; "" is none)
+
+ private struct Face {
+ var wl = "wSurL", wr = "wSurR", ll = "", lr = "", bl = "", br = "", mouth = "smile", tongue = ""
+ var pl = "pNeuL", pr = "pNeuR"
+ var look = 1.0 // how much the pupils follow the gaze
+ var spirals = false, question = false
+ var clip = true // pupils kept inside the whites (the wink's sits over the edge)
+ }
+ private func face(_ s: ChumsState) -> Face {
+ switch s {
+ case .idle, .subagents, .speaking: return Face()
+ case .listening: return Face(mouth: "O", pl: "pSurL", pr: "pSurR", look: 0.6)
+ case .thinking: return Face(wl: "wThkL", wr: "wThkR", mouth: "dot", pl: "pThkL", pr: "pThkR", look: 0, question: true)
+ case .working: return Face(mouth: "flat")
+ case .done: return Face(wl: "", wr: "", ll: "happyL", lr: "happyR", mouth: "D")
+ case .needs: return Face(wl: "wSadL", wr: "wSadR", mouth: "frown", pl: "pSadL", pr: "pSadR", look: 0.4)
+ case .approval: return Face(mouth: "dotC")
+ case .blocked: return Face(wl: "wAngL", wr: "wAngR", bl: "browL", br: "browR", mouth: "zig", pl: "pAngL", pr: "pAngR", look: 0)
+ case .dizzy: return Face(wl: "", wr: "", mouth: "wavy", spirals: true)
+ case .sleep: return Face(wl: "", wr: "", ll: "dashL", lr: "dashR", mouth: "yawn")
+ }
+ }
+ private static let wink = Face(wl: "wWinkL", wr: "", lr: "winkR", mouth: "winkMouth", tongue: "tongue", pl: "pWinkL", pr: "pWinkL", look: 0, clip: false)
+ private static let content = Face(wl: "", wr: "", ll: "happyL", lr: "happyR", mouth: "smile")
+ private static let startled = Face(mouth: "O", pl: "pSurL", pr: "pSurR", look: 0)
+ private static let cross = Face(wl: "wAngL", wr: "wAngR", bl: "browL", br: "browR", mouth: "zig", pl: "pAngL", pr: "pAngR", look: 0)
+
+ // MARK: the parts
+
+ /// A face part: its outline blends from one shape into the next on a spring (all of them 64 points, leftmost first,
+ /// clockwise, so any two blend), or shrinks to nothing and grows back.
+ private struct Part {
+ var from: [P2], to: [P2], b = 1.0, bv = 0.0, name = "", none = true
+ var shape: [P2] { b >= 1 ? to : Strokes.mix(from, to, b) }
+ var shown: Bool { !(none && b > 0.98) }
+ mutating func set(_ n: String) {
+ guard n != name else { return }
+ let cur = shape
+ if n.isEmpty {
+ let c = RayStage.centroid(cur); from = cur; to = [P2](repeating: c, count: cur.count); none = true
+ } else {
+ let g = SolArt.glyph(n)
+ from = none && b > 0.98 ? [P2](repeating: RayStage.centroid(g), count: g.count) : cur
+ to = g; none = false
+ }
+ name = n; b = 0; bv = 0
+ }
+ }
+ private static func centroid(_ p: [P2]) -> P2 { p.reduce(P2.zero, +) / Double(max(1, p.count)) }
+ private static let empty = [P2](repeating: .zero, count: SolArt.N)
+ // whites L R, closed-eye lines L R, brows L R, mouth, tongue
+ private var parts: [Part] = (0..<8).map { _ in Part(from: RayStage.empty, to: RayStage.empty) }
+ private var pupils: [SIMD4<Double>] = [SolArt.pupil("pNeuL"), SolArt.pupil("pNeuR")] // cx cy rx ry
+ private var look = 1.0
+ private var spiralsK = 0.0, questionK = 0.0
+ /// Where the thinking dots sit: the middle of the sheet's question mark (up and to the right).
+ private static let thinkAt: P2 = { let g = SolArt.glyph("qHook") + SolArt.glyph("qDot"); return g.reduce(P2.zero, +) / Double(max(1, g.count)) }()
+ private var shown = Face(), shownKey = "", faceStarted = false
+
+ // MARK: state
+
+ private struct Arm { var phase, gain: Double; var flop = 0.0, fv = 0.0, len = 0.0, lv = 0.0, grab = 0.0 }
+ private var arms: [Arm] = (0..<10).map { (i: Int) -> Arm in
+ let x = Double(i)
+ let ph: Double = x * 2.399 + 0.7 * sin(x * 1.7)
+ let gn: Double = 0.82 + 0.18 * (1 + sin(x * 2.9 + 1))
+ return Arm(phase: ph, gain: gn)
+ }
+ private var cur = Body()
+ private var shapeV = SIMD4<Double>(0, 0, 0, 0)
+ private var blend: [Double] = SolArt.base, blendKey = SIMD4<Double>(1, 0, 0, 0)
+ private var state: ChumsState = .idle
+ private var t = 0.0, busyAt = 0.0
+ private var wavePhase = 0.0, turn = 0.0, spinV = 0.0, crownIdle = 9.0, fastFor = 0.0
+ private var squash = (k: 0.0, v: 0.0), hop = (y: 0.0, v: 0.0), bump = 0.0
+ private var center = P2(99, 128), cv = P2.zero, fingerOff = P2.zero, dragV = P2.zero
+ private var finger: CGPoint?
+ private var trauma = 0.0, knock = 0.0, nextTool = 0.8, toolFlash = 0.0
+ private var winkT = 0.0, crossT = 0.0, petT = 0.0, startT = 0.0, pokes: [Double] = []
+ private var minis = 0.0
+ private var scale = 1.0, scaleV = 0.0
+ private var tilt = 0.0
+
+ // MARK: Staged
+
+ func onState(_ r: Rig, _ s: ChumsState, prev: ChumsState?, variant: Bool) {
+ state = s
+ // every change: a little gather first (the arms draw in, it squashes), then it springs into the new state
+ if prev != s && prev != nil {
+ for i in arms.indices { arms[i].lv -= 1.5; arms[i].fv += Double(i % 2 == 0 ? 1 : -1) * 0.8 }
+ squash.v -= 1.4
+ }
+ switch s {
+ case .done:
+ hop.v = -240; squash.v += 3
+ for i in arms.indices { arms[i].fv += rnd(-5, 5) }
+ case .listening: squash.v += 2
+ case .needs: knock = 0
+ case .blocked: squash.v -= 2
+ default: break
+ }
+ busyAt = t
+ }
+
+ func step(_ r: Rig, _ dt0: Double) {
+ let dt = min(dt0, 0.05)
+ t += dt
+ guard !r.ao else {
+ // dimmed: drawn about once a second, so nothing in flight; it rests in its state's pose
+ winkT = 0; crossT = 0; startT = 0; petT = 0; trauma = 0; spinV = 0; hop = (0, 0); squash = (0, 0); bump = 0
+ for i in arms.indices { arms[i].flop = 0; arms[i].fv = 0; arms[i].len = 0; arms[i].lv = 0; arms[i].grab = 0 }
+ return
+ }
+ var target = body(state)
+ // the voice, done's shake, being petted, poked too often
+ if state == .listening { target.len += r.voice * 0.12; target.amp += r.voice * 0.25 }
+ if state == .speaking { target.amp += r.voice * 0.3; target.len += r.voice * 0.08 }
+ if state == .done && r.stateT < 1.5 { let k = 1 - r.stateT / 1.5; target.amp += 0.3 * k; target.speed += 9 * k }
+ if petT > 0 { target.amp *= 0.6; target.speed *= 0.5 }
+ if crossT > 0 { target.shape = SIMD4(0.45, 0.55, 0, 0); target.amp = 0.1 }
+ if startT > 0 { target.shape = SIMD4(0.75, 0, 0.25, 0); target.amp = 0.3; target.speed = 3 }
+ let e = min(1, dt * 3.5)
+ cur.amp += (target.amp - cur.amp) * e; cur.speed += (target.speed - cur.speed) * e
+ cur.len += (target.len - cur.len) * e; cur.turn += (target.turn - cur.turn) * min(1, dt * 1.5)
+ cur.up += (target.up - cur.up) * e; cur.curl += (target.curl - cur.curl) * e; cur.droop += (target.droop - cur.droop) * e
+ cur.shiver += (target.shiver - cur.shiver) * e; cur.wave += (target.wave - cur.wave) * e
+ tilt += (target.tilt + (state == .dizzy ? sin(t * 2.2) * 0.12 : 0) - tilt) * min(1, dt * 4)
+ wavePhase += cur.speed * dt
+ // the arms' shape: the sheet's shapes, on a spring (melting takes its time)
+ let ws = TAU * (state == .sleep ? 0.9 : 1.6)
+ let acc: SIMD4<Double> = (target.shape - cur.shape) * (ws * ws) - shapeV * (2 * 0.62 * ws)
+ shapeV += acc * dt; cur.shape += shapeV * dt
+ // the crown turns it (and the state's own slow turn); fast for a second, dizzy
+ crownIdle += dt
+ spinV *= exp(-dt * 1.3)
+ turn += (cur.turn + spinV) * dt
+ // done turning: it comes back round to the sheet's pose (the nearest whole turn)
+ if target.turn == 0 && abs(spinV) < 0.8 {
+ let home = (turn / TAU).rounded() * TAU
+ turn += (home - turn) * min(1, dt * (abs(spinV) < 0.2 ? 1.6 : 0.6))
+ }
+ if abs(spinV) > 9 && crownIdle < 0.2 && state != .dizzy { fastFor += dt } else { fastFor = 0 }
+ if fastFor > 1 { fastFor = 0; r.setState(.dizzy) }
+ trauma = max(0, trauma - dt * 0.75)
+ winkT = max(0, winkT - dt); crossT = max(0, crossT - dt); petT = max(0, petT - dt); startT = max(0, startT - dt)
+ toolFlash = max(0, toolFlash - dt)
+ // each arm: a flop (a shake, a turn, a drag pulls it behind), its length (a tap snaps them in, a tool call reaches)
+ for i in arms.indices {
+ let wf = TAU * (1.9 + Double(i % 3) * 0.25)
+ arms[i].fv += (-wf * wf * arms[i].flop - 2 * 0.16 * wf * arms[i].fv + trauma * rnd(-1, 1) * 160) * dt
+ arms[i].flop = clamp(arms[i].flop + arms[i].fv * dt, -2.2, 2.2)
+ let wl = TAU * 2.6
+ arms[i].lv += (-wl * wl * arms[i].len - 2 * 0.3 * wl * arms[i].lv) * dt
+ arms[i].len = clamp(arms[i].len + arms[i].lv * dt, -0.6, 0.6)
+ arms[i].grab = max(0, arms[i].grab - dt * 1.8)
+ }
+ let wsq = TAU * 3
+ squash.v += (-wsq * wsq * squash.k - 2 * 0.22 * wsq * squash.v) * dt; squash.k = clamp(squash.k + squash.v * dt, -0.25, 0.25)
+ hop.v += 1000 * dt; hop.y += hop.v * dt
+ if hop.y > 0 { if hop.v > 100 { squash.v -= hop.v / 160 }; hop.y = 0; hop.v = 0 }
+ bump = max(0, bump - dt * 3)
+ // where it is: home, a finger pulling it
+ var home = P2(99, state == .approval ? 74 : state == .listening ? 140 : state == .sleep ? 134 : 128)
+ // a finger pulls it toward itself: eased in and out, so letting go never jerks it
+ let fo: P2 = finger.map { P2(clamp(($0.x - 99) * 0.35, -30, 30), clamp(($0.y - 128) * 0.3, -26, 26)) } ?? .zero
+ fingerOff += (fo - fingerOff) * min(1, dt * 6); home += fingerOff
+ let wc = TAU * 2.2
+ let pull: P2 = (home - center) * (wc * wc), damp: P2 = cv * (wc * 1.1)
+ cv += (pull - damp) * dt; center += cv * dt
+ dragV += (cv - dragV) * min(1, dt * 7)
+ // the work: each tool call, the arm at the top reaches out and the eyes glance up at it
+ nextTool -= dt
+ if nextTool <= 0 && (!r.worlds.queue.isEmpty || state == .working), let c = r.worlds.nextEvent(r) {
+ nextTool = r.worlds.queue.isEmpty ? rnd(1.4, 2.4) : 0.5
+ if c.kind != .stop, let i = arms.indices.min(by: { armOff($0, -Double.pi / 2) < armOff($1, -Double.pi / 2) }) {
+ arms[i].grab = 1; arms[i].lv += 3; toolFlash = 0.5
+ }
+ }
+ // needs you: a knock every few seconds
+ if state == .needs {
+ let was = knock; knock += dt; if knock >= 3.2 { knock = 0 }
+ if was < 0.2 && knock >= 0.2 { bump = 1; squash.v += 2.5; r.onHaptic?(.strong) }
+ }
+ minis += ((state == .subagents ? 1 : 0) - minis) * min(1, dt * 3)
+ // small for an approval: eased there and back (with a little overshoot)
+ let wsc = TAU * 2.2, sgoal = state == .approval ? 0.5 : state == .subagents ? 0.8 : 1.0
+ scaleV += (wsc * wsc * (sgoal - scale) - 2 * 0.7 * wsc * scaleV) * dt; scale += scaleV * dt
+ stepFace(r, dt)
+ let moving = finger != nil || abs(spinV) > 0.1 || trauma > 0.01 || hop.v != 0 || abs(squash.v) > 0.05 || simd_length(cv) > 2
+ || winkT > 0 || crossT > 0 || petT > 0 || startT > 0 || minis > 0.02 || parts.contains { abs($0.bv) > 0.05 }
+ || simd_length(shapeV) > 0.02 || !(state == .idle || state == .sleep || state == .needs || state == .approval || state == .thinking)
+ if moving { busyAt = t }
+ }
+ private func armOff(_ i: Int, _ a: Double) -> Double { abs(remainder(SolArt.armAngle[i] + turn + tilt - a, TAU)) }
+
+ private func stepFace(_ r: Rig, _ dt: Double) {
+ var f = face(state)
+ if state == .done && r.stateT > 1.8 { f = Self.content }
+ if petT > 0 && state != .sleep && state != .dizzy { f = Self.content }
+ if trauma > 0.12 && state != .dizzy { f = Self.startled } // shaken: whoa
+ if startT > 0 { f = Self.startled }
+ if winkT > 0 { f = Self.wink }
+ if crossT > 0 { f = Self.cross }
+ shown = f
+ let names = [f.wl, f.wr, f.ll, f.lr, f.bl, f.br, f.mouth, f.tongue]
+ for i in 0..<8 {
+ parts[i].set(names[i])
+ if !faceStarted { parts[i].b = 1; parts[i].from = parts[i].to }
+ }
+ if !faceStarted { for k in 0..<2 { pupils[k] = [SolArt.pupil(f.pl), SolArt.pupil(f.pr)][k] }; look = f.look }
+ faceStarted = true
+ for i in 0..<8 {
+ let w = TAU * 4.2
+ parts[i].bv += (-w * w * (parts[i].b - 1) - 2 * 0.66 * w * parts[i].bv) * dt
+ parts[i].b += parts[i].bv * dt
+ }
+ let e = min(1, dt * 12)
+ let pt: [SIMD4<Double>] = [SolArt.pupil(f.pl), SolArt.pupil(f.pr)]
+ for i in 0..<2 { pupils[i] += (pt[i] - pupils[i]) * e }
+ look += (f.look - look) * e
+ spiralsK += ((f.spirals ? 1 : 0) - spiralsK) * min(1, dt * 8)
+ questionK += ((f.question ? 1 : 0) - questionK) * min(1, dt * 4)
+ }
+
+ // MARK: input
+
+ func motion(_ r: Rig, _ ax: Double, _ ay: Double, _ az: Double) {
+ let e = max(0, sqrt(ax * ax + ay * ay + az * az) - 0.9)
+ trauma = min(1, trauma + e * e * 0.25)
+ // the arms swing behind the watch's moves (above a little, so walking doesn't keep them busy)
+ let lat = sqrt(ax * ax + ay * ay)
+ if lat > 0.3 {
+ let k = min(2.5, lat - 0.3) * 6.5
+ for i in arms.indices {
+ let ang = SolArt.armAngle[i] + turn + tilt
+ let torque = cos(ang) * (-ay) - sin(ang) * (-ax) // the push across the arm
+ arms[i].fv += torque / max(lat, 1e-6) * k
+ }
+ busyAt = t
+ }
+ if e > 0 { busyAt = t }
+ }
+ func crown(_ r: Rig, _ delta: Double) { spinV = clamp(spinV + delta * 1.6, -14, 14); crownIdle = 0; busyAt = t }
+ func touched(_ r: Rig, at pt: CGPoint) { finger = pt; busyAt = t }
+ func dragged(_ r: Rig, at pt: CGPoint) { finger = pt; busyAt = t }
+ func released(_ r: Rig) { finger = nil }
+ func poke(_ r: Rig) {
+ pokes = pokes.filter { t - $0 < 3 } + [t]
+ for i in arms.indices { arms[i].lv -= 5.5 } // the arms snap in (and spring back out)
+ squash.v -= 3
+ switch state {
+ case .sleep: // woken with a start, then back to sleep
+ startT = 1.3; squash.v -= 1.5
+ case .blocked: // crosser
+ crossT = max(crossT, 1.2); for i in arms.indices { arms[i].fv += rnd(-2, 2) }
+ case .dizzy:
+ for i in arms.indices { arms[i].fv += rnd(-3, 3) }
+ default:
+ if pokes.count >= 4 { pokes = []; crossT = 2.2; winkT = 0; squash.v -= 1 }
+ else if crossT <= 0 { winkT = 1.1 }
+ }
+ busyAt = t
+ }
+ func pet(_ r: Rig) { petT = 0.45; busyAt = t }
+ func deny(_ r: Rig) { crossT = 1.2 }
+ func hit(_ pt: CGPoint) -> Bool {
+ simd_length(P2(pt.x, pt.y) - center) < Self.RC * (state == .approval ? 1.2 : 2.1)
+ }
+
+ // MARK: drawing
+
+ func draw(_ r: Rig, _ ctx: GraphicsContext) {
+ // dimmed: drawn as one layer at half strength (piece by piece, the overlaps would show through lighter)
+ if r.ao { var c = ctx; c.opacity = 0.5; c.drawLayer { l in self.paint(r, l) } } else { paint(r, ctx) }
+ }
+
+ private func paint(_ r: Rig, _ ctx: GraphicsContext) {
+ let p = r.pose(raw: true)
+ let g = ctx
+ let RC = Self.RC
+ let scale = self.scale
+ let breathe = state == .sleep ? 0.012 * sin(t * TAU / 4.2) : 0
+ let pulse = 1 + 0.05 * bump
+ var b = g
+ b.translateBy(x: center.x, y: center.y + hop.y)
+ b.scaleBy(x: scale * pulse * (1 - squash.k * 0.5 - breathe), y: scale * pulse * (1 + squash.k + breathe))
+ // the arms, from the sheet's shapes, bent by their wave
+ refreshBlend()
+ let pts = deformed(scale: RC, rot: turn + tilt, drag: dragV, wave: true)
+ b.fill(Strokes.smoothClosed(pts), with: .color(Self.yellow))
+ // the face
+ var fc = b
+ fc.rotate(by: .radians(tilt * 0.6))
+ fc.scaleBy(x: RC, y: RC)
+ drawFace(fc, r: r, pose: p)
+ // thinking: three dots up and to the right, swelling one after another (on it). Not the sheet's question mark,
+ // which read as "I didn't get that" right after you'd spoken
+ if questionK > 0.02 {
+ var q = b; q.rotate(by: .radians(tilt * 0.3 + sin(t * 1.3) * 0.05)); q.scaleBy(x: RC, y: RC)
+ q.translateBy(x: 0, y: (1 - questionK) * 0.3 + sin(t * 1.6) * 0.03)
+ let qa = q.faded(questionK), c = Self.thinkAt
+ var dots = Path()
+ for i in 0..<3 {
+ let k = 0.5 + 0.5 * sin(t * 5.2 - Double(i) * 0.9), r = 0.1 + 0.045 * k
+ let x = c.x + 0.3 + (Double(i) - 1) * 0.34, y = c.y - 0.22 - 0.06 * k
+ dots.addEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))
+ }
+ qa.fill(dots, with: .color(Self.yellow))
+ }
+ // done: the sheet's motion strokes around it while it shakes
+ if state == .done && r.stateT < 1.9 {
+ let st = r.stateT, a = min(1, st / 0.12) * clamp((1.9 - st) / 0.5, 0, 1)
+ var d = b; d.scaleBy(x: RC, y: RC)
+ let dd = SolArt.dashes
+ for j in 0..<(dd.count / 6) {
+ let p0 = P2(dd[j * 6], dd[j * 6 + 1]), c = P2(dd[j * 6 + 2], dd[j * 6 + 3]), p1 = P2(dd[j * 6 + 4], dd[j * 6 + 5])
+ let m = (p0 + p1) / 2, out = m / max(0.01, simd_length(m))
+ let o: P2 = out * (0.035 * sin(st * 38 + Double(j) * 1.9) + 0.12 * outQ(min(1, st / 0.3)) - 0.12)
+ var path = Path()
+ path.move(to: CGPoint(x: p0.x + o.x, y: p0.y + o.y))
+ path.addQuadCurve(to: CGPoint(x: p1.x + o.x, y: p1.y + o.y), control: CGPoint(x: c.x + o.x, y: c.y + o.y))
+ d.faded(a).stroke(path, with: .color(Self.yellow), style: StrokeStyle(lineWidth: 0.085, lineCap: .round))
+ }
+ }
+ // subagents: three small suns going round it
+ if minis > 0.02 {
+ let small = Self.miniPath
+ var o = g; o.translateBy(x: center.x, y: center.y + hop.y) // their orbit doesn't shrink with it
+ for k in 0..<3 {
+ let a = t * 0.7 + Double(k) * TAU / 3, c = P2(cos(a) * 82, sin(a) * 80) * minis
+ let bob = sin(t * 3.1 + Double(k) * 2) * 3
+ var m = o.faded(minis); m.translateBy(x: c.x, y: c.y + bob); m.rotate(by: .radians(t * 0.5 + Double(k)))
+ m.scaleBy(x: RC * 0.26, y: RC * 0.26)
+ m.fill(small, with: .color(Self.yellow))
+ m.rotate(by: .radians(-(t * 0.5 + Double(k))))
+ for side in [-1.0, 1.0] {
+ m.fill(Path(ellipseIn: CGRect(x: side * 0.37 - 0.3, y: -0.5, width: 0.6, height: 0.6)), with: .color(Self.cream))
+ m.fill(Path(ellipseIn: CGRect(x: side * 0.37 - 0.15 + cos(a) * 0.08, y: -0.35, width: 0.3, height: 0.3)), with: .color(Self.ink))
+ }
+ }
+ }
+ }
+
+ func front(_ r: Rig, _ ctx: GraphicsContext) {}
+
+ /// The base shape's outline, for the small suns: built once.
+ private static let miniPath: Path = {
+ let s = SolArt.base, K = SolArt.K
+ var pts: [P2] = []
+ for a in 0..<10 {
+ let o = a * K * 4
+ for k in stride(from: 0, to: K, by: 2) { pts.append(P2(s[o + 2 * k], s[o + 2 * k + 1])) }
+ for k in stride(from: K - 2, to: 0, by: -2) { pts.append(P2(s[o + 2 * K + 2 * k], s[o + 2 * K + 2 * k + 1])) }
+ }
+ return Strokes.smoothClosed(pts)
+ }()
+
+ /// The four shapes mixed by the state's weights (only when the weights move).
+ private func refreshBlend() {
+ let w = cur.shape
+ if simd_length(w - blendKey) < 1e-4 { return }
+ blendKey = w
+ let A = SolArt.base, B = SolArt.angry, C = SolArt.melt, D = SolArt.dizzy
+ var out = [Double](repeating: 0, count: A.count)
+ for i in 0..<A.count {
+ let ab = A[i] * w.x + B[i] * w.y
+ let cd = C[i] * w.z + D[i] * w.w
+ out[i] = ab + cd
+ }
+ let sum = max(1e-6, w.x + w.y + w.z + w.w)
+ if abs(sum - 1) > 1e-4 { for i in out.indices { out[i] /= sum } }
+ blend = out
+ }
+
+ /// The outline, every arm bent by its wave (and its flop, its length), turned by `rot`, in pt.
+ private func deformed(scale RC: Double, rot: Double, drag: P2, wave: Bool) -> [P2] {
+ let K = Self.K, s = blend
+ var out: [P2] = []
+ out.reserveCapacity(10 * (2 * K - 2))
+ let cr = cos(rot), sr = sin(rot)
+ var R = [P2](repeating: .zero, count: K), L = R, C = R, sl = [Double](repeating: 0, count: K)
+ var nR = R, nL = R
+ for a in 0..<10 {
+ let o = a * K * 4, arm = arms[a]
+ for k in 0..<K {
+ R[k] = P2(s[o + 2 * k], s[o + 2 * k + 1])
+ L[k] = P2(s[o + 2 * K + 2 * k], s[o + 2 * K + 2 * k + 1])
+ C[k] = (R[k] + L[k]) * 0.5
+ }
+ sl[0] = 0
+ for k in 1..<K { sl[k] = sl[k - 1] + simd_length(C[k] - C[k - 1]) }
+ let total = max(1e-6, sl[K - 1])
+ // the arm's direction, turned: a drag pulls it behind, a turn leaves it trailing
+ let ang = SolArt.armAngle[a] + rot
+ let dir = P2(cos(ang), sin(ang))
+ let crossV = dir.x * drag.y - dir.y * drag.x
+ var bias = arm.flop - clamp(crossV * 0.012, -1.2, 1.2) - clamp(spinV * 0.09, -1.1, 1.1)
+ // how it holds them: up toward you, hanging, curled round one way, shivering, the top ones waving
+ bias += (cur.up * -dir.x + cur.droop * dir.x) * 1.1 + cur.curl * 0.9
+ if cur.shiver > 0.01 { bias += cur.shiver * 0.2 * sin(t * 31 + arm.phase * 3) }
+ if cur.wave > 0.01 { bias += cur.wave * 1.3 * max(0, -dir.y - 0.2) * sin(t * 7 + Double(a) * 0.9) }
+ // the small suns going round: the arm nearest each reaches for it as it passes
+ var near = 0.0
+ if minis > 0.02 && wave {
+ for k in 0..<3 {
+ let ak = t * 0.7 + Double(k) * TAU / 3, off = remainder(ak - ang, TAU)
+ let c = pow(max(0, cos(off)), 8) * minis
+ near += c; bias += c * clamp(off, -0.6, 0.6) * 1.4
+ }
+ }
+ let amp = wave ? cur.amp * arm.gain * (1 + 0.6 * arm.grab) : 0
+ let len = cur.len + arm.len + 0.3 * sin(arm.grab * Double.pi) + 0.3 * near
+ var phi = 0.0
+ var nc = C[0]
+ nR[0] = R[0]; nL[0] = L[0]
+ for k in 1..<K {
+ let u = sl[k] / total, du = (sl[k] - sl[k - 1]) / total
+ let wgt = smooth(0.1, 0.45, u)
+ let wv = amp * sin(TAU * 0.85 * u - wavePhase + arm.phase) * 2.2
+ phi += du * (wv + bias * 1.6) * wgt
+ let seg: P2 = (C[k] - C[k - 1]) * (1 + len * wgt)
+ let c = cos(phi), sn = sin(phi)
+ nc += P2(seg.x * c - seg.y * sn, seg.x * sn + seg.y * c)
+ let dr = R[k] - C[k], dl = L[k] - C[k]
+ nR[k] = nc + P2(dr.x * c - dr.y * sn, dr.x * sn + dr.y * c)
+ nL[k] = nc + P2(dl.x * c - dl.y * sn, dl.x * sn + dl.y * c)
+ }
+ for k in 0..<K { out.append(nR[k]) }
+ for k in stride(from: K - 2, to: 0, by: -1) { out.append(nL[k]) }
+ }
+ return out.map { q in P2((q.x * cr - q.y * sr) * RC, (q.x * sr + q.y * cr) * RC) }
+ }
+ private func smooth(_ a: Double, _ b: Double, _ x: Double) -> Double { let k = clamp((x - a) / (b - a), 0, 1); return k * k * (3 - 2 * k) }
+
+ /// The face, in units of the middle's radius: cream whites with black pupils, black lines and mouth, a pink tongue.
+ private func drawFace(_ g0: GraphicsContext, r: Rig, pose p: Pose) {
+ var e = p.eye
+ if let f = finger { let d = P2(f.x, f.y) - center; let l = max(1, simd_length(d)); e.gx = d.x / l * min(1, l / 40); e.gy = d.y / l * min(1, l / 40) }
+ if state == .working { e.gx = sin(t * 2.2) * 0.8; e.gy = toolFlash > 0 ? -0.9 : 0.45 }
+ if state == .approval { e.gx = 0; e.gy = 0.9 }
+ if abs(spinV) > 0.5 { e.gx = clamp(spinV * 0.2, -1, 1) }
+ var g = g0
+ g.translateBy(x: e.gx * 0.05 * look, y: e.gy * 0.04 * look) // the whole face turns a little toward it
+ let open = r.ao ? 1 : clamp(e.open, 0, 1)
+ // whites, squashed shut by a blink; pupils inside them
+ for i in 0..<2 where parts[i].shown {
+ var w = parts[i].shape
+ let c = Self.centroid(w)
+ if open < 0.999 { w = w.map { P2($0.x, c.y + ($0.y - c.y) * max(0.06, open)) } }
+ let white = Strokes.smoothClosed(w)
+ g.fill(white, with: .color(Self.cream))
+ var inner = g; if shown.clip || open < 0.95 { inner.clip(to: white) }
+ let pp = pupils[i]
+ let wr = Self.extent(w)
+ let gx = clamp(e.gx, -1, 1) * max(0, wr.x - pp.z) * 0.8 * look
+ let gy = clamp(e.gy, -1, 1) * max(0, wr.y - pp.w) * 0.7 * look
+ inner.fill(Path(ellipseIn: CGRect(x: pp.x + gx - pp.z, y: pp.y + gy - pp.w, width: 2 * pp.z, height: 2 * pp.w)), with: .color(Self.ink))
+ if open < 0.3 { // shut for a blink: the sheet's closed line
+ let d = SolArt.glyph(i == 0 ? "dashL" : "dashR"), dc = Self.centroid(d)
+ g.fill(Strokes.smoothClosed(d.map { $0 - dc + c }), with: .color(Self.ink))
+ }
+ }
+ // dizzy: spirals turning where the eyes are
+ if spiralsK > 0.02 {
+ for (i, sp) in Self.spirals.enumerated() {
+ var s = g.faded(spiralsK); s.translateBy(x: sp.c.x, y: sp.c.y)
+ s.rotate(by: .radians(t * 4.2 * (i == 0 ? 1 : 1.15))); s.scaleBy(x: spiralsK, y: spiralsK)
+ s.fill(sp.path, with: .color(Self.ink))
+ }
+ }
+ // the tongue under the mouth line, then lines, brows and the mouth
+ var mouthPts = parts[6].shape
+ if state == .speaking && winkT <= 0 && petT <= 0 {
+ let v = clamp(r.voice * 1.5, 0, 1)
+ mouthPts = Strokes.mix(SolArt.glyph("smile"), SolArt.glyph("Dtalk"), v)
+ } else if state == .listening && parts[6].name == "O" && parts[6].b > 0.9 {
+ let k = 0.72 + 0.55 * clamp(r.voice * 1.4, 0, 1), c = Self.centroid(mouthPts)
+ mouthPts = mouthPts.map { c + ($0 - c) * P2(0.9 + 0.1 * k, k) }
+ } else if state == .sleep && parts[6].name == "yawn" {
+ let k = 0.96 + 0.07 * sin(t * TAU / 4.2), c = Self.centroid(mouthPts)
+ mouthPts = mouthPts.map { c + ($0 - c) * k }
+ }
+ if parts[7].shown { g.fill(Strokes.smoothClosed(parts[7].shape), with: .color(Self.pink)) }
+ for i in 2..<6 where parts[i].shown { g.fill(Strokes.smoothClosed(parts[i].shape), with: .color(Self.ink)) }
+ if parts[6].shown { g.fill(Strokes.smoothClosed(mouthPts), with: .color(Self.ink)) }
+ }
+ private static func extent(_ p: [P2]) -> P2 {
+ var lo = P2(9, 9), hi = P2(-9, -9)
+ for q in p { lo = simd_min(lo, q); hi = simd_max(hi, q) }
+ return (hi - lo) * 0.5
+ }
+ /// The sheet's spiral eyes, each round its own middle (they turn there).
+ private static let spirals: [(c: P2, path: Path)] = ["spiralL", "spiralR"].map { n in
+ let g = SolArt.glyph(n), e = extent(g)
+ var lo = P2(9, 9); for q in g { lo = simd_min(lo, q) }
+ let c = lo + e
+ return (c, Strokes.smoothClosed(g.map { $0 - c }))
+ }
+}
+
+/// Ray, traced from its character sheet: in units of the middle's radius, centred
+/// on it, y down. Each shape is ten arms (from the top, clockwise), each arm its right then its left edge, 16 points
+/// each from the valley beside it to its tip. base: the sheet's sun · angry: its jagged arms · melt: asleep, the arms
+/// dripping down · dizzy: its pinwheel. Glyphs: the face parts, each 64 points round its outline, leftmost first, clockwise.
+enum SolArt {
+ static let K = 16, N = 64
+ static let base: [Double] = [-0.445, -0.996, -0.408, -1.019, -0.377, -1.052, -0.351, -1.094, -0.329, -1.152, -0.312, -1.242, -0.296, -1.367, -0.274, -1.489, -0.247, -1.597, -0.212, -1.694, -0.179, -1.765, -0.149, -1.812, -0.12, -1.844, -0.09, -1.866, -0.056, -1.88, -0.02, -1.884, 0.345, -0.938, 0.307, -0.963, 0.275, -0.997, 0.25, -1.041, 0.233, -1.098, 0.227, -1.178, 0.23, -1.31, 0.23, -1.448, 0.22, -1.561, 0.202, -1.653, 0.175, -1.727, 0.144, -1.783, 0.11, -1.825, 0.072, -1.854, 0.028, -1.875, -0.02, -1.884, 0.345, -0.938, 0.4, -0.926, 0.455, -0.93, 0.508, -0.949, 0.558, -0.987, 0.609, -1.051, 0.669, -1.166, 0.732, -1.32, 0.792, -1.443, 0.852, -1.529, 0.927, -1.597, 1.025, -1.658, 1.121, -1.699, 1.204, -1.716, 1.272, -1.716, 1.332, -1.698, 0.903, -0.525, 0.902, -0.566, 0.929, -0.62, 0.974, -0.717, 1.009, -0.849, 1.044, -1.01, 1.083, -1.123, 1.142, -1.222, 1.225, -1.319, 1.321, -1.411, 1.371, -1.479, 1.395, -1.536, 1.402, -1.585, 1.394, -1.63, 1.37, -1.668, 1.332, -1.698, 0.903, -0.525, 0.931, -0.497, 0.973, -0.481, 1.028, -0.477, 1.091, -0.488, 1.161, -0.523, 1.254, -0.601, 1.364, -0.7, 1.469, -0.769, 1.573, -0.816, 1.682, -0.841, 1.801, -0.847, 1.902, -0.836, 1.976, -0.812, 2.029, -0.778, 2.066, -0.732, 1.018, 0.022, 1.033, -0.014, 1.071, -0.04, 1.14, -0.052, 1.254, -0.067, 1.363, -0.105, 1.463, -0.171, 1.573, -0.28, 1.681, -0.387, 1.779, -0.451, 1.903, -0.494, 1.993, -0.529, 2.044, -0.57, 2.073, -0.619, 2.081, -0.675, 2.066, -0.732, 1.018, 0.022, 1.036, 0.064, 1.086, 0.098, 1.189, 0.132, 1.344, 0.16, 1.46, 0.186, 1.544, 0.231, 1.616, 0.31, 1.682, 0.404, 1.751, 0.46, 1.848, 0.491, 1.951, 0.513, 2.013, 0.545, 2.051, 0.589, 2.066, 0.645, 2.057, 0.709, 0.829, 0.577, 0.867, 0.542, 0.922, 0.523, 1.004, 0.519, 1.098, 0.53, 1.19, 0.565, 1.289, 0.631, 1.417, 0.742, 1.516, 0.813, 1.605, 0.853, 1.704, 0.87, 1.806, 0.868, 1.896, 0.846, 1.969, 0.809, 2.022, 0.764, 2.057, 0.709, 0.829, 0.577, 0.811, 0.626, 0.823, 0.68, 0.873, 0.739, 0.984, 0.818, 1.067, 0.897, 1.122, 1.007, 1.175, 1.173, 1.232, 1.291, 1.311, 1.379, 1.414, 1.445, 1.483, 1.492, 1.514, 1.542, 1.519, 1.597, 1.497, 1.652, 1.447, 1.699, 0.318, 0.964, 0.363, 0.958, 0.416, 0.971, 0.484, 1.003, 0.554, 1.054, 0.62, 1.131, 0.7, 1.262, 0.784, 1.421, 0.849, 1.521, 0.918, 1.592, 1.006, 1.651, 1.11, 1.699, 1.212, 1.727, 1.306, 1.733, 1.382, 1.725, 1.447, 1.699, 0.318, 0.964, 0.287, 0.984, 0.261, 1.017, 0.242, 1.062, 0.228, 1.127, 0.223, 1.218, 0.227, 1.343, 0.221, 1.46, 0.205, 1.566, 0.176, 1.67, 0.141, 1.756, 0.103, 1.819, 0.068, 1.863, 0.032, 1.892, -0.008, 1.91, -0.052, 1.916, -0.321, 0.995, -0.29, 1.012, -0.266, 1.043, -0.249, 1.087, -0.238, 1.153, -0.237, 1.246, -0.251, 1.364, -0.268, 1.494, -0.273, 1.596, -0.264, 1.68, -0.243, 1.752, -0.213, 1.812, -0.179, 1.857, -0.142, 1.89, -0.099, 1.909, -0.052, 1.916, -0.321, 0.995, -0.376, 0.996, -0.439, 1.027, -0.518, 1.097, -0.619, 1.229, -0.711, 1.337, -0.806, 1.409, -0.919, 1.456, -1.05, 1.49, -1.134, 1.53, -1.203, 1.602, -1.267, 1.699, -1.316, 1.752, -1.364, 1.777, -1.415, 1.781, -1.465, 1.762, -0.859, 0.704, -0.85, 0.737, -0.862, 0.779, -0.898, 0.842, -0.987, 0.961, -1.087, 1.077, -1.182, 1.16, -1.299, 1.238, -1.386, 1.308, -1.448, 1.384, -1.495, 1.474, -1.521, 1.559, -1.529, 1.628, -1.521, 1.683, -1.499, 1.728, -1.465, 1.762, -0.859, 0.704, -0.903, 0.676, -0.967, 0.674, -1.051, 0.7, -1.153, 0.757, -1.252, 0.785, -1.359, 0.78, -1.482, 0.74, -1.591, 0.693, -1.671, 0.683, -1.752, 0.709, -1.844, 0.769, -1.918, 0.802, -1.98, 0.803, -2.034, 0.78, -2.071, 0.734, -1.009, 0.083, -1.022, 0.127, -1.065, 0.177, -1.144, 0.242, -1.233, 0.289, -1.328, 0.312, -1.462, 0.311, -1.617, 0.3, -1.748, 0.31, -1.853, 0.339, -1.938, 0.385, -2.006, 0.446, -2.055, 0.518, -2.081, 0.592, -2.087, 0.666, -2.071, 0.734, -1.009, 0.083, -1.028, 0.045, -1.073, 0.016, -1.17, -0.011, -1.31, -0.054, -1.433, -0.117, -1.533, -0.192, -1.624, -0.299, -1.703, -0.402, -1.773, -0.46, -1.864, -0.493, -1.947, -0.517, -1.997, -0.549, -2.027, -0.593, -2.039, -0.646, -2.03, -0.704, -0.869, -0.527, -0.905, -0.492, -0.961, -0.47, -1.04, -0.46, -1.129, -0.469, -1.219, -0.503, -1.31, -0.562, -1.411, -0.661, -1.51, -0.745, -1.607, -0.8, -1.704, -0.831, -1.798, -0.839, -1.879, -0.827, -1.946, -0.798, -1.997, -0.758, -2.03, -0.704, -0.869, -0.527, -0.865, -0.571, -0.895, -0.62, -0.985, -0.694, -1.097, -0.794, -1.171, -0.897, -1.227, -1.038, -1.274, -1.208, -1.31, -1.302, -1.361, -1.357, -1.438, -1.39, -1.503, -1.42, -1.539, -1.464, -1.552, -1.518, -1.542, -1.575, -1.505, -1.627, -0.445, -0.996, -0.505, -0.981, -0.569, -0.986, -0.639, -1.011, -0.712, -1.056, -0.779, -1.123, -0.844, -1.226, -0.918, -1.372, -0.982, -1.476, -1.056, -1.555, -1.138, -1.616, -1.222, -1.654, -1.309, -1.673, -1.387, -1.673, -1.451, -1.658, -1.505, -1.627]
+ static let angry: [Double] = [-0.44, -0.976, -0.374, -1.03, -0.325, -1.116, -0.294, -1.229, -0.286, -1.349, -0.296, -1.463, -0.291, -1.53, -0.271, -1.573, -0.234, -1.591, -0.191, -1.591, -0.154, -1.617, -0.132, -1.689, -0.103, -1.823, -0.083, -1.905, -0.054, -1.95, -0.011, -1.968, 0.346, -0.929, 0.278, -0.981, 0.235, -1.068, 0.212, -1.19, 0.217, -1.316, 0.249, -1.431, 0.261, -1.498, 0.248, -1.544, 0.213, -1.566, 0.17, -1.562, 0.131, -1.583, 0.113, -1.651, 0.097, -1.789, 0.072, -1.889, 0.038, -1.946, -0.011, -1.968, 0.346, -0.929, 0.416, -0.915, 0.485, -0.931, 0.55, -0.973, 0.602, -1.043, 0.638, -1.158, 0.664, -1.282, 0.697, -1.357, 0.757, -1.408, 0.804, -1.478, 0.861, -1.534, 0.951, -1.57, 1.048, -1.635, 1.131, -1.708, 1.198, -1.74, 1.258, -1.742, 0.883, -0.523, 0.878, -0.585, 0.93, -0.704, 0.99, -0.835, 1.001, -0.923, 0.982, -0.999, 0.997, -1.067, 1.061, -1.132, 1.134, -1.196, 1.166, -1.271, 1.17, -1.359, 1.221, -1.458, 1.282, -1.577, 1.302, -1.656, 1.295, -1.711, 1.258, -1.742, 0.883, -0.523, 0.941, -0.488, 1.029, -0.491, 1.144, -0.536, 1.249, -0.61, 1.319, -0.7, 1.367, -0.747, 1.416, -0.755, 1.45, -0.72, 1.491, -0.682, 1.564, -0.684, 1.685, -0.731, 1.805, -0.805, 1.881, -0.846, 1.94, -0.847, 1.977, -0.811, 0.996, 0.01, 1.029, -0.04, 1.121, -0.064, 1.275, -0.09, 1.426, -0.143, 1.497, -0.181, 1.51, -0.241, 1.531, -0.305, 1.606, -0.358, 1.71, -0.385, 1.775, -0.423, 1.793, -0.494, 1.828, -0.571, 1.923, -0.656, 1.977, -0.736, 1.977, -0.811, 0.996, 0.01, 1.044, 0.076, 1.176, 0.127, 1.316, 0.144, 1.399, 0.173, 1.439, 0.246, 1.519, 0.284, 1.609, 0.289, 1.66, 0.323, 1.649, 0.383, 1.63, 0.445, 1.683, 0.501, 1.828, 0.54, 1.971, 0.583, 2.037, 0.641, 2.045, 0.707, 0.815, 0.554, 0.855, 0.521, 0.911, 0.502, 0.987, 0.496, 1.083, 0.51, 1.173, 0.539, 1.252, 0.587, 1.339, 0.67, 1.414, 0.732, 1.492, 0.768, 1.599, 0.788, 1.723, 0.795, 1.856, 0.777, 1.961, 0.754, 2.013, 0.736, 2.045, 0.707, 0.815, 0.554, 0.797, 0.602, 0.807, 0.656, 0.853, 0.716, 0.953, 0.795, 1.033, 0.873, 1.083, 0.977, 1.131, 1.132, 1.187, 1.246, 1.258, 1.331, 1.36, 1.394, 1.436, 1.44, 1.473, 1.485, 1.483, 1.536, 1.468, 1.59, 1.424, 1.641, 0.318, 0.937, 0.367, 0.934, 0.425, 0.951, 0.493, 0.987, 0.56, 1.04, 0.627, 1.128, 0.716, 1.28, 0.793, 1.417, 0.861, 1.505, 0.94, 1.576, 1.031, 1.632, 1.124, 1.668, 1.218, 1.685, 1.302, 1.684, 1.369, 1.67, 1.424, 1.641, 0.318, 0.937, 0.283, 0.956, 0.257, 0.99, 0.238, 1.039, 0.225, 1.114, 0.223, 1.234, 0.22, 1.372, 0.206, 1.486, 0.184, 1.578, 0.142, 1.665, 0.094, 1.751, 0.068, 1.828, 0.054, 1.881, 0.039, 1.917, 0.017, 1.94, -0.01, 1.95, -0.319, 0.962, -0.283, 0.984, -0.256, 1.022, -0.237, 1.08, -0.229, 1.167, -0.234, 1.286, -0.255, 1.426, -0.268, 1.551, -0.269, 1.63, -0.249, 1.691, -0.21, 1.751, -0.153, 1.808, -0.109, 1.868, -0.077, 1.913, -0.045, 1.94, -0.01, 1.95, -0.319, 0.962, -0.373, 0.963, -0.434, 0.995, -0.509, 1.06, -0.596, 1.175, -0.682, 1.275, -0.788, 1.355, -0.904, 1.417, -1.016, 1.45, -1.091, 1.483, -1.149, 1.546, -1.208, 1.644, -1.246, 1.698, -1.283, 1.725, -1.326, 1.729, -1.369, 1.713, -0.844, 0.686, -0.832, 0.722, -0.837, 0.766, -0.864, 0.822, -0.932, 0.915, -1.029, 1.026, -1.123, 1.11, -1.233, 1.186, -1.316, 1.259, -1.377, 1.339, -1.419, 1.423, -1.441, 1.503, -1.444, 1.572, -1.433, 1.629, -1.408, 1.677, -1.369, 1.713, -0.844, 0.686, -0.91, 0.655, -1.011, 0.673, -1.132, 0.728, -1.237, 0.738, -1.329, 0.7, -1.413, 0.693, -1.487, 0.724, -1.549, 0.722, -1.581, 0.676, -1.62, 0.638, -1.697, 0.664, -1.826, 0.745, -1.919, 0.789, -1.983, 0.787, -2.016, 0.745, -0.99, 0.078, -1.03, 0.157, -1.136, 0.242, -1.271, 0.297, -1.411, 0.307, -1.528, 0.277, -1.597, 0.24, -1.652, 0.25, -1.68, 0.303, -1.735, 0.344, -1.815, 0.357, -1.867, 0.392, -1.874, 0.463, -1.928, 0.547, -1.999, 0.648, -2.016, 0.745, -0.99, 0.078, -1.03, 0.017, -1.151, -0.021, -1.314, -0.083, -1.453, -0.168, -1.554, -0.193, -1.61, -0.223, -1.608, -0.277, -1.593, -0.33, -1.637, -0.376, -1.719, -0.39, -1.793, -0.411, -1.837, -0.483, -1.96, -0.554, -2.053, -0.619, -2.078, -0.689, -0.853, -0.523, -0.94, -0.47, -1.064, -0.459, -1.175, -0.486, -1.239, -0.545, -1.272, -0.611, -1.33, -0.63, -1.4, -0.629, -1.491, -0.709, -1.589, -0.785, -1.66, -0.8, -1.719, -0.756, -1.8, -0.727, -1.939, -0.739, -2.033, -0.73, -2.078, -0.689, -0.853, -0.523, -0.837, -0.571, -0.851, -0.624, -0.902, -0.679, -1.014, -0.754, -1.126, -0.848, -1.192, -0.925, -1.218, -1.012, -1.237, -1.109, -1.291, -1.206, -1.325, -1.298, -1.384, -1.38, -1.469, -1.463, -1.507, -1.514, -1.516, -1.557, -1.498, -1.592, -0.44, -0.976, -0.549, -0.953, -0.639, -0.99, -0.688, -1.082, -0.707, -1.176, -0.754, -1.215, -0.815, -1.191, -0.879, -1.206, -0.932, -1.31, -0.984, -1.484, -1.028, -1.566, -1.089, -1.58, -1.154, -1.545, -1.263, -1.581, -1.396, -1.616, -1.498, -1.592]
+ static let melt: [Double] = [-0.405, -0.982, -0.348, -1.018, -0.304, -1.077, -0.271, -1.183, -0.234, -1.309, -0.184, -1.396, -0.116, -1.463, -0.029, -1.509, 0.104, -1.538, 0.228, -1.57, 0.313, -1.615, 0.381, -1.686, 0.436, -1.759, 0.484, -1.796, 0.534, -1.808, 0.585, -1.798, 0.377, -0.957, 0.32, -0.992, 0.282, -1.04, 0.262, -1.097, 0.262, -1.158, 0.281, -1.216, 0.321, -1.267, 0.395, -1.313, 0.489, -1.362, 0.56, -1.424, 0.614, -1.503, 0.649, -1.585, 0.659, -1.658, 0.651, -1.718, 0.627, -1.765, 0.585, -1.798, 0.377, -0.957, 0.448, -0.945, 0.531, -0.96, 0.671, -1.026, 0.815, -1.084, 0.933, -1.105, 1.043, -1.097, 1.149, -1.062, 1.246, -1.001, 1.351, -0.891, 1.47, -0.747, 1.581, -0.651, 1.644, -0.602, 1.671, -0.563, 1.678, -0.521, 1.665, -0.478, 0.907, -0.515, 0.893, -0.548, 0.898, -0.584, 0.921, -0.616, 0.96, -0.643, 1.017, -0.659, 1.085, -0.66, 1.154, -0.643, 1.224, -0.601, 1.314, -0.523, 1.397, -0.461, 1.466, -0.427, 1.53, -0.416, 1.586, -0.422, 1.632, -0.442, 1.665, -0.478, 0.907, -0.515, 0.957, -0.475, 1.053, -0.441, 1.194, -0.404, 1.309, -0.353, 1.405, -0.284, 1.48, -0.198, 1.546, -0.08, 1.611, 0.081, 1.664, 0.18, 1.733, 0.253, 1.819, 0.311, 1.869, 0.353, 1.893, 0.395, 1.899, 0.439, 1.888, 0.484, 1.069, 0.129, 1.077, 0.102, 1.103, 0.086, 1.142, 0.084, 1.191, 0.095, 1.249, 0.127, 1.308, 0.188, 1.38, 0.295, 1.449, 0.396, 1.517, 0.464, 1.595, 0.513, 1.676, 0.543, 1.749, 0.553, 1.808, 0.545, 1.856, 0.522, 1.888, 0.484, 1.069, 0.129, 1.083, 0.165, 1.126, 0.201, 1.211, 0.265, 1.293, 0.347, 1.35, 0.435, 1.398, 0.561, 1.442, 0.701, 1.479, 0.777, 1.541, 0.84, 1.643, 0.914, 1.708, 0.978, 1.748, 1.045, 1.769, 1.11, 1.771, 1.169, 1.755, 1.223, 0.838, 0.626, 0.877, 0.606, 0.924, 0.613, 0.973, 0.649, 1.022, 0.731, 1.074, 0.868, 1.129, 0.968, 1.202, 1.038, 1.306, 1.088, 1.429, 1.122, 1.506, 1.165, 1.561, 1.231, 1.612, 1.271, 1.665, 1.28, 1.715, 1.264, 1.755, 1.223, 0.838, 0.626, 0.822, 0.667, 0.827, 0.723, 0.868, 0.822, 0.923, 0.95, 0.945, 1.05, 0.939, 1.162, 0.914, 1.299, 0.907, 1.395, 0.926, 1.475, 0.979, 1.566, 1.019, 1.636, 1.033, 1.686, 1.028, 1.729, 1.005, 1.763, 0.968, 1.786, 0.343, 0.969, 0.396, 0.966, 0.45, 0.983, 0.501, 1.015, 0.54, 1.058, 0.564, 1.114, 0.573, 1.195, 0.567, 1.325, 0.572, 1.429, 0.598, 1.515, 0.642, 1.596, 0.709, 1.671, 0.788, 1.734, 0.86, 1.773, 0.917, 1.79, 0.968, 1.786, 0.343, 0.969, 0.313, 0.984, 0.289, 1.009, 0.27, 1.045, 0.256, 1.095, 0.251, 1.177, 0.251, 1.304, 0.245, 1.413, 0.225, 1.523, 0.194, 1.636, 0.161, 1.724, 0.131, 1.782, 0.1, 1.821, 0.067, 1.848, 0.031, 1.865, -0.01, 1.87, -0.282, 1.004, -0.248, 1.021, -0.221, 1.05, -0.201, 1.09, -0.189, 1.146, -0.185, 1.225, -0.196, 1.334, -0.212, 1.465, -0.216, 1.562, -0.206, 1.648, -0.188, 1.717, -0.162, 1.772, -0.13, 1.814, -0.094, 1.844, -0.054, 1.863, -0.01, 1.87, -0.282, 1.004, -0.327, 0.999, -0.366, 1.014, -0.396, 1.046, -0.413, 1.1, -0.414, 1.201, -0.424, 1.313, -0.466, 1.44, -0.504, 1.559, -0.513, 1.66, -0.509, 1.748, -0.52, 1.806, -0.546, 1.846, -0.583, 1.87, -0.63, 1.877, -0.682, 1.863, -0.803, 0.707, -0.798, 0.75, -0.818, 0.817, -0.845, 0.909, -0.851, 0.987, -0.834, 1.065, -0.789, 1.162, -0.76, 1.247, -0.754, 1.325, -0.774, 1.421, -0.804, 1.533, -0.811, 1.625, -0.801, 1.703, -0.773, 1.77, -0.733, 1.825, -0.682, 1.863, -0.803, 0.707, -0.83, 0.694, -0.867, 0.705, -0.909, 0.747, -0.97, 0.822, -1.043, 0.878, -1.146, 0.918, -1.245, 0.951, -1.308, 0.993, -1.35, 1.057, -1.38, 1.152, -1.401, 1.235, -1.43, 1.284, -1.469, 1.312, -1.516, 1.318, -1.564, 1.3, -1.013, 0.129, -1.024, 0.2, -1.065, 0.3, -1.129, 0.417, -1.192, 0.498, -1.276, 0.568, -1.4, 0.646, -1.488, 0.716, -1.552, 0.791, -1.599, 0.875, -1.629, 0.969, -1.642, 1.068, -1.637, 1.159, -1.623, 1.222, -1.599, 1.267, -1.564, 1.3, -1.013, 0.129, -1.022, 0.099, -1.045, 0.079, -1.079, 0.075, -1.12, 0.087, -1.17, 0.122, -1.231, 0.193, -1.309, 0.311, -1.38, 0.405, -1.452, 0.471, -1.534, 0.518, -1.617, 0.545, -1.689, 0.551, -1.747, 0.541, -1.792, 0.516, -1.822, 0.476, -0.901, -0.502, -0.935, -0.464, -1.002, -0.436, -1.134, -0.395, -1.253, -0.34, -1.344, -0.276, -1.415, -0.195, -1.477, -0.085, -1.545, 0.08, -1.596, 0.181, -1.657, 0.249, -1.741, 0.307, -1.793, 0.349, -1.819, 0.39, -1.829, 0.433, -1.822, 0.476, -0.901, -0.502, -0.884, -0.564, -0.889, -0.623, -0.911, -0.671, -0.945, -0.704, -0.989, -0.719, -1.04, -0.711, -1.095, -0.678, -1.156, -0.608, -1.22, -0.52, -1.281, -0.464, -1.35, -0.432, -1.422, -0.422, -1.486, -0.433, -1.536, -0.458, -1.568, -0.501, -0.405, -0.982, -0.464, -0.977, -0.539, -1.009, -0.675, -1.094, -0.789, -1.144, -0.91, -1.161, -1.024, -1.154, -1.118, -1.118, -1.202, -1.056, -1.275, -0.961, -1.349, -0.814, -1.417, -0.71, -1.504, -0.635, -1.553, -0.588, -1.572, -0.545, -1.568, -0.501]
+ static let dizzy: [Double] = [-0.57, -0.985, -0.515, -1.025, -0.481, -1.075, -0.468, -1.141, -0.471, -1.239, -0.459, -1.338, -0.42, -1.439, -0.371, -1.537, -0.35, -1.616, -0.356, -1.701, -0.39, -1.808, -0.421, -1.89, -0.427, -1.946, -0.414, -1.991, -0.386, -2.026, -0.345, -2.047, 0.19, -1.037, 0.136, -1.057, 0.09, -1.094, 0.049, -1.154, 0.016, -1.23, 0.001, -1.316, 0.007, -1.43, 0.019, -1.565, 0.013, -1.676, -0.013, -1.774, -0.059, -1.866, -0.118, -1.948, -0.179, -2.005, -0.235, -2.038, -0.289, -2.051, -0.345, -2.047, 0.19, -1.037, 0.253, -1.035, 0.309, -1.049, 0.359, -1.075, 0.4, -1.116, 0.435, -1.175, 0.464, -1.273, 0.494, -1.381, 0.535, -1.465, 0.598, -1.546, 0.694, -1.636, 0.816, -1.734, 0.889, -1.788, 0.937, -1.812, 0.98, -1.82, 1.02, -1.811, 0.83, -0.694, 0.814, -0.736, 0.822, -0.796, 0.852, -0.898, 0.866, -0.996, 0.853, -1.106, 0.849, -1.195, 0.87, -1.272, 0.92, -1.354, 1.004, -1.451, 1.06, -1.535, 1.088, -1.614, 1.096, -1.681, 1.085, -1.736, 1.06, -1.781, 1.02, -1.811, 0.83, -0.694, 0.866, -0.665, 0.916, -0.652, 0.98, -0.652, 1.054, -0.669, 1.127, -0.705, 1.204, -0.772, 1.295, -0.867, 1.375, -0.931, 1.465, -0.977, 1.572, -1.009, 1.675, -1.021, 1.751, -1.021, 1.802, -1.007, 1.841, -0.981, 1.868, -0.944, 1.045, -0.135, 1.053, -0.177, 1.082, -0.216, 1.14, -0.253, 1.253, -0.301, 1.348, -0.354, 1.42, -0.418, 1.487, -0.517, 1.548, -0.603, 1.618, -0.661, 1.722, -0.714, 1.8, -0.754, 1.845, -0.795, 1.87, -0.842, 1.879, -0.892, 1.868, -0.944, 1.045, -0.135, 1.063, -0.091, 1.105, -0.056, 1.185, -0.029, 1.314, 0.001, 1.424, 0.046, 1.524, 0.119, 1.615, 0.197, 1.69, 0.235, 1.787, 0.246, 1.885, 0.249, 1.946, 0.268, 1.987, 0.301, 2.012, 0.346, 2.018, 0.399, 2.002, 0.456, 0.92, 0.503, 0.95, 0.461, 0.995, 0.429, 1.053, 0.408, 1.119, 0.4, 1.187, 0.408, 1.263, 0.438, 1.368, 0.505, 1.465, 0.562, 1.556, 0.593, 1.65, 0.607, 1.745, 0.602, 1.834, 0.581, 1.908, 0.547, 1.963, 0.506, 2.002, 0.456, 0.92, 0.503, 0.912, 0.547, 0.933, 0.593, 0.996, 0.649, 1.084, 0.728, 1.144, 0.815, 1.187, 0.937, 1.225, 1.066, 1.266, 1.147, 1.323, 1.2, 1.409, 1.236, 1.48, 1.27, 1.519, 1.313, 1.537, 1.361, 1.535, 1.411, 1.51, 1.456, 0.456, 0.95, 0.514, 0.938, 0.586, 0.948, 0.668, 0.976, 0.734, 1.014, 0.784, 1.068, 0.831, 1.161, 0.885, 1.277, 0.942, 1.359, 1.011, 1.422, 1.092, 1.467, 1.188, 1.496, 1.305, 1.507, 1.401, 1.503, 1.463, 1.487, 1.51, 1.456, 0.456, 0.95, 0.415, 0.981, 0.388, 1.031, 0.373, 1.111, 0.368, 1.229, 0.348, 1.336, 0.299, 1.451, 0.262, 1.551, 0.252, 1.631, 0.268, 1.715, 0.312, 1.823, 0.333, 1.895, 0.332, 1.948, 0.318, 1.99, 0.289, 2.022, 0.249, 2.04, -0.221, 1.051, -0.173, 1.075, -0.131, 1.116, -0.097, 1.171, -0.075, 1.236, -0.072, 1.313, -0.092, 1.423, -0.105, 1.548, -0.102, 1.654, -0.079, 1.747, -0.038, 1.837, 0.02, 1.92, 0.084, 1.983, 0.142, 2.02, 0.196, 2.039, 0.249, 2.04, -0.221, 1.051, -0.271, 1.054, -0.319, 1.085, -0.373, 1.162, -0.442, 1.273, -0.528, 1.363, -0.627, 1.427, -0.744, 1.468, -0.855, 1.497, -0.925, 1.539, -0.975, 1.603, -1.013, 1.7, -1.049, 1.763, -1.09, 1.797, -1.14, 1.809, -1.193, 1.797, -0.82, 0.796, -0.798, 0.836, -0.793, 0.894, -0.801, 0.963, -0.83, 1.031, -0.881, 1.095, -0.965, 1.155, -1.074, 1.221, -1.151, 1.29, -1.208, 1.368, -1.247, 1.458, -1.267, 1.562, -1.268, 1.657, -1.257, 1.721, -1.232, 1.767, -1.193, 1.797, -0.82, 0.796, -0.86, 0.782, -0.912, 0.791, -0.987, 0.833, -1.075, 0.88, -1.163, 0.9, -1.264, 0.894, -1.386, 0.864, -1.483, 0.848, -1.565, 0.858, -1.653, 0.899, -1.729, 0.945, -1.783, 0.961, -1.83, 0.955, -1.871, 0.931, -1.9, 0.888, -1.039, 0.228, -1.039, 0.277, -1.058, 0.327, -1.1, 0.381, -1.166, 0.436, -1.25, 0.48, -1.35, 0.508, -1.478, 0.519, -1.599, 0.528, -1.688, 0.551, -1.762, 0.591, -1.825, 0.648, -1.874, 0.714, -1.901, 0.777, -1.91, 0.834, -1.9, 0.888, -1.039, 0.228, -1.068, 0.176, -1.124, 0.136, -1.229, 0.108, -1.353, 0.075, -1.465, 0.013, -1.571, -0.08, -1.666, -0.179, -1.741, -0.227, -1.83, -0.245, -1.927, -0.24, -1.995, -0.246, -2.042, -0.272, -2.072, -0.312, -2.082, -0.363, -2.068, -0.42, -0.977, -0.425, -1.009, -0.376, -1.057, -0.338, -1.121, -0.313, -1.193, -0.302, -1.261, -0.31, -1.329, -0.34, -1.417, -0.41, -1.518, -0.487, -1.604, -0.531, -1.691, -0.553, -1.79, -0.553, -1.897, -0.533, -1.977, -0.504, -2.032, -0.467, -2.068, -0.42, -0.977, -0.425, -0.97, -0.477, -0.992, -0.529, -1.056, -0.585, -1.169, -0.667, -1.254, -0.755, -1.307, -0.848, -1.337, -0.97, -1.361, -1.072, -1.4, -1.135, -1.465, -1.179, -1.559, -1.209, -1.622, -1.238, -1.656, -1.278, -1.668, -1.328, -1.654, -1.383, -0.57, -0.985, -0.651, -0.955, -0.741, -0.952, -0.855, -0.975, -0.937, -1.005, -0.989, -1.046, -1.028, -1.122, -1.077, -1.242, -1.131, -1.328, -1.197, -1.388, -1.288, -1.434, -1.402, -1.463, -1.499, -1.469, -1.567, -1.457, -1.618, -1.428, -1.654, -1.383]
+ static let dashes: [Double] = [0.684, -2.039, 0.640, -1.957, 0.599, -1.873, 1.569, -1.581, 1.587, -1.777, 1.419, -1.880, -1.445, -1.870, -1.651, -1.813, -1.717, -1.611, 1.827, -1.610, 1.816, -1.571, 1.799, -1.532, 2.183, -1.569, 2.079, -1.484, 1.977, -1.398, 2.169, -1.169, 2.111, -1.157, 2.052, -1.154, -2.000, -1.000, -2.153, -0.911, -2.173, -0.733, -2.303, -0.918, -2.350, -0.832, -2.352, -0.734, 2.082, -0.385, 1.903, -0.345, 1.766, -0.223, 2.228, 0.635, 2.208, 0.899, 1.959, 0.989, -2.113, 1.039, -2.178, 1.052, -2.244, 1.053, -2.023, 1.231, -2.124, 1.310, -2.225, 1.390, -1.879, 1.379, -1.895, 1.413, -1.906, 1.449, -1.682, 1.757, -1.632, 1.889, -1.500, 1.939, 0.620, 1.772, 0.657, 1.858, 0.710, 1.935, -0.407, 1.806, -0.365, 1.964, -0.227, 2.053]
+ /// Each arm's direction, middle to tip, in the base shape.
+ static let armAngle: [Double] = [-1.581, -0.906, -0.341, 0.332, 0.865, 1.598, 2.264, 2.801, -2.808, -2.317]
+ static let pupils: [String: SIMD4<Double>] = [
+ "pSurL": SIMD4(-0.373, -0.203, 0.118, 0.120),
+ "pSurR": SIMD4(0.346, -0.214, 0.118, 0.121),
+ "pSadL": SIMD4(-0.389, -0.140, 0.179, 0.195),
+ "pSadR": SIMD4(0.314, -0.132, 0.163, 0.189),
+ "pThkL": SIMD4(-0.257, -0.054, 0.143, 0.150),
+ "pThkR": SIMD4(0.396, -0.336, 0.146, 0.148),
+ "pAngL": SIMD4(-0.343, -0.094, 0.151, 0.136),
+ "pAngR": SIMD4(0.332, -0.097, 0.149, 0.137),
+ "pWinkL": SIMD4(-0.234, -0.161, 0.153, 0.153),
+ "pNeuL": SIMD4(-0.380, -0.197, 0.140, 0.145),
+ "pNeuR": SIMD4(0.349, -0.207, 0.140, 0.145),
+ ]
+ static func pupil(_ n: String) -> SIMD4<Double> { pupils[n] ?? pupils["pNeuL"]! }
+ private static let raw: [String: [Double]] = [
+ "wSurL": [-0.688, -0.195, -0.688, -0.226, -0.687, -0.256, -0.681, -0.287, -0.667, -0.314, -0.657, -0.344, -0.645, -0.372, -0.627, -0.397, -0.607, -0.420, -0.587, -0.444, -0.562, -0.462, -0.536, -0.478, -0.508, -0.491, -0.480, -0.504, -0.450, -0.510, -0.419, -0.515, -0.389, -0.520, -0.358, -0.521, -0.327, -0.517, -0.297, -0.511, -0.267, -0.505, -0.239, -0.492, -0.213, -0.476, -0.188, -0.456, -0.164, -0.438, -0.143, -0.415, -0.123, -0.392, -0.109, -0.364, -0.093, -0.338, -0.083, -0.309, -0.079, -0.278, -0.073, -0.248, -0.072, -0.217, -0.073, -0.186, -0.076, -0.156, -0.082, -0.125, -0.088, -0.095, -0.104, -0.069, -0.115, -0.040, -0.134, -0.016, -0.151, 0.010, -0.173, 0.031, -0.200, 0.047, -0.224, 0.066, -0.253, 0.077, -0.279, 0.093, -0.309, 0.099, -0.340, 0.102, -0.371, 0.103, -0.402, 0.102, -0.432, 0.100, -0.463, 0.098, -0.493, 0.092, -0.520, 0.077, -0.549, 0.065, -0.572, 0.045, -0.598, 0.028, -0.619, 0.006, -0.633, -0.022, -0.651, -0.047, -0.660, -0.076, -0.671, -0.105, -0.684, -0.133, -0.687, -0.164],
+ "wSurR": [0.039, -0.245, 0.041, -0.276, 0.050, -0.305, 0.063, -0.333, 0.072, -0.363, 0.089, -0.388, 0.104, -0.415, 0.126, -0.437, 0.151, -0.454, 0.174, -0.475, 0.201, -0.490, 0.228, -0.504, 0.257, -0.515, 0.286, -0.524, 0.316, -0.532, 0.347, -0.534, 0.378, -0.533, 0.408, -0.528, 0.437, -0.519, 0.467, -0.510, 0.495, -0.498, 0.521, -0.481, 0.547, -0.465, 0.569, -0.443, 0.588, -0.419, 0.608, -0.396, 0.621, -0.368, 0.637, -0.342, 0.645, -0.312, 0.649, -0.281, 0.655, -0.251, 0.656, -0.221, 0.655, -0.190, 0.652, -0.159, 0.646, -0.129, 0.639, -0.099, 0.622, -0.073, 0.611, -0.045, 0.591, -0.021, 0.572, 0.003, 0.548, 0.022, 0.523, 0.040, 0.498, 0.058, 0.469, 0.070, 0.441, 0.082, 0.413, 0.093, 0.382, 0.097, 0.351, 0.098, 0.320, 0.098, 0.290, 0.095, 0.260, 0.087, 0.233, 0.072, 0.204, 0.062, 0.180, 0.042, 0.154, 0.026, 0.131, 0.006, 0.110, -0.017, 0.092, -0.042, 0.073, -0.066, 0.063, -0.095, 0.051, -0.123, 0.043, -0.153, 0.040, -0.184, 0.040, -0.214],
+ "wSadL": [-0.658, -0.143, -0.657, -0.175, -0.654, -0.206, -0.644, -0.236, -0.633, -0.266, -0.625, -0.296, -0.609, -0.323, -0.592, -0.350, -0.571, -0.373, -0.548, -0.395, -0.525, -0.416, -0.498, -0.432, -0.469, -0.446, -0.439, -0.454, -0.410, -0.465, -0.379, -0.472, -0.347, -0.474, -0.316, -0.472, -0.285, -0.466, -0.254, -0.458, -0.225, -0.447, -0.196, -0.434, -0.170, -0.416, -0.145, -0.396, -0.120, -0.377, -0.103, -0.351, -0.085, -0.325, -0.072, -0.296, -0.058, -0.269, -0.051, -0.238, -0.046, -0.207, -0.041, -0.175, -0.040, -0.144, -0.043, -0.113, -0.048, -0.082, -0.053, -0.050, -0.061, -0.020, -0.078, 0.007, -0.091, 0.035, -0.110, 0.060, -0.129, 0.086, -0.153, 0.106, -0.176, 0.127, -0.203, 0.144, -0.231, 0.158, -0.262, 0.165, -0.292, 0.175, -0.322, 0.184, -0.353, 0.186, -0.385, 0.185, -0.416, 0.180, -0.446, 0.170, -0.476, 0.161, -0.506, 0.150, -0.532, 0.132, -0.557, 0.113, -0.579, 0.090, -0.597, 0.065, -0.615, 0.038, -0.628, 0.010, -0.637, -0.020, -0.649, -0.049, -0.655, -0.080, -0.657, -0.112],
+ "wSadR": [0.060, -0.130, 0.063, -0.161, 0.066, -0.191, 0.070, -0.222, 0.077, -0.251, 0.093, -0.277, 0.106, -0.305, 0.125, -0.329, 0.141, -0.354, 0.162, -0.377, 0.188, -0.394, 0.212, -0.412, 0.240, -0.423, 0.266, -0.440, 0.296, -0.445, 0.326, -0.448, 0.357, -0.451, 0.387, -0.451, 0.418, -0.448, 0.448, -0.443, 0.477, -0.432, 0.503, -0.417, 0.529, -0.401, 0.553, -0.382, 0.575, -0.361, 0.594, -0.337, 0.613, -0.313, 0.625, -0.285, 0.640, -0.258, 0.645, -0.228, 0.652, -0.198, 0.658, -0.168, 0.659, -0.138, 0.657, -0.107, 0.650, -0.077, 0.646, -0.047, 0.639, -0.017, 0.624, 0.009, 0.611, 0.037, 0.594, 0.062, 0.576, 0.087, 0.552, 0.106, 0.530, 0.127, 0.505, 0.145, 0.478, 0.158, 0.448, 0.165, 0.420, 0.178, 0.391, 0.185, 0.360, 0.186, 0.330, 0.185, 0.300, 0.178, 0.271, 0.168, 0.241, 0.160, 0.214, 0.147, 0.188, 0.131, 0.163, 0.113, 0.139, 0.094, 0.122, 0.068, 0.103, 0.044, 0.091, 0.016, 0.074, -0.009, 0.068, -0.039, 0.066, -0.070, 0.062, -0.100],
+ "wThkL": [-0.690, -0.003, -0.689, -0.034, -0.686, -0.065, -0.678, -0.094, -0.667, -0.123, -0.656, -0.152, -0.639, -0.178, -0.623, -0.204, -0.602, -0.227, -0.580, -0.248, -0.556, -0.267, -0.531, -0.285, -0.502, -0.296, -0.473, -0.306, -0.444, -0.318, -0.414, -0.323, -0.383, -0.324, -0.352, -0.323, -0.322, -0.318, -0.292, -0.310, -0.264, -0.299, -0.234, -0.289, -0.209, -0.271, -0.182, -0.256, -0.161, -0.233, -0.143, -0.209, -0.125, -0.184, -0.109, -0.157, -0.093, -0.131, -0.084, -0.102, -0.079, -0.071, -0.076, -0.041, -0.074, -0.010, -0.076, 0.021, -0.081, 0.051, -0.084, 0.082, -0.093, 0.111, -0.109, 0.138, -0.120, 0.167, -0.140, 0.190, -0.159, 0.215, -0.182, 0.235, -0.208, 0.252, -0.234, 0.269, -0.262, 0.281, -0.291, 0.292, -0.319, 0.303, -0.350, 0.308, -0.381, 0.309, -0.411, 0.309, -0.442, 0.305, -0.472, 0.297, -0.501, 0.286, -0.529, 0.275, -0.554, 0.257, -0.580, 0.240, -0.602, 0.219, -0.623, 0.196, -0.640, 0.170, -0.657, 0.145, -0.669, 0.116, -0.683, 0.089, -0.687, 0.058, -0.689, 0.028],
+ "wThkR": [-0.030, -0.287, -0.030, -0.318, -0.027, -0.348, -0.024, -0.379, -0.018, -0.409, -0.006, -0.437, 0.008, -0.464, 0.028, -0.487, 0.046, -0.512, 0.067, -0.534, 0.092, -0.552, 0.117, -0.570, 0.142, -0.587, 0.170, -0.598, 0.201, -0.603, 0.230, -0.612, 0.260, -0.616, 0.291, -0.616, 0.321, -0.612, 0.351, -0.604, 0.380, -0.598, 0.408, -0.585, 0.435, -0.570, 0.461, -0.554, 0.485, -0.535, 0.505, -0.512, 0.523, -0.487, 0.542, -0.463, 0.555, -0.436, 0.568, -0.408, 0.579, -0.379, 0.582, -0.349, 0.582, -0.318, 0.582, -0.288, 0.580, -0.257, 0.576, -0.227, 0.563, -0.199, 0.553, -0.170, 0.541, -0.142, 0.524, -0.117, 0.504, -0.094, 0.482, -0.072, 0.458, -0.053, 0.433, -0.037, 0.405, -0.023, 0.377, -0.012, 0.349, 0.001, 0.319, 0.006, 0.288, 0.007, 0.258, 0.007, 0.227, 0.006, 0.197, 0.002, 0.168, -0.008, 0.140, -0.020, 0.112, -0.032, 0.087, -0.050, 0.065, -0.071, 0.041, -0.090, 0.023, -0.115, 0.008, -0.141, -0.003, -0.170, -0.018, -0.196, -0.024, -0.227, -0.027, -0.257],
+ "wAngL": [-0.669, -0.141, -0.664, -0.167, -0.661, -0.193, -0.657, -0.219, -0.650, -0.245, -0.635, -0.266, -0.623, -0.289, -0.604, -0.307, -0.578, -0.311, -0.552, -0.304, -0.531, -0.289, -0.506, -0.280, -0.481, -0.273, -0.458, -0.260, -0.434, -0.249, -0.409, -0.243, -0.386, -0.229, -0.362, -0.218, -0.337, -0.211, -0.314, -0.198, -0.290, -0.188, -0.264, -0.181, -0.239, -0.174, -0.217, -0.159, -0.193, -0.148, -0.170, -0.136, -0.145, -0.130, -0.120, -0.121, -0.099, -0.106, -0.080, -0.089, -0.080, -0.063, -0.084, -0.037, -0.092, -0.012, -0.106, 0.010, -0.119, 0.033, -0.134, 0.054, -0.149, 0.076, -0.169, 0.092, -0.187, 0.111, -0.210, 0.124, -0.232, 0.139, -0.257, 0.147, -0.281, 0.156, -0.305, 0.167, -0.331, 0.170, -0.358, 0.172, -0.384, 0.172, -0.410, 0.170, -0.436, 0.167, -0.462, 0.160, -0.486, 0.149, -0.511, 0.141, -0.533, 0.127, -0.554, 0.112, -0.573, 0.093, -0.594, 0.077, -0.607, 0.054, -0.624, 0.034, -0.635, 0.011, -0.649, -0.011, -0.657, -0.037, -0.660, -0.063, -0.663, -0.089, -0.667, -0.115],
+ "wAngR": [0.062, -0.084, 0.074, -0.107, 0.096, -0.121, 0.122, -0.129, 0.147, -0.138, 0.170, -0.151, 0.195, -0.158, 0.220, -0.167, 0.243, -0.180, 0.268, -0.188, 0.293, -0.196, 0.315, -0.211, 0.340, -0.218, 0.364, -0.229, 0.386, -0.244, 0.412, -0.250, 0.433, -0.265, 0.458, -0.275, 0.483, -0.283, 0.505, -0.297, 0.529, -0.309, 0.554, -0.317, 0.579, -0.322, 0.600, -0.305, 0.613, -0.282, 0.624, -0.258, 0.637, -0.236, 0.643, -0.210, 0.647, -0.184, 0.650, -0.158, 0.653, -0.131, 0.651, -0.105, 0.647, -0.079, 0.644, -0.052, 0.638, -0.026, 0.627, -0.003, 0.614, 0.021, 0.603, 0.044, 0.584, 0.063, 0.568, 0.084, 0.548, 0.102, 0.526, 0.116, 0.505, 0.132, 0.481, 0.144, 0.455, 0.150, 0.430, 0.159, 0.405, 0.166, 0.379, 0.170, 0.352, 0.172, 0.326, 0.170, 0.300, 0.167, 0.274, 0.160, 0.249, 0.151, 0.224, 0.143, 0.201, 0.130, 0.181, 0.113, 0.159, 0.097, 0.138, 0.082, 0.124, 0.059, 0.105, 0.040, 0.094, 0.016, 0.082, -0.007, 0.071, -0.031, 0.066, -0.057],
+ "wWinkL": [-0.681, -0.151, -0.680, -0.182, -0.678, -0.212, -0.673, -0.242, -0.664, -0.271, -0.648, -0.296, -0.635, -0.323, -0.616, -0.347, -0.597, -0.370, -0.578, -0.394, -0.552, -0.409, -0.528, -0.428, -0.500, -0.441, -0.474, -0.455, -0.444, -0.461, -0.414, -0.463, -0.384, -0.465, -0.354, -0.466, -0.323, -0.463, -0.294, -0.458, -0.267, -0.444, -0.239, -0.432, -0.213, -0.416, -0.188, -0.400, -0.165, -0.380, -0.147, -0.356, -0.129, -0.332, -0.111, -0.307, -0.099, -0.279, -0.092, -0.250, -0.086, -0.220, -0.074, -0.192, -0.075, -0.162, -0.073, -0.132, -0.075, -0.102, -0.087, -0.074, -0.095, -0.045, -0.105, -0.016, -0.123, 0.008, -0.137, 0.035, -0.157, 0.057, -0.178, 0.079, -0.203, 0.096, -0.227, 0.114, -0.255, 0.125, -0.282, 0.139, -0.312, 0.144, -0.342, 0.147, -0.372, 0.149, -0.403, 0.147, -0.433, 0.144, -0.463, 0.140, -0.491, 0.130, -0.519, 0.117, -0.546, 0.105, -0.570, 0.087, -0.592, 0.065, -0.614, 0.045, -0.634, 0.022, -0.646, -0.006, -0.660, -0.033, -0.671, -0.061, -0.674, -0.091, -0.678, -0.121],
+ "happyL": [-0.702, -0.154, -0.701, -0.183, -0.694, -0.211, -0.688, -0.239, -0.676, -0.266, -0.662, -0.291, -0.647, -0.316, -0.628, -0.338, -0.608, -0.358, -0.586, -0.377, -0.561, -0.392, -0.536, -0.406, -0.510, -0.418, -0.482, -0.428, -0.454, -0.435, -0.426, -0.439, -0.397, -0.440, -0.368, -0.437, -0.340, -0.432, -0.312, -0.424, -0.284, -0.415, -0.259, -0.401, -0.235, -0.385, -0.212, -0.367, -0.191, -0.348, -0.171, -0.327, -0.153, -0.304, -0.139, -0.279, -0.127, -0.252, -0.116, -0.226, -0.110, -0.197, -0.106, -0.169, -0.107, -0.140, -0.116, -0.112, -0.136, -0.092, -0.164, -0.084, -0.192, -0.090, -0.212, -0.111, -0.224, -0.137, -0.232, -0.165, -0.240, -0.193, -0.252, -0.219, -0.266, -0.244, -0.286, -0.265, -0.309, -0.283, -0.334, -0.297, -0.360, -0.309, -0.389, -0.313, -0.418, -0.313, -0.446, -0.308, -0.473, -0.298, -0.499, -0.284, -0.521, -0.266, -0.541, -0.245, -0.560, -0.223, -0.572, -0.197, -0.583, -0.170, -0.589, -0.142, -0.597, -0.114, -0.613, -0.090, -0.639, -0.079, -0.668, -0.081, -0.692, -0.098, -0.701, -0.125],
+ "happyR": [0.115, -0.177, 0.119, -0.206, 0.126, -0.234, 0.134, -0.262, 0.147, -0.288, 0.160, -0.313, 0.179, -0.336, 0.197, -0.359, 0.217, -0.379, 0.240, -0.396, 0.262, -0.415, 0.288, -0.429, 0.314, -0.441, 0.342, -0.448, 0.370, -0.455, 0.399, -0.458, 0.428, -0.458, 0.457, -0.455, 0.485, -0.449, 0.514, -0.442, 0.540, -0.430, 0.565, -0.417, 0.590, -0.401, 0.612, -0.383, 0.633, -0.363, 0.651, -0.340, 0.669, -0.317, 0.682, -0.291, 0.693, -0.265, 0.703, -0.237, 0.709, -0.209, 0.714, -0.181, 0.713, -0.152, 0.703, -0.125, 0.680, -0.107, 0.652, -0.101, 0.624, -0.109, 0.605, -0.130, 0.597, -0.158, 0.588, -0.186, 0.581, -0.214, 0.570, -0.240, 0.552, -0.263, 0.532, -0.284, 0.510, -0.303, 0.484, -0.315, 0.456, -0.325, 0.427, -0.327, 0.398, -0.326, 0.370, -0.322, 0.343, -0.312, 0.317, -0.298, 0.293, -0.282, 0.274, -0.261, 0.257, -0.237, 0.245, -0.211, 0.233, -0.184, 0.227, -0.156, 0.219, -0.128, 0.201, -0.106, 0.174, -0.096, 0.146, -0.102, 0.124, -0.121, 0.115, -0.148],
+ "dashL": [-0.638, -0.104, -0.633, -0.123, -0.624, -0.140, -0.608, -0.152, -0.590, -0.158, -0.571, -0.160, -0.552, -0.160, -0.532, -0.161, -0.513, -0.163, -0.494, -0.163, -0.474, -0.165, -0.455, -0.166, -0.436, -0.168, -0.416, -0.170, -0.397, -0.171, -0.378, -0.172, -0.358, -0.174, -0.339, -0.175, -0.320, -0.178, -0.301, -0.180, -0.282, -0.182, -0.262, -0.184, -0.243, -0.185, -0.224, -0.187, -0.204, -0.188, -0.185, -0.188, -0.166, -0.189, -0.146, -0.189, -0.127, -0.187, -0.110, -0.179, -0.095, -0.166, -0.085, -0.149, -0.084, -0.130, -0.088, -0.111, -0.099, -0.095, -0.114, -0.083, -0.131, -0.074, -0.150, -0.070, -0.169, -0.068, -0.188, -0.067, -0.208, -0.067, -0.227, -0.066, -0.246, -0.065, -0.266, -0.064, -0.285, -0.063, -0.304, -0.061, -0.324, -0.060, -0.343, -0.058, -0.362, -0.057, -0.382, -0.056, -0.401, -0.055, -0.420, -0.055, -0.440, -0.054, -0.459, -0.051, -0.478, -0.049, -0.497, -0.048, -0.517, -0.046, -0.536, -0.044, -0.555, -0.042, -0.574, -0.042, -0.593, -0.047, -0.610, -0.057, -0.625, -0.068, -0.635, -0.085],
+ "dashR": [0.128, -0.138, 0.130, -0.157, 0.140, -0.174, 0.154, -0.186, 0.173, -0.192, 0.192, -0.194, 0.211, -0.194, 0.231, -0.193, 0.250, -0.192, 0.269, -0.191, 0.289, -0.190, 0.308, -0.189, 0.327, -0.189, 0.347, -0.188, 0.366, -0.187, 0.385, -0.185, 0.404, -0.184, 0.424, -0.183, 0.443, -0.180, 0.462, -0.178, 0.481, -0.177, 0.501, -0.175, 0.520, -0.173, 0.539, -0.172, 0.558, -0.171, 0.578, -0.171, 0.597, -0.170, 0.616, -0.168, 0.635, -0.164, 0.654, -0.158, 0.669, -0.146, 0.677, -0.129, 0.682, -0.110, 0.678, -0.091, 0.670, -0.074, 0.654, -0.063, 0.636, -0.056, 0.616, -0.055, 0.597, -0.055, 0.578, -0.055, 0.558, -0.055, 0.539, -0.056, 0.520, -0.057, 0.500, -0.058, 0.481, -0.059, 0.462, -0.060, 0.442, -0.062, 0.423, -0.064, 0.404, -0.065, 0.385, -0.066, 0.365, -0.067, 0.346, -0.067, 0.327, -0.068, 0.307, -0.069, 0.288, -0.070, 0.269, -0.070, 0.249, -0.071, 0.230, -0.073, 0.211, -0.074, 0.192, -0.077, 0.173, -0.083, 0.155, -0.090, 0.140, -0.102, 0.131, -0.119],
+ "winkR": [0.108, -0.230, 0.110, -0.252, 0.113, -0.274, 0.118, -0.296, 0.127, -0.317, 0.138, -0.337, 0.149, -0.356, 0.161, -0.375, 0.174, -0.393, 0.188, -0.410, 0.204, -0.427, 0.221, -0.441, 0.238, -0.455, 0.258, -0.466, 0.278, -0.477, 0.298, -0.487, 0.320, -0.492, 0.342, -0.495, 0.364, -0.497, 0.386, -0.497, 0.409, -0.495, 0.431, -0.492, 0.453, -0.487, 0.474, -0.479, 0.494, -0.470, 0.514, -0.460, 0.533, -0.448, 0.551, -0.434, 0.568, -0.420, 0.584, -0.404, 0.598, -0.386, 0.609, -0.367, 0.617, -0.346, 0.618, -0.324, 0.609, -0.303, 0.594, -0.286, 0.573, -0.279, 0.551, -0.279, 0.530, -0.285, 0.512, -0.300, 0.497, -0.316, 0.480, -0.331, 0.461, -0.343, 0.442, -0.355, 0.421, -0.363, 0.399, -0.368, 0.377, -0.369, 0.355, -0.366, 0.334, -0.359, 0.314, -0.348, 0.295, -0.336, 0.278, -0.322, 0.263, -0.305, 0.251, -0.286, 0.241, -0.266, 0.233, -0.245, 0.225, -0.224, 0.216, -0.204, 0.204, -0.185, 0.185, -0.173, 0.162, -0.171, 0.140, -0.175, 0.122, -0.188, 0.112, -0.208],
+ "browL": [-0.567, -0.496, -0.565, -0.514, -0.555, -0.529, -0.539, -0.539, -0.523, -0.548, -0.504, -0.548, -0.487, -0.542, -0.471, -0.532, -0.455, -0.523, -0.438, -0.516, -0.423, -0.505, -0.406, -0.498, -0.390, -0.490, -0.373, -0.481, -0.357, -0.472, -0.341, -0.463, -0.324, -0.455, -0.309, -0.446, -0.293, -0.436, -0.276, -0.428, -0.261, -0.418, -0.245, -0.409, -0.228, -0.400, -0.212, -0.392, -0.196, -0.382, -0.180, -0.373, -0.164, -0.365, -0.148, -0.355, -0.132, -0.346, -0.116, -0.336, -0.104, -0.323, -0.096, -0.306, -0.092, -0.288, -0.097, -0.270, -0.105, -0.254, -0.119, -0.241, -0.137, -0.236, -0.155, -0.238, -0.173, -0.244, -0.190, -0.251, -0.206, -0.259, -0.222, -0.269, -0.238, -0.278, -0.254, -0.287, -0.269, -0.297, -0.285, -0.306, -0.302, -0.314, -0.318, -0.323, -0.334, -0.333, -0.350, -0.341, -0.366, -0.350, -0.382, -0.359, -0.399, -0.368, -0.415, -0.376, -0.431, -0.385, -0.447, -0.394, -0.464, -0.402, -0.480, -0.411, -0.496, -0.420, -0.512, -0.430, -0.528, -0.438, -0.543, -0.449, -0.557, -0.461, -0.566, -0.477],
+ "browR": [0.067, -0.288, 0.070, -0.306, 0.079, -0.322, 0.091, -0.335, 0.105, -0.346, 0.120, -0.355, 0.135, -0.366, 0.151, -0.373, 0.166, -0.383, 0.182, -0.392, 0.197, -0.402, 0.212, -0.411, 0.228, -0.420, 0.243, -0.429, 0.259, -0.437, 0.275, -0.446, 0.290, -0.456, 0.306, -0.463, 0.322, -0.472, 0.338, -0.480, 0.352, -0.491, 0.368, -0.499, 0.384, -0.508, 0.399, -0.517, 0.415, -0.525, 0.431, -0.534, 0.447, -0.542, 0.464, -0.548, 0.482, -0.547, 0.497, -0.537, 0.512, -0.528, 0.521, -0.513, 0.523, -0.495, 0.521, -0.477, 0.514, -0.460, 0.501, -0.449, 0.487, -0.437, 0.471, -0.429, 0.456, -0.419, 0.441, -0.409, 0.426, -0.400, 0.410, -0.391, 0.395, -0.382, 0.379, -0.373, 0.363, -0.365, 0.348, -0.355, 0.333, -0.346, 0.316, -0.339, 0.301, -0.329, 0.286, -0.320, 0.271, -0.310, 0.254, -0.303, 0.239, -0.294, 0.224, -0.283, 0.209, -0.275, 0.193, -0.266, 0.178, -0.257, 0.161, -0.249, 0.145, -0.243, 0.127, -0.238, 0.109, -0.238, 0.093, -0.245, 0.078, -0.255, 0.069, -0.271],
+ "O": [-0.264, 0.469, -0.263, 0.441, -0.260, 0.414, -0.251, 0.388, -0.245, 0.361, -0.234, 0.335, -0.222, 0.311, -0.207, 0.288, -0.190, 0.265, -0.172, 0.245, -0.152, 0.226, -0.129, 0.210, -0.107, 0.194, -0.081, 0.185, -0.054, 0.177, -0.027, 0.174, 0.001, 0.170, 0.028, 0.171, 0.055, 0.177, 0.081, 0.185, 0.108, 0.194, 0.130, 0.210, 0.153, 0.225, 0.173, 0.244, 0.192, 0.264, 0.208, 0.286, 0.222, 0.311, 0.235, 0.335, 0.246, 0.360, 0.251, 0.387, 0.258, 0.414, 0.261, 0.441, 0.262, 0.469, 0.261, 0.497, 0.257, 0.524, 0.252, 0.551, 0.246, 0.578, 0.233, 0.602, 0.220, 0.626, 0.204, 0.649, 0.188, 0.672, 0.170, 0.693, 0.150, 0.711, 0.128, 0.728, 0.104, 0.741, 0.078, 0.751, 0.052, 0.761, 0.025, 0.765, -0.003, 0.766, -0.030, 0.765, -0.058, 0.762, -0.084, 0.755, -0.109, 0.744, -0.134, 0.731, -0.154, 0.712, -0.175, 0.694, -0.194, 0.674, -0.209, 0.651, -0.223, 0.627, -0.236, 0.603, -0.246, 0.577, -0.253, 0.551, -0.261, 0.524, -0.263, 0.497],
+ "frown": [-0.398, 0.532, -0.391, 0.503, -0.377, 0.478, -0.357, 0.457, -0.335, 0.438, -0.312, 0.421, -0.287, 0.405, -0.261, 0.393, -0.234, 0.381, -0.207, 0.372, -0.179, 0.362, -0.152, 0.353, -0.124, 0.344, -0.095, 0.339, -0.067, 0.335, -0.038, 0.331, -0.009, 0.330, 0.020, 0.330, 0.049, 0.330, 0.078, 0.331, 0.107, 0.335, 0.136, 0.340, 0.164, 0.345, 0.192, 0.354, 0.219, 0.364, 0.247, 0.374, 0.272, 0.388, 0.298, 0.401, 0.322, 0.418, 0.345, 0.435, 0.367, 0.454, 0.387, 0.476, 0.401, 0.501, 0.405, 0.529, 0.399, 0.558, 0.379, 0.578, 0.351, 0.584, 0.322, 0.581, 0.296, 0.568, 0.271, 0.554, 0.245, 0.539, 0.220, 0.526, 0.192, 0.516, 0.166, 0.504, 0.138, 0.496, 0.109, 0.490, 0.080, 0.488, 0.051, 0.485, 0.022, 0.485, -0.007, 0.485, -0.036, 0.488, -0.065, 0.491, -0.094, 0.494, -0.122, 0.501, -0.149, 0.511, -0.177, 0.520, -0.204, 0.530, -0.230, 0.543, -0.256, 0.555, -0.283, 0.565, -0.310, 0.578, -0.338, 0.582, -0.367, 0.578, -0.389, 0.559],
+ "dot": [0.070, 0.362, 0.070, 0.350, 0.072, 0.338, 0.075, 0.327, 0.080, 0.316, 0.085, 0.305, 0.091, 0.295, 0.098, 0.285, 0.106, 0.277, 0.116, 0.270, 0.125, 0.263, 0.134, 0.255, 0.145, 0.251, 0.157, 0.248, 0.168, 0.245, 0.180, 0.244, 0.192, 0.243, 0.204, 0.244, 0.215, 0.246, 0.227, 0.248, 0.238, 0.252, 0.248, 0.259, 0.257, 0.266, 0.267, 0.273, 0.276, 0.281, 0.283, 0.290, 0.290, 0.300, 0.295, 0.311, 0.299, 0.322, 0.303, 0.333, 0.306, 0.344, 0.307, 0.356, 0.307, 0.368, 0.306, 0.380, 0.305, 0.392, 0.300, 0.403, 0.296, 0.413, 0.291, 0.424, 0.285, 0.434, 0.278, 0.444, 0.271, 0.454, 0.262, 0.461, 0.252, 0.467, 0.241, 0.473, 0.230, 0.478, 0.220, 0.483, 0.209, 0.487, 0.197, 0.488, 0.185, 0.488, 0.173, 0.487, 0.162, 0.485, 0.151, 0.480, 0.140, 0.476, 0.129, 0.470, 0.119, 0.464, 0.109, 0.458, 0.100, 0.450, 0.094, 0.440, 0.088, 0.429, 0.083, 0.418, 0.079, 0.408, 0.073, 0.397, 0.071, 0.385, 0.070, 0.374],
+ "D": [-0.551, 0.246, -0.540, 0.204, -0.513, 0.170, -0.475, 0.149, -0.433, 0.140, -0.389, 0.142, -0.346, 0.148, -0.305, 0.160, -0.263, 0.172, -0.221, 0.184, -0.179, 0.191, -0.136, 0.200, -0.093, 0.206, -0.050, 0.209, -0.006, 0.209, 0.037, 0.208, 0.080, 0.206, 0.122, 0.195, 0.165, 0.189, 0.208, 0.179, 0.249, 0.166, 0.290, 0.152, 0.332, 0.139, 0.374, 0.130, 0.417, 0.130, 0.460, 0.136, 0.497, 0.160, 0.522, 0.195, 0.533, 0.237, 0.532, 0.280, 0.524, 0.323, 0.511, 0.364, 0.493, 0.404, 0.470, 0.441, 0.447, 0.478, 0.421, 0.512, 0.391, 0.544, 0.359, 0.573, 0.324, 0.598, 0.288, 0.622, 0.250, 0.644, 0.211, 0.663, 0.170, 0.677, 0.128, 0.687, 0.085, 0.697, 0.042, 0.700, -0.001, 0.700, -0.045, 0.698, -0.087, 0.689, -0.130, 0.683, -0.172, 0.673, -0.213, 0.657, -0.253, 0.640, -0.291, 0.619, -0.328, 0.597, -0.364, 0.572, -0.397, 0.545, -0.429, 0.515, -0.458, 0.483, -0.484, 0.448, -0.507, 0.411, -0.525, 0.372, -0.541, 0.332, -0.550, 0.289],
+ "zig": [-0.564, 0.557, -0.544, 0.517, -0.516, 0.481, -0.485, 0.448, -0.455, 0.416, -0.421, 0.386, -0.381, 0.365, -0.337, 0.368, -0.298, 0.390, -0.262, 0.417, -0.228, 0.446, -0.193, 0.474, -0.156, 0.452, -0.126, 0.419, -0.094, 0.387, -0.059, 0.359, -0.017, 0.343, 0.027, 0.349, 0.065, 0.372, 0.100, 0.400, 0.133, 0.430, 0.173, 0.450, 0.207, 0.423, 0.240, 0.391, 0.273, 0.362, 0.311, 0.337, 0.355, 0.334, 0.395, 0.353, 0.430, 0.381, 0.464, 0.411, 0.497, 0.442, 0.529, 0.473, 0.550, 0.512, 0.541, 0.555, 0.501, 0.573, 0.460, 0.557, 0.428, 0.525, 0.397, 0.493, 0.364, 0.462, 0.321, 0.456, 0.290, 0.489, 0.257, 0.520, 0.226, 0.552, 0.188, 0.575, 0.143, 0.572, 0.105, 0.547, 0.073, 0.517, 0.040, 0.486, 0.004, 0.459, -0.036, 0.479, -0.069, 0.509, -0.101, 0.540, -0.135, 0.570, -0.173, 0.593, -0.217, 0.585, -0.256, 0.562, -0.291, 0.534, -0.325, 0.505, -0.364, 0.482, -0.400, 0.507, -0.431, 0.539, -0.461, 0.572, -0.497, 0.598, -0.541, 0.595],
+ "yawn": [-0.242, 0.499, -0.239, 0.475, -0.235, 0.451, -0.229, 0.427, -0.217, 0.406, -0.208, 0.383, -0.198, 0.361, -0.181, 0.343, -0.167, 0.323, -0.150, 0.306, -0.130, 0.291, -0.112, 0.275, -0.090, 0.263, -0.069, 0.250, -0.047, 0.239, -0.024, 0.233, 0, 0.228, 0.024, 0.223, 0.049, 0.222, 0.073, 0.222, 0.097, 0.225, 0.121, 0.230, 0.145, 0.237, 0.167, 0.247, 0.189, 0.258, 0.210, 0.270, 0.228, 0.287, 0.246, 0.303, 0.261, 0.323, 0.275, 0.343, 0.285, 0.365, 0.293, 0.388, 0.301, 0.411, 0.306, 0.435, 0.308, 0.460, 0.307, 0.484, 0.300, 0.508, 0.286, 0.528, 0.268, 0.544, 0.246, 0.555, 0.222, 0.562, 0.198, 0.563, 0.174, 0.558, 0.150, 0.552, 0.126, 0.549, 0.101, 0.549, 0.077, 0.551, 0.054, 0.559, 0.031, 0.568, 0.010, 0.580, -0.010, 0.594, -0.030, 0.609, -0.048, 0.625, -0.069, 0.638, -0.092, 0.646, -0.116, 0.651, -0.141, 0.648, -0.164, 0.641, -0.185, 0.628, -0.204, 0.612, -0.217, 0.592, -0.231, 0.572, -0.236, 0.548, -0.240, 0.524],
+ "winkMouth": [-0.370, 0.352, -0.346, 0.319, -0.306, 0.313, -0.266, 0.323, -0.227, 0.334, -0.187, 0.343, -0.146, 0.348, -0.105, 0.353, -0.065, 0.354, -0.024, 0.352, 0.017, 0.346, 0.057, 0.338, 0.096, 0.325, 0.135, 0.313, 0.173, 0.297, 0.209, 0.278, 0.244, 0.257, 0.276, 0.232, 0.307, 0.205, 0.337, 0.177, 0.365, 0.147, 0.390, 0.115, 0.412, 0.080, 0.432, 0.044, 0.447, 0.006, 0.467, -0.029, 0.504, -0.045, 0.540, -0.028, 0.550, 0.011, 0.540, 0.051, 0.522, 0.088, 0.504, 0.124, 0.481, 0.158, 0.461, 0.194, 0.435, 0.225, 0.407, 0.256, 0.383, 0.288, 0.394, 0.327, 0.420, 0.359, 0.442, 0.393, 0.458, 0.431, 0.452, 0.471, 0.416, 0.487, 0.383, 0.462, 0.359, 0.429, 0.337, 0.394, 0.312, 0.362, 0.272, 0.362, 0.237, 0.383, 0.200, 0.400, 0.163, 0.417, 0.124, 0.430, 0.085, 0.441, 0.044, 0.447, 0.003, 0.452, -0.037, 0.456, -0.078, 0.455, -0.119, 0.454, -0.160, 0.450, -0.201, 0.446, -0.240, 0.436, -0.279, 0.423, -0.318, 0.410, -0.353, 0.389],
+ "tongue": [0.149, 0.423, 0.166, 0.402, 0.188, 0.386, 0.211, 0.371, 0.234, 0.356, 0.261, 0.351, 0.281, 0.332, 0.308, 0.331, 0.327, 0.350, 0.346, 0.370, 0.359, 0.394, 0.376, 0.415, 0.389, 0.440, 0.407, 0.460, 0.430, 0.464, 0.438, 0.439, 0.425, 0.415, 0.414, 0.390, 0.403, 0.366, 0.384, 0.346, 0.366, 0.326, 0.357, 0.301, 0.367, 0.277, 0.383, 0.255, 0.397, 0.232, 0.416, 0.212, 0.435, 0.193, 0.457, 0.179, 0.481, 0.189, 0.498, 0.210, 0.517, 0.230, 0.535, 0.251, 0.550, 0.273, 0.565, 0.296, 0.579, 0.320, 0.592, 0.344, 0.600, 0.370, 0.608, 0.396, 0.614, 0.423, 0.616, 0.450, 0.613, 0.478, 0.607, 0.504, 0.599, 0.530, 0.590, 0.556, 0.574, 0.578, 0.557, 0.599, 0.536, 0.616, 0.511, 0.629, 0.486, 0.639, 0.459, 0.646, 0.432, 0.648, 0.405, 0.649, 0.378, 0.645, 0.351, 0.636, 0.326, 0.627, 0.302, 0.614, 0.281, 0.596, 0.262, 0.576, 0.240, 0.559, 0.225, 0.536, 0.207, 0.515, 0.194, 0.492, 0.177, 0.470, 0.167, 0.444],
+ "wavy": [-0.493, 0.593, -0.487, 0.547, -0.470, 0.504, -0.445, 0.466, -0.412, 0.433, -0.374, 0.407, -0.331, 0.390, -0.286, 0.386, -0.240, 0.389, -0.196, 0.403, -0.155, 0.424, -0.113, 0.444, -0.068, 0.453, -0.023, 0.445, 0.015, 0.419, 0.044, 0.383, 0.068, 0.344, 0.097, 0.308, 0.129, 0.275, 0.167, 0.249, 0.210, 0.232, 0.255, 0.224, 0.301, 0.229, 0.345, 0.242, 0.388, 0.258, 0.430, 0.278, 0.473, 0.293, 0.519, 0.288, 0.559, 0.265, 0.581, 0.225, 0.614, 0.193, 0.659, 0.196, 0.680, 0.237, 0.668, 0.281, 0.646, 0.321, 0.615, 0.356, 0.577, 0.382, 0.534, 0.398, 0.488, 0.401, 0.442, 0.396, 0.399, 0.380, 0.357, 0.360, 0.315, 0.341, 0.270, 0.332, 0.225, 0.338, 0.185, 0.361, 0.155, 0.396, 0.130, 0.435, 0.104, 0.472, 0.071, 0.505, 0.033, 0.531, -0.009, 0.549, -0.055, 0.554, -0.101, 0.552, -0.145, 0.538, -0.187, 0.519, -0.227, 0.497, -0.272, 0.488, -0.318, 0.491, -0.358, 0.514, -0.385, 0.551, -0.401, 0.594, -0.427, 0.632, -0.471, 0.632],
+ "spiralL": [-0.761, -0.153, -0.761, -0.177, -0.759, -0.200, -0.755, -0.224, -0.749, -0.247, -0.741, -0.269, -0.732, -0.291, -0.721, -0.312, -0.708, -0.331, -0.694, -0.351, -0.678, -0.368, -0.662, -0.385, -0.644, -0.402, -0.626, -0.416, -0.606, -0.429, -0.586, -0.441, -0.565, -0.452, -0.543, -0.461, -0.521, -0.469, -0.498, -0.474, -0.474, -0.476, -0.450, -0.477, -0.427, -0.477, -0.403, -0.475, -0.380, -0.471, -0.358, -0.463, -0.336, -0.454, -0.314, -0.444, -0.294, -0.432, -0.275, -0.418, -0.256, -0.403, -0.240, -0.386, -0.224, -0.368, -0.210, -0.349, -0.197, -0.330, -0.186, -0.308, -0.176, -0.287, -0.166, -0.265, -0.160, -0.243, -0.157, -0.219, -0.156, -0.195, -0.158, -0.172, -0.160, -0.148, -0.166, -0.125, -0.176, -0.104, -0.186, -0.082, -0.198, -0.062, -0.213, -0.044, -0.230, -0.027, -0.249, -0.013, -0.269, 0, -0.290, 0.011, -0.312, 0.020, -0.334, 0.029, -0.356, 0.035, -0.380, 0.037, -0.404, 0.037, -0.427, 0.035, -0.450, 0.030, -0.473, 0.022, -0.495, 0.014, -0.516, 0.003, -0.534, -0.011, -0.552, -0.028, -0.567, -0.046, -0.581, -0.065, -0.592, -0.086, -0.602, -0.107, -0.609, -0.130, -0.611, -0.153, -0.611, -0.177, -0.606, -0.200, -0.597, -0.222, -0.587, -0.244, -0.574, -0.264, -0.558, -0.281, -0.540, -0.296, -0.520, -0.308, -0.499, -0.319, -0.476, -0.324, -0.452, -0.327, -0.429, -0.326, -0.405, -0.322, -0.384, -0.312, -0.363, -0.301, -0.345, -0.286, -0.330, -0.268, -0.318, -0.248, -0.311, -0.225, -0.311, -0.201, -0.315, -0.178, -0.325, -0.157, -0.340, -0.139, -0.359, -0.124, -0.381, -0.116, -0.404, -0.114, -0.427, -0.120, -0.448, -0.132, -0.464, -0.148, -0.472, -0.170, -0.465, -0.192, -0.443, -0.199, -0.420, -0.193, -0.397, -0.191, -0.384, -0.210, -0.391, -0.232, -0.409, -0.247, -0.432, -0.253, -0.456, -0.252, -0.479, -0.246, -0.499, -0.233, -0.516, -0.217, -0.526, -0.196, -0.533, -0.173, -0.535, -0.150, -0.531, -0.127, -0.522, -0.105, -0.509, -0.085, -0.492, -0.069, -0.472, -0.055, -0.451, -0.045, -0.428, -0.039, -0.405, -0.036, -0.381, -0.036, -0.358, -0.039, -0.335, -0.047, -0.313, -0.056, -0.293, -0.068, -0.274, -0.082, -0.259, -0.100, -0.248, -0.121, -0.238, -0.143, -0.233, -0.166, -0.232, -0.189, -0.232, -0.213, -0.236, -0.236, -0.243, -0.259, -0.252, -0.281, -0.263, -0.302, -0.278, -0.320, -0.294, -0.338, -0.312, -0.354, -0.330, -0.369, -0.351, -0.380, -0.373, -0.389, -0.395, -0.397, -0.418, -0.403, -0.441, -0.405, -0.465, -0.404, -0.488, -0.400, -0.511, -0.393, -0.533, -0.384, -0.555, -0.374, -0.575, -0.362, -0.594, -0.349, -0.613, -0.334, -0.630, -0.317, -0.644, -0.299, -0.656, -0.278, -0.667, -0.257, -0.674, -0.235, -0.679, -0.211, -0.683, -0.188, -0.685, -0.165, -0.684, -0.141, -0.681, -0.117, -0.676, -0.094, -0.671, -0.071, -0.663, -0.049, -0.652, -0.028, -0.639, -0.008, -0.625, 0.011, -0.609, 0.029, -0.592, 0.045, -0.573, 0.059, -0.553, 0.071, -0.532, 0.082, -0.509, 0.090, -0.486, 0.096, -0.463, 0.099, -0.439, 0.100, -0.416, 0.100, -0.392, 0.099, -0.368, 0.096, -0.345, 0.090, -0.323, 0.082, -0.302, 0.073, -0.278, 0.069, -0.256, 0.076, -0.244, 0.096, -0.248, 0.119, -0.266, 0.135, -0.286, 0.147, -0.308, 0.156, -0.331, 0.162, -0.354, 0.169, -0.377, 0.172, -0.401, 0.172, -0.425, 0.172, -0.448, 0.172, -0.472, 0.172, -0.495, 0.170, -0.519, 0.165, -0.541, 0.158, -0.563, 0.149, -0.584, 0.137, -0.604, 0.125, -0.623, 0.111, -0.641, 0.096, -0.658, 0.080, -0.674, 0.062, -0.689, 0.044, -0.703, 0.025, -0.715, 0.004, -0.727, -0.016, -0.736, -0.038, -0.744, -0.060, -0.750, -0.083, -0.756, -0.106, -0.760, -0.129],
+ "spiralR": [0.008, -0.335, 0.009, -0.358, 0.013, -0.380, 0.019, -0.403, 0.025, -0.425, 0.035, -0.446, 0.046, -0.466, 0.059, -0.485, 0.073, -0.503, 0.088, -0.521, 0.104, -0.537, 0.121, -0.553, 0.139, -0.567, 0.158, -0.580, 0.178, -0.592, 0.199, -0.602, 0.220, -0.611, 0.242, -0.619, 0.264, -0.625, 0.287, -0.629, 0.310, -0.631, 0.333, -0.632, 0.356, -0.632, 0.379, -0.630, 0.401, -0.628, 0.424, -0.623, 0.446, -0.615, 0.467, -0.607, 0.488, -0.597, 0.508, -0.585, 0.527, -0.572, 0.545, -0.558, 0.563, -0.543, 0.579, -0.527, 0.593, -0.509, 0.607, -0.490, 0.620, -0.471, 0.630, -0.451, 0.640, -0.430, 0.649, -0.409, 0.656, -0.387, 0.661, -0.364, 0.664, -0.341, 0.662, -0.318, 0.651, -0.299, 0.629, -0.293, 0.608, -0.302, 0.597, -0.322, 0.591, -0.344, 0.585, -0.366, 0.578, -0.389, 0.571, -0.410, 0.561, -0.431, 0.547, -0.450, 0.534, -0.468, 0.518, -0.485, 0.501, -0.501, 0.482, -0.514, 0.463, -0.526, 0.442, -0.536, 0.420, -0.544, 0.398, -0.551, 0.376, -0.555, 0.353, -0.557, 0.330, -0.558, 0.307, -0.556, 0.284, -0.554, 0.262, -0.547, 0.240, -0.539, 0.219, -0.530, 0.199, -0.519, 0.179, -0.506, 0.161, -0.492, 0.144, -0.476, 0.129, -0.459, 0.116, -0.440, 0.104, -0.420, 0.095, -0.399, 0.088, -0.377, 0.084, -0.355, 0.083, -0.332, 0.083, -0.309, 0.084, -0.286, 0.088, -0.263, 0.095, -0.241, 0.104, -0.220, 0.113, -0.199, 0.127, -0.180, 0.142, -0.163, 0.158, -0.147, 0.175, -0.131, 0.194, -0.117, 0.214, -0.107, 0.236, -0.098, 0.258, -0.091, 0.280, -0.086, 0.303, -0.085, 0.326, -0.087, 0.349, -0.092, 0.370, -0.100, 0.391, -0.111, 0.410, -0.124, 0.426, -0.139, 0.441, -0.157, 0.454, -0.176, 0.464, -0.197, 0.471, -0.219, 0.474, -0.242, 0.474, -0.265, 0.470, -0.288, 0.463, -0.309, 0.453, -0.330, 0.442, -0.350, 0.427, -0.368, 0.409, -0.382, 0.389, -0.393, 0.368, -0.402, 0.345, -0.407, 0.322, -0.407, 0.299, -0.404, 0.278, -0.394, 0.261, -0.379, 0.246, -0.362, 0.236, -0.341, 0.233, -0.318, 0.234, -0.295, 0.242, -0.274, 0.256, -0.256, 0.276, -0.244, 0.299, -0.241, 0.319, -0.251, 0.324, -0.273, 0.317, -0.295, 0.316, -0.318, 0.332, -0.334, 0.355, -0.335, 0.375, -0.325, 0.390, -0.308, 0.398, -0.286, 0.399, -0.263, 0.397, -0.240, 0.389, -0.219, 0.375, -0.201, 0.357, -0.186, 0.337, -0.176, 0.315, -0.169, 0.292, -0.167, 0.269, -0.169, 0.247, -0.175, 0.226, -0.185, 0.207, -0.198, 0.191, -0.215, 0.178, -0.234, 0.169, -0.255, 0.163, -0.277, 0.161, -0.300, 0.161, -0.323, 0.163, -0.346, 0.170, -0.368, 0.179, -0.389, 0.191, -0.408, 0.206, -0.427, 0.222, -0.443, 0.241, -0.456, 0.261, -0.467, 0.283, -0.475, 0.305, -0.479, 0.328, -0.481, 0.351, -0.480, 0.374, -0.478, 0.397, -0.473, 0.418, -0.464, 0.438, -0.453, 0.457, -0.440, 0.475, -0.425, 0.492, -0.409, 0.506, -0.391, 0.517, -0.371, 0.529, -0.351, 0.537, -0.330, 0.542, -0.307, 0.547, -0.285, 0.549, -0.262, 0.549, -0.239, 0.546, -0.216, 0.541, -0.193, 0.535, -0.171, 0.526, -0.150, 0.514, -0.130, 0.501, -0.111, 0.486, -0.094, 0.469, -0.077, 0.452, -0.063, 0.433, -0.050, 0.412, -0.040, 0.391, -0.030, 0.369, -0.023, 0.346, -0.019, 0.324, -0.015, 0.301, -0.014, 0.278, -0.015, 0.255, -0.018, 0.232, -0.021, 0.210, -0.027, 0.189, -0.037, 0.168, -0.047, 0.148, -0.058, 0.130, -0.072, 0.113, -0.088, 0.097, -0.104, 0.082, -0.122, 0.067, -0.140, 0.054, -0.159, 0.044, -0.179, 0.033, -0.200, 0.025, -0.221, 0.018, -0.243, 0.013, -0.266, 0.011, -0.289, 0.010, -0.312],
+ "smile": [-0.250, 0.355, -0.245, 0.338, -0.231, 0.326, -0.214, 0.324, -0.196, 0.327, -0.179, 0.335, -0.163, 0.341, -0.146, 0.348, -0.130, 0.357, -0.113, 0.363, -0.096, 0.369, -0.079, 0.374, -0.062, 0.379, -0.044, 0.381, -0.026, 0.383, -0.008, 0.384, 0.010, 0.384, 0.028, 0.384, 0.046, 0.383, 0.064, 0.381, 0.082, 0.377, 0.099, 0.372, 0.115, 0.365, 0.132, 0.359, 0.148, 0.351, 0.164, 0.342, 0.179, 0.333, 0.196, 0.325, 0.214, 0.323, 0.231, 0.326, 0.244, 0.339, 0.247, 0.357, 0.245, 0.375, 0.236, 0.390, 0.224, 0.404, 0.210, 0.415, 0.195, 0.426, 0.181, 0.436, 0.165, 0.445, 0.149, 0.453, 0.132, 0.459, 0.115, 0.466, 0.098, 0.471, 0.080, 0.474, 0.062, 0.478, 0.045, 0.480, 0.027, 0.481, 0.009, 0.481, -0.009, 0.481, -0.027, 0.480, -0.045, 0.477, -0.063, 0.475, -0.081, 0.472, -0.098, 0.466, -0.115, 0.461, -0.132, 0.455, -0.149, 0.449, -0.165, 0.441, -0.182, 0.434, -0.197, 0.424, -0.212, 0.414, -0.225, 0.402, -0.237, 0.389, -0.246, 0.373],
+ "flat": [-0.172, 0.452, -0.170, 0.439, -0.167, 0.426, -0.162, 0.414, -0.153, 0.404, -0.141, 0.398, -0.128, 0.396, -0.115, 0.396, -0.102, 0.394, -0.089, 0.393, -0.076, 0.392, -0.063, 0.391, -0.050, 0.389, -0.037, 0.387, -0.024, 0.385, -0.011, 0.384, 0.002, 0.382, 0.015, 0.381, 0.028, 0.378, 0.041, 0.376, 0.054, 0.373, 0.067, 0.371, 0.080, 0.370, 0.093, 0.369, 0.106, 0.368, 0.120, 0.367, 0.133, 0.367, 0.146, 0.370, 0.156, 0.378, 0.163, 0.389, 0.168, 0.401, 0.171, 0.414, 0.171, 0.427, 0.170, 0.440, 0.166, 0.452, 0.160, 0.464, 0.152, 0.474, 0.141, 0.482, 0.129, 0.487, 0.116, 0.488, 0.103, 0.489, 0.090, 0.490, 0.076, 0.491, 0.063, 0.492, 0.050, 0.493, 0.037, 0.495, 0.024, 0.496, 0.011, 0.498, -0.002, 0.499, -0.015, 0.500, -0.028, 0.501, -0.041, 0.502, -0.054, 0.504, -0.067, 0.506, -0.080, 0.508, -0.093, 0.510, -0.106, 0.512, -0.119, 0.514, -0.132, 0.514, -0.145, 0.509, -0.154, 0.500, -0.163, 0.490, -0.168, 0.478, -0.171, 0.465],
+ "qHook": [1.377, -1.555, 1.384, -1.588, 1.400, -1.618, 1.422, -1.644, 1.447, -1.666, 1.476, -1.684, 1.509, -1.694, 1.542, -1.701, 1.575, -1.706, 1.609, -1.712, 1.642, -1.719, 1.672, -1.734, 1.698, -1.756, 1.714, -1.786, 1.719, -1.819, 1.712, -1.853, 1.697, -1.883, 1.672, -1.906, 1.642, -1.921, 1.609, -1.927, 1.575, -1.922, 1.547, -1.903, 1.524, -1.878, 1.502, -1.853, 1.470, -1.840, 1.439, -1.853, 1.422, -1.882, 1.423, -1.916, 1.433, -1.948, 1.454, -1.975, 1.480, -1.997, 1.508, -2.016, 1.539, -2.029, 1.572, -2.037, 1.606, -2.039, 1.640, -2.038, 1.674, -2.032, 1.705, -2.019, 1.734, -2.002, 1.761, -1.981, 1.786, -1.958, 1.807, -1.932, 1.823, -1.902, 1.834, -1.870, 1.840, -1.836, 1.840, -1.802, 1.835, -1.769, 1.825, -1.736, 1.810, -1.706, 1.792, -1.677, 1.768, -1.654, 1.741, -1.633, 1.711, -1.617, 1.679, -1.605, 1.647, -1.595, 1.613, -1.589, 1.580, -1.583, 1.547, -1.578, 1.515, -1.564, 1.493, -1.539, 1.472, -1.512, 1.443, -1.495, 1.410, -1.499, 1.385, -1.522],
+ "qDot": [1.281, -1.348, 1.282, -1.366, 1.288, -1.383, 1.297, -1.399, 1.309, -1.412, 1.324, -1.422, 1.341, -1.428, 1.359, -1.430, 1.376, -1.426, 1.392, -1.417, 1.405, -1.404, 1.414, -1.389, 1.419, -1.371, 1.419, -1.353, 1.415, -1.336, 1.405, -1.321, 1.393, -1.307, 1.378, -1.297, 1.361, -1.292, 1.343, -1.292, 1.325, -1.295, 1.309, -1.303, 1.296, -1.316, 1.286, -1.331],
+ "dotC": [-0.119, 0.447, -0.118, 0.435, -0.117, 0.423, -0.113, 0.412, -0.108, 0.401, -0.104, 0.390, -0.097, 0.380, -0.091, 0.370, -0.083, 0.362, -0.073, 0.355, -0.063, 0.348, -0.054, 0.341, -0.043, 0.336, -0.032, 0.333, -0.020, 0.330, -0.008, 0.329, 0.004, 0.329, 0.015, 0.329, 0.027, 0.331, 0.039, 0.333, 0.050, 0.337, 0.060, 0.344, 0.069, 0.352, 0.079, 0.358, 0.088, 0.366, 0.095, 0.375, 0.101, 0.385, 0.106, 0.396, 0.111, 0.407, 0.114, 0.418, 0.117, 0.429, 0.118, 0.441, 0.119, 0.453, 0.118, 0.465, 0.116, 0.477, 0.112, 0.488, 0.107, 0.498, 0.103, 0.509, 0.096, 0.519, 0.090, 0.529, 0.083, 0.539, 0.073, 0.546, 0.063, 0.552, 0.053, 0.558, 0.042, 0.563, 0.031, 0.568, 0.020, 0.572, 0.008, 0.573, -0.003, 0.573, -0.015, 0.572, -0.027, 0.570, -0.038, 0.565, -0.049, 0.561, -0.059, 0.555, -0.069, 0.549, -0.080, 0.543, -0.088, 0.535, -0.094, 0.525, -0.100, 0.514, -0.105, 0.504, -0.110, 0.493, -0.115, 0.482, -0.117, 0.470, -0.118, 0.459],
+ "Dtalk": [-0.364, 0.387, -0.357, 0.359, -0.339, 0.336, -0.314, 0.323, -0.286, 0.317, -0.257, 0.318, -0.229, 0.322, -0.201, 0.330, -0.174, 0.338, -0.146, 0.346, -0.118, 0.351, -0.090, 0.356, -0.061, 0.361, -0.033, 0.362, -0.004, 0.362, 0.024, 0.362, 0.053, 0.360, 0.081, 0.353, 0.109, 0.349, 0.137, 0.343, 0.164, 0.334, 0.191, 0.325, 0.219, 0.316, 0.247, 0.310, 0.276, 0.310, 0.304, 0.314, 0.328, 0.330, 0.345, 0.353, 0.352, 0.381, 0.351, 0.409, 0.346, 0.438, 0.337, 0.465, 0.325, 0.491, 0.310, 0.516, 0.295, 0.540, 0.278, 0.562, 0.258, 0.583, 0.237, 0.603, 0.214, 0.619, 0.190, 0.635, 0.165, 0.650, 0.139, 0.662, 0.112, 0.671, 0.084, 0.678, 0.056, 0.684, 0.028, 0.687, -0.001, 0.686, -0.029, 0.685, -0.057, 0.679, -0.086, 0.675, -0.114, 0.668, -0.140, 0.658, -0.167, 0.647, -0.192, 0.633, -0.216, 0.618, -0.240, 0.602, -0.262, 0.584, -0.283, 0.564, -0.302, 0.543, -0.319, 0.520, -0.334, 0.496, -0.347, 0.470, -0.357, 0.443, -0.363, 0.415],
+ ]
+ private static let glyphs: [String: [P2]] = raw.mapValues { v in stride(from: 0, to: v.count - 1, by: 2).map { P2(v[$0], v[$0 + 1]) } }
+ static func glyph(_ n: String) -> [P2] { glyphs[n] ?? glyphs["smile"]! }
+}
diff --git a/app/ChumsWatch/Rig/Renderer.swift b/app/ChumsWatch/Rig/Renderer.swift
new file mode 100644
index 0000000..f8cc2c3
--- /dev/null
+++ b/app/ChumsWatch/Rig/Renderer.swift
@@ -0,0 +1,200 @@
+import SwiftUI
+#if os(watchOS)
+import WatchKit
+#else
+import UIKit
+#endif
+
+/// Draws one frame of the rig into a Canvas, in the 198 × 242 design space scaled to the screen.
+enum Renderer {
+ /// Scale and offset that fit the design space into `size`, centered.
+ static func fit(_ size: CGSize) -> (s: Double, ox: Double, oy: Double) {
+ let s = min(size.width / DESIGN.width, size.height / DESIGN.height)
+ return (s, (size.width - DESIGN.width * s) / 2, (size.height - DESIGN.height * s) / 2)
+ }
+
+ static func draw(_ r: Rig, _ context: GraphicsContext, size: CGSize) {
+ var ctx = context
+ ctx.fill(Path(CGRect(origin: .zero, size: size)), with: .color(.black))
+ let f = fit(size)
+ ctx.translateBy(x: f.ox, y: f.oy); ctx.scaleBy(x: f.s, y: f.s)
+ let p = r.pose()
+#if os(watchOS)
+ r.pixelScale = f.s * WKInterfaceDevice.current().screenScale
+#else
+ r.pixelScale = f.s * context.environment.displayScale // the screen's, or a picture's (the widgets)
+#endif
+ if let st = r.staged { drawStaged(r, st, ctx); return }
+ let worldOn = r.worlds.worldOn(r)
+ if !r.ao && r.chrome { drawLabel(r, ctx) }
+ // shaken, the scene judders (whole pixels); the words and buttons around it stay still
+ var scene = ctx
+ let q = r.worlds.quake(r); if q != .zero { scene.translateBy(x: q.x, y: q.y) }
+ r.worlds.drawBack(r, scene, p)
+ Characters.draw(r, p.fade > 0 ? scene.faded(max(0, 1 - p.fade)) : scene, p)
+ guard !r.ao else { return }
+ r.worlds.drawFront(r, scene, p)
+ if !r.character.gridded && !worldOn { Characters.drawProps(r, scene, p) }
+ if r.state == .working && !worldOn { Characters.drawTyping(r, scene, pixel: r.character.gridded) }
+ if r.state == .subagents && !worldOn { Characters.drawHelpers(r, scene, p) }
+ guard r.chrome else { return }
+ if r.state == .approval { drawApproval(r, ctx, compact: worldOn) }
+ drawCaption(r, ctx, worldOn: worldOn)
+ drawTalkBar(r, ctx)
+ }
+
+ /// Noodle and Pix fill the screen: they draw first, then what they share the screen with, then the settings dots
+ /// and status on top (with a shadow), then captions over a scrim so the text stays readable over them.
+ private static func drawStaged(_ r: Rig, _ st: Staged, _ ctx: GraphicsContext) {
+ st.draw(r, ctx)
+ guard !r.ao else { return }
+ st.front(r, ctx)
+ guard r.chrome else { return }
+ // the settings dots and the status go over everything it draws (its glass rings too), with a shadow
+ var shadowed = ctx; shadowed.addFilter(.shadow(color: .black.opacity(0.8), radius: 3)); drawLabel(r, shadowed)
+ drawTalkBar(r, ctx)
+ if r.state == .approval && !st.ownsApproval { drawApproval(r, ctx, compact: false) }
+ guard !r.caption.isEmpty && r.state != .approval && !st.ownsCaption(r) else { return }
+ let top = st.captionTop(r)
+ let scrim = Gradient(colors: top ? [.black.opacity(0.75), .black.opacity(0)] : [.black.opacity(0), .black.opacity(0.75)])
+ let band = top ? CGRect(x: 0, y: 30, width: 198, height: 70) : CGRect(x: 0, y: 160, width: 198, height: 82)
+ ctx.fill(Path(band), with: .linearGradient(scrim, startPoint: CGPoint(x: 0, y: band.minY), endPoint: CGPoint(x: 0, y: band.maxY)))
+ var c = ctx
+ if top { c.translateBy(x: 0, y: -142) }
+ drawCaption(r, c, worldOn: false)
+ }
+
+ /// The agents' faces at the top left, overlapping: the one you talk to in front, the others behind it, smaller and
+ /// a little dimmer, an amber ring on any that needs you. Then the status (WORKING, ASKS, TO NOODLE …), up to the clock.
+ private static func drawLabel(_ r: Rig, _ ctx: GraphicsContext) {
+ let B = SettingsButton.self
+ // back to front: the last one behind first, the one you talk to last
+ for (i, f) in r.faces.enumerated().reversed() {
+ let front = i == 0, R = front ? B.r : B.rBack, cx = B.x + (front ? 0 : B.r - B.rBack + Double(i) * B.step)
+ let circle = Path(ellipseIn: CGRect(x: cx - R, y: B.y - R, width: 2 * R, height: 2 * R))
+ ctx.fillCircle(cx, B.y, R + 1.6, .black) // a ring of the background between faces
+ var c = ctx; c.opacity *= front ? 1 : 0.8
+ c.fill(circle, with: .color(.black)) // the avatars are pictures on black
+ c.clip(to: circle)
+ let full = AgentFace.fullBleed.contains(f.character), pad = full ? 0 : R * 0.22
+ c.draw(Image("avatar-\(AgentFace.asset(f.character))").interpolation(full ? .high : .none),
+ in: CGRect(x: cx - R + pad, y: B.y - R + pad, width: 2 * (R - pad), height: 2 * (R - pad)))
+ ctx.stroke(circle, with: .color(f.needs ? Pal.amber : .white.opacity(0.16)), lineWidth: f.needs ? 1.6 : 0.5)
+ }
+ guard !r.label.isEmpty else { return }
+ let amber = r.state == .needs || r.state == .approval
+ let t = ctx.resolve(Text(r.label).font(.system(size: 9.5, weight: .medium, design: .monospaced)).foregroundColor(amber ? Pal.amber : Pal.gray))
+ ctx.draw(t, in: CGRect(x: B.labelX, y: B.y - 6.5, width: 128 - B.labelX, height: 13))
+ }
+
+ private static func text(_ ctx: GraphicsContext, _ s: String, _ rect: CGRect, size: Double, weight: Font.Weight = .medium,
+ mono: Bool = false, color: Color, align: Alignment = .center) {
+ let t = Text(s).font(.system(size: size, weight: weight, design: mono ? .monospaced : .default)).foregroundColor(color)
+ let resolved = ctx.resolve(t)
+ let m = resolved.measure(in: CGSize(width: rect.width, height: rect.height))
+ let x = align == .leading ? rect.minX : rect.midX - m.width / 2
+ ctx.draw(resolved, in: CGRect(x: x, y: rect.minY, width: min(m.width, rect.width), height: rect.height))
+ }
+
+ static func drawApproval(_ r: Rig, _ ctx: GraphicsContext, compact: Bool) {
+ if compact {
+ let y = 190.0
+ ctx.fillRoundRect(22, y, 154, 36, 10, Pal.card)
+ text(ctx, r.approvalTitle, CGRect(x: 34, y: y + 6, width: 130, height: 16), size: 13, mono: true, color: Pal.white, align: .leading)
+ ctx.fillRoundRect(34, y + 25, 130, 3, 1.5, Color(hex: 0x26292D))
+ if r.hold > 0 { ctx.fillRoundRect(34, y + 25, 130 * r.hold, 3, 1.5, Pal.amber) }
+ return
+ }
+ let k = clamp(r.stateT / 0.45, 0, 1), y = lerp(250, 118, outC(k))
+ ctx.fillRoundRect(14, y, 170, 66, 14, Pal.card)
+ text(ctx, r.approvalTitle, CGRect(x: 28, y: y + 12, width: 142, height: 19), size: 15, mono: true, color: Pal.white, align: .leading)
+ text(ctx, r.approvalDetail, CGRect(x: 28, y: y + 33, width: 142, height: 15), size: 11.5, weight: .regular, color: Pal.gray, align: .leading)
+ guard r.cardControls else { return }
+ ctx.fillRoundRect(28, y + 54, 142, 3, 1.5, Color(hex: 0x26292D))
+ if r.hold > 0 { ctx.fillRoundRect(28, y + 54, 142 * r.hold, 3, 1.5, Pal.amber) }
+ ctx.fillCircle(36, 210, 13, Color(hex: 0x1A1C1F))
+ ctx.strokeLine(31.5, 205.5, 40.5, 214.5, Pal.gray, 1.8); ctx.strokeLine(40.5, 205.5, 31.5, 214.5, Pal.gray, 1.8)
+ text(ctx, r.hold > 0 ? "keep holding" : "hold to allow", CGRect(x: 56, y: 203, width: 112, height: 15), size: 11, mono: true,
+ color: r.hold > 0 ? Pal.amber : Pal.gray)
+ }
+
+ /// A caption in its box; when the whole reply doesn't fit, the box keeps its first lines (ending in …) and the
+ /// rest is in the conversation card the handle pulls up.
+ private static func fitted(_ r: Rig, _ ctx: GraphicsContext, _ s: String, full: String, _ rect: CGRect, size: Double, color: Color) {
+ let need = ctx.resolve(Text(full).font(.system(size: size, weight: .medium))).measure(in: CGSize(width: rect.width, height: 2000)).height
+ guard need > rect.height + 1 else { text(ctx, s, rect, size: size, color: color); return }
+ r.captionLong = true // the rest is in the conversation (the handle at the bottom)
+ text(ctx, s, rect, size: size, color: color)
+ }
+
+ /// While you talk, centered near the top, clear of your finger: × (slide left onto it and let go: canceled), a live
+ /// waveform of your voice, ✓ (slide right onto it, or just let go: sent). Plain colors; the one your finger is heading
+ /// to grows, the other fades back.
+ static func drawTalkBar(_ r: Rig, _ ctx0: GraphicsContext) {
+ guard r.state == .listening else { return }
+ var ctx = ctx0; ctx.addFilter(.shadow(color: .black.opacity(0.55), radius: 4))
+ let y = 64.0, cancelK = clamp(-r.talkSlide / Rig.armed, 0, 1), sendK = clamp(r.talkSlide / Rig.armed, 0, 1)
+ // ×: a gray circle, a white ×
+ let rx = 15 + 3 * cancelK
+ ctx.faded(1 - 0.5 * sendK).fillCircle(46, y, rx, Color(white: 0.3 + 0.12 * cancelK))
+ var x = Path(); let a = 4.6 + 0.9 * cancelK
+ x.move(to: CGPoint(x: 46 - a, y: y - a)); x.addLine(to: CGPoint(x: 46 + a, y: y + a))
+ x.move(to: CGPoint(x: 46 + a, y: y - a)); x.addLine(to: CGPoint(x: 46 - a, y: y + a))
+ ctx.faded(1 - 0.5 * sendK).stroke(x, with: .color(Pal.white), style: StrokeStyle(lineWidth: 2.2, lineCap: .round))
+ // ✓: a white circle, a black ✓
+ let rv = 15 + 3 * sendK
+ ctx.faded(1 - 0.5 * cancelK).fillCircle(152, y, rv, Pal.white)
+ var v = Path(); let b = 5.2 + 1 * sendK
+ v.move(to: CGPoint(x: 152 - b * 1.05, y: y + 0.3)); v.addLine(to: CGPoint(x: 152 - b * 0.3, y: y + b * 0.8)); v.addLine(to: CGPoint(x: 152 + b * 1.1, y: y - b * 0.85))
+ ctx.faded(1 - 0.5 * cancelK).stroke(v, with: .color(.black), style: StrokeStyle(lineWidth: 2.3, lineCap: .round, lineJoin: .round))
+ // the waveform: 11 bars, taller in the middle, moving with your voice (and a little even in a pause, so it's
+ // plainly listening)
+ let n = 11, w = 2.6, gap = 2.5, x0 = 99 - (Double(n) * w + Double(n - 1) * gap) / 2
+ var bars = Path()
+ for i in 0..<n {
+ let c = 1 - abs(Double(i) - Double(n - 1) / 2) / (Double(n) / 2) // 1 in the middle … ~0 at the ends
+ let wob = 0.5 + 0.5 * sin(r.t * (7.3 + Double(i) * 0.9) + Double(i) * 1.7)
+ let h = 3 + (0.12 + 0.88 * r.voice) * (6 + 15 * c) * (0.55 + 0.45 * wob)
+ let bx = x0 + Double(i) * (w + gap)
+ bars.addRoundedRect(in: CGRect(x: bx, y: y - h / 2, width: w, height: h), cornerSize: CGSize(width: w / 2, height: w / 2))
+ }
+ ctx.faded(1 - 0.35 * max(cancelK, 0)).fill(bars, with: .color(Pal.white))
+ }
+
+ static func drawCaption(_ r: Rig, _ ctx: GraphicsContext, worldOn: Bool) {
+ let shown: String
+ if r.captionShown >= Double(r.caption.count) { shown = r.caption }
+ else if r.captionShown <= 0 { shown = "" }
+ else { shown = String(r.caption.prefix(Int(r.captionShown))) }
+ r.captionLong = false
+ switch r.state {
+ case .listening:
+ break // no words: the talk bar at the top says it all
+ case .speaking, .done:
+ guard !shown.isEmpty else { return }
+ fitted(r, ctx, shown, full: r.caption, CGRect(x: 18, y: worldOn ? 188 : 176, width: 162, height: worldOn ? 50 : 62), size: 15, color: Pal.white)
+ case .needs:
+ fitted(r, ctx, r.caption, full: r.caption, CGRect(x: 18, y: 186, width: 162, height: 40), size: 14, color: Pal.white)
+ case .blocked:
+ text(ctx, r.caption, CGRect(x: 18, y: 182, width: 162, height: 36), size: 14, color: Pal.white)
+ if !r.subCaption.isEmpty { text(ctx, r.subCaption, CGRect(x: 18, y: 218, width: 162, height: 16), size: 13, weight: .regular, color: Pal.gray) }
+ case .sleep, .idle:
+ if !r.caption.isEmpty { text(ctx, r.caption, CGRect(x: 18, y: 192, width: 162, height: 36), size: 13, weight: .regular, color: Pal.gray) }
+ case .thinking, .working, .subagents:
+ // what you said, in quotes, while Claude works on it (the world's tool-call line steps aside meanwhile)
+ if !r.caption.isEmpty { text(ctx, r.caption, CGRect(x: 18, y: worldOn ? 204 : 186, width: 162, height: 36), size: 13, weight: .regular, color: Pal.white) }
+ default: break
+ }
+ }
+}
+
+/// The agents' faces at the top left, level with the clock, overlapping: the one you talk to in front, the others
+/// behind it (an amber ring on one that needs you). A tap opens the agents and, below them, settings. Drawn with the
+/// character (Renderer) and tapped through the character's own touch handling; the tap zone is the whole corner around
+/// them, generous for a fingertip (design points).
+enum SettingsButton {
+ static let x = 20.0, y = 24.0, r = 11.5 // the front face's center and radius
+ static let step = 15.5, rBack = 9.5 // each face behind: how far right, its radius
+ static let labelX = 68.0 // the status starts after them
+ static func near(_ pt: CGPoint) -> Bool { pt.x < 72 && pt.y < 50 }
+}
diff --git a/app/ChumsWatch/Rig/Rig.swift b/app/ChumsWatch/Rig/Rig.swift
new file mode 100644
index 0000000..886e0a1
--- /dev/null
+++ b/app/ChumsWatch/Rig/Rig.swift
@@ -0,0 +1,456 @@
+import SwiftUI
+
+/// One tool call from a Claude Code session, as the hub reports it.
+struct ToolCall: Equatable {
+ enum Kind: String { case read, edit, bash, test, agent, stop }
+ let id: String
+ let kind: Kind
+ let text: String
+}
+
+/// The character rig: state machine, springs, blinks, saccades, voice, clips, idle variations,
+/// touch, crown and gravity. `tick` advances it; `pose` reads it; `ChumsRenderer` draws it.
+final class Rig {
+ // appearance
+ var character: CharacterKind = .fallback { didSet { if character != oldValue { worlds.calm(self); worlds.reset(self); staged?.onState(self, state, prev: nil, variant: variant) } } }
+ /// Noodle and Pix draw their own screen.
+ var staged: Staged? {
+ switch character {
+ case .stretch: StretchStage.shared
+ case .peeps: PeepsStage.shared
+ case .crunch: PixStaged.apple
+ case .nana: PixStaged.banana
+ case .squint: SquintStage.shared
+ case .ray: RayStage.shared
+ case .tangle: TangleStage.shared
+ case .noodle: NoodleStage.shared
+ default: nil
+ }
+ }
+ var mode: StageMode = .world { didSet { if mode != oldValue { modeChanged() } } }
+ var cute = 0.55
+ var ao = false
+ /// The watch draws its own faces, status, caption, talk bar and approval card on the character's screen; the iPhone
+ /// draws those natively around it, so it turns them off here.
+ var chrome = true
+ /// The approval card's own × and "hold to allow" (the widgets draw their own buttons).
+ var cardControls = true
+ /// Screen pixels per design point, set by the renderer each frame (Pix draws at the screen's own pixels).
+ var pixelScale = 2.0
+
+ // state
+ private(set) var state: ChumsState = .idle
+ private(set) var variant = false
+ private(set) var stateT = 0.0
+ var t = 0.0
+
+ /// Where the rig goes when a one-shot (done, dizzy) finishes. The app keeps this current.
+ var restState: ChumsState = .idle
+ var restVariant = false
+ func settle() { if state != restState || variant != restVariant { setState(restState, variant: restVariant) } }
+ /// States the rig plays out by itself before settling.
+ var inOneShot: Bool { state == .done || state == .dizzy }
+
+ // words on screen, set by the app
+ var label = ""
+ /// The agents' faces at the top left, the one you talk to first: each one's character, and whether it needs you
+ var faces: [(character: String, needs: Bool)] = [(CharacterKind.fallback.rawValue, false)]
+ var caption = "" { didSet { if caption != oldValue { captionShown = (state == .speaking) ? 0 : 999 } } }
+ var captionShown = 999.0
+ /// The caption on screen is cut short (the renderer sets it): a tap there opens the reply in full.
+ var captionLong = false
+ var subCaption = ""
+ var approvalTitle = ""
+ var approvalDetail = ""
+ var onAllow: (() -> Void)?
+ var onDeny: (() -> Void)?
+ var onHaptic: ((Haptic) -> Void)?
+ enum Haptic { case click, strong, success, failure, notification, start, settle } // settle: something set down in its place
+
+ // springs
+ var S = Springs()
+ struct Springs {
+ var lift = Spring(0, 12, 0.45), squash = Spring(0, 16, 0.5), tilt = Spring(0, 12, 0.6), scale = Spring(1, 12, 0.7)
+ var rays = Spring(0.6, 9, 0.6), spin = Spring(0, 5, 0.9), amber = Spring(0, 10, 0.9)
+ var wide = Spring(0, 38, 0.85), happy = Spring(0, 38, 0.85), sleepy = Spring(0, 38, 0.85)
+ var worried = Spring(0, 38, 0.85), closed = Spring(0, 38, 0.85), intent = Spring(0, 38, 0.85)
+ mutating func stepAll(_ dt: Double) {
+ lift.step(dt); squash.step(dt); tilt.step(dt); scale.step(dt); rays.step(dt); spin.step(dt); amber.step(dt)
+ wide.step(dt); happy.step(dt); sleepy.step(dt); worried.step(dt); closed.step(dt); intent.step(dt)
+ }
+ }
+ var spinAngle = 0.0
+
+ // eyes
+ struct Gaze { var x = 0.0, y = 0.0, fx = 0.0, fy = 0.0, tx = 0.0, ty = 0.0, t0 = 0.0, dur = 0.0, fixLeft = 1.0 }
+ var gaze = Gaze()
+ struct Blink { var open = 1.0, phase = 0, t = 0.0, next = 2.5, double = false, doubleIn = -1.0 } // phase 0 idle 1 close 2 hold 3 open
+ var blink = Blink()
+
+ // voice: 0…1. The app feeds the microphone level while listening and word pulses while speaking.
+ var voice = 0.0
+ var voiceInput: Double? = nil
+ private var voiceRaw = 0.0, vt = 0.0
+
+ // one-shots
+ var clip: Clip?
+ struct Particle { var kind: Kind; var x, y, vx, vy, life: Double; var age = 0.0; enum Kind { case spark, heart, sweat, ripple, z } }
+ var particles: [Particle] = []
+ private var idleBag: [String] = [], idleNext = 10.0
+ var idleVar: String?
+ private var idleT = 0.0
+
+ // portrait working: three lines of code get written, the eyes read along
+ struct Typing { var line = 0, prog = 0.0, pause = 0.3, widths: [Double] = [rnd(0.62, 0.92), rnd(0.4, 0.75), rnd(0.55, 0.95)] }
+ var typing = Typing()
+ let DOC = (x: 34.0, w: 130.0, y: 176.0, gap: 9.0)
+
+ // touch
+ var touch: CGPoint? // gaze target while a finger is down (normalized −1…1)
+ /// While you talk: how far the finger has slid, −1 (onto × to cancel) … 1 (onto ✓ to send); armed past ±0.75
+ var talkSlide = 0.0
+ static let armed = 0.75
+ var holding = false // finger held on the approval card
+ var hold = 0.0
+
+ // world, camera, physics
+ let worlds = Worlds()
+ var W = WorldState()
+
+ init() { worlds.reset(self) }
+
+ // MARK: state
+
+ /// The state table.
+ func spec(_ s: ChumsState) -> StateSpec {
+ let st = STATE_SPECS[s]!
+ return st
+ }
+
+ func setState(_ s: ChumsState, variant v: Bool = false) {
+ let prev = state
+ state = s; stateT = 0; variant = v; particles = []; hold = 0; clip = nil
+ staged?.onState(self, s, prev: prev, variant: v)
+ // shaken: thrown in the Physics stage, jolted in place anywhere else; any other state ends it
+ if s == .dizzy && staged == nil {
+ if mode == .physics { if W.loose == nil { W.loose = WorldState.Loose() } } else if W.jolt == nil { worlds.jolt(self, 2) }
+ } else if s != .dizzy { worlds.calm(self) }
+ let st = spec(s)
+ S.lift.t = st.lift; S.scale.t = st.scale; S.tilt.t = st.tilt; S.rays.t = st.rays; S.spin.t = st.spin
+ S.wide.t = st.wide; S.happy.t = st.happy; S.sleepy.t = st.sleepy; S.worried.t = st.worried; S.closed.t = st.closed; S.intent.t = st.intent
+ S.amber.t = (s == .needs || s == .approval) ? 1 : 0
+ if s == .speaking { captionShown = 0 }
+ if s == .done { clip = .jump() }
+ if s == .needs { clip = .knock() }
+ if s == .working { typing = Typing() }
+ if s == .blocked { particles.append(Particle(kind: .sweat, x: 24, y: -26, vx: 0, vy: 0, life: 99)) }
+ saccade(st.home.0, st.home.1, ms: 120)
+ startBlink()
+ worlds.onState(self, s, v)
+ }
+
+ private func modeChanged() {
+ worlds.calm(self)
+ W.zoom = 0; W.zoomV = 0
+ if mode == .physics { W.body = WorldState.Body() }
+ if mode == .world { worlds.reset(self); startLaunch() }
+ }
+
+ // MARK: eyes
+
+ func startBlink(_ double: Bool = false) { blink.phase = 1; blink.t = 0; blink.double = double }
+
+ private func stepBlink(_ dt: Double) {
+ blink.t += dt
+ if blink.doubleIn > 0 { blink.doubleIn -= dt; if blink.doubleIn <= 0 { startBlink() } }
+ switch blink.phase {
+ case 1: blink.open = 1 - inC(clamp(blink.t / 0.07, 0, 1)); if blink.t >= 0.07 { blink.phase = 2; blink.t = 0 }
+ case 2: blink.open = 0; if blink.t >= 0.03 { blink.phase = 3; blink.t = 0 }
+ case 3:
+ blink.open = outC(clamp(blink.t / 0.12, 0, 1))
+ if blink.t >= 0.12 { blink.phase = 0; if blink.double { blink.doubleIn = 0.14; blink.double = false } }
+ default:
+ blink.next -= dt
+ if blink.next <= 0 {
+ // never blink over an expression that owns the eyes
+ if S.closed.x < 0.5 && S.happy.x < 0.5 && state != .dizzy { startBlink(Double.random(in: 0..<1) < 0.15) }
+ blink.next = rnd(2.5, 6)
+ }
+ }
+ }
+
+ func saccade(_ x: Double, _ y: Double, ms: Double? = nil) {
+ gaze.fx = gaze.x; gaze.fy = gaze.y; gaze.tx = clamp(x, -1, 1); gaze.ty = clamp(y, -1, 1); gaze.t0 = 0
+ let dist = hypot(gaze.tx - gaze.fx, gaze.ty - gaze.fy) * 6
+ gaze.dur = (ms ?? (60 + 8 * dist)) / 1000
+ if Double.random(in: 0..<1) < 0.35 && blink.phase == 0 && dist > 2 { startBlink() }
+ }
+
+ private func stepGaze(_ dt: Double) {
+ gaze.t0 += dt
+ let k = gaze.dur > 0 ? minJerk(clamp(gaze.t0 / gaze.dur, 0, 1)) : 1
+ gaze.x = lerp(gaze.fx, gaze.tx, k); gaze.y = lerp(gaze.fy, gaze.ty, k)
+ let st = STATE_SPECS[state]!
+ if let f = touch {
+ if hypot(f.x - gaze.tx, f.y - gaze.ty) > 0.05 { saccade(f.x, f.y, ms: 90) }
+ gaze.fixLeft = 0.25; return
+ }
+ gaze.fixLeft -= dt
+ if gaze.fixLeft > 0 { return }
+ switch state {
+ case .thinking:
+ let pts: [(Double, Double)] = [(0.7, -0.55), (0, 0), (-0.7, -0.55), (0, 0)]
+ let p = pts[Int(stateT / 0.55) % 4]; saccade(p.0, p.1); gaze.fixLeft = 0.55
+ case .approval:
+ saccade(0, Int(stateT / 0.7) % 2 == 0 ? 0.8 : 0); gaze.fixLeft = 0.7
+ case .subagents:
+ saccade([-0.85, 0, 0.85][Int(stateT / 0.85) % 3], 1); gaze.fixLeft = 0.85
+ case .working:
+ let x = clamp((caretX() - 99) / 62, -1, 1)
+ saccade(x, 0.75 + Double(typing.line) * 0.1, ms: typing.prog < 0.05 ? 110 : 45)
+ gaze.fixLeft = typing.pause > 0 ? 0.3 : 0.16
+ case .listening, .dizzy, .sleep:
+ saccade(st.home.0, st.home.1); gaze.fixLeft = 1
+ default:
+ let (lo, hi) = st.fix ?? (1, 2)
+ gaze.fixLeft = rnd(lo, hi)
+ let back = state == .speaking ? 0.7 : 0.55
+ if Double.random(in: 0..<1) < back {
+ saccade(st.home.0 + rnd(-0.05, 0.05), st.home.1 + rnd(-0.05, 0.05))
+ } else {
+ let a = rnd(0, TAU), r = clamp(0.3 + abs(gauss()) * 1.2, 0.3, 0.9)
+ saccade(st.home.0 + cos(a) * r, st.home.1 + sin(a) * r * 0.7)
+ }
+ }
+ }
+
+ // MARK: voice, typing
+
+ private func stepVoice(_ dt: Double, active: Bool) {
+ vt += dt
+ if let v = voiceInput, active { voiceRaw = clamp(v, 0, 1) }
+ else {
+ let syll = max(0, sin(vt * 13.5) * 0.6 + sin(vt * 5.1) * 0.4), phrase = (sin(vt * 1.3) * 0.5 + 0.5) > 0.2 ? 1.0 : 0.1
+ voiceRaw = active ? clamp(syll * phrase * rnd(0.7, 1), 0, 1) : 0
+ }
+ let k = voiceRaw > voice ? 1 - exp(-dt / 0.06) : 1 - exp(-dt / 0.18)
+ voice += (voiceRaw - voice) * k
+ }
+
+ private func stepTyping(_ dt: Double) {
+ if typing.pause > 0 {
+ typing.pause -= dt
+ if typing.pause <= 0 && typing.prog >= 1 {
+ typing.line += 1; typing.prog = 0
+ if typing.line > 2 { typing = Typing(); typing.pause = 0.25 }
+ }
+ return
+ }
+ typing.prog = min(1, typing.prog + dt * rnd(0.7, 1.3) / (typing.widths[typing.line] * 1.6))
+ if typing.prog >= 1 { typing.pause = 0.45 }
+ }
+ func caretX() -> Double { DOC.x + DOC.w * typing.widths[min(typing.line, 2)] * typing.prog }
+
+ // MARK: frame
+
+ func tick(_ dt0: Double) {
+ let dt = min(dt0, 1.0 / 20) // a dropped frame never teleports the rig
+ t += dt; stateT += dt
+ trauma = max(0, trauma - dt * 0.75)
+ staged?.step(self, dt)
+ let st = spec(state)
+ stepBlink(dt); stepGaze(dt)
+ stepVoice(dt, active: state == .listening || state == .speaking)
+
+ // breathing
+ let breathP = state == .sleep ? 5.0 : 4.0, breath = sin(t * TAU / breathP) * (state == .sleep ? 0.04 : 0.03)
+ S.scale.t = st.scale * (1 + breath * lerp(0.6, 1, cute))
+ S.rays.t = st.rays * (1 + breath * 1.5)
+
+ if state == .listening { S.rays.t = 0.85 + voice * 0.4; S.scale.t = 1.08 * (1 + voice * 0.04) }
+ if state == .speaking {
+ S.squash.t = voice * 0.04; S.lift.t = 2 + voice * 1.5; S.rays.t = 0.7 + voice * 0.15
+ captionShown = min(Double(caption.count), captionShown + dt * 24)
+ if voiceRaw < 0.05 && voice > 0.3 && Double.random(in: 0..<1) < 0.02 { startBlink() }
+ } else if state != .blocked && state != .sleep { S.squash.t = 0 }
+ if state == .working { stepTyping(dt); S.lift.t = st.lift + (typing.pause <= 0 && Int(stateT * 9) % 2 == 1 ? 1.4 : 0) }
+ if state == .subagents { S.tilt.t = sin(stateT * 1.6) * 2 * DEG }
+ if state == .blocked { S.squash.t = -0.08 }
+ if state == .sleep { S.squash.t = -0.1 }
+ if state == .dizzy && W.loose == nil && W.jolt == nil {
+ // staged characters play their own dizzy; the rig's own characters are thrown loose (Worlds.loose)
+ S.tilt.t = sin(stateT * TAU * 1.25) * 16 * DEG * max(0, 1 - stateT / 2)
+ S.spin.t = 360 * max(0, 1 - stateT / 2)
+ if stateT > 2 && clip == nil { clip = .shakeOff() }
+ if stateT > (staged?.holds[.dizzy] ?? 2.6) { settle(); startBlink() }
+ }
+ if W.loose != nil || W.jolt != nil { S.tilt.t = 0; S.spin.t = 0 }
+ if state == .done && stateT > (staged?.holds[.done] ?? 2.4) && !W.busy { settle() }
+ if state == .needs && clip == nil && stateT > 3.2 { clip = .knock(); stateT = 0.01 }
+ if state == .approval {
+ hold = holding ? min(1, hold + dt / 1.0) : max(0, hold - dt * 1.6)
+ if hold >= 1 { holding = false; hold = 0; onHaptic?(.success); onAllow?() }
+ }
+ if state == .done && stateT > 0.38 && stateT - dt <= 0.38 {
+ for i in 0..<5 {
+ let a = -Double.pi / 2 + Double(i - 2) * 0.55
+ particles.append(Particle(kind: .spark, x: cos(a) * 50, y: sin(a) * 42, vx: cos(a) * 26, vy: sin(a) * 26, life: 0.8))
+ }
+ if variant { particles.append(Particle(kind: .heart, x: 0, y: -58, vx: 0, vy: -24, life: 1.4)) }
+ }
+ if state == .sleep && Double.random(in: 0..<1) < dt * 0.6 { particles.append(Particle(kind: .z, x: 22, y: -30, vx: 5, vy: -11, life: 2.6)) }
+
+ // idle variations from a shuffle bag, never the same twice in a row
+ if state == .idle {
+ idleNext -= dt
+ if idleVar == nil && idleNext <= 0 {
+ if idleBag.isEmpty { idleBag = ["stretch", "look", "wiggle", "hop"].shuffled() }
+ idleVar = idleBag.removeLast(); idleT = 0; idleNext = rnd(9, 18)
+ if idleVar == "hop" { clip = .hop(6) }
+ if idleVar == "look" { saccade(-0.8, -0.2); gaze.fixLeft = 0.7 }
+ }
+ if let v = idleVar {
+ idleT += dt
+ if v == "stretch" { S.rays.t = idleT < 1 ? 1.1 : 0.6; S.lift.t = idleT < 1 ? 3 : 0; S.squash.t = idleT < 1 ? 0.08 : 0 }
+ if v == "look" && idleT > 0.7 && idleT - dt <= 0.7 { saccade(0.8, -0.2); gaze.fixLeft = 0.7 }
+ if v == "wiggle" { S.spin.t = idleT < 1.2 ? 60 : 0 }
+ if idleT > 1.8 { idleVar = nil }
+ }
+ } else { idleVar = nil }
+
+ if var c = clip { c.t += dt; clip = c.t >= c.dur ? nil : c }
+
+ worlds.step(self, dt)
+ S.stepAll(dt)
+ spinAngle += S.spin.x * DEG * dt
+ for i in particles.indices {
+ particles[i].age += dt; particles[i].x += particles[i].vx * dt; particles[i].y += particles[i].vy * dt
+ if particles[i].kind == .spark { particles[i].vy += 40 * dt }
+ }
+ particles.removeAll { $0.age >= $0.life }
+ }
+
+
+ // MARK: pose
+
+ func pose(raw: Bool = false) -> Pose {
+ let c = clip?.frame() ?? ClipFrame()
+ var p = Pose(t: t)
+ p.cx = 99; p.cy = 112 - (S.lift.x + c.dy)
+ p.sy = (1 + S.squash.x) * c.sy
+ p.tilt = S.tilt.x + c.tilt
+ p.scale = S.scale.x * c.sc
+ p.c = cute
+ p.eye.open = blink.open * (1 - S.closed.x); p.eye.closed = S.closed.x; p.eye.wide = S.wide.x; p.eye.happy = S.happy.x
+ p.eye.sleepy = S.sleepy.x; p.eye.worried = S.worried.x; p.eye.intent = S.intent.x
+ p.eye.spiral = state == .dizzy && W.jolt == nil && (W.loose != nil || stateT < 2.1)
+ p.eye.gx = gaze.x; p.eye.gy = gaze.y
+ p.eye.tremorX = sin(t * TAU * 0.3) * 0.5; p.eye.tremorY = cos(t * TAU * 0.23) * 0.5
+ p.pulse = state == .listening ? voice : state == .speaking ? voice * 0.45 : 0
+ p.amber = S.amber.x
+ p.ao = ao
+ return raw ? p : worlds.apply(self, p)
+ }
+
+ // MARK: input
+
+ /// A finger went down at a point in design space (198 × 242).
+ func touchDown(_ pt: CGPoint) -> TouchTarget {
+ touch = CGPoint(x: clamp((pt.x - 99) / 70, -1, 1), y: clamp((pt.y - 112) / 90, -1, 1))
+ if state == .approval {
+ if let st = staged, st.ownsApproval { // Noodle balances the card on its hair: anywhere holds it but ×
+ if hypot(pt.x - 36, pt.y - 210) < 18 { return .deny }
+ holding = true; return .card
+ }
+ if worlds.worldOn(self) { holding = true; return .card }
+ if pt.y > 196 && pt.x < 60 { return .deny }
+ if pt.y > 112 && pt.y < 196 { holding = true; return .card }
+ return .none
+ }
+ if worlds.onCharacter(self, pt) { return .character }
+ return pt.y > 145 ? .talkZone : .none
+ }
+ enum TouchTarget { case none, character, talkZone, card, deny }
+
+ func touchMoved(_ pt: CGPoint) {
+ touch = CGPoint(x: clamp((pt.x - 99) / 70, -1, 1), y: clamp((pt.y - 112) / 90, -1, 1))
+ }
+
+ func touchUp() {
+ touch = nil
+ holding = false
+ }
+
+ /// A short tap on the character.
+ func poke() {
+ if let st = staged { st.poke(self); onHaptic?(.click); return }
+ let now = t
+ W.pokes = W.pokes.filter { now - $0 < 3 } + [now]
+ if mode == .physics { W.body.vy -= 320; W.body.vx += rnd(-70, 70) } else { clip = .hop(6) }
+ startBlink(); onHaptic?(.click)
+ if W.pokes.count >= 5 { W.pokes = []; S.worried.t = 0.7; W.annoyedT = 0.9 }
+ }
+
+ /// Stroking across the character.
+ func pet(_ distance: Double) {
+ staged?.pet(self)
+ W.petDist += distance
+ if W.petDist > 40 { W.petDist = 0; onHaptic?(.click) }
+ S.happy.t = 1; S.squash.t = -0.06
+ }
+ func petEnded() { S.happy.t = STATE_SPECS[state]!.happy; S.squash.t = 0 }
+
+ /// The Digital Crown turned by `delta` (in the crown's own units).
+ func crown(_ delta: Double) {
+ if let st = staged { st.crown(self, delta); return }
+ if worlds.crown(self, delta) { return }
+ W.crownAcc += delta; spinAngle += delta * 0.4
+ saccade(delta > 0 ? 0.8 : -0.8, 0, ms: 60); gaze.fixLeft = 0.6
+ if abs(W.crownAcc) > 0.4 { W.crownAcc = 0; onHaptic?(.click) }
+ }
+
+ /// The pixel level is a game. Is it on screen and taking input; has it had input lately; a tap there (a jump).
+ var levelLive: Bool { false }
+ var levelPlaying: Bool { false }
+ func levelPress() -> Bool { false }
+
+ /// The watch's own acceleration, in g on the screen's axes (x right, y down, z toward you), about 50 times a second.
+ /// A sharp move shakes the character: in the Physics stage it's thrown the other way (it stays put while the watch
+ /// moves); in Portrait and the level it's jolted where it stands. Staged characters get every move (Noodle sloshes
+ /// with them) and a hard shake makes them dizzy.
+ private var lastKick = -9.0
+ /// How hard it's being shaken, 0…1, the same measure as Noodle's: the square of each move over 0.9 g piles up, and
+ /// drains in about a second. A hard shake jolts harder and leaves it dazed longer.
+ private(set) var trauma = 0.0
+ func motion(_ ax: Double, _ ay: Double, _ az: Double) {
+ guard !ao else { return }
+ staged?.motion(self, ax, ay, az)
+ let g = sqrt(ax * ax + ay * ay + az * az)
+ trauma = min(1, trauma + max(0, g - 0.9) * max(0, g - 0.9) * 0.03)
+ guard state != .approval && state != .listening, t - lastKick > 0.16 else { return }
+ if staged != nil {
+ if g > 2.2 { lastKick = t; if state != .dizzy || stateT > 3 { setState(.dizzy) } }
+ return
+ }
+ // a first shake has to be sharp; once it's going, smaller ones keep it going
+ if mode == .physics {
+ guard g > (W.loose?.phase == .fly ? 1.35 : 1.6) else { return }
+ lastKick = t
+ let h = hypot(ax, ay)
+ let (dx, dy) = h > 0.3 ? (-ax / h, -ay / h) : (cos(rnd(0, TAU)), sin(rnd(0, TAU))) // along z: any way
+ if g < 2.6 && W.loose == nil { worlds.kickBody(self, dx, dy, g); return } // a shove
+ if state != .dizzy { setState(.dizzy) }
+ worlds.kick(self, dx, dy, g)
+ } else {
+ // Portrait and the level: jolted where it stands (the game doesn't move)
+ guard g > (W.jolt != nil ? 1.35 : 1.9) else { return }
+ lastKick = t
+ if state != .dizzy { setState(.dizzy) } else { worlds.jolt(self, g) }
+ }
+ }
+
+ func startLaunch() { worlds.startLaunch(self) }
+
+ /// Tool calls from the hub, in order. Each world turns them into its own landmark.
+ func push(_ call: ToolCall) { worlds.queue.append(call) }
+}
diff --git a/app/ChumsWatch/Rig/RigCore.swift b/app/ChumsWatch/Rig/RigCore.swift
new file mode 100644
index 0000000..026ab30
--- /dev/null
+++ b/app/ChumsWatch/Rig/RigCore.swift
@@ -0,0 +1,247 @@
+import SwiftUI
+@_exported import simd // vector maths for every rig (WatchKit brings it on the watch; the iPhone needs it said)
+
+// Shared math, springs, palette and the state table. The rig is a port of the Character Lab, the HTML prototype the
+// characters were designed in (not in the public repository): same parameters, same springs, same timings. Everything is drawn in a 198 × 242 pt design space
+// (the 45 mm screen) and scaled to the real screen.
+
+let TAU = Double.pi * 2
+let DEG = Double.pi / 180
+let DESIGN = CGSize(width: 198, height: 242)
+
+@inline(__always) func clamp(_ v: Double, _ a: Double, _ b: Double) -> Double { max(a, min(b, v)) }
+@inline(__always) func lerp(_ a: Double, _ b: Double, _ k: Double) -> Double { a + (b - a) * k }
+@inline(__always) func inQ(_ t: Double) -> Double { t * t }
+@inline(__always) func outQ(_ t: Double) -> Double { 1 - (1 - t) * (1 - t) }
+@inline(__always) func inC(_ t: Double) -> Double { t * t * t }
+@inline(__always) func outC(_ t: Double) -> Double { 1 - pow(1 - t, 3) }
+@inline(__always) func minJerk(_ t: Double) -> Double { t * t * t * (10 - 15 * t + 6 * t * t) }
+@inline(__always) func ease3(_ k: Double) -> Double { k < 0.5 ? 4 * k * k * k : 1 - pow(-2 * k + 2, 3) / 2 }
+@inline(__always) func rnd(_ a: Double, _ b: Double) -> Double { Double.random(in: a...b) }
+func gauss() -> Double { sqrt(-2 * log(Double.random(in: 0..<1) + 1e-9)) * cos(TAU * Double.random(in: 0..<1)) * 0.35 }
+
+/// A damped spring toward `t`: ω is stiffness in rad/s, ζ the damping ratio. Two half steps per frame.
+struct Spring {
+ var x: Double, v: Double = 0, t: Double
+ let w: Double, z: Double
+ init(_ x: Double, _ w: Double, _ z: Double) { self.x = x; self.t = x; self.w = w; self.z = z }
+ mutating func step(_ dt: Double) {
+ for _ in 0..<2 {
+ let h = dt / 2
+ v += (w * w * (t - x) - 2 * z * w * v) * h
+ x += v * h
+ }
+ }
+}
+
+extension Color {
+ init(hex: UInt32, alpha: Double = 1) {
+ self.init(.sRGB, red: Double((hex >> 16) & 0xFF) / 255, green: Double((hex >> 8) & 0xFF) / 255,
+ blue: Double(hex & 0xFF) / 255, opacity: alpha)
+ }
+ static func gray(_ v: Double) -> Color { Color(.sRGB, red: v, green: min(1, v + 0.008), blue: min(1, v + 0.02), opacity: 1) }
+}
+
+enum Pal {
+ static let clay = Color(hex: 0xD97757), coral = Color(hex: 0xD77757), ink = Color(hex: 0x1E130F)
+ static let white = Color(hex: 0xF4F5F6), gray = Color(hex: 0x8A8F95), dim = Color(hex: 0x4A4E53)
+ static let amber = Color(hex: 0xFFB020), card = Color(hex: 0x131517), sweat = Color(hex: 0x7FB3E6)
+ static let heart = Color(hex: 0xF2707A), green = Color(hex: 0x3DD68C), red = Color(hex: 0xE5484D)
+}
+
+enum ChumsState: String, CaseIterable {
+ case idle, listening, thinking, working, subagents, speaking, done, needs, approval, blocked, dizzy, sleep
+}
+
+enum CharacterKind: String, CaseIterable, Identifiable {
+ case peeps, stretch, crunch, nana, squint, ray, tangle, noodle
+ var name: String { ["peeps": "Peeps", "stretch": "Stretch", "crunch": "Crunch", "nana": "Nana", "squint": "Squint", "ray": "Ray", "tangle": "Tangle", "noodle": "Noodle"][rawValue]! }
+ var gridded: Bool { false }
+ static let fallback = CharacterKind.noodle
+ var id: String { rawValue }
+ /// A character by its id, or by the id it had before the October 2026 rename where that id isn't taken again
+ /// ("noodle" was Stretch's and is now the tube's: what was stored under it was moved once, `migrate`).
+ init?(id: String) { self.init(rawValue: CharacterKind.legacy[id] ?? id) }
+ static let legacy = ["eyes": "peeps", "apple": "crunch", "banana": "nana", "kao": "squint", "sol": "ray", "scribble": "tangle", "coil": "noodle"]
+ /// The character stored on the watch, under its new id: once.
+ static func migrate() {
+ let d = UserDefaults.standard
+ guard !d.bool(forKey: "renamed2026") else { return }
+ if let c = d.string(forKey: "character") { d.set(c == "noodle" ? "stretch" : legacy[c] ?? c, forKey: "character") }
+ d.set(true, forKey: "renamed2026")
+ }
+ /// Draws its own whole screen (rendered frames, its own pixels) instead of the shared rig and a world.
+ var staged: Bool { !gridded }
+ /// Drawn from rendered frames or its own pixels, at most 24 times a second: no need to draw it 60 times.
+ var framed: Bool { self == .stretch || self == .crunch || self == .nana }
+}
+
+enum StageMode: String, CaseIterable, Identifiable {
+ case portrait, world, physics
+ var id: String { rawValue }
+ var name: String { ["portrait": "Portrait", "world": "World", "physics": "Physics"][rawValue]! }
+ /// Each character's world has its own name.
+ func name(for k: CharacterKind) -> String { self == .world ? (k.gridded ? "Level" : k == .peeps ? "Page" : "World") : name }
+ /// What the stage is, for the settings footer.
+ func about(for k: CharacterKind) -> String {
+ switch self {
+ case .portrait: return "\(k.name) up close, with nothing around it."
+ case .physics: return "Tilt the watch and \(k.name) slides and falls with it. Drag it and throw it; shake the watch to send it flying."
+ case .world:
+ return k.gridded ? "A pixel level: each tool call is a block. Turn the crown to walk, tap to jump."
+ : "A page of code: Peeps reads it, and tool calls change it as they happen."
+ }
+ }
+}
+
+/// Body targets (k) and lid targets (e) per state, plus gaze fixation range and home.
+struct StateSpec {
+ var lift = 0.0, scale = 1.0, tilt = 0.0, rays = 0.6, spin = 0.0
+ var wide = 0.0, happy = 0.0, sleepy = 0.0, worried = 0.0, closed = 0.0, intent = 0.0
+ var fix: (Double, Double)? = nil
+ var home: (Double, Double) = (0, 0)
+}
+
+let STATE_SPECS: [ChumsState: StateSpec] = [
+ .idle: StateSpec(fix: (0.6, 2.4)),
+ .listening: StateSpec(lift: -24, scale: 1.08, rays: 0.85, wide: 1, home: (0, 0.15)), // lower: the talk bar is above
+ .thinking: StateSpec(tilt: -6 * DEG, rays: 0.7, spin: 40),
+ .working: StateSpec(lift: 10, scale: 0.9, intent: 1, home: (0, 0.7)),
+ .subagents: StateSpec(lift: 18, scale: 0.78, intent: 0.4, home: (0, 0.8)),
+ .speaking: StateSpec(lift: 2, scale: 0.92, rays: 0.7, fix: (0.8, 2)),
+ .done: StateSpec(rays: 0.9, happy: 1, fix: (1, 2), home: (0, -0.1)),
+ .needs: StateSpec(lift: 10, scale: 1.02, tilt: 8 * DEG, rays: 0.8, wide: 1, fix: (1.2, 2.4)),
+ .approval: StateSpec(lift: 42, scale: 0.62, rays: 0.5, home: (0, 0.6)),
+ .blocked: StateSpec(lift: -5, scale: 0.96, rays: 0.45, worried: 1, fix: (1.5, 3), home: (0, 0.3)),
+ .dizzy: StateSpec(rays: 0.7, spin: 360),
+ .sleep: StateSpec(lift: -8, scale: 0.94, tilt: 6 * DEG, rays: 0.3, closed: 1),
+]
+
+/// A one-shot, additive animation: dy in pt upward, sy vertical scale, optional tilt and whole-body scale.
+struct ClipFrame { var dy = 0.0, sy = 1.0, tilt = 0.0, sc = 1.0 }
+struct Clip {
+ var t = 0.0
+ let dur: Double
+ let eval: (Double) -> ClipFrame
+
+ static func jump() -> Clip {
+ Clip(dur: 0.91) { t in
+ if t < 0.12 { return ClipFrame(sy: lerp(1, 0.8, outQ(t / 0.12))) }
+ if t < 0.38 { let k = (t - 0.12) / 0.26; return ClipFrame(dy: 22 * outQ(k), sy: lerp(1.18, 1, k)) }
+ if t < 0.58 { let k = (t - 0.38) / 0.2; return ClipFrame(dy: 22 * (1 - inQ(k)), sy: lerp(1, 1.1, k)) }
+ if t < 0.66 { return ClipFrame(sy: 0.78) }
+ let k = (t - 0.66) / 0.25
+ return ClipFrame(sy: 1 + 0.06 * sin(k * .pi) * (1 - k))
+ }
+ }
+ static func hop(_ h: Double = 6) -> Clip {
+ Clip(dur: 0.42) { t in
+ if t < 0.08 { return ClipFrame(sy: lerp(1, 0.9, t / 0.08)) }
+ let k = (t - 0.08) / 0.34
+ return ClipFrame(dy: h * sin(k * .pi), sy: k > 0.9 ? 0.92 : 1.05 - 0.05 * k)
+ }
+ }
+ static func shakeOff() -> Clip {
+ Clip(dur: 0.5) { t in ClipFrame(tilt: 8 * DEG * sin(t * 40) * (1 - t / 0.5)) }
+ }
+ /// Shaking the daze off: a few quick head shakes, bigger and longer than the dizzy one's.
+ static func shakeOffHard() -> Clip {
+ Clip(dur: 0.6) { t in ClipFrame(tilt: 12 * DEG * sin(t * 42) * (1 - t / 0.6)) }
+ }
+ /// Two quick bumps toward you, like knocking on the glass.
+ static func knock() -> Clip {
+ Clip(dur: 1.1) { t in
+ func bump(_ k: Double) -> Double { max(0, 1 - abs(t - k) / 0.09) }
+ return ClipFrame(sc: 1 + 0.09 * max(bump(0.12), bump(0.34)))
+ }
+ }
+ func frame() -> ClipFrame { eval(min(t, dur)) }
+}
+
+struct EyePose {
+ var open = 1.0, closed = 0.0, wide = 0.0, happy = 0.0, sleepy = 0.0, worried = 0.0, intent = 0.0
+ var spiral = false
+ var wince = false // shut tight (a flinch): the closed line arches up instead of resting down
+ var gx = 0.0, gy = 0.0, tremorX = 0.0, tremorY = 0.0
+
+ /// Eyes for a small copy of a character: open, neutral, looking where it's told.
+ static func neutral(gx: Double, gy: Double, intent: Double = 0.5) -> EyePose {
+ var e = EyePose(); e.gx = gx; e.gy = gy; e.intent = intent; return e
+ }
+}
+
+enum GridArms { case rest, raised }
+enum GridLegs { case stand, stepA, stepB, crouch, tap, tucked }
+
+/// Everything a character needs to draw one frame.
+struct Pose {
+ var t: Double
+ var cx = 99.0, cy = 112.0, sy = 1.0, tilt = 0.0, scale = 1.0, c = 0.55
+ var eye = EyePose()
+ var pulse = 0.0, amber = 0.0
+ var ao = false
+ var unitScale = 1.0
+ var world = 0.0
+ var legs: GridLegs? = nil
+ var arms: GridArms? = nil
+ var mini = false
+ var phase = 0.0
+ var tint: Color? = nil
+ var faceRot = 0.0
+ var walking = false
+ var awake = false // in a pixel level: asleep, but up to play
+ var fade = 0.0
+ // shaken loose (Worlds.loose): a gridded character's spin, its squash on a hit (+ against a floor or ceiling, − against a side),
+ // its eyes (1 squeezed shut >_<, 2 spinning) and the stars circling its head (0…1)
+ var roll = 0.0, impact = 0.0
+ var daze = 0
+ var stars = 0.0
+}
+
+/// Changes a world may apply to the pose once the camera is mostly wide.
+struct PoseOverride {
+ var legs: GridLegs? = nil
+ var arms: GridArms? = nil
+ var tilt: Double? = nil
+ var open: Double? = nil
+ var gx: Double? = nil, gy: Double? = nil
+ var happy: Double? = nil, intent: Double? = nil, sleepy: Double? = nil, wide: Double? = nil
+ var closed: Double? = nil, awake: Bool? = nil
+}
+
+struct WorldPose {
+ var cx: Double, cy: Double, scale: Double, unitScale: Double = 1
+ var o = PoseOverride()
+}
+
+/// Pixel art on a grid of `s` pt cells: rows of "X" and ".".
+func pixArtPath(_ art: [String], x: Double, y: Double, s: Double) -> Path {
+ var p = Path()
+ for (j, row) in art.enumerated() {
+ for (i, ch) in row.enumerated() where ch == "X" {
+ p.addRect(CGRect(x: (x + Double(i) * s).rounded(), y: (y + Double(j) * s).rounded(), width: ceil(s), height: ceil(s)))
+ }
+ }
+ return p
+}
+
+extension GraphicsContext {
+ func fillRect(_ x: Double, _ y: Double, _ w: Double, _ h: Double, _ c: Color) {
+ fill(Path(CGRect(x: x, y: y, width: w, height: h)), with: .color(c))
+ }
+ func fillCircle(_ x: Double, _ y: Double, _ r: Double, _ c: Color) {
+ fill(Path(ellipseIn: CGRect(x: x - r, y: y - r, width: r * 2, height: r * 2)), with: .color(c))
+ }
+ func strokeCircle(_ x: Double, _ y: Double, _ r: Double, _ c: Color, _ w: Double) {
+ stroke(Path(ellipseIn: CGRect(x: x - r, y: y - r, width: r * 2, height: r * 2)), with: .color(c), lineWidth: w)
+ }
+ func strokeLine(_ x0: Double, _ y0: Double, _ x1: Double, _ y1: Double, _ c: Color, _ w: Double, dash: [CGFloat] = [], phase: Double = 0) {
+ var p = Path(); p.move(to: CGPoint(x: x0, y: y0)); p.addLine(to: CGPoint(x: x1, y: y1))
+ stroke(p, with: .color(c), style: StrokeStyle(lineWidth: w, lineCap: .round, dash: dash, dashPhase: phase))
+ }
+ func fillRoundRect(_ x: Double, _ y: Double, _ w: Double, _ h: Double, _ r: Double, _ c: Color) {
+ fill(Path(roundedRect: CGRect(x: x, y: y, width: w, height: h), cornerRadius: r), with: .color(c))
+ }
+ /// A copy of the context with its opacity multiplied, for scoped alpha.
+ func faded(_ a: Double) -> GraphicsContext { var c = self; c.opacity *= a; return c }
+}
diff --git a/app/ChumsWatch/Rig/SquintStage.swift b/app/ChumsWatch/Rig/SquintStage.swift
new file mode 100644
index 0000000..78b392c
--- /dev/null
+++ b/app/ChumsWatch/Rig/SquintStage.swift
@@ -0,0 +1,493 @@
+import SwiftUI
+
+/// Squint: only a face, drawn in white marker strokes on the black, like a kaomoji. Two eyes, a mouth and two brows,
+/// each one stroke that changes shape (a dash, a ring, a chevron, an arc, an open D) and blends from one shape into
+/// the next. Each part hangs on its own spring, so a shake rattles them and they settle back one by one.
+/// idle: │ │ ‿, now and then another face for a moment · listening: ○ ○, a mouth that opens with your voice ·
+/// thinking: ─ ○ ~ tilted · working: ─ ─ ─, eyes reading across · subagents: small faces around it · speaking: its
+/// mouth with its voice · done: > < D and a hop, then ◠ ◠ ‿ · needs you: pleading brows, a knock · blocked: angry brows,
+/// a zigzag mouth · dizzy: spirals · sleep: ◡ ◡ and a small breathing o, z's
+/// tap: on an eye it squeezes that one shut (the other goes wide), on its mouth it giggles, anywhere else a wink ·
+/// poke it often: −_− and a shake of the head · your finger near: o o, curious, it follows · dragged fast: > < ·
+/// stroked: ◠ ◠ and a pink chalk blush · crown: picks its face (kept, and shown whenever it's idle) · shake: its
+/// parts rattle, O O; shaken hard it's dizzy
+/// It blinks by squashing its eyes shut and open (never by turning them into another shape). A part changes into a
+/// shape of its own kind by bending into it (a line into an arc); into another kind (a line into a ring) it squashes
+/// away and pops back as the new one. Idle, it breathes and its parts drift a hair.
+final class SquintStage: Staged {
+ static let shared = SquintStage()
+
+ let ownsApproval = false
+ let holds: [ChumsState: Double] = [.done: 2.6, .dizzy: 3.4]
+ func captionTop(_ r: Rig) -> Bool { false }
+ func ownsCaption(_ r: Rig) -> Bool { false }
+ var calm: Bool { t - busyAt > 1.2 }
+
+ // MARK: glyphs (points in pt, centred on the part)
+
+ static let M = 32
+ private static func g(_ pts: [P2]) -> [P2] { Strokes.resample(pts, M) }
+ private static let glyphs: [String: [P2]] = {
+ var d: [String: [P2]] = [:]
+
+ d["none"] = [P2](repeating: .zero, count: M)
+ d["vdash"] = g([P2(-1.5, -14), P2(1.5, 14)])
+ d["slant"] = g([P2(-4, -12), P2(3, 12)]) // ツ's strokes
+ d["hdash"] = g([P2(-13, 0), P2(13, 0)])
+ d["ring"] = g(Strokes.arc(.zero, 15, -Double.pi / 2, Double.pi * 1.55))
+ d["bigring"] = g(Strokes.arc(.zero, 18, -Double.pi / 2, Double.pi * 1.55))
+ d["happy"] = g(Strokes.arc(P2(0, 9), 13, Double.pi * 1.12, Double.pi * 1.88)) // ◠
+ d["shut"] = g(Strokes.arc(P2(0, -7), 13, Double.pi * 0.12, Double.pi * 0.88)) // ◡
+ d["chev"] = g([P2(-9, -11), P2(8, 0), P2(-9, 11)]) // > (the right eye is mirrored: <)
+ d["spiral"] = g((0...90).map { i in let u = Double(i) / 90, a = u * 1.7 * Double.pi * 2; return P2(cos(a), sin(a)) * (2 + u * 17) })
+ d["dot"] = g(Strokes.arc(.zero, 5, 0, Double.pi * 2.1))
+ // mouths
+ d["smile"] = g(Strokes.arc(P2(0, -24), 30, Double.pi * 0.33, Double.pi * 0.67))
+ d["bigsmile"] = g(Strokes.arc(P2(0, -30), 40, Double.pi * 0.27, Double.pi * 0.73))
+ d["flat"] = g([P2(-15, 0), P2(15, 0)])
+ d["short"] = g([P2(-8, 0), P2(8, 0)])
+ d["o"] = g(Strokes.arc(.zero, 9, -Double.pi / 2, Double.pi * 1.55))
+ d["O"] = g(Strokes.arc(.zero, 16, -Double.pi / 2, Double.pi * 1.55, rx: 12))
+ d["D"] = g([P2(-24, -9), P2(24, -9)] + Strokes.arc(P2(0, -9), 24, 0, Double.pi) + [P2(-24, -9.5)])
+ d["frown"] = g(Strokes.arc(P2(0, 26), 28, Double.pi * 1.32, Double.pi * 1.68))
+ d["wave"] = g((0...60).map { i in let x = -19 + 38 * Double(i) / 60; return P2(x, 4.5 * sin(x / 38 * Double.pi * 3)) })
+ d["zig"] = g([P2(-20, 2), P2(-12, -4), P2(-4, 3), P2(4, -4), P2(12, 3), P2(20, -3)])
+ d["tsu"] = g(Strokes.arc(P2(-22, -26), 42, Double.pi * 0.08, Double.pi * 0.46)) // ツ's long curve
+ // brows (left; the right one is mirrored)
+ d["brow"] = g([P2(-12, 0), P2(12, 0)])
+ d["angry"] = g([P2(-12, -6), P2(12, 6)])
+ d["worried"] = g([P2(-12, 6), P2(12, -6)])
+ d["up"] = g(Strokes.arc(P2(0, 10), 15, Double.pi * 1.2, Double.pi * 1.8))
+ return d
+ }()
+
+ /// Kinds of shape: within a kind one bends into the other point by point; across kinds the part swaps.
+ private enum Fam { case none, v, h, loop, chev, spiral, talk }
+ private static func fam(_ name: String) -> Fam {
+ switch name {
+ case "none": return .none
+ case "vdash", "slant": return .v
+ case "ring", "bigring", "o", "O", "dot": return .loop
+ case "chev": return .chev
+ case "spiral": return .spiral
+ case "D": return .talk
+ default: return .h
+ }
+ }
+ /// Its mouth talking, `v` open (0 shut … 1 wide): a top edge, then its lower lip swinging down and back, like the D.
+ private static func talk(_ v: Double) -> [P2] {
+ let W = 17 + 5 * v, d = 2.5 + 21 * v, y0 = -d * 0.2
+ var p: [P2] = (0...10).map { i in P2(-W + 2 * W * Double(i) / 10, y0) }
+ p += (1...22).map { i in let a = Double.pi * Double(i) / 22; return P2(W * cos(a), y0 + d * sin(a)) }
+ return Strokes.resample(p, M)
+ }
+
+ // MARK: faces
+
+ struct Face {
+ var le = "vdash", re: String? = nil, mouth = "smile", lb = "none", rb: String? = nil
+ var eyeY = 0.0, mouthY = 0.0, browY = 0.0, gap = 0.0, tilt = 0.0, scale = 1.0
+ }
+ private func face(_ s: ChumsState) -> Face {
+ switch s {
+ case .idle: return Face()
+ case .listening: return Face(le: "ring", mouth: "o", lb: "up", browY: -2, scale: 1.04)
+ case .thinking: return Face(le: "hdash", re: "ring", mouth: "wave", lb: "none", rb: "up", mouthY: 2, tilt: -0.12)
+ case .working: return Face(le: "hdash", mouth: "short", eyeY: 4, mouthY: -2)
+ case .subagents: return Face(le: "vdash", mouth: "smile", scale: 0.82)
+ case .speaking: return Face(le: "vdash", mouth: "flat")
+ case .done: return Face(le: "chev", mouth: "D", eyeY: -2)
+ case .needs: return Face(le: "vdash", mouth: "frown", lb: "worried", browY: 2, scale: 1.06)
+ case .approval: return Face(le: "ring", mouth: "o", scale: 0.5)
+ case .blocked: return Face(le: "vdash", mouth: "zig", lb: "angry", browY: 6)
+ case .dizzy: return Face(le: "spiral", mouth: "wave")
+ case .sleep: return Face(le: "shut", mouth: "o", eyeY: 6, mouthY: 2, scale: 0.94)
+ }
+ }
+ /// What the crown flips through.
+ private static let deck: [Face] = [
+ Face(), Face(le: "happy", mouth: "bigsmile"), Face(le: "chev", mouth: "D", eyeY: -2),
+ Face(le: "vdash", re: "happy", mouth: "D"), Face(le: "bigring", mouth: "O", lb: "up", browY: -6),
+ Face(le: "vdash", mouth: "frown", lb: "worried", browY: 2), Face(le: "vdash", mouth: "zig", lb: "angry", browY: 6),
+ Face(le: "hdash", re: "ring", mouth: "flat", rb: "up"), Face(le: "slant", mouth: "tsu", mouthY: -4),
+ Face(le: "hdash", mouth: "dot", mouthY: 4), Face(le: "shut", mouth: "o", eyeY: 6),
+ ]
+ /// Now and then, idle, it pulls one of these for a moment.
+ private static let fidgets: [Face] = [
+ Face(le: "hdash", re: "ring", mouth: "flat", rb: "up"), Face(le: "happy", mouth: "smile"),
+ Face(le: "slant", mouth: "tsu", mouthY: -4), Face(le: "shut", mouth: "o", eyeY: 6),
+ ]
+
+ // MARK: the parts
+
+ private struct Part {
+ var from: [P2], to: [P2], b = 1.0, bv = 0.0 // shape: from → to on a spring
+ var fam: Fam
+ var pending: [P2]? = nil, pendingFam = Fam.none // a shape of another kind it is swapping to
+ var sc = 1.0, scv = 0.0 // its size in a swap: squashing away, popping back
+ var off = P2.zero, v = P2.zero // its own spring off its place
+ var shape: [P2] { Strokes.mix(from, to, b) }
+ mutating func set(_ g: [P2], _ f: Fam) {
+ func same(_ a: [P2], _ c: [P2]) -> Bool { zip(a, c).allSatisfy { simd_length($0 - $1) < 0.01 } }
+ if let p = pending { if !same(p, g) { pending = g; pendingFam = f }; return }
+ if same(to, g) { return }
+ if f == fam || f == .none || fam == .none { from = shape; to = g; b = 0; bv = 0; fam = f } else { pending = g; pendingFam = f }
+ }
+ }
+ private var parts: [Part] = (0..<5).map { i in
+ let g = SquintStage.glyphs[i < 3 ? (i < 2 ? "vdash" : "smile") : "none"]!
+ return Part(from: g, to: g, fam: i < 2 ? .v : i == 2 ? .h : .none)
+ }
+ private enum Slot: Int { case le, re, mouth, lb, rb }
+ private var cur = Face() // layout, eased toward the face's
+ private var shown = Face() // the face on screen (state, a fidget, the crown, a wink)
+ private var state: ChumsState = .idle
+ private var t = 0.0, busyAt = 0.0
+
+ private var center = P2(99, 122), cv = P2.zero // the face, on a spring (a finger drags it)
+ private var hop = (y: 0.0, v: 0.0)
+ private var finger: CGPoint?, lookFor = 0.0, look = P2.zero
+ private var wink = 0.0, annoyed = 0.0, pokes: [Double] = []
+ private var reaction: (face: Face, until: Double)? // a tap's face, for a moment
+ private var touchT = 0.0
+ private var touchAt: CGPoint?, lastDrag: (p: CGPoint, t: Double)?, fingerSpeed = 0.0
+ private var petFor = 0.0, blush = 0.0, energy = 0.0
+ private var wob = (a: 0.0, v: 0.0) // a little rock of the head (each crown click)
+ /// The face the crown picked (0: its own), kept between launches.
+ private var chosen = UserDefaults.standard.integer(forKey: "squintFace")
+ private var crownPos = 0.0, crownIdle = 9.0
+ private var fidget: (face: Face, t: Double)?, nextFidget = 14.0
+ private var knock = 0.0, shakeT = 0.0, trauma = 0.0
+ private var minis = 0.0
+ private var toolFlash = 0.0, nextTool = 0.8
+ private var blinkT = -1.0, rigBlink = 0 // its own blink (when the rig blinks): time into it
+ private var mv = 0.0 // the voice, eased, for its mouth
+ private struct Z { var x, y, t: Double }
+ private var zs: [Z] = [], nextZ = 0.5
+
+ // MARK: Staged
+
+ func onState(_ r: Rig, _ s: ChumsState, prev: ChumsState?, variant: Bool) {
+ state = s; fidget = nil; nextFidget = rnd(12, 20)
+ if s == .done { hop.v = -230; for i in 0..<5 { parts[i].v += P2(rnd(-30, 30), rnd(-60, -20)) } }
+ if s == .needs { knock = 0 }
+ busyAt = t
+ }
+
+ func step(_ r: Rig, _ dt0: Double) {
+ let dt = min(dt0, 0.05)
+ t += dt
+ guard !r.ao else { return }
+ crownIdle += dt; wink = max(0, wink - dt); annoyed = max(0, annoyed - dt); lookFor = max(0, lookFor - dt)
+ trauma = max(0, trauma - dt * 0.75)
+ // which face: a wink, annoyed, the crown's, a fidget, done's second beat, or the state's
+ var f = face(state)
+ let picked = Self.deck[((chosen % Self.deck.count) + Self.deck.count) % Self.deck.count]
+ if state == .idle && chosen != 0 { f = picked } // the face the crown picked
+ if state == .done && r.stateT > 1.1 { f = Face(le: "happy", mouth: "bigsmile") }
+ if state == .idle && finger == nil && crownIdle > 3 && chosen == 0 {
+ nextFidget -= dt
+ if nextFidget <= 0 && fidget == nil { fidget = (Self.fidgets.randomElement()!, 0) }
+ if var fd = fidget { fd.t += dt; fidget = fd.t > 1.8 ? nil : fd; if fd.t > 1.8 { nextFidget = rnd(12, 22) } }
+ if let fd = fidget { f = fd.face }
+ }
+ if crownIdle < 2.4 { f = picked } // (in another state, for a moment)
+ // your finger: curious (o o) near it, > < dragged fast, ◠ ◠ and blushing stroked
+ petFor = max(0, petFor - dt); fingerSpeed *= exp(-dt * 6)
+ if finger != nil && (t - touchT > 0.25 || fingerSpeed > 40) { f = fingerSpeed > 260 ? Face(le: "chev", mouth: "D", eyeY: -2) : Face(le: "ring", mouth: "o", lb: "up", browY: -3, scale: 1.04) }
+ if petFor > 0 { f = Face(le: "happy", mouth: "bigsmile") }
+ blush += ((petFor > 0 || (reaction?.face.mouth == "D" && reaction?.face.le == "happy") ? 1 : 0) - blush) * min(1, dt * 5)
+ // shaken: O O while it rattles; hard, it's dizzy
+ energy *= exp(-dt * 1.5)
+ if trauma > 0.3 && state != .dizzy && state != .sleep { f = Face(le: "bigring", mouth: "O", lb: "up", browY: -6) }
+ if let re = reaction { if t < re.until { f = re.face } else { reaction = nil } }
+ if annoyed > 0 { f = Face(le: "hdash", mouth: "flat") } // −_−
+ // working: each tool call, a glance up at it (o o) and back to reading
+ nextTool -= dt; toolFlash = max(0, toolFlash - dt)
+ if nextTool <= 0 && (!r.worlds.queue.isEmpty || state == .working), let c = r.worlds.nextEvent(r) {
+ nextTool = r.worlds.queue.isEmpty ? rnd(1.6, 2.6) : 0.6
+ if c.kind != .stop && state == .working { toolFlash = 0.5; for i in 0..<5 { parts[i].v += P2(0, -50) } }
+ }
+ if toolFlash > 0 && state == .working { f = Face(le: "ring", mouth: "o", lb: "up", browY: -2) }
+ if wink > 0 { f = Face(le: "vdash", re: "happy", mouth: "D") }
+ let ww = TAU * 2.6
+ wob.v += (-ww * ww * wob.a - 2 * 0.3 * ww * wob.v) * dt; wob.a += wob.v * dt
+ if annoyed > 2.0 { wob.a = sin((2.6 - annoyed) * 30) * 0.12 * (annoyed - 2.0) / 0.6 } // a shake of the head
+ shown = f
+ // the shapes
+ let G = Self.glyphs
+ parts[0].set(G[f.le] ?? G["vdash"]!, Self.fam(f.le))
+ parts[1].set(Strokes.mirrored(G[f.re ?? f.le] ?? G["vdash"]!), Self.fam(f.re ?? f.le))
+ mv += (clamp(r.voice * 1.4, 0, 1) - mv) * min(1, dt * 16)
+ if state == .speaking { parts[2].set(Self.talk(0), .talk) } else { parts[2].set(G[f.mouth] ?? G["smile"]!, Self.fam(f.mouth)) }
+ parts[3].set(G[f.lb] ?? G["none"]!, Self.fam(f.lb))
+ parts[4].set(Strokes.mirrored(G[f.rb ?? f.lb] ?? G["none"]!), Self.fam(f.rb ?? f.lb))
+ // a blink: when the rig blinks, it squashes its eyes shut and open
+ if r.blink.phase == 1 && rigBlink != 1 && blinkT < 0 { blinkT = 0 }
+ rigBlink = r.blink.phase
+ if blinkT >= 0 { blinkT += dt; if blinkT > 0.34 { blinkT = -1 } }
+ // springs: the shapes blend (a hair of overshoot), each part settles on its own. In steps of at most 1/120 s:
+ // stepped once per frame, the shape's spring (26 rad/s) is unstable past about 1/25 s a frame, and a run of slow
+ // frames (or the offline renderer at 20 a second) made the eyes grow without end
+ let steps = max(1, Int((dt * 120).rounded(.up))), frameDT = dt
+ if trauma > 0.05 { for i in 0..<5 { parts[i].v += P2(rnd(-1, 1), rnd(-1, 1)) * trauma * 900 * frameDT } }
+ for _ in 0..<steps {
+ let dt = frameDT / Double(steps)
+ for i in 0..<5 {
+ let w = TAU * 4.2
+ parts[i].bv += (-w * w * (parts[i].b - 1) - 2 * 0.62 * w * parts[i].bv) * dt
+ parts[i].b += parts[i].bv * dt
+ // a swap: it squashes away, faster and faster, becomes the new shape, and pops back a little past full size
+ if let g = parts[i].pending {
+ parts[i].scv = min(parts[i].scv, 0) - 190 * dt; parts[i].sc += parts[i].scv * dt
+ if parts[i].sc <= 0.04 {
+ parts[i].from = g; parts[i].to = g; parts[i].b = 1; parts[i].bv = 0
+ parts[i].fam = parts[i].pendingFam; parts[i].pending = nil; parts[i].sc = 0.04; parts[i].scv = 0
+ }
+ } else {
+ let ws = TAU * 3.1
+ parts[i].scv += (-ws * ws * (parts[i].sc - 1) - 2 * 0.48 * ws * parts[i].scv) * dt
+ parts[i].sc += parts[i].scv * dt
+ }
+ let k = TAU * [3.6, 3.4, 2.6, 3.0, 2.9][i]
+ parts[i].v += (-k * k * parts[i].off - 2 * 0.32 * k * parts[i].v) * dt
+ parts[i].off += parts[i].v * dt
+ }
+ }
+ // layout eases toward the face's
+ let e = min(1, dt * 9)
+ cur.eyeY += (f.eyeY - cur.eyeY) * e; cur.mouthY += (f.mouthY - cur.mouthY) * e; cur.browY += (f.browY - cur.browY) * e
+ cur.tilt += (f.tilt - cur.tilt) * e; cur.scale += (f.scale - cur.scale) * e
+ // the face's place: home, a finger pulling it, a hop
+ var home = P2(99, state == .approval ? 70 : state == .sleep ? 132 : 122)
+ if let fp = finger { home += P2(clamp((fp.x - 99) * 0.35, -34, 34), clamp((fp.y - 122) * 0.3, -30, 30)) }
+ if state == .dizzy { home += P2(cos(t * 3.4), sin(t * 3.4)) * 9 }
+ let wc = TAU * 2.2
+ let pull: P2 = (home - center) * (wc * wc), damp: P2 = cv * (wc * 1.0)
+ cv += (pull - damp) * dt; center += cv * dt
+ let trail: [Double] = [5, 5, 8, 6, 6]
+ if finger != nil { for i in 0..<5 { parts[i].v -= cv * (dt * trail[i]) } } // they trail behind
+ hop.v += 1100 * dt; hop.y += hop.v * dt; if hop.y > 0 { hop.y = 0; hop.v = 0 }
+ // needs you: a knock every few seconds
+ if state == .needs {
+ let was = knock; knock += dt; if knock >= 3.2 { knock = 0 }
+ if was < 0.2 && knock >= 0.2 { hop.v = -120; r.onHaptic?(.strong); for i in 0..<5 { parts[i].v += P2(0, 60) } }
+ }
+ // blocked: a shake of the head now and then
+ shakeT = state == .blocked ? shakeT + dt : 0
+ minis += ((state == .subagents ? 1 : 0) - minis) * min(1, dt * 3)
+ // asleep: z's float up
+ if state == .sleep {
+ nextZ -= dt; if nextZ <= 0 { nextZ = 1.6; zs.append(Z(x: center.x + 34, y: center.y - 30, t: 0)) }
+ }
+ for i in zs.indices { zs[i].t += dt * (state == .sleep ? 1 : 4); zs[i].y -= 14 * dt; zs[i].x += 5 * dt } // awake, they clear fast
+ zs.removeAll { $0.t > 2.6 }
+ let moving = abs(wob.v) > 0.05 || blush > 0.02 && blush < 0.98 || parts.contains { abs($0.bv) > 0.05 || simd_length($0.v) > 3 || $0.pending != nil || abs($0.scv) > 0.05 } || blinkT >= 0 || simd_length(cv) > 3 || finger != nil || hop.v != 0
+ || state == .speaking || state == .listening || state == .dizzy || minis > 0.02 || !zs.isEmpty
+ if moving { busyAt = t }
+ }
+
+ // MARK: input
+
+ func motion(_ r: Rig, _ ax: Double, _ ay: Double, _ az: Double) {
+ let e = max(0, sqrt(ax * ax + ay * ay + az * az) - 0.9)
+ trauma = min(1, trauma + e * e * 0.03)
+ energy += e * e * 0.05
+ if energy > 0.4 && state != .dizzy && state != .sleep { energy = 0; r.onHaptic?(.strong); r.setState(.dizzy) }
+ if e > 0 { busyAt = t }
+ }
+ /// The crown picks its face: each click the next one (round and round), kept.
+ func crown(_ r: Rig, _ delta: Double) {
+ let was = Int(floor(crownPos + 0.5))
+ crownPos += delta * 0.45
+ let now = Int(floor(crownPos + 0.5))
+ if now != was {
+ chosen = ((now % Self.deck.count) + Self.deck.count) % Self.deck.count
+ UserDefaults.standard.set(chosen, forKey: "squintFace")
+ r.onHaptic?(.click)
+ wob.v += (delta > 0 ? 1 : -1) * 2.4
+ for i in 0..<5 { parts[i].v += P2(0, delta > 0 ? -40 : 40) }
+ }
+ crownIdle = 0; fidget = nil; reaction = nil; busyAt = t
+ }
+ func touched(_ r: Rig, at pt: CGPoint) { finger = pt; touchAt = pt; touchT = t; lastDrag = (pt, t); busyAt = t }
+ func dragged(_ r: Rig, at pt: CGPoint) {
+ if let l = lastDrag, t - l.t > 0.005 {
+ let v = hypot(Double(pt.x - l.p.x), Double(pt.y - l.p.y)) / (t - l.t)
+ fingerSpeed = max(fingerSpeed * 0.7, v)
+ }
+ lastDrag = (pt, t); finger = pt; busyAt = t
+ }
+ func released(_ r: Rig) { finger = nil; lastDrag = nil }
+ /// A tap: where it lands decides. On an eye, that eye squeezes shut and the other goes wide; on the mouth, a giggle;
+ /// anywhere else, a wink. Four in a row: −_−.
+ func poke(_ r: Rig) {
+ pokes = pokes.filter { t - $0 < 3 } + [t]
+ busyAt = t
+ if pokes.count >= 4 { pokes = []; annoyed = 2.6; wink = 0; reaction = nil; return }
+ guard annoyed <= 0 else { return }
+ let s = 1.28 * cur.scale, at = touchAt.map { P2($0.x, $0.y) } ?? center
+ let eyeL = center + P2(-31, -16 + cur.eyeY) * s, eyeR = center + P2(31, -16 + cur.eyeY) * s, mouth = center + P2(0, 24 + cur.mouthY) * s
+ if simd_length(at - eyeL) < 24 || simd_length(at - eyeR) < 24 {
+ let left = simd_length(at - eyeL) < simd_length(at - eyeR)
+ reaction = (Face(le: left ? "chev" : "bigring", re: left ? "bigring" : "chev", mouth: "o", lb: left ? "angry" : "up", rb: left ? "up" : "angry"), t + 0.95)
+ parts[left ? 0 : 1].v += P2(left ? -40 : 40, 30); hop.v = -70
+ } else if simd_length(at - mouth) < 28 {
+ reaction = (Face(le: "happy", mouth: "D", eyeY: -2), t + 1.1); hop.v = -150
+ } else {
+ wink = 0.75; hop.v = -110
+ }
+ }
+ /// Stroked across: ◠ ◠, a big smile and a blush, while you keep stroking.
+ func pet(_ r: Rig) { petFor = 0.5; busyAt = t }
+ func deny(_ r: Rig) {}
+ func hit(_ pt: CGPoint) -> Bool { abs(Double(pt.x) - center.x) < 70 && abs(Double(pt.y) - center.y) < 60 }
+
+ // MARK: drawing
+
+ /// How open its eyes are in a blink: shut fast (faster and faster), a beat closed, open a hair past and back.
+ private var lid: Double {
+ guard blinkT >= 0 else { return 1 }
+ if blinkT < 0.075 { let u = blinkT / 0.075; return 1 - 0.93 * u * u }
+ if blinkT < 0.115 { return 0.07 }
+ let u = min(1, (blinkT - 0.115) / 0.21), c = 1.3
+ return 0.07 + 0.93 * (1 + (c + 1) * pow(u - 1, 3) + c * pow(u - 1, 2))
+ }
+
+ func draw(_ r: Rig, _ ctx: GraphicsContext) {
+ // dimmed (always on): the whole face at half brightness as one layer. Faded stroke by stroke, the places where
+ // the chalk's strips overlap came out brighter than the rest (half on half).
+ if r.ao { var c = ctx; c.opacity = 0.5; c.drawLayer { l in self.paint(r, l) } } else { paint(r, ctx) }
+ }
+
+ private func paint(_ r: Rig, _ ctx: GraphicsContext) {
+ let p = r.pose(raw: true)
+ var g = ctx
+ // it breathes: slower and deeper asleep
+ let breath = state == .sleep ? sin(t * TAU / 5.5) * 1.8 : sin(t * TAU / 4.4)
+ let s = 1.28 * cur.scale * (1 + 0.012 * breath) * (state == .needs ? 1 + 0.05 * max(0, 1 - knock / 0.4) : 1)
+ let headShake = state == .blocked ? sin(shakeT * 22) * 6 * max(0, 1 - (shakeT.truncatingRemainder(dividingBy: 2.6)) / 0.5) : 0
+ g.translateBy(x: center.x + headShake, y: center.y + hop.y + 0.9 * breath)
+ g.rotate(by: .radians(cur.tilt + wob.a + (state == .dizzy ? sin(t * 2.6) * 0.14 : 0)))
+ g.scaleBy(x: s, y: s)
+ // where they look: the rig's gaze, or your finger
+ var gx = p.eye.gx, gy = p.eye.gy
+ if let fp = finger { let d = P2(fp.x, fp.y) - center; let l = max(1, simd_length(d)); gx = d.x / l * min(1, l / 40); gy = d.y / l * min(1, l / 40) }
+ if state == .working { gx = sin(t * 2.2) * 0.9; gy = 0.2 }
+ let look = P2(gx * 6, gy * 4)
+ let gap = 31.0
+ let places: [P2] = [P2(-gap, -16 + cur.eyeY) + look, P2(gap, -16 + cur.eyeY) + look,
+ P2(0, 24 + cur.mouthY) + look * 0.4,
+ P2(-gap, -44 + cur.browY) + look * 0.5, P2(gap, -44 + cur.browY) + look * 0.5]
+ let widths = [8.0, 8.0, 8.0, 7.0, 7.0]
+ let l = lid
+ for i in 0..<5 {
+ var pts = parts[i].shape
+ // the mouth with a voice: talking, it opens and shuts; listening, its o grows with yours; asleep, it breathes
+ var live = 1.0
+ if i == 2 && parts[i].pending == nil {
+ if state == .speaking && parts[i].fam == .talk { pts = Strokes.mix(pts, Self.talk(mv), min(1, parts[i].b)) }
+ if state == .listening && parts[i].fam == .loop { live = 0.8 + 0.9 * mv }
+ if state == .sleep && parts[i].fam == .loop { live = 0.75 + 0.35 * (0.5 + 0.5 * sin(t * TAU / 4)) }
+ }
+ if state == .dizzy && i < 2 {
+ let a = t * 5 * (i == 0 ? 1 : -1); pts = pts.map { P2($0.x * cos(a) - $0.y * sin(a), $0.x * sin(a) + $0.y * cos(a)) }
+ }
+ // squashed: in a swap (narrower and flatter), in a blink (flatter, a little wider), about a point a bit low
+ let sc = max(0, parts[i].sc)
+ var sx = 0.3 + 0.7 * sc, sy = sc
+ if i < 2 && (parts[i].fam == .v || parts[i].fam == .loop) { sy *= l; sx *= 1 + 0.14 * (1 - l) }
+ sx *= live; sy *= live
+ let ay = i < 2 ? 4.0 : 0
+ // idle, each part drifts a hair on its own
+ let drift = P2(sin(t * 0.63 + Double(i) * 1.9), cos(t * 0.47 + Double(i) * 2.7)) * 0.45
+ let o = places[i] + parts[i].off + drift
+ penPart(i, g.translated(o.x, o.y), pts, widths[i], sx, sy, ay)
+ }
+ // blushing: a few short pink chalk strokes under each eye
+ if blush > 0.02 {
+ let pink = Color(red: 1, green: 0.56, blue: 0.62), bg = g.faded(blush)
+ for side in [-1.0, 1.0] {
+ for k in 0..<3 {
+ let c = P2(side * 40 + (Double(k) - 1) * 5.5, 6 + cur.eyeY)
+ Chalk.draw(bg, [c + P2(-2, 3.5), c + P2(2, -3.5)], width: 2.8, seed: 40 + Double(k) + side * 5, color: pink)
+ }
+ }
+ }
+ // done: a few short strokes flying out from it, for a moment
+ if state == .done, r.stateT < 0.9 {
+ let k = r.stateT / 0.9
+ for j in 0..<6 {
+ let a = -Double.pi / 2 + (Double(j) - 2.5) * 0.42 + (j > 2 ? 0.6 : -0.6), r0 = 70 + 26 * k, r1 = r0 + 12
+ pen(g.faded(1 - k), [P2(cos(a), sin(a)) * r0, P2(cos(a), sin(a)) * r1], 4.5, seed: Double(j))
+ }
+ }
+ // subagents: small faces around it
+ if minis > 0.02 {
+ for k in 0..<3 {
+ let a = t * 0.8 + Double(k) * TAU / 3, c = P2(cos(a) * 84, sin(a) * 66) * minis
+ let m = g.faded(minis * (0.6 + 0.4 * (0.5 + 0.5 * sin(a))))
+ for side in [-1.0, 1.0] { pen(m, [c + P2(side * 8, -10), c + P2(side * 8 + 0.6, -2)], 3.6, seed: Double(k) + side) }
+ pen(m, Strokes.resample(Strokes.arc(c + P2(0, -6), 11, Double.pi * 0.35, Double.pi * 0.65), 12), 3.4, seed: Double(k) + 9)
+ }
+ }
+ // z's
+ for z in zs {
+ let a = clamp(1 - z.t / 2.6, 0, 1) * clamp(z.t / 0.4, 0, 1), q = P2(z.x - center.x, z.y - center.y), sz = 6 + z.t * 2
+ pen(ctx.faded(a).translated(center.x, center.y), [q + P2(-sz, -sz), q + P2(sz, -sz), q + P2(-sz, sz), q + P2(sz, sz)], 3.4, seed: z.x)
+ }
+ }
+
+ func front(_ r: Rig, _ ctx: GraphicsContext) {}
+
+ // MARK: the pen
+
+ /// How its lines are drawn: "chalk" (a white paint marker dragged over a board: solid, pressing in, lifting off dry
+ /// and split, chalk grain at its edges; see `Chalk`), "clean" (solid, smooth, round ends), or "marker" (the first
+ /// version: a wobbling ribbon, cut flat). Set by the `squintLook` default (a launch argument: -squintLook clean).
+ static let look = UserDefaults.standard.string(forKey: "squintLook") ?? "chalk"
+
+ /// One stroke through `pts` (the shape, in its own place), each point then moved by `place` (squashed, put on the
+ /// face). The pen keeps its width however the shape is squashed; a shape still growing from nothing starts thin.
+ private func pen(_ g: GraphicsContext, _ pts: [P2], _ w0: Double, seed: Double, _ place: ((P2) -> P2)? = nil) {
+ guard pts.count > 1 else { return }
+ let len = Strokes.length(pts)
+ guard len > 0.3 else { return }
+ let w = w0 * clamp(len / (w0 * 1.2), 0.3, 1)
+ let g = len < w0 * 1.5 ? g.faded(len / (w0 * 1.5)) : g // growing from nothing (a brow coming), it fades in
+ switch Self.look {
+ case "marker": Strokes.marker(g, place.map { pts.map($0) } ?? pts, width: w, color: .white, seed: seed)
+ case "clean":
+ g.stroke(Self.smoothPath(place.map { pts.map($0) } ?? pts), with: .color(.white), style: StrokeStyle(lineWidth: w, lineCap: .round, lineJoin: .round))
+ default: Chalk.draw(g, pts, width: w, seed: seed, squash: place)
+ }
+ }
+
+ /// Each face part's stroke as last made, and what it was made from: it's made again only when the part's shape, squash
+ /// or width changes (a blink, a swap, a new face), so a face holding still costs only its drawing.
+ private var made: [(key: [Float], stroke: Chalk.Stroke)?] = Array(repeating: nil, count: 5)
+
+ /// Part `i`'s stroke (its shape `pts`, squashed `sx`, `sy` about `ay`) into `g`, already moved to its place.
+ private func penPart(_ i: Int, _ g: GraphicsContext, _ pts: [P2], _ w0: Double, _ sx: Double, _ sy: Double, _ ay: Double) {
+ let squash: (P2) -> P2 = { q in P2(q.x * sx, ay + (q.y - ay) * sy) }
+ guard Self.look != "marker" && Self.look != "clean" else { pen(g, pts, w0, seed: Double(i) * 3.1, squash); return }
+ let len = Strokes.length(pts)
+ guard pts.count > 1, len > 0.3 else { return }
+ let w = w0 * clamp(len / (w0 * 1.2), 0.3, 1)
+ var key = [Float](); key.reserveCapacity(pts.count * 2 + 3)
+ for q in pts { key.append(Float((q.x * 50).rounded())); key.append(Float((q.y * 50).rounded())) }
+ key += [Float((sx * 500).rounded()), Float((sy * 500).rounded()), Float((w * 50).rounded())]
+ if made[i]?.key != key { made[i] = (key, Chalk.make(pts, width: w, seed: Double(i) * 3.1, squash: squash)) }
+ made[i]!.stroke.draw(len < w0 * 1.5 ? g.faded(len / (w0 * 1.5)) : g) // growing from nothing, it fades in
+ }
+
+ /// A smooth path through the points (closed if they meet).
+ static func smoothPath(_ p: [P2]) -> Path {
+ let closed = p.count > 3 && simd_length(p[0] - p[p.count - 1]) < 0.5
+ return closed ? Strokes.smoothClosed(Array(p.dropLast())) : Strokes.smoothOpen(p)
+ }
+}
+
+extension GraphicsContext {
+ func translated(_ x: Double, _ y: Double) -> GraphicsContext { var c = self; c.translateBy(x: x, y: y); return c }
+}
diff --git a/app/ChumsWatch/Rig/Staged.swift b/app/ChumsWatch/Rig/Staged.swift
new file mode 100644
index 0000000..70f627a
--- /dev/null
+++ b/app/ChumsWatch/Rig/Staged.swift
@@ -0,0 +1,41 @@
+import SwiftUI
+
+/// A character that stages itself: it draws the whole screen its own way (Noodle's rendered frames, Pix's pixels)
+/// instead of being posed by the shared rig and placed in a world. It reads the rig's state, time, hold and caption.
+/// The renderer draws the status label on top of it, then its `front`, then captions over a scrim.
+protocol Staged: AnyObject {
+ /// Draws its own approval card (Noodle balances it on its hair), so the renderer doesn't.
+ var ownsApproval: Bool { get }
+ /// It shows the caption itself in this state (Pix's dialog box), so the renderer doesn't.
+ func ownsCaption(_ r: Rig) -> Bool
+ /// Captions sit at the top instead of the bottom in this state (when the character fills the bottom).
+ func captionTop(_ r: Rig) -> Bool
+ /// How long it plays out done and dizzy before settling (its animations are longer than the rig's 2.4 / 2.6 s).
+ var holds: [ChumsState: Double] { get }
+ func onState(_ r: Rig, _ s: ChumsState, prev: ChumsState?, variant: Bool)
+ func step(_ r: Rig, _ dt: Double)
+ func draw(_ r: Rig, _ ctx: GraphicsContext)
+ func front(_ r: Rig, _ ctx: GraphicsContext)
+ func hit(_ pt: CGPoint) -> Bool
+ /// A finger came down on the screen at `pt` (design points).
+ func touched(_ r: Rig, at pt: CGPoint)
+ /// The watch moved: its acceleration in g on the screen's axes (x right, y down, z toward you).
+ func motion(_ r: Rig, _ ax: Double, _ ay: Double, _ az: Double)
+ func poke(_ r: Rig)
+ func pet(_ r: Rig)
+ func deny(_ r: Rig)
+ /// The crown turned by `delta` (its own units), when this character takes it.
+ func crown(_ r: Rig, _ delta: Double)
+ /// The finger moved to `pt` (design points) while down; it came off.
+ func dragged(_ r: Rig, at pt: CGPoint)
+ func released(_ r: Rig)
+ /// Nothing in it is moving fast: it can draw at 30 frames a second.
+ var calm: Bool { get }
+}
+
+extension Staged {
+ func crown(_ r: Rig, _ delta: Double) {}
+ func dragged(_ r: Rig, at pt: CGPoint) {}
+ func released(_ r: Rig) {}
+ var calm: Bool { false }
+}
diff --git a/app/ChumsWatch/Rig/StretchFrames.swift b/app/ChumsWatch/Rig/StretchFrames.swift
new file mode 100644
index 0000000..2196f4a
--- /dev/null
+++ b/app/ChumsWatch/Rig/StretchFrames.swift
@@ -0,0 +1,101 @@
+import Foundation
+import ImageIO
+import CoreGraphics
+
+/// Noodle's frames on the watch: one HEIC image sequence per clip in the app bundle (ChumsWatch/Noodle/<clip>.heics,
+/// made by tools/noodle-watch.sh from the Blender renders), decoded a frame at a time off the main thread. The
+/// player asks for the frame it needs now; it gets it if it's decoded, the closest one before it otherwise, and the
+/// decoder works ahead. A few frames are kept (each 396 × 484 is about 0.75 MB decoded).
+final class StretchFrames: @unchecked Sendable {
+ static let shared = StretchFrames()
+ // two decoders, each with its own image sources, take alternate frames (a frame takes 32–60 ms on a Series 7 and
+ // 24 fps leaves 42, so one alone falls behind), a step below the screen's priority: the screen (drawing, the
+ // conversation card sliding) always comes first, and a frame that isn't ready shows the one before it
+ private let queues = [DispatchQueue(label: "chums.noodle.decode.0", qos: .userInitiated),
+ DispatchQueue(label: "chums.noodle.decode.1", qos: .userInitiated)]
+ private let lock = NSLock()
+ private var sources: [[String: CGImageSource]] = [[:], [:]] // sources[i] only touched on queues[i]
+ private var cache: [String: CGImage] = [:], order: [String] = []
+ private var pending = Set<String>()
+ private let keep = 14
+ private(set) var decodeMs = 0.0 // the last decode's time
+ // for the event log: decodes and their total time, and frames asked for before they were ready
+ private var stats = (decodes: 0, totalMs: 0.0, maxMs: 0.0, asks: 0, misses: 0)
+ func takeStats() -> String? {
+ lock.lock(); defer { stats = (0, 0, 0, 0, 0); lock.unlock() }
+ guard stats.decodes > 0 else { return nil }
+ return String(format: "noodle: %d frames decoded, avg %.1f ms, max %.0f ms; %d of %d asked frames weren't ready",
+ stats.decodes, stats.totalMs / Double(stats.decodes), stats.maxMs, stats.misses, stats.asks)
+ }
+
+ private static func key(_ clip: String, _ f: Int) -> String { "\(clip):\(f)" }
+ /// Offline renders (OfflineRender) wait for each frame, so none is missing from the pictures.
+ var waits = false
+
+ /// The frame if it's ready (else nil), and decoding of it and the next two is scheduled.
+ func frame(_ clip: String, _ f: Int) -> CGImage? {
+ if waits { return decodeNow(clip, f) }
+ lock.lock(); let hit = cache[Self.key(clip, f)]; stats.asks += 1; if hit == nil { stats.misses += 1 }; lock.unlock()
+ for k in f...(f + 4) { schedule(clip, k) }
+ return hit
+ }
+
+ /// A clip about to play: its first frames, so the cut doesn't wait.
+ func preload(_ clip: String) { if !waits { for k in 0..<6 { schedule(clip, k) } } }
+
+ /// The frame, decoded now if it isn't yet (on its decoder's queue, which owns its image sources).
+ private func decodeNow(_ clip: String, _ f: Int) -> CGImage? {
+ let k = Self.key(clip, f)
+ lock.lock(); let hit = cache[k]; lock.unlock()
+ if let hit { return hit }
+ guard let im = queues[f % 2].sync(execute: { decode(clip, f, worker: f % 2) }) else { return nil }
+ lock.lock(); cache[k] = im; order.append(k); while order.count > keep { cache[order.removeFirst()] = nil }; lock.unlock()
+ return im
+ }
+
+ private func schedule(_ clip: String, _ f: Int) {
+ let k = Self.key(clip, f)
+ lock.lock()
+ if cache[k] != nil || pending.contains(k) { lock.unlock(); return }
+ pending.insert(k); lock.unlock()
+ let w = f % 2
+ queues[w].async { [self] in
+ let t0 = CFAbsoluteTimeGetCurrent()
+ let im = decode(clip, f, worker: w)
+ decodeMs = (CFAbsoluteTimeGetCurrent() - t0) * 1000
+ lock.lock()
+ stats.decodes += 1; stats.totalMs += decodeMs; stats.maxMs = max(stats.maxMs, decodeMs)
+ pending.remove(k)
+ if let im { cache[k] = im; order.append(k); while order.count > keep { cache[order.removeFirst()] = nil } }
+ lock.unlock()
+ }
+ }
+
+ private func decode(_ clip: String, _ f: Int, worker w: Int) -> CGImage? {
+ if sources[w][clip] == nil {
+ guard let url = Bundle.main.url(forResource: clip, withExtension: "heics", subdirectory: "Noodle"),
+ let src = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
+ sources[w][clip] = src
+ if sources[w].count > 6 { sources[w] = sources[w].filter { $0.key == clip } } // a handful of clips open at once
+ }
+ guard let src = sources[w][clip], f < CGImageSourceGetCount(src) else { return nil }
+ return CGImageSourceCreateImageAtIndex(src, f, [kCGImageSourceShouldCacheImmediately: true] as CFDictionary)
+ }
+
+ /// Decodes a whole clip in order on the decode queue and reports the times (launch with -noodleBench YES).
+ func bench(_ clip: String, done: @escaping (String) -> Void) {
+ queues[0].async { [self] in
+ var times: [Double] = []
+ var f = 0
+ while true {
+ let t0 = CFAbsoluteTimeGetCurrent()
+ guard decode(clip, f, worker: 0) != nil else { break }
+ times.append((CFAbsoluteTimeGetCurrent() - t0) * 1000); f += 1
+ }
+ guard !times.isEmpty else { done("noodle bench: \(clip) didn't decode"); return }
+ let sorted = times.sorted(), avg = times.reduce(0, +) / Double(times.count)
+ done(String(format: "noodle bench %@: %d frames, first %.0f ms, avg %.1f ms, p95 %.1f ms, max %.0f ms",
+ clip, times.count, times[0], avg, sorted[Int(Double(sorted.count) * 0.95)], sorted.last!))
+ }
+ }
+}
diff --git a/app/ChumsWatch/Rig/StretchStage.swift b/app/ChumsWatch/Rig/StretchStage.swift
new file mode 100644
index 0000000..37eebf5
--- /dev/null
+++ b/app/ChumsWatch/Rig/StretchStage.swift
@@ -0,0 +1,547 @@
+import SwiftUI
+
+/// Stretch on the watch: the same player as design/noodle/player.part, frame for frame.
+/// Each state is a pool of segments: a calm rest loop and several beats that start and end on the same pose, chained at
+/// random (never the same beat twice in a row). noodle.json says, frame by frame, where its hair top, face and the glass
+/// contact are on screen, so the screen plays along: the approval card rides on its hair, tool calls drop on its head and
+/// get bonked away, the glass fogs and ripples where it knocks.
+final class StretchStage: Staged {
+ static let shared = StretchStage()
+
+ // MARK: clip data (ChumsWatch/Noodle/noodle.json, from design/noodle/renders/clips.json)
+
+ struct Clip: Decodable {
+ let n: Int
+ let loop: Bool?
+ let role: String?
+ let state: String?
+ let events: [String: Frames]?
+ let frames: [[Double]]?
+ struct Frames: Decodable {
+ let list: [Int]
+ init(from d: Decoder) throws {
+ let c = try d.singleValueContainer()
+ if let i = try? c.decode(Int.self) { list = [i] } else { list = try c.decode([Int].self) }
+ }
+ }
+ }
+ private struct Meta: Decodable { let fps: Double; let beat_chance: [String: Double]; let clips: [String: Clip] }
+ private let meta: Meta? = {
+ guard let url = Bundle.main.url(forResource: "noodle", withExtension: "json", subdirectory: "Noodle"),
+ let data = try? Data(contentsOf: url) else { return nil }
+ return try? JSONDecoder().decode(Meta.self, from: data)
+ }()
+ private var CL: [String: Clip] { meta?.clips ?? [:] }
+ private var fps: Double { meta?.fps ?? 24 }
+
+ private func of(_ state: String, _ role: String) -> [String] { CL.keys.filter { CL[$0]?.state == state && CL[$0]?.role == role }.sorted() }
+ private func count(_ name: String) -> Int { CL[name]?.n ?? 1 }
+ private func isLoop(_ name: String) -> Bool { CL[name]?.loop == true }
+
+ // MARK: player state
+
+ struct Card { var phase = "fall"; var x = 99.0, y = 38.0, rot = 0.0, vx = 0.0, vy = 0.0, vr = 0.0; var text = ""; var kind = "read" }
+ enum FXKind { case glass, confetti, bonk, z }
+ struct FX { var k: FXKind; var x: Double, y: Double; var t = 0.0; var vx = 0.0, vy = 0.0, r = 0.0, vr = 0.0; var c = Color.white; var amp = 1.0 }
+
+ /// How long one clip takes to dissolve into the next when the state changes (eased): long enough to read as one
+ /// movement rather than a cut.
+ private static let dissolve = 0.3
+ /// The dissolve itself stays short (two poses overlaid read as a ghost); the camera's move carries on after it.
+ private var fadeLength: Double { Self.dissolve }
+ private var clip = "idle_rest", f = 0.0
+ private var queue: [String] = []
+ private var fade: (image: CGImage?, t: Double)?
+ /// Match moves. The clips of each state are framed their own way (its face higher or lower, nearer or farther), so a
+ /// cut from one state to another would jump. Instead the two shots are lined up on the face, and the shot moves:
+ /// cutting in closer, the outgoing frame pushes in to the new framing as it dissolves away; cutting out wider, the
+ /// incoming clip starts pushed in to the old framing and eases out to its own. Always a push in, never a pull out,
+ /// so the bottom edge of the frames (where its body is cut off) never comes into view.
+ /// A placement maps a frame's face `from` to `to`, scaled `k` about it.
+ private struct Place { var from: CGPoint; var to: CGPoint; var k: Double
+ var xf: CGAffineTransform {
+ CGAffineTransform(translationX: -from.x, y: -from.y).concatenating(CGAffineTransform(scaleX: k, y: k)).concatenating(CGAffineTransform(translationX: to.x, y: to.y))
+ }
+ func toward(_ b: Place, _ e: Double) -> Place {
+ Place(from: from, to: CGPoint(x: lerp(Double(to.x), Double(b.to.x), e), y: lerp(Double(to.y), Double(b.to.y), e)), k: lerp(k, b.k, e))
+ }
+ }
+ private static let glide = 0.6
+ private var glideIn: (start: Place, t: Double)? // the incoming clip, easing out to its own framing
+ private var fadeMove: (start: Place, end: Place)? // the outgoing frame, pushing in as it dissolves
+ private func ease(_ u: Double) -> Double { let v = clamp(u, 0, 1); return v * v * (3 - 2 * v) }
+ /// The current clip's placement right now (identity when it's in its own framing).
+ private var placeNow: CGAffineTransform {
+ guard let g = glideIn else { return .identity }
+ let id = Place(from: g.start.from, to: g.start.from, k: 1)
+ return g.start.toward(id, ease(g.t / Self.glide)).xf
+ }
+ private func faceOf(_ name: String, _ i: Int) -> (face: CGPoint, size: Double)? {
+ guard let fr = CL[name]?.frames, !fr.isEmpty else { return nil }
+ let a = fr[max(0, min(fr.count - 1, i))]
+ guard a.count >= 4 else { return nil }
+ return (CGPoint(x: a[2], y: a[3]), max(10, hypot(a[2] - a[0], a[3] - a[1])))
+ }
+ /// Keeps a placement from lifting the frame's bottom edge (its cut-off body) into view.
+ private func grounded(_ p: Place) -> Place {
+ var q = p
+ let bottom = Double(q.to.y) + (242 - Double(q.from.y)) * q.k
+ if bottom < 246 { q.to.y += 246 - bottom }
+ return q
+ }
+ private var bags: [String: [String]] = [:], last: String?
+ private var work = "work_read"
+ private var tool: Card?, card: Card?
+ private var fx: [FX] = []
+ private var fog = 0.0, zT = 0.0, flex = 0.0, held = false
+ /// The gel: Noodle sloshes with the watch. A damped spring the watch's own acceleration drives, standing on the
+ /// screen's bottom edge like a puppet on a stick: sideways it leans and its hair whips, up and down it squashes
+ /// and stretches, toward you it presses into the glass and, hard enough, knocks it (the liquid-glass ring).
+ private var gel = (x: 0.0, y: 0.0, z: 0.0, vx: 0.0, vy: 0.0, vz: 0.0), push = (x: 0.0, y: 0.0, z: 0.0)
+ /// How hard it's being shaken, 0…1: every move of the watch adds the square of how far it goes over 0.9 g (a gentle
+ /// sway adds almost nothing, a hard shake fills it in a quarter of a second), and it drains in about a second.
+ /// The camera answers it (it punches in, shakes by its square, so only hard shakes really shake, and rolls), and so
+ /// does the gel: it wobbles, squashing and stretching fast, and a wave runs up its body from the base.
+ private var trauma = 0.0
+ private var cam = (z: 1.0, vz: 0.0)
+ private var rawFace = (x: 96.0, y: 120.0) // the face in the frame, before the gel and the camera
+ /// The crown stretches it: everything below its eyes grows taller (and thinner, keeping its volume) or squashes,
+ /// the head riding on top undistorted; let go, it springs back and wobbles like jelly.
+ private var neck = (k: 1.0, v: 0.0, to: 1.0), crownIdle = 9.0
+ private var seam: Double { rawFace.y + 20 } // just below its eyes: above it moves, below it stretches
+ private var view = CGAffineTransform.identity // this frame's, for the glass rings' lenses
+ private var shown: CGImage? // the frame on screen, kept while the next decodes
+ private var stateName = "idle"
+ private var demoCallT = 2.5 // demo mode: a made-up tool call every few seconds
+
+ let ownsApproval = true
+ let holds: [ChumsState: Double] = [.done: 4.4, .dizzy: 4.8]
+ func captionTop(_ r: Rig) -> Bool { r.state == .needs }
+ func ownsCaption(_ r: Rig) -> Bool { false }
+
+ private func name(_ s: ChumsState) -> String { s.rawValue }
+ private func restFor(_ s: String) -> String { s == "working" ? work : (of(s, "rest").first ?? "idle_rest") }
+ private var clipNow: String { held ? "approval_hold" : clip }
+ private func frameNo(_ r: Rig) -> Int {
+ if held { return Int((clamp(r.hold, 0, 1) * Double(count("approval_hold") - 1)).rounded()) }
+ let c = count(clip)
+ return isLoop(clip) ? Int(f) % c : min(c - 1, Int(f))
+ }
+
+ /// Where things are on screen this frame: hair top, face, roll, how hard it presses the glass.
+ private struct Anchors { var hx = 120.0, hy = 40.0, fx = 96.0, fy = 120.0, roll = 0.0, press = 0.0, rise = 0.0 }
+ private func anchors(_ r: Rig) -> Anchors {
+ guard let fr = CL[clipNow]?.frames, frameNo(r) < fr.count, fr[frameNo(r)].count >= 7 else { return Anchors() }
+ let a = fr[frameNo(r)]
+ rawFace = (a[2], a[3])
+ let T = placeNow.concatenating(viewTransform(r.t)), h = CGPoint(x: a[0], y: neckY(a[1])).applying(T), f = CGPoint(x: a[2], y: neckY(a[3])).applying(T)
+ return Anchors(hx: h.x, hy: h.y, fx: f.x, fy: f.y, roll: a[4] - gel.x * 0.5, press: a[5], rise: a[6])
+ }
+
+ private func play(_ r: Rig, _ n: String, from: Double = 0, then: [String] = [], dissolve: Bool = true) {
+ guard CL[n] != nil else { return }
+ let was = dissolve ? faceOf(clipNow, frameNo(r)) : nil, wasPlace = placeNow
+ if dissolve { fade = (shown, 0); fadeMove = nil }
+ clip = n; f = from; queue = then; held = false
+ // line the two shots up on the face (see Place)
+ if dissolve, let o = was, let nw = faceOf(n, Int(from)) {
+ let oFace = o.face.applying(wasPlace), oSize = o.size * hypot(Double(wasPlace.a), Double(wasPlace.b))
+ let off = hypot(Double(oFace.x - nw.face.x), Double(oFace.y - nw.face.y)), ratio = nw.size / oSize
+ glideIn = nil
+ if off > 3 || abs(ratio - 1) > 0.04 {
+ if ratio >= 1 { // closer: the old frame pushes in to the new framing
+ let start = Place(from: o.face, to: oFace, k: oSize / o.size)
+ fadeMove = (start, grounded(Place(from: o.face, to: nw.face, k: nw.size / o.size)))
+ } else { // wider: the new clip starts pushed in, eases out
+ glideIn = (grounded(Place(from: nw.face, to: oFace, k: oSize / nw.size)), 0)
+ }
+ }
+ }
+ if n == "approval_in" { card = Card(phase: "fall", x: 99, y: 38, text: r.approvalTitle) }
+ if n == "bump", let e = r.worlds.nextEvent(r) {
+ let kind = e.kind == .read ? "read" : e.kind == .edit ? "edit" : e.kind == .agent ? "search" : "run"
+ tool = Card(phase: "fall", text: e.text, kind: kind)
+ }
+ StretchFrames.shared.preload(n)
+ }
+
+ /// The next segment of the state's pool: its rest loop again, or a beat (never the same one twice in a row).
+ /// It's picked half a second before the current one ends, so its first frames are decoded by the cut.
+ private var upcoming: String?
+ private func pickNext() -> String {
+ let beats = of(stateName, "beat")
+ if !beats.isEmpty && Double.random(in: 0..<1) < (meta?.beat_chance[stateName] ?? 0.4) {
+ var bag = bags[stateName] ?? []
+ if bag.isEmpty {
+ bag = beats.shuffled()
+ if bag.count > 1 && bag.last == last { bag.insert(bag.removeLast(), at: 0) }
+ }
+ last = bag.removeLast(); bags[stateName] = bag
+ return last!
+ }
+ return restFor(stateName)
+ }
+ private func nextSegment(_ r: Rig) {
+ let n = upcoming ?? pickNext(); upcoming = nil
+ play(r, n, dissolve: false)
+ }
+
+ private func next(_ r: Rig) {
+ if !queue.isEmpty { let q = queue.removeFirst(); return play(r, q, then: queue, dissolve: false) }
+ let role = CL[clip]?.role ?? ""
+ // segments of the current state end on its rest pose; anything else (a reaction, another state's clip) dissolves in
+ let seamless = (CL[clip]?.state == stateName && ["rest", "beat", "enter"].contains(role)) || (clip == "bump" && stateName == "working")
+ if seamless { return nextSegment(r) }
+ play(r, restFor(stateName), dissolve: true)
+ }
+
+ private func event(_ r: Rig, _ n: String, _ kind: String) {
+ let a = anchors(r)
+ switch kind {
+ case "contact": fx.append(FX(k: .glass, x: a.fx, y: a.fy + 6)); flexAt = nil; flex = 1; r.onHaptic?(.strong)
+ case "apex":
+ let cols = [Color(hex: 0xFFB020), Color(hex: 0xFF5FAE), Color(hex: 0xF4F5F6), Color(hex: 0xFF7A3D), Color(hex: 0x7FE0B0)]
+ for i in 0..<22 {
+ let ang = -Double.pi / 2 + rnd(-1.2, 1.2), sp = rnd(70, 180)
+ fx.append(FX(k: .confetti, x: a.hx, y: a.hy + 10, vx: cos(ang) * sp, vy: sin(ang) * sp, r: rnd(0, TAU), vr: rnd(-6, 6), c: cols[i % 5]))
+ }
+ case "bonk": fx.append(FX(k: .bonk, x: a.hx - 8, y: a.hy)); r.onHaptic?(.strong)
+ case "land" where n == "bump": if tool != nil { tool!.phase = "ride"; r.onHaptic?(.click) }
+ case "launch" where n == "bump": if tool != nil { tool!.phase = "fly"; tool!.vx = 170; tool!.vy = -150; tool!.vr = 5; tool!.rot = 0 }
+ case "land" where n == "approval_in": if card != nil { card!.phase = "ride"; r.onHaptic?(.strong) }
+ case "launch" where n == "approval_allow": if card != nil { card!.phase = "fly"; card!.vx = 40; card!.vy = -420; card!.vr = 3.2 }
+ case "drop" where n == "approval_deny": if card != nil { card!.phase = "drop"; card!.vx = -30; card!.vy = 20; card!.vr = -2.4 }
+ default: break
+ }
+ }
+
+ // MARK: Staged
+
+ func onState(_ r: Rig, _ s: ChumsState, prev: ChumsState?, variant: Bool) {
+ if s == prev && prev != nil {
+ if s == .dizzy && clip == "dizzy" && f >= Double(count("dizzy") - 1) { play(r, "dizzy") } // shaken again
+ return
+ }
+ stateName = name(s); upcoming = nil
+ for k in of(stateName, "rest") + of(stateName, "enter") { StretchFrames.shared.preload(k) }
+ if tool != nil && tool!.phase != "fly" { tool!.phase = "fly"; tool!.vx = 60; tool!.vy = -200; tool!.vr = 3; tool!.rot = 0 }
+ if prev == .approval && s == .done && variant { return play(r, "approval_allow", then: ["done_in"]) }
+ if prev == .approval && s != .approval && card?.phase == "ride" { card!.phase = "drop"; card!.vx = -30; card!.vy = 20; card!.vr = -2.4 }
+ let enter = of(stateName, "enter")
+ if prev == .sleep && s != .sleep {
+ let fr = CL["popup"]?.frames ?? []
+ let from = fr.firstIndex { $0.count > 6 && $0[6] >= -2.75 } ?? 0
+ return play(r, "popup", from: Double(from), then: enter)
+ }
+ if s == .idle && ["react", "once"].contains(CL[clip]?.role ?? "") && clip != "dizzy" { queue = []; return } // finish the reaction, then idle
+ if s == .working { work = "work_read" }
+ if s == .dizzy { return play(r, "dizzy") }
+ if let e = enter.first { return play(r, e) }
+ play(r, restFor(stateName))
+ }
+
+ func poke(_ r: Rig) { play(r, "poke") }
+ func crown(_ r: Rig, _ delta: Double) {
+ let was = neck.to
+ neck.to = clamp(neck.to + delta * 0.05, 0.72, 1.55)
+ crownIdle = 0
+ if (was < 1.5 && neck.to >= 1.5) || (was > 0.75 && neck.to <= 0.75) { r.onHaptic?(.strong) } // as far as it goes
+ }
+ private func stepNeck(_ r: Rig, _ dt: Double) {
+ crownIdle += dt
+ // a moment after the crown stops, it lets go: back to its own height, overshooting a little and wobbling
+ if crownIdle > 0.6 && neck.to != 1 { if abs(neck.to - 1) > 0.15 { r.onHaptic?(.click) }; neck.to = 1 }
+ let held = crownIdle <= 0.6, w = TAU * (held ? 3.0 : 2.3), z = held ? 0.9 : 0.27
+ neck.v += (-w * w * (neck.k - neck.to) - 2 * z * w * neck.v) * dt
+ neck.k = clamp(neck.k + neck.v * dt, 0.62, 1.7)
+ }
+ /// Where a point of the frame goes when it's stretched: above the seam it moves up or down with the head, below
+ /// it it's stretched toward the bottom edge.
+ private func neckY(_ y: Double) -> Double {
+ let B = 242.0, S = seam, k = neck.k
+ return y < S ? y - (k - 1) * (B - S) : B - k * (B - y)
+ }
+ func motion(_ r: Rig, _ ax: Double, _ ay: Double, _ az: Double) {
+ push = (ax, ay, az)
+ let e = max(0, sqrt(ax * ax + ay * ay + az * az) - 0.9)
+ trauma = min(1, trauma + e * e * 0.03)
+ }
+
+ /// Where the frame is drawn: the gel's lean and squash, then the camera.
+ private func viewTransform(_ t: Double) -> CGAffineTransform { gelTransform(t).concatenating(cameraTransform(t)) }
+
+ /// The camera, about Noodle's face: zoomed in by the shake, shaken by its square, rolled, and never so far that the
+ /// bottom of its body (cut at the frame's edge) comes into view.
+ private func cameraTransform(_ t: Double) -> CGAffineTransform {
+ let s = trauma * trauma
+ func noise(_ a: Double, _ b: Double, _ c: Double) -> Double { sin(t * a) * 0.55 + sin(t * b + 1.3) * 0.3 + sin(t * c + 2.1) * 0.15 }
+ let z = max(1, cam.z), rot = 6 * DEG * s * noise(53.1, 89.7, 131.3)
+ var tx = 15 * s * noise(61.7, 97.3, 143.1), ty = 15 * s * noise(71.9, 109.1, 157.7)
+ let C = rawFace
+ let turn = CGAffineTransform(translationX: -C.x, y: -C.y).concatenating(CGAffineTransform(scaleX: z, y: z))
+ .concatenating(CGAffineTransform(rotationAngle: rot)).concatenating(CGAffineTransform(translationX: C.x, y: C.y))
+ // the stalk's bottom (x 40…158 on the bottom edge) stays below the screen; it can't slide in from the sides either
+ let lowest = [40.0, 99, 158].map { CGPoint(x: $0, y: 242).applying(turn).y }.min()!
+ ty = max(ty, 242 - lowest)
+ tx = clamp(tx, -(z - 1) * 99 - 18, (z - 1) * 99 + 18)
+ return turn.concatenating(CGAffineTransform(translationX: tx, y: ty))
+ }
+
+ /// The gel's lean, squash and push toward the glass this frame, anchored at the middle of the bottom edge.
+ private func gelTransform(_ t: Double) -> CGAffineTransform {
+ // shaken, it jiggles on top of the slosh: squash and stretch, and a lean, both fast
+ let s = trauma * trauma
+ let lean = clamp(gel.x, -34, 34) / 190 + 0.1 * s * sin(t * TAU * 5.1 + 1)
+ let sy = (1 - clamp(gel.y, -28, 28) / 140) * (1 + 0.13 * s * sin(t * TAU * 6.3)), sx = 1 / sqrt(sy)
+ let A = (x: 99.0, y: 242.0)
+ // x' = A.x + sx·(x − A.x) − lean·(y − A.y) + slide, y' = A.y + sy·(y − A.y)
+ let body = CGAffineTransform(a: sx, b: 0, c: -lean, d: sy, tx: A.x - sx * A.x + lean * A.y + gel.x * 0.18, ty: A.y - sy * A.y)
+ // pressed toward you it grows a little around its face
+ let grow = 1 + clamp(gel.z, 0, 0.08), C = rawFace
+ return body.concatenating(CGAffineTransform(translationX: C.x, y: C.y).scaledBy(x: grow, y: grow).translatedBy(x: -C.x, y: -C.y))
+ }
+
+ private func stepGel(_ r: Rig, _ dt: Double) {
+ // a dead band so walking with your keys doesn't keep it wobbling; above it the watch's moves drive the gel
+ func band(_ v: Double) -> Double { abs(v) < 0.12 ? 0 : v - (v > 0 ? 0.12 : -0.12) }
+ let w = TAU * 1.6, wy = TAU * 2.1, wz = TAU * 3.0, z = 0.16
+ gel.vx += (-w * w * gel.x - 2 * z * w * gel.vx - band(push.x) * 2000) * dt
+ gel.vy += (-wy * wy * gel.y - 2 * z * wy * gel.vy - band(push.y) * 2000) * dt
+ gel.vz += (-wz * wz * gel.z - 2 * 0.3 * wz * gel.vz - band(push.z) * 8) * dt
+ gel.x += gel.vx * dt; gel.y += gel.vy * dt; gel.z += gel.vz * dt
+ // the case: it can lean only so far before its hair hits the side
+ if abs(gel.x) > 34 { gel.x = gel.x > 0 ? 34 : -34; gel.vx = -gel.vx * 0.35 }
+ if abs(gel.y) > 28 { gel.y = gel.y > 0 ? 28 : -28; gel.vy = -gel.vy * 0.35 }
+ // toward you it presses up to the glass and bounces back (a shake makes no rings and no taps: only it moves)
+ if gel.z > 0.08 { gel.z = 0.08; gel.vz = -gel.vz * 0.3 }
+ if gel.z < -0.06 { gel.z = -0.06; gel.vz = -gel.vz * 0.3 }
+ stepCamera(dt)
+ }
+
+ private func stepCamera(_ dt: Double) {
+ trauma = max(0, trauma - dt * 0.75)
+ // the zoom follows the shake in, on a spring
+ cam.vz += ((1 + 0.32 * trauma - cam.z) * 140 - cam.vz * 15) * dt; cam.z += cam.vz * dt
+ }
+ /// Your finger on the glass: the same liquid-glass ring as its knock, running out from where you touched.
+ func touched(_ r: Rig, at pt: CGPoint) {
+ guard !r.ao else { return }
+ fx.append(FX(k: .glass, x: Double(pt.x), y: Double(pt.y))); flexAt = (Double(pt.x), Double(pt.y)); flex = 0.6
+ r.onHaptic?(.click)
+ }
+ private var flexAt: (Double, Double)?
+ func pet(_ r: Rig) { if clip != "pet" { play(r, "pet") } }
+ func deny(_ r: Rig) { play(r, "approval_deny") }
+
+ func hit(_ pt: CGPoint) -> Bool {
+ let a = lastAnchors
+ let dx = (Double(pt.x) - a.fx) / 56, dy = (Double(pt.y) - (a.fy - 24)) / 64
+ return dx * dx + dy * dy < 1
+ }
+ private var lastAnchors = Anchors()
+
+ func step(_ r: Rig, _ dt: Double) {
+ if r.ao { return } // dimmed: it holds its frame (no decoding while you can barely see it)
+ if let fd = fade { fade = fd.t + dt > fadeLength ? nil : (fd.image, fd.t + dt) }
+ if fade == nil { fadeMove = nil }
+ if let g = glideIn { glideIn = g.t + dt > Self.glide ? nil : (g.start, g.t + dt) }
+ flex = max(0, flex - dt * 9)
+ stepGel(r, dt)
+ stepNeck(r, dt)
+ // holding the card: the hold sequence follows your finger instead of time
+ let holding = r.state == .approval && r.hold > 0.02 && CL[clip]?.state == "approval" && ["rest", "beat"].contains(CL[clip]?.role ?? "")
+ if holding != held { fade = (shown, 0); fadeMove = nil; held = holding }
+ if !held {
+ let before = f
+ f += dt * fps
+ if let m = CL[clip], upcoming == nil, queue.isEmpty, f > Double(m.n) - 12,
+ m.state == stateName && ["rest", "beat", "enter"].contains(m.role ?? "") {
+ let n = pickNext(); upcoming = n; StretchFrames.shared.preload(n)
+ }
+ if let m = CL[clip] {
+ for (kind, at) in m.events ?? [:] { for fr in at.list where before < Double(fr) && f >= Double(fr) { event(r, clip, kind) } }
+ if f >= Double(m.n) {
+ if clip == "bump", let t = tool { work = ["read": "work_read", "search": "work_search", "edit": "work_edit", "run": "work_run"][t.kind] ?? "work_read" }
+ if clip == "approval_deny" { card = nil }
+ if clip == "dizzy" && r.state == .dizzy && queue.isEmpty { f = Double(m.n - 1) } // it stays shaken off until the state moves on
+ else { next(r) }
+ }
+ }
+ }
+ // the work: a tool call from the session drops on its head
+ if r.state == .working && clip.hasPrefix("work_") {
+ demoCallT -= dt
+ if !r.worlds.queue.isEmpty || (r.worlds.demo && demoCallT <= 0) { demoCallT = rnd(3.5, 6.5); play(r, "bump", dissolve: true) }
+ }
+ // effects
+ let a = anchors(r); lastAnchors = a
+ fog += ((a.press > 0.9 ? 1 : 0) - fog) * min(1, dt * (a.press > 0.9 ? 3 : 0.7))
+ if CL[clip]?.state == "sleep" && ["rest", "beat"].contains(CL[clip]?.role ?? "") { zT -= dt; if zT <= 0 { zT = 1.5; fx.append(FX(k: .z, x: a.hx + 14, y: a.hy + 6)) } }
+ for i in fx.indices {
+ fx[i].t += dt
+ if fx[i].k == .confetti { fx[i].x += fx[i].vx * dt; fx[i].y += fx[i].vy * dt; fx[i].vy += 260 * dt; fx[i].r += fx[i].vr * dt }
+ }
+ fx.removeAll { $0.t >= ($0.k == .z ? 2.6 : $0.k == .confetti ? 1.8 : $0.k == .glass ? 1.1 : 1.0) }
+ for c in [\StretchStage.tool, \StretchStage.card] {
+ guard var k = self[keyPath: c], k.phase == "fly" || k.phase == "drop" else { continue }
+ k.x += k.vx * dt; k.y += k.vy * dt; k.vy += (k.phase == "drop" ? 900 : 380) * dt; k.rot += k.vr * dt
+ self[keyPath: c] = k
+ }
+ if let t = tool, t.y < 20 || t.y > 300 || t.x > 290 { tool = nil }
+ if let c = card, (c.phase == "fly" || c.phase == "drop") && (c.y < -80 || c.y > 340) { card = nil }
+ if let c = card, c.phase != "fly" && c.phase != "drop" && r.state != .approval && !["approval_allow", "approval_deny"].contains(clip) { card = nil }
+ }
+
+ // MARK: drawing
+
+ func draw(_ r: Rig, _ ctx0: GraphicsContext) {
+ if !r.ao, let fr = StretchFrames.shared.frame(clipNow, frameNo(r)) { shown = fr }
+ var ctx = ctx0
+ if r.ao { ctx.opacity *= 0.5 } // dimmed: its colors at half brightness
+ // the glass flexes a hair toward you on a knock
+ if flex > 0 {
+ let s = 1 + 0.03 * flex, c = flexAt ?? (lastAnchors.fx, lastAnchors.fy)
+ ctx.translateBy(x: c.0, y: c.1); ctx.scaleBy(x: s, y: s); ctx.translateBy(x: -c.0, y: -c.1)
+ }
+ view = viewTransform(r.t); ctx.concatenate(view)
+ var now = ctx; now.concatenate(placeNow)
+ if let fd = fade, let old = fd.image {
+ var o = ctx
+ if let m = fadeMove { o.concatenate(m.start.toward(m.end, ease(fd.t / fadeLength)).xf) }
+ frame(o, old, r.t)
+ if let cur = shown { now.opacity *= ease(fd.t / fadeLength); frame(now, cur, r.t) }
+ } else if let cur = shown { frame(now, cur, r.t) }
+ }
+
+ /// One frame of Noodle. Shaken, a wave runs up its body: thin horizontal strips, each pushed sideways along a slow
+ /// S-bend that travels upward, nothing at the base and most at the top of its hair.
+ private func frame(_ ctx: GraphicsContext, _ im: CGImage, _ t: Double) {
+ let rect = CGRect(x: 0, y: 0, width: 198, height: 242), image = Image(decorative: im, scale: 2)
+ let A = 14 * trauma * trauma, k = neck.k, stretched = abs(k - 1) > 0.004
+ guard A > 0.4 || stretched else { ctx.draw(image, in: rect); return }
+ // thin bands of the frame, each moved (stretched below the seam, and the shake's wave) to where it goes
+ let band = stretched ? 4.0 : 5.0, S = seam, cx = rawFace.x
+ let thin = 1 / sqrt(k) // the body keeps its volume: taller is thinner
+ for i in 0..<Int((242 / band).rounded(.up)) {
+ let y0 = Double(i) * band, y = y0 + band / 2, up = (242 - y) / 242
+ let dx = A * up * sin(t * TAU * 4.5 - (242 - y) * TAU / 320)
+ let below = y >= S, ky = below ? k : 1
+ // thinner below the seam, easing in over the 30 pt under it so the neck has no step
+ let sx = 1 + (thin - 1) * clamp((y - S) / 30, 0, 1) * (below ? 1 : 0)
+ let top = neckY(y0), height = max(0.01, neckY(y0 + band) - top)
+ var c = ctx
+ c.clip(to: Path(CGRect(x: -40, y: top, width: 278, height: height + 0.6)))
+ c.translateBy(x: cx + dx, y: top); c.scaleBy(x: sx, y: ky); c.translateBy(x: -cx, y: -y0)
+ c.draw(image, in: rect)
+ }
+ }
+
+ func front(_ r: Rig, _ ctx: GraphicsContext) {
+ let a = lastAnchors
+ // the glass fogs where its face presses, and ripples like liquid glass where it knocks
+ if fog > 0.02 {
+ let g = Gradient(stops: [.init(color: Color(white: 0.93, opacity: 0.16 * fog), location: 0),
+ .init(color: Color(white: 0.93, opacity: 0.07 * fog), location: 0.55),
+ .init(color: Color(white: 0.93, opacity: 0), location: 1)])
+ ctx.fill(Path(CGRect(x: 0, y: 0, width: 198, height: 242)),
+ with: .radialGradient(g, center: CGPoint(x: a.fx, y: a.fy + 8), startRadius: 4, endRadius: 78))
+ }
+ for q in fx where q.k == .glass { glass(ctx, q) }
+ for q in fx {
+ switch q.k {
+ case .confetti:
+ var c = ctx; c.opacity = clamp(1.8 - q.t, 0, 1); c.translateBy(x: q.x, y: q.y); c.rotate(by: .radians(q.r))
+ c.fill(Path(CGRect(x: -3, y: -1.5, width: 6, height: 3)), with: .color(q.c))
+ case .bonk:
+ var p = Path()
+ for i in 0..<6 {
+ let th = -Double.pi / 2 + (Double(i) - 2.5) * 0.45, r0 = 8 + q.t * 10, r1 = 16 + q.t * 14
+ p.move(to: CGPoint(x: q.x + cos(th) * r0, y: q.y + sin(th) * r0)); p.addLine(to: CGPoint(x: q.x + cos(th) * r1, y: q.y + sin(th) * r1))
+ }
+ ctx.stroke(p, with: .color(.white.opacity(1 - q.t)), style: StrokeStyle(lineWidth: 1.6, lineCap: .round))
+ case .z:
+ ctx.faded(clamp(1 - q.t / 2.6, 0, 1)).draw(Text("z").font(.system(size: 10 + q.t * 4, weight: .semibold)).foregroundColor(Pal.gray),
+ at: CGPoint(x: q.x + q.t * 9, y: q.y - q.t * 16), anchor: .bottomLeading)
+ case .glass: break
+ }
+ }
+ // a tool call drops on its head and gets bonked off
+ if var t = tool {
+ let txt = ctx.resolve(Text(t.text).font(.system(size: 10.5, weight: .medium, design: .monospaced)).foregroundColor(t.kind == "run" ? Pal.amber : Pal.white))
+ let w = txt.measure(in: CGSize(width: 180, height: 20)).width + 16, h = 20.0
+ if t.phase == "fall" { let land = Double(CL["bump"]?.events?["land"]?.list.first ?? 6), k = clamp(f / land, 0, 1); t.x = a.hx; t.y = lerp(36, a.hy + 4, k * k); t.rot = 0 }
+ if t.phase == "ride" { t.x = a.hx; t.y = a.hy + 4; t.rot = a.roll * DEG * 0.5 }
+ tool = t
+ cardBody(ctx, t, w, h) { c in
+ c.fill(Path(roundedRect: CGRect(x: 0, y: 0, width: w, height: h), cornerRadius: 7), with: .color(Pal.card))
+ c.stroke(Path(roundedRect: CGRect(x: 0, y: 0, width: w, height: h), cornerRadius: 7), with: .color(Color(hex: 0x2C3035)), lineWidth: 1)
+ c.draw(txt, at: CGPoint(x: 8, y: 10), anchor: .leading)
+ }
+ }
+ // the approval card rides on its hair; holding pushes it up; allow launches it, deny drops it
+ if var c = card {
+ let w = 152.0, h = 60.0
+ if c.phase == "fall" { let land = Double(CL["approval_in"]?.events?["land"]?.list.first ?? 8), k = clamp(f / land, 0, 1); c.x = clamp(a.hx, 82, 116); c.y = lerp(38, a.hy + 6, k * k); c.rot = 0 }
+ if c.phase == "ride" { c.x = clamp(a.hx, 82, 116); c.y = a.hy + 6; c.rot = a.roll * DEG * 0.6 }
+ card = c
+ let title = r.approvalTitle.isEmpty ? c.text : r.approvalTitle
+ cardBody(ctx, c, w, h) { g in
+ g.fill(Path(roundedRect: CGRect(x: 0, y: 0, width: w, height: h), cornerRadius: 13), with: .color(Pal.card))
+ g.stroke(Path(roundedRect: CGRect(x: 0, y: 0, width: w, height: h), cornerRadius: 13), with: .color(Color(hex: 0x2C3035)), lineWidth: 1)
+ g.draw(Text(title).font(.system(size: 14, weight: .medium, design: .monospaced)).foregroundColor(Pal.white),
+ in: CGRect(x: 12, y: 10, width: w - 24, height: 18))
+ g.draw(Text(r.hold > 0 ? "keep holding" : "hold to allow").font(.system(size: 10.5, weight: .medium, design: .monospaced))
+ .foregroundColor(r.hold > 0 ? Pal.amber : Pal.gray), at: CGPoint(x: 12, y: 36), anchor: .leading)
+ g.fill(Path(roundedRect: CGRect(x: 12, y: 47, width: w - 24, height: 3), cornerRadius: 1.5), with: .color(Color(hex: 0x26292D)))
+ if r.hold > 0 { g.fill(Path(roundedRect: CGRect(x: 12, y: 47, width: (w - 24) * r.hold, height: 3), cornerRadius: 1.5), with: .color(Pal.amber)) }
+ }
+ if r.state == .approval {
+ ctx.fillCircle(36, 210, 13, Color(hex: 0x1A1C1F))
+ ctx.strokeLine(31.5, 205.5, 40.5, 214.5, Pal.gray, 1.8); ctx.strokeLine(40.5, 205.5, 31.5, 214.5, Pal.gray, 1.8)
+ }
+ }
+ }
+
+ /// Cards come in and leave from under the status row, as if from behind the bezel.
+ private func cardBody(_ ctx0: GraphicsContext, _ c: Card, _ w: Double, _ h: Double, _ draw: (GraphicsContext) -> Void) {
+ var ctx = ctx0
+ ctx.clip(to: Path(CGRect(x: 0, y: 38, width: 198, height: 204)))
+ ctx.translateBy(x: c.x, y: c.y); ctx.rotate(by: .radians(c.rot)); ctx.translateBy(x: -w / 2, y: -h)
+ draw(ctx)
+ }
+
+ /// A knock on the glass: a ring of liquid glass runs out from the contact and refracts the frame under it. Each
+ /// thin band of the ring redraws Noodle's frame magnified or shrunk around the contact (a lens ridge: magnified on
+ /// the inner slope, compressed on the outer), with a highlight and a shade so it reads as glass even over black.
+ private func glass(_ ctx: GraphicsContext, _ q: FX) {
+ let k = q.t / 1.1
+ guard k < 1, let im = shown else { return }
+ let R = 16 + 150 * outC(k), wid = 16 + 26 * k, A = 0.16 * pow(1 - k, 1.5) * q.amp
+ let image = Image(decorative: im, scale: 2), rect = CGRect(x: 0, y: 0, width: 198, height: 242)
+ func ring(_ r0: Double, _ r1: Double) -> Path {
+ var p = Path(); p.addEllipse(in: CGRect(x: q.x - r1, y: q.y - r1, width: 2 * r1, height: 2 * r1))
+ if r0 > 0 { p.addEllipse(in: CGRect(x: q.x - r0, y: q.y - r0, width: 2 * r0, height: 2 * r0)) }
+ return p
+ }
+ func lens(_ r0: Double, _ r1: Double, _ s: Double) {
+ var c = ctx
+ c.clip(to: ring(r0, r1), style: FillStyle(eoFill: true))
+ c.translateBy(x: q.x, y: q.y); c.scaleBy(x: s, y: s); c.translateBy(x: -q.x, y: -q.y)
+ c.concatenate(view) // the frame where the gel and camera have it
+ c.draw(image, in: rect)
+ }
+ if k < 0.3 { lens(0, max(4, R - wid / 2), 1 + 0.05 * (1 - k / 0.3)) } // the contact bulges toward you
+ let bands = 12 // 18 in the Lab; fewer on the watch
+ for i in 0..<bands {
+ let u0 = Double(i) / Double(bands), u1 = Double(i + 1) / Double(bands), um = (u0 + u1) / 2
+ lens(max(0, R - wid / 2 + wid * u0), R - wid / 2 + wid * u1, 1 + A * cos(Double.pi * um))
+ }
+ let a = (1 - k) * (1 - k), r0 = max(0, R - wid / 2), r1 = R + wid / 2
+ let g = Gradient(stops: [.init(color: .white.opacity(0), location: r0 / r1),
+ .init(color: .white.opacity(0.16 * a), location: (r0 + 0.32 * (r1 - r0)) / r1),
+ .init(color: .white.opacity(0), location: (r0 + 0.5 * (r1 - r0)) / r1),
+ .init(color: .black.opacity(0.22 * a), location: (r0 + 0.7 * (r1 - r0)) / r1),
+ .init(color: .black.opacity(0), location: 1)])
+ ctx.fill(ring(r0, r1), with: .radialGradient(g, center: CGPoint(x: q.x, y: q.y), startRadius: 0, endRadius: r1), style: FillStyle(eoFill: true))
+ }
+}
diff --git a/app/ChumsWatch/Rig/Strokes.swift b/app/ChumsWatch/Rig/Strokes.swift
new file mode 100644
index 0000000..4d7a328
--- /dev/null
+++ b/app/ChumsWatch/Rig/Strokes.swift
@@ -0,0 +1,105 @@
+import SwiftUI
+
+/// Drawing helpers the flat characters share: polylines resampled to a fixed count (so any two can be blended point
+/// by point), and a marker stroke (a ribbon a little uneven in width, cut flat at the ends) instead of a perfect one.
+typealias P2 = SIMD2<Double>
+
+enum Strokes {
+ /// The points of a polyline, `n` of them, evenly spaced along its length.
+ static func resample(_ pts: [P2], _ n: Int) -> [P2] {
+ guard pts.count > 1 else { return [P2](repeating: pts.first ?? .zero, count: n) }
+ var cum = [0.0]
+ for i in 1..<pts.count { cum.append(cum[i - 1] + simd_length(pts[i] - pts[i - 1])) }
+ let total = cum.last!
+ guard total > 1e-9 else { return [P2](repeating: pts[0], count: n) }
+ var out: [P2] = [], j = 0
+ for k in 0..<n {
+ let d = total * Double(k) / Double(n - 1)
+ while j < pts.count - 2 && cum[j + 1] < d { j += 1 }
+ let seg = max(1e-9, cum[j + 1] - cum[j]), u = (d - cum[j]) / seg
+ out.append(pts[j] + (pts[j + 1] - pts[j]) * u)
+ }
+ return out
+ }
+ static func line(_ a: P2, _ b: P2) -> [P2] { [a, b] }
+ /// An arc around `c`, from angle `a0` to `a1` (radians; screen y down, so π/2 is straight down).
+ static func arc(_ c: P2, _ r: Double, _ a0: Double, _ a1: Double, rx: Double? = nil) -> [P2] {
+ (0...48).map { i in let a = a0 + (a1 - a0) * Double(i) / 48; return c + P2(cos(a) * (rx ?? r), sin(a) * r) }
+ }
+ static func mirrored(_ g: [P2]) -> [P2] { g.map { P2(-$0.x, $0.y) } }
+ static func mix(_ a: [P2], _ b: [P2], _ k: Double) -> [P2] { zip(a, b).map { $0 + ($1 - $0) * k } }
+ static func length(_ g: [P2]) -> Double { zip(g, g.dropFirst()).reduce(0) { $0 + simd_length($1.1 - $1.0) } }
+
+ @inline(__always) static func hash(_ a: Double, _ b: Double) -> Double {
+ let v = sin(a * 127.1 + b * 311.7) * 43758.5453; return v - floor(v)
+ }
+
+ /// A marker stroke along `pts` (already placed): `width` thick, its width wandering a little along the way
+ /// (`seed` keeps the wander the same from frame to frame), cut flat at the ends, rounded where it turns hard.
+ static func marker(_ ctx: GraphicsContext, _ pts0: [P2], width w: Double, color: Color, seed: Double = 0, wander: Double = 0.14, boil: Double? = nil) {
+ let n = pts0.count
+ guard n > 1, length(pts0) > 1.5 else { return }
+ // the line breathes, like hand-drawn frames: a smooth sway along it, new each `boil` step
+ var pts = pts0
+ if let b = boil {
+ let ph1 = hash(seed, b) * (Double.pi * 2), ph2 = hash(b, seed + 3) * (Double.pi * 2)
+ pts = pts0.enumerated().map { i, q in
+ let u = Double(i) / Double(n - 1)
+ return q + P2(sin(u * 5 + ph1), cos(u * 4 + ph2)) * 0.45
+ }
+ }
+ var left: [CGPoint] = [], right: [CGPoint] = []
+ left.reserveCapacity(n); right.reserveCapacity(n)
+ var joints: [P2] = []
+ for i in 0..<n {
+ let a = pts[max(0, i - 1)], b = pts[min(n - 1, i + 1)]
+ var t = b - a; let l = simd_length(t); t = l > 1e-9 ? t / l : P2(1, 0)
+ let nrm = P2(-t.y, t.x)
+ let ww = w * (1 + wander * (hash(seed, Double(i) * 0.37) - 0.5) * 2 * (0.5 + 0.5 * sin(Double(i) * 0.6 + seed)))
+ let p = pts[i]
+ left.append(CGPoint(x: p.x + nrm.x * ww / 2, y: p.y + nrm.y * ww / 2))
+ right.append(CGPoint(x: p.x - nrm.x * ww / 2, y: p.y - nrm.y * ww / 2))
+ if i > 0 && i < n - 1 {
+ let u = pts[i] - pts[i - 1], v = pts[i + 1] - pts[i]
+ let lu = simd_length(u), lv = simd_length(v)
+ if lu > 1e-6 && lv > 1e-6 && simd_dot(u / lu, v / lv) < 0.75 { joints.append(p) }
+ }
+ }
+ var path = Path()
+ path.move(to: left[0]); for p in left.dropFirst() { path.addLine(to: p) }
+ for p in right.reversed() { path.addLine(to: p) }
+ path.closeSubpath()
+ ctx.fill(path, with: .color(color))
+ if !joints.isEmpty { // round where it turns hard (a separate fill)
+ var j = Path()
+ for q in joints { j.addEllipse(in: CGRect(x: q.x - w * 0.48, y: q.y - w * 0.48, width: w * 0.96, height: w * 0.96)) }
+ ctx.fill(j, with: .color(color))
+ }
+ }
+
+ /// A smooth closed curve through points (Catmull-Rom as cubic Béziers).
+ static func smoothClosed(_ p: [P2]) -> Path {
+ var path = Path(); let n = p.count
+ guard n > 2 else { return path }
+ path.move(to: CGPoint(x: p[0].x, y: p[0].y))
+ for i in 0..<n {
+ let p0 = p[(i - 1 + n) % n], p1 = p[i], p2 = p[(i + 1) % n], p3 = p[(i + 2) % n]
+ let c1 = p1 + (p2 - p0) / 6, c2 = p2 - (p3 - p1) / 6
+ path.addCurve(to: CGPoint(x: p2.x, y: p2.y), control1: CGPoint(x: c1.x, y: c1.y), control2: CGPoint(x: c2.x, y: c2.y))
+ }
+ path.closeSubpath()
+ return path
+ }
+ /// A smooth open curve through points.
+ static func smoothOpen(_ p: [P2]) -> Path {
+ var path = Path(); let n = p.count
+ guard n > 1 else { return path }
+ path.move(to: CGPoint(x: p[0].x, y: p[0].y))
+ for i in 0..<(n - 1) {
+ let p0 = p[max(0, i - 1)], p1 = p[i], p2 = p[i + 1], p3 = p[min(n - 1, i + 2)]
+ let c1 = p1 + (p2 - p0) / 6, c2 = p2 - (p3 - p1) / 6
+ path.addCurve(to: CGPoint(x: p2.x, y: p2.y), control1: CGPoint(x: c1.x, y: c1.y), control2: CGPoint(x: c2.x, y: c2.y))
+ }
+ return path
+ }
+}
diff --git a/app/ChumsWatch/Rig/TangleStage.swift b/app/ChumsWatch/Rig/TangleStage.swift
new file mode 100644
index 0000000..726e797
--- /dev/null
+++ b/app/ChumsWatch/Rig/TangleStage.swift
@@ -0,0 +1,1088 @@
+import SwiftUI
+
+/// Tangle: a ball of yarn drawn in one thick pale-blue marker line, with a face on a crowd of its wires (the messy
+/// scribble-lines sheet). The line is one pen stroke: it starts as a tight knot wound round and round under the face,
+/// then goes round a ring drawing loops, and ends tucked back into the ball. Its mood is a handful of numbers (how big
+/// the loops are, how far they swing out, orbits, spikes, flat, how alive) and each state is a target for them. Slow
+/// waves run along the line all the time, so the loops slide past each other, swell and shrink and the whole mass shifts
+/// and breathes; every point is a particle on a spring to where all that puts it, with tension along the line, so it
+/// never cuts from one look to the next and the loops lag, overshoot and settle. Every loop is a little different, like
+/// a hand's scribble, and the line never turns tighter than its own width. One flat colour, like the sheet.
+/// It's yarn, and it behaves like yarn:
+/// crown, one way: a thread pulls off it as you turn, the ball rolling on it as it comes off; the thread falls and
+/// runs along the bottom of the screen, and reels back in (the ball rolling back) when you stop · the other way: it
+/// winds itself tight, squinting with the effort, a click at each notch, and boings loose when you let go
+/// shake: it wobbles like jelly and its loops fly loose and tangle; after, it knots itself back with a tug and shakes it
+/// off; shaken hard, dizzy: spiral eyes, the ball circling and rocking, then it shakes that off too
+/// touch: the threads near your finger stretch toward it and twang when you let go, the ball leans to you and gives
+/// under the finger, the eyes follow it · tap: a twang, surprise, then a giggle; tapped too often, annoyed · stroke it
+/// (pet): eyes closed, it purrs · hold a finger off it: an arm reaches out for it and follows it
+/// the face: bigger than the sheet's and drawn on a rim of the yarn's own colour, so it reads even over a gap between
+/// wires; it pops to each new expression and lags a little behind the body; it never goes away
+/// idle: the calm ball alive with slow loops, eyes looking about; now and then it closes its eyes content · listening:
+/// rounder, floating over its shadow, eyes closed and smiling, bobbing with your voice · thinking: eyes up, a small o,
+/// a slow sway · working: a loop in three swings out into an orbit, eyes reading, a loop flicks out at each tool call ·
+/// subagents: small yarn balls going round it · speaking: its mouth opens with its voice · done: orbits, the open smile,
+/// sparkles · needs you: worried, the ball sags, a knock · blocked: wound tight and spiky, trembling · dizzy: above ·
+/// sleep: sags flat into a puddle, breathing
+final class TangleStage: Staged {
+ static let shared = TangleStage()
+
+ let ownsApproval = false
+ let holds: [ChumsState: Double] = [.done: 2.6, .dizzy: 3.4]
+ func captionTop(_ r: Rig) -> Bool { false }
+ func ownsCaption(_ r: Rig) -> Bool { false }
+ /// It never stops moving, but slowly enough in the calm states to draw at 30 frames a second.
+ var calm: Bool { t - busyAt > 0.6 }
+
+ // the sheet's colours, its scale, its marker
+ static let blue = Color(red: 155 / 255, green: 194 / 255, blue: 229 / 255)
+ static let ink = Color(red: 0.01, green: 0.01, blue: 0.015)
+ /// The face: white on the yarn.
+ static let faceInk = Color.white
+ /// pt per pixel of the sheet (its cells are 341 px): everything here is in the sheet's pixels.
+ static let K = 0.49
+ /// The marker's width.
+ static let W = 15.5
+ /// Points in the ball (the first `kN` of them the knot under the face), points in the end of the line.
+ static let N = 380, A = 60, kN = 76
+ /// The tightest a loop may be made: a radius of 0.9 of the marker's width.
+ static let minRadius = 0.9 * W
+ /// A kink: the line turning more than this between two points half a stroke apart.
+ static let kink = 60 * Double.pi / 180
+ /// The arm's shoulder never turns tighter than this.
+ static let shoulder = 2.4 * W
+ /// The drawn line's points: half a stroke apart.
+ static let step = 0.5 * W
+ /// The face: bigger than the sheet's, each mark on a rim of the yarn's colour this wide.
+ static let faceScale = 1.2, rim = 11.0
+ /// The thread the crown pulls off: at most this long, never turning tighter than `strandBend`.
+ static let maxStrand = 430.0, strandBend = 2.2 * W
+
+ // MARK: mood
+
+ fileprivate enum Y: Int, CaseIterable {
+ case R, turns, ring, rounds, rl, rlv, ecc, lean, orbit, swirl, spike, loose, mess, flat, sag, arm, aimx, aimy
+ case curlAng, faceX, faceY, life, tempo
+ }
+ private static let base: [Double] = {
+ var m = [Double](repeating: 0, count: Y.allCases.count)
+ let d: [Y: Double] = [.R: 122, .turns: 14, .ring: 0.36, .rounds: 1.2, .rl: 0.5, .rlv: 0.2, .ecc: 0.3, .lean: 0.2,
+ .mess: 0.25, .aimx: -1.7, .aimy: -0.4, .curlAng: -0.5, .life: 1.05, .tempo: 1.75]
+ for (k, v) in d { m[k.rawValue] = v }
+ return m
+ }()
+ private static func mood(_ d: [Y: Double]) -> [Double] { var m = base; for (k, v) in d { m[k.rawValue] = v }; return m }
+ /// Each state's shape and how alive it is, fitted to its cell on the sheet. (Every state winds the same number of
+ /// loops: changing it would wind the line round, its ends fastest.)
+ private func target(_ s: ChumsState) -> [Double] {
+ switch s {
+ case .idle, .speaking: return Self.base
+ case .listening: return Self.mood([.R: 128, .rl: 0.5, .ring: 0.42, .faceX: -0.18, .life: 0.8, .tempo: 1.5])
+ case .thinking: return Self.mood([.lean: 0.6, .rl: 0.5, .ring: 0.38, .life: 0.75, .tempo: 0.8])
+ case .working: return Self.mood([.orbit: 0.45, .life: 1.05, .tempo: 2.6])
+ case .subagents: return Self.mood([.R: 108, .life: 0.8, .tempo: 1.5])
+ case .done: return Self.mood([.orbit: 1, .R: 116, .life: 1.25, .tempo: 2.6])
+ case .needs: return Self.mood([.sag: 1, .rl: 0.48, .ring: 0.36, .life: 0.8, .tempo: 1.1])
+ case .approval: return Self.mood([.R: 118, .rl: 0.5, .ring: 0.38, .life: 0.7])
+ case .blocked: return Self.mood([.spike: 1, .rl: 0.42, .ring: 0.32, .R: 116, .life: 0.6, .tempo: 3])
+ case .dizzy: return Self.mood([.swirl: 0.35, .loose: 0.5, .R: 118, .rl: 0.46, .ring: 0.44, .life: 1.2, .tempo: 2.2])
+ case .sleep: return Self.mood([.flat: 1, .R: 124, .rl: 0.5, .ring: 0.4, .life: 0.4, .tempo: 0.45])
+ }
+ }
+ /// How it moves in each state: a slow turn (rad/s), a float, a breath, a tremble, how much its line wanders.
+ private struct Motion { var drift = 0.06, bob = 0.0, breathe = 0.015, tremble = 0.0, wobble = 1.0 }
+ private func motion(_ s: ChumsState) -> Motion {
+ switch s {
+ case .idle, .speaking: return Motion()
+ case .subagents: return Motion(drift: 0.1)
+ case .listening: return Motion(drift: 0.1, bob: 4)
+ case .thinking: return Motion(drift: 0.04, wobble: 0.7)
+ case .working: return Motion(drift: 0.5, wobble: 1.2)
+ case .done: return Motion(drift: 0.4, wobble: 1.3)
+ case .needs: return Motion(drift: 0.08)
+ case .approval: return Motion(drift: 0.08, bob: 2)
+ case .blocked: return Motion(drift: 0.15, tremble: 1.1, wobble: 0.8)
+ case .dizzy: return Motion(drift: 0.12, breathe: 0, wobble: 1.3)
+ case .sleep: return Motion(drift: 0.02, breathe: 0.035, wobble: 0.5)
+ }
+ }
+
+ // MARK: faces (the sheet's marks, every part blends into the next)
+
+ private struct Look {
+ var pose = "00"
+ var eL = "", eR = "", eL2 = "", eR2 = "", bL = "", bR = "", m = "", cL = "", cR = "", sw = "", tg = ""
+ var look = 1.0, aim = P2.zero // how much the eyes follow the gaze; a fixed look (px)
+ var spirals = false // dizzy: spiral eyes
+ var key: String { pose + eL + eR + eL2 + m + tg + (spirals ? "@" : "") }
+ }
+ private static func dots(_ pose: String, mouth: String = "", scale: Double = 0.8) -> Look {
+ Look(pose: pose, eL: "21.eL@\(pose).eL*1.2", eR: "21.eR@\(pose).eR*1.2", m: mouth.isEmpty ? "21.m@\(pose).m*\(scale)" : mouth)
+ }
+ private func look(_ s: ChumsState) -> Look {
+ switch s {
+ case .idle, .subagents, .speaking: return Self.dots("00", mouth: "00.m")
+ case .listening: return Look(pose: "11", eL: "11.eL", eR: "11.eR", m: "11.m")
+ case .thinking: var l = Self.dots("00", scale: 0.65); l.look = 0; l.aim = P2(5, -7); return l
+ case .working: return Self.dots("00", scale: 0.6)
+ case .done: return Self.whee
+ case .needs: return Look(pose: "02", eL: "02.eL", eR: "02.eR", bL: "02.bL", bR: "02.bR", m: "02.m", look: 0.5)
+ case .approval: var l = Self.dots("00", scale: 0.65); l.look = 0; l.aim = P2(0, 6); return l
+ case .blocked: return Self.cross
+ case .dizzy: return Self.dizzy
+ case .sleep: return Self.sleepy
+ }
+ }
+ private static let content = Look(pose: "00", eL: "00.eL", eR: "00.eR", m: "00.m", look: 0)
+ private static let delight = Look(pose: "01", eL: "[email protected]*0.85", eR: "[email protected]*0.85", m: "01.m", tg: "01.tg", look: 0)
+ private static let whee = Look(pose: "01", eL: "01.eL", eR: "01.eR", m: "01.m", tg: "01.tg")
+ private static let surprise = Look(pose: "00", eL: "[email protected]", eR: "[email protected]", m: "[email protected]*1.7", look: 0.3)
+ private static let curious = Look(pose: "00", eL: "[email protected]*0.85", eR: "[email protected]*0.85", m: "[email protected]*1.1")
+ private static let frazzled = Look(pose: "12", eL: "12.eL", eR: "12.eR", m: "12.m", cL: "12.cL", cR: "12.cR", sw: "12.sw", look: 0.4)
+ private static let reaching = Look(pose: "21", eL: "21.eL", eR: "21.eR", m: "21.m")
+ private static let cross = Look(pose: "10", eL: "10.eLa", eR: "10.eRa", eL2: "10.eLb", eR2: "10.eRb", m: "10.m", look: 0)
+ private static let strain = Look(pose: "10", eL: "10.eLa", eR: "10.eRa", eL2: "10.eLb", eR2: "10.eRb", m: "[email protected]*0.7", look: 0)
+ private static let dizzy = Look(pose: "12", m: "12.m", look: 0, spirals: true)
+ private static let sleepy = Look(pose: "20", eL: "20.eL", eR: "20.eR", m: "[email protected]*0.7", look: 0)
+
+ /// A face part: its outline (64 points) blends from one shape into the next on a spring, or shrinks away and back.
+ private struct Part {
+ var from: [P2], to: [P2], b = 1.0, bv = 0.0, name = "", none = true
+ var shape: [P2] { b >= 1 ? to : Strokes.mix(from, to, b) }
+ var shown: Bool { !(none && b > 0.98) }
+ mutating func set(_ n: String, _ g: [P2]) {
+ guard n != name else { return }
+ let cur = shape
+ if n.isEmpty {
+ let c = TangleStage.centroid(cur); from = cur; to = [P2](repeating: c, count: cur.count); none = true
+ } else {
+ from = none && b > 0.98 ? [P2](repeating: TangleStage.centroid(g), count: g.count) : cur
+ to = g; none = false
+ }
+ name = n; b = 0; bv = 0
+ }
+ }
+ private static func centroid(_ p: [P2]) -> P2 { p.reduce(P2.zero, +) / Double(max(1, p.count)) }
+ private static let empty = [P2](repeating: .zero, count: ScribbleArt.N)
+ // eL eR eL2 eR2 bL bR m cL cR sw tg
+ private var parts: [Part] = (0..<11).map { _ in Part(from: TangleStage.empty, to: TangleStage.empty) }
+ private var shown = Look(), shownKey = "", gazeK = 1.0, aim = P2.zero, spiralK = 0.0
+ private var pop = (k: 0.0, v: 0.0) // the face pops to each new expression
+ private var faceOff = P2.zero, faceOffV = P2.zero // and lags a little behind the body
+ /// A mark, moved so its face's middle (between the eyes) is at 0.
+ private static func faceGlyph(_ name: String, _ pose: String) -> [P2] {
+ let o = ScribbleArt.faceOrigin(pose)
+ return ScribbleArt.glyph(name).map { $0 - o }
+ }
+
+ // MARK: the line
+
+ /// Its body: a ball of yarn, one thread wound round, the crown its spool (Yarn).
+ private let yarn = Yarn()
+
+ private var pos = [P2](repeating: .zero, count: TangleStage.N + TangleStage.A)
+ private var vel = [P2](repeating: .zero, count: TangleStage.N + TangleStage.A)
+ private var tgt = [P2](repeating: .zero, count: TangleStage.N + TangleStage.A)
+ private var shoulderKind = -1, aimA = 0.0, aimL = 1.6 // which of the four ways the shoulder took
+ private var drawn: [P2] = [] // the line as drawn (smoothed)
+ private var mood = TangleStage.base, moodV = [Double](repeating: 0, count: Y.allCases.count)
+ private var started = false
+ /// The waves along the line: their phase (runs at the mood's tempo), and a bigger swell now and then.
+ private var ph = 0.0, gustT = 9.0, nextGust = 3.0
+
+ // MARK: state
+
+ private var state: ChumsState = .idle
+ private var t = 0.0, busyAt = 0.0, stateT = 0.0
+ private var cur = Motion()
+ private var spin = 0.0, crownIdle = 9.0, crownAcc = 0.0
+ /// The crown: the thread pulled off (its length, px), how fast it reels back, which side it fell; how tightly wound.
+ private var strand = 0.0, strandV = 0.0, strandSide = 1.0, lastStrand = 0.0, tugT = 9.0
+ private var wound = 0.0, woundV = 0.0
+ /// The drawing's own turn: rolling on the thread, a thinking sway. The face never turns with it.
+ private var roll = 0.0, sway = 0.0, rot = 0.0
+ /// The whole body: where it sits, a jelly wobble (an offset that stretches it along itself), a lean.
+ private var center = P2(99, 128), cv = P2.zero, fingerOff = P2.zero, dragV = P2.zero
+ private var jelly = P2.zero, jellyV = P2.zero, tilt = 0.0, tiltV = 0.0, circle = 0.0
+ private var squash = (k: 0.0, v: 0.0), hop = (y: 0.0, v: 0.0), bump = 0.0
+ /// Shaken: how tangled its loops are (they come loose and scramble), and the knotting back and shaking off after.
+ private var tangle = 0.0, tanglePeak = 0.0, lastShake = -9.0, scramble = 0.0, shakeOff = 0.0
+ private var finger: CGPoint?, lastTouch: CGPoint?, reach = 0.0, pluck = 0.0
+ private var knock = 0.0, nextTool = 0.8, toolFlash = 0.0
+ private var startle = 0.0, boingT = 0.0, crossT = 0.0, petT = 0.0, pokes: [Double] = []
+ private var fidget = 0.0, nextFidget = 9.0
+ private var minis = 0.0, sparkle = 0.0, shadowK = 0.0
+ /// Small at the top for an approval: eased there and back.
+ private var scale = 1.0, scaleV = 0.0
+
+ // MARK: Staged
+
+ func onState(_ r: Rig, _ s: ChumsState, prev: ChumsState?, variant: Bool) {
+ let was = state
+ state = s; stateT = 0
+ switch s {
+ case .done: hop.v = -220; squash.v -= 2; kick(radial: 60) // it bursts open
+ case .needs: knock = 0
+ case .listening: squash.v += 2
+ case .blocked: squash.v -= 3; kick(radial: -60) // it winds up tight
+ case .dizzy: tangle = max(tangle, 0.85); tanglePeak = 0 // knocked loose (it re-knots at the end)
+ default: break
+ }
+ if was == .dizzy && s != .dizzy { shakeOff = 0.7; woundV += 2.4 } // it shakes the daze off, knots back up
+ fidget = 0; nextFidget = rnd(8, 14)
+ busyAt = t
+ }
+
+ func step(_ r: Rig, _ dt0: Double) {
+ let dt = min(dt0, 1.0 / 30)
+ t += dt; stateT += dt
+ guard !r.ao else {
+ // dimmed: drawn about once a second, so nothing in flight; it rests in its shape, the loops still
+ startle = 0; boingT = 0; crossT = 0; petT = 0; toolFlash = 0; finger = nil; reach = 0; pluck = 0
+ hop = (0, 0); squash = (0, 0); bump = 0; jelly = .zero; jellyV = .zero; tilt = 0; tiltV = 0
+ tangle = 0; tanglePeak = 0; shakeOff = 0; strand = 0; strandV = 0; lastStrand = 0; wound = 0; woundV = 0
+ roll = 0; sway = 0; rot = 0; faceOff = .zero; faceOffV = .zero; pop = (0, 0)
+ if started { generate(); pos = tgt; for i in vel.indices { vel[i] = .zero } }
+ return
+ }
+ var m = motion(state)
+ if petT > 0 { m.drift = 0.03; m.wobble = 0.6; m.tremble = 0.3 } // stroked, it purrs
+ let e = min(1, dt * 3)
+ cur.drift += (m.drift - cur.drift) * e; cur.bob += (m.bob - cur.bob) * e; cur.breathe += (m.breathe - cur.breathe) * e
+ cur.tremble += (m.tremble - cur.tremble) * e; cur.wobble += (m.wobble - cur.wobble) * e
+ crownIdle += dt; petT = max(0, petT - dt); startle = max(0, startle - dt); boingT = max(0, boingT - dt)
+ crossT = max(0, crossT - dt); toolFlash = max(0, toolFlash - dt); bump = max(0, bump - dt * 3)
+ shakeOff = max(0, shakeOff - dt); tugT += dt
+ // the crown let go: the thread reels back in (slow, then quicker), the wound ball boings loose and settles
+ if crownIdle > 0.45 {
+ if strand > 0 { strandV = min(strandV + 420 * dt, 240); strand = max(0, strand - strandV * dt) } else { strandV = 0 }
+ if wound > 0.6 && woundV == 0 { boingT = 0.9 }
+ let wk = TAU * 1.4
+ woundV += (-wk * wk * wound - 2 * 0.3 * wk * woundV) * dt
+ wound += woundV * dt
+ if abs(wound) < 0.002 && abs(woundV) < 0.01 { wound = 0; woundV = 0 }
+ } else { strandV = 0 }
+ // the ball rolls on the thread as it comes off and goes back on
+ let R0 = max(60, mood[Y.R.rawValue])
+ roll += (strand - lastStrand) / (R0 * 0.85) * strandSide; lastStrand = strand
+ if strand == 0 && crownIdle > 1 {
+ let home = (roll / TAU).rounded() * TAU // and comes back upright
+ roll += (home - roll) * min(1, dt * 1.5)
+ }
+ sway += ((state == .thinking ? 0.16 * sin(t * 0.9) : 0) - sway) * min(1, dt * 2.5) // thinking: a slow sway
+ rot = roll + sway
+ spin += cur.drift * dt
+ // shaken: tangled while it's shaken, then it knots itself back up (a tug) and shakes it off
+ if t - lastShake > 0.25 { tangle = max(0, tangle - dt * (state == .dizzy ? 0.12 : 0.55)) }
+ if tanglePeak > 0.45 && tangle < 0.3 && state != .dizzy { tanglePeak = 0; woundV += 2.6; shakeOff = 0.7 }
+ scramble += dt * 3.2 * tangle
+ // the mood: each number on its own spring to the state's target (a little overshoot)
+ var goal = target(state)
+ if tangle > 0 {
+ goal[Y.loose.rawValue] = max(goal[Y.loose.rawValue], tangle * 0.9); goal[Y.mess.rawValue] += 0.5 * tangle
+ goal[Y.life.rawValue] += 0.5 * tangle
+ }
+ if crossT > 0 { goal[Y.spike.rawValue] = 0.7; goal[Y.rl.rawValue] = 0.46; goal[Y.tempo.rawValue] = 2.6 }
+ if startle > 0 && state == .sleep { goal[Y.flat.rawValue] = 0.45; goal[Y.life.rawValue] = 0.9 }
+ if petT > 0 { goal[Y.life.rawValue] *= 0.6; goal[Y.tempo.rawValue] *= 0.5 }
+ if state == .listening || state == .speaking { goal[Y.life.rawValue] += r.voice * 0.4 }
+ if strand > 0 { goal[Y.R.rawValue] *= 1 - 0.1 * min(1, strand / Self.maxStrand) } // the thread comes out of it
+ if let f = finger, reach > 0.02 {
+ // an arm out for the finger: aimed at it, in the ball's own units
+ let d = (P2(f.x, f.y) - center) / Self.K / max(0.4, scale)
+ let R = mood[Y.R.rawValue], l = max(1, simd_length(d))
+ var a = d / l * clamp(l / R, 1.45, 2.1)
+ // the hand stays on the screen, below the clock
+ let k = R * Self.K * max(0.4, scale)
+ let onScreen = P2(clamp(center.x + a.x * k, 16, 182), clamp(center.y + a.y * k, 64, 222))
+ a = (onScreen - center) / k
+ // the aim swings round the ball (its angle and its reach eased), never cutting across the middle
+ if reach < 0.05 { aimA = atan2(a.y, a.x); aimL = simd_length(a) }
+ aimA += remainder(atan2(a.y, a.x) - aimA, TAU) * min(1, dt * 5)
+ aimL += (simd_length(a) - aimL) * min(1, dt * 5)
+ goal[Y.arm.rawValue] = reach
+ let la = aimA - rot - tilt // in the turned drawing's own frame
+ goal[Y.aimx.rawValue] = cos(la) * aimL; goal[Y.aimy.rawValue] = sin(la) * aimL
+ }
+ let wm = TAU * 1.25
+ for i in 0..<mood.count {
+ // the arm's aim moves quickly; the number of loops slowly
+ let aimFast = i == Y.aimx.rawValue || i == Y.aimy.rawValue ? 3 : i == Y.turns.rawValue ? 0.3 : 1.0
+ let w = wm * aimFast
+ moodV[i] += (w * w * (goal[i] - mood[i]) - 2 * 0.72 * w * moodV[i]) * dt
+ mood[i] += moodV[i] * dt
+ }
+ // the waves along the line; now and then (when it's calm) a bigger swell runs through it
+ ph += max(0.1, mood[Y.tempo.rawValue] + 2 * max(0, wound)) * dt
+ gustT += dt
+ if [.idle, .thinking, .subagents, .speaking, .approval, .needs, .listening].contains(state) {
+ nextGust -= dt
+ if nextGust <= 0 { gustT = 0; nextGust = rnd(3.5, 6.5) }
+ }
+ // a finger: held off the ball, the arm reaches for it; on it (or near), its threads are pulled toward it
+ let Rp = mood[Y.R.rawValue] * Self.K * scale
+ var fd = 1e9
+ if let f = finger { fd = simd_length(P2(f.x, f.y) - center) }
+ if finger != nil && fd > Rp * 1.05 { reach = min(1, reach + dt * 3) } else { reach = max(0, reach - dt * 2) }
+ pluck += ((finger != nil && fd < Rp * 1.35 && reach < 0.5 ? 1 : 0) - pluck) * min(1, dt * 10)
+ // the body: squash, hop, jelly, lean, where it sits (a finger pulls it a little toward itself)
+ let ws = TAU * 2.6, sqT = pluck * -0.07
+ squash.v += (-ws * ws * (squash.k - sqT) - 2 * 0.3 * ws * squash.v) * dt; squash.k = clamp(squash.k + squash.v * dt, -0.25, 0.25)
+ hop.v += 1000 * dt; hop.y += hop.v * dt
+ if hop.y > 0 { if hop.v > 100 { squash.v -= hop.v / 160 }; hop.y = 0; hop.v = 0 }
+ let wj = TAU * 3.1
+ let ja: P2 = jelly * (-wj * wj) - jellyV * (2 * 0.13 * wj)
+ jellyV += ja * dt; jelly += jellyV * dt
+ if simd_length(jelly) > 34 { jelly = jelly / simd_length(jelly) * 34 }
+ var tiltT = 0.0
+ if let f = finger { tiltT += clamp((Double(f.x) - center.x) / 70, -1, 1) * 0.13 } // it leans to you
+ let dz = state == .dizzy ? clamp(1.3 - stateT / 3.4, 0.25, 1) : 0
+ tiltT += dz * 0.17 * sin(t * 4.1) // dizzy: it rocks
+ if shakeOff > 0 { tiltT += 0.16 * sin(shakeOff * 26) * shakeOff / 0.7 } // and shakes it off
+ let wt = TAU * 2.2
+ tiltV += (-wt * wt * (tilt - tiltT) - 2 * 0.5 * wt * tiltV) * dt; tilt += tiltV * dt
+ circle += ((state == .dizzy ? dz : 0) - circle) * min(1, dt * 3)
+ var home = P2(99, state == .approval ? 74 : state == .listening ? 136 : state == .sleep ? 146 : 128)
+ home += P2(cos(t * 3.6), sin(t * 3.6)) * (7 * circle) // dizzy: it circles
+ let fo: P2 = finger.map { P2(clamp(($0.x - 99) * 0.18, -16, 16), clamp(($0.y - 128) * 0.15, -14, 14)) } ?? .zero
+ fingerOff += (fo - fingerOff) * min(1, dt * 6); home += fingerOff
+ let wc = TAU * 2
+ let pull: P2 = (home - center) * (wc * wc), damp: P2 = cv * (wc * 1.1)
+ cv += (pull - damp) * dt; center += cv * dt
+ dragV += (cv - dragV) * min(1, dt * 7)
+ // the face lags behind the body (a little), and pops to each new expression
+ let fw = TAU * 2.4
+ let fT: P2 = cv * -0.06 + jellyV * -0.012
+ let fa: P2 = (fT - faceOff) * (fw * fw) - faceOffV * (2 * 0.42 * fw)
+ faceOffV += fa * dt; faceOff += faceOffV * dt
+ let pw = TAU * 3.2
+ pop.v += (-pw * pw * pop.k - 2 * 0.3 * pw * pop.v) * dt; pop.k += pop.v * dt
+ // the work: each tool call, a loop flicks out, a little hop, the eyes glance up
+ nextTool -= dt
+ if nextTool <= 0 && (!r.worlds.queue.isEmpty || state == .working), let c = r.worlds.nextEvent(r) {
+ nextTool = r.worlds.queue.isEmpty ? rnd(1.4, 2.4) : 0.5
+ if c.kind != .stop { flick(); hop.v = min(hop.v, -90); toolFlash = 0.6 }
+ }
+ if state == .needs {
+ let was = knock; knock += dt; if knock >= 3.2 { knock = 0 }
+ if was < 0.2 && knock >= 0.2 { bump = 1; squash.v += 2.4; r.onHaptic?(.strong); kick(radial: 90) }
+ }
+ if state == .idle && finger == nil && crownIdle > 3 {
+ nextFidget -= dt
+ if nextFidget <= 0 { fidget = 2.4; nextFidget = rnd(10, 18) }
+ }
+ fidget = max(0, fidget - dt)
+ let wsc = TAU * 2.2, sgoal = state == .approval ? 0.5 : 1.0
+ scaleV += (wsc * wsc * (sgoal - scale) - 2 * 0.75 * wsc * scaleV) * dt; scale += scaleV * dt
+ minis += ((state == .subagents ? 1 : 0) - minis) * min(1, dt * 3)
+ sparkle += ((state == .done ? 1 : 0) - sparkle) * min(1, dt * 5)
+ shadowK += ((state == .listening ? 1 : 0) - shadowK) * min(1, dt * 7)
+ // the ball of yarn: where it sits and how big (wound tight, a little smaller), then its own physics
+ yarn.center = center + P2(jelly.x * 0.3, hop.y + jelly.y * 0.3)
+ yarn.scale = scale * (1 - 0.12 * wound) * (1 + 0.04 * bump)
+ yarn.step(dt, gravity: P2(clamp(r.W.padX, -0.6, 0.6), 1))
+ if yarn.busy { busyAt = t }
+ stepLook(r, dt)
+ // fast moves draw at 60 frames a second; the slow life of the calm states at 30
+ let fast = finger != nil || strand > 0.5 || abs(wound) > 0.005 || abs(woundV) > 0.02 || tangle > 0.01 || shakeOff > 0
+ || simd_length(jelly) > 0.4 || simd_length(jellyV) > 4 || abs(tiltV) > 0.03 || hop.v != 0 || abs(squash.v) > 0.3
+ || simd_length(cv) > 4 || startle > 0 || boingT > 0 || crossT > 0 || abs(scaleV) > 0.02 || abs(pop.v) > 0.05
+ || parts.contains { abs($0.bv) > 0.05 } || [.working, .done, .dizzy, .blocked, .speaking, .listening].contains(state)
+ if fast { busyAt = t }
+ }
+
+ @inline(__always) private func smooth(_ a: Double, _ b: Double, _ x: Double) -> Double {
+ let k = clamp((x - a) / (b - a), 0, 1); return k * k * (3 - 2 * k)
+ }
+
+ /// Where the mood puts every point of the line (in the sheet's pixels, round the ball's middle).
+ private func generate() {
+ let m = mood
+ func g(_ y: Y) -> Double { m[y.rawValue] }
+ // wound tight by the crown: smaller, tighter loops; boinged loose after: bigger ones
+ let wd = wound
+ let R = g(.R) * (1 - 0.12 * max(0, wd) - 0.05 * min(0, wd))
+ let orbit = clamp(g(.orbit), 0, 1.2), swirl = clamp(g(.swirl), 0, 1.2), turns = max(1, g(.turns))
+ let ring = g(.ring) * (1 - 0.15 * min(1, orbit)) * (1 - 0.35 * max(0, wd) - 0.4 * min(0, wd))
+ let rlW = 1 - 0.22 * max(0, wd) - 0.3 * min(0, wd)
+ let loose = g(.loose), spike = g(.spike) * (1 - clamp(loose, 0, 1)), mess = g(.mess) * cur.wobble // shaken loose, the bristles relax
+ let L = max(0, g(.life)), p = ph
+ let gust = gustT < 1.8 ? sin(Double.pi * gustT / 1.8) : 0
+ let fc = P2(g(.faceX), g(.faceY)), knotW = 1 - clamp(swirl, 0, 1)
+ let turn = spin
+ let N = Self.N
+ // the whole mass shifts a little, side to side and up and down
+ let shift = P2(cos(p * 0.45), sin(p * 0.37 + 1)) * (0.05 * L)
+ let irr = 1.0 + 1.1 * tangle // tangled: every loop more its own
+ let squashY = 1 - 0.4 * clamp(g(.flat), 0, 1.2)
+ let irrT = irr * (1 - 0.7 * min(1, orbit)) // orbits: their loops' own turn kept steady
+ let scr = scramble
+ // the whole line in one: past the ball's last point it carries straight on, tucking its end back in
+ for i in 0..<(N + Self.A) {
+ let s = Double(i) / Double(N - 1), sc = s - 0.5
+ let tuck = smooth(1, 1.16, s)
+ // every loop its own: smooth noise along the line, about one value per loop, drifting slowly
+ let lp = turns * s + 0.05 * p + scr
+ let nR = Self.vn(lp * 0.9, 1), nE = Self.vn(lp * 0.8, 2), nT = Self.vn(lp * 0.5, 3)
+ let nX = Self.vn(lp * 0.3, 4), nY = Self.vn(lp * 0.3, 5), nS = Self.vn(lp * 0.4, 6), nC = Self.vn(s * 2.4 + 0.03 * p + scr * 0.5, 7)
+ // the hand goes round a ring, drawing loops as it goes; the ring bunches up and spreads as waves go round it,
+ // and the loops crowd round some of it and wander off elsewhere
+ let cang = TAU * g(.rounds) * sc + 0.6 + turn * 0.5 + L * 0.4 * Self.vn(s * 1.8 + p * 0.25, 11) + irr * 0.35 * nC
+ let cr = ring * (1 + 0.25 * Self.vn(s * 4.4 + p * 0.1, 12) + L * 0.2 * Self.vn(s * 1.4 - p * 0.16, 13)) * (1 - 0.5 * tuck)
+ var cx = cos(cang) * cr + shift.x * sin(TAU * 0.5 * s + 0.6) + irr * 0.13 * nX
+ var cy = sin(cang) * cr + shift.y * cos(TAU * 0.5 * s) + irr * 0.13 * nY
+ // orbits: about one loop in three flies out into a big ellipse round the ball (each grows into it over a loop)
+ let kk = turns * sc, ow = orbit * smooth(-0.1, 0.9, sin(TAU * kk / 3 + 0.4))
+ // the loops slide along the line, and swell and shrink as a wave runs through them
+ let th = TAU * turns * sc + turn + L * 1.3 * Self.vn(s * 1.1 - p * 0.2, 14) + irrT * 0.9 * nS // uneven spacing
+ let swell = L * (0.16 * Self.vn(s * 2.8 - p * 0.35, 15) + 0.08 * Self.vn(s * 5.8 + p * 0.22, 16)) + gust * 0.22 * sin(TAU * s - p * 2)
+ var rr = g(.rl) * rlW * (1 + g(.rlv) * (Self.vn(s * 6.2 + p * 0.1, 17) + 0.5 * Self.vn(s * 12.6 - p * 0.06, 18)) + swell)
+ rr = rr * (1 - ow) + ow * (0.95 + 0.12 * sin(TAU * 3.3 * s + 1) + 0.6 * swell)
+ rr *= (1 + irr * 0.32 * nR) * (1 - 0.45 * tuck) // sizes differ
+ if loose > 0.001 {
+ let q = sin(TAU * 2.5 * s + 0.5 + scr * 0.3)
+ rr += loose * 0.3 * exp(-q * q * 2.5) // some loops swing wide
+ }
+ var e = g(.ecc) * (1 - ow) + ow * 0.48 + L * 0.12 * Self.vn(s * 3.2 + p * 0.28, 19)
+ e = clamp(e + irr * 0.22 * nE, 0, 0.72) // roundness differs
+ var psi = cang + g(.lean) + L * 0.25 * Self.vn(s * 1.6 + p * 0.16, 20) + irrT * 0.5 * nT // so does tilt
+ if ow > 0.001 {
+ // its own tilt, a little off the others' (a bounded offset: never a jump round the loop)
+ psi += ow * (0.45 * sin(1.2 * kk + 0.3 * sin(p * 0.4)) + 0.35)
+ }
+ // the knot: the start of the line winds round and round under the face, its loops drifting: the same line,
+ // its loops smaller and centred on the face (so it flows on into the rest, never a fold where they meet)
+ let kw = (1 - smooth(0.15, 0.24, s)) * knotW
+ if kw > 0.001 {
+ let u = s / 0.24
+ let wk = P2(cos(TAU * 0.6 * u + p * 0.5) + 0.6 * Self.vn(u * 1.5, 9), sin(TAU * 0.5 * u + p * 0.6 + 1) + 0.6 * Self.vn(u * 1.5, 10)) * 0.08
+ let rk = (0.21 + 0.05 * sin(TAU * 2.3 * u - p * 0.8) + 0.03 * L * sin(p * 1.3 + u * 5)) * (1 + 0.22 * Self.vn(u * 3.8 + 0.04 * p, 8))
+ let ek = 0.22 + 0.1 * sin(TAU * 0.9 * u + p * 0.4), psik = psi + 0.5 * sin(TAU * 0.7 * u + p * 0.3)
+ cx += (fc.x + wk.x - cx) * kw; cy += (fc.y + wk.y - cy) * kw
+ rr += (rk - rr) * kw; e += (ek - e) * kw; psi += (psik - psi) * kw
+ }
+ // never tighter than the marker: each loop at least so big, its ends at least so round (b² / a ≥ minRadius,
+ // allowing for the flattening a puddle gets later)
+ rr = max(rr, 1.15 * Self.minRadius / (R * squashY * squashY))
+ e = min(e, max(0, 1 - sqrt(Self.minRadius / (squashY * squashY * rr * R))))
+ let a = th - psi
+ if spike > 0.001 {
+ // bristles: where a loop swings out, every few points the line pokes out and back (a short hairpin)
+ let ca = max(0, cos(a)), outer = ca * ca
+ let k = Double(i % 12) - 5.5, comb = exp(-k * k / 7.2) // rounded teeth, tips just inside the limit
+ rr += spike * 0.22 * outer * comb * (1 - smooth(0.6, 1, 1 - smooth(0.15, 0.24, s))) // not on the knot
+ }
+ let lx = cos(a) * rr, ly = sin(a) * rr * (1 - e)
+ let cp = cos(psi), sp = sin(psi)
+ var q = P2(cx + lx * cp - ly * sp, cy + lx * sp + ly * cp)
+ if swirl > 0.001 {
+ // dizzy: the ball twisted like a whirlpool, its middle turned further than its edge
+ let tw = swirl * 1.4 * (1 - smooth(0, 1.1, simd_length(q))), ct = cos(tw), st = sin(tw)
+ q = P2(q.x * ct - q.y * st, q.x * st + q.y * ct)
+ }
+ q *= R
+ if q.x.isFinite && q.y.isFinite { tgt[i] = q } // (never a bad number into the line)
+ }
+ let A = Self.A
+ // the thread the crown pulled off: from the line's end, the way it was going, out and down, then along the
+ // bottom of the screen back under the ball; never turning tighter than `strandBend`, a slow wave running down it
+ if strand > 1 {
+ let ws = smooth(0, 30, strand)
+ let cr = cos(rot + tilt), sr = sin(rot + tilt)
+ let P0 = tgt[N - 1], d0: P2 = tgt[N - 1] - tgt[N - 2]
+ var q = P2(P0.x * cr - P0.y * sr, P0.x * sr + P0.y * cr)
+ if lastStrandStart { strandSide = q.x >= 0 ? 1 : -1; lastStrandStart = false }
+ var hd = atan2(d0.x * sr + d0.y * cr, d0.x * cr - d0.y * sr)
+ let side = strandSide
+ let flow = side > 0 ? 0.55 : Double.pi - 0.55
+ let floorY = (226 - center.y) / (Self.K * max(0.4, scale)), wallX = 190 / max(0.4, scale)
+ // (its length counts from the ball's edge: the line's end is somewhere inside the ball)
+ let ds = (strand + R * 0.85) / Double(A), maxTurn = ds / Self.strandBend
+ var out = [P2](repeating: .zero, count: A)
+ for j in 0..<A {
+ let u = Double(j) / Double(A - 1)
+ // out and down, falling more the further it goes; a wave runs down it (stronger toward its end)
+ var ht = flow + (Double.pi / 2 - flow) * 0.5 * u
+ let onFloor = smooth(floorY - 70, floorY - 25, q.y)
+ let floorH = side > 0 ? Double.pi + 0.08 : -0.08 // along the bottom, back under the ball
+ ht = ht + remainder(floorH - ht, TAU) * onFloor
+ let nearWall = smooth(wallX - 60, wallX - 15, abs(q.x)) * (1 - onFloor)
+ ht = ht + remainder(Double.pi / 2 - ht, TAU) * nearWall // at the side: straight down
+ let wave = (0.5 - 0.3 * onFloor) * smooth(0, 0.2, u) * sin(TAU * Double(j) * ds / 120 - t * 3.2 - (tugT < 0.6 ? 2 : 0))
+ ht += wave
+ hd += clamp(remainder(ht - hd, TAU), -maxTurn, maxTurn)
+ q += P2(cos(hd), sin(hd)) * ds
+ out[j] = P2(q.x * cr + q.y * sr, -q.x * sr + q.y * cr)
+ }
+ blendEnd(out, ws, from: P0)
+ } else { lastStrandStart = true }
+ // an arm reaching out with a hand (a loop the line runs round, then a finger). It leaves the line by the
+ // shortest way that never turns tighter than `shoulder` (arcs and a straight)
+ let wa = clamp(g(.arm), 0, 1)
+ if wa > 0.001 {
+ let T = P2(g(.aimx), g(.aimy)) * R
+ let tl = max(1, simd_length(T)), dd = T / tl, nn = P2(-dd.y, dd.x)
+ let rp = R * 0.17
+ let Ew: P2 = T - dd * (R * 0.3) // the wrist
+ let nh = 22 // 16 round the palm, 6 the finger
+ let open = TAU * smooth(0.35, 1, wa) // the palm curls round as the arm grows
+ let exit: P2 = dd * cos(open) + nn * sin(open)
+ let wrist2: P2 = Ew + dd * (rp * sin(open)) + nn * (rp * (1 - cos(open)))
+ var hand = [P2](repeating: .zero, count: nh)
+ for k in 0..<nh {
+ if k < 16 {
+ let th = open * Double(k + 1) / 16
+ hand[k] = Ew + dd * (rp * sin(th)) + nn * (rp * (1 - cos(th)))
+ } else {
+ hand[k] = wrist2 + exit * (R * 0.075 * Double(k - 15))
+ }
+ }
+ // from the line's end, its way, to the wrist, pointing at the target
+ let P0: P2 = tgt[N - 1], d0: P2 = tgt[N - 1] - tgt[N - 2]
+ let way = Self.dubins(P0, atan2(d0.y, d0.x), Ew, atan2(dd.y, dd.x), Self.shoulder, count: A - nh, keep: &shoulderKind)
+ blendEnd(way + hand, wa, from: P0)
+ }
+ // mess: a slow smooth wander along the line; sag: it hangs heavy; flat: a puddle, wide and low
+ let flat = clamp(g(.flat), 0, 1.2), sag = clamp(g(.sag), 0, 1.2)
+ let sx = 1 + 0.26 * flat, sy = 1 - 0.4 * flat
+ let mk = mess * R * 0.06
+ for i in 0..<tgt.count {
+ let xi = Double(i)
+ let w = P2(sin(xi * 0.21 + t * 0.8) + 0.5 * sin(xi * 0.067 + 1.3), cos(xi * 0.17 + t * 0.6) + 0.5 * cos(xi * 0.053))
+ var q = tgt[i] + (i < N ? w * mk : w * (mk * 0.3))
+ if sag > 0.001 && i < N {
+ let yy = max(0, q.y / R + 0.2)
+ q = P2(q.x * (1 - sag * 0.1 * yy), q.y + sag * R * 0.22 * yy * yy)
+ }
+ tgt[i] = i < N ? P2(q.x * sx, q.y * sy) : q
+ }
+ }
+ private var lastStrandStart = true
+
+ /// The end of the line becomes `other` by `w`: by blending how each turns and steps along its length (never their
+ /// places), walked out from the line's end, so the mix is never tighter than either.
+ private func blendEnd(_ other: [P2], _ w: Double, from P0: P2) {
+ let N = Self.N, A = Self.A
+ var cont = [P2](repeating: .zero, count: A)
+ for j in 0..<A { cont[j] = tgt[N + j] }
+ var hc = atan2(cont[0].y - P0.y, cont[0].x - P0.x), ha = atan2(other[0].y - P0.y, other[0].x - P0.x)
+ ha = hc + remainder(ha - hc, TAU)
+ var q = P0, prevC = P0, prevA = P0
+ for j in 0..<A {
+ let sc: P2 = cont[j] - prevC, sa: P2 = other[j] - prevA
+ let lc = simd_length(sc), la = simd_length(sa)
+ if j > 0 {
+ if lc > 1e-6 { hc += remainder(atan2(sc.y, sc.x) - hc, TAU) }
+ if la > 1e-6 { ha += remainder(atan2(sa.y, sa.x) - ha, TAU) }
+ }
+ let hh = hc + (ha - hc) * w, l = lc + (la - lc) * w
+ q += P2(cos(hh), sin(hh)) * l
+ prevC = cont[j]; prevA = other[j]
+ tgt[N + j] = q
+ }
+ }
+
+ /// A push out from the middle (in, when negative) for the whole line (a burst, a knock).
+ private func kick(radial: Double) {
+ for i in pos.indices {
+ // the whole line swells (or draws in) together: a push in proportion to where each point is, so it can
+ // stretch the line but never fold it
+ vel[i] += pos[i] * (radial / 80)
+ }
+ }
+ /// One loop flicks out (a tool call).
+ private func flick() {
+ let c = Int.random(in: (Self.kN + 20)..<(Self.N - 30))
+ for i in max(0, c - 18)..<min(Self.N, c + 18) {
+ let k = 1 - abs(Double(i - c)) / 18
+ vel[i] += pos[i] * (5 * k * k) // that stretch of line swells out
+ }
+ }
+ /// The threads near `p` (screen points) twang: a quick shiver across them that runs off along the line.
+ private func twang(at p: CGPoint, strength: Double) {
+ let w0 = (P2(p.x, p.y) - center) / (Self.K * max(0.4, scale)), c = cos(-(rot + tilt)), s = sin(-(rot + tilt))
+ let fl = P2(w0.x * c - w0.y * s, w0.x * s + w0.y * c)
+ let n = pos.count
+ for i in 1..<(n - 1) {
+ let l = simd_length(pos[i] - fl)
+ guard l < 110 else { continue }
+ let k = 1 - l / 110, d: P2 = pos[i + 1] - pos[i - 1], dl = max(1e-6, simd_length(d))
+ let nrm = P2(-d.y, d.x) / dl
+ vel[i] += nrm * (strength * k * k * sin(Double(i) * 0.9))
+ }
+ }
+
+ private func stepLook(_ r: Rig, _ dt: Double) {
+ var l = look(state)
+ if state == .done && stateT > 2.2 { l = Self.delight }
+ if fidget > 0 || petT > 0 { l = Self.content }
+ if pluck > 0.5 && petT <= 0 { l = Self.curious }
+ if reach > 0.5 { l = Self.reaching }
+ if yarn.moving > 0.25 && yarn.off > 0.01 { l = Self.whee } // reeled in or fed out
+ if wound > 0.22 { l = Self.strain }
+ if boingT > 0 { l = Self.delight }
+ if tangle > 0.3 && state != .sleep && state != .dizzy { l = Self.frazzled }
+ if shakeOff > 0 { l = Self.content }
+ if state == .dizzy { l = Self.dizzy }
+ if startle > 0 {
+ if state == .sleep { l = startle > 0.5 ? Self.surprise : Self.sleepy }
+ else if state != .dizzy { l = startle > 0.45 ? Self.surprise : Self.delight }
+ }
+ if crossT > 0 { l = Self.cross }
+ if state == .working && toolFlash > 0 { l.aim = P2(0, -6); l.look = 0 }
+ if l.key != shownKey && faceStarted { pop.v += 2.2 } // a new expression: the face pops
+ shownKey = l.key
+ shown = l
+ let names = [l.eL, l.eR, l.eL2, l.eR2, l.bL, l.bR, l.m, l.cL, l.cR, l.sw, l.tg]
+ for i in 0..<11 {
+ if names[i] != parts[i].name {
+ parts[i].set(names[i], names[i].isEmpty ? [] : Self.faceGlyph(names[i], l.pose))
+ if !faceStarted { parts[i].b = 1; parts[i].from = parts[i].to }
+ }
+ let w = TAU * 4.2
+ parts[i].bv += (-w * w * (parts[i].b - 1) - 2 * 0.68 * w * parts[i].bv) * dt
+ parts[i].b += parts[i].bv * dt
+ }
+ faceStarted = true
+ let e = min(1, dt * 10)
+ gazeK += (l.look - gazeK) * e; aim += (l.aim - aim) * e
+ spiralK += ((l.spirals ? 1 : 0) - spiralK) * min(1, dt * 8)
+ }
+ private var faceStarted = false
+
+ // MARK: input
+
+ func motion(_ r: Rig, _ ax: Double, _ ay: Double, _ az: Double) {
+ let g = sqrt(ax * ax + ay * ay + az * az)
+ if g > 0.3 { yarn.jolt(P2(-ax, -ay) * 900, hard: max(0, g - 1.1)) } // the thread swings, its turns come loose
+ let lat = sqrt(ax * ax + ay * ay)
+ let c = cos(-(rot + tilt)), s = sin(-(rot + tilt))
+ if lat > 0.3 {
+ // the body is thrown against the move and wobbles like jelly
+ let dir = P2(-ax, -ay) / lat
+ jellyV += dir * ((min(2.5, lat) - 0.3) * 30)
+ if g <= 1.25 {
+ // a small move: the outer loops lag behind it, the knot barely
+ let k = (lat - 0.3) * 30
+ let a = P2(dir.x * c - dir.y * s, dir.x * s + dir.y * c) * k
+ for i in pos.indices { let out = min(1.2, simd_length(pos[i]) / 110); vel[i] += a * (out * out) }
+ }
+ busyAt = t
+ }
+ if g > 1.25 {
+ // shaken: its loops fly loose and tangle
+ tangle = min(1, tangle + (g - 1.1) * 0.05); tanglePeak = max(tanglePeak, tangle); lastShake = t
+ let push0 = P2(-ax, -ay) * (g * 16)
+ let push = P2(push0.x * c - push0.y * s, push0.x * s + push0.y * c)
+ for i in pos.indices {
+ let x = Double(i)
+ let jit = P2(sin(x * 0.13 + t * 9), cos(x * 0.11 + t * 7)) * (g * 14)
+ let out = min(1.3, simd_length(pos[i]) / 110) // the knot's small loops barely jostled
+ vel[i] += push + jit * (out * out)
+ }
+ busyAt = t
+ }
+ }
+ func crown(_ r: Rig, _ delta: Double) {
+ crownIdle = 0; busyAt = t
+ // the crown is its spool: one way reels the thread in off the ball, the other feeds it back; once it's all wound,
+ // turning on winds it tighter (it squints with the effort and boings loose when you let go)
+ if delta > 0 && yarn.off <= 0 { wound = min(1, wound + delta * 0.05); woundV = 0 }
+ else if delta < 0 && wound > 0.02 { wound = max(0, wound + delta * 0.05); woundV = 0 }
+ else if yarn.crown(delta) { r.onHaptic?(.click); tugT = 0; squash.v += delta > 0 ? -0.4 : 0.3 }
+ }
+ func touched(_ r: Rig, at pt: CGPoint) { finger = pt; lastTouch = pt; busyAt = t; onThread = yarn.touch(P2(pt.x, pt.y)) }
+ private var onThread = false
+ func dragged(_ r: Rig, at pt: CGPoint) {
+ // on the thread: it's pulled along; on the ball: it rolls the way your finger goes
+ if let f = finger { yarn.drag(from: P2(f.x, f.y), to: P2(pt.x, pt.y)); if !onThread { jellyV += P2(pt.x - f.x, pt.y - f.y) * 0.3 } }
+ finger = pt; busyAt = t
+ }
+ func released(_ r: Rig) {
+ yarn.release(); onThread = false
+ if let f = finger, pluck > 0.3 {
+ // let go: the threads it had pulled snap back with a twang, the ball wobbles back
+ twang(at: f, strength: 150 * pluck)
+ let d = P2(f.x, f.y) - center, l = max(1, simd_length(d))
+ jellyV += d / l * -40 * pluck
+ }
+ finger = nil
+ }
+ func poke(_ r: Rig) {
+ pokes = pokes.filter { t - $0 < 3 } + [t]
+ yarn.tap()
+ if let p = lastTouch {
+ twang(at: p, strength: 170)
+ let d = P2(p.x, p.y) - center, l = max(1, simd_length(d))
+ jellyV += d / l * -55
+ }
+ squash.v -= 3
+ switch state {
+ case .blocked: crossT = max(crossT, 1.2) // crosser
+ case .dizzy: break // it's too dizzy to mind
+ case .sleep: startle = 1.1; hop.v = -90 // woken with a start, then back to sleep
+ default:
+ if pokes.count >= 4 { pokes = []; crossT = 2.2; startle = 0 }
+ else if crossT <= 0 { startle = 0.9; hop.v = -130; squash.v -= 0.4 }
+ }
+ busyAt = t
+ }
+ func pet(_ r: Rig) { petT = 0.45; busyAt = t }
+ func deny(_ r: Rig) { crossT = 1.2 }
+ func hit(_ pt: CGPoint) -> Bool { simd_length(P2(pt.x, pt.y) - yarn.center) < yarn.radius + 14 }
+
+ // MARK: drawing
+
+ func draw(_ r: Rig, _ ctx: GraphicsContext) {
+ // dimmed: drawn as one layer at half strength (piece by piece, the overlaps would show through lighter)
+ if r.ao { var c = ctx; c.opacity = 0.5; c.drawLayer { l in self.paint(r, l) } } else { paint(r, ctx) }
+ }
+
+ private func paint(_ r: Rig, _ ctx: GraphicsContext) {
+ let p = r.pose(raw: true)
+ let g0 = ctx
+ let sc = scale
+ let L = mood[Y.life.rawValue]
+ let bob = cur.bob * sin(t * TAU * 0.45) - (state == .listening ? r.voice * 5 : 0)
+ let breathe = cur.breathe * sin(t * TAU / 3.6)
+ let morph = 0.03 * L * sin(ph * 0.9) // it shifts its shape: wider, then taller
+ let tremble = cur.tremble * sin(t * 113) * (0.6 + 0.4 * sin(t * 7))
+ let stretch = P2(clamp(abs(dragV.x) * 0.0006, 0, 0.1), clamp(abs(dragV.y) * 0.0006, 0, 0.1))
+ let pulse = 1 + 0.05 * bump
+ // the floating pose's shadow stays on the ground
+ if shadowK > 0.05 {
+ var s = g0.faded(shadowK); s.translateBy(x: center.x, y: center.y); s.scaleBy(x: Self.K * sc * (1 - bob * 0.012), y: Self.K * sc)
+ for d in ScribbleArt.deco("11") where d.kind == 3 { s.fill(Strokes.smoothClosed(d.pts), with: .color(Self.blue)) }
+ }
+ var b = g0
+ b.translateBy(x: center.x + tremble + jelly.x * 0.3, y: center.y + hop.y + bob + jelly.y * 0.3)
+ b.rotate(by: .radians(tilt))
+ // jelly: stretched along the way it was thrown, narrower across
+ let jl = simd_length(jelly)
+ if jl > 0.05 {
+ let ja = atan2(jelly.y, jelly.x), jk = min(0.14, jl / 160)
+ b.rotate(by: .radians(ja)); b.scaleBy(x: 1 + jk, y: 1 - 0.6 * jk); b.rotate(by: .radians(-ja))
+ }
+ b.scaleBy(x: Self.K * sc * pulse * (1 + stretch.x - stretch.y * 0.5 - squash.k * 0.5 - breathe * 0.5 + morph),
+ y: Self.K * sc * pulse * (1 + stretch.y - stretch.x * 0.5 + squash.k + breathe - morph))
+ yarn.draw(g0, color: Self.blue)
+ drawDeco(b, r: r)
+ // the face on the ball's front (smaller as the ball gets smaller, never too small to read)
+ var f = g0
+ f.translateBy(x: yarn.center.x + faceOff.x, y: yarn.center.y + bob + faceOff.y - yarn.radius * 0.05)
+ f.scaleBy(x: Self.K * sc * yarn.faceK, y: Self.K * sc * yarn.faceK)
+ drawFace(f, r: r, pose: p)
+ // subagents: small balls of yarn going round it
+ if minis > 0.02 {
+ for k in 0..<3 {
+ let a = t * 0.75 + Double(k) * TAU / 3, c = P2(cos(a) * 84, sin(a) * 74) * minis
+ var m = g0.faded(minis); m.translateBy(x: center.x + c.x, y: center.y + c.y)
+ let rot = t * (1.2 + 0.3 * Double(k)) + Double(k)
+ m.scaleBy(x: Self.K * 0.24, y: Self.K * 0.24)
+ var ball = m; ball.rotate(by: .radians(rot))
+ ball.stroke(Self.mini, with: .color(Self.blue), style: StrokeStyle(lineWidth: Self.W * 1.6, lineCap: .round, lineJoin: .round))
+ for side in [-1.0, 1.0] { m.fill(Path(ellipseIn: CGRect(x: side * 22 - 9, y: -16, width: 18, height: 26)), with: .color(Self.faceInk)) }
+ }
+ }
+ }
+
+ func front(_ r: Rig, _ ctx: GraphicsContext) {}
+
+ /// The line, in one flat colour: smoothed so it never turns tighter than `minRadius`, the knot under the face with a
+ /// wider pass of itself underneath, so the face always sits on wire, never on a gap.
+ private func drawLine(_ g: GraphicsContext) {
+ // evenly spaced along the line, half a stroke apart, then relaxed wherever it turns too tight
+ var len = 0.0, lenK = 0.0
+ for i in 1..<pos.count { len += simd_length(pos[i] - pos[i - 1]); if i == Self.kN { lenK = len } }
+ guard len.isFinite && len > 1 else { return }
+ let n = max(64, min(1400, Int(len / Self.step)))
+ drawn = Strokes.resample(pos, n)
+ Self.relax(&drawn)
+ let line = StrokeStyle(lineWidth: Self.W, lineCap: .round, lineJoin: .round)
+ let knotW = 1 - clamp(mood[Y.swirl.rawValue], 0, 1)
+ if knotW > 0.05 {
+ var under = Path(); Self.addRun(&under, drawn, 0, Int(Double(n - 1) * lenK / max(1, len)))
+ g.stroke(under, with: .color(Self.blue), style: StrokeStyle(lineWidth: Self.W * (1 + 0.6 * knotW), lineCap: .round, lineJoin: .round))
+ }
+ var all = Path(); Self.addRun(&all, drawn, 0, drawn.count - 1)
+ g.stroke(all, with: .color(Self.blue), style: line)
+ }
+
+ /// The line is made smooth where it's made (loops never smaller or sharper-ended than `minRadius`, each loop always
+ /// turning on ahead of the hand that draws it); this only rounds off a kink the springs might fold in a fast move.
+ /// (Easing every tight spot toward its neighbours would shrink a small loop tighter, so loops are left alone.)
+ static func relax(_ p: inout [P2]) {
+ let n = p.count
+ guard n > 4 else { return }
+ for _ in 0..<20 {
+ var changed = false
+ for i in 1..<(n - 1) {
+ let a = p[i] - p[i - 1], b = p[i + 1] - p[i]
+ let la = simd_length(a), lb = simd_length(b)
+ let th = la > 1e-6 && lb > 1e-6 ? acos(clamp(simd_dot(a, b) / (la * lb), -1, 1)) : Double.pi
+ if th > kink {
+ for j in max(1, i - 1)...min(n - 2, i + 1) {
+ let mid: P2 = (p[j - 1] + p[j + 1]) * 0.5
+ p[j] += (mid - p[j]) * (j == i ? 0.5 : 0.25)
+ }
+ changed = true
+ }
+ }
+ if !changed { break }
+ }
+ }
+
+ /// The shortest way from `p0` heading `h0` to `p1` heading `h1` that never turns tighter than `rho` (an arc, a
+ /// straight, an arc: the four Dubins ways, the shortest kept), as `count` points evenly along it, the first a step on.
+ static func dubins(_ p0: P2, _ h0: Double, _ p1: P2, _ h1: Double, _ rho: Double, count: Int, keep: inout Int) -> [P2] {
+ func rot90(_ v: P2) -> P2 { P2(-v.y, v.x) }
+ let u0 = P2(cos(h0), sin(h0)), u1 = P2(cos(h1), sin(h1))
+ typealias Way = (len: Double, c0: P2, s0: Double, a0: Double, q0: P2, q1: P2, c1: P2, s1: Double, a1: Double)
+ var best: Way? = nil, bestKind = -1, kept: Way? = nil
+ for (kind, (s0, s1)) in [(1.0, 1.0), (-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0)].enumerated() { // +1 turns toward +90°
+ let c0: P2 = p0 + rot90(u0) * (rho * s0), c1: P2 = p1 + rot90(u1) * (rho * s1)
+ let v: P2 = c1 - c0, d = simd_length(v)
+ var u: P2
+ if s0 == s1 {
+ guard d > 1e-6 else { continue }
+ u = v / d
+ } else {
+ guard d > 2 * rho else { continue }
+ let beta = atan2(v.y, v.x), phi = beta + s0 * asin(2 * rho / d)
+ u = P2(cos(phi), sin(phi))
+ }
+ let q0: P2 = c0 - rot90(u) * (rho * s0), q1: P2 = c1 - rot90(u) * (rho * s1)
+ let straight = simd_dot(q1 - q0, u)
+ guard straight >= -1e-6 else { continue }
+ func sweep(_ from: P2, _ to: P2, _ sgn: Double) -> Double {
+ let a = atan2(from.y, from.x), b = atan2(to.y, to.x)
+ var x = (b - a) * sgn; x = x.truncatingRemainder(dividingBy: TAU); if x < 0 { x += TAU }; return x
+ }
+ let a0 = sweep(u0, u, s0), a1 = sweep(u, u1, s1)
+ let len = rho * (a0 + a1) + straight
+ let way: Way = (len, c0, s0, a0, q0, q1, c1, s1, a1)
+ if kind == keep { kept = way }
+ if best == nil || len < best!.len { best = way; bestKind = kind }
+ }
+ // keep last frame's way unless another is clearly shorter (switching would make the arm jump)
+ if let k = kept, let b = best, k.len < b.len * 1.15 { best = k } else { keep = bestKind }
+ guard let b = best else { return (1...count).map { p0 + (p1 - p0) * (Double($0) / Double(count)) } }
+ let l0 = rho * b.a0, ls = simd_length(b.q1 - b.q0)
+ return (1...count).map { k in
+ let x = b.len * Double(k) / Double(count)
+ if x <= l0 {
+ let start: P2 = p0 - b.c0, ang = b.s0 * x / rho
+ return b.c0 + P2(start.x * cos(ang) - start.y * sin(ang), start.x * sin(ang) + start.y * cos(ang))
+ } else if x <= l0 + ls {
+ return b.q0 + (b.q1 - b.q0) * ((x - l0) / max(1e-9, ls))
+ } else {
+ let start: P2 = b.q1 - b.c1, ang = b.s1 * (x - l0 - ls) / rho
+ return b.c1 + P2(start.x * cos(ang) - start.y * sin(ang), start.x * sin(ang) + start.y * cos(ang))
+ }
+ }
+ }
+
+ /// Smooth value noise, −1…1, one random value at each whole `x` (the same every time for a seed), eased between.
+ @inline(__always) static func vn(_ x: Double, _ seed: Double) -> Double {
+ let i = floor(x), f = x - i, e = f * f * f * (f * (f * 6 - 15) + 10)
+ let a = Strokes.hash(i, seed), b = Strokes.hash(i + 1, seed)
+ return (a + (b - a) * e) * 2 - 1
+ }
+
+ /// A run of the line's points as a smooth subpath (a curve through the midpoints).
+ private static func addRun(_ path: inout Path, _ p: [P2], _ a: Int, _ b: Int) {
+ guard b > a else { return }
+ path.move(to: CGPoint(x: p[a].x, y: p[a].y))
+ if b - a == 1 { path.addLine(to: CGPoint(x: p[b].x, y: p[b].y)); return }
+ for i in (a + 1)..<b {
+ let m = (p[i] + p[i + 1]) * 0.5
+ path.addQuadCurve(to: CGPoint(x: m.x, y: m.y), control: CGPoint(x: p[i].x, y: p[i].y))
+ }
+ path.addLine(to: CGPoint(x: p[b].x, y: p[b].y))
+ }
+ /// The small balls: a short line wound round.
+ private static let mini: Path = {
+ var p: [P2] = []
+ for i in 0..<90 {
+ let s = Double(i) / 89, th = TAU * 5 * s, c = P2(cos(TAU * 1.2 * s), sin(TAU * 1.2 * s)) * 30
+ p.append(c + P2(cos(th), sin(th) * 0.8) * (52 + 10 * sin(TAU * 3 * s)))
+ }
+ var path = Path(); addRun(&path, p, 0, p.count - 1)
+ return path
+ }()
+
+ /// The sheet's sparkles twinkle round it when it's done, its sweat when it's frazzled.
+ private func drawDeco(_ g: GraphicsContext, r: Rig) {
+ if sparkle > 0.02 {
+ for (i, d) in ScribbleArt.deco("01").enumerated() where d.kind == 1 {
+ let c = Self.centroid(d.pts), ph = t * 5 + Double(i) * 1.7
+ let k = (0.7 + 0.3 * sin(ph)) * sparkle * (state == .done ? outQ(min(1, stateT / 0.5)) : 1)
+ let pts = d.pts.map { c * (0.9 + 0.1 * sparkle) + ($0 - c) * k }
+ g.faded(sparkle * (0.75 + 0.25 * sin(ph))).fill(Strokes.smoothClosed(pts), with: .color(Self.blue))
+ }
+ }
+ let sweat = shown.sw.isEmpty ? 0.0 : 1.0
+ if sweat > 0 {
+ for (i, d) in ScribbleArt.deco("12").enumerated() where d.kind == 2 {
+ let off = P2(0, (t * 0.9 + Double(i) * 0.3).truncatingRemainder(dividingBy: 1) * 6)
+ g.fill(Strokes.smoothClosed(d.pts.map { $0 + off }), with: .color(Self.blue))
+ }
+ }
+ }
+
+ /// The dizzy eyes: a spiral, two and a half turns out from the middle.
+ private static let spiral: Path = {
+ var pts: [P2] = []
+ for i in 0...60 {
+ let u = Double(i) / 60, a = u * 1.6 * TAU
+ pts.append(P2(cos(a), sin(a)) * (3 + 17 * u))
+ }
+ var path = Path(); addRun(&path, pts, 0, pts.count - 1)
+ return path
+ }()
+
+ /// The face: dark marks (a light tongue) on the yarn, each on a rim of the yarn's own colour so it reads even over a
+ /// gap between wires; it follows the finger and the gaze, blinks, pops to each new expression and lags the body.
+ private func drawFace(_ g0: GraphicsContext, r: Rig, pose p: Pose) {
+ var e = p.eye
+ if let f = finger {
+ let d = P2(f.x, f.y) - center, l = max(1, simd_length(d))
+ e.gx = d.x / l * min(1, l / 30); e.gy = d.y / l * min(1, l / 30)
+ }
+ if state == .working { e.gx = sin(t * 2.4) * 0.9; e.gy = 0.35 }
+ let gaze = P2(clamp(e.gx, -1, 1) * 7, clamp(e.gy, -1, 1) * 5.5) * gazeK + aim
+ let open = r.ao ? 1 : clamp(e.open, 0, 1)
+ var g = g0
+ g.translateBy(x: gaze.x * 0.4, y: gaze.y * 0.4)
+ let k = Self.faceScale * (1 + 0.12 * pop.k)
+ g.scaleBy(x: k, y: k)
+ var marks = Path(), tongue: Path? = nil
+ for i in 0..<11 where parts[i].shown {
+ var pts = parts[i].shape
+ if i == 6 && state == .speaking && parts[6].name == "00.m" && fidget <= 0 && petT <= 0 {
+ pts = Strokes.mix(pts, Self.faceGlyph("[email protected]*0.85", "00"), clamp(r.voice * 1.5, 0, 1))
+ }
+ if i < 4 { // eyes: the gaze, and a blink for open ones
+ let c = Self.centroid(pts)
+ let n = parts[i].name
+ let isOpen = n.hasPrefix("21.e") || n.hasPrefix("01.e") || n.hasPrefix("02.e") || n.hasPrefix("12.e")
+ pts = pts.map { q in P2(q.x + gaze.x * 0.6, isOpen ? c.y + (q.y - c.y) * max(0.12, open) + gaze.y * 0.6 : q.y + gaze.y * 0.6) }
+ }
+ if i == 10 { tongue = Strokes.smoothClosed(pts) } else { marks.addPath(Strokes.smoothClosed(pts)) }
+ }
+ // dizzy: spiral eyes where its eyes are, turning
+ var spirals = Path()
+ if spiralK > 0.02 {
+ for (side, name) in [(1.0, "12.eL"), (-1.0, "12.eR")] {
+ let c = ScribbleArt.anchor(name) - ScribbleArt.faceOrigin("12")
+ let a = t * 5 * side
+ let tr = CGAffineTransform(rotationAngle: a).scaledBy(x: spiralK, y: spiralK)
+ .concatenating(CGAffineTransform(translationX: c.x, y: c.y))
+ spirals.addPath(Self.spiral.applying(tr))
+ }
+ }
+ g.fill(marks, with: .color(Self.faceInk))
+ if let tg = tongue { g.fill(tg, with: .color(Self.blue)) }
+ if spiralK > 0.02 {
+ g.stroke(spirals, with: .color(Self.faceInk), style: StrokeStyle(lineWidth: 5.5, lineCap: .round, lineJoin: .round))
+ }
+ }
+}
+
+/// Tangle's face marks and its decorations, traced from its character sheet (refs/scribble-reference.png), in pixels
+/// of the sheet (cells 341 px), each pose's round its own middle, y down; little-endian Int16 eighths of a pixel, base64.
+/// Poses by their place on the sheet: 00 calm · 01 excited · 02 worried · 10 angry · 11 floating · 12 frazzled ·
+/// 20 puddle · 21 reaching · 22 swirl. Decorations: 1 sparkles, 2 sweat, 3 the floating shadow, 4 motion strokes. Face
+/// marks are 64 points, leftmost first, clockwise, so any two blend; "[email protected]*0.8" is 21's left eye moved onto 00's
+/// and scaled.
+enum ScribbleArt {
+ static let N = 64
+ private static func values(_ s: String) -> [Double] {
+ guard let d = Data(base64Encoded: s) else { return [] }
+ let b = [UInt8](d)
+ return stride(from: 0, to: b.count - 1, by: 2).map { i in Double(Int16(bitPattern: UInt16(b[i]) | UInt16(b[i + 1]) << 8)) / 8 }
+ }
+ private static let decos: [String: [(kind: Int, pts: [P2])]] = decoRaw.mapValues { raw in
+ let v = values(raw.1), h = raw.0
+ var vi = 0, out: [(kind: Int, pts: [P2])] = []
+ for k in 0..<h[0] {
+ let kind = h[1 + 2 * k], n = h[2 + 2 * k]
+ out.append((kind, (0..<n).map { j in P2(v[vi + 2 * j], v[vi + 2 * j + 1]) })); vi += 2 * n
+ }
+ return out
+ }
+ static func deco(_ pose: String) -> [(kind: Int, pts: [P2])] { decos[pose] ?? [] }
+ private static let marks: [String: [P2]] = faceRaw.mapValues { s in
+ let v = values(s); return stride(from: 0, to: v.count - 1, by: 2).map { P2(v[$0], v[$0 + 1]) }
+ }
+ /// The middle of a mark's box (where another mark goes when it takes its place).
+ static func anchor(_ n: String) -> P2 {
+ if let g = marks[n] {
+ var lo = P2(1e9, 1e9), hi = P2(-1e9, -1e9)
+ for q in g { lo = simd_min(lo, q); hi = simd_max(hi, q) }
+ return (lo + hi) * 0.5
+ }
+ if n.hasSuffix(".eL") || n.hasSuffix(".eR") { return .zero }
+ let p = String(n.prefix(2)) // a pose without that mark: under its eyes
+ return (anchor(p + ".eL") + anchor(p + ".eR")) * 0.5 + P2(0, 26)
+ }
+ /// The eyes' places in each pose.
+ static let anchors: [String: (String, String)] = [
+ "00": ("00.eL", "00.eR"), "01": ("01.eL", "01.eR"), "02": ("02.eL", "02.eR"), "10": ("10.eLa", "10.eRa"),
+ "11": ("11.eL", "11.eR"), "12": ("12.eL", "12.eR"), "20": ("20.eL", "20.eR"), "21": ("21.eL", "21.eR"),
+ ]
+ /// A face's middle: between its eyes.
+ static func faceOrigin(_ pose: String) -> P2 {
+ guard let a = anchors[pose] else { return .zero }
+ return (anchor(a.0) + anchor(a.1)) * 0.5
+ }
+ /// A mark by name: "00.m", or "[email protected]" (moved onto another's place), with "*0.8" to scale it there.
+ static func glyph(_ name: String) -> [P2] {
+ var n = Substring(name), k = 1.0
+ if let s = n.firstIndex(of: "*") { k = Double(n[n.index(after: s)...]) ?? 1; n = n[..<s] }
+ guard let at = n.firstIndex(of: "@") else { return marks[String(n)] ?? marks["00.m"]! }
+ let src = marks[String(n[..<at])] ?? marks["00.m"]!, to = anchor(String(n[n.index(after: at)...]))
+ let from = anchor(String(n[..<at]))
+ return src.map { to + ($0 - from) * k }
+ }
+ private static let decoRaw: [String: ([Int], String)] = [
+ "01": ([12, 1, 58, 1, 16, 1, 38, 1, 17, 1, 24, 1, 28, 1, 20, 1, 15, 1, 11, 1, 29, 1, 27, 1, 46], "wAPb+7wD5Pu7A/H7uAP++7QDC/yxAxf8qwMj/KUDL/ydAzn8lANC/IoDSvx/A1D8dANV/G0DW/xsA2L8cANo/HgDbfyEA3D8jwN1/JkDffyiA4b8qgOQ/LEDm/y3A6f8uwOz/L4DwPzCA838xgPW/M0D2fzUA9f82APR/NsDx/zdA7r84QOu/OUDofzqA5X88QOJ/PgDf/wBBHX8CwRt/BUEZ/weBGH8IwRa/CIEVPwbBE/8EQRK/AYEQ/z8Azz88gMy/OsDKPzkAx384AMR/NwDBPzZA/b71QPp+9ID3vvNA9j7xgPX+7ACBPyoAgz8pAIV/KQCIPynAin8rQIx/LUCNfy9AjX8xgIy/M0CKvzSAiH80wIX/NACDvzKAgX8wwIB/LkCAPxw+4L8avuJ/Gj7kvxr+538cPun/Hf7sfyB+7v8i/vF/JT7z/yd+9j8p/vh/LH76/y7+/X8xfv+/M/7B/3Z+xD95PsZ/e77H/35+yH9Avwg/Qj8G/0J/BP9B/wJ/QL8/vz7+/P88vvp/On73vzf+9T81fvK/Mv7wPzC+7f8uPuu/K37pfyj+5v8mPuS/I37ifyD+4P8efuA/FcEK/1NBC79RAQ0/T4EPP08BEb9PQRQ/UIEWf1JBGD9UgRj/VwEYv1lBF/9bARX/XEETv1yBEP9cAQ6/WoEMv1iBC39pwNE/Z8DRv2aA079lQNZ/Y4DZP2HA2z9hANz/YcDev2QA4H9mAOI/ZsDkv2eA5z9pAOf/asDnv2vA5f9sQON/bUDg/2+A3v9xANy/cYDav3AA2T9twNf/bADV/2sA039X/tk/VT7Z/1M+2z9Sftz/Uz7e/1S+4H9XfuG/Wn7i/12+5D9g/uU/Y/7mP2d+5z9qvug/bj7o/3E+6b9zvul/dX7n/3Y+5j91vuQ/c/7if3G+4L9u/t9/a77eP2h+3P9lPtv/Yf7av16+2f9bftl/ccDywG/A9ABuwPYAbwD4QHCA+kBywPxAdcD+QHjA/8B7wMEAvsDBgIFBAQCDQT+ARIE9gESBO0BDQTkAQUE3QH6A9YB7gPRAeADzgHTA8oBiPvqAYD78gF8+/sBfPsGAn/7DwKH+xUCkPsYApr7FgKj+xECqfsJAqv7AAKp+/YBpPvtAZz76AGS++cBKPxIAiH8TwIf/FcCIfxfAij8ZAIw/GQCN/xgAjz8WQI8/FECOPxKAjD8RgKo+58CofumApz7sAKX+7sCj/vDAoT7ygJ++9ECf/vYAoX73QKO++ECl/vnAp378AKh+/sCpvsEA6z7BwOz+wUDuPv+Arz79ALA++kCx/vhAtD72gLW+9MC1vvLAtH7xQLJ+8ECwPu9Arv7tAK2+6kCsPuhAtgDswLTA7oC0wPCAtgDywLgA9YC6QPgAvMD6gL9A/QCCAT9AhQEBQMfBA0DKgQSAzUEFAM+BBEDRgQLA0gEAwNHBPsCQQTxAjgE5wIuBN4CJATVAhgEzgINBMYCAgS/AvcDtwLsA7IC4gOwAmD84QJb/OgCWPzyAlT8/wJR/AwDS/wYA0T8IgM7/CwDMvw1Ayj8PQMi/EQDI/xLAyr8UAM0/FUDQPxcA0n8ZANP/G4DVPx5A1j8hgNb/JMDX/ygA2P8qgNp/LADcfywA3f8rAN5/KMDevyYA3v8igN9/H0DgPxxA4b8ZQON/FsDlvxTA6D8SwOo/EQDqfw9A6X8NwOc/DIDkfwsA4f8IwN//BoDefwPA3T8AgNv/PYCa/zqAmf84gI="),
+ "11": ([1, 3, 196], "O/+zBC3/tAQf/7QEEv+1BAT/tgT2/rYE6P63BNr+twTM/rgEvv65BLH+uwSj/rsElf68BIf+vQR5/r4Ea/7ABF7+wQRQ/sIEQ/7DBDX+xQQo/sYEGv7HBAz+yAT+/ckE8f3MBOP9zgTV/dAEyP3SBLv91QSu/dcEof3aBJP93QSH/eEEe/3mBHL97QRs/fQEav38BGz9BAVy/QsFev0RBYX9FgWR/RoFnv0fBav9IgW4/SUFxf0nBdP9KQXh/SsF7/0tBf39LwUL/jAFGf4yBSf+MwU1/jUFQ/42BVD+NwVe/jcFbP44BXn+OgWH/jsFlf48BaP+PQWx/j4Fv/4/Bc3+QAXb/kAF6P5ABfb+QQUD/0EFEP9CBR3/QwUr/0QFOP9EBUb/RQVT/0UFYf9HBW7/RwV8/0gFiv9IBZn/RwWn/0cFtf9HBcP/RwXR/0cF3/9HBez/RwX6/0cFCABHBRYARwUlAEcFMwBGBUAARwVOAEcFXABGBWoARgV4AEYFhgBGBZQARQWiAEUFsABFBb4ARQXMAEQF2gBDBegAQgX2AEIFBAFBBRIBQAUgAT8FLgE/BTwBPgVJAT4FVwE8BWUBOwVzATkFgQE4BY8BNwWdATYFqwE1BbkBMwXHATEF1QEvBeMBLQXwASsF/QEpBQsCKAUYAiYFJQIkBTICIAU/Ah4FSwIaBVgCFgViAhAFawIKBXICAgV0AvoEcgLyBG0C6wRkAuUEWQLfBE0C2wRBAtcENALVBCcC0wQaAtAEDALNBP8BywTxAckE4wHHBNYBxgTIAcQEugHCBKwBwASeAb8EkQG+BIMBvQR1AbwEZwG6BFoBuQRMAbgEPQG4BC8BtwQhAbcEEwG2BAUBtgT3ALUE6QC0BNsAswTNALIEvwCxBLEAsASjAK8ElQCvBIcArwR6AK4EbACuBF4ArQRQAK0EQgCtBDQArQQmAK0EGACtBAoArAT8/60E7v+tBOD/rQTT/60Exf+tBLf/rgSq/64EnP+vBI7/rwSA/68Ecv+wBGT/sARW/7EESf+yBA=="),
+ "12": ([4, 2, 59, 2, 54, 2, 41, 2, 38], "1vvv/M379/zF+//8wPsJ/b/7FP3B+x/9xvsq/c37Mv3X+zr94vtB/e77Rv36+0v9CPxP/RX8U/0h/FT9LvxU/Tf8Uv05/E39NvxI/S78Q/0j/D39F/w4/Qr8NP3/+y798/sp/ej7I/3h+xz93vsU/eD7Df3n+wn98fsH/fz7CP0I/Az9FPwR/SH8Fv0s/B39N/wl/UH8Lf1K/Df9U/xB/Vz8Sv1k/FD9bPxS/XH8Tv1x/Ef9bvw+/Wf8Nf1f/Cr9Vvwf/Uz8Fv1C/A39N/wF/Sz8/fwg/Pf8FPzy/An87fz8++z87vvr/OL77Pz2A3H96QNz/dwDd/3QA3z9xQOD/bkDiv2uA5L9pAOa/ZsDpP2SA679iwO5/YUDxP2DA839hQPV/YsD1/2RA9X9mQPO/aIDxP2tA7r9twOw/cEDp/3MA5/91gOX/eIDkf3uA439+gOL/QMEjP0KBJD9CwSX/QgEnf0ABKP99QOp/ekDsP3cA7b90QO9/cgDw/3FA8r9yQPP/dAD0f3aA9D95gPN/fIDyP3+A8T9CQS9/RQEtv0eBK79JQSl/SkEm/0pBJH9JgSH/SAEff0YBHb9DgRy/QIEcP3W+9j9yPvb/bz73/2x++T9pvvr/Z779P2Z+/79mPsI/pr7Ev6g+xr+qfsg/rP7JP6/+yT+y/sk/tf7If7k+xz+8PsV/vn7D/7++wr++vsG/vL7Bf7n+wX+2vsH/s77Cv7E+wr+v/sG/r77AP7D+/v9zPv3/dj78/3l+/D98/vt/QH86/0N/On9Fvzl/Rj84P0T/Nz9C/zZ/f/71/3y+9b95PvX/QYEOP75Azr+7QM9/uQDQf7gA0f+4wNM/uoDTf71A07+AgRP/g8EUv4cBFX+KQRY/jIEXf42BGL+MgRl/ikEaP4dBGr+EQRs/gcEb/4DBHT+BAR6/goEfv4TBID+IASA/i0EgP47BH/+RwR8/lAEeP5XBHD+WgRn/lkEXv5VBFX+TQRN/kQERv45BED+LQQ8/iAEOv4TBDj+"),
+ "22": ([6, 4, 135, 4, 58, 4, 122, 4, 64, 4, 111, 4, 49], "Ov7F+y3+yfsg/sz7FP7R+wf+1fv7/dr77/3g++P95vvX/ev7y/3y+7/9+Pu0/f77qP0F/J39DPyR/RT8hf0b/Hn9I/xu/Sr8Y/0x/Ff9OfxM/UH8Qv1J/Df9Uvwr/Vr8If1j/Bb9a/wM/XT8Av1+/Pj8iPzu/JL85Pyc/Nr8pvzR/LD8x/y6/L78xfy2/M/8rfzZ/KT84/yc/O38lPz4/Iv8A/2E/A79fPwZ/XX8I/1u/C79Z/w6/WD8Rf1Z/FH9Uvxd/Uz8aP1G/HT9QPyA/Tr8jP01/Jj9L/yl/Sr8sf0l/L79IPzK/Rz81/0Y/OT9FPzx/RD8/f0O/Ar+DPwX/g38H/4S/CP+Ffwf/hn8Fv4e/An+I/z8/Sf88P0s/OP9MvzY/Tf8zP08/L/9Qvyz/Uf8p/1N/Jv9VPyQ/Vr8hP1h/Hj9aPxs/W/8YP12/FX9fvxJ/YX8Pv2M/DL9lPwn/Zv8HP2j/BH9rPwG/bT8+/y8/PD8xfzm/M383PzW/NL83vzJ/Oj8v/zx/LX8+/ys/AX9ovwP/Zn8GP2Q/CL9iPws/X78Nv12/ED9bfxL/WT8Vf1c/GH9U/xs/Uv8d/1D/IL9O/yO/TP8mf0s/KT9Jfyv/R38u/0V/Mb9D/zS/Qn83f0C/On9/Pv0/fb7AP7w+wz+6/sY/uX7JP7g+zD+2/s9/tb7Sv7R+1T+zfta/sj7WP7E+1L+wvtH/sP7Av0F/Pb8Cvzq/BD83vwX/NP8H/zI/Cf8vfww/LL8Ofyo/EL8nvxM/JX8VvyL/F/8gvxp/Hn8c/xw/H38Z/yI/F/8k/xX/J78T/yp/Ej8tPxB/MD8OvzM/DT82Pwu/OT8KPzv/CP8/Pwh/Af9IvwO/Sf8DP0s/Ab9Mvz8/Dn88PxA/OT8SPzZ/FD8zfxY/ML8X/y3/Gf8rPxw/KH8efyW/IP8i/yM/IH8lfx3/J/8bfyo/GL8svxZ/Lz8T/zH/Eb80fw9/Nv8NPzm/Cv88vwj/P38G/wI/RT8E/0M/Bj9B/wU/QP8Df0C/EsDHf1MAyP9UQMq/VkDNP1iA0D9agNL/XIDVv15A2L9gANt/YcDef2NA4X9lAOR/ZoDnf2hA6n9pwO1/a0Dwv2yA879uAPb/b0D6P3CA/T9xwMB/ssDDv7PAxv+0wMo/tYDNf7ZA0L+3ANQ/uADXf7jA2r+5QN4/ucDhv7pA5P+6wOh/u0Drv7vA7z+8APK/vID2P70A+b+9AP0/vUDAv/1AxH/9QMf//UDLf/0Azz/9ANK//MDWP/xA2b/8AN0/+8Dgv/uA5H/7AOe/+oDrP/nA7r/5QPI/+MD1f/gA+L/3QPv/9oD/P/XAwgA1gMSANkDFwDdAxQA4QMNAOUDAgDqA/b/7gPp//MD3P/2A9D/+QPD//0Dtv8ABKj/AwSb/wUEjf8GBID/CARx/woEZP8MBFb/DQRI/w0EOv8OBCv/DgQd/w4ED/8OBAH/DgTy/g0E5P4NBNb+DATI/goEuv4IBKz+BwSd/gUEj/4DBIL+AAR0/v4DZ/77A1r++ANN/vYDQP7zAzP+7wMn/usDGv7nAw7+4gMB/t0D9f3YA+j90wPc/c0D0P3IA8T9wgO3/bwDq/23A579sAOS/aoDhv2jA3r9nANu/ZQDYv2MA1f9gwNM/XoDQf1xAzf9ZwMu/V0DJf1TAx79OgS//TcExf04BM39PATX/UAE5P1FBPH9SQT+/U0EC/5QBBn+VAQl/lYEMv5ZBED+WwRO/l4EXP5gBGr+YgR5/mMEh/5kBJX+ZQSj/mUEsv5lBMD+ZQTO/mYE3f5lBOv+ZQT6/mUECP9kBBb/YwQk/2EEMv9gBD//YARM/2EEVP9jBFb/ZQRQ/2gERv9sBDv/bwQu/3MEIf92BBP/dwQG/3kE+P56BOr+fATb/n0Ezv59BMD+fQSx/n0Eo/57BJX+egSH/nkEef53BGv+dgRd/nQET/5yBEH+bwQz/mwEJv5oBBn+ZQQM/mAE//1bBPL9VgTm/VAE2/1IBND9QQTF/aP7lgCf+50AnfupAJ37tgCd+8QAnvvSAJ/74ACg++0Aovv7AKX7CAGn+xYBq/sjAa77MAGz+z0BtvtJAbv7VgG/+2IBxPtvAcn7ewHO+4gB1PuUAdn7oQHf+60B5fu5Aez7xgHz+9IB+vveAQL86QEJ/PUBEPwAAhj8DAIg/BcCKfwhAjL8KwI6/DYCQ/w/Akz8SQJV/FMCX/xcAmj8ZgJy/G8CfPx4Aob8gQKQ/IoCm/yTAqb8mwKx/KICvPyqAsf8sQLT/LgC3vy+Aun8xgL1/MwCAv3SAg392AIX/dsCHf3ZAh391AIW/c8CDP3IAgH9wAL1/LgC6fyxAt78qQLT/KACyPyYAr38jwKz/IUCqfx8Ap/8cwKU/GoCivxgAoD8VgJ2/E0CbPxDAmL8OQJZ/C8CT/wkAkf8GgI+/A8CNfwEAi38+QEm/O4BHvziARf81gEP/MsBCPy/AQL8tAH8+6gB9fucAe77kAHo+4QB4/t3Ad37agHY+14B0/tRAc77RQHK+zkBxvssAcP7HwG/+xMBvfsGAbn7+QC3++wAtfveALP70QCx+8MAr/u1AK77pwCt+5sAqfuVAJL7wwGN+8gBjfvRAY/73gGS++oBlvv3AZr7BAKg+xECpvsdAqz7KgK0+zUCu/tBAsT7TALM+1YC1vtgAuD7agLp+3QC8/t+Avz7hwIH/I8CEvyXAh78nQIq/KQCNvypAkL8rgJL/K8CTvytAkn8qAJA/KACNfyYAir8jwIf/IYCFfx9Agr8cwIA/GoC9/tgAu77VgLl+0sC3PtBAtT7NQLL+yoCxPsfArz7FAK1+wkCrvv9Aaj78QGi++UBnPvZAZb7zQE="),
+ ]
+ private static let faceRaw: [String: String] = [
+ "00.eL": "Wv4R/13+Af9m/vP+dP7q/oT+5v6U/uv+of71/qj+BP+q/hT/rv4l/7L+NP+5/kT/wv5S/8z+Xv/Z/mn/5/5y//b+eP8H/3v/F/95/yf/dP81/2v/Qf9g/0v/U/9U/0X/Wv81/2D/Jv9o/xj/df8O/4X/C/+V/w7/o/8X/6n/J/+r/zf/qf9I/6X/WP+f/2f/l/92/4//hP+G/5L/e/+e/2//qv9i/7T/U/+8/0X/xP81/8r/Jf/O/xX/0P8E/9D/9P7O/+P+y//U/sb/xP6//7b+uP+o/q//m/6k/5D+mP+F/oz/e/5+/3P+cP9r/mH/Zv5R/2D+Qv9d/jH/Wv4h/w==",
+ "00.eR": "4P9R/+H/QP/o/zD/8/8j/wIAHP8TAB7/IgAm/yoANP8vAET/MQBV/zUAZv86AHb/QgCF/0sAk/9XAJ//ZgCo/3UArv+GALP/lwCz/6cAsP+3AKr/xgCi/9MAl//eAIr/5wB8/+8Abf/2AF3//wBP/w4BR/8fAUX/LwFJ/zoBVv8/AWb/PwF3/zoBh/80AZf/LAGm/yMBtP8ZAcL/DwHP/wIB2//1AOX/5gDu/9cA9v/IAP3/twACAKcABQCWAAYAhQAGAHQABQBjAAMAUwD+/0QA9/81AO//JgDl/xoA2v8OAM7/BADA//v/sv/z/6L/7P+T/+f/g//i/3L/4f9i/w==",
+ "00.m": "hf4hAIv+CgCf/v7/t/7//8r+DADY/h8A5v4zAPT+RgAF/1cAGP9mACv/cwBA/34AVv+IAGz/kQCD/5cAmv+dALL/ogDJ/6QA4f+kAPn/owARAJ8AKACaAD8AkwBVAIoAagCAAH8AdACSAGYApABWALYARgDMAD4A4wBDAPMAVAD3AGsA7wCBAN4AkgDMAKEAuACvAKQAvACQAMgAewDTAGUA3ABOAOQANwDqACAA8AAIAPQA8f/1ANn/9QDB//UAqf/0AJL/7wB6/+sAY//lAE3/3gA2/9UAIf/KAA3/vgD4/rEA5f6kANL+lQDA/oUAsP50AKD+YQCU/k0Aif44AA==",
+ "01.eL": "4P50/+H+af/i/l7/4/5T/+T+SP/n/j7/6v4z/+z+KP/w/h7/8/4T//b+Cf/7/v/+//71/gT/6/4J/+H+D//Y/hf/0P4f/8j+J//C/jH/vf48/7n+Rv+5/lH/vP5b/8H+Y//I/mr/0f5v/9v+c//l/nT/8P51//v+dv8G/3b/Ef91/xz/dP8n/3P/Mv9y/z3/b/9I/2z/Uv9r/13/af9o/2X/cv9i/33/Xv+H/1v/kv9Y/5z/U/+m/03/sP9I/7n/Qf/C/zr/yv8x/9D/J//V/xz/1/8R/9j/B//U//3+z//1/sf/7v6+/+r+tP/l/qv/4v6g/+D+lf/g/or/4P5//w==",
+ "01.eR": "OwCk/zsAmf88AI7/PACD/z0AeP8/AG3/QgBi/0QAV/9GAEz/SgBC/0wAN/9RAC3/VAAi/1kAGP9dAA7/YgAE/2gA+/5uAPH+dgDp/n4A4v6IAN3+kwDZ/p4A2f6pANz+sgDh/roA6f7AAPL+xAD8/skABv/LABH/zAAc/8wAKP/MADP/ywA+/8sASf/KAFT/yABf/8YAav/EAHX/wwCA/8EAi/+9AJX/uwCg/7kAq/+0ALX/sQC//6wAyf+oANT/ogDd/5sA5v+UAO7/iwD1/4IA+v93AP7/bAD+/2IA+v9YAPX/UADt/0oA5P9EANr/QQDQ/z0Axf88ALr/OwCv/w==",
+ "01.m": "+v58APv+awD9/loACf9NABj/RAAp/0AAOv9AAEv/QABd/0AAbv9AAID/QACR/0AAov9AALT/QADF/z8A1v89AOf/OAD4/zgACgA3ABsANgAsADUAPgA2AE8ANwBfAD0AbgBGAHoAUgB+AGMAgwBzAH4AhAB7AJUAdgClAHIAtgBqAMUAYwDVAFsA5ABTAPMARwAAATwADgEzABwBJQAmARcAMQEKAD0B+v9CAer/SQHa/04Byf9QAbf/UAGm/08Blv9JAYb/QgF1/z4BZv83AVj/LAFK/yMBPf8XATH/CgEl//4AHf/uABX/3wAN/88ABv/AAAL/rwD9/p8A+/6NAA==",
+ "01.tg": "bf8UAW3/DQFv/wcBc/8BAXf//AB8//cAgf/yAIf/7wCM/+sAkv/nAJj/5QCe/+EApf/gAKz/3gCy/9wAuf/aAL//2QDG/9gAzf/YANT/1wDb/9cA4f/XAOj/2ADv/9gA9v/ZAPz/2wADAN0ACQDfABAA4QAWAOQAHADnACEA6wAjAPIAIQD4AB4A/gAaAAMBFQAJAREADgEMABIBBwAXAQIAGwH8/x8B9v8jAfH/JwHr/ysB5f8uAd//MAHY/zIB0f8zAcr/NAHE/zQBvf8zAbb/MwGv/zIBqP8xAaL/MAGb/y8Blf8tAY7/KgGI/ygBgv8kAXz/IQF2/x4Bcf8ZAQ==",
+ "02.bL": "QP4Z/0T+Df9P/gf/W/4D/2f+//5z/v3+f/76/ov+9v6X/vL+ov7t/q7+6f66/uT+xf7f/tH+2v7c/tX+5/7P/vL+yf79/sT+CP+8/hL/tv4c/67+Jv+m/i//nf44/5X+Qf+M/kr/g/5S/3r+W/9x/mX/af5x/2T+ff9l/ob/bf6I/3n+hP+F/n3/kP52/5r+bv+k/mb/rf5d/7b+U/++/kr/x/5A/8/+N//W/iz/3v4i/+X+F//s/g3/8v4B//j+9v79/uv+A//g/gj/1P4M/8j+Ef+8/hX/sf4a/6X+Hf+Z/iH/jf4l/4D+J/90/ir/aP4s/1v+LP9P/ir/RP4k/w==",
+ "02.bR": "RQB5/kcAbf5PAGT+XABj/mYAav5vAHL+dwB8/oAAhf6IAI7+kQCX/pwAnv6lAKb+sACt/rsAsv7GALn+0QC+/twAxP7nAMr+8wDO/v4A0/4LAdb+FwHa/iMB3P4vAd7+PAHf/kgB4v5UAeT+YQHl/m0B5/55Aer+hgHt/o8B9f6RAQH/jQEM/4IBE/92ARX/agEW/10BFv9RARX/RAEU/zgBE/8rARH/HwEO/xMBDf8GAQr/+wAG/+8AA//jAP7+1wD7/ssA9v7AAPH+tQDr/qsA5P6gAN7+lgDW/owAzv6DAMb+egC9/nEAtP5oAKz+XwCi/lcAmf5QAI/+SQCE/g==",
+ "02.eL": "4v6h/+b+m//p/pX/6P6O/+f+h//l/oH/5f56/+X+c//m/mz/6P5l/+r+X//v/lr/8v5U//f+T//8/kr/Av9G/wf/Qv8N/z7/FP88/xr/Of8g/zf/J/81/y7/Nf81/zX/PP81/0P/N/9J/zn/UP88/1b/Pv9c/0L/Yf9G/2b/S/9q/1H/bv9X/3D/Xf9x/2T/cv9r/3H/cv9w/3j/b/9//2z/hf9o/4v/Zf+R/2H/l/9c/5z/V/+h/1H/pf9M/6n/Rv+s/z//r/85/7L/M/+0/yz/tf8l/7b/Hv+3/xf/uP8Q/7n/Cv+4/wP/t//8/rX/9v6z//D+r//q/qz/5f6n/w==",
+ "02.eR": "aAB5/2gAcv9oAGv/aQBk/2sAXf9uAFf/cQBR/3UAS/97AEb/gABC/4UAPf+MADv/kgA3/5gANf+fADP/pgAz/60AM/+0ADT/uwA1/8IAN//IADr/zgA+/9QAQv/ZAEb/3wBK/+QAT//oAFX/7ABb//AAYf/xAGf/8gBu//MAdf/zAHz/8gCD//EAiv/wAJH/7QCY//EAnf/2AKH/9wCo//IArP/rAK//5QCx/94AtP/XALX/0AC1/8kAtf/CALX/uwC1/7QAtP+uALL/pwCv/6AArf+aAKv/kwCo/40Apf+GAKP/gACg/3oAnP90AJj/cACT/2wAjf9pAIf/aACA/w==",
+ "02.m": "7/6RAPD+ewD4/mcABf9WABj/SwAs/0UAQv9FAFj/RQBs/0AAe/8wAIj/HwCX/xAAqv8FAL/////U//3/6f8BAPz/DAANABkAHQAnADIAJwBFAB0AWAASAGwADACCAAsAlwANAKsAFgC9ACIAzAAxANkAQwDjAFYA7ABqAPMAfgD0AJMA5ACgANEAmQDFAIcAvQBzALUAXwCrAEwAnAA9AIgANABzADMAYAA9AE4ASgA6AFEAJQBSABAATAD//z8A7v8xANz/JgDG/yUAs/8uAKL/PACV/00Ahv9dAHT/aABf/20ASv9sADT/bAAf/3AAEf+AAAv/lQAG/6oA9P6lAA==",
+ "10.eLa": "mv4h/53+FP+l/gr/sf4E/77+BP/L/gj/1/4N/+P+FP/u/hv/+v4h/wX/KP8R/y7/HP81/yj/O/80/0H/P/9H/0v/Tv9X/1T/Y/9Z/2//Xv97/2T/h/9q/5P/b/+f/3X/q/97/7j/f//E/4X/z/+M/9v/kf/n/5j/8f+g//n/qv/8/7f/+f/E/+//zf/j/9L/1v/S/8n/z/+8/8v/sP/G/6T/wP+X/7z/i/+3/3//sv9y/63/Z/+m/1v/of9P/5v/Q/+V/zj/j/8r/4n/IP+D/xT/ff8I/3f//P5x//D+a//l/mT/2v5e/87+WP/D/lH/t/5K/63+Qv+j/jn/nP4u/w==",
+ "10.eLb": "sv7R/7j+w//F/r3/1P68/+P+vf/y/r7/Af+//xD/wP8f/8L/Lv/E/zz/xv9L/8n/Wv/M/2n/zf94/9D/hv/U/5X/2P+j/9z/sv/f/8D/5f/N/+3/1v/4/9r/BgDU/xQAyf8dALv/IwCt/ycAn/8sAJD/MACC/zYAdP87AGb/QABY/0YAS/9MAD3/UgAv/1cAIf9eABT/ZAAH/2wA+f5yAOr+dADc/nAA1P5kANf+VgDg/kkA6/4/APf+NgAD/y0AD/8lAB3/HgAq/xgAOP8SAEb/DQBJ/wMAO//+/yz//f8d//v/Dv/4///+9f/x/vH/4v7t/9P+6//G/uX/uf7e/w==",
+ "10.eRa": "bQCZ/20AjP9wAID/dgB1/30Aa/+FAGH/jQBY/5UATv+dAET/pQA7/64AMv+2ACj/vgAf/8YAFf/OAAz/1gAC/94A+P7mAO/+7gDl/vcA3P7/ANL+BwHJ/g8Bv/4YAbb+IAGt/ikBpP4yAZv+OgGS/kUBi/5QAYf+XQGH/mgBjP5wAZb+dAGi/nIBrv5sAbn+ZgHE/l4Bzv5XAdj+TgHh/kYB6/4+AfX+NgH+/i4BCP8mARL/HwEb/xYBJP8NAS3/BQE3//wAQP/0AEn/6wBS/+MAW//aAGT/0QBt/8gAdf+/AH7/tgCH/60Aj/+kAJj/mQCf/44ApP+CAKX/dQCi/w==",
+ "10.eRb": "nQDR/58Aw/+mALb/sACs/7sAo//HAJr/0wCR/94AiP/qAH//9QB3/wEBb/8NAWf/GQFf/yYBWP8zAVH/PwFK/0wBQ/9ZATz/ZgE2/3MBMP+BATP/iwE9/4oBS/+CAVf/eAFh/2wBav9hAXP/VQF7/0kBg/89AYz/MQGU/yYBnv8qAaX/OQGl/0cBpf9WAaX/ZAGl/3MBpv+BAaj/jwGs/50Br/+qAbb/swHB/7YBz/+wAdv/pAHk/5YB5/+HAeb/eQHl/2sB5f9cAeT/TgHk/z8B5P8wAeT/IgHk/xMB5P8FAeT/9gDl/+gA5v/aAOf/ywDo/70A6f+uAOb/owDe/w==",
+ "10.m": "FP9BARb/KAEe/xEBK//8ADr/6ABK/9UAW//DAG3/sgCB/6MAlP+TAKn/hgC//3kA1P9tAOr/YgAAAFcAFwBOAC8ARwBHAEEAYAA9AHgANwCQADIAqQAuAMEALQDaACwA8wAtAAwBLgAkATMAPAE6AFMBRABoAVAAewFhAIsBdACWAYoAnAGiAJwBugCVAdIAiQHnAHYB9wBfAQEBRgEEAS0BBQEVAQMB/AABAeMA/gDLAP0AsgD9AJkA/gCBAAMBaQALAVIAEwE7AB4BJQAoAQ8AMwH4/z4B4/9KAcz/VQG2/2ABoP9rAYj/cgFw/3cBV/96AT//dgEo/2wBGf9ZAQ==",
+ "11.eL": "3vuj/977lv/f+4n/4Pt8/+L7cP/m+2T/6vtY//T7T/8A/E3/CfxW/w38Yv8O/G//Dvx8/w78iP8O/JX/D/yi/xD8r/8T/Lv/FvzI/xz80/8n/Nf/MvzQ/zn8xf8//Lr/RPyu/0j8ov9N/Jb/UPyK/1T8ff9X/HH/Xfxm/2j8X/90/F3/gPxj/4j8bf+K/Hn/ifyG/4j8k/+G/KD/hPys/4D8uP99/MX/ePzR/3P83f9u/Oj/Z/zz/2D8/v9Y/AgAT/wQAET8FwA4/B0ALPwfAB/8HwAS/BwAB/wWAPz7DwD0+wUA7fv6/+j77//l++L/4vvW/+D7yf/e+7z/3vuw/w==",
+ "11.eR": "v/yb/7/8iv/A/Hr/xfxq/9D8Xv/g/Fv/7vxj//b8cf/4/IH/+vyS//78ov8D/bL/CP3B/xH9z/8b/d3/J/3n/zb97/9G/fP/Vv3y/2b97P90/eT/gP3Z/4r9y/+S/b3/mP2u/579n/+k/Y//qP1//7H9cv+//Wj/z/1m/9/9av/p/Xb/7v2G/+79lv/r/af/5/22/+L9xv/b/dX/1P3k/8z98v/C/QAAuP0MAKz9GACf/SMAkf0rAIP9NABz/TkAY/08AFP9PQBC/T0AMv07ACL9NwAT/TAABP0pAPf8IADq/BQA4PwHANf8+v/Q/Ov/yfzc/8X8zP/B/Lz/v/yr/w==",
+ "11.m": "9vujAPr7kAAL/IoAGvyXACX8pwAx/LcAPPzHAEn81QBY/OMAaPzuAHn8+ACL/AABnfwGAbH8CgHE/A0B2PwOAev8DQH+/AgBEv0EAST9/QA2/fQARv3qAFb93gBk/dEAcv3CAH79swCJ/aMAlv2UAKb9iQC5/YkAyf2UANL9pQDQ/bkAyf3LAL/92wC0/ewAp/37AJn9CQGL/RYBfP0jAWv9LgFb/TgBSf1BATf9SAEk/U4BEf1TAf78VgHq/FcB1vxXAcP8VgGv/FMBnPxPAYn8SQF3/EMBZfw6AVT8MAFE/CYBNfwZASb8DAEZ/P0AD/zsAAb82wD9+8kA9/u2AA==",
+ "12.eL": "1P6p/9T+ov/V/pz/1/6W/9n+j//b/on/3v6D/+H+fv/k/nj/6f5z/+7+b//y/mr/+P5n//7+ZP8E/2L/Cv9g/xH/Xv8X/17/Hv9f/yT/Yf8q/2P/MP9l/zb/af87/23/P/9x/0P/d/9G/3z/Sv+C/0z/iP9N/4//Tv+V/0//nP9Q/6L/T/+p/07/r/9M/7X/S/+8/0n/wv9G/8j/RP/O/0D/1P88/9n/OP/d/zP/4v8u/+b/KP/o/yL/6/8b/+z/Ff/t/w7/7P8I/+z/Af/q//v+6P/1/uX/8P7h/+v+3f/m/tn/4/7T/9/+zv/b/sj/2f7C/9f+vP/V/rb/1P6v/w==",
+ "12.eR": "UQCh/1EAmv9SAJP/UwCM/1UAhv9YAID/WwB6/18AdP9kAG//aQBq/24AZv9zAGH/eQBe/4AAXP+GAFn/jQBX/5MAV/+aAFf/oQBY/6gAWv+uAFz/tABf/7oAY//AAGb/xQBr/8kAcf/OAHb/0QB8/9MAgv/VAIn/1wCP/9gAlv/ZAJ3/2QCk/9gAq//WALH/1AC4/9IAvv/PAMT/ygDK/8YAz//BANT/vADY/7YA3P+wAOD/qgDj/6QA5f+dAOb/lgDm/48A5v+IAOX/gQDk/3sA4v91AN//bwDb/2oA1/9lANL/YQDN/1wAx/9YAML/VQC8/1MAtf9SAK//UQCo/w==",
+ "12.m": "wf4RAcT++gDN/uUA2/7SAO7+xQAE/8AAG//FAC7/0QA//+IAUP/xAGb/9QB6/+kAif/XAJj/xgCs/7gAwv+yANn/sgDu/7sAAQDIABEA2QAlAOIANwDUAEgAxABaALYAbwCsAIYAqACcAK8ArwC8ALwAzwDNAN4A4wDiAPcA7QACAQEB/AAWAeYAFgHQAA4BugAJAaYA/ACZAOkAiQDYAHQA2wBiAOoAUgD7AEAACQEpAA8BEwALAf///gDv/+4A3P/gAMf/2QCy/+MAov/0AJP/BQF//xIBaf8XAVL/FQE9/wsBK//7ABz/6gAH/+AA8f7mAOL+9wDZ/gwBz/4gAQ==",
+ "12.cL": "M/7x/zb+7f86/u3/Pv7v/0H+8/9C/vj/Rf78/0f+AABK/gQATP4IAE/+DABR/hAAVP4UAFf+FwBa/hsAXf4fAGD+IgBj/iYAZv4qAGr+LQBt/jAAcf4zAHX+NgB4/jkAfP48AID+PwCE/kIAiP5FAIz+RwCQ/kkAkv5OAJL+UgCP/lYAi/5XAIb+WACB/lcAff5WAHj+VQB0/lMAcP5RAGz+TgBn/kwAZP5JAGD+RgBc/kMAWP5AAFX+PQBS/jkAT/42AEv+MgBI/i8ARf4rAEP+JwBB/iIAP/4eADz+GgA6/hYAOf4RADf+DQA2/ggANP4EADT+//8z/vr/M/72/w==",
+ "12.cR": "/wBhAAIBXgAGAVwACQFZAA0BVgAQAVMAEwFQABYBTQAaAUoAHQFHACEBRAAkAUEAKAE+ACsBOwAuATgAMQE1ADQBMQA3AS4AOgEqAD0BJwBAASMAQgEgAEQBHABHARgASQEVAEwBEQBPAQ4AUwEMAFcBCwBbAQ0AXgEQAF8BFQBfARkAXQEdAFsBIQBaASYAWAEqAFYBLgBUATIAUgE2AFABOgBNAT0ASgFBAEcBRABEAUcAQQFLAD4BTgA7AVEANwFUADQBVwAwAVkALQFcACkBXwAlAWEAIQFjAB0BZQAZAWcAFQFoABEBagANAWwACAFsAAQBawAAAWkA/gBlAA==",
+ "12.sw": "YgHp/mMB3/5jAdX+YwHM/mQBwv5kAbj+ZQGv/mcBpf5pAZv+bwGV/nUBnf55Aab+egGv/nsBuf57AcP+ewHN/nwB1v59AeD+fgHq/oAB8/6BAf3+ggEG/4MBEP+GARn/igEi/5IBJ/+cASb/owEf/6cBF/+qAQ3/qQEE/6gB+v6mAfH+owHn/qIB3f6iAdT+qAHN/rAB0v61Adv+ugHj/r4B7P7BAfX+wgH//sMBCP/DARL/wgEc/8ABJf+8AS7/twE2/7ABPf+oAUP/nwFF/5UBRf+LAUT/ggFA/3sBOv90ATP/bwEr/2sBIv9oARn/ZAEQ/2MBBv9jAfz+YwHz/g==",
+ "20.eL": "uv4qAL7+HQDI/hUA1f4VAOH+GwDs/iIA9/4pAAH/MgAM/zgAGP89ACT/QQAx/0QAPv9GAEv/RgBY/0UAZf9CAHH/PgB9/zkAif8zAJP/KgCd/yIApP8XAKv/DACx/wAAtf/0/7j/5/+7/9r/wv/P/8z/x//Z/8f/4//O/+j/2v/p/+f/6f/0/+f/AQDj/w4A3/8aANn/JgDS/zEAzP89AMT/RwC7/1AAsP9YAKX/YACa/2cAj/9sAIP/cgB2/3YAaf94AFz/ewBP/3wAQv98ADX/ewAo/3kAHP92AA//cwAC/28A9v5pAOv+ZADg/l0A1f5VAMv+TADD/kIAvv42AA==",
+ "20.eR": "OgDC/zwAtv9EAKz/UACr/1oAsf9kALn/bgDA/3gAyP+CAM//jADV/5gA2P+kANz/sQDd/70A3f/JAN3/1gDb/+EA1//tANT/+ADO/wIBxv8LAb7/EwG1/xoBqv8fAZ//JAGU/ycBiP8rAXz/MQFx/zsBav9HAWj/UQFu/1cBeP9ZAYX/WQGR/1cBnf9UAan/TwG1/0oBwP9EAcr/PQHU/zQB3f8sAef/IgHv/xkB9/8PAf3/BAEEAPgACADtAAwA4AAOANQAEADIABEAuwAQAK8ADwCjAA4AlwALAIsABwB/AAMAdAD+/2kA+P9fAPH/VQDp/0wA4f9EANj/PgDN/w==",
+ "21.eL": "ZP9Y/2T/UP9k/0f/Zf8//2f/N/9p/zD/a/8o/23/IP9x/xn/dP8R/3f/Cv97/wL/gP/8/ob/9v6M//D+kf/r/pf/5f6e/+H+pf/d/q3/2/61/9r+vf/a/sX/3P7N/9/+1P/j/tr/6P7g/+7+5P/1/uf//f7q/wT/7P8M/+3/FP/u/xz/7v8k/+3/LP/s/zX/7P89/+r/Rf/o/03/5f9U/+P/XP/g/2T/3P9r/9n/cv/U/3j/z/9//8n/hf/D/4r/vf+Q/7b/lP+u/5X/pv+X/57/mP+W/5j/jv+W/4b/lP9//5D/eP+L/3P/hf9u/37/a/93/2f/cP9l/2j/ZP9g/w==",
+ "21.eR": "6wCo/+sAoP/rAJf/7ACP/+0Ah//vAH//8gB4//QAcP/3AGn/+wBh/wABW/8EAVT/CQFO/w8BSP8WAUP/HAE//yQBO/8rATj/MwE2/zsBNv9DATf/SwE6/1IBPf9ZAUL/YAFG/2UBTP9qAVP/bgFa/3EBYv9zAWn/dAFx/3UBef92AYL/dwGK/3YBkv91AZr/dAGi/3MBqv9xAbL/bQG5/2sBwf9nAcj/ZAHP/18B1v9aAdz/VAHi/04B5/9HAev/PwHu/zgB8f8wAfL/KAHy/yAB8f8YAe7/EQHr/woB5/8DAeL//QDc//gA1v/0AM//8QDH/+4AwP/sALj/6wCw/w==",
+ "21.m": "1v9gANb/WADY/1AA2/9IAN3/QQDh/zoA5P8zAOn/LADu/yYA8/8gAPj/GgD//xUABgASAA0ADgAUAAoAHAAHACMABgArAAUAMwAGADsACABCAAsASgAOAFEAEgBXABYAXQAcAGEAIwBlACoAaQAxAGwAOABtAEAAbwBIAHAAUABvAFgAbgBgAGwAZwBrAG8AaQB3AGUAfgBiAIUAXgCMAFkAkwBUAJkATgCeAEgAowBBAKcAOgCqADIArQArAK8AIwCxABsAsQATALAACwCuAAQArAD8/6kA9v+lAO//oADp/5sA5f+UAOD/jgDc/4cA2v9/ANf/eADW/3AA1v9oAA==",
+ ]
+}
diff --git a/app/ChumsWatch/Rig/WorldPage.swift b/app/ChumsWatch/Rig/WorldPage.swift
new file mode 100644
index 0000000..597ac8c
--- /dev/null
+++ b/app/ChumsWatch/Rig/WorldPage.swift
@@ -0,0 +1,218 @@
+import SwiftUI
+
+/// Eyes' world: a page of code in the dark. The eyes read it word by word — 160–260 ms fixations, 35 ms jumps,
+/// a 90 ms sweep back at each line end. Tool calls happen on the page: an edit rewrites a word in clay,
+/// a command adds a › line and its output, a test adds a ✓ line (or a red one if it failed).
+final class PageWorld: WorldImpl {
+ static let X = 30.0, WIDTH = 138.0, Y = 110.0, LH = 9.0, ROWS = 8
+ private let HELP: [(Double, Double)] = [(44, 132), (154, 132), (99, 166)]
+
+ enum LineKind { case code, cmd, out, pass, fail }
+ struct Line { var kind: LineKind; var ind: Double; var words: [Double]; var born = 99.0; var edit = -1 }
+ struct Event { var kind: ToolCall.Kind; var t = 0.0; var row: Int; var j = -1 }
+
+ var lines: [Line] = []
+ var indent = 0
+ var row = 1, word = 0, fixT = 0.3
+ var top = 0.0, topS = 0.0
+ var gx = 0.0, gy = 0.6
+ private var from = (0.0, 0.6), to = (0.0, 0.6), sT = 1.0, sDur = 0.04
+ var ev: Event?
+ var linesRead = 0
+ var alpha = 0.0, happyT = 0.0, doneT = -1.0
+ var bad = -1
+ var helpK = [0.0, 0.0, 0.0]
+ var subT = 0.0
+
+ func reset() {
+ lines = []; indent = 0; row = 1; word = 0; fixT = 0.3; top = 0; topS = 0; gx = 0; gy = 0.6
+ from = (0, 0.6); to = (0, 0.6); sT = 1; sDur = 0.04; ev = nil; linesRead = 0; alpha = 0; happyT = 0; doneT = -1; bad = -1; helpK = [0, 0, 0]
+ for _ in 0..<40 { lines.append(makeLine(.code)) }
+ }
+
+ private func makeLine(_ kind: LineKind) -> Line {
+ if kind == .code {
+ let r = Double.random(in: 0..<1)
+ indent = min(3, max(0, indent + (r < 0.3 ? 1 : r < 0.58 ? -1 : 0)))
+ }
+ let ind = kind == .code ? Double(indent) * 8 : 0, maxW = PageWorld.WIDTH - ind - 12
+ let n = kind == .pass || kind == .fail ? 1 : kind == .out ? Int.random(in: 1...3) : Int.random(in: 2...5)
+ var words: [Double] = [], used = 0.0
+ for _ in 0..<n {
+ let w = (kind == .pass || kind == .fail) ? 42 : rnd(6, 26)
+ if used + w > maxW { break }
+ words.append(w); used += w + 4
+ }
+ if words.isEmpty { words = [12] }
+ return Line(kind: kind, ind: ind, words: words)
+ }
+
+ private func wordPos(_ r: Int, _ j: Int) -> (x: Double, y: Double) {
+ let L = lines[r]
+ var x = PageWorld.X + L.ind + (L.kind == .cmd || L.kind == .pass || L.kind == .fail ? 10 : 0)
+ for i in 0..<min(j, L.words.count) { x += L.words[i] + 4 }
+ return (x + L.words[min(j, L.words.count - 1)] / 2, PageWorld.Y + (Double(r) - topS) * PageWorld.LH)
+ }
+ private func lookAtWord(_ r: Int, _ j: Int, _ dur: Double) {
+ let q = wordPos(r, j)
+ from = (gx, gy); to = (clamp((q.x - 99) / 62, -1, 1), clamp(0.4 + (Double(r) - top) / Double(PageWorld.ROWS) * 0.6, 0, 1)); sT = 0; sDur = dur
+ }
+
+ private func startEvent(_ rig: Rig) {
+ guard let e = rig.worlds.nextEvent(rig) else { return }
+ ev = Event(kind: e.kind, row: row); rig.worlds.announce(rig, e.text)
+ switch e.kind {
+ case .edit:
+ let j = min(1, lines[row].words.count - 1)
+ lines[row].edit = j; word = j; ev?.j = j; fixT = 1.3
+ case .bash, .test, .agent:
+ var add = [makeLine(.cmd), makeLine(.out), makeLine(.out)]
+ if e.kind == .test { add.append(makeLine(rig.worlds.results[e.id] == false ? .fail : .pass)) } else { add.append(makeLine(.out)) }
+ for i in add.indices { add[i].born = -(0.2 + Double(i) * 0.1) }
+ lines.insert(contentsOf: add, at: row); word = 0; fixT = 0.4
+ default: break
+ }
+ }
+
+ func onState(_ r: Rig, _ s: ChumsState, _ v: Bool) {
+ if s == .subagents { r.W.subCalls = 0 }
+ bad = s == .blocked ? row : -1
+ doneT = s == .done ? 0 : -1
+ if s == .working { fixT = 0.25 }
+ }
+
+ func step(_ r: Rig, _ dt: Double) {
+ let targets: [ChumsState: Double] = [.working: 1, .done: 1, .blocked: 0.9, .idle: 0.45, .thinking: 0.3, .subagents: 0.16, .approval: 0.2]
+ alpha += ((targets[r.state] ?? 0) - alpha) * min(1, dt * 4)
+ topS += (top - topS) * min(1, dt * 6)
+ sT += dt
+ let e = minJerk(clamp(sT / sDur, 0, 1)); gx = lerp(from.0, to.0, e); gy = lerp(from.1, to.1, e)
+ happyT = max(0, happyT - dt); if doneT >= 0 { doneT += dt }
+ for i in lines.indices { lines[i].born += dt }
+ if ev != nil { ev!.t += dt }
+ for i in 0..<3 { helpK[i] = clamp(helpK[i] + dt * 3 * (r.state == .subagents && r.stateT > 0.3 + Double(i) * 0.3 ? 1 : -1), 0, 1) }
+ if r.state == .subagents && helpK[0] >= 1 {
+ subT -= dt
+ if subT <= 0 { subT = rnd(0.5, 1); r.W.subCalls += 1; r.worlds.announce(r, "3 subagents: \(r.W.subCalls) tool calls") }
+ }
+ if r.W.launch?.world == true || r.state != .working { return }
+ fixT -= dt
+ if fixT > 0 { return }
+ word += 1
+ if word >= lines[row].words.count {
+ row += 1; word = 0; linesRead += 1
+ while lines.count < row + 14 { lines.append(makeLine(.code)) }
+ if lines.count > 120 { let cut = lines.count - 120; lines.removeFirst(cut); row -= cut; top -= Double(cut); topS -= Double(cut); if bad >= 0 { bad -= cut } }
+ if Double(row) - top > 3 { top = Double(row) - 3 }
+ if lines[row].kind == .pass { happyT = 0.8; r.onHaptic?(.click) }
+ fixT = 0.3
+ if linesRead % 2 == 0 && (ev == nil || ev!.t > 1.4) { startEvent(r) }
+ lookAtWord(row, word, 0.09) // the sweep back to the next line
+ } else { lookAtWord(row, word, 0.035); fixT = rnd(0.16, 0.26) }
+ }
+
+ func pose(_ r: Rig, _ p: Pose) -> WorldPose {
+ let par = sin(r.worlds.watchRot(r)) * 2, dyc = (r.clip?.frame().dy ?? 0) * 0.6
+ var w = WorldPose(cx: 99 + par, cy: (r.state == .subagents ? 58 : 66) - dyc, scale: r.state == .subagents ? 0.6 : 0.72)
+ w.o.tilt = 0
+ if let L = r.W.launch, L.world {
+ w.o.open = L.t < 0.4 ? 0 : L.t < 0.55 ? (L.t - 0.4) / 0.15 : (L.t > 0.9 && L.t < 1.02 ? 0 : 1)
+ w.o.gx = 0; w.o.gy = L.t > 1.1 ? 0.6 : 0
+ return w
+ }
+ switch r.state {
+ case .working:
+ w.o.gx = gx; w.o.gy = gy; w.o.intent = (ev?.kind == .edit && ev!.t < 1.3) ? 0.8 : 0.3
+ if happyT > 0 { w.o.happy = 1 }
+ case .thinking:
+ w.o.gx = 0.5 + 0.18 * sin(p.t * 0.8); w.o.gy = -0.35 + 0.08 * sin(p.t * 1.3); w.o.sleepy = 0.3
+ case .subagents:
+ let hx = [-1.0, 0, 1, 0][Int(r.stateT / 1.3) % 4]; w.o.gx = hx * 0.75; w.o.gy = hx == 0 ? 1 : 0.75
+ case .blocked:
+ let q = bad >= 0 && bad < lines.count ? wordPos(bad, 0) : (x: 99.0, y: 0.0)
+ w.o.gx = clamp((q.x + 30 - 99) / 62, -1, 1); w.o.gy = 0.75
+ case .approval:
+ w.o.gx = 0; w.o.gy = Int(r.stateT / 1.4) % 2 == 1 ? 0 : 1
+ default: break
+ }
+ return w
+ }
+
+ func back(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose) {
+ let launchT = r.W.launch?.world == true ? r.W.launch!.t : nil
+ let px = -sin(r.worlds.watchRot(r)) * 6, off = r.W.scrub / 34
+ let r0 = Int((topS + off).rounded(.down)) - 1
+ for rr in max(0, r0)..<min(lines.count, r0 + PageWorld.ROWS + 3) {
+ let L = lines[rr]
+ guard L.born >= 0 else { continue }
+ let y = PageWorld.Y + (Double(rr) - topS - off) * PageWorld.LH
+ let edge = clamp(min(y - (PageWorld.Y - 12), PageWorld.Y + Double(PageWorld.ROWS) * PageWorld.LH - y) / 12, 0, 1)
+ guard edge > 0 else { continue }
+ var a = alpha * edge * clamp(L.born / 0.12, 0, 1)
+ if let lt = launchT { a = edge * clamp((lt - 0.6 - Double(rr - r0) * 0.06) / 0.15, 0, 1) * 0.8 }
+ guard a > 0.01 else { continue }
+ let c = ctx.faded(a)
+ let cur = rr == row && r.state == .working, read = rr < row
+ var flash = 0.0
+ if doneT >= 0 { let d = doneT * 12 - Double(rr - r0); flash = d > 0 && d < 2 ? 1 - abs(d - 1) : 0 }
+ var x = PageWorld.X + L.ind + px
+ if cur { c.fillRect(PageWorld.X - 9 + px, y - 3, 1.6, 6, Pal.gray) }
+ if L.kind == .cmd {
+ var ch = Path(); ch.move(to: CGPoint(x: x + 1, y: y - 2.5)); ch.addLine(to: CGPoint(x: x + 4, y: y)); ch.addLine(to: CGPoint(x: x + 1, y: y + 2.5))
+ c.stroke(ch, with: .color(Color(hex: 0xA9AEB4)), style: StrokeStyle(lineWidth: 1.3, lineCap: .round, lineJoin: .round)); x += 10
+ }
+ if L.kind == .pass || L.kind == .fail {
+ if L.kind == .pass {
+ var ck = Path(); ck.move(to: CGPoint(x: x, y: y)); ck.addLine(to: CGPoint(x: x + 2, y: y + 2)); ck.addLine(to: CGPoint(x: x + 6, y: y - 2.5))
+ c.stroke(ck, with: .color(Pal.green), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))
+ } else { c.strokeLine(x, y - 2.5, x + 5, y + 2.5, Pal.red, 1.5); c.strokeLine(x + 5, y - 2.5, x, y + 2.5, Pal.red, 1.5) }
+ x += 10
+ }
+ let et = (ev?.kind == .edit && ev?.row == rr) ? ev!.t : 9
+ for (j, w0) in L.words.enumerated() {
+ var ww = w0
+ var col: Color = read ? Color(hex: 0x43464B) : Color(hex: 0x303337)
+ if cur { col = j < word ? Color(hex: 0x7A7F85) : j == word ? Color(hex: 0xEDEFF1) : Pal.dim }
+ switch L.kind { case .cmd: col = Color(hex: 0xA9AEB4); case .out: col = Color(hex: 0x3A3D41); case .pass: col = Pal.green; case .fail: col = Pal.red; case .code: break }
+ if L.edit == j {
+ if et < 0.22 { ww = w0 * (1 - et / 0.22) }
+ else if et < 1.3 { ww = w0 * min(1, (et - 0.22) / 0.6); col = Pal.clay }
+ else { col = Color(hex: 0x7B4A3A) }
+ }
+ if rr == bad { col = Pal.red }
+ if flash > 0.3 && L.kind != .pass { col = Pal.gray }
+ if ww > 0.5 { c.fillRoundRect(x, y - 1.6, ww, 3.2, 1.6, col) }
+ if L.edit == j && et >= 0.22 && et < 1.3 && Int(r.t * 4) % 2 == 0 { c.fillRect(x + ww + 1.2, y - 3.6, 1.4, 7.2, Pal.white) }
+ x += w0 + 4
+ }
+ if rr == bad {
+ var sq = Path(), sx = PageWorld.X + L.ind + px
+ for k in 0...40 { let pt = CGPoint(x: sx, y: y + 4.2 + (k % 2 == 1 ? 1.2 : -0.2)); if k == 0 { sq.move(to: pt) } else { sq.addLine(to: pt) }; sx += 2.2 }
+ c.stroke(sq, with: .color(Pal.red), lineWidth: 1)
+ }
+ }
+ // subagents: three more pairs of eyes open in the dark, each reading a few lines of its own
+ for (i, (hx, hy)) in HELP.enumerated() where helpK[i] > 0.02 {
+ let k = helpK[i]
+ let sw = (r.t * 0.8 + Double(i) * 0.37).truncatingRemainder(dividingBy: 1)
+ let hgx = sw < 0.85 ? lerp(-0.8, 0.8, (sw / 0.85 * 5).rounded(.down) / 4) : 0.8 - 1.6 * (sw - 0.85) / 0.15
+ let bl = (r.t * 0.5 + Double(i) * 0.31).truncatingRemainder(dividingBy: 3.1) < 0.09 ? 0.05 : 1
+ let lc = ctx.faded(min(1, k * 2))
+ for l in 0..<3 { lc.fillRoundRect(hx - 16, hy + 15 + Double(l) * 5, [30.0, 21, 26][l] * k, 2, 1, Color(hex: 0x303337)) }
+ var m = p
+ m.cx = hx + px * 0.5; m.cy = hy; m.scale = 0.3; m.sy = 1; m.tilt = 0; m.amber = 0; m.pulse = 0; m.tint = Pal.gray
+ m.eye = .neutral(gx: hgx, gy: 0.8); m.eye.open = min(1, k * 1.3) * bl
+ Characters.drawEyes(r, ctx, m)
+ }
+ }
+
+ func front(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose) {
+ guard r.state == .blocked else { return }
+ ctx.fill(Characters.dropPath(x: p.cx + 34, y: p.cy - 14, s: 0.8), with: .color(Pal.sweat))
+ }
+
+ func scrubLabel(_ r: Rig) -> String? {
+ let n = Int((-r.W.scrub / 34).rounded()), h = r.W.history
+ return h.count > n ? h[h.count - 1 - n] : nil
+ }
+}
diff --git a/app/ChumsWatch/Rig/Worlds.swift b/app/ChumsWatch/Rig/Worlds.swift
new file mode 100644
index 0000000..77c00ee
--- /dev/null
+++ b/app/ChumsWatch/Rig/Worlds.swift
@@ -0,0 +1,454 @@
+import SwiftUI
+
+/// Camera, physics, launch, crown scrub and the per-character worlds.
+struct WorldState {
+ var padX = 0.0, padY = 1.0 // gravity across the screen (x right, y down); length 0 flat … 1 hanging
+ /// rot: the body's angle (it spins free while thrown, then rights itself against gravity)
+ struct Body { var x = 99.0, y = 118.0, vx = 0.0, vy = 0.0, sq = 0.0, sqv = 0.0, rot = 0.0, rotV = 0.0, surprised = 0.0 }
+ var body = Body()
+ /// The Physics stage, shaken hard: the body flies, spinning, until it comes to rest, then sits dazed with stars
+ /// circling and shakes it off where it lies.
+ struct Loose {
+ enum Phase { case fly, daze }
+ var phase = Phase.fly
+ var t = 0.0, still = 0.0, sinceKick = 0.0
+ }
+ var loose: Loose?
+ /// Shaken in Portrait or the level: the character stays where it is (the game doesn't move) and is jolted in
+ /// place. While you shake, the scene judders and it hops and flails, eyes squeezed shut; when you stop, it sits
+ /// dazed with spinning eyes and stars circling its head, then shakes it off. Everything moves on its pixel grid.
+ struct Jolt {
+ var t = 0.0, sinceKick = 0.0
+ var h = 0.0, vh = 0.0 // the hop, in the character's own pixels
+ var quake = 0.0 // how hard the scene judders, 0…1
+ var peak = 0.0 // the hardest the shake got (Rig.trauma)
+ var daze: Double { 1.4 + 1.2 * peak } // a hard shake leaves it dazed longer
+ static let rattle = 0.45, off = 0.5 // after the last shake: rattle, then sit dazed, then shake it off
+ }
+ var jolt: Jolt?
+ var drag: CGPoint?
+ var hardHits: [Double] = []
+ struct Tick { var x: Double, y: Double, age: Double, strong: Bool }
+ var ticks: [Tick] = []
+ struct Dust { var x: Double, y: Double, vx: Double, vy: Double, age: Double }
+ var dust: [Dust] = []
+ var pokes: [Double] = []
+ struct Launch { var t = 0.0, y = -60.0, vy = 0.0, world = false }
+ var launch: Launch?
+ var zoom = 0.0, zoomV = 0.0
+ var wp = WorldPose(cx: 99, cy: 112, scale: 1)
+ var subCalls = 0
+ var history: [String] = []
+ var label = "", labelT = 0.0
+ var busy = false
+ var scrub = 0.0, scrubTarget = 0.0, scrubIdle = 99.0, crownAcc = 0.0
+ var petDist = 0.0, annoyedT = 0.0
+}
+
+protocol WorldImpl: AnyObject {
+ func reset()
+ func onState(_ r: Rig, _ s: ChumsState, _ v: Bool)
+ func step(_ r: Rig, _ dt: Double)
+ func pose(_ r: Rig, _ p: Pose) -> WorldPose
+ func back(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose)
+ func front(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose)
+ func scrubLabel(_ r: Rig) -> String?
+}
+
+/// The camera is wide in these states and close in the rest (listening, speaking, needs you). Shaken (dizzy), it
+/// stays where it is: in the level, the jolt plays in the level.
+let WIDE: Set<ChumsState> = [.idle, .thinking, .working, .subagents, .approval, .blocked, .done, .sleep, .dizzy]
+
+/// Tool calls used when there's no hub to watch (demo mode and previews).
+private let DEMO_CALLS: [(ToolCall.Kind, String)] = [
+ (.read, "Read hub.mjs"), (.read, "Read chums-channel.mjs"), (.edit, "Edit hub.mjs"), (.bash, "Bash npm run build"),
+ (.edit, "Edit Voice.swift"), (.test, "Bash npm test"), (.read, "Read project.yml"), (.edit, "Edit HubClient.swift"),
+ (.bash, "Bash git diff"), (.test, "Bash swift test"),
+]
+
+final class Worlds {
+ var queue: [ToolCall] = []
+ var results: [String: Bool] = [:]
+ var demo = false
+ private var demoIdx = 0, demoT = 0.0
+ let page = PageWorld()
+
+ func current(_ r: Rig) -> WorldImpl {
+ return page // staged characters have no world
+ }
+ func reset(_ r: Rig) {
+ page.reset(); _ = r
+ }
+ /// Worlds only hold a state (the flag rising, the gate opening) while they are on screen.
+ func onState(_ r: Rig, _ s: ChumsState, _ v: Bool) { r.W.busy = false; if r.mode == .world && !r.character.staged { current(r).onState(r, s, v) } }
+
+ func worldOn(_ r: Rig) -> Bool { r.mode == .world && !r.character.staged && r.W.zoom > 0.04 }
+ func physicsOn(_ r: Rig) -> Bool { r.mode == .physics && !r.character.staged && r.state != .listening && r.state != .approval && r.W.launch == nil }
+ /// The body is simulated: the Physics stage (thrown or not).
+ func bodyOn(_ r: Rig) -> Bool { physicsOn(r) || r.W.loose != nil }
+
+ // MARK: shaken (Physics: thrown; Portrait and the level: jolted in place)
+
+ /// The Physics stage, shaken hard: the body is thrown, `dx, dy` the way it flies, `g` how hard the watch moved.
+ func kick(_ r: Rig, _ dx: Double, _ dy: Double, _ g: Double) {
+ guard !r.character.staged else { return }
+ if r.W.loose == nil { r.W.loose = WorldState.Loose() }
+ let v = clamp((g - 1.1) * 560, 300, 1300)
+ r.W.body.vx += dx * v; r.W.body.vy += dy * v
+ r.W.body.rotV += (dx >= 0 ? 1 : -1) * rnd(5, 11) // it tumbles the way it's thrown
+ r.W.body.surprised = 0.6
+ r.W.loose?.phase = .fly; r.W.loose?.sinceKick = 0; r.W.loose?.still = 0
+ }
+
+ /// The Physics stage, shaken gently: a shove without the daze.
+ func kickBody(_ r: Rig, _ dx: Double, _ dy: Double, _ g: Double) {
+ let v = clamp((g - 1.1) * 520, 200, 1000)
+ r.W.body.vx += dx * v; r.W.body.vy += dy * v; r.W.body.surprised = 0.5
+ }
+
+ /// Portrait or the level, shaken: one more jolt (a hop if it's on its feet, the scene judders again).
+ func jolt(_ r: Rig, _ g: Double) {
+ guard !r.character.staged else { return }
+ var J = r.W.jolt ?? WorldState.Jolt()
+ J.peak = max(J.peak, r.trauma)
+ // half pixels a second: a light shake hops it 1½ pixels, a hard one throws it up 6
+ if J.h <= 0.01 { J.vh = 38 + 42 * r.trauma }
+ J.quake = 1; J.sinceKick = 0
+ r.W.jolt = J
+ }
+
+ /// Something else needs the character (you talk, an approval comes): the shake is over.
+ func calm(_ r: Rig) {
+ r.W.jolt = nil
+ r.W.loose = nil
+ }
+
+ private func stepShaken(_ r: Rig, _ dt: Double) {
+ if var L = r.W.loose {
+ L.t += dt; L.sinceKick += dt
+ let b = r.W.body
+ switch L.phase {
+ case .fly:
+ L.still = hypot(b.vx, b.vy) < 45 ? L.still + dt : 0
+ if L.still > 0.3 && L.sinceKick > 0.5 { L.phase = .daze; L.t = 0 }
+ case .daze:
+ // it lies there seeing stars, then shakes it off
+ if L.t > 1.5 && L.t - dt <= 1.5 { r.clip = .shakeOffHard() }
+ if L.t > 2.15 { r.W.loose = nil; if r.state == .dizzy { r.settle() }; return }
+ }
+ r.W.loose = L
+ }
+ if var J = r.W.jolt {
+ J.t += dt; J.sinceKick += dt
+ J.quake = max(0, J.quake - dt * 4)
+ if J.h > 0 || J.vh > 0 {
+ J.vh -= 240 * dt; J.h += J.vh * dt
+ if J.h <= 0 { J.h = 0; J.vh = 0 }
+ }
+ if J.sinceKick > WorldState.Jolt.rattle + J.daze + WorldState.Jolt.off && J.h <= 0 {
+ r.W.jolt = nil; if r.state == .dizzy { r.settle(); r.startBlink() }; return
+ }
+ r.W.jolt = J
+ }
+ }
+
+ /// The scene's judder while the jolt lasts, in whole pixels of the character's own grid.
+ func quake(_ r: Rig) -> CGPoint {
+ guard let J = r.W.jolt, J.quake > 0.05 else { return .zero }
+ let px = pixel(r), i = Int(r.t * 30)
+ let xs = [1.0, -1, 0, 1, -1, 1, 0, -1], ys = [0.0, 1, -1, 0, 1, -1, 1, 0]
+ // half a pixel for a light shake, one for a firm one, two for a hard one; half that as it fades
+ let k = (r.trauma < 0.25 ? 0.5 : r.trauma < 0.6 ? 1 : 2) * (J.quake > 0.5 ? 1.0 : 0.5)
+ return CGPoint(x: (xs[i % 8] * px * k).rounded(), y: (ys[(i * 3) % 8] * px * k).rounded())
+ }
+
+ /// One pixel of the character as drawn now: a gridded character's level grid or its own cell up close; the
+ /// others have none, so 4 pt.
+ private func pixel(_ r: Rig) -> Double {
+ return 4
+ }
+
+ /// The pose while shaken: thrown (Physics), or jolted where it stands.
+ private func shakenPose(_ r: Rig, _ p: inout Pose) {
+ let gridded = r.character.gridded
+ if let L = r.W.loose {
+ switch L.phase {
+ case .fly:
+ p.daze = 1
+ // arms and legs flail while it flies
+ p.arms = Int(r.t * 7) % 2 == 0 ? .raised : .rest
+ p.legs = Int(r.t * 9) % 2 == 0 ? .stepA : .stepB
+ case .daze:
+ p.daze = 2; p.stars = min(1, L.t * 4) * (L.t > 1.6 ? max(0, 1 - (L.t - 1.6) / 0.3) : 1)
+ p.legs = .crouch; p.arms = .rest
+ let wob = sin(L.t * TAU * 1.3) * 7 * DEG * max(0, 1 - L.t / 1.5) + (r.clip?.frame().tilt ?? 0)
+ if gridded { p.roll += wob } else { p.tilt += wob }
+ }
+ if !gridded && r.W.body.surprised > 0 { p.eye.wide = max(p.eye.wide, 1) }
+ }
+ guard let J = r.W.jolt else { return }
+ // a gridded character's own pixel as drawn now: every move is a whole pixel or half of one, like its eyes
+ let u = gridded ? lerp(8.4, 9.4, r.cute) * p.unitScale : 9 * p.scale, half = u / 2
+ let s = J.sinceKick, R = WorldState.Jolt.rattle, D = J.daze
+ p.cy -= (J.h.rounded() * half) // the hop, half a pixel at a time
+ if s < R || J.h > 0 {
+ // rattled: shaking side to side half a pixel, eyes squeezed shut, arms and legs scrambling
+ p.cx += (Int(r.t * 12) % 2 == 0 ? -half : half)
+ p.daze = 1
+ p.arms = Int(r.t * 8) % 2 == 0 ? .raised : .rest
+ p.legs = J.h > 0 ? .stand : (Int(r.t * 10) % 2 == 0 ? .stepA : .stepB)
+ if !gridded { p.eye.intent = 1; p.eye.wide = 0 }
+ } else if s < R + D {
+ // dazed: it sits down, sways half a pixel each way, eyes spinning, stars circling its head
+ let k = s - R
+ p.daze = 2; p.stars = min(1, k * 4)
+ if k < 1.0 { p.legs = .crouch; p.cy += u } // sitting: knees bent, its feet stay on the ground
+ p.arms = .rest
+ p.cx += [0, -half, 0, half][Int(k * 2.4) % 4]
+ p.eye.spiral = true
+ } else {
+ // shakes it off: a quick side to side, eyes shut, the stars gone
+ let k = s - R - D
+ p.cx += (Int(k * 16) % 2 == 0 ? -half : half) * (k < 0.35 ? 1 : 0)
+ p.stars = max(0, 1 - k / 0.15)
+ p.eye.closed = k < 0.3 ? 1 : 0; p.eye.spiral = false
+ p.legs = .stand; p.arms = .rest
+ }
+ }
+
+ /// The body's box (its arms and legs included) turned by its spin: how far it reaches from its center each way.
+ private func reach(_ r: Rig, _ rot: Double) -> (l: Double, r: Double, t: Double, b: Double) {
+ let e = extents(r), c = cos(rot), s = sin(rot)
+ var l = 0.0, rr = 0.0, t = 0.0, bb = 0.0
+ for (x, y) in [(-e.hx, -e.top), (e.hx, -e.top), (-e.hx, e.bottom), (e.hx, e.bottom)] {
+ let X = x * c - y * s, Y = x * s + y * c
+ l = min(l, X); rr = max(rr, X); t = min(t, Y); bb = max(bb, Y)
+ }
+ return (-l, rr, -t, bb)
+ }
+
+ /// The next tool call for the world to show: a real one from the hub, or in demo mode a made-up one.
+ func nextEvent(_ r: Rig) -> ToolCall? {
+ if !queue.isEmpty { return queue.removeFirst() }
+ guard demo else { return nil }
+ let d = DEMO_CALLS[demoIdx % DEMO_CALLS.count]; demoIdx += 1
+ let id = "demo-\(demoIdx)"
+ if d.0 == .test { results[id] = true }
+ return ToolCall(id: id, kind: d.0, text: d.1)
+ }
+ func announce(_ r: Rig, _ text: String) {
+ r.W.label = text; r.W.labelT = 0
+ r.W.history.append(text); if r.W.history.count > 80 { r.W.history.removeFirst() }
+ }
+
+ // MARK: gravity
+
+ func watchRot(_ r: Rig) -> Double { atan2(r.W.padX, r.W.padY) }
+ func gravMag(_ r: Rig) -> Double { min(1, hypot(r.W.padX, r.W.padY)) }
+
+ func extents(_ r: Rig) -> (hx: Double, top: Double, bottom: Double) {
+ let c = r.cute
+ switch r.character {
+ case .peeps: let s = 0.8; return ((lerp(25, 26, c) + lerp(11, 13, c)) * s, lerp(17, 19, c) * s, lerp(17, 19, c) * s)
+ case .stretch, .crunch, .nana, .squint, .ray, .tangle, .noodle: return (50, 60, 60)
+ }
+ }
+
+ private func stepPhysics(_ r: Rig, _ dt: Double) {
+ var b = r.W.body
+ let a = watchRot(r), m = gravMag(r) * 1200
+ let ax = sin(a) * m, ay = cos(a) * m
+ let flying = r.W.loose?.phase == .fly && r.W.drag == nil
+ if let d = r.W.drag {
+ b.vx += ((d.x - b.x) * 250 - b.vx * 24) * dt; b.vy += ((d.y - b.y) * 250 - b.vy * 24) * dt
+ } else { b.vx += ax * dt; b.vy += ay * dt }
+ let air = 1 - 0.6 * dt; b.vx *= air; b.vy *= air
+ b.x += b.vx * dt; b.y += b.vy * dt
+ // thrown, it bounces livelier and spins from the walls it scrapes along (a roll: speed along the wall over its size)
+ let e = reach(r, b.rot), bounce = flying ? 0.58 : 0.45, roll = 1 / 30.0
+ let lo = 8 + e.l, hi = 190 - e.r, top = 36 + e.t, bot = 234 - e.b
+ if b.x < lo { impact(r, &b, abs(b.vx), vertical: false, 8, b.y); b.x = lo; b.vx = abs(b.vx) * bounce; b.vy *= 0.7; if flying { b.rotV = lerp(b.rotV, b.vy * roll, 0.6) } }
+ if b.x > hi { impact(r, &b, abs(b.vx), vertical: false, 190, b.y); b.x = hi; b.vx = -abs(b.vx) * bounce; b.vy *= 0.7; if flying { b.rotV = lerp(b.rotV, -b.vy * roll, 0.6) } }
+ if b.y < top { impact(r, &b, abs(b.vy), vertical: true, b.x, 36); b.y = top; b.vy = abs(b.vy) * bounce; b.vx *= 0.7; if flying { b.rotV = lerp(b.rotV, -b.vx * roll, 0.6) } }
+ if b.y > bot { impact(r, &b, abs(b.vy), vertical: true, b.x, 234); b.y = bot; b.vy = -abs(b.vy) * bounce; b.vx *= 0.7; if flying { b.rotV = lerp(b.rotV, b.vx * roll, 0.6) } }
+ b.sqv += (-400 * b.sq - 2 * 0.35 * 20 * b.sqv) * dt; b.sq += b.sqv * dt
+ if flying {
+ b.rotV *= 1 - 0.9 * dt; b.rot += b.rotV * dt
+ } else {
+ // it rights itself: upright against gravity (or leaning into a drag), by the shortest way round
+ let upT = r.W.drag != nil ? clamp(b.vx / 900, -0.5, 0.5) : -a * (gravMag(r) > 0.2 ? 1 : 0)
+ let goal = upT + TAU * ((b.rot - upT) / TAU).rounded()
+ b.rotV += ((goal - b.rot) * 90 - b.rotV * 14) * dt; b.rot += b.rotV * dt
+ }
+ b.surprised = max(b.surprised - dt, (r.W.drag != nil || hypot(b.vx, b.vy) > 420) ? 0.5 : 0)
+ r.W.body = b
+ }
+
+ private func impact(_ r: Rig, _ b: inout WorldState.Body, _ speed: Double, vertical: Bool, _ x: Double, _ y: Double) {
+ guard speed >= 60 else { return }
+ let s = min(speed / 600, 1) * 0.25
+ b.sq = vertical ? s : -s; b.sqv = 0
+ if speed > 250 {
+ r.W.ticks.append(.init(x: x, y: y, age: 0, strong: speed > 700)); if r.W.ticks.count > 8 { r.W.ticks.removeFirst() }
+ if r.trauma < 0.15 { r.onHaptic?(speed > 700 ? .strong : .click) } // shaking it, you feel the shake already
+ }
+ if speed > 160 { for _ in 0..<4 { r.W.dust.append(.init(x: x, y: y, vx: rnd(-30, 30), vy: rnd(-40, 0), age: 0)) } }
+ if speed > 700 {
+ r.W.hardHits = r.W.hardHits.filter { r.t - $0 < 4 } + [r.t]
+ if r.W.hardHits.count >= 3 && r.state != .dizzy { r.W.hardHits = []; r.setState(.dizzy) }
+ }
+ }
+
+ // MARK: launch
+
+ func startLaunch(_ r: Rig) {
+ if r.mode == .world {
+ current(r).reset(); r.W.launch = .init(world: true); r.W.zoom = 1; r.W.zoomV = 0; r.W.label = ""
+ } else { r.W.launch = .init() }
+ }
+
+ private func stepLaunch(_ r: Rig, _ dt: Double) {
+ guard var L = r.W.launch else { return }
+ L.t += dt
+ if L.world { r.W.launch = L.t > 1.8 ? nil : L; return }
+ if L.t > 0.3 {
+ L.vy += 1400 * dt; L.y += L.vy * dt
+ if L.y > 118 {
+ L.y = 118
+ if L.vy > 90 {
+ let v = L.vy; L.vy = -v * 0.45; r.clip = nil
+ r.W.body.sq = min(v / 600, 1) * 0.25; r.W.body.sqv = 0
+ r.onHaptic?(v > 700 ? .strong : .click)
+ for i in 0..<5 { r.W.dust.append(.init(x: 99 + Double(i - 2) * 10, y: 118 + extents(r).bottom, vx: Double(i - 2) * 22, vy: rnd(-40, -20), age: 0)) }
+ } else { L.vy = 0 }
+ }
+ }
+ if L.t > 1.6 { r.W.launch = nil; r.W.body = WorldState.Body() } else { r.W.launch = L }
+ }
+
+ // MARK: frame
+
+ func step(_ r: Rig, _ dt: Double) {
+ let n = max(1, Int((dt * 120).rounded()))
+ for _ in 0..<n where bodyOn(r) { stepPhysics(r, dt / Double(n)) }
+ stepShaken(r, dt)
+ if r.mode != .world { r.W.zoom = 0; r.W.zoomV = 0 }
+ else {
+ let zt: Double = (WIDE.contains(r.state) || r.W.launch?.world == true) ? 1 : 0
+ r.W.zoomV += ((zt - r.W.zoom) * 36 - r.W.zoomV * 12) * dt // critically damped, ω 6
+ r.W.zoom = clamp(r.W.zoom + r.W.zoomV * dt, 0, 1.04)
+ }
+ r.W.labelT += dt; r.W.scrubIdle += dt
+ if r.W.scrubIdle > 3 { r.W.scrubTarget = 0 }
+ r.W.scrub += (r.W.scrubTarget - r.W.scrub) * min(1, dt * (r.W.scrubIdle > 3 ? 5 : 14))
+ if r.W.annoyedT > 0 { r.W.annoyedT -= dt; if r.W.annoyedT <= 0 { r.S.worried.t = STATE_SPECS[r.state]!.worried } }
+ if r.W.launch != nil { stepLaunch(r, dt) }
+ if r.mode == .world && !r.character.staged { current(r).step(r, dt) }
+ if demo && r.mode != .world && (r.state == .working || r.state == .subagents) {
+ demoT += dt; if demoT > 2.2 { demoT = 0; if let e = nextEvent(r) { announce(r, e.text) } }
+ }
+ for i in r.W.ticks.indices { r.W.ticks[i].age += dt }
+ r.W.ticks.removeAll { $0.age >= 0.5 }
+ for i in r.W.dust.indices { r.W.dust[i].age += dt; r.W.dust[i].x += r.W.dust[i].vx * dt; r.W.dust[i].y += r.W.dust[i].vy * dt; r.W.dust[i].vy += 90 * dt }
+ r.W.dust.removeAll { $0.age >= 0.6 }
+ }
+
+ // MARK: pose
+
+ func apply(_ r: Rig, _ p0: Pose) -> Pose {
+ var p = stagePose(r, p0)
+ shakenPose(r, &p)
+ return p
+ }
+
+ private func stagePose(_ r: Rig, _ p0: Pose) -> Pose {
+ var p = p0
+ if r.mode == .world {
+ let w = current(r).pose(r, p); r.W.wp = w
+ let e = clamp(r.W.zoom, 0, 1)
+ p.cx = lerp(p.cx, w.cx, e); p.cy = lerp(p.cy, w.cy, e); p.scale = lerp(p.scale, w.scale, e)
+ p.unitScale = lerp(p.unitScale, w.unitScale, e); p.world = e
+ if e > 0.5 {
+ let o = w.o
+ if let v = o.legs { p.legs = v }; if let v = o.arms { p.arms = v }; if let v = o.tilt { p.tilt = v }
+ if let v = o.open { p.eye.open = v }; if let v = o.gx { p.eye.gx = v }; if let v = o.gy { p.eye.gy = v }
+ if let v = o.happy { p.eye.happy = v }; if let v = o.intent { p.eye.intent = v }
+ if let v = o.sleepy { p.eye.sleepy = v }; if let v = o.wide { p.eye.wide = v }
+ if let v = o.closed { p.eye.closed = v }; if let v = o.awake { p.awake = v }
+ }
+ return p
+ }
+ // portrait idle: the eyes look toward whichever way the watch is turned
+ if r.state == .idle && gravMag(r) > 0.2 && abs(watchRot(r)) > 0.05 { p.eye.gx = clamp(p.eye.gx + sin(watchRot(r)) * 1.1, -1, 1) }
+ if let L = r.W.launch, !L.world {
+ if L.t > 0.3 { p.cy = L.y; p.cx = 99; p.sy *= 1 - r.W.body.sq } else { p.cy = -80 }
+ } else if physicsOn(r) || (r.mode == .physics && r.W.drag != nil) {
+ let b = r.W.body
+ p.cx = b.x; p.cy = b.y; p.scale *= 0.8; p.unitScale = 0.8; p.sy *= 1 - b.sq
+ if r.character.gridded { p.roll = b.rot; p.impact = b.sq } else { p.tilt += b.rot }
+ if b.surprised > 0 { p.eye.wide = max(p.eye.wide, 1) }
+ }
+ return p
+ }
+
+ // MARK: input
+
+ func crown(_ r: Rig, _ delta: Double) -> Bool {
+ guard r.mode == .world, !r.character.staged else { return false }
+ // one crown detent is one step back; the crown itself clicks
+ r.W.scrubIdle = 0; r.W.scrubTarget = clamp(r.W.scrubTarget - delta * 34, -700, 0)
+ return true
+ }
+
+ func onCharacter(_ r: Rig, _ pt: CGPoint) -> Bool {
+ if let st = r.staged { return st.hit(pt) }
+ let p = r.pose()
+ let e = extents(r), s = (r.character.gridded ? p.unitScale : p.scale) / 0.8
+ return abs(pt.x - p.cx) < e.hx * s + 8 && pt.y > p.cy - e.top * s - 8 && pt.y < p.cy + e.bottom * s + 8
+ }
+
+ // MARK: drawing
+
+ private func camera(_ r: Rig, _ ctx: inout GraphicsContext, _ p: Pose) {
+ let e = clamp(r.W.zoom, 0, 1), a0 = clamp((e - 0.45) / 0.45, 0, 1), f = 1 + (1 - e) * 0.5, w = r.W.wp
+ ctx.opacity *= a0 * a0 * (3 - 2 * a0)
+ ctx.translateBy(x: p.cx, y: p.cy); ctx.scaleBy(x: f, y: f); ctx.translateBy(x: -w.cx, y: -w.cy)
+ }
+
+ func drawBack(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose) {
+ guard worldOn(r) else { return }
+ var c = r.ao ? ctx.faded(0.4) : ctx; camera(r, &c, p) // always on: the world stays, dimmed
+ current(r).back(r, c, p)
+ }
+
+ func drawFront(_ r: Rig, _ ctx: GraphicsContext, _ p: Pose) {
+ if worldOn(r) {
+ var c = ctx; camera(r, &c, p)
+ current(r).front(r, c, p)
+ // one line of fact under the world: the last tool call, or where the crown has taken you
+ var text: String?, ta = 1.0
+ if r.W.scrubIdle < 3 && abs(r.W.scrub) > 6 {
+ let n = Int((-r.W.scrub / 34).rounded())
+ if let s = current(r).scrubLabel(r) { text = "\(s), \(n) \(n == 1 ? "step" : "steps") back" }
+ } else if (r.state == .working || r.state == .subagents || (r.character.gridded && r.W.labelT < 3)) && !r.W.label.isEmpty && r.caption.isEmpty {
+ text = r.W.label; ta = clamp(r.W.labelT / 0.25, 0, 1)
+ }
+ if let text {
+ let e = clamp(r.W.zoom, 0, 1), a0 = clamp((e - 0.45) / 0.45, 0, 1)
+ ctx.faded(a0 * ta).draw(Text(text).font(.system(size: 10.5, weight: .medium, design: .monospaced)).foregroundColor(Pal.gray),
+ at: CGPoint(x: 99, y: 216), anchor: .center)
+ }
+ }
+ for k in r.W.ticks {
+ ctx.faded((1 - k.age / 0.5) * 0.7).strokeCircle(k.x, k.y, 4 + k.age * 30, k.strong ? Pal.white : Pal.gray, 1.2)
+ }
+ for d in r.W.dust { ctx.faded(1 - d.age / 0.6).fillRect(d.x, d.y, 2, 2, Pal.dim) }
+ if let L = r.W.launch, !L.world {
+ let k = clamp(L.t / 0.3, 0, 1), y = 118 + extents(r).bottom
+ ctx.faded(L.t > 1.2 ? max(0, 1 - (L.t - 1.2) / 0.4) : 1).fillRect(99 - 99 * k, y, 198 * k, 1.6, Color(hex: 0x3A3D41))
+ }
+ }
+}
+
+/// An angle brought into −π…π.
+func wrapAngle(_ a: Double) -> Double { a - TAU * (a / TAU).rounded() }
diff --git a/app/ChumsWatch/Rig/Yarn.swift b/app/ChumsWatch/Rig/Yarn.swift
new file mode 100644
index 0000000..669adb7
--- /dev/null
+++ b/app/ChumsWatch/Rig/Yarn.swift
@@ -0,0 +1,194 @@
+import SwiftUI
+
+/// Tangle's body: a real ball of yarn. One thread is wound round and round a ball (each turn drifting a little off the
+/// last, so it covers the ball the way yarn does, the outer turns over the inner ones), and its end hangs off it.
+/// The Digital Crown is the spool. Turned one way it reels the thread in: the end runs to the crown, the thread pays
+/// out off the ball, which turns as it goes and gets smaller, all the way down to the last little knot. Turned back,
+/// it feeds the thread out again and the ball winds it up. The thread between them hangs and sways on its own weight;
+/// a finger on the ball spins it, a finger on the thread plucks it.
+/// Everything is in points, round the ball's middle (y down, z toward you).
+final class Yarn {
+ typealias V3 = SIMD3<Double>
+
+ // MARK: sizes
+
+ /// The full ball's radius and the last knot's; the thread's width; how many turns it is wound.
+ static let R0 = 54.0, Rmin = 8.0, width = 7.6, turns = 9.0
+ /// Points per turn of the thread on the ball; points in the loose thread.
+ static let M = 48, K = 30
+ /// Where the spool is: just past the right edge, at the crown.
+ static let spool = P2(206, 86)
+
+ // MARK: the thread on the ball
+
+ /// The whole thread wound on a ball of radius 1, from its inner end out: a curve on the sphere that turns a little
+ /// off a great circle all the time (more, then less), so each turn crosses the last at a new angle.
+ private static let wound: [V3] = {
+ let n = Int(turns) * M + 1
+ var e1 = V3(1, 0, 0)
+ var out: [V3] = []
+ for i in 0..<n {
+ let u = Double(i) / Double(M) // turns so far
+ // each turn's plane tips round as it winds (its axis wandering over the ball), so the turns cross
+ // (the axis visits every direction, so from no side do the turns all line up into a star)
+ let lam = 1.15 * u + 0.3 * sin(u * 0.7), cz = 0.92 * sin(0.41 * u + 0.35)
+ let a = V3(sqrt(1 - cz * cz) * cos(lam), cz, sqrt(1 - cz * cz) * sin(lam))
+ e1 = simd_normalize(e1 - a * simd_dot(e1, a))
+ let e2 = simd_cross(a, e1), th = TAU * u
+ out.append(simd_normalize(e1 * cos(th) + e2 * sin(th)))
+ }
+ return out
+ }()
+
+ // MARK: state
+
+ /// How much of it is reeled off: 0 all wound, 1 down to the last knot.
+ private(set) var off = 0.0
+ /// The ball's turn, and its spin (rad/s about each axis).
+ private var q = simd_quatd(angle: 0.4, axis: simd_normalize(V3(1, 0.3, 0)))
+ private var spin = V3.zero
+ /// The loose thread: its points and where they were (it moves by Verlet steps).
+ private var rope: [P2] = [], was: [P2] = []
+ /// How firmly its end is on the spool (0: hanging loose, 1: on it); how slack it is (0 taut).
+ private var onSpool = 0.0, slack = 0.08
+ private var t = 0.0, reeling = 0.0, lastOff = 0.0
+ private var grab: (i: Int, at: P2)?
+ /// The thread swinging loose after a shake or a tug (how far each turn bulges off the ball).
+ private var loose = 0.0, looseV = 0.0
+ /// Where the ball's middle is on screen, how big it's drawn, set by its stage each frame.
+ var center = P2(99, 128), scale = 1.0
+ /// The face's size for the ball's: the knot keeps a readable face.
+ var faceK: Double { 0.62 + 0.38 * radius / Self.R0 }
+ var radius: Double { (Self.Rmin + (Self.R0 - Self.Rmin) * pow(max(0, 1 - off), 0.45)) * scale }
+ /// Being reeled in or fed out right now.
+ var busy: Bool { reeling > 0.05 || simd_length(spin) > 0.05 || grab != nil || abs(looseV) > 0.02 }
+ var moving: Double { reeling }
+
+ // MARK: input
+
+ /// The crown: negative reels the thread in (off the ball), positive feeds it back. Returns true at each notch.
+ @discardableResult func crown(_ delta: Double) -> Bool {
+ let before = (off * 40).rounded(.down)
+ off = clamp(off - delta * 0.025, 0, 1) // about 40 crown steps from ball to knot
+ reeling = min(1, reeling + abs(delta) * 2)
+ return (off * 40).rounded(.down) != before
+ }
+ /// A finger down at `p`: on the thread, it takes hold of it.
+ func touch(_ p: P2) -> Bool {
+ guard !rope.isEmpty else { return false }
+ var best = -1, bd = 16.0
+ for i in 2..<rope.count where simd_length(rope[i] - p) < bd { bd = simd_length(rope[i] - p); best = i }
+ if best >= 0 { grab = (best, p); return true }
+ return false
+ }
+ /// The finger moving: the thread it holds follows it; on the ball, it spins the ball.
+ func drag(from a: P2, to b: P2) {
+ if grab != nil { grab!.at = b; return }
+ let d = b - a, r = max(20, radius)
+ // a trackball: the ball rolls the way the finger goes
+ spin += V3(d.y, -d.x, 0) / r * 9
+ }
+ func release() {
+ grab = nil
+ }
+ /// Shaken or jolted: the thread swings, the turns come loose for a moment.
+ func jolt(_ a: P2, hard: Double) {
+ for i in rope.indices.dropFirst() { was[i] -= a * (0.00012 * Double(i) / Double(Self.K)) } // a push to its speed
+ looseV += hard * 1.2
+ spin += V3(a.y, -a.x, 0) * 0.004
+ }
+ /// A tap on the ball: it gives and the loose turns bounce.
+ func tap() { looseV += 1.4; spin += V3(rnd(-1, 1), rnd(-1, 1), 0) * 1.5 }
+
+ // MARK: step
+
+ func step(_ dt: Double, gravity: P2 = P2(0, 1)) {
+ t += dt
+ reeling *= exp(-dt * 3)
+ let R = radius
+ // the turns that came loose settle back (a spring)
+ let wl = TAU * 2.2
+ looseV += (-wl * wl * loose - 2 * 0.35 * wl * looseV) * dt; loose += looseV * dt
+ // the end of the thread on the ball, in the ball's frame, and where it is now
+ let endI = endIndex
+ let endLocal = Self.wound[min(Self.wound.count - 1, Int(endI))] * layer(endI)
+ // the ball turns so the thread leaves it toward where it goes: the spool, or hanging down when loose
+ let toward: V3 = onSpool > 0.5 ? simd_normalize(V3(Self.spool.x - center.x, Self.spool.y - center.y, 0.35 * R)) : simd_normalize(V3(0.75, 0.6, 0.4))
+ let v = simd_normalize(q.act(endLocal))
+ let ax = simd_cross(v, toward), s = simd_length(ax)
+ if s > 1e-4 {
+ let ang = asin(min(1, s)) * min(1, dt * (grab == nil ? 5 : 1.5))
+ q = simd_quatd(angle: ang, axis: ax / s) * q
+ }
+ // a spin from a finger, slowing down
+ let sl = simd_length(spin)
+ if sl > 1e-4 { q = simd_quatd(angle: sl * dt, axis: spin / sl) * q; spin *= exp(-dt * 2.2) }
+ q = q.normalized
+ // the loose thread: on the spool once some is reeled in, loose again when it's all wound back
+ let want = off > 0.003 ? 1.0 : 0.0
+ onSpool += (want - onSpool) * min(1, dt * (want > onSpool ? 5 : 1.6))
+ // taut while it's reeled in, slack while it's fed out, a little sag when still
+ let dOff = off - lastOff; lastOff = off
+ let slackWant = dOff > 1e-5 ? 0.0 : dOff < -1e-5 ? 0.22 : 0.08
+ slack += (slackWant - slack) * min(1, dt * 4)
+ let a = center + project(q.act(endLocal)).p
+ let tipFree = a + P2(14, 18)
+ let tip = tipFree + (Self.spool - tipFree) * smooth01(onSpool)
+ let span = simd_length(tip - a)
+ let len = onSpool < 0.02 ? 26.0 : max(26 * (1 - onSpool), span * (1 + slack))
+ if rope.isEmpty {
+ rope = (0..<Self.K).map { i in a + (tipFree - a) * (Double(i) / Double(Self.K - 1)) }; was = rope
+ // turned from the start so the thread leaves it where it should
+ for _ in 0..<60 {
+ let v = simd_normalize(q.act(endLocal)), ax = simd_cross(v, toward), s = simd_length(ax)
+ if s > 1e-5 { q = simd_quatd(angle: asin(min(1, s)), axis: ax / s) * q }
+ }
+ }
+ // Verlet: gravity, a little air, then the lengths and the ends held
+ let g = gravity * 900.0
+ for i in 1..<Self.K {
+ let v = (rope[i] - was[i]) * 0.985
+ was[i] = rope[i]; rope[i] += v + g * (dt * dt)
+ }
+ let seg = len / Double(Self.K - 1)
+ for _ in 0..<14 {
+ rope[0] = a
+ if onSpool > 0.02 { rope[Self.K - 1] = rope[Self.K - 1] + (tip - rope[Self.K - 1]) * smooth01(onSpool) }
+ if let gr = grab { rope[gr.i] = gr.at }
+ for i in 0..<(Self.K - 1) {
+ let d = rope[i + 1] - rope[i], l = max(1e-6, simd_length(d)), e = (l - seg) / l
+ let wa = i == 0 ? 0.0 : 0.5, wb = (i + 1 == Self.K - 1 && onSpool > 0.5) ? 0.0 : 0.5
+ let tot = max(1e-6, wa + wb)
+ rope[i] += d * (e * wa / tot); rope[i + 1] -= d * (e * wb / tot)
+ }
+ for i in 1..<Self.K where rope[i].y > 236 { rope[i].y = 236 } // the bottom of the screen
+ }
+ }
+
+ // MARK: drawing
+
+ /// The thread's last point on the ball (fractional index into `wound`).
+ private var endIndex: Double { max(Double(Self.M) * 0.6, Double(Self.wound.count - 1) * (1 - off)) }
+ /// How far out each part of the thread lies: the outer turns over the inner ones, each turn loose by a little.
+ @inline(__always) private func layer(_ i: Double) -> Double {
+ let r = radius, u = i / Double(Self.M)
+ return r * (0.84 + 0.16 * u / Self.turns) * (1 + 0.025 * sin(u * 2.3 + t * 0.6) + loose * 0.06 * sin(u * 5.1 + t * 7))
+ }
+ @inline(__always) private func project(_ p: V3) -> (p: P2, z: Double) { (P2(p.x, p.y), p.z) }
+
+ /// The ball and its thread: one flat colour, like the marker line it's drawn in (no outline).
+ func draw(_ g: GraphicsContext, color: Color) {
+ let w = Self.width * scale, n = Int(endIndex)
+ var pts: [P2] = []
+ pts.reserveCapacity(n + 1)
+ for i in 0...n {
+ let p = q.act(Self.wound[i] * layer(Double(i)))
+ pts.append(center + P2(p.x, p.y))
+ }
+ let style = StrokeStyle(lineWidth: w, lineCap: .round, lineJoin: .round)
+ if !rope.isEmpty { g.stroke(Strokes.smoothOpen(rope), with: .color(color), style: style) }
+ g.stroke(Strokes.smoothOpen(pts), with: .color(color), style: style)
+ }
+
+ @inline(__always) private func smooth01(_ u: Double) -> Double { let v = clamp(u, 0, 1); return v * v * (3 - 2 * v) }
+}
diff --git a/app/ChumsWatch/Screen.swift b/app/ChumsWatch/Screen.swift
new file mode 100644
index 0000000..c6d4df1
--- /dev/null
+++ b/app/ChumsWatch/Screen.swift
@@ -0,0 +1,657 @@
+import AVFoundation
+import SwiftUI
+import CoreMotion
+#if os(watchOS)
+import WatchKit
+#else
+import UIKit
+#endif
+
+// The screen's engine, the same on the watch and the iPhone: the character, the hub's state, holding to talk, the
+// gestures on the character, approvals and the conversation. Each app draws it its own way (ChumsWatchApp, ChumsPhone).
+// What a view shows from it (listening, the conversation) is tracked through the controller and the hub, which are
+// observable; what changes every frame or every touch here is ignored, so it never makes a view redraw.
+
+@MainActor @Observable
+final class ScreenModel {
+ let rig = Rig()
+ let hub: HubClient
+ let controller: Controller
+ private let recorder = Recorder()
+ private let speaker = Speaker()
+ private let motion = CMMotionManager()
+ @ObservationIgnored private var lastDate: Date?
+ @ObservationIgnored private var micAllowed = true
+ /// Something that went wrong, in words, for a screen that doesn't draw the watch's caption (the iPhone shows it as a
+ /// note in the conversation).
+ @ObservationIgnored var onNotice: ((String) -> Void)?
+ private func tell(_ s: String) { rig.caption = s; onNotice?(s) }
+ /// The note when the microphone isn't allowed (the iPhone adds a way to Settings under it).
+ static let micRefused = "Allow the microphone for Chums in Settings."
+ @ObservationIgnored private var spokenKind: String?
+ @ObservationIgnored private var dimmed = false
+ @ObservationIgnored private var wokeAt = Date.distantPast
+
+ struct Gesture {
+ enum Mode { case none, talk, drag, pet, allow }
+ var down = false, moved = false
+ var level = false, jumped = false // the touch is on a pixel level; it made the character jump
+ var settings = false // it landed on the faces at the top left
+ var approval: String? // the approval card under the finger, fixed at touch-down
+ var target: Rig.TouchTarget = .none
+ var mode: Mode = .none
+ var t0 = Date(), start = CGPoint.zero, last = CGPoint.zero, lastT = Date()
+ var vx = 0.0, vy = 0.0
+ var timer: Task<Void, Never>?
+ }
+ @ObservationIgnored private var g = Gesture()
+
+ /// Something it showed you arrived (the screen shows a pill for it).
+ @ObservationIgnored var onArtifact: ((Artifact, String) -> Void)?
+
+ /// Talk to another agent: what's on screen becomes its. A recording already going keeps the agent it started with.
+ func setAgent(_ id: String) {
+ guard id != controller.agent else { return }
+ controller.agent = id
+ if controller.talk == .speaking { controller.talk = .none }
+ hub.event("agent: \(id)")
+ }
+
+ init(hub: HubClient) {
+ self.hub = hub
+ ArtifactImages.shared.hub = hub
+ controller = Controller(rig: rig, hub: hub)
+ rig.onHaptic = { Haptics.play($0) }
+ rig.onAllow = { [weak self] in guard let self else { return }; self.answer(true, self.g.approval) }
+ speaker.onFinish = { [weak self] in self?.controller.speechFinished(kind: self?.spokenKind) }
+ }
+
+ /// Runs once for the model SwiftUI keeps. SwiftUI may build and drop extra copies of the screen, so anything
+ /// shared (the hub's callback, the motion manager, the iPhone's clock) is wired here and not in init.
+ func prepare() async {
+#if os(iOS)
+ if clock == nil { clock = EngineClock(self, fast: fullRate) }
+#endif
+ // a new approval taps your wrist once, when it arrives from the hub (not when it's drawn)
+ hub.onApproval = { [weak self] a in
+ guard let self else { return }
+ let who = self.controller.info(a.session)
+ Alerts.post("\(who.name) needs approval", a.summary ?? a.description)
+ if a.session == self.controller.agent { Haptics.play(.notification) }
+ else {
+ // another agent's: its pill (the card is there when you go to it)
+ let line = Spoken(id: "approval-" + a.requestId, session: a.session, text: "Needs your OK: \(a.summary ?? a.description)",
+ kind: "question", audio: nil, at: nil, artifact: nil, agent: a.session)
+ self.controller.onBackground?(who, line)
+ }
+ }
+ hub.onSpoken = { [weak self] line in
+ guard let self else { return }
+ self.spokenKind = line.kind
+ if let a = line.artifact, line.owner == self.controller.agent { self.onArtifact?(a, line.text) }
+ if let a = line.artifact { Task { _ = await ArtifactImages.shared.thumb(a) } }
+ self.controller.spoken(line) { text in
+ var voiceOn = UserDefaults.standard.object(forKey: "voice") as? Bool ?? true // Settings › Voice
+#if targetEnvironment(simulator)
+ voiceOn = false // the Simulator plays through the Mac's speakers; it never speaks
+#endif
+ if voiceOn && line.speaksHere && ["done", "question", "blocked", "working", "status", "ask", "info", "artifact"].contains(line.kind) && self.controller.talk != .listening {
+ // the Mac's voice when it rendered one (in the answer itself, else fetched), else the watch's own
+ if let b64 = line.audioData, let d = Data(base64Encoded: b64), self.speaker.play(d) {
+ self.hub.event("speech: \(line.agent ?? "?") inline \(d.count / 1024) KB")
+ } else if let path = line.audio {
+ Task {
+ if let d = await self.hub.speech(path), self.speaker.play(d) { self.hub.event("speech: \(line.agent ?? "?") fetched") }
+ else { self.speaker.speak(text); self.hub.event("speech: \(line.agent ?? "?") the watch's voice (no audio)") }
+ }
+ } else { self.speaker.speak(text) }
+ } else { self.controller.speechFinished(kind: line.kind) }
+ }
+ }
+ StayOn.shared.onEvent = { [hub] in hub.event($0) }
+ startMotion()
+ // its prompt would cover the self-test and Simulator captures (-quiet YES)
+#if os(watchOS)
+ // (the iPhone doesn't poll in the background, so it has nothing to notify you of)
+ if !UserDefaults.standard.bool(forKey: "selftest") && !UserDefaults.standard.bool(forKey: "quiet") { Alerts.setUp() }
+#endif
+ if UserDefaults.standard.bool(forKey: "noodleBench") { // decode speed on this watch (-noodleBench YES)
+ for clip in ["idle_rest", "work_read", "subagents_rest"] { StretchFrames.shared.bench(clip) { [hub] in hub.event($0) } }
+ }
+#if targetEnvironment(simulator)
+ // Simulator captures (-quiet YES): no permission sheets over the recording (the capture's voice is made up anyway)
+ if UserDefaults.standard.bool(forKey: "quiet") { Recorder.fake = true; micAllowed = true; hub.event("mic: not asked (capture)"); return }
+#endif
+#if os(watchOS)
+ micAllowed = await Recorder.requestPermission()
+#else
+ micAllowed = AVAudioApplication.shared.recordPermission != .denied // asked at the first hold, not at launch
+#endif
+ }
+
+ /// The screen dims (always on) or wakes. Dimmed, the character draws as an outline once a second and motion
+ /// stops; the hub still polls, so the character can still tap your wrist.
+ @ObservationIgnored private var lastInput = Date()
+ func setDimmed(_ dim: Bool) {
+ rig.ao = dim; hub.screen = dim ? "dim" : "on"
+ // how long since your last touch or crown: about 15 s (or 70) is watchOS's wake time running out; less is a turn
+ if dim && !dimmed {
+ motion.stopDeviceMotionUpdates()
+ hub.event(String(format: "screen dim, %.1f s after the last touch or crown, %.1f s after it woke", Date().timeIntervalSince(lastInput), Date().timeIntervalSince(wokeAt)))
+ }
+ if !dim && dimmed { wokeAt = Date(); StayOn.shared.woke(); startMotion(); hub.event("screen on"); hub.nudge() }
+ dimmed = dim
+ }
+
+ /// The crown turned: walk in a pixel level (or scrub). The first turn after a pause is logged, to check the crown reaches Chums.
+ @ObservationIgnored private var lastCrown = Date.distantPast
+ @ObservationIgnored private var crownBurst = (sum: 0.0, start: Date(), last: Date())
+ func crown(_ delta: Double) {
+ lastInput = Date(); StayOn.shared.lastInput = lastInput
+ // each turn of the crown, in the log once it ends: how far and how fast (for tuning what the crown does)
+ if Date().timeIntervalSince(crownBurst.last) > 0.6 {
+ if crownBurst.sum != 0 { hub.event(String(format: "crown turn: %+.1f in %.1f s", crownBurst.sum, crownBurst.last.timeIntervalSince(crownBurst.start))) }
+ crownBurst = (0, Date(), Date())
+ }
+ crownBurst.sum += delta; crownBurst.last = Date()
+ if Date().timeIntervalSince(lastCrown) > 3 { hub.event("crown \(String(format: "%.2f", delta)), level \(rig.levelLive ? "live" : "off"), state \(rig.state), memory \(Self.memoryMB()) MB") }
+ lastCrown = Date()
+ rig.crown(delta)
+ }
+
+ func setDemo(_ on: Bool) {
+ controller.demo = on ? DemoDriver() : nil
+ rig.worlds.demo = on
+ }
+
+ /// The app's memory footprint, the number watchOS kills apps over (about 300 MB on this watch).
+ static func memoryMB() -> Int {
+ var info = task_vm_info_data_t()
+ var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)
+ let kr = withUnsafeMutablePointer(to: &info) {
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) }
+ }
+ return kr == KERN_SUCCESS ? Int(info.phys_footprint / 1_048_576) : -1
+ }
+ @ObservationIgnored private var memAt = Date.distantPast
+ @ObservationIgnored private var memLast = 0
+ let perf = Perf()
+
+#if os(iOS)
+ /// The iPhone runs frame() on its own clock, whatever is on screen: a stage under a card, or scrolled out of the
+ /// conversation, draws nothing, and the engine still goes on (a reply still finishes). The stages only draw the rig.
+ @ObservationIgnored private var clock: EngineClock?
+ /// The big stage draws a live character, at the screen's own rate: the clock runs at that rate too (else 30 a second).
+ @ObservationIgnored var fullRate = false { didSet { clock?.fast = fullRate } }
+#endif
+
+ /// One frame: read the inputs, update the state, advance the rig. Called again with the same date, it does nothing.
+ func frame(_ date: Date) {
+ // frame rate and memory, in the hub's log every 30 s (config "diagnostics": for working on the app)
+ if HubConfig.diagnostics && date.timeIntervalSince(memAt) > 30 {
+ memAt = date
+ let m = Self.memoryMB()
+ if abs(m - memLast) >= 5 { memLast = m; hub.event("memory \(m) MB") }
+ if let p = perf.take() { hub.event("\(p); \(rig.character.rawValue), memory \(m) MB") }
+ if rig.character == .stretch, let s = StretchFrames.shared.takeStats() { hub.event(s) }
+ }
+ let dt = lastDate.map { date.timeIntervalSince($0) } ?? 1.0 / 60
+ guard dt > 0 else { return }
+ lastDate = date
+ controller.update()
+ let all = hub.state?.agents ?? Agents.known, me = controller.agent
+ let mine = UserDefaults.standard.string(forKey: "character") ?? controller.info(me).character
+ let fake = UserDefaults.standard.string(forKey: "fakeNeeds") // Simulator captures: -fakeNeeds noodle
+ // the faces at the top: the one you talk to, then at most two others, those that need you first (asking, stuck,
+ // rate limited), then those at work, then the idle ones; never more than three
+ func urgency(_ a: AgentInfo) -> Int {
+ if a.needs || a.id == fake { return 0 }
+ switch a.status { case "blocked": return 1; case "waiting", "limited": return 2; case "working", "compacting": return 3
+ case "offline": return 5; default: return 4 }
+ }
+ let others = all.filter { $0.id != me }.enumerated().sorted { (urgency($0.element), $0.offset) < (urgency($1.element), $1.offset) }.map(\.element)
+ rig.faces = [(mine, false)] + others.prefix(2).map { ($0.character, $0.needs || $0.id == fake) }
+ rig.voiceInput = rig.state == .listening ? (Self.fakeVoice ? Self.voiceLike(rig.t) : recorder.level) : nil
+ rig.tick(dt)
+ }
+
+ /// Simulator captures (-fakeVoice YES): no one speaks into the Mac, so the waveform follows a made-up voice.
+ static let fakeVoice = UserDefaults.standard.bool(forKey: "fakeVoice")
+ /// Something like speech: syllables (~5 a second) of varying loudness, grouped into words with short gaps.
+ static func voiceLike(_ t: Double) -> Double {
+ let word = 0.5 + 0.5 * sin(t * 2.3) * sin(t * 1.1 + 1)
+ let syllable = max(0, sin(t * TAU * 4.7)) * (0.6 + 0.4 * sin(t * 13.1))
+ return clamp(0.12 + 0.75 * syllable * (0.35 + 0.65 * max(0, word)), 0, 1)
+ }
+
+ // MARK: touch
+
+ private func design(_ p: CGPoint, _ size: CGSize) -> CGPoint {
+ let f = Renderer.fit(size)
+ return CGPoint(x: (p.x - f.ox) / f.s, y: (p.y - f.oy) / f.s)
+ }
+
+ func drag(_ loc: CGPoint, in size: CGSize) {
+ let pt = design(loc, size), now = Date()
+ lastInput = now; StayOn.shared.lastInput = now
+ if !g.down {
+ g = Gesture(); g.down = true; g.t0 = now; g.start = pt; g.last = pt; g.lastT = now
+ // the faces at the top left belong to the agents' list: no ripple, no jump, no poke, no talking
+ if SettingsButton.near(pt) && rig.state != .approval {
+ g.settings = true
+ hub.event("settings tap at \(Int(pt.x)),\(Int(pt.y))\(dimmed ? " on the dimmed screen" : "")")
+ return
+ }
+ g.target = rig.touchDown(pt)
+ onHandle = pt.y > 214 && abs(pt.x - 99) < 50 && rig.state != .approval
+ if !onHandle { rig.staged?.touched(rig, at: pt) } // Noodle: the glass ripples under your finger
+ // just woken from the dimmed screen (the touch that woke it may never arrive): a touch held anywhere talks, sooner
+ let fromSleep = now.timeIntervalSince(wokeAt) < 0.4 && g.target != .card && g.target != .deny // the waking touch arrives within ~20 ms
+ // a pixel level is a game: a tap jumps at once. In the lower part it waits for the release (it may be a hold to
+ // talk), unless you're already playing; held anywhere, it talks either way
+ g.level = !fromSleep && !onHandle && rig.levelLive
+ if g.level && (g.target != .talkZone || rig.levelPlaying) { g.jumped = rig.levelPress() }
+ if fromSleep { g.target = .talkZone }
+ if now.timeIntervalSince(wokeAt) < 5 { hub.event("touch \(Int(now.timeIntervalSince(wokeAt) * 1000)) ms after the screen woke\(fromSleep ? ": talk from sleep" : "")") }
+ if !hub.connected { hub.nudge() } // a touch while the Mac was out of reach: look again now
+ g.approval = hub.state?.approvals.first(where: { $0.session == controller.agent })?.requestId
+ switch g.target {
+ case .card: g.mode = .allow
+ case .deny: rig.staged?.deny(rig); answer(false, g.approval)
+ case .talkZone, .character, .none:
+ // held still anywhere (on the character, in the level, lower down), it talks
+ let hold = fromSleep ? 150 : 450
+ g.timer = Task { [weak self] in
+ try? await Task.sleep(for: .milliseconds(hold))
+ guard let self, !Task.isCancelled, self.g.down, !self.g.moved else { return }
+ self.g.mode = .talk; self.beginTalk()
+ }
+ default: break
+ }
+ return
+ }
+ if g.settings { return }
+ rig.touchMoved(pt)
+ if g.mode != .talk && !onHandle { rig.staged?.dragged(rig, at: pt) }
+ let dts = max(0.008, now.timeIntervalSince(g.lastT))
+ g.vx = g.vx * 0.5 + (pt.x - g.last.x) / dts * 0.5; g.vy = g.vy * 0.5 + (pt.y - g.last.y) / dts * 0.5; g.lastT = now
+ if !g.moved && hypot(pt.x - g.start.x, pt.y - g.start.y) > 6 {
+ g.moved = true
+ if g.mode != .talk { g.timer?.cancel() }
+ if g.target == .character && g.mode != .talk { g.mode = rig.mode == .physics || rig.W.loose != nil ? .drag : .pet }
+ }
+ // talking: sliding left onto × arms cancel, right onto ✓ arms send; a tap on the wrist as either arms
+ if g.mode == .talk {
+ let slide = clamp((pt.x - g.start.x) / 46, -1, 1), was = rig.talkSlide
+ if (abs(slide) >= Rig.armed) != (abs(was) >= Rig.armed) || (slide >= Rig.armed && was <= -Rig.armed) || (slide <= -Rig.armed && was >= Rig.armed) { Haptics.play(.click) }
+ rig.talkSlide = slide
+ }
+ if g.mode == .drag { rig.W.drag = pt }
+ if g.mode == .pet { rig.pet(abs(pt.x - g.last.x)) }
+ g.last = pt
+ }
+
+ /// This agent's conversation, oldest first: the hub's recent lines (after a relaunch) and every line since launch.
+ var conversation: [ChatLine] {
+ var seen = Set<String>(), all: [Spoken] = []
+ for l in (hub.state?.spoken ?? []) + controller.lines where l.owner == controller.agent && seen.insert(l.id).inserted { all.append(l) }
+ return all.enumerated().sorted { ($0.element.at ?? Double($0.offset)) < ($1.element.at ?? Double($1.offset)) }.map { ChatLine($0.element) }
+ }
+ /// The touch started on the handle at the bottom (pulling up there opens the conversation).
+ @ObservationIgnored private(set) var onHandle = false
+ var talking: Bool { g.mode == .talk }
+ /// The finger now belongs to the conversation card: drop whatever the touch had started.
+ func cancelTouch() { g.timer?.cancel(); rig.touchUp(); g.down = false; g.mode = .none }
+
+ enum TapAction { case none, settings, chat }
+ /// What a tap opens: the agents' list (the faces at the top left), or nothing.
+ func dragEnd(_ loc: CGPoint, in size: CGSize) -> TapAction {
+ let pt = design(loc, size)
+ g.timer?.cancel()
+ rig.touchUp()
+ rig.staged?.released(rig)
+ defer { g.down = false; g.mode = .none }
+ let short = Date().timeIntervalSince(g.t0) < 0.3 && !g.moved
+ // the faces at the top left: a tap there, quick or slow, as long as it stayed put
+ if g.settings { if Date().timeIntervalSince(g.t0) < 1.2 && hypot(pt.x - g.start.x, pt.y - g.start.y) < 14 { return .settings }; return .none }
+ switch g.mode {
+ case .talk:
+ let cancel = rig.talkSlide <= -Rig.armed
+ rig.talkSlide = 0
+ if cancel { cancelTalk() } else { endTalk() }
+ case .drag:
+ rig.W.drag = nil; rig.W.body.vx = clamp(g.vx, -1400, 1400); rig.W.body.vy = clamp(g.vy, -1400, 1400)
+ if rig.W.loose != nil { rig.W.loose?.phase = .fly; rig.W.loose?.sinceKick = 0 } // thrown again
+ case .pet: rig.petEnded()
+ default:
+ if short && g.level && !g.jumped && rig.levelPress() {}
+ else if short && g.target == .character && !g.jumped { rig.poke() }
+ }
+ return .none
+ }
+
+ // MARK: talk and approvals
+
+ @ObservationIgnored private var talkApproval: String? // the approval card on screen while you spoke
+ @ObservationIgnored private var talkAgent = Agents.fallback // who you were talking to when you started: it goes to them
+ @ObservationIgnored private var talkLimit: Task<Void, Never>?
+
+ private func beginTalk() {
+ guard micAllowed else { tell(Self.micRefused); return }
+ speaker.stop()
+ do {
+ try recorder.start()
+ talkApproval = g.approval; talkAgent = controller.agent
+ controller.talk = .listening
+ Haptics.play(.start)
+ // a hold that never ends (a sleeve on the screen) stops after 30 s; on the iPhone, where a tap keeps it
+ // listening, after 2 minutes
+#if os(watchOS)
+ let limit = 30.0
+#else
+ let limit = 120.0
+#endif
+ talkLimit = Task { [weak self] in
+ try? await Task.sleep(for: .seconds(limit))
+ guard let self, !Task.isCancelled, self.g.mode == .talk else { return }
+ self.g.mode = .none; self.endTalk()
+ }
+ } catch { tell("The microphone isn't available right now."); hub.event("mic failed: \(error.localizedDescription)") }
+ }
+
+ // MARK: talking on a soul screen: what you say becomes a proposed change to that agent's soul
+
+ /// Your voice's loudness now, 0…1. It's read from the recorder, not stored, so it's never tracked: a view that
+ /// follows it reads it inside a TimelineView, every frame.
+ var talkLevel: Double { Self.fakeVoice ? Self.voiceLike(rig.t) : recorder.level ?? 0 }
+ func startSoulTalk() -> Bool {
+ guard micAllowed else { return false }
+ speaker.stop()
+ do { try recorder.start(); Haptics.play(.start); return true } catch { return false }
+ }
+ /// Let go: nil when it was canceled (or too short); otherwise the hub's proposal, question or reason it failed.
+ func endSoulTalk(cancel: Bool, agent: String) async -> SoulProposal? {
+ guard let clip = recorder.stop() else { return nil }
+ defer { try? FileManager.default.removeItem(at: clip.url) }
+ if cancel || clip.seconds < 0.35 { if cancel { Haptics.play(.click) }; return nil }
+ Haptics.play(.click)
+ return await hub.sendSoul(audio: clip.url, agent: agent)
+ }
+
+ /// Let go on ×: what you said is thrown away, nothing is sent.
+ private func cancelTalk() {
+ talkLimit?.cancel()
+ if let clip = recorder.stop() { try? FileManager.default.removeItem(at: clip.url) }
+ if controller.talk == .listening { controller.talk = .none }
+ Haptics.play(.click)
+ controller.note("Canceled")
+ hub.event("talk canceled")
+ controller.flushHeld()
+ }
+
+ /// Letting go always stops the microphone, whatever the character is doing; a reply that arrived meanwhile waits.
+ private func endTalk() {
+ talkLimit?.cancel()
+ guard let clip = recorder.stop() else { if controller.talk == .listening { controller.talk = .none }; return }
+ guard clip.seconds > 0.35 else {
+ try? FileManager.default.removeItem(at: clip.url)
+ if controller.talk == .listening { controller.talk = .none }
+ controller.flushHeld()
+ return
+ }
+ controller.talk = .sending
+ controller.orderSent()
+ Haptics.play(.click)
+ let approval = talkApproval, to = talkAgent
+ Task {
+ let result = await hub.send(audio: clip.url, approval: approval, agent: to)
+ try? FileManager.default.removeItem(at: clip.url)
+ if controller.talk == .sending { controller.talk = .none }
+ if result == nil { Haptics.play(.failure); tell(hub.connected ? "Couldn't send that. Try again." : "Can't reach your Mac.") }
+ else if result?.kind == "empty" { Haptics.play(.failure) }
+ controller.flushHeld()
+ }
+ }
+
+ /// Allow or deny the approval that was under the finger. Nothing happens if it changed meanwhile; the tap of
+ /// success comes only once the hub has the verdict.
+ private func answer(_ allow: Bool, _ id: String?) {
+ guard let id, hub.state?.approvals.contains(where: { $0.requestId == id }) == true else {
+ Haptics.play(.failure); tell("That request changed. Look again."); return
+ }
+ controller.verdictAllowed = allow
+ Task {
+ if await hub.verdict(id, allow: allow) { Haptics.play(allow ? .success : .failure) }
+ else { controller.verdictAllowed = nil; Haptics.play(.failure); tell("Can't reach your Mac. Try again.") }
+ }
+ }
+
+ // MARK: the iPhone's controls (its microphone button, composer and approval card), the same paths as the watch's touch
+
+ /// The microphone button went down: talk to the agent on screen (an approval of its on screen is what a yes or no answers).
+ func micDown() {
+ guard g.mode != .talk else { return }
+#if !os(watchOS)
+ // the first hold asks for the microphone; that hold doesn't record (hold again once it's allowed)
+ if !Recorder.fake && AVAudioApplication.shared.recordPermission == .undetermined {
+ Task { micAllowed = await Recorder.requestPermission(); if !micAllowed { tell(Self.micRefused) } }
+ return
+ }
+ micAllowed = AVAudioApplication.shared.recordPermission == .granted || Recorder.fake
+#endif
+ g = Gesture(); g.down = true; g.mode = .talk
+ g.approval = hub.state?.approvals.first(where: { $0.session == controller.agent })?.requestId
+ beginTalk()
+ }
+ /// It came up: send what was said, or throw it away (slid onto ×).
+ func micUp(cancel: Bool) {
+ g.down = false
+ guard g.mode == .talk else { return }
+ g.mode = .none; rig.talkSlide = 0
+ if cancel { cancelTalk() } else { endTalk() }
+ }
+ var listening: Bool { controller.talk == .listening }
+ /// Typed words, sent as if said; nil when they couldn't go.
+ func send(text: String, files: [String] = []) async -> RouteResult? {
+ controller.orderSent()
+ speaker.stop()
+ let r = await hub.say(text, agent: controller.agent, files: files)
+ if r == nil { Haptics.play(.failure); tell(hub.connected ? "Couldn't send that. Try again." : "Can't reach your Mac.") }
+ return r
+ }
+ /// Allow or deny an approval (the iPhone's card).
+ func decide(_ requestId: String, allow: Bool) { answer(allow, requestId) }
+ /// Stop reading aloud (the iPhone mutes when you start typing).
+ func hush() { speaker.stop() }
+
+ // MARK: self-test: synthetic touches through the real gesture path (launch with -selftest YES)
+
+ func selfTest(size: CGSize, settings: (Bool) -> Void) async {
+ func screen(_ x: Double, _ y: Double) -> CGPoint { let f = Renderer.fit(size); return CGPoint(x: f.ox + x * f.s, y: f.oy + y * f.s) }
+ func wait(_ s: Double) async { try? await Task.sleep(for: .milliseconds(Int(s * 1000))) }
+ func log(_ s: String) { FileHandle.standardError.write(("SELFTEST " + s + "\n").data(using: .utf8)!) }
+ try? await Task.sleep(for: .seconds(2))
+ let p = rig.pose()
+ log("screen \(size) state \(rig.state) character \(rig.character) mode \(rig.mode) at \(Int(p.cx)),\(Int(p.cy))")
+ // 0. hold to talk, slide onto ×, then onto ✓, then back onto × and let go: canceled, nothing sent
+ drag(screen(110, 120), in: size); await wait(0.7)
+ for i in 1...8 { drag(screen(110 - Double(i) * 7, 120), in: size); await wait(0.03) }
+ log("slide left: \(rig.talkSlide <= -Rig.armed ? "× armed" : "FAILED (\(rig.talkSlide))"), caption \(rig.caption)")
+ await wait(2.2)
+ for i in 1...16 { drag(screen(54 + Double(i) * 7, 120), in: size); await wait(0.03) }
+ log("slide right: \(rig.talkSlide >= Rig.armed ? "✓ armed" : "FAILED (\(rig.talkSlide))"), caption \(rig.caption)")
+ await wait(2.2)
+ for i in 1...16 { drag(screen(166 - Double(i) * 7, 120), in: size); await wait(0.03) }
+ _ = dragEnd(screen(54, 120), in: size); await wait(0.2)
+ log("let go on ×: talk \(controller.talk), caption \(rig.caption)")
+ await wait(1.5)
+ // 1. tap the character: a poke (in a pixel level, a jump)
+ let before = rig.W.pokes.count
+ drag(screen(p.cx, p.cy), in: size); await wait(0.1)
+ _ = dragEnd(screen(p.cx, p.cy), in: size)
+ log("poke: \(rig.W.pokes.count > before ? "ok" : "FAILED")")
+ await wait(1)
+ // 2. stroke across it: pet (happy target set while stroking)
+ drag(screen(p.cx - 20, p.cy), in: size)
+ for i in 1...8 { drag(screen(p.cx - 20 + Double(i) * 6, p.cy), in: size); await wait(0.02) }
+ let happy = rig.S.happy.t
+ _ = dragEnd(screen(p.cx + 28, p.cy), in: size)
+ log("pet: \(happy == 1 ? "ok" : "FAILED")")
+ await wait(0.8)
+ // 3. hold the lower screen: listening after 450 ms, thinking after release
+ drag(screen(99, 210), in: size); await wait(0.7)
+ log("hold to talk: \(controller.talk == .listening ? "listening" : "not listening (\(rig.caption))")")
+ _ = dragEnd(screen(99, 210), in: size); await wait(0.1)
+ log("release: talk \(controller.talk)")
+ await wait(1.5)
+ // 3b. held high up too (in the level, where a tap jumps): it talks
+ drag(screen(150, 70), in: size); await wait(0.7)
+ log("hold high up to talk: \(controller.talk == .listening ? "listening" : "not listening")")
+ _ = dragEnd(screen(150, 70), in: size); await wait(1.5)
+ // 4. the faces at the top left open the agents' list: a quick tap, a slow one, one a little off them
+ for (x, y, hold) in [(20.0, 24.0, 0.05), (26.0, 30.0, 0.7), (44.0, 40.0, 0.2)] {
+ drag(screen(x, y), in: size); await wait(hold)
+ let open = dragEnd(screen(x, y), in: size) == .settings
+ log("tap at \(Int(x)),\(Int(y)) held \(hold) s opens settings: \(open ? "ok" : "FAILED")")
+ }
+ settings(true); await wait(1.5); settings(false)
+ // 5. crown: in a pixel level it walks; elsewhere in a world it scrubs back
+ rig.crown(3); await wait(0.3)
+ log("crown: scrub \(Int(rig.W.scrub)) pt (mode \(rig.mode))")
+ log("stay-on call reaches watchOS: \(StayOn.set(idle: 15, sleepGesture: true) ? "ok" : "FAILED")")
+ log("done")
+ }
+
+ /// A light shake, then a hard one in every direction, every 12 s, as the motion sensors would report them, 50
+ /// samples a second (launch with -shakeDemo YES).
+ func shakeDemo() async {
+ func shake(_ seconds: Double, _ g: Double) async {
+ let n = Int(seconds * 50)
+ for i in 0..<n {
+ let t = Double(i) / 50
+ rig.motion(g * sin(t * TAU * 4.5), g * 0.8 * sin(t * TAU * 3.7 + 1), g * 0.7 * sin(t * TAU * 5.3 + 2))
+ try? await Task.sleep(for: .milliseconds(20))
+ }
+ rig.motion(0, 0, 0)
+ }
+ try? await Task.sleep(for: .seconds(2))
+ while true {
+ await shake(0.5, 1.5)
+ try? await Task.sleep(for: .seconds(4))
+ await shake(1.6, 3.6)
+ try? await Task.sleep(for: .seconds(6))
+ }
+ }
+
+ /// Simulator captures (-crownDemo YES): the crown turned up a dozen detents, held, let go; then down, let go.
+ func crownDemo() async {
+ func wait(_ s: Double) async { try? await Task.sleep(for: .milliseconds(Int(s * 1000))) }
+ await wait(2.5)
+ for _ in 0..<12 { crown(1); await wait(0.07) }
+ await wait(1.2); await wait(2.6) // held, then let go: it springs back
+ for _ in 0..<7 { crown(-1); await wait(0.08) }
+ await wait(2.8)
+ for _ in 0..<24 { crown(1); await wait(0.035) } // fast, all the way
+ await wait(3.5)
+ }
+
+ /// Simulator captures (-playDemo YES): a tap, a finger dragged across, the crown spun, a shake, as a person would.
+ func playDemo(size: CGSize) async {
+ func screen(_ x: Double, _ y: Double) -> CGPoint { let f = Renderer.fit(size); return CGPoint(x: f.ox + x * f.s, y: f.oy + y * f.s) }
+ func wait(_ s: Double) async { try? await Task.sleep(for: .milliseconds(Int(s * 1000))) }
+ func tap(_ x: Double, _ y: Double) async { drag(screen(x, y), in: size); await wait(0.08); _ = dragEnd(screen(x, y), in: size) }
+ await wait(2.5)
+ await tap(150, 190); await wait(2) // a tap
+ await tap(120, 40); await wait(2) // another, up high
+ let eye = rig.staged?.hit(CGPoint(x: 60, y: 112)) == true ? 60.0 : 55.0
+ await tap(eye, 112); await wait(1.6) // poke an eye
+ drag(screen(30, 200), in: size) // drag across
+ for i in 0..<70 { let u = Double(i) / 70; drag(screen(30 + 140 * u, 200 - 110 * sin(u * .pi)), in: size); await wait(0.03) }
+ _ = dragEnd(screen(170, 200), in: size)
+ await wait(1.5)
+ for i in 0..<120 { rig.W.padX = 0.55 * sin(Double(i) / 120 * TAU); await wait(0.03) } // tilt
+ rig.W.padX = 0; await wait(1.5)
+ for _ in 0..<16 { rig.crown(0.9); await wait(0.06) } // crown up: bubbles
+ await wait(3.5)
+ for _ in 0..<30 { rig.crown(-0.9); await wait(0.05) } // crown down: wind
+ await wait(3)
+ for i in 0..<70 { let t = Double(i) / 50; rig.motion(3.2 * sin(t * TAU * 4.5), 2.4 * sin(t * TAU * 3.7 + 1), 2 * sin(t * TAU * 5.3 + 2)); await wait(0.02) }
+ rig.motion(0, 0, 0) // shake
+ }
+
+ // MARK: motion: gravity for physics and the eyes; the watch's moves throw the character around
+
+ private func startMotion() {
+ guard motion.isDeviceMotionAvailable else { return }
+ motion.deviceMotionUpdateInterval = 1.0 / 50
+ motion.startDeviceMotionUpdates(to: .main) { [weak self] m, _ in
+ guard let self, let m else { return }
+ // the sensors' axes (y up the screen, z out of it) turned into the screen's (y down, z toward you)
+ self.rig.W.padX = m.gravity.x; self.rig.W.padY = -m.gravity.y
+ let a = m.userAcceleration
+ self.rig.motion(a.x, -a.y, a.z)
+ let w = m.rotationRate
+ StayOn.shared.motion(rotation: sqrt(w.x * w.x + w.y * w.y + w.z * w.z), accel: sqrt(a.x * a.x + a.y * a.y + a.z * a.z), gravityZ: m.gravity.z)
+ }
+ }
+}
+
+#if os(iOS)
+/// The iPhone's engine clock: a display link that calls ScreenModel.frame 30 times a second, or at the screen's own rate
+/// while a stage draws a live character big. Paused while the app is in the background, where it costs nothing.
+@MainActor
+final class EngineClock: NSObject {
+ private weak var model: ScreenModel?
+ private var link: CADisplayLink?
+ var fast: Bool { didSet { if fast != oldValue { pace() } } }
+
+ init(_ model: ScreenModel, fast: Bool) {
+ self.model = model; self.fast = fast
+ super.init()
+ let l = CADisplayLink(target: self, selector: #selector(tick(_:)))
+ link = l
+ pace()
+ l.isPaused = UIApplication.shared.applicationState == .background
+ l.add(to: .main, forMode: .common) // .common: it keeps going while you scroll
+ let nc = NotificationCenter.default
+ nc.addObserver(self, selector: #selector(background), name: UIApplication.didEnterBackgroundNotification, object: nil)
+ nc.addObserver(self, selector: #selector(foreground), name: UIApplication.willEnterForegroundNotification, object: nil)
+ }
+ private func pace() {
+ link?.preferredFrameRateRange = fast ? .default : CAFrameRateRange(minimum: 30, maximum: 30, preferred: 30)
+ }
+ @objc private func tick(_ l: CADisplayLink) {
+ guard let model else { l.invalidate(); return }
+ // the moment this frame will be on screen: the rig is where the stage draws it then
+ model.frame(Date(timeIntervalSinceNow: l.targetTimestamp - CACurrentMediaTime()))
+ }
+ @objc private func background() { link?.isPaused = true }
+ @objc private func foreground() { link?.isPaused = false }
+}
+#endif
+
+/// Frame timing and CPU for the event log, every 30 s while the screen is on: how often frames come, how long one
+/// takes to draw on the main thread, how many came late enough to see (over 50 ms), and how busy the app is.
+final class Perf {
+ private var n = 0, sum = 0.0, maxMs = 0.0, late = 0, active = 0.0, last: Date?, since = Date()
+ private var cpu0 = Perf.cpu()
+ func drew(_ ms: Double, at date: Date) {
+ n += 1; sum += ms; maxMs = max(maxMs, ms)
+ if let l = last {
+ let gap = date.timeIntervalSince(l)
+ if gap < 0.5 { active += gap; if gap > 0.05 { late += 1 } } // longer gaps: dimmed, or the card was up
+ }
+ last = date
+ }
+ func take() -> String? {
+ let now = Date(), wall = now.timeIntervalSince(since), c = Perf.cpu()
+ defer { n = 0; sum = 0; maxMs = 0; late = 0; active = 0; since = now; cpu0 = c }
+ guard n > 30, active > 1 else { return nil }
+ return String(format: "perf: %.0f fps over %.0f s on screen, frame %.1f ms avg, %.0f max, %d late; cpu %.0f%%",
+ Double(n) / active, active, sum / Double(n), maxMs, late, (c - cpu0) / wall * 100)
+ }
+ static func cpu() -> Double {
+ var u = rusage(); getrusage(RUSAGE_SELF, &u)
+ return Double(u.ru_utime.tv_sec + u.ru_stime.tv_sec) + Double(u.ru_utime.tv_usec + u.ru_stime.tv_usec) / 1e6
+ }
+}
diff --git a/app/ChumsWatch/Soul.swift b/app/ChumsWatch/Soul.swift
new file mode 100644
index 0000000..882d5d2
--- /dev/null
+++ b/app/ChumsWatch/Soul.swift
@@ -0,0 +1,526 @@
+import SwiftUI
+
+/// An agent, opened on the watch. What you can change about how it runs is in tiles at the top (what it runs on, its
+/// model, its permissions, its voice: each opens a list). Its soul is the text under them: what it does, what it hands
+/// off, how it talks, notes. At the bottom, hold the button and say what should be different: a separate model on the
+/// Mac turns it into a change, shown in plain words; Save keeps it (it applies from the agent's next order), Cancel
+/// drops it, Undo goes back one.
+struct SoulView: View {
+ let agent: AgentInfo
+ let model: ScreenModel
+ let hub: HubClient
+
+ enum Step: Equatable { case card, listening, writing, preview, clarify(String), saving, saved, failed(String) }
+ @State private var step = Step.card
+ @State private var card: SoulCard?
+ @State private var proposal: SoulProposal?
+ @State private var slide = 0.0 // the finger's slide while talking: −1 × … 1 ✓
+ @State private var pressing = false
+ @State private var holdStart: Task<Void, Never>?
+
+ var body: some View {
+ // one scroll: read it, and at the end, change it
+ ScrollViewReader { proxy in
+ ScrollView {
+ VStack(spacing: 8) {
+ Color.clear.frame(height: 0).id("top")
+ // who it is: its face and name
+ HStack(spacing: 9) {
+ AgentFace(character: agent.character, size: 32)
+ Text(shown?.name ?? agent.name).font(.system(size: 18, weight: .semibold)).foregroundStyle(Pal.white)
+ Spacer(minLength: 0)
+ }
+ .padding(.leading, 4)
+ // what you can change: each a tile that opens a list
+ runtimeTile
+ modelTile
+ permissionTile
+ voiceTile
+ if let m = message { messageTile(m).padding(.top, 4) }
+ // who it is: words on the page, no tiles
+ if let c = shown {
+ VStack(alignment: .leading, spacing: 10) {
+ part("What it does", c.owns, changed: step == .preview && c.owns != card?.owns)
+ part("Hands off", c.refers, changed: step == .preview && c.refers != card?.refers)
+ part("How it talks", c.voice, changed: step == .preview && c.voice != card?.voice)
+ part("Notes", c.body, changed: step == .preview && c.body != card?.body, lines: 8)
+ }
+ .padding(.horizontal, 6).padding(.top, 8)
+ } else { ProgressView().padding(.top, 8) }
+ // at the bottom: change it, or take the last change back
+ controls.padding(.top, 10)
+ if card?.canUndo == true && (step == .card || step == .saved) {
+ Button { Task { await undo() } } label: {
+ Label("Undo last change", systemImage: "arrow.uturn.backward").font(.system(size: 14, weight: .medium))
+ .foregroundStyle(Pal.white).frame(maxWidth: .infinity, minHeight: 38)
+ }
+ .buttonStyle(.plain).glassEffect(.regular.interactive(), in: Capsule())
+ }
+ Color.clear.frame(height: 0).id("end")
+ }
+ .padding(.horizontal, 2)
+ }
+ // Simulator captures: the scene driver scrolls, holds the button and saves as a finger would
+ .onChange(of: Capture.shared.soulScroll) { _, id in
+ guard let id else { return }
+ withAnimation(.easeInOut(duration: 1.1)) { proxy.scrollTo(id, anchor: id == "top" ? .top : .bottom) }
+ Capture.shared.soulScroll = nil
+ }
+ .onChange(of: Capture.shared.soulPress) { _, down in
+ guard let down else { return }
+ Capture.shared.soulPress = nil
+ if down {
+ guard [Step.card, .saved].contains(step) || isMessage(step), model.startSoulTalk() else { return }
+ pressing = true; step = .listening
+ } else {
+ pressing = false
+ guard step == .listening else { return }
+ slide = 0
+ Task { await finishTalking(cancel: false) }
+ }
+ }
+ .onChange(of: Capture.shared.soulSave) { _, on in
+ guard on else { return }
+ Capture.shared.soulSave = false
+ Task { await save() }
+ }
+ }
+ .defaultScrollAnchor(UserDefaults.standard.bool(forKey: "soulBottom") ? .bottom : .top) // Simulator captures
+ .opacity(step == .listening ? 0.2 : 1)
+ .overlay { if step == .listening { TalkBar(slide: slide, level: { model.talkLevel }) } }
+ .navigationTitle("Soul")
+ .task {
+ async let m = hub.models(), p = hub.permissions()
+ (models, permissions) = await (m, p)
+ }
+ .task {
+ card = await hub.soul(agent.id)
+ // Simulator captures: a typed instruction instead of a spoken one (-soulSay "…")
+ if let said = UserDefaults.standard.string(forKey: "soulSay"), step == .card {
+ step = .writing
+ if let r = await hub.soulFromText(said, agent: agent.id), r.proposal != nil { proposal = r; step = .preview }
+ else { step = .card }
+ }
+ }
+ }
+
+ private var shown: SoulCard? { step == .preview ? proposal?.soul ?? card : card }
+
+ /// What's going on, above the parts: the proposed change, a question back, saved, why it failed, or working on it.
+ private var message: (text: String, color: Color, busy: Bool)? {
+ switch step {
+ case .preview: return (proposal?.summary ?? "", Pal.white, false)
+ case .clarify(let q): return (q, Pal.amber, false)
+ case .saved: return ("Saved. \(card?.name ?? agent.name) follows it from its next order.", Pal.white, false)
+ case .failed(let why): return (why, Pal.red, false)
+ case .writing: return ("Writing the change…", Pal.gray, true)
+ case .saving: return ("Saving…", Pal.gray, true)
+ default: return nil
+ }
+ }
+ private func messageTile(_ m: (text: String, color: Color, busy: Bool)) -> some View {
+ HStack(alignment: .top, spacing: 8) {
+ if m.busy { ProgressView().frame(width: 16, height: 16) }
+ Text(m.text).font(.system(size: 15, weight: .medium)).foregroundStyle(m.color).fixedSize(horizontal: false, vertical: true)
+ Spacer(minLength: 0)
+ }
+ .padding(11)
+ .glassEffect(.regular.tint(.white.opacity(0.1)), in: RoundedRectangle(cornerRadius: 16, style: .continuous))
+ }
+
+ /// The characters, each its own agent, in the order the watch lists them first.
+ static let looks = ["noodle", "squint", "ray", "tangle", "peeps", "stretch", "crunch", "nana"]
+
+ /// A tile that opens a list: what it is, small, and its value under it.
+ private func tile(_ title: String, _ value: String) -> some View {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title).font(.system(size: 11, weight: .semibold)).foregroundStyle(Pal.gray)
+ Text(value).font(.system(size: 14, weight: .medium)).foregroundStyle(Pal.white).lineLimit(1)
+ }
+ Spacer(minLength: 0)
+ Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Pal.gray)
+ }
+ .padding(.horizontal, 11).padding(.vertical, 9)
+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
+ }
+
+ /// Its model and its permissions, as on the iPhone's card: a list for its runtime, its runtime's own setting first.
+ @State private var models: [String: ModelChoices]?
+ @State private var permissions: [String: PermissionChoices]?
+ @State private var pickedModel: String?? // picked here (until then, the hub's)
+ @State private var pickedPermission: String??
+ private var runtimeNow: String { runtime ?? agent.runtime ?? "claude" }
+ private func named(_ id: String?, in items: [ModelChoices.Model]?, default d: String?) -> String {
+ guard let items else { return " " }
+ if let id { return items.first { $0.id == id }?.name ?? id }
+ return d ?? "\(AgentRuntimes.name(runtimeNow))'s own"
+ }
+ private var modelTile: some View {
+ let c = models?[runtimeNow], now = pickedModel ?? agent.model
+ return NavigationLink {
+ ChoiceList(title: "Model", items: c?.models, defaultLabel: c?.default, runtime: runtimeNow,
+ footer: "It restarts on the model you pick. Its conversation carries on.",
+ picked: Binding(get: { now }, set: { pickedModel = .some($0) })) { await hub.setModel(agent.id, model: $0) }
+ } label: { tile("Model", named(now, in: c?.models, default: c?.default)) }
+ .buttonStyle(.plain)
+ }
+ @State private var choosingPermission = UserDefaults.standard.bool(forKey: "openPermissions") // Simulator captures
+ private var permissionTile: some View {
+ let c = permissions?[runtimeNow], now = pickedPermission ?? agent.permission
+ return Button { choosingPermission = true } label: { tile("Permissions", named(now, in: c?.modes, default: c?.default)) }
+ .buttonStyle(.plain)
+ .navigationDestination(isPresented: $choosingPermission) {
+ ChoiceList(title: "Permissions", items: c?.modes, defaultLabel: c?.default, runtime: runtimeNow,
+ footer: "It restarts with what you pick. Its conversation carries on.",
+ picked: Binding(get: { now }, set: { pickedPermission = .some($0) })) { await hub.setPermission(agent.id, mode: $0) }
+ }
+ }
+
+ /// What it runs on, as a row like its voice: a tap opens the two to pick from (AgentRuntimes).
+ @State private var runtime: String?
+ @State private var choosingRuntime = UserDefaults.standard.bool(forKey: "openRuntimes") // Simulator captures
+ private var runtimeTile: some View {
+ let current = runtime ?? agent.runtime ?? "claude"
+ return Button { choosingRuntime = true } label: { tile("Runs on", AgentRuntimes.name(current)) }
+ .buttonStyle(.plain)
+ .accessibilityIdentifier("runtime-row")
+ .navigationDestination(isPresented: $choosingRuntime) {
+ AgentRuntimes(agent: agent, hub: hub, picked: Binding(get: { current }, set: { runtime = $0; pickedModel = nil; pickedPermission = nil }))
+ }
+ }
+
+ /// Its voice on the Mac: a tap opens the voices (each plays a sample, a tap picks it).
+ @State private var voice: String?
+ private var voiceTile: some View {
+ let id = voice ?? agent.voice
+ return NavigationLink {
+ AgentVoices(agent: agent, hub: hub, picked: Binding(get: { voice ?? agent.voice }, set: { voice = $0 }))
+ } label: { tile("Voice", id.map(AgentVoices.label) ?? "The watch's own") }
+ .buttonStyle(.plain)
+ }
+
+ /// One part of the soul, as words on the page: its name small, the words under it; a part a change would touch is
+ /// white, with a mark beside its name.
+ @ViewBuilder private func part(_ label: String, _ value: String?, changed: Bool, lines: Int? = nil) -> some View {
+ if let value, !value.isEmpty {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 4) {
+ Text(label).font(.system(size: 11, weight: .semibold)).foregroundStyle(changed ? Pal.white : Pal.gray)
+ if changed { Circle().fill(Pal.white).frame(width: 4, height: 4) }
+ }
+ Text(value).font(.system(size: 15)).foregroundStyle(changed ? Pal.white : Color(white: 0.85))
+ .lineLimit(lines).fixedSize(horizontal: false, vertical: true)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ }
+ }
+
+ /// Save and Cancel for a proposed change; otherwise the button you hold to talk (× and ✓ show above your finger).
+ @ViewBuilder private var controls: some View {
+ if step == .preview {
+ HStack(spacing: 8) {
+ Button { Haptics.play(.click); proposal = nil; step = .card } label: {
+ Text("Cancel").font(.system(size: 15, weight: .semibold)).foregroundStyle(Pal.white).frame(maxWidth: .infinity, minHeight: 40)
+ }
+ .buttonStyle(.plain).glassEffect(.regular.interactive(), in: Capsule())
+ Button { Task { await save() } } label: {
+ Text("Save").font(.system(size: 15, weight: .semibold)).foregroundStyle(.black).frame(maxWidth: .infinity, minHeight: 40)
+ }
+ .buttonStyle(.plain).glassEffect(.regular.tint(.white).interactive(), in: Capsule())
+ }
+ } else {
+ HStack(spacing: 7) {
+ Image(systemName: "mic.fill").font(.system(size: 13, weight: .semibold))
+ Text("Hold to change").font(.system(size: 15, weight: .semibold))
+ }
+ .foregroundStyle(Pal.white).opacity(step == .listening ? 0 : 1)
+ .frame(maxWidth: .infinity, minHeight: 42)
+ .glassEffect(step == .listening ? .regular.tint(.white.opacity(0.18)) : .regular.interactive(), in: Capsule())
+ .contentShape(Capsule())
+ .gesture(DragGesture(minimumDistance: 0)
+ .onChanged { v in
+ if !pressing {
+ pressing = true
+ guard [Step.card, .saved].contains(step) || isMessage(step) else { return }
+ holdStart = Task {
+ try? await Task.sleep(for: .milliseconds(180))
+ guard !Task.isCancelled, pressing, model.startSoulTalk() else { return }
+ step = .listening
+ }
+ }
+ if step == .listening {
+ let s = clamp(v.translation.width / 46, -1, 1)
+ if (abs(s) >= Rig.armed) != (abs(slide) >= Rig.armed) { Haptics.play(.click) }
+ slide = s
+ }
+ }
+ .onEnded { _ in
+ pressing = false; holdStart?.cancel()
+ guard step == .listening else { return }
+ let cancel = slide <= -Rig.armed
+ slide = 0
+ Task { await finishTalking(cancel: cancel) }
+ })
+ .disabled(step == .writing || step == .saving)
+ .accessibilityLabel("Hold to change \(agent.name)'s soul")
+ }
+ }
+
+ private func isMessage(_ s: Step) -> Bool { if case .clarify = s { return true }; if case .failed = s { return true }; return false }
+
+ private func finishTalking(cancel: Bool) async {
+ step = .writing
+ guard let r = await model.endSoulTalk(cancel: cancel, agent: agent.id) else { step = .card; return }
+ if let e = r.error { Haptics.play(.failure); step = .failed(e) }
+ else if let q = r.clarify { Haptics.play(.notification); step = .clarify(q) }
+ else if r.proposal != nil { Haptics.play(.notification); proposal = r; step = .preview }
+ else { step = .failed("Couldn't reach your Mac.") }
+ }
+
+ private func save() async {
+ guard let id = proposal?.proposal else { return }
+ step = .saving
+ let (c, err) = await hub.saveSoul(agent.id, proposal: id)
+ if let c { Haptics.play(.success); card = c; proposal = nil; step = .saved; hub.event("soul saved: \(agent.id)") }
+ else { Haptics.play(.failure); proposal = nil; step = .failed(err ?? "Couldn't save it.") }
+ }
+
+ private func undo() async {
+ step = .saving
+ let (c, err) = await hub.undoSoul(agent.id)
+ if let c { Haptics.play(.click); card = c; step = .card } else { step = .failed(err ?? "Couldn't undo it.") }
+ }
+}
+
+/// × · your voice · ✓, as on the main screen: the side your finger slides toward grows, the other fades.
+struct TalkBar: View {
+ let slide: Double
+ let level: () -> Double
+ /// A bar of the waveform: taller in the middle, moving with your voice, and a little even in a pause.
+ private func bar(_ i: Int, _ t: Double) -> Double {
+ let c: Double = 1 - abs(Double(i) - 5) / 5.5
+ let wob: Double = 0.5 + 0.5 * sin(t * (7.3 + Double(i) * 0.9) + Double(i) * 1.7)
+ let loud: Double = 0.12 + 0.88 * level()
+ return 3 + loud * (6 + 15 * c) * (0.55 + 0.45 * wob)
+ }
+ var body: some View {
+ TimelineView(.animation) { tl in
+ let t = tl.date.timeIntervalSinceReferenceDate, cancelK = clamp(-slide / Rig.armed, 0, 1), sendK = clamp(slide / Rig.armed, 0, 1)
+ HStack(spacing: 10) {
+ Image(systemName: "xmark").font(.system(size: 13 + 2 * cancelK, weight: .bold)).foregroundStyle(Pal.white)
+ .frame(width: 30 + 6 * cancelK, height: 30 + 6 * cancelK).background(Color(white: 0.3 + 0.12 * cancelK), in: Circle())
+ .opacity(1 - 0.5 * sendK)
+ HStack(spacing: 2.5) {
+ ForEach(0..<11, id: \.self) { i in Capsule().fill(Pal.white).frame(width: 2.6, height: bar(i, t)) }
+ }
+ .frame(height: 26)
+ Image(systemName: "checkmark").font(.system(size: 13 + 2 * sendK, weight: .bold)).foregroundStyle(.black)
+ .frame(width: 30 + 6 * sendK, height: 30 + 6 * sendK).background(Pal.white, in: Circle())
+ .opacity(1 - 0.5 * cancelK)
+ }
+ }
+ }
+}
+
+/// One of an agent's settings picked from a list on the watch (its model, its permissions): its runtime's own setting
+/// first (Default), then each choice with a line about it, the current one checked. A tap switches it: the agent
+/// restarts with it, and its conversation carries on.
+struct ChoiceList: View {
+ let title: String
+ let items: [ModelChoices.Model]?
+ let defaultLabel: String?
+ let runtime: String
+ let footer: String
+ @Binding var picked: String?
+ let apply: (String?) async -> String? // nil once it's set, else why not
+ @State private var busy: String??
+ @State private var error: String?
+
+ var body: some View {
+ List {
+ if let items {
+ Section {
+ row(nil, "Default", about: defaultLabel.map { "\(AgentRuntimes.name(runtime))'s setting: \($0)" })
+ ForEach(items) { m in row(m.id, m.name, about: m.about) }
+ } footer: { Text(footer) }
+ } else {
+ Text(error ?? "Asking your Mac…").foregroundStyle(Pal.gray)
+ }
+ if let error, items != nil { Text(error).font(.system(size: 12)).foregroundStyle(Pal.amber) }
+ }
+ .navigationTitle(title)
+ }
+
+ private func row(_ id: String?, _ name: String, about: String?) -> some View {
+ Button {
+ guard busy == nil, id != picked else { return }
+ Haptics.play(.click); busy = .some(id); error = nil
+ Task {
+ if let e = await apply(id) { error = e; Haptics.play(.failure) }
+ else { picked = id; Haptics.play(.success) }
+ busy = nil
+ }
+ } label: {
+ HStack {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(name).foregroundStyle(Pal.white)
+ if let about { Text(about).font(.system(size: 12)).foregroundStyle(Pal.gray) }
+ }
+ Spacer()
+ if busy == .some(id) { ProgressView().frame(width: 16, height: 16) }
+ else if picked == id { Image(systemName: "checkmark").foregroundStyle(Pal.clay) }
+ }
+ }
+ .disabled(busy != nil)
+ .accessibilityAddTraits(picked == id ? .isSelected : [])
+ }
+}
+
+/// What an agent runs on: Claude Code or Codex, one under the other with the current one checked. A tap switches it:
+/// the hub stops the one and starts the other, and each keeps its own thread for when you switch back. One that isn't
+/// installed on the Mac is dimmed.
+struct AgentRuntimes: View {
+ let agent: AgentInfo
+ let hub: HubClient
+ @Binding var picked: String
+ @State private var switching: String?
+ @State private var error: String?
+
+ static let all = ["claude", "codex"]
+ static func name(_ id: String) -> String { id == "codex" ? "Codex" : "Claude Code" }
+#if os(watchOS)
+ private static let check = Pal.clay
+#else
+ private static let check = Color.white
+#endif
+
+ var body: some View {
+ let installed = hub.state?.runtimes ?? Self.all
+ List {
+ Section {
+ ForEach(Self.all, id: \.self) { id in
+ let can = installed.contains(id)
+ Button { pick(id, can: can) } label: {
+ HStack {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(Self.name(id)).foregroundStyle(can ? Pal.white : Pal.gray)
+ if !can { Text("Not installed on your Mac").font(.system(size: 12)).foregroundStyle(Pal.gray) }
+ }
+ Spacer()
+ if switching == id { ProgressView().frame(width: 16, height: 16) }
+ else if picked == id { Image(systemName: "checkmark").foregroundStyle(Self.check) }
+ }
+ }
+ .disabled(switching != nil)
+ .accessibilityAddTraits(picked == id ? .isSelected : [])
+ }
+ } footer: {
+ Text("It stops one and starts the other. Each keeps its own conversation.")
+ }
+ if let error { Text(error).font(.system(size: 12)).foregroundStyle(Pal.amber) }
+ }
+ .navigationTitle("Runs on")
+ }
+
+ private func pick(_ id: String, can: Bool) {
+ guard id != picked, switching == nil else { return }
+ guard can else { error = "\(Self.name(id)) isn't installed on your Mac."; Haptics.play(.failure); return }
+ Haptics.play(.click); switching = id; error = nil
+ Task {
+ if let e = await hub.setRuntime(agent.id, runtime: id) { error = e; Haptics.play(.failure) }
+ else { picked = id; Haptics.play(.success) }
+ switching = nil
+ }
+ }
+}
+
+/// The voices the Mac speaks in (Kokoro's English ones), British first: a tap plays a sample line in that voice and
+/// makes it this agent's.
+struct AgentVoices: View {
+ let agent: AgentInfo
+ let hub: HubClient
+ @Binding var picked: String?
+ @State private var voices: [VoiceInfo]?
+ @State private var speaker = Speaker()
+ @State private var error: String?
+ @State private var playing: String?
+
+#if os(watchOS)
+ private static let check = Pal.clay
+ private static let small = Font.system(size: 12)
+ private static let quiet = Pal.gray
+#else
+ private static let check = Color.white // the iPhone's colours are white and grays
+ private static let small = Font.footnote // text styles: they follow the text size
+ private static let quiet = Ink.quiet
+#endif
+ /// "Lily, British" from "bf_lily".
+ static func label(_ id: String) -> String {
+ let name = id.split(separator: "_").last.map { $0.prefix(1).uppercased() + $0.dropFirst() } ?? id
+ return "\(name), \(id.hasPrefix("b") ? "British" : "American")"
+ }
+
+ var body: some View {
+ List {
+ if let voices {
+ ForEach(["British", "American"], id: \.self) { accent in
+ Section(accent) {
+ ForEach(voices.filter { $0.accent == accent }) { v in
+ voiceRow(v)
+ }
+ }
+ #if os(iOS)
+ .cardRows() // the Model page's rows
+ #endif
+ }
+ } else {
+ Text(error ?? "Asking your Mac…").foregroundStyle(Self.quiet)
+ #if os(iOS)
+ .listRowBackground(Color.clear)
+ #endif
+ }
+ if let error, voices != nil {
+ Text(error).font(Self.small).foregroundStyle(Pal.amber)
+ #if os(iOS)
+ .listRowBackground(Color.clear)
+ #endif
+ }
+ }
+ .navigationTitle("Voice")
+ .task { voices = await hub.voices(); if voices == nil { error = "Can't reach your Mac" } }
+ }
+
+ private func voiceRow(_ v: VoiceInfo) -> some View {
+ Button { pick(v) } label: {
+ HStack {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(v.name)
+ #if os(iOS)
+ .foregroundStyle(.white) // not the tint a list gives a button
+ #endif
+ Text("\(v.gender), grade \(v.grade)").font(Self.small).foregroundStyle(Self.quiet)
+ }
+ Spacer()
+ #if os(iOS)
+ if playing == v.id { ProgressView().tint(.white) }
+ else if picked == v.id { Image(systemName: "checkmark").font(.body.weight(.semibold)).foregroundStyle(Self.check) }
+ #else
+ if playing == v.id { ProgressView().frame(width: 16, height: 16) }
+ else if picked == v.id { Image(systemName: "checkmark").foregroundStyle(Self.check) }
+ #endif
+ }
+ }
+ }
+
+ private func pick(_ v: VoiceInfo) {
+ Haptics.play(.click); playing = v.id; error = nil
+ Task {
+ if let e = await hub.setVoice(agent.id, voice: v.id) { error = e; playing = nil; Haptics.play(.failure); return }
+ picked = v.id
+ if let d = await hub.speech("/v1/voices/\(v.id)/sample") { _ = speaker.play(d) }
+ playing = nil
+ }
+ }
+}
diff --git a/app/ChumsWatch/StayOn.swift b/app/ChumsWatch/StayOn.swift
new file mode 100644
index 0000000..c882f0e
--- /dev/null
+++ b/app/ChumsWatch/StayOn.swift
@@ -0,0 +1,79 @@
+import Foundation
+import ObjectiveC
+
+#if os(watchOS)
+
+/// Keeping the screen on while you hold the watch and look at it, and letting it sleep when it's put down.
+///
+/// watchOS has no public way to do this, and no way to fake a touch. But WatchKit's own `isAutorotating` works by
+/// calling a method of the app object watchOS runs every watch app on (PepperUICore's PUICApplication):
+/// `setExtendedIdleTime:disablesSleepGesture:wantsAutorotation:`, with 23 s and the wrist-down gesture off when on,
+/// 15 s and the gesture on when off (WatchKit's disassembly). We call the same method with our own idle time, without
+/// turning the picture. It's not public API, which is fine for an app you build and sign yourself (it never goes to the App Store).
+///
+/// Held: the watch moves a little all the time (your hand is never still) and its screen faces up toward you. Hanging
+/// from the keys or in a pocket it faces sideways; on a table it doesn't move.
+@MainActor
+final class StayOn {
+ static let shared = StayOn()
+ var onEvent: ((String) -> Void)?
+ var enabled = true { didSet { if !enabled { apply(held: false, force: true) } } }
+
+ private var lastMoved = Date.distantPast, facingSince: Date?, notFacingSince: Date?, current: Bool?, lastSet = Date.distantPast, flip = false
+ /// The last touch or crown (the app tells it): the idle countdown runs from there.
+ var lastInput = Date()
+ static let heldIdle = 600.0, restIdle = 20.0
+
+ /// Every motion sample: rotation rate in rad/s, the watch's own acceleration in g, gravity's z (−1: screen up).
+ func motion(rotation: Double, accel: Double, gravityZ: Double) {
+ let now = Date()
+ if rotation > 0.06 || accel > 0.03 { lastMoved = now }
+ if gravityZ < -0.45 { facingSince = facingSince ?? now; notFacingSince = nil } else { notFacingSince = notFacingSince ?? now; if gravityZ > -0.3 { facingSince = nil } }
+ guard enabled else { return }
+ // quick to decide it's held, slow to decide it isn't (a glance away or a still moment isn't putting it down):
+ // held once it faces you for half a second while moving; let go after 12 s without moving or 4 s facing away
+ let moving = now.timeIntervalSince(lastMoved) < 12
+ let held = current == true
+ ? moving && (notFacingSince.map { now.timeIntervalSince($0) < 4 } ?? true)
+ : moving && (facingSince.map { now.timeIntervalSince($0) > 0.5 } ?? false)
+ // while held, set it again every 30 s (alternating a hair), in case a new value restarts the countdown
+ if held != current || (held && now.timeIntervalSince(lastSet) > 30) { apply(held: held) }
+ }
+
+ /// The screen woke: start from the resting idle time until the motion says it's held.
+ func woke() { current = nil }
+
+ private func apply(held: Bool, force: Bool = false) {
+ let first = current != held
+ current = held; lastSet = Date(); flip.toggle()
+ // put down, it sleeps 20 s from now (an idle time shorter than the time since your last touch sleeps at once)
+ let rest = Date().timeIntervalSince(lastInput) + Self.restIdle
+ let idle = held ? Self.heldIdle + (flip ? 0.5 : 0) : (enabled ? rest : 15)
+ guard Self.set(idle: idle, sleepGesture: !held) else { if first { onEvent?("stay on: not available on this watchOS") }; return }
+ if first || force { onEvent?(held ? "stay on: held and facing you, screen stays on (idle \(Int(idle)) s, no wrist-down dim)" : "stay on: put down, sleeps in \(Int(Self.restIdle)) s") }
+ }
+
+ private typealias SetIdle = @convention(c) (AnyObject, Selector, Double, Bool, Bool) -> Void
+ /// PUICApplication.sharedPUICApplication.setExtendedIdleTime(idle, disablesSleepGesture: !sleepGesture, wantsAutorotation: false)
+ @discardableResult static func set(idle: Double, sleepGesture: Bool) -> Bool {
+ guard let cls = NSClassFromString("PUICApplication") as? NSObject.Type else { return false }
+ let shared = NSSelectorFromString("sharedPUICApplication"), sel = NSSelectorFromString("setExtendedIdleTime:disablesSleepGesture:wantsAutorotation:")
+ guard cls.responds(to: shared), let app = cls.perform(shared)?.takeUnretainedValue() as? NSObject, app.responds(to: sel) else { return false }
+ unsafeBitCast(app.method(for: sel), to: SetIdle.self)(app, sel, idle, !sleepGesture, false)
+ return true
+ }
+}
+
+#else
+/// The iPhone keeps its own screen on; the shared screen model only tells it things.
+@MainActor
+final class StayOn {
+ static let shared = StayOn()
+ var onEvent: ((String) -> Void)?
+ var enabled = false
+ var lastInput = Date()
+ func woke() {}
+ func motion(rotation: Double, accel: Double, gravityZ: Double) {}
+ @discardableResult static func set(idle: Double, sleepGesture: Bool) -> Bool { false }
+}
+#endif
diff --git a/app/ChumsWatch/Voice.swift b/app/ChumsWatch/Voice.swift
new file mode 100644
index 0000000..bc06f07
--- /dev/null
+++ b/app/ChumsWatch/Voice.swift
@@ -0,0 +1,105 @@
+import AVFoundation
+
+/// Push-to-talk capture: 16 kHz mono AAC, the smallest file Whisper still reads well.
+final class Recorder {
+ private var recorder: AVAudioRecorder?
+ /// Simulator captures (-fakeVoice YES): no microphone at all (the Simulator stalls seconds reopening it), just an
+ /// empty clip as long as the hold; the stand-in hub doesn't listen to it.
+ static var fake = false
+ private var fakeClip: (url: URL, start: Date)?
+
+ static func requestPermission() async -> Bool {
+ await withCheckedContinuation { cont in
+ AVAudioApplication.requestRecordPermission { cont.resume(returning: $0) }
+ }
+ }
+
+ func start() throws {
+ if Self.fake {
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("utterance-\(UUID().uuidString).m4a")
+ try Data().write(to: url); fakeClip = (url, Date()); return
+ }
+ let session = AVAudioSession.sharedInstance()
+ try session.setCategory(.playAndRecord, mode: .default, options: [])
+ try session.setActive(true)
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("utterance-\(UUID().uuidString).m4a")
+ let settings: [String: Any] = [
+ AVFormatIDKey: kAudioFormatMPEG4AAC,
+ AVSampleRateKey: 16_000,
+ AVNumberOfChannelsKey: 1,
+ AVEncoderAudioQualityKey: AVAudioQuality.medium.rawValue,
+ ]
+ let r = try AVAudioRecorder(url: url, settings: settings)
+ r.isMeteringEnabled = true
+ guard r.record() else { throw NSError(domain: "Chums", code: 1) }
+ recorder = r
+ }
+
+ /// Voice level 0…1 from the input meter, for the character to pulse with.
+ var level: Double? {
+ guard let r = recorder, r.isRecording else { return nil }
+ r.updateMeters()
+ let db = Double(r.averagePower(forChannel: 0)) // −160 … 0 dBFS
+ return min(1, max(0, (db + 50) / 40))
+ }
+
+ /// Returns the file and how long it ran; nil if nothing was recording.
+ func stop() -> (url: URL, seconds: TimeInterval)? {
+ if let f = fakeClip { fakeClip = nil; return (f.url, Date().timeIntervalSince(f.start)) }
+ guard let r = recorder else { return nil }
+ let seconds = r.currentTime
+ r.stop()
+ recorder = nil
+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) // the mic is off between holds
+ return (r.url, seconds)
+ }
+}
+
+/// Speaks replies through the watch speaker (or AirPods when connected).
+final class Speaker: NSObject, AVSpeechSynthesizerDelegate, AVAudioPlayerDelegate {
+ private let synth = AVSpeechSynthesizer()
+ private var player: AVAudioPlayer?
+ var onFinish: (() -> Void)?
+ override init() { super.init(); synth.delegate = self }
+ func speechSynthesizer(_ s: AVSpeechSynthesizer, didFinish u: AVSpeechUtterance) { DispatchQueue.main.async { self.onFinish?() } }
+ func audioPlayerDidFinishPlaying(_ p: AVAudioPlayer, successfully: Bool) { DispatchQueue.main.async { self.onFinish?() } }
+
+ /// Plays a reply's voice rendered on the Mac; false if it can't, so the caller falls back to `speak`.
+ func play(_ data: Data) -> Bool {
+ let session = AVAudioSession.sharedInstance()
+ try? session.setCategory(.playback, mode: .spokenAudio, options: [])
+ try? session.setActive(true)
+ synth.stopSpeaking(at: .immediate); player?.stop()
+ guard let p = try? AVAudioPlayer(data: data) else { return false }
+ p.delegate = self; player = p
+ return p.play()
+ }
+
+ func speak(_ text: String, voice id: String? = nil) {
+ let session = AVAudioSession.sharedInstance()
+ try? session.setCategory(.playback, mode: .spokenAudio, options: [])
+ try? session.setActive(true)
+ let u = AVSpeechUtterance(string: text)
+ u.voice = Self.voice(id ?? UserDefaults.standard.string(forKey: "watchVoice"))
+ u.rate = 0.52
+ synth.stopSpeaking(at: .immediate); player?.stop()
+ synth.speak(u)
+ }
+
+ /// The watch voice chosen in Settings (Watch voice), else the system's US English one.
+ static func voice(_ id: String?) -> AVSpeechSynthesisVoice? {
+ id.flatMap { AVSpeechSynthesisVoice(identifier: $0) } ?? AVSpeechSynthesisVoice(language: "en-US")
+ }
+
+ /// The English voices installed on the watch, best first (premium, enhanced, then default), novelty voices left out.
+ static var englishVoices: [AVSpeechSynthesisVoice] {
+ AVSpeechSynthesisVoice.speechVoices()
+ .filter { $0.language.hasPrefix("en") && !$0.voiceTraits.contains(.isNoveltyVoice) }
+ .sorted { ($0.quality.rawValue, $1.name) > ($1.quality.rawValue, $0.name) }
+ }
+ static func qualityName(_ v: AVSpeechSynthesisVoice) -> String {
+ switch v.quality { case .premium: return "Premium"; case .enhanced: return "Enhanced"; default: return "Default" }
+ }
+
+ func stop() { synth.stopSpeaking(at: .immediate); player?.stop(); player = nil }
+}
diff --git a/app/ChumsWatch/noodle-shapes.bin b/app/ChumsWatch/noodle-shapes.bin
new file mode 100644
index 0000000..234194b
Binary files /dev/null and b/app/ChumsWatch/noodle-shapes.bin differ
diff --git a/app/ChumsWidget/ChumsWidget.swift b/app/ChumsWidget/ChumsWidget.swift
new file mode 100644
index 0000000..74ac8df
--- /dev/null
+++ b/app/ChumsWidget/ChumsWidget.swift
@@ -0,0 +1,65 @@
+import WidgetKit
+import SwiftUI
+
+/// Chums on the watch face and in the Smart Stack: its mark, and one tap opens Chums. It's there for the moments Chums
+/// isn't in front: after a crown press, or after the watch restarts (an app can't start itself).
+@main
+struct ChumsWidget: Widget {
+ var body: some WidgetConfiguration {
+ StaticConfiguration(kind: "chums", provider: Provider()) { _ in ChumsWidgetView() }
+ .configurationDisplayName("Chums")
+ .description("Opens Chums, where you talk to your coding agents.")
+ .supportedFamilies([.accessoryCircular, .accessoryRectangular, .accessoryCorner, .accessoryInline])
+ }
+}
+
+struct Entry: TimelineEntry { let date: Date }
+
+struct Provider: TimelineProvider {
+ func placeholder(in context: Context) -> Entry { Entry(date: .now) }
+ func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { completion(Entry(date: .now)) }
+ func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
+ completion(Timeline(entries: [Entry(date: .now)], policy: .never))
+ }
+}
+
+struct ChumsWidgetView: View {
+ @Environment(\.widgetFamily) private var family
+
+ var body: some View {
+ Group {
+ switch family {
+ case .accessoryRectangular:
+ HStack(spacing: 8) {
+ ChumsMark().frame(width: 40, height: 28)
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Chums").font(.headline)
+ Text("Open").font(.caption2).foregroundStyle(.secondary)
+ }
+ Spacer(minLength: 0)
+ }
+ case .accessoryInline:
+ Text("Chums")
+ case .accessoryCorner:
+ ChumsMark().padding(6)
+ default:
+ ChumsMark().padding(9)
+ }
+ }
+ .containerBackground(for: .widget) { Color.black }
+ }
+}
+
+/// The Chums mark: two eyes on black, like Peeps.
+struct ChumsMark: View {
+ var body: some View {
+ Canvas { ctx, size in
+ let h = min(size.height * 0.8, size.width * 0.5), w = h * 0.62, gap = w * 0.7
+ for dx: CGFloat in [-1, 1] {
+ let r = CGRect(x: size.width / 2 + dx * (gap + w) / 2 - w / 2, y: (size.height - h) / 2, width: w, height: h)
+ ctx.fill(Path(roundedRect: r, cornerRadius: w / 2), with: .color(.white))
+ }
+ }
+ .widgetAccentable()
+ }
+}
diff --git a/app/Shared/Characters.xcassets/Contents.json b/app/Shared/Characters.xcassets/Contents.json
new file mode 100644
index 0000000..73c0059
--- /dev/null
+++ b/app/Shared/Characters.xcassets/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/app/Shared/Characters.xcassets/avatar-crunch.imageset/Contents.json b/app/Shared/Characters.xcassets/avatar-crunch.imageset/Contents.json
new file mode 100644
index 0000000..efbdd4d
--- /dev/null
+++ b/app/Shared/Characters.xcassets/avatar-crunch.imageset/Contents.json
@@ -0,0 +1 @@
+{ "images" : [ { "filename" : "avatar-crunch.png", "idiom" : "universal" } ], "info" : { "author" : "xcode", "version" : 1 } }
diff --git a/app/Shared/Characters.xcassets/avatar-crunch.imageset/avatar-crunch.png b/app/Shared/Characters.xcassets/avatar-crunch.imageset/avatar-crunch.png
new file mode 100644
index 0000000..c2a135d
Binary files /dev/null and b/app/Shared/Characters.xcassets/avatar-crunch.imageset/avatar-crunch.png differ
diff --git a/app/Shared/Characters.xcassets/avatar-nana.imageset/Contents.json b/app/Shared/Characters.xcassets/avatar-nana.imageset/Contents.json
new file mode 100644
index 0000000..e71fcee
--- /dev/null
+++ b/app/Shared/Characters.xcassets/avatar-nana.imageset/Contents.json
@@ -0,0 +1 @@
+{ "images" : [ { "filename" : "avatar-nana.png", "idiom" : "universal" } ], "info" : { "author" : "xcode", "version" : 1 } }
diff --git a/app/Shared/Characters.xcassets/avatar-nana.imageset/avatar-nana.png b/app/Shared/Characters.xcassets/avatar-nana.imageset/avatar-nana.png
new file mode 100644
index 0000000..5a9b5b1
Binary files /dev/null and b/app/Shared/Characters.xcassets/avatar-nana.imageset/avatar-nana.png differ
diff --git a/app/Shared/Characters.xcassets/avatar-noodle.imageset/Contents.json b/app/Shared/Characters.xcassets/avatar-noodle.imageset/Contents.json
new file mode 100644
index 0000000..342a61d
--- /dev/null
+++ b/app/Shared/Characters.xcassets/avatar-noodle.imageset/Contents.json
@@ -0,0 +1 @@
+{"images": [{"filename": "avatar-noodle.png", "idiom": "universal"}], "info": {"author": "xcode", "version": 1}}
\ No newline at end of file
diff --git a/app/Shared/Characters.xcassets/avatar-noodle.imageset/avatar-noodle.png b/app/Shared/Characters.xcassets/avatar-noodle.imageset/avatar-noodle.png
new file mode 100644
index 0000000..0bca84b
Binary files /dev/null and b/app/Shared/Characters.xcassets/avatar-noodle.imageset/avatar-noodle.png differ
diff --git a/app/Shared/Characters.xcassets/avatar-peeps.imageset/Contents.json b/app/Shared/Characters.xcassets/avatar-peeps.imageset/Contents.json
new file mode 100644
index 0000000..6f6e13c
--- /dev/null
+++ b/app/Shared/Characters.xcassets/avatar-peeps.imageset/Contents.json
@@ -0,0 +1 @@
+{ "images" : [ { "filename" : "avatar-peeps.png", "idiom" : "universal" } ], "info" : { "author" : "xcode", "version" : 1 } }
diff --git a/app/Shared/Characters.xcassets/avatar-peeps.imageset/avatar-peeps.png b/app/Shared/Characters.xcassets/avatar-peeps.imageset/avatar-peeps.png
new file mode 100644
index 0000000..a632d03
Binary files /dev/null and b/app/Shared/Characters.xcassets/avatar-peeps.imageset/avatar-peeps.png differ
diff --git a/app/Shared/Characters.xcassets/avatar-ray.imageset/Contents.json b/app/Shared/Characters.xcassets/avatar-ray.imageset/Contents.json
new file mode 100644
index 0000000..7c76fb1
--- /dev/null
+++ b/app/Shared/Characters.xcassets/avatar-ray.imageset/Contents.json
@@ -0,0 +1 @@
+{"images": [{"filename": "avatar-ray.png", "idiom": "universal"}], "info": {"author": "xcode", "version": 1}}
\ No newline at end of file
diff --git a/app/Shared/Characters.xcassets/avatar-ray.imageset/avatar-ray.png b/app/Shared/Characters.xcassets/avatar-ray.imageset/avatar-ray.png
new file mode 100644
index 0000000..4cfafec
Binary files /dev/null and b/app/Shared/Characters.xcassets/avatar-ray.imageset/avatar-ray.png differ
diff --git a/app/Shared/Characters.xcassets/avatar-squint.imageset/Contents.json b/app/Shared/Characters.xcassets/avatar-squint.imageset/Contents.json
new file mode 100644
index 0000000..13c7553
--- /dev/null
+++ b/app/Shared/Characters.xcassets/avatar-squint.imageset/Contents.json
@@ -0,0 +1 @@
+{"images": [{"filename": "avatar-squint.png", "idiom": "universal"}], "info": {"author": "xcode", "version": 1}}
\ No newline at end of file
diff --git a/app/Shared/Characters.xcassets/avatar-squint.imageset/avatar-squint.png b/app/Shared/Characters.xcassets/avatar-squint.imageset/avatar-squint.png
new file mode 100644
index 0000000..23326e0
Binary files /dev/null and b/app/Shared/Characters.xcassets/avatar-squint.imageset/avatar-squint.png differ
diff --git a/app/Shared/Characters.xcassets/avatar-stretch.imageset/Contents.json b/app/Shared/Characters.xcassets/avatar-stretch.imageset/Contents.json
new file mode 100644
index 0000000..6aecd49
--- /dev/null
+++ b/app/Shared/Characters.xcassets/avatar-stretch.imageset/Contents.json
@@ -0,0 +1 @@
+{ "images" : [ { "filename" : "avatar-stretch.png", "idiom" : "universal" } ], "info" : { "author" : "xcode", "version" : 1 } }
diff --git a/app/Shared/Characters.xcassets/avatar-stretch.imageset/avatar-stretch.png b/app/Shared/Characters.xcassets/avatar-stretch.imageset/avatar-stretch.png
new file mode 100644
index 0000000..868e472
Binary files /dev/null and b/app/Shared/Characters.xcassets/avatar-stretch.imageset/avatar-stretch.png differ
diff --git a/app/Shared/Characters.xcassets/avatar-tangle.imageset/Contents.json b/app/Shared/Characters.xcassets/avatar-tangle.imageset/Contents.json
new file mode 100644
index 0000000..1a5a301
--- /dev/null
+++ b/app/Shared/Characters.xcassets/avatar-tangle.imageset/Contents.json
@@ -0,0 +1 @@
+{"images": [{"filename": "avatar-tangle.png", "idiom": "universal"}], "info": {"author": "xcode", "version": 1}}
\ No newline at end of file
diff --git a/app/Shared/Characters.xcassets/avatar-tangle.imageset/avatar-tangle.png b/app/Shared/Characters.xcassets/avatar-tangle.imageset/avatar-tangle.png
new file mode 100644
index 0000000..e88cca9
Binary files /dev/null and b/app/Shared/Characters.xcassets/avatar-tangle.imageset/avatar-tangle.png differ
diff --git a/app/project.yml b/app/project.yml
new file mode 100644
index 0000000..32e45bb
--- /dev/null
+++ b/app/project.yml
@@ -0,0 +1,166 @@
+name: Chums
+# Bundle IDs come from $CHUMS_BUNDLE and the team from $CHUMS_TEAM (bin/chums-install and bin/chums-sim set them): an
+# ID belongs to the team that first registered it, so signing with another team needs another ID.
+options:
+ bundleIdPrefix: dev.chums
+ deploymentTarget:
+ iOS: "26.0"
+ watchOS: "26.0"
+ createIntermediateGroups: true
+settings:
+ base:
+ SWIFT_VERSION: "5.0"
+ MARKETING_VERSION: "0.1"
+ CURRENT_PROJECT_VERSION: "1"
+ DEVELOPMENT_TEAM: "${CHUMS_TEAM}"
+ CODE_SIGN_STYLE: Automatic
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ ENABLE_PREVIEWS: "YES"
+targets:
+ Chums:
+ type: application
+ platform: iOS
+ sources:
+ - ChumsPhone
+ - ChumsPhoneShared
+ # the watch's engine, shared: the characters, the hub, talking, the conversation (watch-only parts are #if'd)
+ - path: ChumsWatch
+ includes: [Rig/*.swift, Screen.swift, HubClient.swift, HubConfig.swift, Voice.swift, Controller.swift, Chat.swift,
+ Artifacts.swift, Alerts.swift, Agents.swift, AgentFace.swift, Soul.swift, StayOn.swift]
+ - path: ChumsWatch/Noodle
+ type: folder
+ buildPhase: resources
+ # Noodle's shapes: the tube's poses and the moves between them (without it, every pose is a crumpled ball)
+ - path: ChumsWatch/noodle-shapes.bin
+ buildPhase: resources
+ - Shared/Characters.xcassets
+ info:
+ path: ChumsPhone/Info.plist
+ properties:
+ CFBundleDisplayName: Chums
+ CFBundleShortVersionString: $(MARKETING_VERSION)
+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)
+ UILaunchScreen: {}
+ UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait]
+ UIUserInterfaceStyle: Dark
+ NSMicrophoneUsageDescription: Listens only while you hold the microphone (or after you open Chums to talk).
+ NSCameraUsageDescription: Takes a photo to send to an agent, when you choose Take Photo.
+ CFBundleURLTypes:
+ - CFBundleURLName: chums
+ CFBundleURLSchemes: [chums]
+ NSAppTransportSecurity:
+ NSAllowsLocalNetworking: true
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${CHUMS_BUNDLE}
+ TARGETED_DEVICE_FAMILY: "1"
+ scheme:
+ testTargets: [ChumsPhoneUITests]
+ dependencies:
+ # the Home Screen and Lock Screen widgets and the Talk control
+ - target: ChumsPhoneWidgets
+ embed: true
+ # The watch app ships inside the phone app, in its Watch folder.
+ - target: ChumsWatch
+ embed: true
+ copy:
+ destination: productsDirectory
+ subpath: $(CONTENTS_FOLDER_PATH)/Watch
+ ChumsWatch:
+ type: application
+ platform: watchOS
+ sources:
+ - path: ChumsWatch
+ excludes: [Noodle]
+ # Noodle's clips: one HEIC image sequence per clip (tools/noodle-watch.sh) and their per-frame data
+ - path: ChumsWatch/Noodle
+ type: folder
+ buildPhase: resources
+ # the characters' faces, shared with the iPhone app and its widgets
+ - Shared/Characters.xcassets
+ info:
+ path: ChumsWatch/Info.plist
+ properties:
+ CFBundleDisplayName: Chums
+ WKApplication: true
+ # a standalone watch app: it asks for Health access on the watch (a dependent one asks through the iPhone app)
+ WKRunsIndependentlyOfCompanionApp: true
+ WKCompanionAppBundleIdentifier: ${CHUMS_BUNDLE}
+ NSMicrophoneUsageDescription: Listens only while you hold the screen.
+ NSHealthShareUsageDescription: Runs a workout session only to stay on screen, like a keyring pet. It never saves a workout.
+ NSHealthUpdateUsageDescription: Runs a workout session only to stay on screen, like a keyring pet. It never saves a workout.
+ # workout-processing keeps Chums running; Apple requires audio too for a workout app that taps your wrist
+ WKBackgroundModes: [workout-processing, audio]
+ NSLocalNetworkUsageDescription: Talks to the hub running on your Mac.
+ # plain HTTP only for the Simulator's 127.0.0.1; a real watch uses the Funnel HTTPS address
+ NSAppTransportSecurity:
+ NSAllowsLocalNetworking: true
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${CHUMS_BUNDLE}.watchkitapp
+ # HealthKit, only to run a workout session that keeps Chums on screen (keyring mode); nothing is saved
+ CODE_SIGN_ENTITLEMENTS: ChumsWatch/ChumsWatch.entitlements
+ TARGETED_DEVICE_FAMILY: "4"
+ dependencies:
+ # the complication / Smart Stack widget that opens Chums
+ - target: ChumsWidget
+ ChumsWidget:
+ type: app-extension
+ platform: watchOS
+ sources: [ChumsWidget]
+ info:
+ path: ChumsWidget/Info.plist
+ properties:
+ CFBundleDisplayName: Chums
+ NSExtension:
+ NSExtensionPointIdentifier: com.apple.widgetkit-extension
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${CHUMS_BUNDLE}.watchkitapp.widget
+ TARGETED_DEVICE_FAMILY: "4"
+ SKIP_INSTALL: YES
+ ChumsPhoneWidgets:
+ type: app-extension
+ platform: iOS
+ sources:
+ - ChumsPhoneWidgets
+ - ChumsPhoneShared
+ - path: ChumsWatch/HubConfig.swift
+ # the watch's characters, to draw its screen in the widgets (WatchScreen)
+ - path: ChumsWatch
+ includes: [Rig/*.swift, AgentFace.swift]
+ - path: ChumsWatch/Noodle
+ type: folder
+ buildPhase: resources
+ - path: ChumsWatch/noodle-shapes.bin
+ buildPhase: resources
+ - Shared/Characters.xcassets
+ info:
+ path: ChumsPhoneWidgets/Info.plist
+ properties:
+ CFBundleDisplayName: Chums
+ CFBundleShortVersionString: $(MARKETING_VERSION)
+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)
+ NSExtension:
+ NSExtensionPointIdentifier: com.apple.widgetkit-extension
+ NSAppTransportSecurity:
+ NSAllowsLocalNetworking: true
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${CHUMS_BUNDLE}.widgets
+ TARGETED_DEVICE_FAMILY: "1"
+ SKIP_INSTALL: YES
+ ASSETCATALOG_COMPILER_APPICON_NAME: ""
+ # the iPhone app driven by real touches in the Simulator (ChumsPhoneUITests.swift says how to run it)
+ ChumsPhoneUITests:
+ type: bundle.ui-testing
+ platform: iOS
+ sources: [ChumsPhoneUITests]
+ dependencies:
+ - target: Chums
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${CHUMS_BUNDLE}.uitests
+ GENERATE_INFOPLIST_FILE: YES
+ TEST_TARGET_NAME: Chums
+ TARGETED_DEVICE_FAMILY: "1"
diff --git a/bin/chums-agents b/bin/chums-agents
new file mode 100755
index 0000000..a015a9c
--- /dev/null
+++ b/bin/chums-agents
@@ -0,0 +1,93 @@
+#!/bin/zsh
+# The agents (~/.chums/agents.json). Claude Code ones are each a session run in the background by a LaunchAgent;
+# Codex, Copilot and ACP ones ("runtime" in agents.json) are run by the hub itself (hub/runtimes.mjs).
+# chums-agents install write and start a LaunchAgent per Claude Code agent (again after editing agents.json),
+# and remove those of agents that run on something else now
+# chums-agents add|remove <id> one agent's LaunchAgent (the hub uses these when you switch its runtime on the watch)
+# chums-agents status which are running
+# chums-agents stop|start|restart <id>
+# chums-agents open <id> take an agent into this terminal (Claude Code: its LaunchAgent stops and it goes back
+# when you quit; Codex: a Codex terminal on the same thread, the watch stays on it too)
+# LaunchAgent labels are $CHUMS_LABEL_PREFIX.agent.<id> (default dev.chums; see tools/common.zsh).
+ROOT="${0:A:h:h}"; LA=~/Library/LaunchAgents; D=gui/$(id -u)
+source "$ROOT/tools/common.zsh"
+chums_help "$@"
+[[ -z "$1" ]] && chums_help --help
+[[ -x "$CHUMS_NODE" ]] || chums_die "node not found. Install Node.js 20.11 or later (brew install node), or set CHUMS_NODE."
+[[ -f ~/.chums/agents.json ]] || chums_die "no ~/.chums/agents.json yet. Start the hub once (bin/chums-hub); it writes the defaults."
+# ids [claude|hub]: the agents run as Claude Code sessions, or by the hub
+ids() { "$CHUMS_NODE" -e 'const w=process.argv[1];console.log(JSON.parse(require("fs").readFileSync(process.env.HOME+"/.chums/agents.json","utf8")).filter(a=>((a.runtime??"claude")==="claude")===(w!=="hub")).map(a=>a.id).join(" "))' "$1" }
+runtime() { "$CHUMS_NODE" -e 'const a=JSON.parse(require("fs").readFileSync(process.env.HOME+"/.chums/agents.json","utf8")).find(a=>a.id===process.argv[1]);console.log(a?(a.runtime??"claude"):"")' "$1" }
+label() { echo "$CHUMS_LABEL_PREFIX.agent.$1" }
+plist() {
+ cat > "$LA/$(label $1).plist" <<PL
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+ <key>Label</key><string>$(label $1)</string>
+ <key>ProgramArguments</key><array><string>$APPX</string><string>/usr/bin/expect</string><string>$ROOT/tools/agent-host.exp</string><string>$1</string></array>
+ <key>EnvironmentVariables</key><dict><key>CHUMS_NODE</key><string>$CHUMS_NODE</string>${CHUMS_NO_RC:+<key>CHUMS_NO_RC</key><string>1</string>}</dict>
+ <key>RunAtLoad</key><true/>
+ <key>KeepAlive</key><true/>
+ <key>ThrottleInterval</key><integer>30</integer>
+ <key>StandardOutPath</key><string>$HOME/.chums/agents/$1.launchd.log</string>
+ <key>StandardErrorPath</key><string>$HOME/.chums/agents/$1.launchd.log</string>
+</dict></plist>
+PL
+}
+# a hub-run agent is started and stopped with the hub
+hubrun() { local r=$(runtime $1); [[ -n "$r" && "$r" != claude ]] && { echo "$1 runs on $r inside the hub: restart the hub to restart it (its log: ~/.chums/agents/$1.host.log)"; return 0 }; return 1 }
+case "$1" in
+ add|remove|stop|start|restart|open)
+ [[ -n "$2" ]] || { all=(${=$(ids claude)} ${=$(ids hub)}); chums_die "which agent? bin/chums-agents $1 <id> (in ~/.chums/agents.json: $all)" } ;;
+esac
+case "$1" in
+ install)
+ mkdir -p ~/.chums/agents "$LA"
+ # run through Chums.app, so every permission the agent needs belongs to "Chums" (bin/chums-permissions grants them)
+ APPX=$(CHUMS_NO_RESTART=1 "$ROOT/tools/mac-app/build.zsh") || chums_die "couldn't build ~/Applications/Chums.app"
+ failed=()
+ for a in $(ids claude); do
+ plist $a || { failed+=($a); continue }
+ chums_reload $(label $a) "$LA/$(label $a).plist" && echo "started $a" || failed+=($a)
+ done
+ for a in $(ids hub); do echo "$a: run by the hub ($(runtime $a)); restart the hub after editing agents.json"; done
+ # a LaunchAgent whose agent runs on something else now (or is gone) is removed
+ keep=" $(ids claude) "
+ for f in $LA/$CHUMS_LABEL_PREFIX.agent.*.plist(N); do
+ a=${${f:t}%.plist}; a=${a#$CHUMS_LABEL_PREFIX.agent.}
+ [[ $keep == *" $a "* ]] && continue
+ launchctl bootout $D/$(label $a) 2>/dev/null; rm -f "$f"; echo "removed $a's LaunchAgent (it isn't a Claude Code agent now)"
+ done
+ (( ${#failed} )) && chums_die "didn't start: $failed (their logs: ~/.chums/agents/<id>.launchd.log)"
+ true ;;
+ add)
+ [[ $(runtime $2) == claude ]] || chums_die "$2 isn't a Claude Code agent in ~/.chums/agents.json"
+ mkdir -p ~/.chums/agents "$LA"
+ APPX=$(CHUMS_NO_RESTART=1 "$ROOT/tools/mac-app/build.zsh") || chums_die "couldn't build ~/Applications/Chums.app"
+ plist $2 && chums_reload $(label $2) "$LA/$(label $2).plist" && echo "started $2" || chums_die "couldn't start $2" ;;
+ remove)
+ launchctl bootout $D/$(label $2) 2>/dev/null; rm -f "$LA/$(label $2).plist"; echo "removed $2's LaunchAgent" ;;
+ status)
+ for a in $(ids claude); do
+ pid=$(launchctl print $D/$(label $a) 2>/dev/null | awk '/^\tpid = /{print $3}')
+ if [[ -n "$pid" ]]; then state="running (pid $pid)"; else state="not running"; fi
+ echo "$a: $state $(tail -1 ~/.chums/agents/$a.host.log 2>/dev/null)"
+ done
+ for a in $(ids hub); do echo "$a: $(runtime $a), run by the hub $(tail -1 ~/.chums/agents/$a.host.log 2>/dev/null)"; done ;;
+ stop) hubrun $2 || { launchctl bootout $D/$(label $2) && echo "stopped $2" } ;;
+ start) hubrun $2 || { launchctl bootstrap $D "$LA/$(label $2).plist" && echo "started $2" } ;;
+ restart) hubrun $2 || { launchctl kickstart -k $D/$(label $2) && echo "restarted $2" } ;;
+ open)
+ case "$(runtime $2)" in
+ claude)
+ launchctl bootout $D/$(label $2) 2>/dev/null; sleep 2
+ args=("${(@f)$("$CHUMS_NODE" $ROOT/tools/agent-cmd.mjs $2)}") || exit 1
+ cd "$args[1]"; "${(@)args[2,-1]}"
+ launchctl bootstrap $D "$LA/$(label $2).plist" && echo "$2 is back in the background" ;;
+ codex) exec "$ROOT/bin/chums-codex" $2 ;; # a Codex terminal on the hub's app-server, on the agent's thread
+ "") echo "no agent $2 in ~/.chums/agents.json"; exit 1 ;;
+ *) echo "$2 runs on $(runtime $2) inside the hub, with no terminal to open: its conversation is in the agent's own history (Copilot: copilot --resume, while the hub isn't running it)"; exit 1 ;;
+ esac ;;
+ *) chums_die "unknown command $1 (bin/chums-agents --help)" ;;
+esac
diff --git a/bin/chums-claude b/bin/chums-claude
new file mode 100755
index 0000000..3b325d4
--- /dev/null
+++ b/bin/chums-claude
@@ -0,0 +1,61 @@
+#!/bin/zsh
+# Start an interactive Claude Code session that the watch can reach:
+# - loads the Chums channel (orders in, spoken replies out, approvals both ways)
+# - keeps Remote Control on, so the same session still shows in the Claude app
+# - keeps the project's own .mcp.json if it has one
+# Usage: chums-claude <agent id> [extra claude args...] e.g. chums-claude noodle (the watch and the iPhone reach a
+# session named after one of the agents in ~/.chums/agents.json; without a name it's the folder's, which they can't)
+
+[[ $1 == (-h|--help) ]] && { awk 'NR == 1 { next } /^#/ { sub(/^# ?/, ""); print; next } { exit }' "$0"; exit 0 }
+CHUMS_ROOT="${0:A:h:h}"
+die() { echo "chums: $*" >&2; exit 1 }
+[[ -f ~/.chums/config.json ]] || die "no ~/.chums/config.json yet. Start the hub once (bin/chums-hub), then run this again."
+command -v node >/dev/null 2>&1 || die "node is not installed (the channel and the hooks run on it). Install Node.js 20.11 or later (brew install node)."
+[[ -d "$CHUMS_ROOT/node_modules/@modelcontextprotocol/sdk" ]] || die "the npm packages aren't installed. Run bin/chums-setup (or npm ci in $CHUMS_ROOT)."
+command -v claude >/dev/null 2>&1 ||
+ die "claude is not on PATH. Install Claude Code (curl -fsSL https://claude.ai/install.sh | bash), or add its folder (often ~/.local/bin) to PATH."
+MCP_JSON="$CHUMS_ROOT/channel/mcp.json"
+cat > "$MCP_JSON" <<EOF
+{ "mcpServers": { "chums": { "command": "node", "args": ["$CHUMS_ROOT/channel/chums-channel.mjs"] } } }
+EOF
+
+if [[ -n "$1" && "$1" != -* ]]; then export CHUMS_NAME="$1"; shift; fi
+
+# Photos and files sent from the iPhone land in ~/.chums/uploads: the session reads them without asking (it was sent
+# them to read); it never edits its soul files itself; and it can't open Claude Code's question dialog (AskUserQuestion),
+# which only this terminal shows: it asks on the watch and the iPhone instead, with chums_reply (status 'question').
+# Hooks report what the session is doing to the hub: tool calls and failures, permission requests, notifications,
+# prompts, stops and stop failures, compaction, subagents, session start and end. See design/STATES.md.
+HOOKS_JSON="$CHUMS_ROOT/channel/hooks.json"
+HOOK="node '$CHUMS_ROOT/channel/chums-hook.mjs'"
+cat > "$HOOKS_JSON" <<EOF
+{ "permissions": { "deny": ["Edit(~/.chums/souls/**)", "Write(~/.chums/souls/**)", "MultiEdit(~/.chums/souls/**)", "AskUserQuestion"], "allow": ["Read(~/.chums/uploads/**)"] },
+ "hooks": {
+ "PreToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "PostToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "PostToolUseFailure": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "PermissionRequest": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "PermissionDenied": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "Notification": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "StopFailure": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "SubagentStart": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "SubagentStop": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "PreCompact": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "PostCompact": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "SessionStart": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "SessionEnd": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }],
+ "Stop": [{ "hooks": [{ "type": "command", "command": "$HOOK", "timeout": 2 }] }]
+} }
+EOF
+
+configs=(--mcp-config "$MCP_JSON")
+[[ -f ./.mcp.json ]] && configs+=(--mcp-config ./.mcp.json)
+
+rc=(--remote-control)
+[[ -n "$CHUMS_NO_RC" ]] && rc=()
+
+# Speaking to the watch is always allowed; a reply that waits on an approval would never be heard.
+exec command claude "${configs[@]}" "${rc[@]}" --settings "$HOOKS_JSON" \
+ --allowedTools mcp__chums__chums_reply \
+ --dangerously-load-development-channels server:chums "$@"
diff --git a/bin/chums-codex b/bin/chums-codex
new file mode 100755
index 0000000..aacce0e
--- /dev/null
+++ b/bin/chums-codex
@@ -0,0 +1,25 @@
+#!/bin/zsh
+# A Codex terminal on a Codex agent's own thread, connected to the app-server the hub runs for it (not a copy):
+# what the watch says to the agent shows here as it happens, and what you type here goes to the same agent. The watch
+# shows that work's status and tool calls too; only turns from the watch are spoken on it. An approval shows in both
+# places, and the first answer wins. Quitting the terminal leaves the agent running for the watch.
+# chums-codex [id] [codex args…] (no id: the only Codex agent in ~/.chums/agents.json)
+source "${0:A:h:h}/tools/common.zsh"
+chums_help "$@"
+[[ -x "$CHUMS_NODE" ]] || chums_die "node not found. Install Node.js 20.11 or later (brew install node), or set CHUMS_NODE."
+[[ -f ~/.chums/agents.json ]] || chums_die "no ~/.chums/agents.json yet. Start the hub once (bin/chums-hub); it writes the defaults."
+NODE=$CHUMS_NODE
+CODEX=$(command -v codex || echo ~/.npm-global/bin/codex)
+[[ -x "$CODEX" ]] || chums_die "codex is not installed. Install it with: npm install -g @openai/codex (or brew install --cask codex), then codex login"
+ids=($($NODE -e 'console.log(JSON.parse(require("fs").readFileSync(process.env.HOME+"/.chums/agents.json","utf8")).filter(a=>a.runtime==="codex").map(a=>a.id).join(" "))'))
+id=$1; [[ -n "$id" ]] && shift
+if [[ -z "$id" ]]; then
+ (( ${#ids} == 1 )) && id=$ids[1] || { echo "Which Codex agent? ${ids:-none in ~/.chums/agents.json}"; exit 1 }
+fi
+(( ${ids[(Ie)$id]} )) || { echo "$id isn't a Codex agent (\"runtime\": \"codex\" in ~/.chums/agents.json)"; exit 1 }
+rt=~/.chums/agents/$id.runtime.json
+[[ -f $rt ]] || { echo "$id hasn't started in the hub yet (is the hub running? its log: ~/.chums/agents/$id.host.log)"; exit 1 }
+field() { $NODE -e 'console.log(require(process.argv[1])[process.argv[2]])' $rt $1 }
+thread=$(field thread); sock=$(field socket); cwd=$(field cwd)
+[[ -S "$sock" ]] || { echo "the hub's Codex app-server for $id isn't running ($sock is missing)"; exit 1 }
+cd "$cwd" && exec "$CODEX" resume "$thread" --remote "unix://$sock" "$@"
diff --git a/bin/chums-doctor b/bin/chums-doctor
new file mode 100755
index 0000000..188b1fc
--- /dev/null
+++ b/bin/chums-doctor
@@ -0,0 +1,14 @@
+#!/bin/zsh
+# Checks the whole chain, from the tools on this Mac to the watch, and prints a pass/fail list with the fix for each
+# failure. Read-only: it starts, stops, writes and installs nothing, and never prints the tokens. Safe to run any time.
+# bin/chums-doctor exit code 0 when nothing failed, 1 otherwise (NO_COLOR=1: no colours)
+# The checks are in tools/doctor.py.
+ROOT="${0:A:h:h}"
+# python3 comes with Xcode or its command line tools; without either, macOS would offer to install them in a dialog
+if ! xcode-select -p >/dev/null 2>&1; then
+ print "Chums doctor"
+ print " FAIL no Xcode or command line tools on this Mac (the checks run on their python3)"
+ print " fix: install Xcode 26 from the App Store and open it once (or, for now: xcode-select --install)"
+ exit 1
+fi
+exec /usr/bin/env python3 "$ROOT/tools/doctor.py" "$@"
diff --git a/bin/chums-hub b/bin/chums-hub
new file mode 100755
index 0000000..58fe419
--- /dev/null
+++ b/bin/chums-hub
@@ -0,0 +1,8 @@
+#!/bin/zsh
+# Run the Chums hub (Mac side). Logs to the terminal; config and token live in ~/.chums/config.json.
+# It runs until stopped (Ctrl-C). To run it in the background at login instead: bin/chums-setup --launchd.
+[[ $1 == (-h|--help) ]] && { awk 'NR == 1 { next } /^#/ { sub(/^# ?/, ""); print; next } { exit }' "$0"; exit 0 }
+command -v node >/dev/null 2>&1 || { echo "chums: node is not installed. Install Node.js 20.11 or later (brew install node)." >&2; exit 1 }
+node -e 'const [a, b] = process.versions.node.split(".").map(Number); process.exit(a > 20 || (a == 20 && b >= 11) ? 0 : 1)' ||
+ { echo "chums: node $(node -v) is too old. The hub needs Node.js 20.11 or later (brew upgrade node)." >&2; exit 1 }
+exec node "${0:A:h:h}/hub/hub.mjs"
diff --git a/bin/chums-install b/bin/chums-install
new file mode 100755
index 0000000..0d61844
--- /dev/null
+++ b/bin/chums-install
@@ -0,0 +1,151 @@
+#!/bin/zsh
+# Build Chums (signed) and install it straight onto the Apple Watch, then launch it; the iPhone app too, when Xcode
+# knows the iPhone. Run it again to update the app,
+# after the hub's token or public address changed, and within 7 days when you sign with a free Personal Team.
+# Needs: the watch known to Xcode (xcrun devicectl list devices), Developer Mode on the watch, an Apple ID in Xcode.
+# Settings (environment or ~/.chums/config.json): CHUMS_TEAM / "team", CHUMS_BUNDLE / "bundleId". See tools/common.zsh.
+# What each error means and how to fix it: docs/troubleshooting.md.
+set -e
+ROOT="${0:A:h:h}"
+source "$ROOT/tools/common.zsh"
+chums_help "$@"
+: ${DEVELOPER_DIR:=/Applications/Xcode.app/Contents/Developer}; export DEVELOPER_DIR
+[[ -d $DEVELOPER_DIR ]] || chums_die "Xcode not found at $DEVELOPER_DIR. Install Xcode 26 or later, or set DEVELOPER_DIR."
+chums_need xcodegen "Install it with: brew install xcodegen"
+chums_need_config
+
+# The watch first: the build takes minutes, and without a watch there is nothing to install it on.
+JSON=$(mktemp)
+xcrun devicectl list devices --json-output "$JSON" >/dev/null 2>&1 || true
+IFS=$'\t' read -r WATCH WNAME WDEV < <(python3 -c '
+import json, sys
+try: devices = json.load(open(sys.argv[1]))["result"]["devices"]
+except Exception: devices = []
+for d in devices:
+ if d.get("hardwareProperties", {}).get("platform") == "watchOS":
+ p = d.get("deviceProperties", {})
+ print(d["identifier"], p.get("name", "Apple Watch"), p.get("developerModeStatus", ""), sep="\t"); break' "$JSON") || true
+# The iPhone app (the agents, their conversations, the widgets and the Talk control) goes on the iPhone, if Xcode has it.
+IFS=$'\t' read -r PHONE PNAME PDEV < <(python3 -c '
+import json, sys
+try: devices = json.load(open(sys.argv[1]))["result"]["devices"]
+except Exception: devices = []
+for d in devices:
+ p, c = d.get("deviceProperties", {}), d.get("connectionProperties", {})
+ if d.get("hardwareProperties", {}).get("platform") == "iOS" and c.get("pairingState") == "paired" and c.get("tunnelState") != "unavailable":
+ print(d["identifier"], p.get("name", "iPhone"), p.get("developerModeStatus", ""), sep="\t"); break' "$JSON") || true
+rm -f "$JSON"
+if [[ -z "$WATCH" ]]; then
+ echo "Xcode doesn't know any Apple Watch yet. The first time:"
+ echo " 1. Connect the paired iPhone to this Mac with a USB cable, unlock it and tap Trust."
+ echo " 2. Keep the watch unlocked, near the iPhone, on the same Wi-Fi as the Mac."
+ echo " 3. Open Xcode › Window › Devices and Simulators and wait until the watch is listed."
+ echo "Then run this again. Details: docs/setup.md, \"Connect the iPhone and the watch to Xcode\"."
+ exit 1
+fi
+# "unknown": Xcode can't reach the watch right now to ask (asleep, or the iPhone off USB); the install says if it fails
+[[ $WDEV == unknown ]] && echo "Xcode can't read $WNAME's Developer Mode right now: trying anyway (keep the watch unlocked and awake)."
+if [[ -n "$WDEV" && "$WDEV" != enabled && "$WDEV" != unknown ]]; then
+ echo "$WNAME has Developer Mode $WDEV. On the watch: Settings › Privacy & Security › Developer Mode, turn it on,"
+ echo "restart the watch when it asks, then unlock it and confirm Turn On. Then run this again."
+ echo "No switch there? docs/setup.md, \"Turn on Developer Mode\"."
+ exit 1
+fi
+echo "Watch: $WNAME"
+
+"$ROOT/tools/gen-config.sh"
+cd "$ROOT/app"
+
+# Sign with a paid team if Xcode has one, else your free Personal Team (installs expire after 7 days).
+: ${CHUMS_TEAM:=$(chums_cfg team)}; export CHUMS_TEAM
+KINDF=$(mktemp) # pick-team.py says "free" on stderr for a free Personal Team
+TEAM=$(python3 "$ROOT/tools/pick-team.py" 2>"$KINDF") || TEAM=""
+KIND=$(cat "$KINDF" 2>/dev/null); rm -f "$KINDF"
+if [[ -z "$TEAM" ]]; then
+ echo "No developer team can sign: Xcode lists no team for any Apple ID."
+ echo "Add an Apple ID in Xcode › Settings › Apple Accounts › + › Apple ID. Any Apple ID has a free Personal Team that"
+ echo "can install Chums on your own devices (installs last 7 days)."
+ echo "(A paid team also lists nothing while Apple converts a membership, e.g. from individual to organization.)"
+ echo "Then run this again. (Or: CHUMS_TEAM=<team ID> bin/chums-install)"
+ exit 1
+fi
+# a bundle ID belongs to the team that registered it first, so the default one carries the team's ID; set CHUMS_BUNDLE
+# (or "bundleId" in ~/.chums/config.json) to keep one you already registered
+: ${CHUMS_BUNDLE:=$(chums_cfg bundleId)}
+: ${CHUMS_BUNDLE:=dev.chums.${TEAM:l}}
+export CHUMS_BUNDLE CHUMS_TEAM=$TEAM
+xcodegen generate --quiet
+echo "Signing with team $TEAM as $CHUMS_BUNDLE"
+[[ "$KIND" == free ]] && echo "(a free Personal Team: this install expires on $(date -v+7d '+%Y-%m-%d'); run bin/chums-install again before then)"
+# -target (not -scheme): scheme builds demand the multi-GB watchOS platform download; target builds don't.
+# Release: the characters do real per-frame maths (the tube is lit and sliced live); Debug Swift is ~15× slower.
+echo "Building (a few minutes the first time)…"
+LOG=$(mktemp)
+xcodebuild -project Chums.xcodeproj -target Chums -configuration Release DEVELOPMENT_TEAM="$TEAM" \
+ -allowProvisioningUpdates -allowProvisioningDeviceRegistration SYMROOT="$PWD/build/sym" build > "$LOG" 2>&1 || true
+grep -E "error:|BUILD" "$LOG" | sort -u | head -8
+if ! grep -q "BUILD SUCCEEDED" "$LOG"; then
+ if grep -q "No Account for Team" "$LOG"; then
+ echo "Xcode isn't signed in to the Apple ID for team $TEAM. Xcode › Settings › Apple Accounts › + › Apple ID, sign in, then run this again."
+ echo "Any Apple ID works: a free one gets a Personal Team that can install on your own devices."
+ elif grep -qi "has no devices" "$LOG"; then
+ echo "Team $TEAM has no registered devices yet. Xcode registers a device the first time you run an app on it:"
+ echo " 1. open $ROOT/app/Chums.xcodeproj"
+ echo " 2. choose the Chums scheme and your iPhone as the destination, press Run (⌘R)"
+ echo " 3. choose the ChumsWatch scheme and your watch as the destination, press Run"
+ echo "Then run bin/chums-install again. Details: docs/troubleshooting.md, \"Your team has no devices\"."
+ elif grep -qi "cannot be registered to your development team" "$LOG"; then
+ echo "The bundle ID $CHUMS_BUNDLE belongs to another team. Pick one of your own: \"bundleId\": \"com.<you>.chums\" in"
+ echo "~/.chums/config.json (or CHUMS_BUNDLE=…), then run this again."
+ elif grep -qi "App ID limit" "$LOG"; then
+ echo "A free Personal Team can register 10 App IDs in 7 days, and each new bundle ID uses 4 (the iPhone app, its"
+ echo "widgets, the watch app, the watch's widget)."
+ echo "Wait for the oldest to expire, and keep one bundle ID from then on (\"bundleId\" in ~/.chums/config.json)."
+ elif grep -qi "license" "$LOG" && grep -qi "agree" "$LOG"; then
+ echo "Xcode's license hasn't been accepted: open Xcode once, or run sudo xcodebuild -license accept. Then run this again."
+ fi
+ echo "Build failed; full log: $LOG"
+ echo "Known errors and their fixes: docs/troubleshooting.md"
+ exit 1
+fi
+
+ILOG=$(mktemp)
+# The wireless connection to the watch often drops the first attempt or two; retry.
+for i in 1 2 3 4 5; do
+ xcrun devicectl device install app --device "$WATCH" build/sym/Release-watchos/ChumsWatch.app > "$ILOG" 2>&1 && break
+ why=$(grep -m1 -o 'ERROR: [^(]*' "$ILOG" || tail -1 "$ILOG")
+ if grep -q "IXErrorDomain error 48" "$ILOG"; then tip="the iPhone is installing Chums on the watch itself: unlock the watch and wait for it"
+ elif grep -qi "locked" "$ILOG"; then tip="unlock the watch"
+ elif grep -qi "disk image" "$ILOG"; then tip="unlock the watch and let Xcode finish preparing it (Window › Devices and Simulators)"
+ else tip="keep the watch unlocked, awake and near the iPhone"; fi
+ echo "install attempt $i failed ($why); $tip"
+ if [[ $i == 5 ]]; then echo "Full log: $ILOG. Known errors and their fixes: docs/troubleshooting.md"; WATCH_FAILED=1; break; fi
+ sleep 6
+done
+if [[ -n "$WATCH_FAILED" ]]; then
+ :
+elif xcrun devicectl device process launch --device "$WATCH" "$CHUMS_BUNDLE.watchkitapp" > "$ILOG" 2>&1; then
+ echo "Chums is running on the watch."
+else
+ echo "Chums is installed, but it didn't open ($(grep -m1 -o 'ERROR: [^(]*' "$ILOG" || tail -1 "$ILOG"))."
+ grep -qi "locked" "$ILOG" && echo "The watch was locked: unlock it and open Chums from its app list."
+fi
+# Then the iPhone app. (It carries the watch app too: installed after the watch has it, the iPhone has nothing to send.)
+if [[ -z "$PHONE" ]]; then
+ echo "No iPhone known to Xcode: skipping the iPhone app (connect the iPhone by USB once, then run this again)."
+elif [[ -n "$PDEV" && "$PDEV" != enabled && "$PDEV" != unknown ]]; then
+ echo "$PNAME has Developer Mode $PDEV: skipping the iPhone app. On the iPhone: Settings › Privacy & Security ›"
+ echo "Developer Mode, turn it on, restart, confirm Turn On. Then run this again."
+else
+ for i in 1 2 3; do
+ if xcrun devicectl device install app --device "$PHONE" build/sym/Release-iphoneos/Chums.app > "$ILOG" 2>&1; then
+ echo "Chums is installed on $PNAME."; break
+ fi
+ echo "iPhone install attempt $i failed ($(grep -m1 -o 'ERROR: [^(]*' "$ILOG" || tail -1 "$ILOG")); unlock the iPhone"
+ [[ $i == 3 ]] && echo "Skipping the iPhone app. Full log: $ILOG"
+ sleep 4
+ done
+fi
+
+[[ -n "$WATCH_FAILED" ]] && exit 1
+echo "Next: start the agents (bin/chums-agents install; docs/setup.md, step 10), and check the whole chain with bin/chums-doctor."
diff --git a/bin/chums-permissions b/bin/chums-permissions
new file mode 100755
index 0000000..526a7ee
--- /dev/null
+++ b/bin/chums-permissions
@@ -0,0 +1,42 @@
+#!/bin/zsh
+# The permissions the agents need on this Mac, granted once. The hub, the agents and tailscaled run through one app,
+# Chums (~/Applications/Chums.app, tools/mac-app), so everything they ask for belongs to it, and Claude Code, Codex or
+# Node.js updates don't undo it. Opening Chums shows a window: Allow All, then answer each macOS dialog.
+# bin/chums-permissions open Chums (the same as double-clicking it in ~/Applications); builds it if needed
+# bin/chums-permissions check what's granted, asking nothing and changing nothing
+ROOT="${0:A:h:h}"
+source "$ROOT/tools/common.zsh"
+chums_help "$@"
+[[ -z "$1" || "$1" == check ]] || chums_die "unknown command $1 (bin/chums-permissions --help)"
+APP=${CHUMS_MAC_APP:-$HOME/Applications/Chums.app}
+APPX=$APP/Contents/MacOS/Chums
+LA=~/Library/LaunchAgents
+
+if [[ $1 != check ]]; then
+ "$ROOT/tools/mac-app/build.zsh" >/dev/null || chums_die "couldn't build $APP (tools/mac-app/build.zsh)"
+ open "$APP" && print "Chums is open: click Allow All, then answer each macOS dialog."
+ exit 0
+fi
+
+[[ -x $APPX ]] || { print "no $APP yet: bin/chums-setup --launchd, bin/chums-agents install and bin/chums-permissions build it"; exit 1 }
+print "Chums: $APP"
+[[ $(cat "$APP/Contents/Resources/stamp" 2>/dev/null) == $("$ROOT/tools/mac-app/build.zsh" --expected-stamp) ]] \
+ || print " note Chums.app is out of date: bin/chums-agents install rebuilds it (then Allow All again if it's signed ad hoc)"
+n=0
+[[ -f $LA/$CHUMS_LABEL_PREFIX.hub.plist ]] || { print " the hub doesn't run as a LaunchAgent: what it does on the Mac asks as the terminal it runs in, not as Chums"; n=1 }
+for f in $LA/$CHUMS_LABEL_PREFIX.hub.plist $LA/$CHUMS_LABEL_PREFIX.tailscaled.plist $LA/$CHUMS_LABEL_PREFIX.agent.*.plist(N); do
+ [[ -f $f && $(plutil -extract ProgramArguments.0 raw "$f" 2>/dev/null) != $APPX ]] && { print " ${f:t} doesn't start through Chums"; n=1 }
+done
+(( n )) && print " fix bin/chums-setup --launchd and bin/chums-agents install" || print " ok the hub, tailscaled and the agents run as Chums"
+show() { local label=$1; shift; printf " %-5s %s\n" $("$APPX" --check "$@" >/dev/null 2>&1 && print ok || print no) "$label" }
+show "Accessibility" accessibility
+show "Screen Recording" screen
+show "Full Disk Access (optional; covers your folders)" fda
+"$APPX" --check apps 2>/dev/null | while IFS=$'\t' read -r st name; do
+ case $st in
+ granted) printf " %-5s control %s\n" ok "$name" ;;
+ not-open) printf " %-5s control %s (not open: can't be checked)\n" "?" "$name" ;;
+ *) printf " %-5s control %s (%s)\n" no "$name" "$st" ;;
+ esac
+done
+print " (your folders: Chums's window shows them; checking them here would ask)"
diff --git a/bin/chums-setup b/bin/chums-setup
new file mode 100755
index 0000000..3890c1a
--- /dev/null
+++ b/bin/chums-setup
@@ -0,0 +1,145 @@
+#!/bin/zsh
+# Checks that this Mac has what Chums needs, installs the Node dependencies and the speech-to-text model, and says
+# what is missing and how to get it. Safe to run again.
+# bin/chums-setup check everything; install npm packages, the Whisper model and the agents' voices
+# (Kokoro) if missing
+# bin/chums-setup --launchd also run the hub (and tailscaled) in the background as LaunchAgents, started at login
+# Settings: see tools/common.zsh (CHUMS_LABEL_PREFIX, CHUMS_NODE, CHUMS_BUNDLE, CHUMS_TEAM). Whisper model folder:
+# CHUMS_WHISPER_MODEL (the hub reads the same variable).
+ROOT="${0:A:h:h}"
+source "$ROOT/tools/common.zsh"
+chums_help "$@"
+LAUNCHD=0; [[ "$1" == --launchd ]] && LAUNCHD=1
+[[ -z "$1" || "$1" == --launchd ]] || chums_die "unknown option $1 (bin/chums-setup --help)"
+MODEL=${CHUMS_WHISPER_MODEL:-~/Documents/huggingface/models/argmaxinc/whisperkit-coreml/openai_whisper-base}
+missing=0
+ok() { print -- " ok $*" }
+warn() { print -- " -- $*" }
+bad() { print -- " MISSING $*"; missing=$((missing + 1)) }
+
+print "Chums setup ($ROOT)"
+print "\nThe Mac side (hub, channel, hooks):"
+[[ $(uname) == Darwin ]] && ok "macOS $(sw_vers -productVersion)" || bad "macOS: the hub uses macOS tools (screencapture, sips, WebKit)"
+
+if [[ -x "$CHUMS_NODE" ]]; then
+ v=$("$CHUMS_NODE" -p 'process.versions.node')
+ if "$CHUMS_NODE" -e 'const [a,b]=process.versions.node.split(".").map(Number); process.exit(a>20||(a==20&&b>=11)?0:1)'; then ok "node $v"
+ else bad "node $v is too old: Chums needs Node.js 20.11 or later (brew install node)"; fi
+else bad "node: install Node.js 20.11 or later (brew install node)"; fi
+
+if [[ -d "$ROOT/node_modules/@modelcontextprotocol/sdk" ]]; then ok "npm packages"
+elif command -v npm >/dev/null; then print " ... installing npm packages"; (cd "$ROOT" && npm ci --no-audit --no-fund >/dev/null) && ok "npm packages" || bad "npm packages: run npm ci in $ROOT"
+else bad "npm packages: npm not found (it comes with Node.js)"; fi
+
+# the coding agents: Claude Code, Codex, or both (docs/setup.md, "Pick your agent"); bin/chums-doctor checks sign-in
+have_agent=0
+if command -v claude >/dev/null 2>&1; then ok "claude $(command claude --version 2>/dev/null | head -1)"; have_agent=1
+elif [[ -x ~/.local/bin/claude ]]; then
+ warn "claude is in ~/.local/bin, which isn't on PATH: add it in ~/.zshrc (bin/chums-claude runs claude from PATH)"; have_agent=1
+else warn "claude: not installed (Claude Code agents need it): curl -fsSL https://claude.ai/install.sh | bash"; fi
+CODEX=$(command -v codex || { [[ -x ~/.npm-global/bin/codex ]] && echo ~/.npm-global/bin/codex })
+if [[ -n "$CODEX" ]]; then ok "codex ${$("$CODEX" --version 2>/dev/null | head -1)#codex-cli }"; have_agent=1
+else warn "codex: not installed (Codex agents need it): npm install -g @openai/codex"; fi
+(( have_agent )) || bad "a coding agent: install Claude Code or Codex (or both), then sign in to it"
+
+command -v python3 >/dev/null && ok "python3" || bad "python3: install the Xcode command line tools (xcode-select --install)"
+[[ -x /usr/bin/expect ]] && ok "expect (runs the background agents)" || warn "expect: only bin/chums-agents needs it"
+
+if command -v whisperkit-cli >/dev/null; then
+ ok "whisperkit-cli"
+ if [[ -f "$MODEL/config.json" || -d "$MODEL/AudioEncoder.mlmodelc" ]]; then ok "Whisper model ($MODEL)"
+ else
+ print " ... downloading the Whisper base model (about 150 MB) to ${MODEL:h}"
+ T=$(mktemp -d); say -o "$T/hello.wav" --data-format=LEI16@16000 "hello" 2>/dev/null
+ whisperkit-cli transcribe --model base --download-model-path "${MODEL:h:h:h:h}" --audio-path "$T/hello.wav" >/dev/null 2>&1
+ rm -rf "$T"
+ [[ -d "$MODEL" ]] && ok "Whisper model ($MODEL)" || bad "Whisper model: not at $MODEL. Download openai_whisper-base from huggingface.co/argmaxinc/whisperkit-coreml there, or set CHUMS_WHISPER_MODEL"
+ fi
+else bad "whisperkit-cli (speech to text on the Mac): brew install whisperkit-cli"; fi
+command -v ffmpeg >/dev/null && ok "ffmpeg" || bad "ffmpeg (converts each clip for Whisper): brew install ffmpeg"
+
+# the agents' voices: Kokoro on the GPU through MLX (Apple Silicon), in its own Python (tools/kokoro-server.py)
+KPY=~/.chums/kokoro/.venv/bin/python
+if [[ $(uname -m) != arm64 ]]; then warn "agents' voices: Kokoro needs Apple Silicon; the watch reads replies with its own voice"
+elif [[ -x $KPY ]] && "$KPY" -c 'import mlx_audio, misaki' 2>/dev/null; then
+ [[ -f ~/.chums/kokoro/.voices-english ]] || { (cd ~/.chums/kokoro && "$KPY" "$ROOT/tools/kokoro-server.py" --once --voices english >/dev/null 2>&1) && touch ~/.chums/kokoro/.voices-english; }
+ ok "agents' voices (Kokoro, ~/.chums/kokoro)"
+elif command -v uv >/dev/null; then
+ print " ... installing the agents' voices (Kokoro: its Python in ~/.chums/kokoro, about 1.1 GB; its model, about 0.35 GB)"
+ mkdir -p ~/.chums/kokoro
+ if uv venv -q --python 3.12 ~/.chums/kokoro/.venv && uv pip install -q --python "$KPY" -r "$ROOT/tools/kokoro-requirements.txt" \
+ && (cd ~/.chums/kokoro && "$KPY" "$ROOT/tools/kokoro-server.py" --once --voices english >/dev/null 2>&1)
+ then touch ~/.chums/kokoro/.voices-english; ok "agents' voices (Kokoro, ~/.chums/kokoro)"
+ else warn "agents' voices: Kokoro didn't install (the watch reads replies with its own voice). Run bin/chums-setup again"; fi
+else warn "agents' voices: install uv (brew install uv) and run bin/chums-setup again; until then the watch reads replies with its own voice"; fi
+
+if command -v tailscale >/dev/null && command -v tailscaled >/dev/null; then ok "tailscale + tailscaled"
+else bad "tailscale (the watch reaches the hub through Tailscale Funnel): brew install tailscale"; fi
+
+print "\nThe watch app (only to build it):"
+DEV=${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}
+if [[ -d $DEV ]]; then
+ xv=$(DEVELOPER_DIR=$DEV xcodebuild -version 2>/dev/null | head -1)
+ [[ ${${xv#Xcode }%%.*} -ge 26 ]] 2>/dev/null && ok "$xv" || bad "Xcode 26 or later (found: ${xv:-none}); the app targets watchOS 26"
+else bad "Xcode 26 or later from the App Store (or set DEVELOPER_DIR)"; fi
+command -v xcodegen >/dev/null && ok "xcodegen" || bad "xcodegen: brew install xcodegen"
+
+print "\nThis machine's settings:"
+[[ -f $CHUMS_CONFIG ]] && ok "$CHUMS_CONFIG (hub token, ports$(chums_cfg publicURL | grep -q . && echo ', public URL'))" \
+ || warn "$CHUMS_CONFIG: not yet; the hub writes it on its first start (bin/chums-hub)"
+[[ -n $(chums_cfg publicURL) ]] && ok "public URL $(chums_cfg publicURL)" || warn "no public URL yet: run bin/chums-tunnel (the watch needs it; the Simulator doesn't)"
+
+if (( LAUNCHD )); then
+ print "\nLaunchAgents ($CHUMS_LABEL_PREFIX.*):"
+ [[ -x "$CHUMS_NODE" ]] || chums_die "node not found; can't write the hub's LaunchAgent"
+ LA=~/Library/LaunchAgents; D=gui/$(id -u); mkdir -p $LA ~/.chums/tailscale
+ hub=$LA/$CHUMS_LABEL_PREFIX.hub.plist
+ # a hub started in a terminal holds the ports: the LaunchAgent's would fail and be restarted over and over
+ port=$(chums_cfg port); port=${port:-7717}
+ held=$(lsof -nP -t -iTCP:$port -sTCP:LISTEN 2>/dev/null | head -1)
+ if [[ -n $held ]] && ! launchctl print $D/$CHUMS_LABEL_PREFIX.hub 2>/dev/null | grep -q "state = running"; then
+ chums_die "a hub is already running (pid $held, port $port), most likely bin/chums-hub in a terminal: stop it there (Ctrl-C), then run bin/chums-setup --launchd again"
+ fi
+ # the hub and tailscaled run through Chums.app, so every permission they and the agents need belongs to "Chums".
+ # The hub is Interactive: without it launchd throttles it (and Whisper and Kokoro, its children) as background work,
+ # and speech in and out is slower after a quiet while.
+ APPX=$(CHUMS_NO_RESTART=1 "$ROOT/tools/mac-app/build.zsh") || chums_die "couldn't build ~/Applications/Chums.app"
+ # a LaunchAgent gets no shell PATH: node's and whisperkit-cli's folders, then Homebrew's (Apple silicon, Intel)
+ WK=$(command -v whisperkit-cli 2>/dev/null)
+ HUBPATH=${CHUMS_NODE:h}${WK:+:${WK:h}}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
+ cat > $hub <<PL
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+ <key>Label</key><string>$CHUMS_LABEL_PREFIX.hub</string>
+ <key>ProgramArguments</key><array><string>$APPX</string><string>/usr/bin/caffeinate</string><string>-s</string><string>$CHUMS_NODE</string><string>$ROOT/hub/hub.mjs</string></array>
+ <key>EnvironmentVariables</key><dict><key>PATH</key><string>$HUBPATH</string></dict>
+ <key>RunAtLoad</key><true/>
+ <key>KeepAlive</key><true/>
+ <key>ProcessType</key><string>Interactive</string>
+ <key>StandardOutPath</key><string>$HOME/.chums/hub.log</string>
+ <key>StandardErrorPath</key><string>$HOME/.chums/hub.log</string>
+</dict></plist>
+PL
+ chums_reload $CHUMS_LABEL_PREFIX.hub $hub && ok "hub: $hub (log ~/.chums/hub.log)"
+ if command -v tailscaled >/dev/null; then
+ tsd=$LA/$CHUMS_LABEL_PREFIX.tailscaled.plist
+ cat > $tsd <<PL
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+ <key>Label</key><string>$CHUMS_LABEL_PREFIX.tailscaled</string>
+ <key>ProgramArguments</key><array><string>$APPX</string><string>$(command -v tailscaled)</string><string>--tun=userspace-networking</string>
+ <string>--statedir=$HOME/.chums/tailscale</string><string>--socket=$HOME/.chums/tailscale/tailscaled.sock</string><string>--port=0</string></array>
+ <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
+ <key>StandardOutPath</key><string>$HOME/.chums/tailscale/tailscaled.log</string><key>StandardErrorPath</key><string>$HOME/.chums/tailscale/tailscaled.log</string>
+</dict></plist>
+PL
+ chums_reload $CHUMS_LABEL_PREFIX.tailscaled $tsd && ok "tailscaled: $tsd"
+ fi
+fi
+
+print
+if (( missing )); then print "$missing missing. Install them and run bin/chums-setup again (details: docs/setup.md, \"What you need\")."; exit 1; fi
+print "Ready. Next: bin/chums-hub, then bin/chums-tunnel, then bin/chums-install (or bin/chums-sim). See docs/setup.md."
+print "bin/chums-doctor checks the whole chain (sign-ins, hub, Funnel, Xcode, the watch) at any point."
diff --git a/bin/chums-sim b/bin/chums-sim
new file mode 100755
index 0000000..38b9cf0
--- /dev/null
+++ b/bin/chums-sim
@@ -0,0 +1,52 @@
+#!/bin/zsh
+# Run the Chums watch app in the watchOS Simulator (no signing needed). Talks to the hub on this Mac.
+set -e
+ROOT="${0:A:h:h}"
+source "$ROOT/tools/common.zsh"
+chums_help "$@"
+: ${DEVELOPER_DIR:=/Applications/Xcode.app/Contents/Developer}; export DEVELOPER_DIR
+[[ -d $DEVELOPER_DIR ]] || chums_die "Xcode not found at $DEVELOPER_DIR. Install Xcode 26 or later, or set DEVELOPER_DIR."
+chums_need xcodegen "Install it with: brew install xcodegen"
+chums_need_config
+NAME="Chums Watch"
+
+"$ROOT/tools/gen-config.sh" >/dev/null
+cd "$ROOT/app"
+: ${CHUMS_BUNDLE:=$(chums_cfg bundleId)}
+: ${CHUMS_BUNDLE:=dev.chums}
+export CHUMS_BUNDLE
+xcodegen generate --quiet
+LOG=$(mktemp)
+xcodebuild -project Chums.xcodeproj -target ChumsWatch -sdk watchsimulator -configuration Debug \
+ CODE_SIGNING_ALLOWED=NO SYMROOT="$PWD/build/sym" build > "$LOG" 2>&1 || true
+grep -E "error:|BUILD" "$LOG" | awk '!seen[$0]++' | head -20
+grep -q "BUILD SUCCEEDED" "$LOG" || chums_die "the build failed. Full log: $LOG (known errors: docs/troubleshooting.md)"
+rm -f "$LOG"
+
+UDID=$(xcrun simctl list devices -j | python3 -c '
+import json, sys
+for rt, devs in json.load(sys.stdin)["devices"].items():
+ for d in devs:
+ if d["name"] == sys.argv[1] and d["isAvailable"]: print(d["udid"]); raise SystemExit' "$NAME")
+if [[ -z "$UDID" ]]; then
+ RUNTIME=$(xcrun simctl list runtimes -j | python3 -c '
+import json, sys
+rts = [r for r in json.load(sys.stdin)["runtimes"] if r["platform"] == "watchOS" and r["isAvailable"]]
+print(rts[-1]["identifier"] if rts else "")')
+ [[ -z "$RUNTIME" ]] && { echo "No watchOS simulator runtime. Run: xcodebuild -downloadPlatform watchOS"; exit 1; }
+ TYPE=$(xcrun simctl list devicetypes -j | python3 -c '
+import json, sys
+t = [d for d in json.load(sys.stdin)["devicetypes"] if "Watch" in d["name"]]
+pick = next((d for d in t if "Series 7 (45mm)" in d["name"]), None) or next((d for d in t if "45mm" in d["name"] or "46mm" in d["name"]), t[-1] if t else None)
+print(pick["identifier"] if pick else "")')
+ [[ -z "$TYPE" ]] && chums_die "Xcode lists no Apple Watch simulator. Run: xcodebuild -downloadPlatform watchOS"
+ UDID=$(xcrun simctl create "$NAME" "$TYPE" "$RUNTIME")
+fi
+
+xcrun simctl boot "$UDID" 2>/dev/null || true
+open -a Simulator --args -CurrentDeviceUDID "$UDID"
+xcrun simctl bootstatus "$UDID" -b >/dev/null
+xcrun simctl install "$UDID" build/sym/Debug-watchsimulator/ChumsWatch.app
+xcrun simctl privacy "$UDID" grant microphone "$CHUMS_BUNDLE.watchkitapp" 2>/dev/null || true
+xcrun simctl launch "$UDID" "$CHUMS_BUNDLE.watchkitapp"
+echo "$UDID"
diff --git a/bin/chums-tunnel b/bin/chums-tunnel
new file mode 100755
index 0000000..6bb034f
--- /dev/null
+++ b/bin/chums-tunnel
@@ -0,0 +1,35 @@
+#!/bin/zsh
+# Puts the hub's watch API (127.0.0.1:7718, nothing else) on the internet with Tailscale Funnel, so the watch reaches
+# the Mac over whatever network it has: the iPhone in your pocket, Wi-Fi or cellular, at home or away. watchOS
+# doesn't support apps talking to a home-network address (TN3135), so this is the watch's real way to the Mac.
+# tailscaled runs without admin rights (userspace networking); its state is in ~/.chums/tailscale.
+# First run: sign in at the link it prints (and allow Funnel if it asks), then run bin/chums-install.
+set -e
+source "${0:A:h:h}/tools/common.zsh"
+chums_help "$@"
+chums_need tailscale "Install it with: brew install tailscale (the open-source CLI and tailscaled, not the App Store app)"
+chums_need tailscaled "Install it with: brew install tailscale"
+chums_need_config
+DIR=~/.chums/tailscale; SOCK=$DIR/tailscaled.sock; mkdir -p $DIR
+ts() { tailscale --socket="$SOCK" "$@" }
+if ! ts status --json >/dev/null 2>&1; then
+ if [[ -f ~/Library/LaunchAgents/$CHUMS_LABEL_PREFIX.tailscaled.plist ]]; then launchctl kickstart -k gui/$UID/$CHUMS_LABEL_PREFIX.tailscaled
+ else nohup tailscaled --tun=userspace-networking --statedir=$DIR --socket=$SOCK --port=0 >> $DIR/tailscaled.log 2>&1 &; fi
+ sleep 2
+fi
+if ! ts status >/dev/null 2>&1; then
+ echo "Signing Chums' tailscaled in to your tailnet: open the link below, sign in and connect the machine (first time only)."
+ ts up --hostname=chums-hub
+fi
+PORT=$(python3 -c "import json,os;print(json.load(open(os.path.expanduser('~/.chums/config.json'))).get('publicPort', 7718))")
+echo "Turning on Funnel for 127.0.0.1:$PORT. If a link appears, open it and approve: it turns on HTTPS certificates and Funnel."
+ts funnel --bg $PORT
+HOST=$(ts status --json | python3 -c "import json,sys;print(json.load(sys.stdin)['Self']['DNSName'].rstrip('.'))")
+python3 - "https://$HOST" <<'PY'
+import json, os, sys
+p = os.path.expanduser('~/.chums/config.json'); c = json.load(open(p)); c['publicURL'] = sys.argv[1]
+json.dump(c, open(p, 'w'), indent=2); os.chmod(p, 0o600)
+PY
+echo "The watch API is at https://$HOST (Tailscale Funnel). Run bin/chums-install to build it into the watch app."
+echo "A new Funnel name can take up to 10 minutes (it has taken about 25) to appear in public DNS."
+echo "bin/chums-doctor checks it from outside: public DNS, then a request through Funnel."
diff --git a/channel/chums-channel.mjs b/channel/chums-channel.mjs
new file mode 100755
index 0000000..b76d96c
--- /dev/null
+++ b/channel/chums-channel.mjs
@@ -0,0 +1,250 @@
+#!/usr/bin/env node
+// Chums channel: a Claude Code channel (MCP server) that connects one session to the Chums hub.
+// in: orders spoken on the watch -> notifications/claude/channel
+// out: chums_reply tool -> one spoken line on the watch
+// both ways: permission prompts -> approval card on the watch -> allow/deny verdict
+// Launched by Claude Code (see bin/chums-claude). Talks to the hub over localhost HTTP.
+//
+// Tools only (CHUMS_SESSION set): for agents the hub itself drives (Codex, Copilot and other Agent Client Protocol
+// agents, hub/runtimes.mjs), which give it to their agent as an ordinary MCP server. The hub already knows the session
+// and brings it orders and verdicts, so this only offers chums_reply and chums_show for that session: no channel, no
+// registering, no polling.
+
+import os from 'node:os'
+import fs from 'node:fs'
+import path from 'node:path'
+import crypto from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { Server } from '@modelcontextprotocol/sdk/server/index.js'
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
+import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
+import { z } from 'zod'
+import { MAX_WORDS, PHONE_WORDS, WATCH_GUIDE, PAGE_GUIDE, OWNER, Owner, wordsFor } from '../hub/standing.mjs'
+
+const toolsOnly = !!process.env.CHUMS_SESSION
+// a hub-driven agent's MCP server gets the hub's address from the hub, and its token or the file that has it (its HOME
+// may be another)
+const CONFIG = process.env.CHUMS_CONFIG || path.join(os.homedir(), '.chums', 'config.json')
+let cfg
+try { cfg = process.env.CHUMS_HUB && process.env.CHUMS_TOKEN ? { token: process.env.CHUMS_TOKEN } : JSON.parse(fs.readFileSync(CONFIG, 'utf8')) }
+catch (e) {
+ // (not e.message: a JSON error quotes the file, and the file holds the token)
+ process.stderr.write(`[chums] can't read ${CONFIG} (${e.code ?? 'not valid JSON'}). Start the hub once (bin/chums-hub): it writes it.\n`)
+ process.exit(1)
+}
+const HUB = process.env.CHUMS_HUB || `http://127.0.0.1:${cfg.port}`
+const sessionId = process.env.CHUMS_SESSION || crypto.randomUUID()
+const name = process.env.CHUMS_NAME || path.basename(process.cwd())
+const err = (...a) => process.stderr.write(`[chums] ${a.join(' ')}\n`)
+
+async function hub(pathname, body, method = body ? 'POST' : 'GET') {
+ const res = await fetch(HUB + pathname, {
+ method,
+ headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/json' },
+ body: body ? JSON.stringify(body) : undefined,
+ })
+ if (!res.ok) {
+ const why = await res.json().then(b => b.error).catch(() => null)
+ throw Object.assign(new Error(why ?? `hub ${res.status} ${pathname}`), { status: res.status })
+ }
+ return res.json()
+}
+
+const mcp = new Server(
+ { name: 'chums', version: '0.1.0' },
+ {
+ capabilities: toolsOnly ? { tools: {} } : {
+ experimental: { 'claude/channel': {}, 'claude/channel/permission': {} },
+ tools: {},
+ },
+ instructions: toolsOnly ? WATCH_GUIDE : [
+ `${Owner} talks to this session (named "${name}") from an Apple Watch, often away from the desk.`,
+ `${Owner}'s messages arrive as <channel source="chums" utterance_id="..." via="watch"> or via="phone"; from the watch they are voice transcripts, so expect recognition errors and read for intent.`,
+ 'Do the work exactly as if it had been typed here.',
+ `Whenever you finish work ${OWNER} asked for from the watch, or you need ${OWNER}, call the chums_reply tool.`,
+ 'The watch is a small conversational companion, not a reading surface: reply like a quick text message, about 8 words,',
+ `${MAX_WORDS} at most (the tool refuses longer). Result first, plain words, no preamble, no restating what was said,`,
+ 'no explanations. If there is more to say, it stays on the Mac: say "Details on your Mac."',
+ `From the iPhone (via="phone") the reply is shown as text: give the answer itself in plain sentences, ${PHONE_WORDS} words at most, still no code, paths, URLs, markdown or lists.`,
+ 'Never include code, file paths, URLs, markdown or lists; they are read aloud.',
+ "Set status: 'done' when finished, 'question' when you need an answer, 'blocked' when you cannot continue, 'working' only for a rare progress note on long tasks.",
+ `To ask ${OWNER} something (a choice, a go-ahead), call chums_reply with status 'question' and wait: the answer comes as the next message. Don't use AskUserQuestion: its dialog shows only in this terminal, where nobody is.`,
+ 'Only use chums_reply for messages that came from the watch, not for messages typed in the terminal.',
+ 'The watch shows and speaks every chums_reply; you cannot see or hear it, and that is expected.',
+ `If ${OWNER} asks whether you can hear, just answer. Never investigate the watch app or the hub unless asked to.`,
+ `Never start replies with a name or give yourself one: on the watch you appear as the character ${OWNER} picked.`,
+ `When ${OWNER} asks to see something (the screen, an app or browser tab, a web page, a file, an image, a chart), or you made something visual that was asked for, call chums_show instead of chums_reply: it puts a picture in the watch chat that can be opened and zoomed, and says its text; the iPhone opens the file itself.`,
+ "For the whole screen use screenshot: 'screen'; for an app use its name, e.g. screenshot: 'Safari'. chums_show finds the app's window itself and is quick: call it first, without looking for apps, windows or browser extensions some other way. If what's wanted isn't on screen in that app (a Stripe dashboard, say), also pass open: its URL, and it opens there before the screenshot. Pages that need a login (dashboards, mail) are screenshots of the browser; a public page is url; a file is file (a page, a document, a PDF, text or code, a table, an image or a video). If it fails, the error says why and which apps have windows open.", PAGE_GUIDE,
+ ].join(' '),
+ },
+)
+
+// For hub-driven agents: neither tool changes anything on the Mac (one speaks on the watch, the other shows a picture
+// there), so agents that ask before MCP tool calls that might can run them without asking.
+const QUIET = { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false }
+
+mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
+ tools: [{
+ name: 'chums_reply',
+ description: `Speak one short sentence to ${OWNER} on the Apple Watch. Use after finishing or when you need ${OWNER}.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ text: { type: 'string', description: `One short spoken sentence, like a text message: about 8 words, ${MAX_WORDS} at most (to the iPhone: plain sentences, ${PHONE_WORDS} words at most). No code, paths or URLs.` },
+ status: { type: 'string', enum: ['done', 'question', 'blocked', 'working'] },
+ },
+ required: ['text'],
+ },
+ ...(toolsOnly ? { annotations: QUIET } : {}),
+ }, {
+ name: 'chums_show',
+ description: `Show ${OWNER} something on the Apple Watch and the iPhone: a screenshot of the screen or an app window, a web page, or a file: a page, a document, a PDF, text or code, a table, an image or a video. The watch shows it as a picture that can be opened and zoomed (a video as a still), with a short spoken line; the iPhone opens the file itself. ${PAGE_GUIDE}`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ screenshot: { type: 'string', description: "'screen' for the whole display, or an app's name (e.g. 'Safari') for its front window." },
+ open: { type: 'string', description: "With screenshot of an app: a URL to open in that app first (e.g. 'https://dashboard.stripe.com'), for when what's wanted isn't already on screen there." },
+ url: { type: 'string', description: 'A public web page to render at phone width (not one behind a login: screenshot the browser instead).' },
+ file: { type: 'string', description: 'Absolute path of the file: HTML or SVG, PDF, Markdown, text or code, CSV or TSV, an image, a video (.mov, .mp4, .m4v), or a document macOS previews (Word, Excel, PowerPoint, Pages, Keynote, Numbers, RTF, EPUB, USDZ).' },
+ title: { type: 'string', description: 'Two to four words, shown on the watch, e.g. "Stripe dashboard".' },
+ text: { type: 'string', description: `One short spoken line, like a reply: ${MAX_WORDS} words at most.` },
+ },
+ },
+ ...(toolsOnly ? { annotations: QUIET } : {}),
+ }],
+}))
+
+// a screenshot of the whole screen, or of an app's front window, as a PNG. It needs the Screen Recording permission of
+// the app this session runs in (macOS asks for it, or it's in System Settings › Privacy & Security).
+const sh = (cmd, args) => new Promise((resolve, reject) => execFile(cmd, args, { timeout: 15_000 }, (e, out, errOut) => e ? reject(new Error(String(errOut || e.message).trim())) : resolve(String(out).trim())))
+async function screenshot(target) {
+ const out = path.join(os.tmpdir(), `chums-shot-${Date.now()}.png`)
+ if (/^(screen|desktop|display|everything)$/i.test(target)) { await sh('/usr/sbin/screencapture', ['-x', out]); return { file: out, from: 'screen' } }
+ const js = `ObjC.import("CoreGraphics");
+ const all = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo($.kCGWindowListOptionAll | $.kCGWindowListExcludeDesktopElements, $.kCGNullWindowID)));
+ const want = ${JSON.stringify(target.toLowerCase())};
+ const w = all.filter(w => w.kCGWindowLayer === 0 && (w.kCGWindowOwnerName || "").toLowerCase().includes(want) && w.kCGWindowBounds.Height > 150 && w.kCGWindowBounds.Width > 150)
+ .sort((a, b) => (b.kCGWindowIsOnscreen ? 1 : 0) - (a.kCGWindowIsOnscreen ? 1 : 0));
+ w.length ? w[0].kCGWindowNumber + " " + w[0].kCGWindowOwnerName : ""`
+ const found = await sh('/usr/bin/osascript', ['-l', 'JavaScript', '-e', js])
+ if (!found) {
+ // say which apps do have windows, so the session can pick the right one
+ const open = await sh('/usr/bin/osascript', ['-l', 'JavaScript', '-e', `ObjC.import("CoreGraphics");
+ const all = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo($.kCGWindowListOptionAll | $.kCGWindowListExcludeDesktopElements, $.kCGNullWindowID)));
+ [...new Set(all.filter(w => w.kCGWindowLayer === 0 && w.kCGWindowBounds.Height > 150).map(w => w.kCGWindowOwnerName))].join(", ")`]).catch(() => '')
+ throw new Error(`No open window of ${target}.${open ? ` Apps with windows open: ${open}.` : ''}`)
+ }
+ const [wid, ...owner] = found.split(' ')
+ await sh('/usr/sbin/screencapture', ['-x', '-o', '-l', wid, out])
+ return { file: out, from: owner.join(' ') }
+}
+const PERMISSION = `macOS refused the screenshot: the app this session runs in needs Screen Recording (System Settings › Privacy & Security › Screen & System Audio Recording). Tell ${OWNER}, in a few words.`
+
+mcp.setRequestHandler(CallToolRequestSchema, async req => {
+ if (req.params.name === 'chums_show') return show(req.params.arguments ?? {})
+ if (req.params.name !== 'chums_reply') throw new Error(`unknown tool: ${req.params.name}`)
+ const { text, status = 'done' } = req.params.arguments ?? {}
+ // the watch shows a line or two and reads it aloud: refuse anything longer, so the session says it again, shorter
+ // (the iPhone shows the text: a few sentences)
+ const words = String(text ?? '').trim().split(/\s+/).filter(Boolean).length, limit = wordsFor(lastVia)
+ if (words > limit) {
+ const where = lastVia === 'phone' ? 'the iPhone' : 'the watch'
+ return { content: [{ type: 'text', text: `Too long for ${where} (${words} words). Say it again in ${limit} words or fewer; details stay on the Mac.` }], isError: true }
+ }
+ try {
+ await hub('/channel/reply', { sessionId, text: String(text), status })
+ return { content: [{ type: 'text', text: 'Spoken on the watch.' }] }
+ } catch (e) {
+ return { content: [{ type: 'text', text: `The watch hub is unreachable (${e.message}); ${OWNER} did not hear this.` }], isError: true }
+ }
+})
+
+async function show({ screenshot: target, open: openURL, url, file, title, text }) {
+ const fail = t => ({ content: [{ type: 'text', text: t }], isError: true })
+ const words = String(text ?? '').trim().split(/\s+/).filter(Boolean).length
+ if (words > wordsFor(lastVia)) return fail(`Too long (${words} words). Say it in ${wordsFor(lastVia)} words or fewer.`)
+ if (!target && !url && !file) return fail('Give screenshot, url or file.')
+ let shot
+ if (target) {
+ // what's wanted isn't on screen yet: open it in that app, and give the page a moment to load
+ if (openURL && !/^(screen|desktop|display|everything)$/i.test(target)) {
+ try { await sh('/usr/bin/open', ['-a', String(target), String(openURL)]); await new Promise(r => setTimeout(r, 3500)) }
+ catch (e) { return fail(`Couldn't open ${openURL} in ${target}: ${e.message}`) }
+ }
+ try { shot = await screenshot(String(target)) }
+ catch (e) { return fail(/could not create image|not permitted|denied/i.test(e.message) ? PERMISSION : `Screenshot failed: ${e.message}`) }
+ }
+ try {
+ const a = await hub('/channel/artifact', {
+ sessionId, file: shot?.file ?? file, url, title: title ?? (shot ? shot.from : undefined), text,
+ kind: shot ? 'screenshot' : undefined, from: shot?.from,
+ })
+ return { content: [{ type: 'text', text: `Shown on the watch: ${a.title} (${a.w}×${a.h}).` }] }
+ } catch (e) {
+ return fail(e.status === 422 ? `The watch couldn't show it: ${e.message}` : `The watch hub is unreachable (${e.message}); ${OWNER} did not see this.`)
+ } finally { if (shot) fs.rm(shot.file, () => {}) }
+}
+
+const PermissionRequest = z.object({
+ method: z.literal('notifications/claude/channel/permission_request'),
+ params: z.object({
+ request_id: z.string(),
+ tool_name: z.string(),
+ description: z.string(),
+ input_preview: z.string(),
+ }),
+})
+
+mcp.setNotificationHandler(PermissionRequest, async ({ params }) => {
+ try { await hub('/channel/permission', { sessionId, ...params }) }
+ catch (e) { err('could not relay permission request:', e.message) }
+})
+
+await mcp.connect(new StdioServerTransport())
+
+// ---- hub loop: register, then long-poll for orders and verdicts ----
+// Each item is acknowledged on the next poll; the hub sends it again until then, so ids already handled are skipped.
+let registered = false
+let lastVia = 'watch' // where the latest order was said: its reply's length follows
+const handled = new Set(), handledOrder = []
+async function loop() {
+ let ack = []
+ for (;;) {
+ try {
+ if (!registered) {
+ await hub('/channel/register', { sessionId, name, cwd: process.cwd() })
+ registered = true
+ err('connected to hub as', name)
+ }
+ const { items } = await hub(`/channel/next?sessionId=${sessionId}${ack.length ? `&ack=${ack.join(',')}` : ''}`)
+ ack = items.map(it => it.id).filter(Boolean)
+ for (const it of items) {
+ if (it.id && handled.has(it.id)) continue
+ if (it.id) { handled.add(it.id); handledOrder.push(it.id); if (handledOrder.length > 500) handled.delete(handledOrder.shift()) }
+ if (it.type === 'order') {
+ lastVia = it.device === 'phone' ? 'phone' : 'watch'
+ await mcp.notification({
+ method: 'notifications/claude/channel',
+ params: { content: it.text, meta: { utterance_id: it.utteranceId, via: lastVia } },
+ })
+ } else if (it.type === 'verdict') {
+ await mcp.notification({
+ method: 'notifications/claude/channel/permission',
+ params: { request_id: it.requestId, behavior: it.behavior },
+ })
+ }
+ }
+ } catch (e) {
+ // 404: the hub restarted and forgot us, re-register now. Anything else: hub down, retry in 5 s.
+ registered = false
+ if (e.status !== 404) await new Promise(r => setTimeout(r, 5000))
+ }
+ }
+}
+const bye = () => { hub('/channel/bye', { sessionId }).catch(() => {}).finally(() => process.exit(0)) }
+if (toolsOnly) process.stdin.on('end', () => process.exit(0)) // the hub owns this session: no register, poll or bye
+else {
+ loop()
+ process.stdin.on('end', bye)
+ process.on('SIGTERM', bye)
+}
diff --git a/channel/chums-hook.mjs b/channel/chums-hook.mjs
new file mode 100644
index 0000000..0825b2a
--- /dev/null
+++ b/channel/chums-hook.mjs
@@ -0,0 +1,41 @@
+#!/usr/bin/env node
+// Claude Code hook -> Chums hub. Runs on the hook events chums-claude registers (tool calls and failures,
+// permission requests, notifications, prompts, stops and stop failures, compaction, subagents, session start/end),
+// so the watch shows what the session is doing as it happens.
+// It never blocks Claude Code: it prints nothing, always exits 0, and gives up after 800 ms.
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+const done = () => process.exit(0)
+setTimeout(done, 800).unref()
+
+let input = ''
+process.stdin.on('data', c => { input += c })
+process.stdin.on('end', async () => {
+ try {
+ const cfg = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.chums/config.json'), 'utf8'))
+ const ev = JSON.parse(input || '{}')
+ const cwd = ev.cwd || process.cwd()
+ const body = {
+ name: process.env.CHUMS_NAME || path.basename(cwd),
+ cwd,
+ event: ev.hook_event_name,
+ tool: ev.tool_name ?? null,
+ input: ev.tool_input ?? null,
+ // enough of the result to tell a passing test run from a failing one
+ result: ev.tool_response ? JSON.stringify(ev.tool_response).slice(-1500) : null,
+ // what the other events carry: why it stopped, what it needs, which subagent, which compaction
+ notification: ev.notification_type ?? null, message: ev.message ?? null,
+ error: ev.error_type ?? ev.error ?? null, trigger: ev.trigger ?? null,
+ agent: ev.agent_id ?? null, agentType: ev.agent_type ?? null,
+ source: ev.source ?? null, reason: ev.reason ?? null, mode: ev.permission_mode ?? null,
+ }
+ await fetch(`http://127.0.0.1:${cfg.port}/hook`, {
+ method: 'POST', body: JSON.stringify(body),
+ headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/json' },
+ signal: AbortSignal.timeout(700),
+ })
+ } catch {}
+ done()
+})
diff --git a/design/STATES.md b/design/STATES.md
new file mode 100644
index 0000000..97aef8c
--- /dev/null
+++ b/design/STATES.md
@@ -0,0 +1,96 @@
+# Chums states
+
+What the watch shows is driven by what Claude Code and Codex actually report. This maps every signal to a **state**
+(persists until something else is true), a **reaction** (a one-shot over the current state), a **detail** of a state,
+or nothing. Verified on 2026-10-02 against the
+[Claude Code hooks reference](https://code.claude.com/docs/en/hooks) (33 hook events) and the
+[Agent Client Protocol schema](https://github.com/agentclientprotocol/agent-client-protocol/blob/main/schema/v1/schema.json) (v1);
+the Codex column on 2026-10-10 against Codex 0.160's own app-server schema (`codex app-server generate-ts`). The hub
+turns Codex's (and ACP agents') signals into the Claude Code hook events of the same row (`hub/runtimes.mjs`), so
+everything below them is shared.
+
+Character names in the tables below predate the October 2026 rename: Eyes is now Peeps, the Blender Noodle is
+Stretch, and Pix is Crunch (apple) and Nana (banana).
+
+The hub computes everything below. The watch app (`app/ChumsWatch/Controller.swift`) shows less of it today:
+
+- Thinking shows while what you said is sent and transcribed, and while an agent compacts. From a prompt to the first
+ tool call the hub reports `working`, and the watch shows Working.
+- Waiting (rate limited) shows as Blocked, and Compacting as Thinking.
+- Sleep shows when the agent has no session on the Mac or the watch can't reach the hub. Nothing puts an agent to
+ sleep after 10 minutes without activity; `SessionEnd` makes it idle.
+- Of the reactions, Tool call and Poke play. Tool failed, Interrupted and Wake don't: the watch doesn't read the hub's
+ `reactions`.
+- Done follows a turn in which the agent used tools. Its *approved* variant follows any approval you allowed, with no
+ 5 s window. Approval has no *plan* variant on the watch.
+
+## States
+
+Priority decides which state wins when several sessions disagree (highest first). Only Needs you, Approval and
+Blocked interrupt you with a haptic you can't miss.
+
+| State | Priority | Claude Code hooks | Codex app-server | Agent Client Protocol | Watch-side |
+| --- | --- | --- | --- | --- | --- |
+| Approval | 10 | `PermissionRequest`; `Notification` `permission_prompt` | `item/commandExecution/requestApproval`, `item/fileChange/requestApproval`, `item/permissions/requestApproval` | `session/request_permission` (options `allow_once`, `allow_always`, `reject_once`, `reject_always`) | variant *plan*: `ExitPlanMode` asks you to approve a plan |
+| Needs you | 9 | `Notification` `idle_prompt`, `elicitation_dialog`, `elicitation_url_dialog`, `agent_needs_input`; `Elicitation` | `thread/status/changed` `waitingOnUserInput`; `item/tool/requestUserInput` | — | variant *question*: it asked something |
+| Blocked | 8 | `StopFailure` `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `cloud_credential_error`, `unknown` | `turn/completed` `failed` (any other error) | stop reason `refusal`, `max_tokens`, `max_turn_requests` | |
+| Listening | 7 | — | — | — | you hold the screen |
+| Waiting **(new)** | 6 | `StopFailure` `rate_limit`, `overloaded`; ends on `Notification` `quota_auto_resume_fired` | `turn/completed` `failed` with `usageLimitExceeded`, `rateLimitExceeded`, `serverOverloaded`, `sessionBudgetExceeded` | — | resumes by itself; shows when |
+| Speaking | 6 | `MessageDisplay`; the `chums_reply` channel tool | the `chums_reply` MCP tool; else the turn's `final_answer`, said by the hub | `agent_message_chunk` | |
+| Done | 6 | `Stop`; `Notification` `agent_completed` | `turn/completed` `completed` | stop reason `end_turn` | variant *approved*: you allowed it within 5 s |
+| Thinking | 5 | from `UserPromptSubmit` until the first tool call or message | from `turn/started` until the first item | `agent_thought_chunk` | also while your words are transcribed |
+| Compacting **(new)** | 5 | `PreCompact` (`manual`, `auto`) until `PostCompact` | `item/started` … `item/completed` `contextCompaction` | — | |
+| Working | 4 | `PreToolUse` … `PostToolUse` | `item/started` … `item/completed` (`commandExecution`, `fileChange`, `mcpToolCall`, `webSearch`) | `tool_call` / `tool_call_update` (`pending`, `in_progress`) | detail: the kind of tool, below |
+| Subagents | 4 | `SubagentStart` / `SubagentStop` (count of live `agent_id`s); `TeammateIdle` | `subAgentActivity`; `collabAgentToolCall` `spawnAgent` / `closeAgent` | — | |
+| Dizzy | 3 | — | — | — | you shake your keys |
+| Idle | 2 | `SessionStart` `startup`, `resume`, `clear`, `fork` | `thread/start`, `thread/resume` (the hub starts its app-server) | — | |
+| Sleep | 1 | `SessionEnd` (`clear`, `resume`, `logout`, `prompt_input_exit`, `other`); 10 min without activity | its app-server exits (offline) | — | variant *offline*: the Mac or the hub is unreachable |
+
+### Working, by kind of tool
+
+| Kind (ACP `ToolKind`) | Claude Code tools | Stretch | Peeps | Crunch, Nana |
+| --- | --- | --- | --- | --- |
+| `read` | Read, NotebookRead | reads lines, eyes sweeping | reads the page | +1 READ |
+| `search` / `fetch` | Grep, Glob, WebSearch, WebFetch | looks around | reads the page | +1 GREP |
+| `edit` / `delete` / `move` | Edit, Write, MultiEdit, NotebookEdit | pecks along like typing | a line is rewritten | +1 EDIT |
+| `execute` | Bash | leans in and watches the output scroll | a command and its output | +1 BASH |
+| `think` / `other` / `switch_mode` | Task, Skill, everything else | reads | reads | +1 tool name |
+
+## Reactions
+
+One-shot, played over whatever state is current.
+
+| Reaction | Signal | What it looks like |
+| --- | --- | --- |
+| Tool call | `PreToolUse`; Codex `item/started`; ACP `tool_call` | Noodle: a card drops on its head and it bonks it away. Eyes: a new line. Pix: +1 TOOL floats up |
+| Tool failed | `PostToolUseFailure`; `PermissionDenied`; Codex `item/completed` `failed` (a command that couldn't run; one that exits non-zero is only marked failed); ACP `tool_call_update` `failed` | a flinch, then a guilty look at you |
+| Interrupted | you stopped it: a tool result with `interrupted`, a new prompt while it works; Codex `turn/completed` `interrupted`; ACP stop reason `cancelled` | it freezes mid-move, then looks at you |
+| Wake | `SessionStart` | pops up |
+| Poke, pet | your finger | |
+
+## Not acted (planned for the status row, not built yet)
+
+| Signal | Where it will show |
+| --- | --- |
+| Permission mode (`default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`; ACP `current_mode_update`) | the status row, as a badge |
+| Plan and tasks (`TaskCreated`, `TaskCompleted`; ACP `plan` entries `pending`, `in_progress`, `completed`) | the status row, as 3 / 5 |
+| Context use (ACP `usage_update`) | Compacting is the state that matters; usage itself isn't shown |
+
+## Ignored on purpose
+
+`Setup`, `UserPromptExpansion`, `PostToolBatch`, `InstructionsLoaded`, `ConfigChange`, `CwdChanged`, `DirectoryAdded`,
+`FileChanged`, `WorktreeCreate`, `WorktreeRemove`, `PreModelSwitch`, `PostModelSwitch`, `ElicitationResult`,
+`Notification` `auth_success`, `elicitation_complete`, `elicitation_response`, `quota_auto_resume_stale`,
+`quota_auto_resume_disabled`; ACP `user_message_chunk`, `available_commands_update`, `config_option_update`,
+`session_info_update`. None of them changes what you need to know from your keys.
+
+## Where it's implemented
+
+- `bin/chums-claude` registers the hooks; `channel/chums-hook.mjs` forwards each event; `hub/hub.mjs` (`onHook`) turns
+ them into session statuses (`idle`, `working`, `waiting`, `blocked`, `limited`, `compacting`) and reactions.
+- `hub/runtimes.mjs` does the same for agents the hub runs (Codex; experimental: Copilot, ACP agents): it puts their
+ events into hook events for `onHook`. `docs/other-agents.md` has the details.
+- `app/ChumsWatch/Rig/` acts every state out for every character; `design/noodle/animate.py` renders Stretch's.
+- `app/ChumsWatch/Controller.swift` maps hub statuses onto the watch rig. Waiting and Compacting show as Blocked and
+ Thinking there; the rig has no Waiting or Compacting state yet (`Rig/Pix.swift` already draws both for Crunch and
+ Nana).
diff --git a/design/characters/coil3d/CoilRest-fit.swift b/design/characters/coil3d/CoilRest-fit.swift
new file mode 100644
index 0000000..dbfbd00
--- /dev/null
+++ b/design/characters/coil3d/CoilRest-fit.swift
@@ -0,0 +1,27 @@
+import CoreGraphics
+
+// Generated from the reference (design/characters/coil): the tube at rest as a chain of points, its thickness along it,
+// its colour model, and where its head sits. Regenerate with design/characters/coil/export.py; do not edit by hand.
+
+enum CoilRest {
+ /// Its colour: an albedo along it (16 knots, tail to head) times a light shared by all of it, plus a white sheen, both as
+ /// 9 lighting terms of where the surface faces (1, x, y, z, xy, xz, yz, x²−y², 3z²−1); and, for where it lies as
+ /// traced, a small correction per knot that matches the reference closer.
+ static let albedo: [SIMD3<Double>] = [SIMD3(0.29726, 0.42719, 0.87854), SIMD3(0.61576, 0.46785, 0.87616), SIMD3(0.19151, 0.61922, 0.95174), SIMD3(0.19626, 0.68465, 0.95191), SIMD3(0.11870, 0.53001, 0.92171), SIMD3(0.20187, 0.38485, 0.90982), SIMD3(0.53575, 0.24933, 0.86741), SIMD3(0.69910, 0.15308, 0.67251), SIMD3(0.83687, 0.29390, 0.51923), SIMD3(0.78161, 0.31251, 0.70288), SIMD3(0.54595, 0.40696, 0.91386), SIMD3(0.53748, 0.34651, 0.90227), SIMD3(0.71375, 0.31993, 0.88333), SIMD3(0.88956, 0.46480, 0.77386), SIMD3(0.92825, 0.44527, 0.22190), SIMD3(0.92659, 0.47725, 0.18046)]
+ static let light: [Double] = [0.84488, -0.10194, 0.21310, 0.55242, -0.03921, 0.14323, -0.16665, 0.06919, -0.13055]
+ static let sheen: [Double] = [0.03846, 0.03785, -0.14596, -0.18758, -0.03766, -0.15785, 0.07060, -0.08013, 0.03057]
+ static let correction: [SIMD3<Double>] = [SIMD3(-0.11479, 0.03663, -0.03730), SIMD3(-0.01702, -0.01006, -0.01592), SIMD3(-0.07834, -0.08654, -0.14076), SIMD3(0.23077, -0.11557, 0.03043), SIMD3(-0.09008, 0.04780, -0.08199), SIMD3(0.02750, 0.09961, -0.01994), SIMD3(0.22502, 0.15344, 0.19903), SIMD3(0.03440, -0.02215, 0.04956), SIMD3(-0.07793, 0.05523, 0.01766), SIMD3(-0.06734, 0.01130, 0.06889), SIMD3(0.04962, -0.02982, 0.00174), SIMD3(0.03001, 0.02776, 0.01156), SIMD3(0.12098, -0.00311, -0.12357), SIMD3(-0.03263, 0.16984, 0.03874), SIMD3(-0.32263, 0.03174, 0.08335), SIMD3(0.02716, -0.18727, 0.00381), SIMD3(-0.07725, 0.12420, -0.02175), SIMD3(-0.08270, -0.00584, 0.04834), SIMD3(-0.00307, 0.07272, -0.01096), SIMD3(0.05728, 0.01882, -0.00930), SIMD3(0.01104, 0.00377, -0.00545), SIMD3(0.01192, -0.14879, 0.02196), SIMD3(0.04348, -0.07505, 0.00467), SIMD3(-0.19121, -0.16088, 0.05048), SIMD3(-0.06647, -0.02914, 0.02816), SIMD3(0.01283, -0.01248, 0.00484), SIMD3(0.02025, 0.06060, -0.01611), SIMD3(-0.05545, 0.12960, -0.00362), SIMD3(-0.02508, -0.00719, 0.00185), SIMD3(0.02340, 0.00797, 0.00095), SIMD3(0.11129, -0.26407, 0.01197), SIMD3(-0.06919, -0.09246, 0.01016), SIMD3(0.10390, 0.01789, 0.02013), SIMD3(-0.07908, -0.07528, 0.00459), SIMD3(0.01510, 0.00205, 0.00186), SIMD3(-0.04421, 0.08777, -0.01045), SIMD3(-0.05487, 0.02551, 0.06082), SIMD3(-0.02908, -0.02142, -0.00191), SIMD3(0.00676, 0.02061, -0.00089), SIMD3(0.10676, -0.05928, -0.12894), SIMD3(0.02799, 0.04936, 0.01851), SIMD3(0.08662, 0.10681, 0.00383), SIMD3(-0.00309, -0.08215, -0.00606), SIMD3(0.02143, 0.03892, 0.00525), SIMD3(-0.03302, 0.00937, 0.03940), SIMD3(-0.05588, -0.04871, -0.02161), SIMD3(-0.01119, -0.00299, -0.00457), SIMD3(-0.03236, -0.01495, -0.01063), SIMD3(0.11460, 0.10338, 0.04422), SIMD3(0.01135, 0.01294, 0.00519), SIMD3(0.03386, 0.00841, 0.01807), SIMD3(0.09356, 0.06214, 0.02776), SIMD3(-0.00841, -0.01483, -0.00182), SIMD3(-0.03479, -0.03097, -0.01268), SIMD3(-0.16324, -0.05055, -0.09176), SIMD3(-0.00467, -0.00392, -0.00402), SIMD3(-0.01256, -0.00422, -0.00152), SIMD3(0.33073, 0.10242, 0.18929), SIMD3(0.02268, -0.00513, -0.00967), SIMD3(0.02450, 0.00635, 0.00094), SIMD3(0.06464, 0.01916, 0.03455), SIMD3(-0.01582, 0.00177, -0.00321), SIMD3(-0.11269, -0.03648, -0.06693), SIMD3(-0.12606, 0.01863, 0.00052), SIMD3(-0.00294, 0.00250, 0.01330), SIMD3(0.02305, -0.01540, 0.00394), SIMD3(0.26560, -0.04595, -0.00356), SIMD3(0.04496, 0.05186, 0.11928), SIMD3(0.03523, 0.03082, 0.04881), SIMD3(0.03434, 0.01553, 0.00005), SIMD3(-0.01669, -0.00656, -0.04035), SIMD3(-0.09979, 0.02283, -0.00096), SIMD3(-0.05138, 0.09574, 0.21870), SIMD3(0.01947, -0.06312, -0.05361), SIMD3(0.01008, -0.01951, -0.02579), SIMD3(0.10263, -0.17891, -0.44234), SIMD3(-0.01120, 0.04735, 0.06769), SIMD3(-0.19540, 0.16035, 0.27711), SIMD3(-0.09138, 0.01731, 0.04484), SIMD3(0.00474, 0.01811, 0.01418), SIMD3(-0.06381, 0.05747, 0.17647), SIMD3(-0.14468, 0.08496, 0.17569), SIMD3(0.05070, -0.00862, -0.02055), SIMD3(0.07340, -0.02409, -0.03409), SIMD3(0.30065, -0.18316, -0.38013), SIMD3(0.05702, -0.05572, -0.13446), SIMD3(-0.14641, 0.05347, 0.11295), SIMD3(-0.23644, 0.11616, 0.22231), SIMD3(-0.00870, 0.00621, 0.01859), SIMD3(-0.09914, 0.06266, 0.12793), SIMD3(0.13844, -0.06769, -0.06733), SIMD3(0.04995, -0.02355, -0.01892), SIMD3(0.07425, -0.02722, -0.02818), SIMD3(-0.28908, 0.14232, 0.14616), SIMD3(-0.05083, 0.02873, 0.04188), SIMD3(-0.15543, 0.06298, 0.05258), SIMD3(-0.21831, 0.07577, 0.05712), SIMD3(0.00546, -0.00219, -0.00400), SIMD3(0.09392, -0.04729, -0.05186), SIMD3(-0.04554, 0.12643, 0.05062), SIMD3(0.05890, 0.01406, -0.02389), SIMD3(0.09067, -0.00446, -0.03343), SIMD3(0.11385, -0.26314, -0.11999), SIMD3(0.05121, -0.04049, -0.03461), SIMD3(-0.10681, -0.04818, 0.01920), SIMD3(-0.19790, -0.02513, 0.06969), SIMD3(0.00793, -0.00293, -0.00439), SIMD3(-0.03907, 0.08288, 0.04603), SIMD3(-0.22617, 0.02858, 0.08106), SIMD3(0.07372, 0.00451, -0.07462), SIMD3(0.01058, 0.04803, -0.02941), SIMD3(0.48678, -0.06163, -0.18375), SIMD3(0.21756, -0.05959, -0.17918), SIMD3(0.01527, -0.11563, 0.07468), SIMD3(0.11426, -0.11206, -0.05739), SIMD3(0.02860, 0.00712, -0.02993), SIMD3(-0.19576, 0.04464, 0.08171), SIMD3(0.15015, -0.03708, -0.01055), SIMD3(-0.02823, -0.03558, 0.02517), SIMD3(-0.02501, 0.01670, 0.04809), SIMD3(-0.31425, 0.07146, 0.02411), SIMD3(0.03733, 0.00387, -0.10003), SIMD3(-0.01368, 0.05943, 0.03265), SIMD3(0.04920, -0.03314, -0.12050), SIMD3(-0.01013, 0.00398, 0.02923), SIMD3(0.11101, -0.02546, -0.02111), SIMD3(0.02170, -0.10705, 0.08748), SIMD3(0.01255, 0.03172, -0.03074), SIMD3(0.01188, 0.03073, -0.04390), SIMD3(-0.05404, 0.23434, -0.17644), SIMD3(-0.05629, 0.06702, 0.01531), SIMD3(0.03069, -0.16703, 0.07456), SIMD3(0.03782, -0.23373, 0.14726), SIMD3(0.01273, -0.01763, 0.00049), SIMD3(0.02499, -0.09840, 0.06294), SIMD3(0.04552, -0.08324, 0.05823), SIMD3(-0.01913, 0.00042, -0.01808), SIMD3(-0.02570, 0.00632, -0.02770), SIMD3(-0.08597, 0.17955, -0.12725), SIMD3(0.01468, 0.05071, -0.04924), SIMD3(0.03388, -0.05119, 0.09847), SIMD3(0.05183, -0.07922, 0.13285), SIMD3(-0.00345, -0.00812, 0.00822), SIMD3(0.02654, -0.06687, 0.04598)]
+ /// The tube at rest: 96 points evenly along it, tail to head (pt, around the character's centre), and its radius at each.
+ static let nodes: [SIMD2<Double>] = [SIMD2(35.450, 72.225), SIMD2(31.571, 72.758), SIMD2(27.679, 72.359), SIMD2(24.052, 70.903), SIMD2(21.209, 68.241), SIMD2(19.678, 64.655), SIMD2(19.362, 60.756), SIMD2(20.028, 56.898), SIMD2(21.480, 53.259), SIMD2(23.581, 49.950), SIMD2(25.985, 46.850), SIMD2(28.490, 43.829), SIMD2(30.960, 40.781), SIMD2(33.350, 37.669), SIMD2(35.666, 34.502), SIMD2(37.891, 31.270), SIMD2(40.010, 27.968), SIMD2(42.040, 24.609), SIMD2(43.892, 21.153), SIMD2(45.042, 17.411), SIMD2(45.244, 13.504), SIMD2(44.279, 9.719), SIMD2(42.020, 6.544), SIMD2(38.694, 4.506), SIMD2(34.876, 3.671), SIMD2(30.971, 3.922), SIMD2(27.246, 5.123), SIMD2(23.821, 7.034), SIMD2(20.475, 9.083), SIMD2(17.111, 11.103), SIMD2(13.714, 13.067), SIMD2(10.298, 14.997), SIMD2(6.861, 16.891), SIMD2(3.390, 18.720), SIMD2(-0.132, 20.451), SIMD2(-3.711, 22.059), SIMD2(-7.338, 23.555), SIMD2(-10.998, 24.970), SIMD2(-14.673, 26.344), SIMD2(-18.354, 27.704), SIMD2(-22.039, 29.051), SIMD2(-25.733, 30.373), SIMD2(-29.440, 31.662), SIMD2(-33.218, 32.703), SIMD2(-37.127, 32.896), SIMD2(-40.929, 31.994), SIMD2(-43.991, 29.626), SIMD2(-45.080, 25.919), SIMD2(-44.369, 22.080), SIMD2(-42.537, 18.624), SIMD2(-39.914, 15.717), SIMD2(-36.785, 13.353), SIMD2(-33.563, 11.115), SIMD2(-30.333, 8.886), SIMD2(-27.099, 6.664), SIMD2(-23.863, 4.444), SIMD2(-20.626, 2.227), SIMD2(-17.388, 0.011), SIMD2(-14.147, -2.201), SIMD2(-10.904, -4.409), SIMD2(-7.657, -6.614), SIMD2(-4.410, -8.817), SIMD2(-1.163, -11.020), SIMD2(2.082, -13.225), SIMD2(5.328, -15.429), SIMD2(8.582, -17.622), SIMD2(11.844, -19.803), SIMD2(15.102, -21.991), SIMD2(18.334, -24.215), SIMD2(21.518, -26.508), SIMD2(24.645, -28.879), SIMD2(27.717, -31.320), SIMD2(30.720, -33.845), SIMD2(33.597, -36.512), SIMD2(36.079, -39.542), SIMD2(37.853, -43.033), SIMD2(38.767, -46.838), SIMD2(38.616, -50.744), SIMD2(37.223, -54.391), SIMD2(34.666, -57.340), SIMD2(31.228, -59.186), SIMD2(27.369, -59.803), SIMD2(23.494, -59.277), SIMD2(19.867, -57.795), SIMD2(16.375, -56.006), SIMD2(12.933, -54.121), SIMD2(9.530, -52.169), SIMD2(6.157, -50.163), SIMD2(2.822, -48.096), SIMD2(-0.466, -45.955), SIMD2(-3.717, -43.758), SIMD2(-6.955, -41.541), SIMD2(-10.191, -39.322), SIMD2(-13.424, -37.099), SIMD2(-16.652, -34.868), SIMD2(-19.878, -32.634)]
+ static let radii: [Double] = [14.712, 15.566, 16.384, 16.951, 17.384, 17.621, 17.567, 17.438, 17.304, 17.086, 16.755, 16.398, 16.064, 15.770, 15.491, 15.248, 15.076, 14.939, 14.808, 14.690, 14.575, 14.409, 14.306, 14.301, 14.301, 14.301, 14.301, 14.301, 14.301, 14.309, 14.339, 14.384, 14.430, 14.476, 14.513, 14.527, 14.528, 14.528, 14.528, 14.528, 14.528, 14.528, 14.528, 14.528, 14.528, 14.528, 14.528, 14.528, 14.528, 14.531, 14.582, 14.712, 14.871, 15.033, 15.194, 15.356, 15.516, 15.668, 15.805, 15.935, 16.065, 16.195, 16.325, 16.452, 16.555, 16.614, 16.656, 16.696, 16.736, 16.751, 16.651, 16.433, 16.190, 15.941, 15.639, 15.176, 14.588, 13.936, 13.248, 12.672, 12.276, 12.061, 11.912, 11.847, 11.869, 11.916, 11.967, 12.039, 12.193, 12.411, 12.638, 12.843, 12.968, 13.033, 13.090, 13.153]
+ /// The head (an egg), around the tube's end at rest, and the tube's direction there.
+ static let headRect = CGRect(x: -45.044, y: -59.301, width: 69.916, height: 83.536)
+ static let restEnd = 2.53583
+ static let headCenter = SIMD2(-11.717, -17.796)
+ static let eyeL = SIMD2(-16.442, -29.564), eyeR = SIMD2(-4.865, -32.515), eyeSize = SIMD2(4.200, 5.675)
+ /// Matching the reference closely where it shows the tube: 14 knots along it, 9 lighting terms each; used where the
+ /// surface faces a way the reference shows at that point (`seen`: per knot, 24 directions round the view, how far
+ /// toward the edge it is seen), and blended out beyond that.
+ static let traced: [SIMD3<Double>] = [SIMD3(0.24785, 0.61698, 0.95239), SIMD3(-0.21412, -0.20700, -0.05046), SIMD3(0.14906, -0.22004, -0.31282), SIMD3(0.13864, -0.22478, -0.00547), SIMD3(-0.37286, 0.32589, -0.24019), SIMD3(-0.43774, 0.16147, 0.02614), SIMD3(0.04190, 0.16948, 0.32078), SIMD3(0.09995, -0.01010, -0.06343), SIMD3(-0.07762, 0.01444, -0.00498), SIMD3(0.26233, 0.64718, 0.99965), SIMD3(-0.15999, -0.16033, 0.01195), SIMD3(0.10719, -0.29428, -0.21303), SIMD3(0.16310, -0.19994, 0.02014), SIMD3(-0.24743, 0.30510, -0.10860), SIMD3(-0.25891, 0.04808, -0.00567), SIMD3(-0.07130, 0.08812, 0.23539), SIMD3(0.07436, 0.03780, -0.07542), SIMD3(0.01814, 0.01667, -0.03218), SIMD3(0.15072, 0.68414, 0.99795), SIMD3(-0.13561, -0.08938, 0.04637), SIMD3(0.07382, -0.31641, -0.13864), SIMD3(0.08296, -0.15214, 0.03125), SIMD3(-0.15618, 0.27173, -0.00698), SIMD3(-0.08931, -0.02073, -0.04454), SIMD3(-0.15181, 0.07105, 0.15268), SIMD3(0.07768, 0.07647, -0.07849), SIMD3(-0.05763, 0.08803, -0.02805), SIMD3(0.10092, 0.65356, 0.95610), SIMD3(-0.12290, 0.01300, 0.07611), SIMD3(0.08507, -0.27964, -0.08155), SIMD3(0.06167, -0.15185, 0.03064), SIMD3(-0.09256, 0.23326, 0.06668), SIMD3(0.05884, -0.02048, -0.06463), SIMD3(-0.17369, 0.11936, 0.08303), SIMD3(0.08257, 0.09804, -0.07472), SIMD3(-0.04034, 0.07945, -0.00204), SIMD3(0.13029, 0.55217, 0.88864), SIMD3(-0.15744, 0.06930, 0.11933), SIMD3(0.14903, -0.23900, -0.03414), SIMD3(0.07425, -0.19882, 0.01819), SIMD3(-0.03806, 0.18890, 0.11733), SIMD3(0.11696, -0.01655, -0.05199), SIMD3(-0.14773, 0.16741, 0.03078), SIMD3(0.06822, 0.09268, -0.06536), SIMD3(-0.08675, 0.02190, 0.02478), SIMD3(0.30851, 0.43860, 0.81009), SIMD3(-0.20133, 0.07821, 0.16965), SIMD3(0.23013, -0.23607, 0.01462), SIMD3(0.18940, -0.24744, -0.00490), SIMD3(0.01385, 0.13532, 0.14151), SIMD3(0.11071, -0.01682, -0.01306), SIMD3(-0.11058, 0.16637, 0.00389), SIMD3(0.02674, 0.07858, -0.04970), SIMD3(-0.06584, 0.00225, 0.03361), SIMD3(0.49394, 0.36945, 0.71880), SIMD3(-0.23965, 0.05548, 0.19787), SIMD3(0.24671, -0.22018, 0.05034), SIMD3(0.30103, -0.27388, -0.04818), SIMD3(0.06417, 0.08208, 0.12974), SIMD3(0.04907, -0.01604, 0.02540), SIMD3(-0.12780, 0.14387, -0.01443), SIMD3(-0.00740, 0.04828, -0.02258), SIMD3(-0.07837, 0.00547, 0.00383), SIMD3(0.55928, 0.39672, 0.69826), SIMD3(-0.27545, 0.02300, 0.18614), SIMD3(0.12474, -0.15837, 0.09484), SIMD3(0.35362, -0.24451, -0.05232), SIMD3(0.08893, 0.03751, 0.08184), SIMD3(-0.05633, -0.00099, 0.04405), SIMD3(-0.22349, 0.12418, -0.01506), SIMD3(0.01220, 0.01993, -0.00140), SIMD3(-0.06355, 0.06578, -0.00172), SIMD3(0.54164, 0.42020, 0.75519), SIMD3(-0.24049, -0.02451, 0.14528), SIMD3(-0.01562, -0.07074, 0.12637), SIMD3(0.35826, -0.24281, -0.00990), SIMD3(0.11654, -0.02433, -0.00100), SIMD3(-0.13899, 0.02687, 0.05021), SIMD3(-0.29303, 0.09715, -0.01553), SIMD3(0.04750, 0.00812, 0.00660), SIMD3(-0.09043, 0.06558, 0.02932), SIMD3(0.51632, 0.47228, 0.83342), SIMD3(-0.12942, -0.11659, 0.06540), SIMD3(-0.09919, -0.01967, 0.10391), SIMD3(0.35108, -0.23307, 0.03357), SIMD3(0.16307, -0.09703, -0.11148), SIMD3(-0.17568, 0.04058, 0.03317), SIMD3(-0.27057, 0.02320, -0.05124), SIMD3(0.05772, 0.00155, -0.00269), SIMD3(-0.17093, 0.06785, 0.04378), SIMD3(0.55210, 0.50604, 0.86125), SIMD3(0.05093, -0.24307, -0.02184), SIMD3(-0.06472, -0.00326, 0.04864), SIMD3(0.38713, -0.24837, 0.03398), SIMD3(0.22518, -0.17994, -0.25522), SIMD3(-0.16241, 0.04583, 0.01555), SIMD3(-0.11589, -0.08573, -0.10794), SIMD3(0.01908, -0.00099, -0.02280), SIMD3(-0.20294, 0.01606, 0.03978), SIMD3(0.60920, 0.58412, 0.82081), SIMD3(0.15900, -0.36452, -0.05819), SIMD3(-0.04635, 0.02604, 0.01643), SIMD3(0.44937, -0.21853, -0.01343), SIMD3(0.26755, -0.26643, -0.42571), SIMD3(-0.22019, 0.07723, 0.04061), SIMD3(0.02932, -0.17302, -0.14408), SIMD3(-0.06880, -0.00690, -0.05303), SIMD3(-0.09705, 0.03330, 0.04798), SIMD3(0.60514, 0.62253, 0.62835), SIMD3(0.24101, -0.48523, -0.01524), SIMD3(-0.07818, 0.05947, 0.04494), SIMD3(0.46057, -0.22435, -0.18446), SIMD3(0.28936, -0.35426, -0.63318), SIMD3(-0.29490, 0.10870, 0.12565), SIMD3(0.13822, -0.25053, -0.13030), SIMD3(-0.15265, -0.01145, -0.08450), SIMD3(-0.02969, -0.01924, -0.08437), SIMD3(0.59279, 0.66588, 0.51725), SIMD3(0.29839, -0.59461, 0.04028), SIMD3(-0.14513, 0.10906, 0.09290), SIMD3(0.44722, -0.21640, -0.27975), SIMD3(0.32048, -0.44756, -0.83606), SIMD3(-0.38224, 0.14786, 0.22366), SIMD3(0.22904, -0.31720, -0.09687), SIMD3(-0.24261, -0.01200, -0.11848), SIMD3(-0.03760, -0.02690, -0.08230)]
+ static let seen: [Double] = [0.471, 0.442, 0.728, 0.655, 0.462, 0.373, 0.481, 0.481, 0.481, 0.235, 0.314, 0.367, 0.430, 0.462, 0.681, 0.681, 0.900, 0.938, 0.940, 0.940, 0.940, 0.474, 0.474, 0.472, 0.941, 0.884, 0.532, 0.385, 0.126, 0.187, 0.475, 0.475, 0.475, 0.469, 0.628, 0.735, 0.859, 0.923, 0.923, 0.923, 0.450, 0.469, 0.942, 0.946, 0.948, 0.948, 0.948, 0.943, 0.685, 0.609, 0.395, 0.276, 0.000, 0.000, 0.478, 0.625, 0.708, 0.705, 0.784, 0.836, 0.925, 0.931, 0.931, 0.931, 0.000, 0.000, 0.783, 0.785, 0.786, 0.751, 0.736, 0.734, 0.428, 0.335, 0.259, 0.231, 0.116, 0.158, 0.481, 0.775, 0.940, 0.940, 0.940, 0.937, 0.935, 0.935, 0.934, 0.732, 0.311, 0.362, 0.624, 0.624, 0.624, 0.553, 0.525, 0.525, 0.214, 0.167, 0.171, 0.186, 0.232, 0.317, 0.363, 0.387, 0.470, 0.470, 0.470, 0.469, 0.468, 0.468, 0.475, 0.532, 0.623, 0.724, 0.724, 0.724, 0.664, 0.277, 0.262, 0.262, 0.000, 0.000, 0.086, 0.162, 0.208, 0.281, 0.342, 0.357, 0.357, 0.175, 0.144, 0.000, 0.000, 0.000, 0.238, 0.910, 0.910, 0.910, 0.831, 0.834, 0.804, 0.472, 0.472, 0.000, 0.468, 0.470, 0.470, 0.541, 0.537, 0.245, 0.321, 0.350, 0.350, 0.350, 0.289, 0.284, 0.284, 0.284, 0.274, 0.926, 0.934, 0.936, 0.938, 0.944, 0.944, 0.944, 0.944, 0.469, 0.936, 0.940, 0.940, 0.940, 0.933, 0.123, 0.160, 0.175, 0.300, 0.314, 0.393, 0.568, 0.568, 0.568, 0.549, 0.620, 0.624, 0.468, 0.469, 0.472, 0.943, 0.943, 0.943, 0.939, 0.468, 0.470, 0.854, 0.854, 0.854, 0.000, 0.000, 0.000, 0.150, 0.157, 0.196, 0.284, 0.284, 0.284, 0.475, 0.421, 0.369, 0.000, 0.000, 0.000, 0.472, 0.472, 0.472, 0.469, 0.256, 0.216, 0.598, 0.561, 0.526, 0.000, 0.000, 0.000, 0.000, 0.000, 0.468, 0.468, 0.468, 0.470, 0.626, 0.626, 0.597, 0.000, 0.000, 0.000, 0.000, 0.000, 0.256, 0.256, 0.513, 0.433, 0.343, 0.550, 0.550, 0.464, 0.466, 0.469, 0.470, 0.470, 0.935, 0.935, 0.936, 0.940, 0.940, 0.940, 0.882, 0.276, 0.312, 0.334, 0.334, 0.334, 0.513, 0.513, 0.553, 0.216, 0.633, 0.926, 0.928, 0.928, 0.931, 0.938, 0.940, 0.940, 0.940, 0.936, 0.936, 0.470, 0.696, 0.696, 0.667, 0.552, 0.625, 0.669, 0.669, 0.669, 0.642, 0.627, 0.277, 0.000, 0.923, 0.926, 0.926, 0.920, 0.466, 0.469, 0.470, 0.470, 0.470, 0.468, 0.468, 0.000, 0.451, 0.451, 0.459, 0.429, 0.312, 0.334, 0.334, 0.334, 0.321, 0.313, 0.000, 0.000, 0.925, 0.925, 0.925, 0.647, 0.240, 0.240, 0.240, 0.000, 0.000, 0.000, 0.000, 0.000, 0.438, 0.438, 0.676, 0.684, 0.470, 0.470, 0.470, 0.000, 0.000, 0.000]
+}
diff --git a/design/characters/coil3d/bakeall.py b/design/characters/coil3d/bakeall.py
new file mode 100644
index 0000000..158ef24
--- /dev/null
+++ b/design/characters/coil3d/bakeall.py
@@ -0,0 +1,62 @@
+"""Bakes every change of shape in Coil's graph and writes app/ChumsWatch/noodle-shapes.bin (Float32, little-endian):
+ header: 'COIL', shapes S, points N, edges E
+ S shapes × N points × 3
+ per edge: from, to (int32), keys K (int32), seconds (float32), then K × N × 3
+Shapes are named in shapes.NAMES order; the knot's shape is the last key of its tying."""
+import numpy as np, struct, tube3d as T, rod
+from shapes import R, L, NN, clear, rk, at
+from morph import bake, stats, NS, project
+import tie2
+NAMES=['zigzag','tornado','spring','sleep','messy','shell','lolly','slinky','knot']
+EDGES=[('zigzag','tornado'),('zigzag','spring'),('zigzag','sleep'),('zigzag','shell'),('zigzag','lolly'),('zigzag','slinky'),
+ ('tornado','spring'),('tornado','sleep'),('tornado','messy'),('tornado','shell'),('tornado','lolly'),('spring','sleep'),
+ ('shell','lolly'),('sleep','lolly')]
+lib=dict(np.load('lib.npz'))
+# the knot: tied from the tornado with a led head, baked with collisions (tie2), the head ending toward you
+tie2.seg=L/(tie2.n-1)
+keys,_=tie2.bake(lib['tornado'])
+off=lib['tornado'].mean(0)-at(keys[0]).mean(0)
+tieK=np.array([at(k,NS)+off for k in keys])
+from scipy.ndimage import zoom
+# densify the tie keys in time to match the other bakes, smooth, keep constraints
+# densify the tie keys in time along smooth curves (Catmull-Rom), then make it smooth and valid like the others
+def cr(P0,P1,P2,P3,w):
+ w2=w*w;w3=w2*w
+ return P0*(-0.5*w3+w2-0.5*w)+P1*(1.5*w3-2.5*w2+1)+P2*(-1.5*w3+2*w2+0.5*w)+P3*(0.5*w3-0.5*w2)
+nk=len(tieK);dense=[]
+for f in np.linspace(0,nk-1,170):
+ i=min(nk-2,int(f));w=f-i
+ dense.append(cr(tieK[max(0,i-1)],tieK[i],tieK[i+1],tieK[min(nk-1,i+2)],w))
+from morph import finish
+tieK=finish(np.array(dense),tieK[0],tieK[-1],glide=2)
+lib['knot']=at(tieK[-1])
+out=[]
+for a,b in EDGES:
+ best=None
+ for mode in ('all','foot','head'):
+ K=bake(lib[a],lib[b],mode)
+ cl,mk,st,jk,err=stats(K,lib[b])
+ score=st+0.5*jk+3*max(0,mk-1.2)+(50 if cl<1.0 else 0)
+ if best is None or score<best[0]: best=(score,mode,K,(cl,mk,st,jk,err))
+ _,mode,K,s=best
+ print('%-8s -> %-8s %-4s clear %.2f R*k %.2f step %.1f jerk %.1f'%(a,b,mode,s[0],s[1],s[2],s[3]))
+ out.append((a,b,K))
+cl,mk,st,jk,err=stats(tieK,lib['knot'])
+print('tornado -> knot tie clear %.2f R*k %.2f step %.1f jerk %.1f'%(cl,mk,st,jk))
+out.append(('tornado','knot',tieK))
+def secs(K):
+ travel=np.linalg.norm(np.diff(K,axis=0),axis=2).mean(axis=1).sum()
+ return float(np.clip(1.3+travel/140,1.5,2.6))
+buf=bytearray(b'COIL')+struct.pack('<3i',len(NAMES),NN,len(out))
+for n in NAMES: buf+=np.asarray(lib[n],np.float32).tobytes()
+for a,b,K in out:
+ K64=np.array([at(k) for k in K[::2]])
+ # the ends exactly the library's shapes, the difference eased out over the first and last few keys
+ da=lib[a]-K64[0]; db=lib[b]-K64[-1]; m=6
+ for i in range(min(m,len(K64))):
+ w=1-i/m; K64[i]+=da*w; K64[-1-i]+=db*w
+ K64=K64.astype(np.float32)
+ buf+=struct.pack('<3if',NAMES.index(a),NAMES.index(b),len(K64),secs(K))+K64.tobytes()
+open('../../../app/ChumsWatch/noodle-shapes.bin','wb').write(bytes(buf))
+np.savez('baked.npz',**{'%s-%s'%(a,b):K for a,b,K in out})
+print('bytes',len(buf))
diff --git a/design/characters/coil3d/crescents/README.md b/design/characters/coil3d/crescents/README.md
new file mode 100644
index 0000000..9e8672f
--- /dev/null
+++ b/design/characters/coil3d/crescents/README.md
@@ -0,0 +1,23 @@
+# Noodle's renderer, prototyped in numpy
+
+How NoodleStage.swift paints the tube (October 2026), worked out here against a per-pixel truth. Frames come from the
+app: run any render with `SIMCTL_CHILD_NOODLE_DUMP=1` and the app writes `Documents/coil-dump.bin` (per frame: t, then
+the 64 points as Float32), which these scripts read.
+
+- `coilpaint.py`: the Swift colour model (albedo × light + sheen + highlight, the shade and depth cue) read from
+ NoodleRest.swift; `truth()` renders a frame per pixel as the union of spheres along the curve (z-buffer, the normal of
+ the frontmost sphere with its component along the tube removed, the 3D proximity shade). That is what the tube
+ should look like.
+- `tiles4.py`: the painter the Swift does. The tube is the union of discs at cuts along the curve; each disc paints the
+ crescent its nearer neighbour's disc leaves uncovered (so within a stretch every pixel is painted by the nearest disc
+ holding it); a disc nearer than both neighbours (an apex of the stretch, an end facing you) is painted whole, in
+ strips across. Every tile is one fill with one linear gradient across the tube whose stops are the truth sampled on
+ the tile itself (the frontmost sphere within 3R of arc at that point, refined along the sweep). Painted back to
+ front. The gradient axis is the projected tangent smoothed along the tube.
+- `view.py dump.bin 32 out.png`: truth | painter for the frame at 32 s, with zooms of the head and the leftmost nose.
+- `variants.py`, `tiles.py`, `tiles2.py`, `sweep.py`: the earlier attempts (a port of the previous quad renderer,
+ discs with straight-tube gradients, forward-only crescents), kept for the record of what fails and why: beads come
+ from gradients modelled per slice instead of sampled, from unstable axes, and from any tile painted far from where
+ its colours were taken.
+- `motion.py dump.bin timeline`: per-second peak speed, acceleration, tightest bend (R·k) and self-clearance.
+- `beforeafter.py before-dir after-dir out.png 32,44`: close-ups of the same frames from two renders.
diff --git a/design/characters/coil3d/crescents/beforeafter.py b/design/characters/coil3d/crescents/beforeafter.py
new file mode 100644
index 0000000..0fe3da7
--- /dev/null
+++ b/design/characters/coil3d/crescents/beforeafter.py
@@ -0,0 +1,39 @@
+"""Before/after close-ups: the same frames from two renders (scale 3: 594 x 726), cropped where the tube runs toward
+or away from you, side by side, zoomed. Usage: beforeafter.py before-dir after-dir out.png t1,t2,... [zoom]"""
+import sys, numpy as np
+from PIL import Image, ImageDraw, ImageFont
+bd, ad, out = sys.argv[1], sys.argv[2], sys.argv[3]
+times = [float(x) for x in sys.argv[4].split(',')]
+zoom = float(sys.argv[5]) if len(sys.argv) > 5 else 2.0
+S = 3
+def frame(d, t):
+ return Image.open('%s/f%05d.png' % (d, int(round(t * 60)))).convert('RGB')
+def crop_box(im):
+ """A box round the character (non-black pixels, below the clock/avatar strip), square-ish."""
+ a = np.asarray(im).astype(int).sum(2)
+ a[:int(28 * S)] = 0 # the clock and avatar strip
+ a[int(185 * S):] = 0 # the caption band
+ ys, xs = np.nonzero(a > 60)
+ if len(xs) == 0: return (0, 0, im.size[0], im.size[1])
+ x0, x1, y0, y1 = xs.min(), xs.max(), ys.min(), ys.max()
+ return (max(0, x0 - 6), max(0, y0 - 6), min(im.size[0], x1 + 6), min(im.size[1], y1 + 6))
+try: font = ImageFont.truetype('/System/Library/Fonts/SFNS.ttf', 22)
+except Exception: font = ImageFont.load_default()
+rows = []
+for t in times:
+ b, a = frame(bd, t), frame(ad, t)
+ box = crop_box(b)
+ bx = tuple(max(0, min(v, w)) for v, w in zip(box, (b.size[0], b.size[1], b.size[0], b.size[1])))
+ bb, aa = b.crop(bx), a.crop(bx)
+ w, h = bb.size; tw, th = int(w * zoom), int(h * zoom)
+ rows.append((t, bb.resize((tw, th), Image.LANCZOS), aa.resize((tw, th), Image.LANCZOS)))
+W = max(r[1].size[0] for r in rows) * 2 + 24
+H = sum(r[1].size[1] + 40 for r in rows) + 8
+sheet = Image.new('RGB', (W, H), (18, 18, 20)); dr = ImageDraw.Draw(sheet)
+y = 8
+for t, bb, aa in rows:
+ sheet.paste(bb, (8, y + 28)); sheet.paste(aa, (16 + bb.size[0], y + 28))
+ dr.text((8, y + 4), 'before t=%.1fs' % t, fill=(200, 200, 205), font=font)
+ dr.text((16 + bb.size[0], y + 4), 'after t=%.1fs' % t, fill=(200, 200, 205), font=font)
+ y += bb.size[1] + 40
+sheet.save(out); print(out, sheet.size)
diff --git a/design/characters/coil3d/crescents/coilpaint.py b/design/characters/coil3d/crescents/coilpaint.py
new file mode 100644
index 0000000..53e23b4
--- /dev/null
+++ b/design/characters/coil3d/crescents/coilpaint.py
@@ -0,0 +1,159 @@
+"""Experiments for Coil's slice renderer: a per-pixel sphere-sweep truth (what the surface really looks like under the
+Swift colour model) against painter's-algorithm variants built only from what Canvas can fill (convex polygons and
+discs with linear gradients), rasterised in numpy. Frames come from the Swift app's COIL_DUMP (t + 64 x 3 floats)."""
+import numpy as np, re, sys
+from PIL import Image
+
+import os # the colour model is in the app (Coil is Noodle since the October 2026 rename)
+SWIFT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../../app/ChumsWatch/Rig/NoodleRest.swift')
+src = open(SWIFT).read()
+def arr3(name):
+ body = src.split('static let %s:' % name)[1].split('\n')[0]
+ return np.array([[float(a), float(b), float(c)] for a, b, c in re.findall(r'SIMD3\(([-\d.]+), ([-\d.]+), ([-\d.]+)\)', body)])
+def arrf(name):
+ body = src.split('static let %s:' % name)[1].split('\n')[0]
+ return np.array([float(v) for v in re.findall(r'-?\d+\.\d+', body.split('=')[1])])
+ALB = arr3('albedo'); LIGHT = arrf('light'); SHEEN = arrf('sheen')
+LEN = float(re.search(r'length = ([\d.]+)', src).group(1)); R = float(re.search(r'radius = ([\d.]+)', src).group(1))
+N = 64; SEG = LEN / (N - 1)
+H = np.array([-0.45, -0.62, 0.65]); H /= np.linalg.norm(H)
+TINT = np.array([0.42, 0.22, 0.48])
+W, HH = 198, 242; CX, CY = 99.0, 138.0
+
+def ease(x):
+ x = np.clip(x, 0, 1); return x * x * (3 - 2 * x)
+def shs(c, Nv):
+ x, y, z = Nv[..., 0], Nv[..., 1], Nv[..., 2]
+ return c[0] + c[1] * x + c[2] * y + c[3] * z + c[4] * x * y + c[5] * x * z + c[6] * y * z + c[7] * (x * x - y * y) + c[8] * (3 * z * z - 1)
+def shade(u, Nv):
+ """The Swift NoodleStage.shade: u along the tube (0 tail, 1 head), Nv unit normals (..., 3)."""
+ u = np.asarray(u, float); kn = len(ALB)
+ ua = np.minimum(1, u * LEN / 373); f = ua * (kn - 1); k0 = np.minimum(kn - 2, f.astype(int)); w = (f - k0)[..., None]
+ alb = ALB[k0] * (1 - w) + ALB[k0 + 1] * w
+ hk = (ease((u - 0.86) / 0.14) * 0.85)[..., None]
+ alb = alb * (1 - hk) + np.array([1.0, 0.70, 0.13]) * hk
+ lit = shs(LIGHT, Nv)[..., None]; sheen = shs(SHEEN, Nv)[..., None]
+ spec = (0.2 * np.clip((Nv @ H), 0, None) ** 10)[..., None]
+ return alb * lit + sheen + np.array([1, 0.97, 0.92]) * spec
+def darken(col, a, z):
+ sh = np.minimum(a, 0.85)[..., None]
+ zc = np.clip(z / 60, -1, 1); cue = (1 - 0.25 * (0.5 - 0.5 * zc))[..., None]
+ return col * (1 - (1 - TINT) * sh) * cue
+
+def load_dump(path):
+ raw = np.fromfile(path, np.float32).reshape(-1, 1 + N * 3)
+ return raw[:, 0], raw[:, 1:].reshape(-1, N, 3).astype(float)
+
+def catmull(world, sub=5):
+ """The Swift's curve: Catmull-Rom through the 64 points, `sub` samples a link."""
+ n = len(world); cnt = (n - 1) * sub + 1
+ q = np.zeros((cnt, 3))
+ for i in range(cnt):
+ f = i / sub; j = min(n - 2, int(f)); w = f - j
+ p0, p1, p2, p3 = world[max(0, j - 1)], world[j], world[j + 1], world[min(n - 1, j + 2)]
+ q[i] = 0.5 * (2 * p1 + (p2 - p0) * w + (2 * p0 - 5 * p1 + 4 * p2 - p3) * w * w + (3 * p1 - p0 - 3 * p2 + p3) * w ** 3)
+ return q
+
+def unit(v): return v / np.maximum(np.linalg.norm(v, axis=-1, keepdims=True), 1e-12)
+
+def ao_nodes(world, Nv, surf, i, far):
+ """The Swift's 3D proximity shade at surface point(s) with normal(s), against the 64 nodes other than near i."""
+ keep = np.ones(surf.shape[:-1])
+ for j in range(N):
+ if abs(i - j) <= far: continue
+ D = world[j] - surf; dd = np.linalg.norm(D, axis=-1)
+ nd = (D * Nv).sum(-1) / np.maximum(dd, 1e-6)
+ f = np.clip(1 - (dd - R) / (1.8 * R), 0, 1)
+ keep *= 1 - np.where((dd <= 2.8 * R) & (nd > 0), nd * f * f, 0)
+ return 1 - keep
+
+def truth(world, S=4, sub=20, ao=True, cue=True):
+ """Per-pixel sphere sweep: at each pixel the nearest sphere's surface, the tube's normal there (the sphere's normal
+ with its component along the tube removed), shaded by the Swift model; AO sampled at the pixel's surface point."""
+ q = catmull(world, sub); cnt = len(q); u = np.arange(cnt) / (cnt - 1)
+ T = unit(np.roll(q, -1, 0) - np.roll(q, 1, 0)); T[0] = unit(q[1] - q[0]); T[-1] = unit(q[-1] - q[-2])
+ img = np.zeros((HH * S, W * S, 3)); zb = np.full((HH * S, W * S), -1e9)
+ nid = np.full((HH * S, W * S), -1); nrm = np.zeros((HH * S, W * S, 3))
+ yy, xx = np.mgrid[0:HH * S, 0:W * S]; X = (xx + 0.5) / S - CX; Y = (yy + 0.5) / S - CY
+ for i in range(cnt):
+ p = q[i]
+ x0 = int(max(0, (p[0] + CX - R - 1) * S)); x1 = int(min(W * S, (p[0] + CX + R + 1) * S))
+ y0 = int(max(0, (p[1] + CY - R - 1) * S)); y1 = int(min(HH * S, (p[1] + CY + R + 1) * S))
+ if x1 <= x0 or y1 <= y0: continue
+ dx = X[y0:y1, x0:x1] - p[0]; dy = Y[y0:y1, x0:x1] - p[1]
+ d2 = dx * dx + dy * dy; m = d2 < R * R
+ if not m.any(): continue
+ dz = np.sqrt(np.clip(R * R - d2, 0, None)); z = p[2] + dz
+ Nraw = np.stack([dx, dy, dz], -1) / R
+ t = T[i]
+ Nt = Nraw - (Nraw @ t)[..., None] * t
+ if i == 0 or i == cnt - 1: Nt = Nraw
+ Nt = unit(Nt)
+ win = m & (z > zb[y0:y1, x0:x1])
+ if not win.any(): continue
+ zb[y0:y1, x0:x1][win] = z[win]; nid[y0:y1, x0:x1][win] = i; nrm[y0:y1, x0:x1][win] = Nt[win]
+ hit = nid >= 0
+ ids = nid[hit]; uu = ids / (cnt - 1); Nv = nrm[hit]
+ col = shade(uu, Nv)
+ a = np.zeros(len(ids))
+ if ao:
+ far = int(np.ceil(3.5 * R / SEG))
+ # surface points
+ surf = np.stack([X[hit], Y[hit], zb[hit]], 1)
+ node = np.rint(uu * (N - 1)).astype(int)
+ keep = np.ones(len(ids))
+ for j in range(N):
+ sel = np.abs(node - j) > far
+ if not sel.any(): continue
+ D = world[j] - surf[sel]; dd = np.linalg.norm(D, axis=1)
+ nd = (D * Nv[sel]).sum(1) / np.maximum(dd, 1e-6)
+ f = np.clip(1 - (dd - R) / (1.8 * R), 0, 1)
+ k = np.ones(len(dd)); ok = (dd <= 2.8 * R) & (nd > 0); k[ok] = 1 - (nd * f * f)[ok]
+ keep[sel] *= k
+ a = 1 - keep
+ zmid = zb[hit] - 0 # depth of the surface; the Swift uses the slice's centre depth: use the sphere centre
+ zc = zb[hit] - np.sqrt(np.clip(R * R - 0, 0, None)) * 0
+ if cue: col = darken(col, a, q[ids, 2])
+ else: col = col * (1 - (1 - TINT) * np.minimum(a, 0.85)[:, None])
+ img[hit] = col
+ return img
+
+def to_img(img, S, down=2):
+ im = Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8))
+ return im.resize((W * down, HH * down), Image.LANCZOS)
+
+# ---------------------------------------------------------------- painter's variants (numpy rasteriser of fills)
+def fill_disc_lingrad(img, c, r, n2, mid, rm, cols, S, X, Y):
+ """Fill a disc at c (radius r) with a linear gradient along n2 about `mid` (as Canvas would)."""
+ x0 = int(max(0, (c[0] + CX - r - 1) * S)); x1 = int(min(W * S, (c[0] + CX + r + 1) * S))
+ y0 = int(max(0, (c[1] + CY - r - 1) * S)); y1 = int(min(HH * S, (c[1] + CY + r + 1) * S))
+ if x1 <= x0 or y1 <= y0: return
+ px = X[y0:y1, x0:x1]; py = Y[y0:y1, x0:x1]
+ m = (px - c[0]) ** 2 + (py - c[1]) ** 2 <= r * r
+ if not m.any(): return
+ s = ((px - mid[0]) * n2[0] + (py - mid[1]) * n2[1]) / rm
+ k = len(cols); f = (1 - np.clip(s, -1, 1)) / 2 * (k - 1); k0 = np.minimum(k - 2, f.astype(int)); w = f - k0
+ col = cols[k0] * (1 - w)[..., None] + cols[k0 + 1] * w[..., None]
+ sub = img[y0:y1, x0:x1]; sub[m] = col[m]
+
+def fill_poly_lingrad(img, poly, n2, mid, rm, cols, S, X, Y):
+ poly = np.asarray(poly)
+ lo = poly.min(0); hi = poly.max(0)
+ x0 = int(max(0, (lo[0] + CX - 1) * S)); x1 = int(min(W * S, (hi[0] + CX + 1) * S))
+ y0 = int(max(0, (lo[1] + CY - 1) * S)); y1 = int(min(HH * S, (hi[1] + CY + 1) * S))
+ if x1 <= x0 or y1 <= y0: return
+ px = X[y0:y1, x0:x1]; py = Y[y0:y1, x0:x1]
+ m = np.ones(px.shape, bool)
+ # orientation
+ area = 0
+ for e in range(len(poly)):
+ p, p1 = poly[e], poly[(e + 1) % len(poly)]; area += p[0] * p1[1] - p1[0] * p[1]
+ sgn = 1 if area > 0 else -1
+ for e in range(len(poly)):
+ p0, p1 = poly[e], poly[(e + 1) % len(poly)]
+ m &= sgn * ((p1[0] - p0[0]) * (py - p0[1]) - (p1[1] - p0[1]) * (px - p0[0])) >= 0
+ if not m.any(): return
+ s = ((px - mid[0]) * n2[0] + (py - mid[1]) * n2[1]) / rm
+ k = len(cols); f = (1 - np.clip(s, -1, 1)) / 2 * (k - 1); k0 = np.minimum(k - 2, f.astype(int)); w = f - k0
+ col = cols[k0] * (1 - w)[..., None] + cols[k0 + 1] * w[..., None]
+ sub = img[y0:y1, x0:x1]; sub[m] = col[m]
diff --git a/design/characters/coil3d/crescents/motion.py b/design/characters/coil3d/crescents/motion.py
new file mode 100644
index 0000000..fe6b68e
--- /dev/null
+++ b/design/characters/coil3d/crescents/motion.py
@@ -0,0 +1,38 @@
+"""Motion measurements from a COIL_DUMP (t + 64 points per frame at 60 fps): per-frame peak point speed, peak
+acceleration (jerkiness), the tightest bend (R·k), the self-clearance, and where they spike along the 60 s timeline."""
+import sys, numpy as np
+from coilpaint import load_dump, R, SEG, N
+
+def stats(path, label=''):
+ T, Wd = load_dump(path)
+ n = len(T); dt = 1 / 60
+ V = np.diff(Wd, axis=0) / dt # pt/s per point
+ speed = np.linalg.norm(V, axis=2) # (n-1, 64)
+ A = np.diff(V, axis=0) / dt
+ acc = np.linalg.norm(A, axis=2) # (n-2, 64)
+ # bend: joint turn angles -> R*k = theta / seg * R
+ d = np.diff(Wd, axis=1); d /= np.linalg.norm(d, axis=2, keepdims=True)
+ th = np.arccos(np.clip((d[:, :-1] * d[:, 1:]).sum(2), -1, 1))
+ rk = th.max(1) / SEG * R
+ # clearance: min distance between non-adjacent points / 2R
+ idx = np.arange(N); far = np.abs(idx[:, None] - idx[None]) > int(np.ceil(4.5 * R / SEG))
+ clear = np.empty(n)
+ for f in range(n):
+ D = np.linalg.norm(Wd[f][:, None] - Wd[f][None], axis=2)
+ clear[f] = D[far].min() / (2 * R)
+ print('%s frames %d' % (label, n))
+ print(' speed (pt/s, max over points): p50 %.0f p90 %.0f p99 %.0f max %.0f' % tuple(np.percentile(speed.max(1), [50, 90, 99, 100])))
+ print(' accel (pt/s², max over points): p50 %.0f p90 %.0f p99 %.0f max %.0f' % tuple(np.percentile(acc.max(1), [50, 90, 99, 100])))
+ print(' R·k (tightest bend): p50 %.2f p90 %.2f p99 %.2f max %.2f' % tuple(np.percentile(rk, [50, 90, 99, 100])))
+ print(' clear (min gap / 2R): p50 %.2f p10 %.2f p1 %.2f min %.2f' % tuple(np.percentile(clear, [50, 10, 1, 0])))
+ return T, speed.max(1), acc.max(1), rk, clear
+
+def timeline(T, sp, ac, rk, cl, events=None):
+ print(' per second: peak speed / peak accel / max R·k / min clearance')
+ for s in range(int(T[-1])):
+ a = s * 60; b = min(len(ac), a + 60)
+ print(' %2ds %5.0f %6.0f %.2f %.2f' % (s, sp[a:min(len(sp), a + 60)].max(), ac[a:b].max(), rk[a:a + 60].max(), cl[a:a + 60].min()))
+
+if __name__ == '__main__':
+ r = stats(sys.argv[1], sys.argv[1])
+ if len(sys.argv) > 2 and sys.argv[2] == 'timeline': timeline(*r)
diff --git a/design/characters/coil3d/crescents/sweep.py b/design/characters/coil3d/crescents/sweep.py
new file mode 100644
index 0000000..4bea638
--- /dev/null
+++ b/design/characters/coil3d/crescents/sweep.py
@@ -0,0 +1,90 @@
+"""The sphere-sweep painter: discs at every cut, back to front, each with a linear gradient across whose stops are the
+true visible surface (the frontmost sphere of the tube's own run at that screen point: its normal with the component
+along the tube removed), sampled on the rim where that disc actually shows (toward its farther neighbour)."""
+import numpy as np
+from coilpaint import *
+import variants as V
+
+M = 8
+SS = 1 - 2 * np.arange(M) / (M - 1)
+
+def frames_nodes(world):
+ """AO at the 64 nodes: for each node, the shade for the m directions of its own frame (n_i across, bn_i toward you)."""
+ n = N; far = int(np.ceil(3.5 * R / SEG))
+ aoN = np.zeros((n, M)); nF = np.zeros((n, 3)); bF = np.zeros((n, 3))
+ for i in range(n):
+ tg = unit(world[min(n - 1, i + 1)] - world[max(0, i - 1)]); lin = np.hypot(tg[0], tg[1])
+ nrm = np.array([0, -1.0, 0]) if lin < 0.05 else np.array([tg[1] / lin, -tg[0] / lin, 0])
+ bn = unit(np.cross(nrm, tg))
+ if bn[2] < 0: bn = -bn
+ Nv = SS[:, None] * nrm + np.sqrt(np.clip(1 - SS * SS, 0, None))[:, None] * bn
+ aoN[i] = ao_nodes(world, Nv, world[i] + Nv * R, i, far); nF[i] = nrm; bF[i] = bn
+ return aoN, nF, bF
+
+def ao_lookup(aoN, nF, u, Nv):
+ """AO for a surface normal Nv near u along the tube: the node's table by the across coordinate of Nv in its frame."""
+ fn = u * (N - 1); i0 = min(N - 2, int(fn)); w = fn - i0
+ out = 0.0
+ for i, wi in ((i0, 1 - w), (i0 + 1, w)):
+ s = np.clip(Nv @ nF[i], -1, 1)
+ f = (1 - s) / 2 * (M - 1); k0 = min(M - 2, int(f)); wk = f - k0
+ out += wi * (aoN[i][k0] * (1 - wk) + aoN[i][k0 + 1] * wk)
+ return out
+
+def sweep(world, S=4, step=2.2, maxturn=0.035, ao=True, contact=True, cue=True, J=12, stops=M, caps='linear', dbg=None):
+ n = N; q = catmull(world, 5); cnt = len(q); pr = q[:, :2]
+ tang = unit(q[np.minimum(cnt - 1, np.arange(cnt) + 2)] - q[np.maximum(0, np.arange(cnt) - 2)])
+ cuts = V.cut_slices(q, pr, tang, maxlen=step, maxturn=maxturn)
+ Sn = len(cuts); C = pr[cuts]; Z = q[cuts, 2]; U = np.array(cuts) / (cnt - 1)
+ ss = 1 - 2 * np.arange(stops) / (stops - 1)
+ if ao: aoN, nF, bF = frames_nodes(world)
+ # contact table (segments between cuts)
+ A = C[:-1]; B = C[1:]; Rr = np.full(Sn - 1, R); Zs = (Z[:-1] + Z[1:]) / 2; ARCs = (U[:-1] + U[1:]) / 2 * LEN
+ LO = np.minimum(A, B) - (R + 9); HI = np.maximum(A, B) + (R + 9)
+ segs = (A, B, Rr, Zs, ARCs, LO, HI)
+ cols = np.zeros((Sn, stops, 3)); axes = np.zeros((Sn, 2))
+ prevN = None
+ for k in range(Sn):
+ c = C[k]; zk = Z[k]
+ zm = Z[k - 1] if k > 0 else -1e9; zp = Z[k + 1] if k < Sn - 1 else -1e9
+ # the gradient axis: across the projected tangent (the smoothed-by-cut-span direction)
+ a_ = cuts[max(0, k - 1)]; b_ = cuts[min(Sn - 1, k + 1)]
+ d = pr[b_] - pr[a_]; l = np.linalg.norm(d)
+ if l > 1e-3: nrm = np.array([d[1], -d[0]]) / l
+ else: nrm = prevN if prevN is not None else np.array([0, -1.0])
+ if prevN is not None and nrm @ prevN < 0: nrm = -nrm
+ prevN = nrm
+ # where this disc shows: toward its farther neighbour; at a depth maximum, its own across line
+ if zm > zk or zp > zk:
+ far_c = C[k - 1] if (k > 0 and (k == Sn - 1 or zm < zp)) else C[k + 1]
+ v = far_c - c; lv = np.linalg.norm(v); v = v / lv if lv > 1e-6 else np.zeros(2)
+ v = v - nrm * (v @ nrm); lv = np.linalg.norm(v); v = v / lv if lv > 1e-6 else np.zeros(2)
+ else: v = np.zeros(2)
+ axes[k] = nrm
+ for i, s in enumerate(ss):
+ p = c + R * (np.sqrt(max(0, 1 - s * s)) * v + s * nrm)
+ # the frontmost sphere of this run at p
+ lo = max(0, cuts[k] - J); hi = min(cnt - 1, cuts[k] + J)
+ best = -1e9; jb = cuts[k]; dzb = 0
+ for j in range(lo, hi + 1):
+ dx = p - pr[j]; d2 = dx @ dx
+ if d2 > R * R * 1.0001: continue
+ dz = np.sqrt(max(0, R * R - d2)); zz = q[j, 2] + dz
+ if zz > best: best = zz; jb = j; dzb = dz
+ Nraw = np.array([p[0] - pr[jb][0], p[1] - pr[jb][1], dzb]) / R
+ if jb == 0 or jb == cnt - 1: Nv = unit(Nraw)
+ else:
+ t = tang[jb]; Nv = Nraw - (Nraw @ t) * t; ln = np.linalg.norm(Nv)
+ Nv = Nv / ln if ln > 1e-6 else unit(Nraw)
+ uj = jb / (cnt - 1)
+ col = shade(uj, Nv)
+ a = ao_lookup(aoN, nF, uj, Nv) if ao else 0.0
+ if contact: a = 1 - (1 - a) * V.contact_keep(p, zk, U[k] * LEN, segs)
+ cols[k, i] = darken(col[None], np.array([a]), np.array([zk]))[0] if cue else col * (1 - (1 - TINT) * min(a, 0.85))
+ order = sorted(range(Sn), key=lambda o: (Z[o], o))
+ img = np.zeros((HH * S, W * S, 3))
+ yy, xx = np.mgrid[0:HH * S, 0:W * S]; X = (xx + 0.5) / S - CX; Y = (yy + 0.5) / S - CY
+ for o in order:
+ fill_disc_lingrad(img, C[o], R, axes[o], C[o], R, cols[o], S, X, Y)
+ if dbg is not None: dbg.update(cuts=cuts, cols=cols, axes=axes, C=C, Z=Z)
+ return img, Sn
diff --git a/design/characters/coil3d/crescents/tiles.py b/design/characters/coil3d/crescents/tiles.py
new file mode 100644
index 0000000..a3a9113
--- /dev/null
+++ b/design/characters/coil3d/crescents/tiles.py
@@ -0,0 +1,119 @@
+"""The crescent tiling: the sphere sweep's footprint is tiled by crescents T_k = disc_k \\ disc_{k+1} (disjoint, their
+union the whole sweep but the last disc, which the backward crescents T'_k = disc_k \\ disc_{k-1} of the last few
+discs cover). Each tile is a thin band (as wide as the step) along its disc's rim, filled with a linear gradient
+across the tube whose stops are the true visible surface sampled on that rim (the frontmost sphere of the tube's own
+run there). Painted back to front, so nearer runs cover farther ones; within a run the order doesn't matter."""
+import numpy as np
+from coilpaint import *
+import variants as V
+import sweep as SW
+
+M = 8
+SS = 1 - 2 * np.arange(M) / (M - 1)
+
+def smoothstep(x):
+ x = np.clip(x, 0, 1); return x * x * (3 - 2 * x)
+
+def contact_keep_smooth(sp, me_z, me_arc, segs):
+ A, B, Rr, Z, ARC, LO, HI = segs
+ wz = smoothstep((Z - me_z - 0.8 * R) / (0.8 * R)); wa = smoothstep((np.abs(ARC - me_arc) - 6 * R) / (1.5 * R))
+ sel = (wz > 0) & (wa > 0) & (sp[0] >= LO[:, 0]) & (sp[0] <= HI[:, 0]) & (sp[1] >= LO[:, 1]) & (sp[1] <= HI[:, 1])
+ if not sel.any(): return 1.0
+ a, b, rr = A[sel], B[sel], Rr[sel]
+ ab = b - a; l = np.maximum((ab * ab).sum(1), 1e-9)
+ tt = np.clip(((sp - a) * ab).sum(1) / l, 0, 1)
+ dist = np.linalg.norm(sp - (a + ab * tt[:, None]), axis=1) - rr
+ x = smoothstep(1 - dist / 9)
+ return np.prod(1 - 0.65 * x * wz[sel] * wa[sel])
+
+def fill_crescent_lingrad(img, c0, c1, n2, cols, S, X, Y, eps=0.5):
+ """Fill the crescent of disc(c0) beyond disc(c1): inside disc(c0), outside disc(c1) shrunk by eps, and on the far
+ side of the chord through the two rims' crossing points (so a tiny step gives a hair-thin crescent, never a ring)."""
+ lo = np.minimum(c0, c1) - R - 1; hi = np.maximum(c0, c1) + R + 1
+ x0 = int(max(0, (lo[0] + CX) * S)); x1 = int(min(W * S, (hi[0] + CX) * S))
+ y0 = int(max(0, (lo[1] + CY) * S)); y1 = int(min(HH * S, (hi[1] + CY) * S))
+ if x1 <= x0 or y1 <= y0: return
+ px = X[y0:y1, x0:x1]; py = Y[y0:y1, x0:x1]
+ d = c1 - c0; l = np.linalg.norm(d); v = d / max(l, 1e-9)
+ along = (px - c0[0]) * v[0] + (py - c0[1]) * v[1]
+ m = ((px - c0[0]) ** 2 + (py - c0[1]) ** 2 <= R * R) & ((px - c1[0]) ** 2 + (py - c1[1]) ** 2 > (R - eps) ** 2) & (along <= l / 2 + eps)
+ if not m.any(): return
+ s = ((px - c0[0]) * n2[0] + (py - c0[1]) * n2[1]) / R
+ k = len(cols); f = (1 - np.clip(s, -1, 1)) / 2 * (k - 1); k0 = np.minimum(k - 2, f.astype(int)); w = f - k0
+ col = cols[k0] * (1 - w)[..., None] + cols[k0 + 1] * w[..., None]
+ sub = img[y0:y1, x0:x1]; sub[m] = col[m]
+
+def tiles(world, S=4, step=2.2, maxturn=0.035, ao=True, contact=True, cue=True, J=12, qback=None, caps=True, dbg=None):
+ n = N; q = catmull(world, 5); cnt = len(q); pr = q[:, :2]
+ tang = unit(q[np.minimum(cnt - 1, np.arange(cnt) + 2)] - q[np.maximum(0, np.arange(cnt) - 2)])
+ cuts = V.cut_slices(q, pr, tang, maxlen=step, maxturn=maxturn)
+ Sn = len(cuts); C = pr[cuts]; Z = q[cuts, 2]; U = np.array(cuts) / (cnt - 1)
+ far_nodes = int(np.ceil(3.5 * R / SEG))
+ A = C[:-1]; B = C[1:]; Rr = np.full(Sn - 1, R); Zs = (Z[:-1] + Z[1:]) / 2; ARCs = (U[:-1] + U[1:]) / 2 * LEN
+ LO = np.minimum(A, B) - (R + 9); HI = np.maximum(A, B) + (R + 9)
+ segs = (A, B, Rr, Zs, ARCs, LO, HI)
+ if qback is None: qback = int(np.ceil(2 * R / step)) + 2
+ # tiles: (k, other, z) -- disc k minus disc `other`
+ T = [(k, k + 1) for k in range(Sn - 1)] + [(k, k - 1) for k in range(Sn - 1, max(0, Sn - 1 - qback), -1)]
+ def stops_for(k, other):
+ c = C[k]; nb = other if other is not None else (k - 1 if k > 0 else k + 1)
+ d = C[nb] - c; l = np.linalg.norm(d)
+ if l < 1e-6: return None
+ v = d / l; nrm = np.array([v[1], -v[0]])
+ if other is None: v = np.zeros(2)
+ cols = np.zeros((M, 3))
+ for i, s in enumerate(SS):
+ p = c + R * (-np.sqrt(max(0, 1 - s * s)) * v + s * nrm)
+ # the frontmost sphere of the contiguous chain of spheres whose discs hold p (a part of the tube looping
+ # back over p is another chain: its own tiles paint there)
+ best = -1e9; jb = cuts[k]; dzb = 0.0
+ for direction in (-1, 1):
+ j = cuts[k] if direction < 0 else cuts[k] + 1
+ while 0 <= j < cnt:
+ dx = p - pr[j]; d2 = dx @ dx
+ if d2 > R * R * 1.0001: break
+ dz = np.sqrt(max(0, R * R - d2)); zz = q[j, 2] + dz
+ if zz > best: best = zz; jb = j; dzb = dz
+ j += direction
+ Nraw = np.array([p[0] - pr[jb][0], p[1] - pr[jb][1], dzb]) / R
+ if jb == 0 or jb == cnt - 1: Nv = unit(Nraw)
+ else:
+ t = tang[jb]; Nv = Nraw - (Nraw @ t) * t; ln = np.linalg.norm(Nv)
+ Nv = Nv / ln if ln > 1e-6 else unit(Nraw)
+ uj = jb / (cnt - 1)
+ col = shade(uj, Nv)
+ a = ao_nodes(world, Nv[None], (np.array([p[0], p[1], q[jb, 2] + dzb]))[None], int(round(uj * (N - 1))), far_nodes)[0] if ao else 0.0
+ if contact: a = 1 - (1 - a) * contact_keep_smooth(p, Z[k], U[k] * LEN, segs)
+ cols[i] = darken(col[None], np.array([a]), np.array([Z[k]]))[0] if cue else col * (1 - (1 - TINT) * min(a, 0.85))
+ return nrm, cols
+ prepared = []
+ for k, o in T:
+ r = stops_for(k, o)
+ if r is None: continue
+ prepared.append((Z[k], k, o, r[0], r[1]))
+ if caps:
+ for k in (0, Sn - 1):
+ r = stops_for(k, None)
+ if r is not None: prepared.append((Z[k] - 1e-3, k, None, r[0], r[1]))
+ # the ball: the end sphere's own normals along a ray from the highlight through the centre to the far rim
+ e = 0 if k == 0 else cnt - 1; te = tang[e]; face = max(0.0, te[2] if k == Sn - 1 else -te[2])
+ if face > 0.05:
+ hl = np.array([H[0], H[1]]); hl = hl / np.linalg.norm(hl) * (0.55 * R)
+ hc = C[k] + hl; ray = -hl / np.linalg.norm(hl); span = R + np.linalg.norm(hl)
+ cols = np.zeros((M, 3))
+ for i in range(M):
+ rho = i / (M - 1) * span; pt = hc + ray * rho; dd = pt - C[k]; r2 = dd @ dd
+ Nv = np.array([dd[0], dd[1], np.sqrt(max(0, R * R - r2))]) / R; Nv = unit(Nv)
+ col = shade(e / (cnt - 1), Nv)
+ a = ao_nodes(world, Nv[None], np.array([pt[0], pt[1], q[e, 2] + Nv[2] * R])[None], int(round(e / (cnt - 1) * (N - 1))), far_nodes)[0] if ao else 0.0
+ cols[i] = darken(col[None], np.array([a]), np.array([Z[k]]))[0] if cue else col * (1 - (1 - TINT) * min(a, 0.85))
+ prepared.append((Z[k] - 0.5e-3, k, 'ball', (hc, span, face), cols))
+ prepared.sort(key=lambda x: (x[0], x[1]))
+ img = np.zeros((HH * S, W * S, 3))
+ yy, xx = np.mgrid[0:HH * S, 0:W * S]; X = (xx + 0.5) / S - CX; Y = (yy + 0.5) / S - CY
+ for z, k, o, nrm, cols in prepared:
+ if o is None: fill_disc_lingrad(img, C[k], R, nrm, C[k], R, cols, S, X, Y)
+ elif o == 'ball': fill_disc_radial(img, C[k], R, nrm[0], nrm[1], nrm[2], cols, S, X, Y)
+ else: fill_crescent_lingrad(img, C[k], C[o], nrm, cols, S, X, Y)
+ if dbg is not None: dbg.update(cuts=cuts, C=C, Z=Z, tiles=prepared)
+ return img, len(prepared)
diff --git a/design/characters/coil3d/crescents/tiles2.py b/design/characters/coil3d/crescents/tiles2.py
new file mode 100644
index 0000000..5e7faed
--- /dev/null
+++ b/design/characters/coil3d/crescents/tiles2.py
@@ -0,0 +1,90 @@
+"""Crescent tiling, second cut: every disc paints what its NEARER neighbour's disc doesn't cover (a crescent on its far
+side, sampled on that rim), so within a run each pixel is painted by the nearest disc holding it; a disc nearer than
+both neighbours (a depth apex, the facing end) is painted whole, as three strips across so the colour along the tube
+is sampled every ~10 pt. Stops are the true visible surface: the frontmost sphere of the contiguous chain of spheres
+holding the sample point, its normal with the component along the tube removed (the end spheres: the sphere's own).
+Painted back to front."""
+import numpy as np
+from coilpaint import *
+import variants as V
+from tiles import smoothstep, contact_keep_smooth, fill_crescent_lingrad
+
+M = 8
+SS = 1 - 2 * np.arange(M) / (M - 1)
+
+def fill_strip_lingrad(img, c, v, lo, hi, n2, cols, S, X, Y, eps=0.5, half=1.0):
+ """Fill the part of disc(c) with lo <= (p-c).v <= hi (chords across v), widened by eps, gradient along n2."""
+ x0 = int(max(0, (c[0] + CX - R - 1) * S)); x1 = int(min(W * S, (c[0] + CX + R + 1) * S))
+ y0 = int(max(0, (c[1] + CY - R - 1) * S)); y1 = int(min(HH * S, (c[1] + CY + R + 1) * S))
+ if x1 <= x0 or y1 <= y0: return
+ px = X[y0:y1, x0:x1]; py = Y[y0:y1, x0:x1]
+ t = (px - c[0]) * v[0] + (py - c[1]) * v[1]
+ m = ((px - c[0]) ** 2 + (py - c[1]) ** 2 <= R * R) & (t >= lo - eps) & (t <= hi + eps)
+ if not m.any(): return
+ s = ((px - c[0]) * n2[0] + (py - c[1]) * n2[1]) / (R * half)
+ k = len(cols); f = (1 - np.clip(s, -1, 1)) / 2 * (k - 1); k0 = np.minimum(k - 2, f.astype(int)); w = f - k0
+ col = cols[k0] * (1 - w)[..., None] + cols[k0 + 1] * w[..., None]
+ sub = img[y0:y1, x0:x1]; sub[m] = col[m]
+
+def tiles2(world, S=4, step=2.2, maxturn=0.035, ao=True, contact=True, cue=True, strips=3, dbg=None):
+ n = N; q = catmull(world, 5); cnt = len(q); pr = q[:, :2]
+ tang = unit(q[np.minimum(cnt - 1, np.arange(cnt) + 2)] - q[np.maximum(0, np.arange(cnt) - 2)])
+ cuts = V.cut_slices(q, pr, tang, maxlen=step, maxturn=maxturn)
+ Sn = len(cuts); C = pr[cuts]; Z = q[cuts, 2]; U = np.array(cuts) / (cnt - 1)
+ far_nodes = int(np.ceil(3.5 * R / SEG))
+ A = C[:-1]; B = C[1:]; Rr = np.full(Sn - 1, R); Zs = (Z[:-1] + Z[1:]) / 2; ARCs = (U[:-1] + U[1:]) / 2 * LEN
+ LO = np.minimum(A, B) - (R + 9); HI = np.maximum(A, B) + (R + 9)
+ segs = (A, B, Rr, Zs, ARCs, LO, HI)
+
+ def sample(k, p):
+ """The true visible surface of this run at screen point p near disc k: colour."""
+ best = -1e9; jb = cuts[k]; dzb = 0.0
+ for direction in (-1, 1):
+ j = cuts[k] if direction < 0 else cuts[k] + 1
+ while 0 <= j < cnt:
+ dx = p - pr[j]; d2 = dx @ dx
+ if d2 > R * R * 1.0001: break
+ dz = np.sqrt(max(0, R * R - d2)); zz = q[j, 2] + dz
+ if zz > best: best = zz; jb = j; dzb = dz
+ j += direction
+ Nraw = np.array([p[0] - pr[jb][0], p[1] - pr[jb][1], dzb]) / R
+ if jb == 0 or jb == cnt - 1: Nv = unit(Nraw)
+ else:
+ t = tang[jb]; Nv = Nraw - (Nraw @ t) * t; ln = np.linalg.norm(Nv)
+ Nv = Nv / ln if ln > 1e-6 else unit(Nraw)
+ uj = jb / (cnt - 1)
+ col = shade(uj, Nv)
+ a = ao_nodes(world, Nv[None], np.array([p[0], p[1], q[jb, 2] + dzb])[None], int(round(uj * (N - 1))), far_nodes)[0] if ao else 0.0
+ if contact: a = 1 - (1 - a) * contact_keep_smooth(p, Z[k], U[k] * LEN, segs)
+ return darken(col[None], np.array([a]), np.array([Z[k]]))[0] if cue else col * (1 - (1 - TINT) * min(a, 0.85))
+
+ prepared = [] # (z, kind, k, geometry, nrm, cols)
+ for k in range(Sn):
+ zm = Z[k - 1] if k > 0 else -np.inf; zp = Z[k + 1] if k < Sn - 1 else -np.inf
+ c = C[k]
+ if zm > Z[k] or zp > Z[k]:
+ o = k - 1 if zm > zp else k + 1
+ d = C[o] - c; l = np.linalg.norm(d)
+ if l < 1e-6: continue
+ v = d / l; nrm = np.array([v[1], -v[0]])
+ cols = np.array([sample(k, c + R * (-np.sqrt(max(0, 1 - s * s)) * v + s * nrm)) for s in SS])
+ prepared.append((Z[k], 'crescent', k, o, nrm, cols))
+ else:
+ # nearer than both neighbours: the whole disc, in strips along the tube
+ nb = k + 1 if k < Sn - 1 else k - 1
+ d = C[nb] - c; l = np.linalg.norm(d)
+ v = d / l if l > 1e-6 else np.array([1.0, 0]); nrm = np.array([v[1], -v[0]])
+ edges = np.linspace(-R, R, strips + 1)
+ for i in range(strips):
+ lo, hi = edges[i], edges[i + 1]; mid = (lo + hi) / 2
+ half = np.sqrt(max(0, R * R - mid * mid)) / R
+ cols = np.array([sample(k, c + v * mid + nrm * (s * R * half)) for s in SS])
+ prepared.append((Z[k] + i * 1e-6, 'strip', k, (v, lo, hi), nrm, cols))
+ prepared.sort(key=lambda x: (x[0], x[2]))
+ img = np.zeros((HH * S, W * S, 3))
+ yy, xx = np.mgrid[0:HH * S, 0:W * S]; X = (xx + 0.5) / S - CX; Y = (yy + 0.5) / S - CY
+ for z, kind, k, g, nrm, cols in prepared:
+ if kind == 'crescent': fill_crescent_lingrad(img, C[k], C[g], nrm, cols, S, X, Y)
+ else: fill_strip_lingrad(img, C[k], g[0], g[1], g[2], nrm, cols, S, X, Y)
+ if dbg is not None: dbg.update(cuts=cuts, C=C, Z=Z, tiles=prepared)
+ return img, len(prepared)
diff --git a/design/characters/coil3d/crescents/tiles4.py b/design/characters/coil3d/crescents/tiles4.py
new file mode 100644
index 0000000..88f8f44
--- /dev/null
+++ b/design/characters/coil3d/crescents/tiles4.py
@@ -0,0 +1,103 @@
+"""Crescent tiling, fourth cut (to port): each disc paints the crescent its nearer neighbour's disc leaves (so within
+a run every pixel is painted by the nearest disc holding it); a disc nearer than both neighbours (an apex of the
+run, or a facing end) is painted whole, in strips across the tube every ~2 pt. Which neighbour is nearer is read
+off a smoothed depth, so a ripple doesn't make apexes. Stops: the frontmost sphere of the tube within ±3R of arc
+(the own run) at the sample point, its normal with the along-tube component removed."""
+import numpy as np
+from coilpaint import *
+import variants as V
+from tiles import smoothstep, contact_keep_smooth, fill_crescent_lingrad
+from tiles2 import fill_strip_lingrad
+
+M = 8
+SS = 1 - 2 * np.arange(M) / (M - 1)
+
+def tiles4(world, S=4, step=2.2, maxturn=0.035, ao=True, contact=True, cue=True, strip=2.2, minstep=0.3, inset=0.35,
+ zwin=6, arcwin=3.0, refine=True, axwin=4, smoothaxis=True, dbg=None):
+ n = N; q = catmull(world, 5); cnt = len(q); pr = q[:, :2]
+ tang = unit(q[np.minimum(cnt - 1, np.arange(cnt) + 2)] - q[np.maximum(0, np.arange(cnt) - 2)])
+ cuts = V.cut_slices(q, pr, tang, maxlen=step, maxturn=maxturn)
+ kept = [cuts[0]]
+ for c in cuts[1:-1]:
+ if np.linalg.norm(pr[c] - pr[kept[-1]]) >= minstep: kept.append(c)
+ if np.linalg.norm(pr[cuts[-1]] - pr[kept[-1]]) < minstep and len(kept) > 1: kept.pop()
+ kept.append(cuts[-1]); cuts = kept
+ Sn = len(cuts); C = pr[cuts]; Z = q[cuts, 2]; U = np.array(cuts) / (cnt - 1)
+ # smoothed depth for the direction decision
+ Zs = np.array([Z[max(0, k - zwin):k + zwin + 1].mean() for k in range(Sn)])
+ # the gradient's axis: across the projected tangent, smoothed along the tube (orientations mod 180, weighted by how
+ # side-on the tube is) so a foreshortened stretch doesn't swing it from one disc to the next
+ lin = np.hypot(tang[:, 0], tang[:, 1]); th = np.arctan2(tang[:, 1], tang[:, 0])
+ vv = np.stack([np.cos(2 * th), np.sin(2 * th)], 1) * (lin * lin + 0.02)[:, None]
+ ker = np.exp(-0.5 * (np.arange(-3 * axwin, 3 * axwin + 1) / axwin) ** 2); ker /= ker.sum()
+ vs = np.stack([np.convolve(np.pad(vv[:, i], 3 * axwin, mode='edge'), ker, mode='valid') for i in range(2)], 1)
+ ax_th = np.arctan2(vs[:, 1], vs[:, 0]) / 2
+ axis = np.stack([-np.sin(ax_th), np.cos(ax_th)], 1) # perpendicular to the smoothed tangent
+ far_nodes = int(np.ceil(3.5 * R / SEG))
+ A = C[:-1]; B = C[1:]; Rr = np.full(Sn - 1, R); Zm = (Z[:-1] + Z[1:]) / 2; ARCs = (U[:-1] + U[1:]) / 2 * LEN
+ LO = np.minimum(A, B) - (R + 9); HI = np.maximum(A, B) + (R + 9)
+ segs = (A, B, Rr, Zm, ARCs, LO, HI)
+ win = int(round(arcwin * R / (LEN / (cnt - 1))))
+
+ def sample(k, p):
+ lo = max(0, cuts[k] - win); hi = min(cnt - 1, cuts[k] + win)
+ d2 = ((pr[lo:hi + 1] - p) ** 2).sum(1); inside = d2 <= R * R * 1.0001
+ if not inside.any(): jb = cuts[k]; dzb = 0.0; best = q[jb, 2]; cxy = pr[jb]; t = tang[jb]
+ else:
+ dz = np.sqrt(np.clip(R * R - d2, 0, None)); zz = np.where(inside, q[lo:hi + 1, 2] + dz, -1e9)
+ j = int(np.argmax(zz)); jb = lo + j; best = zz[j]; dzb = dz[j]; cxy = pr[jb]; t = tang[jb]
+ # the sweep is continuous: refine where along it the surface is frontmost (a parabola through the
+ # neighbours), so the normal doesn't step from sphere to sphere
+ if refine and 0 < j < hi - lo and inside[j - 1] and inside[j + 1]:
+ a, b, c = zz[j - 1], zz[j], zz[j + 1]; den = a - 2 * b + c
+ if den < -1e-9:
+ f = np.clip(0.5 * (a - c) / den, -0.5, 0.5)
+ jn = jb + (1 if f > 0 else -1); w = abs(f)
+ cxy = pr[jb] * (1 - w) + pr[jn] * w; cz = q[jb, 2] * (1 - w) + q[jn, 2] * w
+ t = unit(tang[jb] * (1 - w) + tang[jn] * w)
+ dd = p - cxy; dzb = np.sqrt(max(0, R * R - dd @ dd)); best = cz + dzb
+ Nraw = np.array([p[0] - cxy[0], p[1] - cxy[1], dzb]) / R
+ if jb == 0 or jb == cnt - 1: Nv = unit(Nraw)
+ else:
+ Nv = Nraw - (Nraw @ t) * t; ln = np.linalg.norm(Nv)
+ Nv = Nv / ln if ln > 1e-6 else unit(Nraw)
+ uj = jb / (cnt - 1)
+ col = shade(uj, Nv)
+ a = ao_nodes(world, Nv[None], np.array([p[0], p[1], q[jb, 2] + dzb])[None], int(round(uj * (N - 1))), far_nodes)[0] if ao else 0.0
+ if contact: a = 1 - (1 - a) * contact_keep_smooth(p, Z[k], U[k] * LEN, segs)
+ return darken(col[None], np.array([a]), np.array([Z[k]]))[0] if cue else col * (1 - (1 - TINT) * min(a, 0.85))
+
+ prepared = []
+ nstrips = 0
+ prev_n = None
+ for k in range(Sn):
+ zm = Zs[k - 1] if k > 0 else -np.inf; zp = Zs[k + 1] if k < Sn - 1 else -np.inf
+ c = C[k]
+ if zm > Zs[k] or zp > Zs[k]:
+ o = k - 1 if zm > zp else k + 1
+ d = C[o] - c; l = np.linalg.norm(d); v = d / l; nrm = np.array([v[1], -v[0]])
+ if smoothaxis:
+ nrm = axis[cuts[k]].copy()
+ if prev_n is not None and nrm @ prev_n < 0: nrm = -nrm
+ vp = v - nrm * (v @ nrm); lp = np.linalg.norm(vp); v = vp / lp if lp > 0.3 else v
+ prev_n = nrm
+ cols = np.array([sample(k, c + (R - inset) * (-np.sqrt(max(0, 1 - s * s)) * v + s * nrm)) for s in SS])
+ prepared.append((Z[k], 'crescent', k, o, nrm, cols))
+ else:
+ nb = k + 1 if k < Sn - 1 else k - 1
+ d = C[nb] - c; l = np.linalg.norm(d)
+ v = d / l if l > 1e-6 else np.array([1.0, 0]); nrm = np.array([v[1], -v[0]])
+ ns = max(3, int(np.ceil(2 * R / strip))); edges = np.linspace(-R, R, ns + 1)
+ for i in range(ns):
+ lo, hi = edges[i], edges[i + 1]; mid = (lo + hi) / 2
+ half = np.sqrt(max(0, R * R - mid * mid)) / R
+ cols = np.array([sample(k, c + v * mid + nrm * (s * max(0.0, R * half - inset))) for s in SS])
+ prepared.append((Z[k] + i * 1e-6, 'strip', k, (v, lo, hi, max(half, 1e-3)), nrm, cols)); nstrips += 1
+ prepared.sort(key=lambda x: (x[0], x[2]))
+ img = np.zeros((HH * S, W * S, 3))
+ yy, xx = np.mgrid[0:HH * S, 0:W * S]; X = (xx + 0.5) / S - CX; Y = (yy + 0.5) / S - CY
+ for z, kind, k, g, nrm, cols in prepared:
+ if kind == 'crescent': fill_crescent_lingrad(img, C[k], C[g], nrm, cols, S, X, Y)
+ else: fill_strip_lingrad(img, C[k], g[0], g[1], g[2], nrm, cols, S, X, Y, half=g[3])
+ if dbg is not None: dbg.update(cuts=cuts, C=C, Z=Z, tiles=prepared, nstrips=nstrips)
+ return img, len(prepared)
diff --git a/design/characters/coil3d/crescents/variants.py b/design/characters/coil3d/crescents/variants.py
new file mode 100644
index 0000000..8928edc
--- /dev/null
+++ b/design/characters/coil3d/crescents/variants.py
@@ -0,0 +1,172 @@
+"""Painter's variants for Coil, rasterised like Canvas would (fills of convex polygons / discs with linear gradients)."""
+import numpy as np
+from coilpaint import *
+
+M = 8
+SS = 1 - 2 * np.arange(M) / (M - 1) # the stops' across coordinate, +1 .. -1 (the Swift's k order)
+
+def cut_slices(q, pr, tang, maxlen=2.2, maxturn=0.035):
+ cnt = len(q); cuts = [0]; run = 0.0; turned = 0.0
+ for i in range(1, cnt):
+ run += np.linalg.norm(pr[i] - pr[i - 1]); turned += np.arccos(np.clip(tang[i - 1] @ tang[i], -1, 1))
+ if run >= maxlen or turned >= maxturn or i == cnt - 1: cuts.append(i); run = 0; turned = 0
+ return cuts
+
+def contact_keep(sp, me_z, me_arc, segs):
+ A, B, Rr, Z, ARC, LO, HI = segs
+ sel = (Z > me_z + 1.2 * R) & (np.abs(ARC - me_arc) >= 3.5 * R)
+ sel &= (sp[0] >= LO[:, 0]) & (sp[0] <= HI[:, 0]) & (sp[1] >= LO[:, 1]) & (sp[1] <= HI[:, 1])
+ if not sel.any(): return 1.0
+ a, b, rr = A[sel], B[sel], Rr[sel]
+ ab = b - a; l = np.maximum((ab * ab).sum(1), 1e-9)
+ tt = np.clip(((sp - a) * ab).sum(1) / l, 0, 1)
+ dist = np.linalg.norm(sp - (a + ab * tt[:, None]), axis=1) - rr
+ x = np.clip(1 - dist / 9, 0, 1)
+ return np.prod(1 - 0.65 * x * x * (3 - 2 * x))
+
+def current(world, S=4, contact=True, ao=True, smooth=2, disc_lin=0.6):
+ """A port of the Swift draw as of the hand-over: quads between joint bisectors, a near-end disc where the slice is
+ foreshortened (lin < 0.6), AO from the 64 nodes' own frames, a contact darkening, colours smoothed by stop index."""
+ n = N; q = catmull(world, 5); cnt = len(q)
+ pr = q[:, :2]
+ tang = unit(q[np.minimum(cnt - 1, np.arange(cnt) + 2)] - q[np.maximum(0, np.arange(cnt) - 2)])
+ cuts = cut_slices(q, pr, tang)
+ slices = []; prevN = np.array([0, -1.0, 0])
+ for s in range(len(cuts) - 1):
+ a, b = cuts[s], cuts[s + 1]
+ t3 = unit(q[b] - q[a] + tang[a] * 0.001); lin = np.hypot(t3[0], t3[1])
+ nrm = prevN if lin < 0.05 else np.array([t3[1] / lin, -t3[0] / lin, 0])
+ bn = unit(np.cross(nrm, t3))
+ if bn[2] < 0: bn = -bn
+ prevN = nrm
+ slices.append(dict(a=a, b=b, z=(q[a, 2] + q[b, 2]) / 2, n=nrm, bn=bn, u=(a + b) / 2 / (cnt - 1), t3=t3, lin=lin))
+ Sn = len(slices)
+ # AO at the nodes, in the nodes' own frames
+ far = int(np.ceil(3.5 * R / SEG))
+ aoNode = np.zeros((n, M))
+ for i in range(n):
+ tg = unit(world[min(n - 1, i + 1)] - world[max(0, i - 1)]); lin = np.hypot(tg[0], tg[1])
+ nrm = np.array([0, -1.0, 0]) if lin < 0.05 else np.array([tg[1] / lin, -tg[0] / lin, 0])
+ bn = unit(np.cross(nrm, tg));
+ if bn[2] < 0: bn = -bn
+ Nv = SS[:, None] * nrm + np.sqrt(np.clip(1 - SS * SS, 0, None))[:, None] * bn
+ aoNode[i] = ao_nodes(world, Nv, world[i] + Nv * R, i, far)
+ segs = []
+ A = np.array([pr[s['a']] for s in slices]); B = np.array([pr[s['b']] for s in slices])
+ Rr = np.full(Sn, R); Z = np.array([s['z'] for s in slices]); ARC = np.array([s['u'] * LEN for s in slices])
+ LO = np.minimum(A, B) - (R + 9); HI = np.maximum(A, B) + (R + 9)
+ segs = (A, B, Rr, Z, ARC, LO, HI)
+ cols = np.zeros((Sn, M, 3))
+ for o, sl in enumerate(slices):
+ n2 = sl['n'][:2]; mid = (A[o] + B[o]) / 2
+ fn = sl['u'] * (n - 1); i0 = min(n - 2, int(fn)); wn = fn - i0
+ Nv = SS[:, None] * sl['n'] + np.sqrt(np.clip(1 - SS * SS, 0, None))[:, None] * sl['bn']
+ c = shade(np.full(M, sl['u']), Nv)
+ a = aoNode[i0] * (1 - wn) + aoNode[i0 + 1] * wn if ao else np.zeros(M)
+ if contact:
+ for k in range(M):
+ sp = mid + n2 * (SS[k] * R)
+ keep = contact_keep(sp, sl['z'], ARC[o], segs)
+ a[k] = 1 - (1 - a[k]) * keep
+ cols[o] = darken(c, a, np.full(M, sl['z']))
+ for _ in range(smooth):
+ c0 = cols.copy()
+ cols[1:-1] = c0[:-2] * 0.25 + c0[1:-1] * 0.5 + c0[2:] * 0.25
+ # joints
+ J = np.zeros((Sn + 1, 2))
+ for k in range(Sn + 1):
+ a_ = slices[k - 1]['n'][:2] if k > 0 else slices[0]['n'][:2]
+ b_ = slices[k]['n'][:2] if k < Sn else a_
+ m2 = a_ + b_; l = np.linalg.norm(m2); J[k] = m2 / l if l > 1e-6 else a_
+ cP = np.ones(Sn); cM = np.ones(Sn)
+ for k in range(Sn):
+ dn = J[k] - J[k + 1]; den = dn @ dn
+ if den <= 1e-10: continue
+ tt = ((B[k] - A[k]) @ dn) / den
+ lim = np.clip(0.97 * abs(tt) / R, 0, 1)
+ if tt > 0: cP[k] = lim
+ else: cM[k] = lim
+ offP = np.ones(Sn + 1); offM = np.ones(Sn + 1)
+ for k in range(Sn + 1):
+ offP[k] = min(cP[k - 1] if k > 0 else 1, cP[k] if k < Sn else 1)
+ offM[k] = min(cM[k - 1] if k > 0 else 1, cM[k] if k < Sn else 1)
+ order = sorted(range(Sn), key=lambda o: (Z[o], o))
+ img = np.zeros((HH * S, W * S, 3))
+ yy, xx = np.mgrid[0:HH * S, 0:W * S]; X = (xx + 0.5) / S - CX; Y = (yy + 0.5) / S - CY
+ for o in order:
+ sl = slices[o]; n2 = sl['n'][:2]
+ d2 = B[o] - A[o]; l2 = np.linalg.norm(d2); ext = d2 / l2 * 0.6 if l2 > 1e-6 else np.zeros(2)
+ mid = (A[o] + B[o]) / 2
+ ja, jb = J[o], J[o + 1]
+ quad = [A[o] + ja * (R * offP[o]) - ext, B[o] + jb * (R * offP[o + 1]) + ext, B[o] - jb * (R * offM[o + 1]) + ext, A[o] - ja * (R * offM[o]) - ext]
+ if l2 > 1e-6: fill_poly_lingrad(img, quad, n2, mid, R, cols[o], S, X, Y)
+ if o == 0: fill_disc_lingrad(img, A[o], R, n2, mid, R, cols[o], S, X, Y)
+ if o == Sn - 1: fill_disc_lingrad(img, B[o], R, n2, mid, R, cols[o], S, X, Y)
+ if sl['lin'] < disc_lin and o != 0 and o != Sn - 1:
+ fill_disc_lingrad(img, B[o] if sl['t3'][2] > 0 else A[o], R, n2, mid, R, cols[o], S, X, Y)
+ return img
+
+def smooth_dirs(d2, lin, win):
+ """Smooth 2D line orientations (mod 180) along the tube, weighted by how side-on the tube is: doubled angles."""
+ th = np.arctan2(d2[:, 1], d2[:, 0])
+ v = np.stack([np.cos(2 * th), np.sin(2 * th)], 1) * np.maximum(lin, 0.02)[:, None]
+ k = np.exp(-0.5 * (np.arange(-3 * win, 3 * win + 1) / win) ** 2); k /= k.sum()
+ vs = np.stack([np.convolve(np.pad(v[:, i], 3 * win, mode='edge'), k, mode='valid') for i in range(2)], 1)
+ th2 = np.arctan2(vs[:, 1], vs[:, 0]) / 2
+ return np.stack([np.cos(th2), np.sin(th2)], 1)
+
+def discs(world, S=4, step=2.0, maxturn=0.035, contact=True, ao=True, smooth=0, dirwin=0, pure=False):
+ """A sphere sweep painted back to front: at every cut a disc of radius R, filled with a linear gradient across the
+ tube (perpendicular to the projected tangent) whose stops are the Swift shading at the cross-section's normals.
+ No quads, no joints. `dirwin` smooths the across direction along the tube (in fine samples)."""
+ n = N; q = catmull(world, 5); cnt = len(q)
+ pr = q[:, :2]
+ tang = unit(q[np.minimum(cnt - 1, np.arange(cnt) + 2)] - q[np.maximum(0, np.arange(cnt) - 2)])
+ lin_all = np.hypot(tang[:, 0], tang[:, 1])
+ if dirwin > 0: dirs = smooth_dirs(tang[:, :2], lin_all, dirwin)
+ cuts = cut_slices(q, pr, tang, maxlen=step, maxturn=maxturn)
+ centres = cuts
+ Sn = len(centres)
+ fr = []
+ prevN = np.array([0, -1.0, 0])
+ for c in centres:
+ t3 = tang[c]; lin = lin_all[c]
+ if dirwin > 0:
+ d = dirs[c]; nrm = np.array([-d[1], d[0], 0.0]) # perpendicular to the smoothed direction
+ if nrm @ prevN < 0: nrm = -nrm
+ else:
+ nrm = prevN if lin < 0.05 else np.array([t3[1] / lin, -t3[0] / lin, 0])
+ if nrm @ prevN < 0: nrm = -nrm
+ bn = unit(np.cross(nrm, t3))
+ if bn[2] < 0: bn = -bn
+ prevN = nrm
+ fr.append((nrm, bn, t3, lin))
+ far = int(np.ceil(3.5 * R / SEG))
+ Z = q[centres, 2]; U = np.array(centres) / (cnt - 1); ARC = U * LEN; P2 = pr[centres]
+ # contact table: short segments between consecutive centres
+ A = P2[:-1]; B = P2[1:]; Rr = np.full(Sn - 1, R); Zs = (Z[:-1] + Z[1:]) / 2; ARCs = (ARC[:-1] + ARC[1:]) / 2
+ LO = np.minimum(A, B) - (R + 9); HI = np.maximum(A, B) + (R + 9)
+ segs = (A, B, Rr, Zs, ARCs, LO, HI)
+ cols = np.zeros((Sn, M, 3))
+ for o in range(Sn):
+ nrm, bn, t3, lin = fr[o]
+ Nv = SS[:, None] * nrm + np.sqrt(np.clip(1 - SS * SS, 0, None))[:, None] * bn
+ c = shade(np.full(M, U[o]), Nv)
+ a = np.zeros(M)
+ if ao:
+ i = int(round(U[o] * (n - 1)))
+ a = ao_nodes(world, Nv, q[centres[o]] + Nv * R, i, far)
+ if contact:
+ for k in range(M):
+ sp = P2[o] + nrm[:2] * (SS[k] * R)
+ a[k] = 1 - (1 - a[k]) * contact_keep(sp, Z[o], ARC[o], segs)
+ cols[o] = darken(c, a, np.full(M, Z[o]))
+ for _ in range(smooth):
+ c0 = cols.copy(); cols[1:-1] = c0[:-2] * 0.25 + c0[1:-1] * 0.5 + c0[2:] * 0.25
+ order = sorted(range(Sn), key=lambda o: (Z[o], o))
+ img = np.zeros((HH * S, W * S, 3))
+ yy, xx = np.mgrid[0:HH * S, 0:W * S]; X = (xx + 0.5) / S - CX; Y = (yy + 0.5) / S - CY
+ for o in order:
+ nrm = fr[o][0]
+ fill_disc_lingrad(img, P2[o], R, nrm[:2], P2[o], R, cols[o], S, X, Y)
+ return img, Sn
diff --git a/design/characters/coil3d/crescents/view.py b/design/characters/coil3d/crescents/view.py
new file mode 100644
index 0000000..f5d7714
--- /dev/null
+++ b/design/characters/coil3d/crescents/view.py
@@ -0,0 +1,19 @@
+"""Side-by-side viewer: for a frame, full truth | tiles, then zooms (head, leftmost cusp) of both."""
+import sys, numpy as np
+from PIL import Image, ImageDraw
+from coilpaint import *
+import tiles4 as TL
+def render_pair(world, S=4, zs=5, extra=None, kw=None):
+ q=catmull(world,5); head=q[-1,:2]+np.array([CX,CY]); left=q[np.argmin(q[:,0]),:2]+np.array([CX,CY])
+ tr=to_img(truth(world,S=S),S); tl=to_img(TL.tiles4(world,S=S,**(kw or {}))[0],S)
+ crops=[(int(head[0])-35,int(head[1])-25,70,50),(int(left[0])-15,int(left[1])-25,70,50)]+(extra or [])
+ tw,th=W*2,HH*2
+ out=Image.new('RGB',(2*(tw+8)+8,th+len(crops)*(50*zs+8)+16),(24,24,26)); dr=ImageDraw.Draw(out)
+ for c,(label,im) in enumerate((('truth',tr),('tiles',tl))):
+ x0=8+c*(tw+8); out.paste(im,(x0,8)); dr.text((x0+4,th+2),label,fill=(220,220,220))
+ for j,(x,y,w,h) in enumerate(crops):
+ z=im.crop((x*2,y*2,(x+w)*2,(y+h)*2)).resize((w*zs,h*zs),Image.LANCZOS); out.paste(z,(x0,8+th+8+j*(50*zs+8)))
+ return out
+if __name__=='__main__':
+ T,Wd=load_dump(sys.argv[1]); tt=float(sys.argv[2]); out=sys.argv[3]
+ render_pair(Wd[int(round(tt*60))]).save(out); print(out)
diff --git a/design/characters/coil3d/export.py b/design/characters/coil3d/export.py
new file mode 100644
index 0000000..6c223ca
--- /dev/null
+++ b/design/characters/coil3d/export.py
@@ -0,0 +1,92 @@
+"""Exports Noodle's pose library to app/ChumsWatch/Rig/NoodleRest.swift: the colour model fitted to the reference, the
+tube's length and radius, and every pose as 64 points evenly along the tube (tail to head), each checked to keep its
+parts apart. Run: python3 export.py"""
+import numpy as np, re, base64, struct, json
+import tube3d as T, rod
+from zigzag3d import make as make_zigzag
+ZIG,_=make_zigzag(kmax=0.6)
+T.L=T.length(ZIG) # the tube is as long as the rest pose needs to make its bends round
+import tie2
+tie2.seg=T.L/(tie2.n-1)
+from tie2 import bake
+R=T.R; L=T.L; NN=64
+def bisect_turns(make, lo=1.0, hi=5.0):
+ for _ in range(50):
+ mid=(lo+hi)/2
+ if T.length(make(mid))<L: lo=mid
+ else: hi=mid
+ return make(hi)
+def helix(r0,r1,pitch,turns,tilt=0.0,phase=0.0):
+ t=np.linspace(0,turns*2*np.pi,1600);k=t/t[-1];r=r0+(r1-r0)*k
+ P=np.stack([r*np.cos(t+phase),-(k*turns*pitch),r*np.sin(t+phase)],1)
+ if tilt:
+ c,s=np.cos(tilt),np.sin(tilt);[email protected]([[1,0,0],[0,c,-s],[0,s,c]]).T
+ return P
+def at64(P):
+ Q,_=T.resample(P,NN);return Q
+SEG=L/(NN-1)
+TMAX=0.78*SEG/R # the most a joint may turn: no bend tighter than about 1.3 tube radii
+def turns(P):
+ d=np.diff(P,axis=0);d/=np.linalg.norm(d,axis=1,keepdims=True)
+ return np.arccos(np.clip((d[:-1]*d[1:]).sum(1),-1,1))
+def roundbends(P):
+ """Smooth along the tube just enough that no bend is tighter than TMAX allows, then restore the length."""
+ from scipy.ndimage import gaussian_filter1d
+ D,_=T.resample(P,400)
+ best=None
+ for sig in np.arange(0.0,14.1,0.5):
+ if sig>0:
+ k=int(4*sig)+2
+ t0=D[1]-D[0];t1=D[-1]-D[-2]
+ pad=np.vstack([D[0]-t0*np.arange(k,0,-1)[:,None],D,D[-1]+t1*np.arange(1,k+1)[:,None]])
+ Q=gaussian_filter1d(pad,sig,axis=0)[k:-k]
+ else: Q=D.copy()
+ c=Q.mean(0);Q=(Q-c)*(L/T.length(Q))+c
+ Q64=at64(Q)
+ m=turns(Q64).max()
+ if best is None or m<best[0]: best=(m,Q64)
+ if m<=TMAX: break
+ return best[1]
+G=70.0
+def ground(P):
+ P=P.copy();P[:,1]+=G-P[:,1].max();c=P.mean(0);P[:,0]-=c[0];P[:,2]-=c[2];return P
+# zigzag: the traced reference centreline, later folds in front (an 80 pt ramp)
+zig=ZIG
+poses={
+ 'zigzag':zig,
+ 'tornado':bisect_turns(lambda tr:helix(20,46,38,tr)),
+ 'sleep':bisect_turns(lambda tr:helix(52,20,2*R*1.02,tr,tilt=-0.42,phase=2.2)),
+ 'spring':bisect_turns(lambda tr:helix(26,26,58,tr)),
+ 'messy':np.load('messy.npy'),
+}
+out={}
+radii=np.full(NN,R)
+for k,P in poses.items():
+ Q=ground(roundbends(P*(L/T.length(P))))
+ out[k]=Q
+ print('%-8s len %.1f clearance %.2f extent %s max R*k %.2f'%(k,T.length(Q),rod.min_sep(Q,radii,4.5*R),np.ptp(Q,axis=0).round(0),turns(Q).max()/SEG*R))
+keys,ms=bake(poses['tornado']*(L/T.length(poses['tornado'])))
+print('tie bake: %d keys, sim clearance %.2f'%(len(keys),ms))
+# the tie keys start from the tornado as grounded/centred above: same transform
+t64=at64(poses['tornado']*(L/T.length(poses['tornado'])))
+off=out['tornado']-t64 # a pure translation
+tie=np.array([roundbends(at64(k))+off[0] for k in keys])
+print('tie keys: min clearance %.2f, max R*k %.2f'%(min(rod.min_sep(k,radii,4.5*R) for k in tie),max(turns(k).max() for k in tie)/SEG*R))
+out['knot']=tie[-1]
+src=open('CoilRest-fit.swift').read()
+def line(name): return [l for l in src.split('\n') if l.strip().startswith('static let %s:'%name)][0]
+def pts(P): return '['+', '.join('SIMD3(%.2f, %.2f, %.2f)'%tuple(p) for p in P)+']'
+blob=base64.b64encode(np.asarray(tie,np.float32).tobytes()).decode()
+lines=['import simd','','// Generated by design/characters/coil3d/export.py; do not edit by hand.','// The colour model fitted to the reference (albedo along the tube × a light of where the surface faces, plus a sheen),',
+'// and the tube\'s poses: each 64 points evenly along it, tail to head, in pt (y down, z toward you), checked so no two',
+'// parts come closer than the tube\'s width.','','enum NoodleRest {',
+' static let length = %.3f, radius = %.3f'%(L,R),
+line('albedo'),line('light'),line('sheen')]
+for k in ['zigzag','tornado','sleep','spring','messy','knot']:
+ lines.append(' static let %s: [SIMD3<Double>] = %s'%(k,pts(out[k])))
+lines.append(' /// Tying the knot from the tornado: %d keys of 64 points (Float32, little-endian), baked offline with collisions.'%len(tie))
+lines.append(' static let tie = "%s"'%blob)
+lines.append('}')
+open('../../../app/ChumsWatch/Rig/NoodleRest.swift','w').write('\n'.join(lines)+'\n')
+np.savez('poses64.npz',**out,tie=tie)
+print('written')
diff --git a/design/characters/coil3d/knot_relaxed.npy b/design/characters/coil3d/knot_relaxed.npy
new file mode 100644
index 0000000..fefe58c
Binary files /dev/null and b/design/characters/coil3d/knot_relaxed.npy differ
diff --git a/design/characters/coil3d/knotrelax.py b/design/characters/coil3d/knotrelax.py
new file mode 100644
index 0000000..aa3c2fc
--- /dev/null
+++ b/design/characters/coil3d/knotrelax.py
@@ -0,0 +1,39 @@
+"""SONO-style relaxation: an open trefoil tightened to 2R clearance at length L (ideal-knot style)."""
+import numpy as np, tube3d as T, rod
+R=T.R
+def relax(P, L, R, excl, iters=4000, shrink=0.996, seed=0):
+ P=P.copy(); n=len(P); seg=T.length(P)/(n-1); target=L/(n-1)
+ iu=np.triu_indices(n,1)
+ s=np.arange(n)*seg
+ far=(np.abs(s[:,None]-s[None])>excl)[iu]
+ I,J=iu[0][far],iu[1][far]
+ for it in range(iters):
+ # overlaps -> push apart to 2R (+1%)
+ d=P[J]-P[I]; dist=np.linalg.norm(d,axis=1); lim=2*R*1.02
+ hit=dist<lim
+ if hit.any():
+ push=d[hit]/dist[hit][:,None]*(lim-dist[hit])[:,None]*0.5
+ np.add.at(P,I[hit],-push); np.add.at(P,J[hit],push)
+ # restore segment lengths (a few passes)
+ for _ in range(3):
+ dd=np.diff(P,axis=0); ln=np.linalg.norm(dd,axis=1); cor=dd*((ln-seg)/np.maximum(ln,1e-9))[:,None]*0.5
+ P[:-1]+=cor; P[1:]-=cor
+ # light smoothing of curvature (keeps it pretty)
+ Q=P.copy(); Q[1:-1]=P[1:-1]+0.05*(P[:-2]+P[2:]-2*P[1:-1]); P=Q
+ if seg>target: seg=max(target,seg*shrink)
+ # recompute far mask arc-length based on seg
+ return P
+t0=0.95; zk=3.2
+t=np.linspace(t0,2*np.pi-t0,400)
+P0=np.stack([np.sin(t)+2*np.sin(2*t),np.cos(t)-2*np.cos(2*t),-zk*np.sin(3*t)],1)
+P0=P0*(1.45*T.L/T.length(P0)); P0,_=T.resample(P0,400)
+radii=np.full(400,R)
+print('start len',round(T.length(P0),1),'minsep',round(rod.min_sep(P0,radii,4.5*R),3))
+P=relax(P0,T.L,R,4.5*R)
+P,_=T.resample(P,400)
+print('relaxed len',round(T.length(P),1),'minsep',round(rod.min_sep(P,radii,4.5*R),3),'extent',np.ptp(P,axis=0).round(0))
+np.save('knot_relaxed.npy',P)
+# with the head swell 1.4 at the tip, is the head end clear?
+from slicer import radius_profile
+rp=radius_profile(np.linspace(0,1,400),1.4)
+print('with swell 1.4: minsep',round(rod.min_sep(P,rp,4.5*R),3))
diff --git a/design/characters/coil3d/messy.npy b/design/characters/coil3d/messy.npy
new file mode 100644
index 0000000..7ed274d
Binary files /dev/null and b/design/characters/coil3d/messy.npy differ
diff --git a/design/characters/coil3d/morph.py b/design/characters/coil3d/morph.py
new file mode 100644
index 0000000..10c17b1
--- /dev/null
+++ b/design/characters/coil3d/morph.py
@@ -0,0 +1,87 @@
+"""Bakes a change of shape A -> B as frames of a rope sim: pulled toward a blend of the two (each link's direction
+turning, as a front or all at once), its length kept, its bends never tighter than the limit, its foot planted, and
+its parts never closer than the tube's width. So it finds its own way round itself. Played back on the watch."""
+import numpy as np, tube3d as T, rod
+from shapes import R, L, NN, clear, rk, at
+from trans import dirblend, weights
+NS=96
+SEGS=L/(NS-1)
+KMAX=0.8*SEGS/R # joint turn limit (bend radius >= ~1.25 R)
+def iu_far(n,excl):
+ I,J=np.triu_indices(n,1); m=(J-I)>excl; return I[m],J[m]
+I,J=iu_far(NS,int(np.ceil(4.5*R/SEGS)))
+ZB=1.5
+def bend(X,k=0.5):
+ d=np.diff(X,axis=0); t=d/np.linalg.norm(d,axis=1,keepdims=True)
+ th=np.arccos(np.clip((t[:-1]*t[1:]).sum(1),-1,1))
+ bad=np.where(th>KMAX)[0]+1
+ if len(bad):
+ mid=(X[bad-1]+X[bad+1])/2; X[bad]+=k*(mid-X[bad])*np.clip((th[bad-1]-KMAX)/KMAX*3,0.2,1)[:,None]
+ return X
+def project(X,pin,iters=30):
+ for _ in range(iters):
+ X[0]=pin
+ X=bend(X,0.6); X=bend(X,0.6); X=bend(X,0.6)
+ # collisions: parts that meet slide past each other mostly in depth (one in front of the other)
+ dv=X[J]-X[I]; dist=np.linalg.norm(dv,axis=1); lim=2*R*1.04; hit=dist<lim
+ if hit.any():
+ dh=dv[hit]; sz=np.where(dh[:,2]>=0,1.0,-1.0)
+ dirn=dh/np.maximum(dist[hit],1e-9)[:,None]+np.stack([0*sz,0*sz,ZB*sz],1)
+ dirn/=np.linalg.norm(dirn,axis=1,keepdims=True)
+ push=dirn*(lim-dist[hit])[:,None]*0.5
+ wi=np.where(I[hit]==0,0,1.0)[:,None]
+ np.add.at(X,I[hit],-push*wi); np.add.at(X,J[hit],push*(2-wi))
+ # lengths
+ for _k in range(2):
+ dd=np.diff(X,axis=0); ln=np.linalg.norm(dd,axis=1); cor=dd*((ln-SEGS)/np.maximum(ln,1e-9))[:,None]*0.5
+ X[:-1]+=cor; X[1:]-=cor
+ X[0]=pin
+ return X
+def bake(A,B,mode,frames=160,settle=30,pull=0.07):
+ A=at(A,NS); B=at(B,NS)
+ X=A.copy(); out=[X.copy()]
+ for f in range(1,frames+settle+1):
+ p=min(1,f/frames); e=p*p*(3-2*p)
+ tgt=dirblend(A,B,weights(NS-1,e,mode))
+ X+=(tgt-X)*pull
+ X=project(X,tgt[0])
+ out.append(X.copy())
+ K=np.array(out)
+ return finish(K,A,B)
+def finish(K,A,B,rounds=6,sigma=3.0,glide=16):
+ """Make a baked change of shape smooth in time and still valid: glide the end exactly into B, then alternate a
+ smoothing in time (ends held) with putting every frame back within its constraints, until both hold."""
+ from scipy.ndimage import gaussian_filter1d
+ K=K.copy(); n=len(K)
+ for i in range(glide):
+ w=(i+1)/glide; w=w*w*(3-2*w)
+ K[n-glide+i]=K[n-glide+i]*(1-w)+B*w
+ K[0]=A; K[-1]=B
+ pad=int(4*sigma)+1
+ for _ in range(rounds):
+ Kp=np.concatenate([np.repeat(K[:1],pad,0),K,np.repeat(K[-1:],pad,0)])
+ Kp=gaussian_filter1d(Kp,sigma,axis=0)[pad:-pad]
+ for f in range(1,n-1):
+ X=Kp[f].copy(); K[f]=project(X,X[0].copy(),iters=3)
+ K[0]=A; K[-1]=B
+ # last, a smoothing in time alone (the frames it averages are valid, so the result stays valid), as strong as it
+ # can be while no part comes closer than the tube's width
+ for sig in (3.0, 2.0, 1.0):
+ pad2=int(4*sig)+1
+ Kp=np.concatenate([np.repeat(K[:1],pad2,0),K,np.repeat(K[-1:],pad2,0)])
+ Ks=gaussian_filter1d(Kp,sig,axis=0)[pad2:-pad2]; Ks[0]=A; Ks[-1]=B
+ if min(clear(at(k)) for k in Ks[::3]) >= 0.98: return Ks
+ return K
+def stats(K,B):
+ cl=min(clear(at(k)) for k in K); mk=max(rk(at(k)) for k in K)
+ v=np.linalg.norm(np.diff(K,axis=0),axis=2).max(axis=1) # fastest point per frame
+ acc=np.linalg.norm(np.diff(K,2,axis=0),axis=2).max()
+ err=np.linalg.norm(at(K[-1],NS)-at(B,NS),axis=1).max()
+ return cl,mk,v.max(),acc,err
+if __name__=='__main__':
+ import sys
+ lib=dict(np.load('lib.npz'))
+ a,b=sys.argv[1],sys.argv[2]
+ for mode in ('all','foot','head'):
+ K=bake(lib[a],lib[b],mode)
+ print('%s->%s %-4s clear %.2f R*k %.2f max step %.1f pt max jerk %.1f end error %.1f pt'%((a,b,mode)+stats(K,lib[b])))
diff --git a/design/characters/coil3d/render3d.py b/design/characters/coil3d/render3d.py
new file mode 100644
index 0000000..e33fbab
--- /dev/null
+++ b/design/characters/coil3d/render3d.py
@@ -0,0 +1,51 @@
+import numpy as np
+from PIL import Image, ImageDraw
+from tube3d import *
+def shade_n(u,N):
+ x,y,z=N[...,0],N[...,1],N[...,2]
+ F=np.stack([np.ones_like(x),x,y,z,x*y,x*z,y*z,x*x-y*y,3*z*z-1],-1)
+ kn=len(ALB);f=np.clip(u,0,1)*(kn-1);k0=np.minimum(kn-2,f.astype(int));w=(f-k0)[...,None]
+ alb=ALB[k0]*(1-w)+ALB[k0+1]*w
+ return alb*(F@LIGHT)[...,None]+(F@SHEEN)[...,None]
+def render(P,yaw=0.0,S=4,W=198,H=242,center=(99,138),ao=True,label=''):
+ c,s=np.cos(yaw),np.sin(yaw);[email protected]([[c,0,s],[0,1,0],[-s,0,c]]).T
+ n=len(P);u=np.linspace(0,1,n)
+ # u along the albedo: the traced tube covers the first part; the head stays its end colour
+ ua=np.clip(u*L/373.0,0,1)
+ T=np.gradient(P,axis=0);T/=np.linalg.norm(T,axis=1,keepdims=True)
+ img=np.zeros((H*S,W*S,3));zb=np.full((H*S,W*S),-1e9)
+ yy,xx=np.mgrid[0:H*S,0:W*S].astype(float)
+ X=xx/S-center[0];Y=yy/S-center[1]
+ sarc=np.concatenate([[0],np.cumsum(np.linalg.norm(np.diff(P,axis=0),axis=1))])
+ for i in range(n):
+ p=P[i];r=R
+ x0=int(max(0,(p[0]+center[0]-r-2)*S));x1=int(min(W*S,(p[0]+center[0]+r+2)*S));y0=int(max(0,(p[1]+center[1]-r-2)*S));y1=int(min(H*S,(p[1]+center[1]+r+2)*S))
+ if x1<=x0 or y1<=y0: continue
+ dx=X[y0:y1,x0:x1]-p[0];dy=Y[y0:y1,x0:x1]-p[1]
+ # sphere sweep: each sample a sphere of radius R (the union is the tube); the tube's normal is the sphere's
+ # normal with its component along the tube removed
+ d2=dx*dx+dy*dy;m=d2<r*r
+ if not m.any(): continue
+ dz=np.sqrt(np.clip(r*r-d2,0,None));z=p[2]+dz
+ Nraw=np.stack([dx,dy,dz],-1)/r
+ t=T[i];Nt=Nraw-(Nraw@t)[...,None]*t;Nt/=np.linalg.norm(Nt,axis=-1,keepdims=True)+1e-9
+ if i==0 or i==n-1: Nt=Nraw # rounded ends
+ zz=z+(Nraw@t)*0 # depth of the sphere surface
+ zbuf=zb[y0:y1,x0:x1];win=m&(z>zbuf)
+ if not win.any(): continue
+ col=shade_n(np.full(win.sum(),ua[i]),Nt[win])
+ if ao:
+ far=np.abs(sarc-sarc[i])>3.5*R
+ Q=P[far]
+ if len(Q):
+ pts=np.stack([dx[win]+p[0],dy[win]+p[1],z[win]],1)
+ D=Q[None]-pts[:,None];dd=np.linalg.norm(D,axis=2)
+ nd=(D*Nt[win][:,None]).sum(2)/np.maximum(dd,1e-6)
+ occ=(np.clip(nd,0,1)*np.clip(1-(dd-R)/(1.8*R),0,1)**2).max(1)
+ a=np.clip(occ,0,1)[:,None]
+ col=col*(1-np.array([0.5,0.25,0.06])*a)*(1-0.3*a)
+ sub=img[y0:y1,x0:x1];sub[win]=col;zbuf[win]=z[win]
+ im=Image.fromarray((np.clip(img,0,1)*255).astype(np.uint8)).resize((W*2,H*2),Image.LANCZOS)
+ if label: ImageDraw.Draw(im).text((8,8),label,fill=(255,255,255))
+ # eyes
+ return im
diff --git a/design/characters/coil3d/rod.py b/design/characters/coil3d/rod.py
new file mode 100644
index 0000000..8d1c4a2
--- /dev/null
+++ b/design/characters/coil3d/rod.py
@@ -0,0 +1,165 @@
+"""Discrete rod representation of the tube's centreline (Bergou-style): per-segment length (constant), per-vertex
+material curvature (kappa1, kappa2) in a twist-free (Bishop / rotation-minimising) frame. Shapes are blended in this
+space, then rebuilt by forward kinematics from the foot, so a blend is always exactly length L and C1 smooth.
+Also: the soft, low-passed self-collision projection used after the kinematic blend."""
+import numpy as np
+
+def unit(v):
+ return v / np.maximum(np.linalg.norm(v, axis=-1, keepdims=True), 1e-12)
+
+def rmf(P):
+ """Rotation-minimising frames along polyline P: tangents t (per segment) and normals m1, m2, via Wang et al.'s
+ double reflection."""
+ t = unit(np.diff(P, axis=0))
+ n = len(t)
+ m1 = np.zeros_like(t); m2 = np.zeros_like(t)
+ # first normal: anything perpendicular to t0
+ a = np.array([0.0, 0.0, 1.0]) if abs(t[0, 2]) < 0.9 else np.array([1.0, 0.0, 0.0])
+ m1[0] = unit(a - t[0] * (a @ t[0])); m2[0] = np.cross(t[0], m1[0])
+ for i in range(n - 1):
+ v1 = P[i + 2] - P[i + 1] if False else (P[i + 1] - P[i]) # not used; keep classic form below
+ # double reflection
+ x0, x1 = P[i], P[i + 1]
+ v1 = x1 - x0; c1 = v1 @ v1
+ rL = m1[i] - (2 / c1) * (v1 @ m1[i]) * v1
+ tL = t[i] - (2 / c1) * (v1 @ t[i]) * v1
+ v2 = t[i + 1] - tL; c2 = v2 @ v2
+ m1[i + 1] = unit(rL - (2 / max(c2, 1e-18)) * (v2 @ rL) * v2) if c2 > 1e-18 else rL
+ m2[i + 1] = np.cross(t[i + 1], m1[i + 1])
+ return t, m1, m2
+
+def to_rod(P):
+ """P (n,3) equal-arc polyline -> (root, kappa) with root = (p0, t0, m1_0) and kappa (n-2, 2) material
+ curvature binormal components in the frame of the previous segment (|kb| = 2 tan(theta/2))."""
+ t, m1, m2 = rmf(P)
+ kb = 2 * np.cross(t[:-1], t[1:]) / (1 + np.einsum('ij,ij->i', t[:-1], t[1:]))[:, None]
+ kappa = np.stack([np.einsum('ij,ij->i', kb, m1[:-1]), np.einsum('ij,ij->i', kb, m2[:-1])], 1)
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1).mean()
+ return dict(p0=P[0].copy(), t0=t[0].copy(), m0=m1[0].copy(), kappa=kappa, seg=seg)
+
+def rot_axis(v, axis, ang):
+ """Rodrigues rotation of v (3,) about unit axis by ang."""
+ c, s = np.cos(ang), np.sin(ang)
+ return v * c + np.cross(axis, v) * s + axis * (axis @ v) * (1 - c)
+
+def from_rod(rod, n=None):
+ """Rebuild the polyline from a rod (exact inverse of to_rod up to float error)."""
+ kappa, seg = rod['kappa'], rod['seg']
+ m = len(kappa) + 2
+ P = np.zeros((m, 3)); P[0] = rod['p0']
+ t, m1 = unit(rod['t0']), unit(rod['m0'])
+ m1 = unit(m1 - t * (t @ m1)); m2 = np.cross(t, m1)
+ P[1] = P[0] + t * seg
+ for i in range(m - 2):
+ kb = kappa[i, 0] * m1 + kappa[i, 1] * m2
+ k = np.linalg.norm(kb)
+ if k > 1e-12:
+ axis = kb / k; th = 2 * np.arctan(k / 2)
+ t = rot_axis(t, axis, th); m1 = rot_axis(m1, axis, th)
+ # keep m1 twist-free w.r.t. t (it is by construction, renormalise for drift)
+ m1 = unit(m1 - t * (t @ m1)); m2 = np.cross(t, m1)
+ P[i + 2] = P[i + 1] + t * seg
+ return P
+
+def slerp(a, b, w):
+ a, b = unit(a), unit(b)
+ d = np.clip(a @ b, -1, 1); th = np.arccos(d)
+ if th < 1e-6: return unit(a * (1 - w) + b * w)
+ return (np.sin((1 - w) * th) * a + np.sin(w * th) * b) / np.sin(th)
+
+def blend_rods(A, B, w):
+ """Blend two rods with per-vertex weight w (scalar or (n-2,) array). Root frame slerped with w at the foot."""
+ w = np.broadcast_to(np.asarray(w, float), (len(A['kappa']),))
+ w0 = float(w[0])
+ t0 = slerp(A['t0'], B['t0'], w0)
+ m0 = slerp(A['m0'], B['m0'], w0); m0 = unit(m0 - t0 * (t0 @ m0))
+ return dict(p0=A['p0'] * (1 - w0) + B['p0'] * w0, t0=t0, m0=m0,
+ kappa=A['kappa'] * (1 - w[:, None]) + B['kappa'] * w[:, None], seg=A['seg'] * (1 - w0) + B['seg'] * w0)
+
+def front_weights(n, f, width=0.25, from_foot=True):
+ """A travelling-front weight profile: 0..1 along the rod, the front at progress f in [0,1] (f<0 or >1 pads)."""
+ u = np.linspace(0, 1, n)
+ x = (f * (1 + width) - width) if from_foot else None
+ if from_foot:
+ return np.clip((f * (1 + width) - u) / width, 0, 1) ** 2 * (3 - 2 * np.clip((f * (1 + width) - u) / width, 0, 1))
+ else:
+ v = 1 - u
+ q = np.clip((f * (1 + width) - v) / width, 0, 1)
+ return q * q * (3 - 2 * q)
+
+def smoothstep(x):
+ x = np.clip(x, 0, 1); return x * x * (3 - 2 * x)
+
+# ---------------- self-collision (soft, spatially and temporally smoothed) ----------------
+
+class Collider:
+ """Keeps a persistent per-node offset delta that is low-passed toward the separation the kinematic curve needs.
+ radii: per-node tube radius (so a swollen head collides correctly). excl: arc separation (pt) under which pairs are
+ skipped (adjacent tube)."""
+ def __init__(self, n, excl, margin=0.3, rate=12.0, blur=2):
+ self.n, self.excl, self.margin, self.rate, self.blur = n, excl, margin, rate, blur
+ self.delta = np.zeros((n, 3))
+
+ def target(self, P, radii, iters=3, pin_weight=None):
+ n = self.n
+ Q = P + self.delta
+ s = np.arange(n) * (np.linalg.norm(np.diff(P, axis=0), axis=1).mean())
+ far = np.abs(s[:, None] - s[None]) > self.excl
+ iu = np.triu_indices(n, 1)
+ mask = far[iu]
+ I, J = iu[0][mask], iu[1][mask]
+ rr = radii[I] + radii[J]
+ # weights: the foot side moves less (pin at the foot), the head side more
+ wgt = np.linspace(0.15, 1.0, n) if pin_weight is None else pin_weight
+ for _ in range(iters):
+ d = Q[J] - Q[I]; dist = np.linalg.norm(d, axis=1)
+ lim = rr * (1 + self.margin)
+ hit = dist < lim
+ if not hit.any(): break
+ # soft: the push ramps from 0 at lim to full at rr (C1 in distance)
+ pen = np.zeros_like(dist)
+ x = np.clip((lim[hit] - dist[hit]) / (lim[hit] - rr[hit]), 0, 1)
+ pen[hit] = (x * x * (3 - 2 * x)) * (lim[hit] - dist[hit])
+ dirn = d / np.maximum(dist, 1e-9)[:, None]
+ push = dirn * pen[:, None]
+ wi, wj = wgt[I], wgt[J]; ws = wi + wj
+ corr = np.zeros((n, 3)); cnt = np.zeros(n)
+ np.add.at(corr, I, -push * (wi / ws)[:, None]); np.add.at(corr, J, push * (wj / ws)[:, None])
+ np.add.at(cnt, I, hit.astype(float)); np.add.at(cnt, J, hit.astype(float))
+ corr /= np.maximum(cnt, 1)[:, None]
+ # spatial blur along the chain so a correction is a smooth bump, never a kink
+ for _b in range(self.blur):
+ c2 = corr.copy(); c2[1:-1] = 0.25 * corr[:-2] + 0.5 * corr[1:-1] + 0.25 * corr[2:]; corr = c2
+ Q = Q + corr
+ return Q - P
+
+ def step(self, P, radii, dt):
+ tgt = self.target(P, radii)
+ k = min(1.0, dt * self.rate)
+ self.delta += (tgt - self.delta) * k
+ return P + self.delta
+
+def min_sep(P, radii, excl):
+ n = len(P)
+ s = np.arange(n) * np.linalg.norm(np.diff(P, axis=0), axis=1).mean()
+ D = np.linalg.norm(P[:, None] - P[None], axis=2)
+ rr = radii[:, None] + radii[None]
+ far = np.abs(s[:, None] - s[None]) > excl
+ return (np.where(far, D / rr, 9)).min()
+
+# ---------------- placement: rod-space shape, positional-space placement ----------------
+
+def place(P, target, ground=None):
+ """Rigidly move P (the rod-space blend) so its centroid and yaw match `target` (the positional lerp of the two
+ poses): translation + the closed-form best yaw about the vertical axis. Then sit it on `ground` if given."""
+ c0, c1 = P.mean(0), target.mean(0)
+ A = P - c0; B = target - c1
+ # best rotation about y: maximise sum of (A rotated) . B in the xz plane
+ num = (A[:, 2] * B[:, 0] - A[:, 0] * B[:, 2]).sum(); den = (A[:, 0] * B[:, 0] + A[:, 2] * B[:, 2]).sum()
+ a = np.arctan2(num, den)
+ c, s = np.cos(a), np.sin(a)
+ Rm = np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
+ Q = A @ Rm.T + c1
+ if ground is not None:
+ Q[:, 1] += ground - Q[:, 1].max()
+ return Q
diff --git a/design/characters/coil3d/shapes.py b/design/characters/coil3d/shapes.py
new file mode 100644
index 0000000..4734483
--- /dev/null
+++ b/design/characters/coil3d/shapes.py
@@ -0,0 +1,79 @@
+"""Coil's shape library: every shape the same tube (length L, radius R), its bends round (no tighter than ~1.25 R), its
+parts never closer than the tube's width, standing on the ground (y = G, y down, z toward you), fitting the screen."""
+import numpy as np, tube3d as T, rod
+from scipy.ndimage import gaussian_filter1d
+from zigzag3d import make as make_zigzag
+R=T.R; NN=64; G=70.0
+ZIG,_=make_zigzag(kmax=0.6); L=T.length(ZIG)
+SEG=L/(NN-1)
+def at(P,n=NN): Q,_=T.resample(P,n); return Q
+def turns(P):
+ d=np.diff(P,axis=0);d/=np.linalg.norm(d,axis=1,keepdims=True)
+ return np.arccos(np.clip((d[:-1]*d[1:]).sum(1),-1,1))
+def rk(P): return turns(P).max()/SEG*R
+def clear(P): return rod.min_sep(P,np.full(len(P),R),4.5*R)
+def ground(P):
+ P=P.copy();P[:,1]+=G-P[:,1].max();c=P.mean(0);P[:,0]-=c[0];P[:,2]-=c[2];return P
+def solve_len(make,lo,hi):
+ for _ in range(60):
+ m=(lo+hi)/2
+ if T.length(make(m))<L: lo=m
+ else: hi=m
+ return make(hi)
+def rotx(P,a): c,s=np.cos(a),np.sin(a); return [email protected]([[1,0,0],[0,c,-s],[0,s,c]]).T
+def roty(P,a): c,s=np.cos(a),np.sin(a); return [email protected]([[c,0,s],[0,1,0],[-s,0,c]]).T
+def rotz(P,a): c,s=np.cos(a),np.sin(a); return [email protected]([[c,-s,0],[s,c,0],[0,0,1]]).T
+def helix(r0,r1,pitch,turns_,tilt=0.0,phase=0.0):
+ t=np.linspace(0,turns_*2*np.pi,2000);k=t/t[-1];r=r0+(r1-r0)*k
+ P=np.stack([r*np.cos(t+phase),-(k*turns_*pitch),r*np.sin(t+phase)],1)
+ return rotx(P,tilt) if tilt else P
+def shell(stem=0.0, rin=19.0, b=3.6, c=3.5, phase=np.pi/2, hand=1):
+ """A spiral facing you, wound in to the head at its middle (inner turns come forward); optionally on a stem from
+ the ground (the tail runs straight down from the outer turn)."""
+ def mk(Th):
+ th=np.linspace(0,Th,3000)
+ r=rin+b*(Th-th); a=phase+hand*th
+ P=np.stack([r*np.cos(a),r*np.sin(a),c*th],1)
+ if stem>0:
+ t0=P[1]-P[0];t0/=np.linalg.norm(t0)
+ S=np.array([P[0]-t0*s for s in np.linspace(stem,0,200,endpoint=False)])
+ P=np.vstack([S,P])
+ return P
+ return solve_len(mk,1.0,30.0)
+def slinky(r=24.0,pitch=36.0,tilt=0.25,yaw=0.35):
+ """A spring lying on its side, its axis across the screen."""
+ def mk(tr):
+ t=np.linspace(0,tr*2*np.pi,2000)
+ P=np.stack([-(t/(2*np.pi))*pitch, r*np.cos(t+np.pi/2), r*np.sin(t+np.pi/2)],1)
+ return roty(rotx(P,tilt),yaw)
+ return solve_len(mk,1.0,6.0)
+def smooth_to(P,kmax=0.85):
+ D=at(P,400);best=None
+ for sig in np.arange(0.0,12.1,0.5):
+ if sig>0:
+ k=int(4*sig)+2;t0=D[1]-D[0];t1=D[-1]-D[-2]
+ pad=np.vstack([D[0]-t0*np.arange(k,0,-1)[:,None],D,D[-1]+t1*np.arange(1,k+1)[:,None]])
+ Q=gaussian_filter1d(pad,sig,axis=0)[k:-k]
+ else: Q=D.copy()
+ c=Q.mean(0);Q=(Q-c)*(L/T.length(Q))+c;Q=at(Q)
+ m=rk(Q)
+ if best is None or m<best[0]: best=(m,Q)
+ if m<=kmax: break
+ return best[1]
+def library():
+ S={}
+ S['zigzag']=ZIG
+ S['tornado']=solve_len(lambda tr:helix(20,46,38,tr),1,6)
+ S['spring']=solve_len(lambda tr:helix(26,26,58,tr),1,6)
+ S['sleep']=solve_len(lambda tr:helix(52,20,2*R*1.02,tr,tilt=-0.42,phase=2.2),1,6)
+ S['messy']=np.load('messy.npy')
+ S['shell']=shell(hand=1)
+ S['lolly']=shell(stem=62.0,rin=19.0,b=3.6,c=3.5,phase=np.pi,hand=1)
+ S['slinky']=slinky()
+ out={}
+ for k,P in S.items(): out[k]=ground(smooth_to(P*(L/T.length(P))))
+ return out
+if __name__=='__main__':
+ lib=library()
+ for k,P in lib.items(): print('%-8s len %.0f clearance %.2f R*k %.2f extent %s'%(k,T.length(P),clear(P),rk(P),np.ptp(P,axis=0).round(0)))
+ np.savez('lib.npz',**lib)
diff --git a/design/characters/coil3d/slicer.py b/design/characters/coil3d/slicer.py
new file mode 100644
index 0000000..c0a4141
--- /dev/null
+++ b/design/characters/coil3d/slicer.py
@@ -0,0 +1,205 @@
+"""A renderer that only does what SwiftUI Canvas can do: ~200 slices, each ONE fill of (quad + disc at its far vertex)
+with ONE linear gradient of 8 stops across the width, drawn back to front (painter's sort by depth). No per-pixel
+lighting: the stops are computed from the lighting model at the slice's real 3D normals. Options: perspective, depth
+cue, proximity AO (per stop, against the coarse chain), contact shadow at crossings (per stop), head swell, eyes on the
+dome, drawn at the head's depth."""
+import numpy as np
+from PIL import Image, ImageDraw
+import tube3d as T
+from render3d import shade_n
+
+R = T.R
+W, H = 198, 242
+CENTER = (99.0, 138.0)
+
+def unit(v): return v / np.maximum(np.linalg.norm(v, axis=-1, keepdims=True), 1e-12)
+
+def radius_profile(u, swell=1.0, start=0.86):
+ """Uniform R, then a smooth swell to swell*R at the tip (a club end, still a tube that only bends)."""
+ x = np.clip((u - start) / (1 - start), 0, 1)
+ return R * (1 + (swell - 1) * (x * x * (3 - 2 * x)))
+
+def contact_cue(pt2, ptz, near, sarc, width=9.0, strength=0.65, dz=1.2 * R, excl=3.5 * R):
+ """Darkening at a far surface point from nearer slices (not its own run) whose projected capsule rim is within
+ `width` pt of the point."""
+ A, B, Z, Rr, Sarc = near
+ sel = (Z > ptz + dz) & (np.abs(Sarc - sarc) > excl)
+ if not sel.any(): return 0.0
+ a, b, rr = A[sel], B[sel], Rr[sel]
+ ab = b - a; l2 = np.maximum((ab * ab).sum(1), 1e-9)
+ tt = np.clip(((pt2 - a) * ab).sum(1) / l2, 0, 1)
+ q = a + ab * tt[:, None]; d = np.linalg.norm(pt2 - q, axis=1) - rr
+ x = np.clip(1 - d / width, 0, 1)
+ occ = 1 - np.prod(1 - strength * x * x * (3 - 2 * x))
+ return occ
+
+def render(P, yaw=0.0, S=3, perspective=0.0, depth_cue=0.0, contact=True, ao=True, swell=1.0, eyes=True,
+ stops=8, nslices=200, label='', eye_dir=None, yaw_pivot=None, fog_color=(0.02, 0.02, 0.04), spec=0.0, spec_pow=10.0, rim=0.0):
+ """P: (n,3) centreline in pt (y down, z toward you), about the origin. perspective: 1/f (0 = orthographic).
+ Returns a PIL image (W*2 x H*2)."""
+ c, s = np.cos(yaw), np.sin(yaw)
+ piv = np.zeros(3) if yaw_pivot is None else np.asarray(yaw_pivot)
+ P = (P - piv) @ np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]).T + piv
+ n = len(P); u = np.linspace(0, 1, n)
+ ua = np.clip(u * T.L / 373.0, 0, 1)
+ rad = radius_profile(u, swell)
+ # slices: every k-th centreline sample
+ k = max(1, n // nslices)
+ idx = np.arange(0, n - 1, k); idx = np.append(idx, n - 1) if idx[-1] != n - 1 else idx
+ # perspective projection: screen = xy * f/(f - z); the camera at z = f looking toward -z... z toward you, so near = larger
+ def proj(p):
+ if perspective <= 0: return p[..., :2].copy(), np.ones(p.shape[:-1])
+ sc = 1.0 / (1.0 - p[..., 2] * perspective)
+ return p[..., :2] * sc[..., None], sc
+ Pp, Ps = proj(P)
+ zmid = 0.5 * (P[idx[:-1], 2] + P[idx[1:], 2])
+ # tangents in 3D (central difference over the slice span)
+ tang = unit(P[np.minimum(idx + k, n - 1)] - P[np.maximum(idx - k, 0)])
+ order = np.argsort(zmid, kind='stable') # far first
+ img = np.zeros((H * S, W * S, 3), float)
+ cov = np.zeros((H * S, W * S), float)
+ yy, xx = np.mgrid[0:H * S, 0:W * S]
+ X = (xx + 0.5) / S - CENTER[0]; Y = (yy + 0.5) / S - CENTER[1]
+ # coarse chain for AO: 64 nodes
+ ci = np.linspace(0, n - 1, 64).astype(int); C = P[ci]; Cs = np.arange(64) * (T.L / 63)
+ # near-slice table for contact shadows: screen segments with their depth and screen radius
+ segA = Pp[idx[:-1]]; segB = Pp[idx[1:]]
+ segR = 0.5 * (rad[idx[:-1]] * Ps[idx[:-1]] + rad[idx[1:]] * Ps[idx[1:]])
+ sarc_all = 0.5 * (idx[:-1] + idx[1:]) / (n - 1) * T.L
+ near = (segA, segB, zmid, segR, sarc_all)
+ head_z = P[-1, 2]
+ drew_eyes = False
+ v = np.array([0, 0, 1.0])
+ for q in order:
+ i0, i1 = idx[q], idx[q + 1]
+ a3, b3 = P[i0], P[i1]
+ a2, b2 = Pp[i0], Pp[i1]
+ ra, rb = rad[i0] * Ps[i0], rad[i1] * Ps[i1]
+ t3 = tang[q]
+ # frame: n in-screen perpendicular to the projected tangent; b = n x t (toward the viewer within the cross-section)
+ tin = np.array([t3[0], t3[1], 0.0]); lin = np.linalg.norm(tin)
+ if lin < 0.05:
+ # pointing at the camera: use the previous slice's frame if any (continuity), else x
+ nrm = np.array([0.0, -1.0, 0.0]) if q == 0 else prev_n
+ else:
+ nrm = np.array([t3[1], -t3[0], 0.0]) / lin
+ prev_n = nrm
+ bvec = np.cross(nrm, t3); bvec = unit(bvec)
+ if bvec[2] < 0: bvec = -bvec; nrm = -nrm
+ n2 = nrm[:2]
+ # geometry of this slice in screen space: quad + disc at b (and at a for the first slice)
+ d2 = b2 - a2; l2 = np.linalg.norm(d2)
+ ext = (d2 / l2 * 0.35) if l2 > 1e-6 else np.zeros(2)
+ quad = np.array([a2 + n2 * ra - ext, b2 + n2 * rb + ext, b2 - n2 * rb + ext, a2 - n2 * ra - ext])
+ # bounding box
+ lo = np.floor((np.minimum(quad.min(0), np.minimum(a2 - ra, b2 - rb)) + np.array(CENTER) - 1) * S).astype(int)
+ hi = np.ceil((np.maximum(quad.max(0), np.maximum(a2 + ra, b2 + rb)) + np.array(CENTER) + 1) * S).astype(int)
+ x0, y0 = max(0, lo[0]), max(0, lo[1]); x1, y1 = min(W * S, hi[0]), min(H * S, hi[1])
+ if x1 <= x0 or y1 <= y0: continue
+ px = X[y0:y1, x0:x1]; py = Y[y0:y1, x0:x1]
+ # mask: quad (convex) OR disc(b) OR (disc(a) if first)
+ m = np.ones(px.shape, bool)
+ for e in range(4):
+ p0, p1 = quad[e], quad[(e + 1) % 4]
+ m &= ((p1[0] - p0[0]) * (py - p0[1]) - (p1[1] - p0[1]) * (px - p0[0])) <= 0
+ if l2 <= 1e-6: m[:] = False
+ m |= (px - b2[0]) ** 2 + (py - b2[1]) ** 2 <= rb * rb
+ if q == 0 or (q > 0 and order.tolist().index(q) == 0 and False): pass
+ if i0 == 0: m |= (px - a2[0]) ** 2 + (py - a2[1]) ** 2 <= ra * ra
+ if not m.any(): continue
+ # gradient parameter across the width: s in [-1, 1] along n2 about the slice mid
+ mid = 0.5 * (a2 + b2); rm = 0.5 * (ra + rb)
+ sgrad = ((px - mid[0]) * n2[0] + (py - mid[1]) * n2[1]) / rm
+ # stops
+ ss = np.linspace(-1, 1, stops)
+ Ns = ss[:, None] * nrm[None] + np.sqrt(1 - ss * ss)[:, None] * bvec[None]
+ umid = 0.5 * (ua[i0] + ua[i1])
+ cols = shade_n(np.full(stops, umid), Ns)
+ if spec > 0:
+ Hd = unit(np.array([-0.45, -0.62, 0.65]))
+ lobe = np.clip(Ns @ Hd, 0, 1) ** spec_pow
+ cols = cols + spec * lobe[:, None] * np.array([1.0, 0.97, 0.92])
+ if rim > 0:
+ cols = cols * (1 - rim * (1 - Ns[:, 2]) ** 2)[:, None]
+ if ao:
+ # proximity AO at the stop's surface point against the coarse chain (same model as render3d, soft-combined)
+ pm = 0.5 * (a3 + b3); rr3 = 0.5 * (rad[i0] + rad[i1])
+ surf = pm[None] + Ns * rr3
+ sarc = 0.5 * (i0 + i1) / (n - 1) * T.L
+ far = np.abs(Cs - sarc) > 3.5 * R
+ Q = C[far]
+ if len(Q):
+ D = Q[None] - surf[:, None]; dd = np.linalg.norm(D, axis=2)
+ nd = (D * Ns[:, None]).sum(2) / np.maximum(dd, 1e-6)
+ occ_i = np.clip(nd, 0, 1) * np.clip(1 - (dd - R) / (1.8 * R), 0, 1) ** 2
+ occ = 1 - np.prod(1 - occ_i, axis=1)
+ shade_a = np.clip(occ, 0, 1)
+ else:
+ shade_a = np.zeros(stops)
+ else:
+ shade_a = np.zeros(stops)
+ if contact:
+ # contact shadow from nearer slices at each stop's screen point, combined with the AO as one occlusion
+ for j in range(stops):
+ sp = mid + n2 * (ss[j] * rm)
+ cc = contact_cue(sp, zmid[q], near, sarc_all[q])
+ if cc > 0: shade_a[j] = 1 - (1 - shade_a[j]) * (1 - cc)
+ # hue-preserving shadow: toward a deep magenta-purple (the reference's creases), never below 45% brightness
+ tint = np.array([0.42, 0.22, 0.48])
+ fac = 1 - np.clip(shade_a, 0, 0.85)[:, None] * (1 - tint)
+ cols = cols * fac
+ if depth_cue > 0:
+ zc = zmid[q] / 60.0 # about -1..1
+ f = np.clip(1 - depth_cue * (0.5 - 0.5 * zc), 0, 1)
+ cols = cols * f + np.array(fog_color) * (1 - f) * 0.0
+ # rasterise the gradient (what Canvas does): clamp s and interpolate the stops
+ sc_ = np.clip(sgrad, -1, 1); f_ = (sc_ + 1) / 2 * (stops - 1); k0 = np.minimum(stops - 2, f_.astype(int)); w_ = f_ - k0
+ col = cols[k0] * (1 - w_)[..., None] + cols[k0 + 1] * w_[..., None]
+ sub = img[y0:y1, x0:x1]; sub[m] = col[m]; cov[y0:y1, x0:x1][m] = 1
+ # the eyes: drawn right after the head's slices in the sort (a pseudo-slice at the head's front depth)
+ if eyes and not drew_eyes and i1 == n - 1:
+ drew_eyes = True
+ img = draw_eyes(img, P, Pp, Ps, rad, tang[-1], S, eye_dir)
+ # if the head slice was not last in the order, the eyes were drawn when it was; parts nearer were drawn after
+ im = Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8)).resize((W * 2, H * 2), Image.LANCZOS)
+ if label: ImageDraw.Draw(im).text((8, 8), label, fill=(255, 255, 255))
+ return im
+
+def draw_eyes(img, P, Pp, Ps, rad, t_end, S, eye_dir=None):
+ """Two cream eyes on the head's dome: placed on the sphere of the end cap, foreshortened by the local normal."""
+ n = len(P)
+ hc3 = P[-1]; rh = rad[-1]
+ # the face direction: mostly toward the viewer, tilted along the end tangent and a little up
+ fd = unit(np.array([0, 0, 1.0]) * 0.8 + t_end * 0.45 + np.array([0, -0.25, 0])) if eye_dir is None else unit(np.asarray(eye_dir))
+ # eye basis on the dome
+ up = np.array([0, -1.0, 0]); right = unit(np.cross(up, fd)); up2 = unit(np.cross(fd, right))
+ sep, lift = 0.42, 0.10
+ cream = np.array([0.99, 0.915, 0.83])
+ yy, xx = np.mgrid[0:img.shape[0], 0:img.shape[1]]
+ X = (xx + 0.5) / S - CENTER[0]; Y = (yy + 0.5) / S - CENTER[1]
+ for side in (-1, 1):
+ dirn = unit(fd + right * (side * sep) + up2 * lift)
+ if dirn[2] < 0.12: continue # facing away: hidden
+ p3 = hc3 + dirn * rh * 1.0
+ sc = 1.0 / (1.0 - p3[2] * 0.0) if True else 1
+ p2 = p3[:2]; # orthographic placement is fine for the eyes relative to the projected head
+ # projected head centre and scale
+ hs = Ps[-1]; hc2 = Pp[-1]
+ p2 = hc2 + (p3[:2] - hc3[:2]) * hs
+ rx, ry = 3.4 * hs * (rh / R) ** 0.6, 4.6 * hs * (rh / R) ** 0.6
+ # foreshorten along the direction the eye normal tilts in screen
+ fz = max(0.25, dirn[2])
+ tilt = dirn[:2]; tl = np.linalg.norm(tilt)
+ if tl > 1e-6:
+ ex, ey = tilt / tl
+ else:
+ ex, ey = 1.0, 0.0
+ # ellipse: axis along tilt scaled by fz
+ dx = X - p2[0]; dy = Y - p2[1]
+ a_ = (dx * ex + dy * ey) / fz; b_ = (-dx * ey + dy * ex)
+ # map to the eye's own ellipse (rx across, ry up): approximate by radial scale with the eye's aspect
+ q = (a_ / rx) ** 2 + (b_ / ry) ** 2
+ m = q <= 1
+ soft = np.clip(1.6 - np.sqrt(np.maximum(q, 0)) * 1.0, 0, 1)
+ img[m] = cream
+ return img
diff --git a/design/characters/coil3d/tie.py b/design/characters/coil3d/tie.py
new file mode 100644
index 0000000..61d5ffe
--- /dev/null
+++ b/design/characters/coil3d/tie.py
@@ -0,0 +1,60 @@
+"""Offline bake of the knot entry: a PBD rope (fixed length, 2R self-collision, bending smoothness, foot pinned) whose
+head is led on a path: top of the tornado coil -> down through the top ring -> out between the rings -> away, which
+tightens an overhand knot. Keyframes are recorded as rods; the runtime would blend keyframe to keyframe."""
+import numpy as np, tube3d as T, rod
+R=T.R; n=100; seg=T.L/(n-1)
+def resample_n(P,m): Q,_=T.resample(P,m); return Q
+def pbd_step(X, head_target, pin0, iters=12, excl_nodes=11, bend=0.08):
+ n=len(X)
+ iu=np.triu_indices(n,1); far=(iu[1]-iu[0])>excl_nodes; I,J=iu[0][far],iu[1][far]
+ for _ in range(iters):
+ X[0]=pin0
+ X[-1]+= (head_target-X[-1])*0.5
+ # bending: pull each node toward the midpoint of its neighbours a little (smoothness)
+ X[1:-1]+=bend*(X[:-2]+X[2:]-2*X[1:-1])
+ # collisions
+ d=X[J]-X[I]; dist=np.linalg.norm(d,axis=1); lim=2*R*1.03; hit=dist<lim
+ if hit.any():
+ push=d[hit]/np.maximum(dist[hit],1e-9)[:,None]*(lim-dist[hit])[:,None]*0.5
+ np.add.at(X,I[hit],-push); np.add.at(X,J[hit],push)
+ # lengths
+ for _k in range(2):
+ dd=np.diff(X,axis=0); ln=np.linalg.norm(dd,axis=1); cor=dd*((ln-seg)/np.maximum(ln,1e-9))[:,None]*0.5
+ X[:-1]+=cor; X[1:]-=cor
+ X[0]=pin0
+ return X
+# start: the tornado (head on top ring, radius 44)
+P=resample_n(T.tornado(0.0),n); X=P.copy(); pin0=X[0].copy()
+head0=X[-1].copy(); axis_xz=np.array([X[:,0].mean(),0,X[:,2].mean()])
+top_y=X[:,1].min()
+# path for the head (world pts): over the axis, down through the ring, out sideways, then away
+def lerp(a,b,t): return a+(b-a)*t
+over=np.array([axis_xz[0],top_y-30,axis_xz[2]])
+through=np.array([axis_xz[0],top_y+34,axis_xz[2]])
+# exit direction: opposite to where the head started (so it crosses the standing part)
+hd=head0-axis_xz; hd[1]=0; hd/=np.linalg.norm(hd)
+exitp=np.array([axis_xz[0],top_y+40,axis_xz[2]])-hd*75
+away=exitp+np.array([0,-70,0])-hd*25
+waypts=[head0,over,through,exitp,away]; durs=[40,45,50,70]
+keys=[X.copy()]; sepl=[]
+radii=np.full(n,R)
+for w in range(4):
+ for s in range(durs[w]):
+ tgt=lerp(waypts[w],waypts[w+1],(s+1)/durs[w])
+ X=pbd_step(X,tgt,pin0)
+ sepl.append(rod.min_sep(X,radii,4.5*R))
+ keys.append(X.copy())
+# then settle: let the knot find its shape with the head held
+for s in range(60): X=pbd_step(X,away,pin0); sepl.append(rod.min_sep(X,radii,4.5*R))
+keys.append(X.copy())
+print('sim min clearance over the whole path: %.2f (worst frame %d of %d)'%(min(sepl),int(np.argmin(sepl)),len(sepl)))
+print('final length %.1f, extent %s, head y %.0f'%(T.length(X),np.ptp(X,axis=0).round(0),X[-1,1]))
+np.save('tie_keys.npy',np.array(keys))
+# playback test: blend consecutive keyframes in rod space (10 steps each) and measure clearance
+rods=[rod.to_rod(k) for k in keys]
+worst=9
+for a in range(len(rods)-1):
+ for t in np.linspace(0,1,11):
+ Q=rod.from_rod(rod.blend_rods(rods[a],rods[a+1],t)); worst=min(worst,rod.min_sep(Q,radii,4.5*R))
+print('kinematic playback between the %d keyframes: min clearance %.2f'%(len(keys),worst))
+# how many keyframes would be needed: record every 15 sim steps instead
diff --git a/design/characters/coil3d/tie2.py b/design/characters/coil3d/tie2.py
new file mode 100644
index 0000000..fbed7e2
--- /dev/null
+++ b/design/characters/coil3d/tie2.py
@@ -0,0 +1,40 @@
+"""Bake the knot entry (tie.py), with the head finishing in front (toward you) and up so the face stays seen."""
+import numpy as np, tube3d as T, rod
+R=T.R; n=100; seg=T.L/(n-1)
+def resample_n(P,m): Q,_=T.resample(P,m); return Q
+def pbd_step(X, head_target, pin0, iters=12, excl_nodes=11, bend=0.08):
+ n=len(X)
+ iu=np.triu_indices(n,1); far=(iu[1]-iu[0])>excl_nodes; I,J=iu[0][far],iu[1][far]
+ for _ in range(iters):
+ X[0]=pin0
+ X[-1]+= (head_target-X[-1])*0.5
+ X[1:-1]+=bend*(X[:-2]+X[2:]-2*X[1:-1])
+ d=X[J]-X[I]; dist=np.linalg.norm(d,axis=1); lim=2*R*1.03; hit=dist<lim
+ if hit.any():
+ push=d[hit]/np.maximum(dist[hit],1e-9)[:,None]*(lim-dist[hit])[:,None]*0.5
+ np.add.at(X,I[hit],-push); np.add.at(X,J[hit],push)
+ for _k in range(2):
+ dd=np.diff(X,axis=0); ln=np.linalg.norm(dd,axis=1); cor=dd*((ln-seg)/np.maximum(ln,1e-9))[:,None]*0.5
+ X[:-1]+=cor; X[1:]-=cor
+ X[0]=pin0
+ return X
+def bake(tornado):
+ X=resample_n(tornado,n); pin0=X[0].copy()
+ head0=X[-1].copy(); axis_xz=np.array([X[:,0].mean(),0,X[:,2].mean()])
+ top_y=X[:,1].min()
+ lerp=lambda a,b,t:a+(b-a)*t
+ over=np.array([axis_xz[0],top_y-30,axis_xz[2]])
+ through=np.array([axis_xz[0],top_y+34,axis_xz[2]])
+ hd=np.array([0.25,0,-1.0]);hd/=np.linalg.norm(hd) # leave toward the viewer, a little to the left
+ exitp=np.array([axis_xz[0],top_y+40,axis_xz[2]])-hd*75
+ away=exitp+np.array([0,-62,0])-hd*18
+ waypts=[head0,over,through,exitp,away]; durs=[40,45,50,70]
+ keys=[X.copy()]; sepl=[]; radii=np.full(n,R)
+ for w in range(4):
+ for s in range(durs[w]):
+ X=pbd_step(X,lerp(waypts[w],waypts[w+1],(s+1)/durs[w]),pin0); sepl.append(rod.min_sep(X,radii,4.5*R))
+ if s%6==5: keys.append(X.copy())
+ for s in range(60):
+ X=pbd_step(X,away,pin0); sepl.append(rod.min_sep(X,radii,4.5*R))
+ if s%12==11: keys.append(X.copy())
+ return np.array(keys),min(sepl)
diff --git a/design/characters/coil3d/trans.pkl b/design/characters/coil3d/trans.pkl
new file mode 100644
index 0000000..85db581
Binary files /dev/null and b/design/characters/coil3d/trans.pkl differ
diff --git a/design/characters/coil3d/trans.py b/design/characters/coil3d/trans.py
new file mode 100644
index 0000000..832dd36
--- /dev/null
+++ b/design/characters/coil3d/trans.py
@@ -0,0 +1,42 @@
+"""Which shape can turn straight into which, and how: each link's direction turns from one to the other, all at once
+or as a front running from the foot or the head. Checked for keeping its parts apart and for not swinging round."""
+import numpy as np, tube3d as T, rod
+from shapes import R, L, clear, rk
+def unit(v): return v/np.maximum(np.linalg.norm(v,axis=-1,keepdims=True),1e-12)
+def weights(n,p,mode,wd=0.5):
+ u=np.linspace(0,1,n)
+ if mode=='all': x=np.full(n,p)
+ elif mode=='foot': x=(p*(1+wd)-u)/wd
+ else: x=(p*(1+wd)-(1-u))/wd
+ x=np.clip(x,0,1); return x*x*(3-2*x)
+def dirblend(A,B,w):
+ ta=unit(np.diff(A,axis=0)); tb=unit(np.diff(B,axis=0)); n=len(ta)
+ out=np.zeros_like(ta)
+ for i in range(n):
+ d=np.clip(ta[i]@tb[i],-1,1); th=np.arccos(d)
+ if th<1e-6: out[i]=ta[i]; continue
+ if th>3.1:
+ ax=unit(np.cross(ta[i],np.array([0,0,1.0]))); out[i]=np.cos(w[i]*th)*ta[i]+np.sin(w[i]*th)*np.cross(ax,ta[i]); continue
+ out[i]=(np.sin((1-w[i])*th)*ta[i]+np.sin(w[i]*th)*tb[i])/np.sin(th)
+ seg=np.linalg.norm(np.diff(A,axis=0),axis=1).mean()
+ P=np.vstack([[0,0,0],np.cumsum(out*seg,axis=0)])
+ wm=w.mean()
+ return P-P.mean(0)+(A.mean(0)*(1-wm)+B.mean(0)*wm)
+def check(A,B,mode,steps=24):
+ worst=9; maxk=0
+ for p in np.linspace(0,1,steps):
+ e=p*p*(3-2*p); w=weights(len(A)-1,e,mode)
+ P=dirblend(A,B,w); worst=min(worst,clear(P)); maxk=max(maxk,rk(P))
+ return worst,maxk
+if __name__=='__main__':
+ lib=dict(np.load('lib.npz'))
+ names=list(lib)
+ table={}
+ for a in names:
+ for b in names:
+ if a>=b: continue
+ res={m:check(lib[a],lib[b],m) for m in ('all','foot','head')}
+ best=max(res,key=lambda m:res[m][0])
+ table[(a,b)]=(best,)+res[best]
+ print('%-8s <-> %-8s best %-4s clear %.2f R*k %.2f (all %.2f foot %.2f head %.2f)'%(a,b,best,res[best][0],res[best][1],res['all'][0],res['foot'][0],res['head'][0]))
+ import pickle; pickle.dump(table,open('trans.pkl','wb'))
diff --git a/design/characters/coil3d/tube3d.py b/design/characters/coil3d/tube3d.py
new file mode 100644
index 0000000..5fb3a39
--- /dev/null
+++ b/design/characters/coil3d/tube3d.py
@@ -0,0 +1,67 @@
+import numpy as np, re
+src=open('CoilRest-fit.swift').read()
+def arr3(name):
+ body=src.split('static let %s:'%name)[1].split('\n')[0]
+ return np.array([[float(a),float(b),float(c)] for a,b,c in re.findall(r'SIMD3\(([-\d.]+), ([-\d.]+), ([-\d.]+)\)',body)])
+def arrf(name):
+ body=src.split('static let %s:'%name)[1].split('\n')[0]
+ return np.array([float(v) for v in re.findall(r'-?\d+\.\d+',body.split('=')[1])])
+nodes=np.array([[float(a),float(b)] for a,b in re.findall(r'SIMD2\(([-\d.]+), ([-\d.]+)\)',src.split('static let nodes')[1].split('\n')[0])])
+ALB=arr3('albedo');LIGHT=arrf('light');SHEEN=arrf('sheen')
+R=14.5
+def resample(P,n):
+ s=np.concatenate([[0],np.cumsum(np.linalg.norm(np.diff(P,axis=0),axis=1))]);t=np.linspace(0,s[-1],n)
+ return np.stack([np.interp(t,s,P[:,k]) for k in range(P.shape[1])],1),s[-1]
+def length(P): return np.linalg.norm(np.diff(P,axis=0),axis=1).sum()
+# --- poses (pt; y down; z toward you; centred near the origin, the ground at y=+GROUND) ---
+GROUND=78.0
+def zigzag():
+ P=np.c_[nodes,np.zeros(len(nodes))]
+ d=P[-1]-P[-3];d/=np.linalg.norm(d)
+ ext=np.array([P[-1]+d*k for k in np.linspace(2,30,15)])
+ P=np.vstack([P,ext])
+ P,_=resample(P,400);u=np.linspace(0,1,len(P))
+ P[:,2]=(u-0.5)*115
+ return P
+L=length(zigzag())
+def fitlen(P,c=None):
+ l=length(P);c=P.mean(0) if c is None else c
+ return (P-c)*(L/l)+c
+def helix(r0,r1,pitch,turns,phase=0.0,tilt=0.0,up=True):
+ t=np.linspace(0,turns*2*np.pi,800);k=t/t[-1]
+ r=r0+(r1-r0)*k
+ P=np.stack([r*np.cos(t+phase),-(k*turns*pitch),r*np.sin(t+phase)],1)
+ if tilt:
+ c,s=np.cos(tilt),np.sin(tilt);[email protected]([[1,0,0],[0,c,-s],[0,s,c]]).T
+ return P
+def tornado(phase=0.0):
+ # narrow at the foot, widening as it rises; the head at the top
+ for turns in np.linspace(1.5,3.5,81):
+ P=helix(14,44,38,turns,phase)
+ if length(P)>=L: break
+ P,_=resample(P,400);P[:,1]+=GROUND-P[:,1].max();P[:,0]-=P[:,0].mean()*0;return P
+def sleepcoil(phase=0.0):
+ # wide at the bottom, tighter going up, stacked (touching), seen a little from above
+ for turns in np.linspace(1.2,3.5,93):
+ P=helix(52,20,2*R*1.02,turns,phase+2.2,tilt=-0.42)
+ if length(P)>=L: break
+ P,_=resample(P,400);P[:,1]+=GROUND-P[:,1].max();return P
+def spring(phase=0.0):
+ for turns in np.linspace(1.2,4,113):
+ P=helix(26,26,58,turns,phase)
+ if length(P)>=L: break
+ P,_=resample(P,400);P[:,1]+=GROUND-P[:,1].max();return P
+def knot(phase=0.0,zk=2.8):
+ t=np.linspace(0.75,2*np.pi-0.75,900)
+ P=np.stack([np.sin(t)+2*np.sin(2*t),np.cos(t)-2*np.cos(2*t),-zk*np.sin(3*t)],1)
+ c,s=np.cos(phase),np.sin(phase);[email protected]([[c,0,s],[0,1,0],[-s,0,c]]).T
+ P=P*(L/length(P));P,_=resample(P,400);P[:,1]+=GROUND-P[:,1].max()-6;return P
+def clump(phase=0.0):
+ t=np.linspace(0,1,900);a=2*np.pi*1.75*t;b=np.pi*(0.9*t-0.45)+0.3*np.sin(a*1.3)
+ rho=40+12*np.sin(a*2.0)
+ P=np.stack([rho*np.cos(a+phase)*np.cos(b),rho*np.sin(b),rho*np.sin(a+phase)*np.cos(b)],1)
+ P=P*(L/length(P));P,_=resample(P,400);P[:,1]+=GROUND-P[:,1].max();return P
+def mindist(P,R=R):
+ n=len(P);s=np.concatenate([[0],np.cumsum(np.linalg.norm(np.diff(P,axis=0),axis=1))])
+ D=np.linalg.norm(P[:,None]-P[None],axis=2);far=np.abs(s[:,None]-s[None])>3.2*R
+ return (D[far]).min()/(2*R)
diff --git a/design/characters/coil3d/zigzag3d.npy b/design/characters/coil3d/zigzag3d.npy
new file mode 100644
index 0000000..eef482f
Binary files /dev/null and b/design/characters/coil3d/zigzag3d.npy differ
diff --git a/design/characters/coil3d/zigzag3d.py b/design/characters/coil3d/zigzag3d.py
new file mode 100644
index 0000000..99c464a
--- /dev/null
+++ b/design/characters/coil3d/zigzag3d.py
@@ -0,0 +1,25 @@
+"""The rest pose: the reference's zigzag as seen from the front (x, y traced), given the depth (z) that lets a round tube
+of this width make its bends: each elbow turns partly through depth, so no bend is tighter than ~1.3 tube radii, while
+later folds stay in front of earlier ones."""
+import numpy as np, tube3d as T
+from scipy.optimize import minimize
+R=T.R
+def make(n=96, kmax=0.72, ramp=80.0):
+ zig=T.zigzag()
+ D,_=T.resample(zig[:,:2],n) # the front view, evenly along it
+ u=np.linspace(0,1,n); z0=(u-0.5)*ramp
+ def curve(z): return np.c_[D,z]
+ def obj(z):
+ P=curve(z); d=np.diff(P,axis=0); sl=np.linalg.norm(d,axis=1); t=d/sl[:,None]
+ c=np.clip((t[:-1]*t[1:]).sum(1),-1,1); th=np.arccos(c); k=th/((sl[:-1]+sl[1:])/2)*R
+ over=np.maximum(0,k-kmax)
+ dz2=np.diff(z,2)
+ return 400*np.sum(over**2)+0.02*np.sum(dz2**2)+0.0005*np.sum((z-z0)**2)
+ res=minimize(obj,z0,method='L-BFGS-B',options=dict(maxiter=4000))
+ P=curve(res.x)
+ return P,res
+if __name__=='__main__':
+ P,res=make()
+ d=np.diff(P,axis=0);sl=np.linalg.norm(d,axis=1);t=d/sl[:,None];th=np.arccos(np.clip((t[:-1]*t[1:]).sum(1),-1,1))
+ print('max R*k %.2f, length %.0f, z range %.0f..%.0f'%((th/((sl[:-1]+sl[1:])/2)*R).max(),T.length(P),P[:,2].min(),P[:,2].max()))
+ np.save('zigzag3d.npy',P)
diff --git a/design/mockup/apple-se3-midnight-hw.jpg b/design/mockup/apple-se3-midnight-hw.jpg
new file mode 100644
index 0000000..7d4a3eb
Binary files /dev/null and b/design/mockup/apple-se3-midnight-hw.jpg differ
diff --git a/design/mockup/apple-se3-midnight-mask.png b/design/mockup/apple-se3-midnight-mask.png
new file mode 100644
index 0000000..46054b6
Binary files /dev/null and b/design/mockup/apple-se3-midnight-mask.png differ
diff --git a/design/mockup/compose.py b/design/mockup/compose.py
new file mode 100644
index 0000000..e84d8a1
--- /dev/null
+++ b/design/mockup/compose.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Puts a watch-screen video (or image) into Apple's SE 3 photo, on a background of your choice, as a video.
+
+ python3 compose.py SCREEN OUT [--size 1080x1350] [--bg 1d1d1f | --bg-image FILE] [--height 0.86] [--y 0] [--fps 60]
+
+SCREEN a recording of the watch screen, any size with the screen's shape (396x484 from the Series 7 simulator,
+ 368x448 from the SE 3 one): it fills the screen's opening in the photo.
+OUT .mp4 (H.264), or .mov for ProRes 4444 with a transparent background (--bg none).
+--size the frame, W x H (default 1080x1350, 4:5; 1080x1080, 1920x1080 and 1080x1920 work too)
+--bg background colour (hex), or none for transparent (.mov only)
+--bg-image an image (or video) behind the watch instead, scaled to cover the frame
+--height how much of the frame the watch takes, its height or its width, whichever fills first (default 0.86)
+--y move the watch down (+) or up (-), in pixels of the frame
+
+--watch the watch image (default watch.png here): any PNG with a transparent background and a transparent screen
+ opening; the opening is found in it, so an edited watch (other strap, a lanyard, a bigger canvas) just works.
+"""
+import argparse
+import os
+import subprocess
+import sys
+
+import numpy as np
+from PIL import Image
+from scipy import ndimage
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+p = argparse.ArgumentParser()
+p.add_argument('screen'); p.add_argument('out')
+p.add_argument('--size', default='1080x1350')
+p.add_argument('--bg', default='1d1d1f')
+p.add_argument('--bg-image')
+p.add_argument('--height', type=float, default=0.86)
+p.add_argument('--y', type=float, default=0)
+p.add_argument('--fps', type=int, default=60)
+p.add_argument('--watch', default=os.path.join(HERE, 'watch.png'))
+o = p.parse_args()
+
+# the watch itself, without the empty margin round it (--height is the watch's, however much canvas it came on)
+alpha = np.asarray(Image.open(o.watch).convert('RGBA'))[..., 3]
+ys, xs = np.nonzero(alpha > 8)
+CX, CY = xs.min(), ys.min()
+alpha = alpha[CY:ys.max() + 1, CX:xs.max() + 1]
+WATCH_H, WATCH_W = alpha.shape
+# the screen's opening: the biggest see-through region that doesn't touch the image's edge
+lbl, n = ndimage.label(alpha < 128)
+edge = set(np.unique(np.concatenate([lbl[0], lbl[-1], lbl[:, 0], lbl[:, -1]])))
+sizes = ndimage.sum(np.ones_like(lbl), lbl, range(1, n + 1))
+inner = [i + 1 for i in np.argsort(-sizes) if i + 1 not in edge]
+if not inner:
+ sys.exit(f'no screen opening found in {o.watch}: the screen has to be transparent')
+ys, xs = np.nonzero(lbl == inner[0])
+HOLE_X, HOLE_Y, HOLE_W, HOLE_H = xs.min(), ys.min(), xs.max() - xs.min() + 1, ys.max() - ys.min() + 1
+
+W, H = map(int, o.size.lower().split('x'))
+k = min(H * o.height / WATCH_H, W * o.height / WATCH_W) # it fits the frame both ways
+ww, wh = round(WATCH_W * k / 2) * 2, round(WATCH_H * k / 2) * 2
+x0, y0 = (W - ww) // 2, round((H - wh) / 2 + o.y)
+# the screen video fills the opening and runs a few pixels under the bezel all round: the opening's edge is soft
+# (half see-through), and anything short of it lets the background through as a thin line
+M = 4
+sx, sy = x0 + int((HOLE_X - M) * k), y0 + int((HOLE_Y - M) * k)
+sw, sh = int((HOLE_W + 2 * M) * k / 2 + 1) * 2, int((HOLE_H + 2 * M) * k / 2 + 1) * 2
+alpha = o.bg == 'none'
+if alpha and not o.out.endswith('.mov'):
+ sys.exit('a transparent background needs a .mov output (ProRes 4444)')
+
+image = o.screen.lower().endswith(('.png', '.jpg', '.jpeg'))
+inputs = (['-loop', '1'] if image else []) + ['-i', o.screen, '-loop', '1', '-i', o.watch]
+if o.bg_image:
+ inputs += (['-loop', '1'] if o.bg_image.lower().endswith(('.png', '.jpg', '.jpeg')) else []) + ['-i', o.bg_image]
+ bg = f'[2:v]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},fps={o.fps},format=rgba[bg]'
+else:
+ color = '[email protected]' if alpha else '0x' + o.bg.lstrip('#')
+ bg = f'color=c={color}:s={W}x{H}:r={o.fps},format=rgba[bg]'
+graph = ';'.join([
+ bg,
+ f'[0:v]fps={o.fps},scale={sw}:{sh}:force_original_aspect_ratio=decrease:flags=lanczos,'
+ f'pad={sw}:{sh}:(ow-iw)/2:(oh-ih)/2:color=black,format=rgba[scr]',
+ f'[1:v]crop={WATCH_W}:{WATCH_H}:{CX}:{CY},scale={ww}:{wh}:flags=bicubic,format=rgba[hw]',
+ f'[bg][scr]overlay={sx}:{sy}:shortest=1[b1]',
+ f'[b1][hw]overlay={x0}:{y0}:shortest=1' + ('' if alpha else ',format=yuv420p') + '[v]',
+])
+codec = ['-c:v', 'prores_ks', '-profile:v', '4444', '-pix_fmt', 'yuva444p10le'] if alpha else \
+ ['-c:v', 'libx264', '-crf', '14', '-preset', 'slow', '-pix_fmt', 'yuv420p', '-movflags', '+faststart']
+duration = ['-t', '5'] if image else []
+cmd = ['ffmpeg', '-loglevel', 'error', '-y', *inputs, '-filter_complex', graph, '-map', '[v]', *duration, *codec, o.out]
+subprocess.run(cmd, check=True)
+print(o.out)
diff --git a/design/mockup/cutout.py b/design/mockup/cutout.py
new file mode 100644
index 0000000..897a435
--- /dev/null
+++ b/design/mockup/cutout.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Cuts a watch image shot (or painted) on white out of its white: the background and the screen become transparent.
+
+ python3 cutout.py IN OUT.png [--white 238]
+
+Anything darker than --white (0-255, default 238) is the object, small light spots inside it (glints on the glass and
+the case) are kept; the screen, the big white opening inside the case, becomes see-through like the background. Along
+every edge the pixels mixing object and white are given their share of transparency and their white taken out, so the
+cut-out sits cleanly on any background. Faint marks in the white (left over from an edit) are dropped.
+For a light-coloured object (a white lanyard) on white this can't tell the two apart: shoot or paint it on another
+colour, or keep it on its own layer and cut it out by hand.
+"""
+import argparse
+
+import numpy as np
+from PIL import Image
+from scipy import ndimage
+
+p = argparse.ArgumentParser()
+p.add_argument('src'); p.add_argument('out')
+p.add_argument('--white', type=float, default=238)
+o = p.parse_args()
+
+C = np.asarray(Image.open(o.src).convert('RGB')).astype(np.float64)
+L = C.mean(axis=2)
+W = np.array([255.0, 255.0, 255.0])
+
+# the object: darker than the white, with its small light spots filled in (not the screen: it's far too big)
+solid = L < o.white
+lbl, n = ndimage.label(~solid)
+sizes = ndimage.sum(np.ones_like(lbl), lbl, range(1, n + 1))
+small = np.isin(lbl, [i + 1 for i, s in enumerate(sizes) if s < 4000])
+solid |= small
+# keep the main object only (drop specks)
+lbl, n = ndimage.label(solid)
+sizes = ndimage.sum(np.ones_like(lbl), lbl, range(1, n + 1))
+solid = lbl == (np.argmax(sizes) + 1)
+
+# along the edges: the object's own colour there (averaged from solid pixels nearby), and how much of each pixel is it
+core = ndimage.binary_erosion(solid, iterations=2)
+w = ndimage.uniform_filter(core.astype(float), 9)
+F = np.stack([ndimage.uniform_filter(C[..., c] * core, 9) for c in range(3)], -1) / np.maximum(w, 1e-6)[..., None]
+d = W - F
+alpha_soft = np.clip(((W - C) * d).sum(-1) / np.maximum((d * d).sum(-1), 1e-6), 0, 1)
+near = ndimage.binary_dilation(solid, iterations=3) & ~core
+alpha = np.where(core, 1.0, np.where(near, alpha_soft, 0.0))
+alpha[alpha < 0.06] = 0
+
+# the edge pixels take the object's own colour there (un-mixing the white from a nearly clear pixel only amplifies
+# its noise into a grey seam)
+fg = np.where(core[..., None], C, np.clip(F, 0, 255))
+fg[alpha == 0] = 0
+
+Image.fromarray(np.dstack([fg, alpha * 255]).round().astype(np.uint8), 'RGBA').save(o.out)
+print(o.out, C.shape[1], 'x', C.shape[0])
diff --git a/design/mockup/noband.sh b/design/mockup/noband.sh
new file mode 100755
index 0000000..8a02e32
--- /dev/null
+++ b/design/mockup/noband.sh
@@ -0,0 +1,19 @@
+#!/bin/zsh
+# Rebuilds watch-noband.png from the band-less edit of the watch photo (on white, 828x1348).
+# design/mockup/noband.sh ["$HOME/Downloads/watch no band.png"]
+set -e
+cd "${0:A:h}"
+python3 -W ignore cutout.py "${1:-$HOME/Downloads/watch no band.png}" watch-noband.png
+# the edit left the outer edge of the right glass band brighter and sharper than Apple's (it read as a white line):
+# no brighter than the same edge on the left
+python3 -W ignore - <<'PY'
+from PIL import Image
+import numpy as np
+im = np.asarray(Image.open('watch-noband.png').convert('RGBA')).astype(np.float64)
+L = im[..., :3].mean(-1)
+ys, xs = np.mgrid[0:im.shape[0], 0:im.shape[1]]
+band = (xs >= 750) & (xs <= 760) & (ys >= 280) & (ys <= 1060) & (L > 78)
+im[..., :3] *= np.where(band, 78 / np.maximum(L, 1), 1.0)[..., None]
+Image.fromarray(im.round().astype(np.uint8), 'RGBA').save('watch-noband.png')
+PY
+echo watch-noband.png
diff --git a/design/mockup/prep.py b/design/mockup/prep.py
new file mode 100644
index 0000000..4ad72d9
--- /dev/null
+++ b/design/mockup/prep.py
@@ -0,0 +1,26 @@
+"""Builds watch.png: Apple's SE 3 (midnight) photo cut out with Apple's own mask, the screen left see-through.
+
+The photo was shot on white, so the soft pixels along the outside of the watch carry some of that white; they are
+un-mixed from it here, so the watch sits cleanly on any background. Around the screen the photo's own black is kept.
+Source: apple.com/apple-watch-se-3 ("So much to love"): love_hw (828x1348) and love_hw_mask; on the page the screen
+image (584x708) sits under the hardware at (120, 320) in these 2x pixels and shows through the mask's screen hole.
+"""
+from PIL import Image
+import numpy as np
+from scipy import ndimage
+
+hw = np.asarray(Image.open('apple-se3-midnight-hw.jpg').convert('RGB')).astype(np.float64)
+a = np.asarray(Image.open('apple-se3-midnight-mask.png').convert('RGBA'))[..., 3].astype(np.float64) / 255
+
+# the screen hole: the see-through region around the middle (and a few pixels round it, where the photo is black glass)
+lbl, _ = ndimage.label(a < 0.5)
+hole = ndimage.binary_dilation(lbl == lbl[674, 414], iterations=4)
+
+# un-mix the white the outer edge was shot on: C = a*F + (1-a)*255 -> F = (C - (1-a)*255) / a
+safe = np.maximum(a, 1e-3)[..., None]
+fg = np.clip((hw - (1 - a[..., None]) * 255) / safe, 0, 255)
+fg = np.where(hole[..., None], hw, fg)
+fg = np.where((a < 0.01)[..., None], 0, fg)
+
+Image.fromarray(np.dstack([fg, a * 255]).round().astype(np.uint8), 'RGBA').save('watch.png')
+print('watch.png', fg.shape[1], 'x', fg.shape[0])
diff --git a/design/mockup/stage.py b/design/mockup/stage.py
new file mode 100644
index 0000000..09a3b35
--- /dev/null
+++ b/design/mockup/stage.py
@@ -0,0 +1,190 @@
+#!/usr/bin/env python3
+"""Renders watches on a stage, each playing its own screen recording, with a moving camera, as a video.
+
+ python3 stage.py spec.json out.mp4
+
+The spec (JSON):
+ size [w, h] of the video (default [1080, 1350])
+ fps frames a second (default 60)
+ duration seconds
+ bg background colour (default "#ffffff")
+ watch the watch image (default watch-noband.png here): transparent around it and in its screen opening
+ shadow {"opacity": 0.2, "blur": 26, "dy": 34}: a soft shadow under each watch, in the watch image's pixels
+ watches each {"clip": video, "from": seconds into the clip (default 0), "keys": [{"t", "x", "y", "s", "r", "z"}]}
+ or, for cuts on its screen, "cuts": [{"t": when, "clip": video, "from": seconds}] instead of clip and from
+ x, y: where its centre is on the stage; s: its size (1 = the watch image's own pixels); r: its tilt in
+ degrees; z: in front of the lower ones. Between two keys it eases (slow out, slow in); clips loop.
+ camera keys [{"t", "x", "y", "zoom"}]: the stage point at the centre of the frame, and how much it's enlarged.
+ clock {"clip": video, "at": seconds}: every watch shows the clock from that frame of that clip (recordings made
+ minutes apart would otherwise show different times side by side)
+"""
+import json
+import math
+import os
+import subprocess
+import sys
+
+import numpy as np
+from PIL import Image, ImageFilter
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+spec = json.load(open(sys.argv[1]))
+OUT = sys.argv[2]
+W, H = spec.get('size', [1080, 1350])
+FPS = spec.get('fps', 60)
+DUR = float(spec['duration'])
+BG = spec.get('bg', '#ffffff')
+
+# the watch: cropped to itself; its screen opening; the soft shadow it casts
+watch = Image.open(spec.get('watch', os.path.join(HERE, 'watch-noband.png'))).convert('RGBA')
+watch = watch.crop(watch.getbbox())
+WW, WH = watch.size
+alpha = np.asarray(watch)[..., 3]
+from scipy import ndimage
+lbl, n = ndimage.label(alpha < 128)
+edge = set(np.unique(np.concatenate([lbl[0], lbl[-1], lbl[:, 0], lbl[:, -1]])))
+sizes = ndimage.sum(np.ones_like(lbl), lbl, range(1, n + 1))
+hole_id = [i + 1 for i in np.argsort(-sizes) if i + 1 not in edge][0]
+ys, xs = np.nonzero(lbl == hole_id)
+M = 4 # the screen runs a little under the bezel all round
+HX, HY, HW, HH = xs.min() - M, ys.min() - M, xs.max() - xs.min() + 1 + 2 * M, ys.max() - ys.min() + 1 + 2 * M
+sh = spec.get('shadow', {'opacity': 0.2, 'blur': 26, 'dy': 34})
+PAD = int(sh['blur'] * 3)
+sil = np.maximum(alpha, (lbl == hole_id) * 255).astype(np.uint8) # the whole watch, screen included
+shadow = Image.new('L', (WW + 2 * PAD, WH + 2 * PAD), 0)
+shadow.paste(Image.fromarray(sil), (PAD, PAD))
+shadow = shadow.filter(ImageFilter.GaussianBlur(sh['blur']))
+shadow = Image.merge('RGBA', [Image.new('L', shadow.size, 0)] * 3 + [shadow.point(lambda v: int(v * sh['opacity']))])
+
+
+def ease(u):
+ u = min(1.0, max(0.0, u))
+ return u * u * u * (u * (u * 6 - 15) + 10) # smootherstep: no jolt at either end
+
+
+def bezier(x1, y1, x2, y2):
+ """A CSS-style cubic-bezier timing curve: progress in time -> progress in value."""
+ def f(u):
+ if u <= 0: return 0.0
+ if u >= 1: return 1.0
+ lo, hi = 0.0, 1.0
+ for _ in range(40): # solve x(s) = u
+ m = (lo + hi) / 2
+ x = 3 * (1 - m) ** 2 * m * x1 + 3 * (1 - m) * m * m * x2 + m ** 3
+ lo, hi = (m, hi) if x < u else (lo, m)
+ m = (lo + hi) / 2
+ return 3 * (1 - m) ** 2 * m * y1 + 3 * (1 - m) * m * m * y2 + m ** 3
+ return f
+
+
+def at(keys, t, names):
+ """The keyed values at time t, eased between keys (a key's "ease": [x1, y1, x2, y2], a cubic bezier, shapes the
+ move that arrives at it; without one, smootherstep)."""
+ if t <= keys[0]['t']: k = keys[0]; return [k.get(n, d) for n, d in names]
+ if t >= keys[-1]['t']: k = keys[-1]; return [k.get(n, d) for n, d in names]
+ for a, b in zip(keys, keys[1:]):
+ if a['t'] <= t <= b['t']:
+ u = (t - a['t']) / max(1e-6, b['t'] - a['t'])
+ e = bezier(*b['ease'])(u) if 'ease' in b else ease(u)
+ return [a.get(n, d) + (b.get(n, d) - a.get(n, d)) * e for n, d in names]
+
+
+def fitted(path, at):
+ """One frame of a recording, fitted to the screen opening as the clips are."""
+ vf = f'scale={HW}:{HH}:force_original_aspect_ratio=decrease:flags=lanczos,pad={HW}:{HH}:(ow-iw)/2:(oh-ih)/2:color=black'
+ b = subprocess.check_output(['ffmpeg', '-loglevel', 'error', '-ss', str(at), '-i', path, '-frames:v', '1', '-vf', vf,
+ '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'])
+ return Image.frombytes('RGB', (HW, HH), b)
+
+
+# the clock: its box in a 396 x 484 screen recording, in the fitted frame
+CLOCK = None
+if 'clock' in spec:
+ k = min(HW / 396, HH / 484); ox, oy = (HW - 396 * k) / 2, (HH - 484 * k) / 2
+ box = tuple(round(v) for v in (ox + 296 * k, oy + 28 * k, ox + 382 * k, oy + 64 * k))
+ CLOCK = (fitted(spec['clock']['clip'], spec['clock'].get('at', 1)).crop(box), box[:2])
+
+
+class Clip:
+ """A screen recording read frame by frame at the video's rate, looping, fitted to the screen opening."""
+ def __init__(self, path, start):
+ dur = float(subprocess.check_output(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', path]))
+ self.path, self.start, self.dur = path, start, dur
+ self.w, self.h = HW, HH
+ self._open()
+ def _open(self):
+ vf = f'fps={FPS},scale={self.w}:{self.h}:force_original_aspect_ratio=decrease:flags=lanczos,pad={self.w}:{self.h}:(ow-iw)/2:(oh-ih)/2:color=black'
+ self.p = subprocess.Popen(['ffmpeg', '-loglevel', 'error', '-ss', str(self.start), '-i', self.path, '-vf', vf,
+ '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], stdout=subprocess.PIPE)
+ def next(self):
+ b = self.p.stdout.read(self.w * self.h * 3)
+ if len(b) < self.w * self.h * 3:
+ self.p.kill(); self.start = 0; self._open(); b = self.p.stdout.read(self.w * self.h * 3)
+ im = Image.frombytes('RGB', (self.w, self.h), b)
+ if CLOCK: im.paste(*CLOCK)
+ return im
+
+
+class Cuts:
+ """A watch's screen cutting from one recording to the next at set times (each opened when its turn comes)."""
+ def __init__(self, cuts):
+ self.cuts, self.i, self.clip = sorted(cuts, key=lambda c: c['t']), -1, None
+ def next(self, t):
+ while self.i + 1 < len(self.cuts) and t >= self.cuts[self.i + 1]['t'] - 1e-9:
+ if self.clip: self.clip.p.kill()
+ self.i += 1; c = self.cuts[self.i]; self.clip = Clip(c['clip'], c.get('from', 0))
+ return self.clip.next()
+ @property
+ def p(self): return self.clip.p
+
+
+watches = [dict(w, clip=Cuts(w['cuts']) if 'cuts' in w else Clip(w['clip'], w.get('from', 0))) for w in spec['watches']]
+cams = spec['camera']
+enc = subprocess.Popen(['ffmpeg', '-loglevel', 'error', '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', f'{W}x{H}', '-r', str(FPS),
+ '-i', '-', '-c:v', 'libx264', '-crf', '15', '-preset', 'slow', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', OUT],
+ stdin=subprocess.PIPE)
+
+
+def place(frame, img, cx, cy, S, rot):
+ """Draws img (its centre at its middle) onto frame at (cx, cy), scaled S, turned rot degrees: resampled once, only
+ over the area it covers; shrunk a lot, it's first reduced cleanly so it doesn't shimmer."""
+ if S < 0.7:
+ f = S / 0.85
+ img = img.resize((max(1, round(img.width * f)), max(1, round(img.height * f))), Image.LANCZOS); S /= f
+ w, h = img.size
+ r = math.radians(rot); c, s = math.cos(r), math.sin(r)
+ corners = [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h / 2)]
+ pts = [(cx + S * (c * x - s * y), cy + S * (s * x + c * y)) for x, y in corners]
+ x0, y0 = max(0, math.floor(min(p[0] for p in pts))), max(0, math.floor(min(p[1] for p in pts)))
+ x1, y1 = min(W, math.ceil(max(p[0] for p in pts))), min(H, math.ceil(max(p[1] for p in pts)))
+ if x1 <= x0 or y1 <= y0: return
+ # output (u, v) in the box -> image pixels: centre + R(-rot)(p - (cx, cy)) / S
+ a, b, d, e = c / S, s / S, -s / S, c / S
+ ox, oy = x0 - cx, y0 - cy
+ data = (a, b, w / 2 + a * ox + b * oy, d, e, h / 2 + d * ox + e * oy)
+ patch = img.transform((x1 - x0, y1 - y0), Image.AFFINE, data, resample=Image.BICUBIC)
+ frame.alpha_composite(patch, (x0, y0))
+
+
+frames = int(round(DUR * FPS))
+for i in range(frames):
+ t = i / FPS
+ camx, camy, zoom = at(cams, t, [('x', 0), ('y', 0), ('zoom', 1)])
+ frame = Image.new('RGBA', (W, H), BG)
+ states = []
+ for w in watches:
+ x, y, s, r, z = at(w['keys'], t, [('x', 0), ('y', 0), ('s', 1), ('r', 0), ('z', 0)])
+ states.append((z, x, y, s, r, w))
+ screens = [w['clip'].next(t) if isinstance(w['clip'], Cuts) else w['clip'].next() for w in watches] # every clip moves on
+ for (z, x, y, s, r, w), scr in sorted(zip(states, screens), key=lambda q: q[0][0]):
+ cx, cy, S = W / 2 + (x - camx) * zoom, H / 2 + (y - camy) * zoom, s * zoom
+ img = Image.new('RGBA', (WW, WH), (0, 0, 0, 0))
+ img.paste(scr, (HX, HY))
+ img.alpha_composite(watch)
+ place(frame, shadow, cx + math.sin(math.radians(r)) * 0, cy + sh['dy'] * S, S, r)
+ place(frame, img, cx, cy, S, r)
+ enc.stdin.write(frame.convert('RGB').tobytes())
+ if i % (FPS * 2) == 0: print(f'{t:.0f}s', end=' ', flush=True)
+enc.stdin.close(); enc.wait()
+for w in watches: w['clip'].p.kill()
+print('\n' + OUT)
diff --git a/design/mockup/watch-noband.png b/design/mockup/watch-noband.png
new file mode 100644
index 0000000..984bf38
Binary files /dev/null and b/design/mockup/watch-noband.png differ
diff --git a/design/mockup/watch.png b/design/mockup/watch.png
new file mode 100644
index 0000000..4e59b97
Binary files /dev/null and b/design/mockup/watch.png differ
diff --git a/design/noodle/animate.py b/design/noodle/animate.py
new file mode 100644
index 0000000..f3faa54
--- /dev/null
+++ b/design/noodle/animate.py
@@ -0,0 +1,617 @@
+"""Noodle's animation: every clip the Lab and the watch play.
+
+Headless (recommended; renders in the background):
+ Blender -b design/noodle/noodle.blend -P design/noodle/animate.py -- [clip ...] [--step N] [--out DIR] [--samples N]
+From Blender's Python console:
+ import sys; sys.argv = ['x', '--', 'idle']; exec(open('design/noodle/animate.py').read())
+
+Each clip is keyed acting: a list of poses at times (seconds) with an ease per segment, on top of which run
+ breathing, blinks, a hair spring that lags behind the head (follow-through on every move), and a hair
+ "jiggle" spring on vertical moves. 24 fps, rendered at the watch's 396 x 484 at 128 samples.
+Each state is a pool: a calm rest loop and several beats that start and end on the same rest pose, held at both ends
+ so the hair settles. The player chains them at random, so a long state never repeats visibly.
+Writes renders/anim/<clip>_NNN.png and renders/clips.json: per frame, where the hair top, the face and the glass
+ contact are on the watch screen (198 x 242 pt), plus named events (a card lands, a knock, the apex of a jump),
+ so the Lab can put UI on its head, fog the glass where it presses, and land tool calls on it in sync.
+Then: tools/noodle-watch.sh makes the watch's clips from them.
+"""
+import bpy, math, json, os, sys, time
+from bpy_extras.object_utils import world_to_camera_view
+
+FPS = 24
+D = bpy.data
+sc = bpy.context.scene
+sc.camera = D.objects['Cam']
+
+# headless Blender doesn't always pick up the GPU from preferences: ask for Metal (or CUDA/OptiX) explicitly
+try:
+ cp = bpy.context.preferences.addons['cycles'].preferences
+ for kind in ('METAL', 'OPTIX', 'CUDA', 'HIP'):
+ try:
+ cp.compute_device_type = kind; cp.get_devices()
+ if any(d.type != 'CPU' for d in cp.devices): break
+ except TypeError: continue
+ for d in cp.devices: d.use = d.type != 'CPU'
+ sc.cycles.device = 'GPU'
+ print('cycles devices:', [(d.name, d.use) for d in cp.devices], flush=True)
+except Exception as e:
+ print('GPU setup failed, rendering on CPU:', e, flush=True)
+
+# ---------- the rig (noodle_rig.py, stored in the .blend) ----------
+G = {'__name__': 'noodle_rig'}
+exec(compile(D.texts['noodle_rig.py'].as_string(), 'noodle_rig.py', 'exec'), G)
+pose, shot = G['pose'], G['shot']
+arm = D.objects['Rig']
+HELPERS = [D.objects[f'Helper{i}'] for i in range(3)]
+CORES = [D.objects.get(f'CoreH{i}') for i in range(3)]
+for o in HELPERS + CORES:
+ if o and 'base_z' not in o: o['base_z'] = o.location.z
+HELP_ROT = [o.rotation_euler.z for o in HELPERS]
+
+# ---------- channels ----------
+V3 = ['base', 'mid', 'neck', 'head', 'hairtilt']
+V2 = ['lidsL', 'lidsR', 'gazeL', 'gazeR']
+V1 = ['stretch', 'rise', 'turn', 'toward', 'pupilL', 'pupilR', 'poof', 'shiftx', 'h0', 'h1', 'h2']
+NEUTRAL = dict(base=(0, 0, 0), mid=(0, 0, 0), neck=(0, 0, 0), head=(0, 0, 0), hairtilt=(0, 0, 0), lidsL=(-10, 80), lidsR=(-6, 80),
+ gazeL=(6, -4), gazeR=(6, -4), stretch=1.0, rise=0.0, turn=0.0, toward=0.0, pupilL=19, pupilR=19, poof=1.0, shiftx=0.0,
+ h0=-3.0, h1=-3.0, h2=-3.0)
+CLOSED = (14, 6)
+
+
+def expand(d):
+ """shorthands: lids, gaze, pupil set both sides."""
+ d = dict(d)
+ if 'lids' in d: v = d.pop('lids'); d.setdefault('lidsL', v); d.setdefault('lidsR', v)
+ if 'gaze' in d: v = d.pop('gaze'); d.setdefault('gazeL', v); d.setdefault('gazeR', v)
+ if 'pupil' in d: v = d.pop('pupil'); d.setdefault('pupilL', v); d.setdefault('pupilR', v)
+ return d
+
+
+# ---------- poses the clips are built from ----------
+DEAD = expand(dict(mid=(2, -3, 0), neck=(3, -2, 0), head=(0, 0, 0), lidsL=(-10, 80), lidsR=(-6, 80), gaze=(6, -4), pupil=19))
+LISTEN = expand(dict(mid=(6, 0, 0), neck=(8, 0, 0), head=(4, 0, 0), stretch=1.1, toward=.8, lids=(-85, 85), gaze=(0, 0), pupil=24, poof=1.06))
+THINK = expand(dict(mid=(0, 8, 0), neck=(-4, 12, 0), head=(-6, 10, 0), lidsL=(-55, 80), lidsR=(-2, 80), gaze=(22, 24), pupil=17))
+# working sits lower, so the tool calls that land on its head stay clear of the watch's clock and status row
+WORK = expand(dict(rise=-.55, mid=(6, 0, 0), neck=(10, 0, 0), head=(8, 0, 0), lids=(-22, 40), gaze=(-8, -26), pupil=17))
+RUN = expand(dict(rise=-.55, mid=(4, 0, 0), neck=(6, 0, 0), head=(4, 0, 0), toward=.5, lids=(-60, 70), gaze=(0, -24), pupil=16))
+SEARCH = expand(dict(rise=-.55, mid=(2, 0, 0), neck=(4, 0, 0), head=(0, 0, 0), lids=(-50, 75), gaze=(0, -6), pupil=18))
+SPEAK = expand(dict(mid=(0, -4, 0), neck=(-2, -4, 0), head=(0, 6, 0), stretch=.98, toward=.3, lidsL=(-34, 80), lidsR=(-30, 80), gaze=(0, 2), pupil=21))
+DONE = expand(dict(stretch=1.16, mid=(-4, 0, 0), neck=(0, 0, 0), head=(0, 0, 0), lids=(-80, 22), gaze=(0, 10), poof=1.18))
+NEEDS = expand(dict(toward=3.0, rise=-1.0, mid=(0, 0, 0), neck=(0, 0, 0), head=(0, 0, 0), lids=(-88, 88), gaze=(0, 4), pupil=7))
+APPR = expand(dict(rise=-1.25, mid=(-2, 0, 0), neck=(-4, 0, 0), head=(-6, 0, 0), lids=(-80, 85), gaze=(0, 34), pupil=18))
+BLOCK = expand(dict(mid=(8, 0, 6), neck=(12, 6, 6), head=(6, 8, 0), lidsL=(6, 80), lidsR=(12, 80), gazeL=(4, -34), gazeR=(0, -34), poof=.95))
+SQUASH = expand(dict(stretch=.74, rise=-.12, poof=.82, mid=(0, 0, 0), neck=(0, 0, 0), head=(0, 0, 0), lids=(-88, 88), gaze=(0, 0), pupil=9))
+WAIT = expand(dict(mid=(2, -3, 0), neck=(3, -2, 0), head=(0, 0, 0), lids=(0, 70), gaze=(4, -6), pupil=18))
+SLEEP = expand(dict(rise=-2.7, mid=(4, 0, 0), neck=(4, 0, 0), lids=CLOSED, pupil=19))
+SUBS = expand(dict(shiftx=.25, toward=-.8, rise=.15, mid=(2, -3, 0), neck=(3, -2, 0), lids=(-20, 72), gaze=(-26, -10), pupil=19))
+
+
+# ---------- easing ----------
+def ease(name, k):
+ k = max(0.0, min(1.0, k))
+ if name == 'lin': return k
+ if name == 'in': return k * k
+ if name == 'in3': return k * k * k
+ if name == 'out': return 1 - (1 - k) ** 2
+ if name == 'snap': return 1 - (1 - k) ** 4 # saccades and flinches
+ if name == 'back': c = 1.9; return 1 + (c + 1) * (k - 1) ** 3 + c * (k - 1) ** 2 # overshoot, then settle
+ if name == 'hold': return 0.0 if k < 1 else 1.0
+ return k * k * k * (k * (6 * k - 15) + 10) # 'io': minimum-jerk in-out
+
+
+class K:
+ """A key: a pose at time t, reached with an ease. base= fills every channel (so the key is a full pose);
+ without base, only the channels given are keyed. K(t) alone holds every channel at its last value."""
+ def __init__(self, t, ease='io', base=None, **pose):
+ self.t, self.ease = t, ease
+ full = {k: v for k, v in NEUTRAL.items() if k not in ('h0', 'h1', 'h2')} if base is not None else {}
+ full.update(base or {}); full.update(expand(pose))
+ self.pose, self.hold = full, base is None and not pose
+
+
+class Clip:
+ """keys: list of K, interpolated per channel (like animation curves).
+ role: 'rest' (a calm loop), 'beat' (a one-shot that starts and ends on the state's rest pose), 'enter', 'react',
+ 'once', 'scrub'. The player chains rest and beats at random, so a long state never visibly repeats.
+ breath: (amplitude, period), sway: (roll, turn, period); periods are fitted to divide the duration, so every
+ segment of a state starts and ends at the same phase. blinks: times. events: name -> time or [times].
+ scrub: render n frames from a parameter 0..1 (fn(k) -> pose)."""
+ def __init__(self, name, dur, keys=None, loop=False, breath=(.012, 4.0), blinks=(), events=None, sway=None,
+ helpers=False, scrub=None, n=None, hair=1.0, extra=None, role='once', state=None):
+ self.name, self.dur, self.loop, self.blinks = name, dur, loop, list(blinks)
+ fit = lambda per: dur / max(1, round(dur / per)) if dur else per
+ self.breath = (breath[0], fit(breath[1])) if breath and breath[0] else (0, 1)
+ self.sway = (sway[0], sway[1], fit(sway[2])) if sway else None
+ self.events, self.helpers, self.scrub, self.hair, self.extra = events or {}, helpers, scrub, hair, extra
+ self.role, self.state = role, state
+ self.n = n if n else max(1, round(dur * FPS))
+ self.chan = {c: [] for c in NEUTRAL}
+ for k in sorted(keys or [], key=lambda k: k.t):
+ if k.hold:
+ for c, ks in self.chan.items():
+ if ks: ks.append((k.t, ks[-1][1], 'io'))
+ else:
+ for c, v in k.pose.items(): self.chan[c].append((k.t, v, k.ease))
+
+ def primary(self, t):
+ out = {}
+ for c, ks in self.chan.items():
+ if not ks: out[c] = NEUTRAL[c]; continue
+ if t <= ks[0][0]: out[c] = ks[0][1]; continue
+ if t >= ks[-1][0]: out[c] = ks[-1][1]; continue
+ for (t0, a, _), (t1, b, e) in zip(ks, ks[1:]):
+ if t0 <= t <= t1:
+ k = ease(e, (t - t0) / (t1 - t0) if t1 > t0 else 1)
+ out[c] = tuple(x + (y - x) * k for x, y in zip(a, b)) if isinstance(a, tuple) else a + (b - a) * k
+ break
+ return out
+
+
+def blink_amount(t, times):
+ a = 0.0
+ for b in times:
+ d = t - b
+ if 0 <= d < .05: a = max(a, d / .05)
+ elif .05 <= d < .09: a = 1.0
+ elif .09 <= d < .2: a = max(a, 1 - (d - .09) / .11)
+ return a
+
+
+def overlay(clip, t, p):
+ p = dict(p)
+ amp, per = clip.breath
+ if amp:
+ w = math.sin(2 * math.pi * t / per)
+ p['stretch'] *= 1 + amp * w
+ p['poof'] *= 1 + amp * .6 * math.sin(2 * math.pi * t / per)
+ if clip.sway:
+ roll, turn, per2 = clip.sway
+ s = math.sin(2 * math.pi * t / per2)
+ p['mid'] = (p['mid'][0], p['mid'][1] + roll * s, p['mid'][2])
+ p['turn'] += turn * .5 * math.sin(4 * math.pi * t / per2)
+ b = blink_amount(t, clip.blinks)
+ if b:
+ for side in ('lidsL', 'lidsR'):
+ u, l = p[side]
+ p[side] = (u + (CLOSED[0] - u) * b, l + (CLOSED[1] - l) * b)
+ if clip.extra: p = clip.extra(t, p)
+ return p
+
+
+# ---------- secondary motion: the hair lags behind the head, and jiggles on vertical moves ----------
+def head_signal(p):
+ pitch = p['mid'][0] + p['neck'][0] + p['head'][0]
+ roll = p['mid'][1] + p['neck'][1] + p['head'][1]
+ yaw = p['turn'] + p['mid'][2] + p['neck'][2] + p['head'][2]
+ vert = p['rise'] * 1.0 + (p['stretch'] - 1) * 3.2
+ return [pitch, roll, yaw, vert]
+
+
+def springs(clip, poses):
+ """poses: primary+overlay pose per frame. Returns the same poses with hair follow-through added."""
+ n = len(poses)
+ if n < 2 or clip.scrub: return poses
+ sig = [head_signal(p) for p in poses]
+ W = [11.0, 11.0, 9.0, 13.0]; Z = [.32, .32, .4, .28] # ω, ζ per axis: bouncy hair
+ x = list(sig[0]); v = [0.0] * 4
+ sub = 8; dt = 1 / FPS / sub
+ passes = 3 if clip.loop else 1
+ out = None
+ for ps in range(passes):
+ rec = []
+ for i in range(n):
+ j = (i + 1) % n if clip.loop else min(i + 1, n - 1)
+ for s in range(sub):
+ k = s / sub
+ tgt = [a + (b - a) * k for a, b in zip(sig[i], sig[j])]
+ for a in range(4):
+ v[a] += (W[a] ** 2 * (tgt[a] - x[a]) - 2 * Z[a] * W[a] * v[a]) * dt
+ x[a] += v[a] * dt
+ rec.append(list(x))
+ out = rec
+ res = []
+ g = clip.hair
+ for i, p in enumerate(poses):
+ lag = [h - s for h, s in zip(out[i], sig[i])]
+ q = dict(p)
+ ht = q['hairtilt']
+ q['hairtilt'] = (ht[0] + lag[0] * 1.3 * g + lag[3] * -6 * g, ht[1] + lag[1] * 1.3 * g, ht[2] + lag[2] * .9 * g)
+ q['poof'] = q['poof'] * (1 + max(-.12, min(.12, lag[3] * .35 * g)))
+ res.append(q)
+ return res
+
+
+# ---------- applying a pose, and where things land on screen ----------
+def apply(p, helpers):
+ pose(base=p['base'], mid=p['mid'], neck=p['neck'], head=p['head'], stretch=p['stretch'], rise=p['rise'], turn=p['turn'],
+ toward=p['toward'], lidsL=p['lidsL'], lidsR=p['lidsR'], gazeL=p['gazeL'], gazeR=p['gazeR'],
+ pupilL=p['pupilL'], pupilR=p['pupilR'], poof=p['poof'], hairtilt=p['hairtilt'])
+ arm.location.x += p['shiftx']
+ for i, (h, c) in enumerate(zip(HELPERS, CORES)):
+ z = p[f'h{i}']
+ vis = helpers and z > -2.9
+ h.hide_render = not vis; h.location.z = h['base_z'] + z
+ h.rotation_euler.z = HELP_ROT[i] + p.get(f'r{i}', 0)
+ if c: c.hide_render = not vis; c.location.z = c['base_z'] + z
+ bpy.context.view_layer.update()
+
+
+def scr(co):
+ v = world_to_camera_view(sc, sc.camera, co)
+ return round(v.x * 198, 1), round((1 - v.y) * 242, 1)
+
+
+def anchors(p):
+ dg = bpy.context.evaluated_depsgraph_get()
+ hc = D.objects['HairCloud'].evaluated_get(dg)
+ me = hc.to_mesh(); mw = hc.matrix_world
+ pts = [scr(mw @ v.co) for v in me.vertices]
+ hc.to_mesh_clear()
+ ymin = min(y for _, y in pts)
+ xs = [x for x, y in pts if y < ymin + 4]
+ hx, hy = sum(xs) / len(xs), ymin - 4 # the fur reaches about 4 pt past the cloud
+ (lx, ly), (rx, ry) = scr(D.objects['EyeL'].matrix_world.translation), scr(D.objects['EyeR'].matrix_world.translation)
+ roll = math.degrees(math.atan2(ly - ry, lx - rx))
+ return [round(hx, 1), round(hy, 1), round((lx + rx) / 2, 1), round((ly + ry) / 2, 1), round(roll, 1),
+ round(p['toward'] / 3, 2), round(p['rise'], 2)]
+
+
+# ---------- the clips ----------
+LISTEN = expand(dict(mid=(4, 0, 0), neck=(7, 0, 0), head=(4, 0, 0), stretch=1.05, toward=.25, lids=(-82, 85), gaze=(0, 0), pupil=23, poof=1.04))
+SPEAK = expand(dict(mid=(0, -4, 0), neck=(-2, -4, 0), head=(0, 6, 0), stretch=.99, toward=.1, lidsL=(-34, 80), lidsR=(-30, 80), gaze=(0, 2), pupil=21))
+# working sits lower, so the tool calls that land on its head stay clear of the watch's clock and status row
+WORK = expand(dict(rise=-.45, mid=(6, 0, 0), neck=(10, 0, 0), head=(8, 0, 0), lids=(-22, 40), gaze=(-8, -26), pupil=17))
+NEEDS = expand(dict(toward=3.2, rise=-1.0, mid=(0, 0, 0), neck=(0, 0, 0), head=(0, 0, 0), lids=(-88, 88), gaze=(0, 4), pupil=7))
+
+# how much each state breathes, and how often it plays a beat instead of its rest loop (the player reads this)
+BREATH = dict(idle=.016, listening=.012, thinking=.012, working=.008, subagents=.01, speaking=0, done=.012, needs=.006,
+ approval=.01, blocked=.012, compacting=0, waiting=.012, sleep=.03)
+BEAT_CHANCE = dict(idle=.45, listening=.5, thinking=.6, working=.35, subagents=.45, speaking=.85, done=.5, needs=.35,
+ approval=.3, blocked=.35, waiting=.4, sleep=.15)
+
+
+def build():
+ C = {}
+ def add(c): C[c.name] = c
+
+ def seg(name, state, role, dur, R, keys=(), hold_in=.4, hold_out=.6, **kw):
+ """a rest loop or a beat: held on the rest pose R at both ends, so any segment can follow any other"""
+ ks = [K(0, base=R), K(hold_in, base=R), *keys, K(dur - hold_out, base=R), K(dur, base=R)]
+ kw.setdefault('breath', (BREATH.get(state, .012), 4.0))
+ add(Clip(name, dur, ks, loop=(role == 'rest'), role=role, state=state, **kw))
+
+ def enter(name, state, dur, keys, **kw):
+ kw.setdefault('breath', (0, 1))
+ add(Clip(name, dur, keys, role='enter', state=state, **kw))
+
+ # ======================= idle =======================
+ seg('idle_rest', 'idle', 'rest', 6.0, DEAD, [
+ K(1.3, gaze=(12, -6), neck=(3, -5, 0), head=(0, -3, 0)), K(2.6, gaze=(12, -6)), K(2.75, 'snap', gaze=(-14, -3)),
+ K(4.0, gaze=(-14, -3), mid=(2, 1, 0), neck=(3, 3, 0), head=(0, 2, 0)), K(4.15, 'snap', gaze=(6, -4))],
+ blinks=[.9, 3.4], sway=(2.5, 3, 6.0))
+ seg('idle_look', 'idle', 'beat', 4.0, DEAD, [
+ K(.55, 'snap', gaze=(-32, -2)), K(1.1, 'back', turn=-24, mid=(2, -8, 0), neck=(3, -8, 0), lids=(-50, 84), stretch=1.04),
+ K(1.9, gaze=(-32, 0)), K(2.05, 'snap', gaze=(0, 0)), K(2.5, turn=-8, lidsL=(2, 78), lidsR=(6, 78), stretch=1.0, toward=.4), K(2.9)],
+ blinks=[3.0])
+ shake = [K(.55, stretch=.9, lids=(10, 40), mid=(2, 0, 0), neck=(3, 0, 0))]
+ for i, a in enumerate([18, -18, 16, -15, 11, -7, 3, 0]):
+ shake.append(K(.65 + i * .12, 'io', neck=(3, a, 0), head=(0, a * .8, 0), mid=(2, a * .5, 0), turn=a * .5, lids=(8, 30)))
+ shake += [K(1.75, 'back', stretch=1.08, lids=(-62, 85), poof=1.12), K(2.3)]
+ seg('idle_shake', 'idle', 'beat', 3.2, DEAD, shake, blinks=[2.4], hair=1.7)
+ seg('idle_sideeye', 'idle', 'beat', 3.6, DEAD, [
+ K(1.1, 'io', turn=16, mid=(2, 5, 0), neck=(3, 6, 0), gaze=(-24, -2), lidsL=(10, 66), lidsR=(14, 66)),
+ K(2.2, turn=16, gaze=(-24, -2)), K(2.35, 'snap', gaze=(-26, -2)), K(2.7)], blinks=[1.85])
+ seg('idle_yawn', 'idle', 'beat', 3.6, DEAD, [
+ K(.85, stretch=.92, mid=(4, 0, 0)), K(1.55, stretch=1.24, rise=.18, lids=(10, 12), head=(-14, 0, 0), neck=(-6, 0, 0), gaze=(0, 20), poof=1.14),
+ K(2.0), K(2.45, 'back', stretch=.95, rise=0, poof=.98, lids=(-4, 70), head=(2, 0, 0), neck=(4, 0, 0))], breath=(0, 1))
+ seg('idle_hum', 'idle', 'beat', 3.6, DEAD, [
+ K(.8, mid=(2, 8, 0), neck=(3, 7, 0), lids=(-30, 55), gaze=(0, 0)), K(1.3, mid=(2, -8, 0), neck=(3, -7, 0)),
+ K(1.8, mid=(2, 8, 0), neck=(3, 7, 0)), K(2.3, mid=(2, -6, 0), neck=(3, -5, 0)), K(2.7, mid=(2, -3, 0), neck=(3, -2, 0))], hair=1.3)
+ seg('idle_peek', 'idle', 'beat', 3.6, DEAD, [
+ K(1.0, gaze=(0, -36), head=(12, 0, 0), neck=(10, 0, 0), lids=(-40, 70), toward=.3), K(1.9, gaze=(8, -36)),
+ K(2.2, 'snap', gaze=(0, 0), lids=(-70, 82), head=(0, 0, 0), neck=(3, -2, 0), toward=0), K(2.8)])
+
+ # ======================= listening: attentive, leaning a little toward you =======================
+ enter('listening_in', 'listening', .8, [K(0, base=DEAD), K(.22, stretch=.92, mid=(4, 0, 0), lids=(0, 60)),
+ K(.52, 'back', base=LISTEN, stretch=1.09, poof=1.08), K(.8, base=LISTEN)], hair=1.3)
+ seg('listening_rest', 'listening', 'rest', 4.8, LISTEN, [
+ K(1.5, neck=(11, 0, 0), head=(6, 0, 0)), K(2.1, neck=(7, 0, 0), head=(4, 0, 0)), K(2.8, gaze=(3, 1)), K(3.7, gaze=(0, 0))],
+ blinks=[1.15, 3.95])
+ seg('listen_nod', 'listening', 'beat', 2.4, LISTEN, [
+ K(.75, 'out', neck=(17, 0, 0), head=(10, 0, 0), stretch=1.02), K(1.05, neck=(7, 0, 0), head=(4, 0, 0), stretch=1.05),
+ K(1.35, 'out', neck=(15, 0, 0), head=(9, 0, 0)), K(1.7, neck=(7, 0, 0), head=(4, 0, 0))])
+ seg('listen_tilt_l', 'listening', 'beat', 3.0, LISTEN, [
+ K(1.0, mid=(4, -8, 0), neck=(7, -12, 0), head=(4, -10, 0), gaze=(-6, 4), pupil=26, lids=(-86, 86)), K(2.0)], blinks=[1.6])
+ seg('listen_tilt_r', 'listening', 'beat', 3.0, LISTEN, [
+ K(1.0, mid=(4, 8, 0), neck=(7, 12, 0), head=(4, 10, 0), gaze=(6, 4), pupil=26, lids=(-86, 86)), K(2.0)])
+ seg('listen_lean', 'listening', 'beat', 3.2, LISTEN, [
+ K(1.1, toward=.9, lids=(-40, 70), pupil=19, neck=(11, 0, 0)), K(2.2)], blinks=[1.7])
+ seg('listen_oh', 'listening', 'beat', 2.6, LISTEN, [
+ K(.65, 'snap', lids=(-88, 88), pupil=28, stretch=1.1, poof=1.12, head=(-4, 0, 0)), K(1.4)], hair=1.3)
+ seg('listen_mhm', 'listening', 'beat', 2.8, LISTEN, [
+ K(1.05, neck=(19, 0, 0), head=(12, 0, 0), lids=(-26, 58), stretch=1.0), K(1.6), K(2.0, neck=(7, 0, 0), head=(4, 0, 0), lids=(-82, 85))])
+ seg('listen_blink', 'listening', 'beat', 1.6, LISTEN, [], blinks=[.55, .8])
+
+ # ======================= thinking: most of the time; a lot of small, different acting =======================
+ enter('thinking_in', 'thinking', 1.0, [K(0, base=DEAD), K(.45, gaze=(10, 18), lidsL=(-35, 80), mid=(0, 4, 0)), K(1.0, base=THINK)])
+ seg('thinking_rest', 'thinking', 'rest', 5.0, THINK, [
+ K(1.4, gaze=(14, 28)), K(2.4, gaze=(18, 21), head=(-6, 12, 0)), K(3.4, gaze=(25, 26), head=(-6, 10, 0)), K(4.0)], blinks=[2.9])
+ seg('think_swap', 'thinking', 'beat', 3.8, THINK, [
+ K(1.0, gaze=(-24, 26), mid=(0, -10, 0), neck=(-4, -14, 0), head=(-8, -10, 0), lidsL=(-2, 80), lidsR=(-55, 80)), K(2.4)], blinks=[1.9], hair=1.2)
+ seg('think_squint', 'thinking', 'beat', 3.4, THINK, [
+ K(.95, gaze=(0, -14), lids=(-24, 50), mid=(6, 0, 0), neck=(10, 0, 0), head=(8, 0, 0), toward=.35, stretch=.95), K(2.1),
+ K(2.3, gaze=(4, -14))])
+ seg('think_hm', 'thinking', 'beat', 2.8, THINK, [
+ K(.75, stretch=.95), K(1.0, 'back', gaze=(22, 26), lidsR=(-82, 84), lidsL=(-35, 80), stretch=1.08, poof=1.07, head=(-10, 10, 0)), K(1.6)], hair=1.3)
+ count = [K(.6, gaze=(18, 30))]
+ for i, t in enumerate([.8, 1.15, 1.5, 1.85]):
+ count += [K(t, 'out', neck=(-4 + 12, 12, 0), head=(-6 + 9, 10, 0), stretch=.98), K(t + .17, neck=(-4, 12, 0), head=(-6, 10, 0), stretch=1.0)]
+ count += [K(2.4, gaze=(22, 24))]
+ seg('think_count', 'thinking', 'beat', 3.4, THINK, count)
+ seg('think_sigh', 'thinking', 'beat', 3.4, THINK, [
+ K(1.15, stretch=1.08, poof=1.06, head=(-8, 10, 0), lids=(-40, 80)), K(2.05, stretch=.9, poof=.95, lids=(-8, 70), mid=(6, 6, 0), gaze=(10, 6)),
+ K(2.5)], hair=1.2)
+ roll = [K(.6, gaze=(-10, 30)), K(1.0, gaze=(-26, 14)), K(1.4, gaze=(-20, -10)), K(1.8, gaze=(0, -18)), K(2.2, gaze=(20, -8)), K(2.6, gaze=(26, 14))]
+ seg('think_roll', 'thinking', 'beat', 3.6, THINK, roll + [K(2.75, lidsL=(-20, 80), lidsR=(-20, 80))])
+ seg('think_down', 'thinking', 'beat', 3.4, THINK, [
+ K(1.0, gaze=(0, -34), head=(12, 0, 0), neck=(10, 0, 0), mid=(4, 0, 0), lids=(-30, 60)), K(1.4, gaze=(10, -34)), K(1.8, gaze=(-8, -34)),
+ K(2.3, gaze=(4, -34))])
+
+ # ======================= working: a calm loop per kind of tool call, plus beats =======================
+ enter('working_in', 'working', .8, [K(0, base=DEAD), K(.25, stretch=.92, lids=(-30, 50)), K(.8, 'back', base=WORK)], hair=1.2)
+ read = []
+ for i in range(3):
+ t0 = .55 + i * 1.5
+ read += [K(t0, 'snap', gaze=(-22, -18 - 4 * i), turn=-4), K(t0 + 1.25, 'lin', gaze=(20, -18 - 4 * i), turn=4, neck=(10 + i, 0, 0))]
+ seg('work_read', 'working', 'rest', 6.0, WORK, read, blinks=[2.0, 3.45])
+ edit = []
+ for i, t in enumerate([.6, 1.0, 1.4, 1.8, 2.2, 3.3, 3.7, 4.1]):
+ edit += [K(t, 'out', neck=(13, 0, 0), head=(10, 0, 0), stretch=.98), K(t + .2, neck=(10, 0, 0), head=(8, 0, 0), stretch=1.0)]
+ edit += [K(2.5, gaze=(10, -24)), K(3.05, gaze=(-8, -26))]
+ seg('work_edit', 'working', 'rest', 5.2, WORK, sorted(edit, key=lambda k: k.t), blinks=[2.75])
+ run = [K(.5, gaze=(0, -10))]
+ for i, t in enumerate([1.0, 1.9, 2.8]):
+ run += [K(t, 'lin', gaze=(2, -26 - 2 * i)), K(t + .15, 'snap', gaze=(-2, -10 - 2 * i))]
+ run += [K(3.6, toward=.6, lids=(-30, 55), neck=(13, 0, 0)), K(4.6, toward=.6), K(4.9, 'back', lids=(-70, 75), toward=0)]
+ seg('work_run', 'working', 'rest', 6.0, WORK, run, blinks=[1.5])
+ seg('work_search', 'working', 'rest', 6.0, WORK, [
+ K(.6, 'snap', gaze=(-32, -8)), K(1.3, turn=-16, mid=(6, -6, 0)), K(2.4), K(2.6, 'snap', gaze=(32, -8)), K(3.3, turn=16, mid=(6, 6, 0)),
+ K(4.3), K(4.5, 'snap', gaze=(-8, -26), turn=0, mid=(6, 0, 0))], blinks=[2.0])
+ seg('work_nod', 'working', 'beat', 2.4, WORK, [
+ K(.75, neck=(16, 0, 0), head=(12, 0, 0), lids=(-30, 60)), K(1.05, neck=(8, 0, 0), head=(6, 0, 0)), K(1.35, neck=(14, 0, 0)), K(1.7, lids=(-22, 40), neck=(10, 0, 0))])
+ seg('work_squint', 'working', 'beat', 3.0, WORK, [K(1.0, toward=.8, lids=(-14, 34), neck=(14, 0, 0), gaze=(0, -24)), K(2.1)])
+ seg('work_ponder', 'working', 'beat', 3.2, WORK, [
+ K(.9, gaze=(20, 20), lidsR=(-60, 80), head=(-6, 8, 0), neck=(4, 6, 0)), K(1.8), K(2.1, 'snap', gaze=(-8, -26), lids=(-22, 40))])
+ seg('work_blink', 'working', 'beat', 1.6, WORK, [], blinks=[.55, .8])
+ add(Clip('bump', 1.0, [K(0, base=WORK), K(.18, base=WORK, gaze=(0, 24), lids=(-75, 75), neck=(4, 0, 0), head=(0, 0, 0)),
+ K(.3, 'out', stretch=.86, rise=-.52, neck=(16, 0, 0), head=(8, 0, 0), lids=(6, 30), poof=.9),
+ K(.45, 'out', stretch=1.12, rise=-.32, neck=(0, 0, 0), head=(-6, 0, 0), lids=(-75, 70), gaze=(14, 26), poof=1.08),
+ K(.65, stretch=.98, rise=-.45), K(1.0, base=WORK)], breath=(0, 1), events={'land': .24, 'launch': .42}, hair=1.4, role='react', state='working'))
+ add(Clip('oops', 1.1, [K(0, base=WORK), K(.12, 'snap', stretch=.86, lids=(10, 30), neck=(18, 0, 0), mid=(6, -10, 0), turn=-10),
+ K(.4, lids=(-75, 80), gaze=(0, -30), stretch=1.02, mid=(6, 0, 0), turn=0), K(.62, 'snap', gaze=(8, 0), lids=(-30, 75), toward=.3), K(1.1, base=WORK)],
+ breath=(0, 1), hair=1.3, role='react', state='working'))
+ add(Clip('interrupted', 1.2, [K(0, base=WORK), K(.08, 'snap', stretch=1.12, lids=(-88, 88), pupil=7, toward=-.3, neck=(-2, 0, 0), head=(-6, 0, 0)), K(.55),
+ K(.7, 'snap', gaze=(0, 0), lids=(-30, 80)), K(1.2, base=DEAD)], breath=(0, 1), hair=1.3, role='react', state='working'))
+
+ # ======================= subagents: three small Noodles copy whatever it does =======================
+ UP = dict(h0=0.0, h1=0.0, h2=0.0)
+ SUBR = {**SUBS, **UP}
+ def bob(t, p):
+ p = dict(p)
+ for i, ph in enumerate((0, .33, .66)):
+ p[f'h{i}'] = p[f'h{i}'] + .07 * math.sin(2 * math.pi * (t / 1.2 + ph))
+ p[f'r{i}'] = math.radians(8) * math.sin(2 * math.pi * (t / 2.4 + ph))
+ return p
+ def ramp_bob(t, p): # the bob fades in once the minis are up, and is in phase with the rest loop at the end
+ q = bob(t, p); k = max(0.0, min(1.0, (t - 1.2) / 1.0)); k = k * k * (3 - 2 * k)
+ for i in range(3): q[f'h{i}'] = p[f'h{i}'] + (q[f'h{i}'] - p[f'h{i}']) * k; q[f'r{i}'] = q[f'r{i}'] * k
+ return q
+ sub_in = [K(0, base=DEAD), K(.4, base=SUBS, gaze=(-20, -6))]
+ for i, t in enumerate([.2, .6, 1.0]):
+ sub_in += [K(0, **{f'h{i}': -3.0}), K(t, **{f'h{i}': -3.0}), K(t + .35, 'back', **{f'h{i}': 0.0})]
+ sub_in += [K(.55, 'snap', gaze=(-28, -14)), K(.95, 'snap', gaze=(24, -14)), K(1.35, 'snap', gaze=(0, -24), lids=(-85, 88), stretch=1.08),
+ K(1.7, gaze=(0, -24), stretch=1.0), K(2.4, base=SUBR)]
+ add(Clip('subagents_in', 2.4, sub_in, helpers=True, breath=(0, 1), role='enter', state='subagents', extra=lambda t, p: ramp_bob(t, p)))
+ seg('subagents_rest', 'subagents', 'rest', 4.8, SUBR, [
+ K(1.0, gaze=(-28, -12), turn=-8), K(1.7), K(2.0, gaze=(-4, -22), turn=0), K(2.8), K(3.1, gaze=(22, -14), turn=8), K(3.7)],
+ helpers=True, blinks=[1.8, 3.9], extra=bob)
+ seg('subagents_hop', 'subagents', 'beat', 2.4, SUBR, [
+ K(.5, gaze=(-28, -14)), K(.7, 'out', h0=.35), K(.95, 'in', h0=0.0), K(.9, gaze=(0, -22)), K(1.0, 'out', h1=.35), K(1.25, 'in', h1=0.0),
+ K(1.2, gaze=(24, -14)), K(1.3, 'out', h2=.35), K(1.55, 'in', h2=0.0), K(1.6, lids=(-80, 30))], helpers=True, extra=bob)
+ seg('subagents_sigh', 'subagents', 'beat', 2.4, SUBR, [
+ K(.85, stretch=1.08, poof=1.06, lids=(-40, 80)), K(1.45, stretch=.9, poof=.95, lids=(-6, 70), gaze=(0, -10)), K(1.65)], helpers=True, extra=bob, hair=1.2)
+ seg('subagents_lean', 'subagents', 'beat', 2.4, SUBR, [
+ K(.85, toward=-.2, turn=-14, mid=(6, -8, 0), gaze=(-30, -22), lids=(-20, 50)), K(1.7)], helpers=True, extra=bob)
+
+ # ======================= speaking: phrases at a natural pace, a small nod per syllable =======================
+ def phrase(name, dur, beats, emph=(), side=1):
+ P = dict(turn=7 * side, mid=(0, -4 + 4 * side, 0))
+ ks = [K(.5, **P)]
+ for b in beats:
+ big = b in emph
+ ks.append(K(b, 'io', head=(-12 if big else -7, 6, 0), neck=(-7 if big else -4, -4, 0), stretch=1.07 if big else 1.03,
+ poof=1.05 if big else 1.0, **({'lids': (-80, 86), 'pupil': 23} if big else {})))
+ ks.append(K(b + .14, 'io', head=(0, 6, 0), neck=(-2, -4, 0), stretch=.99, poof=1.0, lidsL=(-34, 80), lidsR=(-30, 80), pupil=21))
+ ks.append(K(beats[-1] + .45, **P))
+ seg(name, 'speaking', 'beat', dur, SPEAK, ks, hold_in=.3, hold_out=.55, breath=(0, 1), hair=1.1)
+ phrase('speak_a', 3.2, [.75, 1.0, 1.25, 1.5, 1.8, 2.05], emph=(1.25,), side=-1)
+ phrase('speak_b', 3.8, [.75, .99, 1.23, 1.47, 1.75, 1.99, 2.24, 2.5], emph=(1.75,), side=1)
+ phrase('speak_c', 2.6, [.75, 1.0, 1.28, 1.5], side=1)
+ phrase('speak_d', 4.4, [.75, .99, 1.24, 1.5, 1.9, 2.14, 2.4, 2.66, 2.9, 3.1], emph=(1.24, 2.66), side=-1)
+ seg('speaking_rest', 'speaking', 'rest', 1.8, SPEAK, [K(.8, gaze=(6, 4)), K(1.1)], hold_in=.3, hold_out=.4, blinks=[.9], breath=(.01, 1.8))
+
+ # ======================= done =======================
+ enter('done_in', 'done', 2.2, [K(0, base=DEAD), K(.35, stretch=.82, rise=-.14, lids=(4, 40), mid=(6, 0, 0), poof=.9),
+ K(.68, 'out', base=DONE, stretch=1.28, rise=.45, head=(-10, 0, 0), poof=1.24), K(.9, turn=28), K(1.15, turn=-24),
+ K(1.35, turn=8, stretch=1.18, rise=.18), K(1.5, 'in', stretch=.86, rise=0, turn=0), K(1.8, 'back', stretch=1.18, poof=1.18),
+ K(2.2, base=DONE)], events={'apex': .7, 'land': 1.5}, hair=1.4)
+ seg('done_rest', 'done', 'rest', 3.6, DONE, [K(1.5, 'out', rise=.05, stretch=1.2), K(1.8, 'in', rise=0, stretch=1.12), K(2.1, stretch=1.16)],
+ sway=(8, 5, 3.6), hair=1.2)
+ seg('done_wiggle', 'done', 'beat', 2.8, DONE, [
+ K(.65, mid=(-4, 10, 0), neck=(0, 8, 0)), K(1.0, mid=(-4, -10, 0), neck=(0, -8, 0)), K(1.35, mid=(-4, 10, 0), neck=(0, 8, 0)),
+ K(1.7, mid=(-4, -6, 0), neck=(0, -5, 0)), K(2.0, mid=(-4, 0, 0), neck=(0, 0, 0))], hair=1.4)
+ seg('done_hop', 'done', 'beat', 2.4, DONE, [K(.6, stretch=.9, rise=-.06), K(.85, 'out', stretch=1.24, rise=.3), K(1.1, 'in', stretch=.92, rise=0),
+ K(1.35, 'back', stretch=1.16)], hair=1.4)
+
+ # ======================= needs you: at the glass =======================
+ enter('needs_in', 'needs', .8, [K(0, base=DEAD), K(.15, stretch=.92, lids=(-88, 88), pupil=12),
+ K(.42, 'in', base=NEEDS, toward=3.3, stretch=1.08), K(.5, 'out', toward=3.2, stretch=.88), K(.8, 'back', base=NEEDS)],
+ events={'contact': .47}, hair=1.3)
+ seg('needs_rest', 'needs', 'rest', 4.0, NEEDS, [
+ K(.5, 'out', toward=2.5, stretch=1.04, head=(-6, 0, 0)), K(.63, 'in', toward=3.26, stretch=.9, head=(0, 0, 0)),
+ K(.78, 'out', toward=2.55, stretch=1.04, head=(-6, 0, 0)), K(.91, 'in', toward=3.26, stretch=.9, head=(0, 0, 0)), K(1.15, toward=3.2, stretch=1.0),
+ K(1.45, 'snap', gaze=(-30, 4), turn=-6), K(1.9), K(2.05, 'snap', gaze=(30, 4), turn=6), K(2.5), K(2.65, 'snap', gaze=(0, 6), turn=0)],
+ hold_in=.3, hold_out=.5, events={'contact': [.63, .91]}, hair=1.3)
+ seg('needs_slide', 'needs', 'beat', 3.2, NEEDS, [
+ K(1.3, rise=-1.4, head=(-10, 0, 0), stretch=.95, gaze=(0, 12), pupil=9), K(1.8), K(2.25, 'back', rise=-1.0, head=(0, 0, 0), stretch=1.0, pupil=7)],
+ hold_in=.3, hold_out=.5, hair=1.2)
+ seg('needs_tap', 'needs', 'beat', 2.4, NEEDS, [
+ K(.45, 'out', toward=2.7), K(.56, 'in', toward=3.26), K(.7, 'out', toward=2.7), K(.81, 'in', toward=3.26),
+ K(.95, 'out', toward=2.7), K(1.06, 'in', toward=3.26), K(1.3, toward=3.2)], hold_in=.3, hold_out=.5, events={'contact': [.56, .81, 1.06]})
+
+ # ======================= approval: the card sits on its hair =======================
+ enter('approval_in', 'approval', .9, [K(0, base=DEAD), K(.22, 'snap', gaze=(0, 30), lids=(-82, 86)), K(.35, gaze=(0, 30)),
+ K(.45, 'out', rise=-.55, stretch=.84, lids=(0, 50), poof=.88), K(.7, rise=-1.34, stretch=1.0, poof=1.0), K(.9, 'back', base=APPR)],
+ events={'land': .35}, hair=1.3)
+ seg('approval_rest', 'approval', 'rest', 4.2, APPR, [
+ K(1.3, gaze=(0, 34)), K(1.45, 'snap', gaze=(0, 0), lids=(-60, 85), toward=.4), K(2.3), K(2.45, 'snap', gaze=(0, 34), lids=(-80, 85), toward=0)],
+ sway=(7, 3, 4.2), blinks=[2.0])
+ seg('approval_wobble', 'approval', 'beat', 2.4, APPR, [
+ K(.7, mid=(-2, 9, 0), neck=(-4, 4, 0), gaze=(14, 30), pupil=13), K(1.05, mid=(-2, -8, 0), neck=(-4, -4, 0), gaze=(-12, 30)), K(1.4, mid=(-2, 3, 0)),
+ K(1.7, mid=(-2, 0, 0), neck=(-4, 0, 0), pupil=18)], hair=1.3)
+ def hold_pose(k):
+ p = dict(NEUTRAL); p.update(APPR)
+ p.update(rise=-1.25 + .32 * k, stretch=1 + .14 * k, poof=1 - .1 * k, lidsL=(-80 + 86 * k, 85 - 45 * k), lidsR=(-80 + 86 * k, 85 - 45 * k),
+ pupilL=18 - 9 * k, pupilR=18 - 9 * k, mid=(-2, (1 if round(k * 12) % 2 else -1) * (.5 + 3 * k), 0))
+ return p
+ add(Clip('approval_hold', 0, scrub=hold_pose, n=13, role='scrub', state='approval'))
+ held = hold_pose(1.0)
+ add(Clip('approval_allow', 1.0, [K(0, base=held), K(.12, 'in', rise=-1.34, stretch=.86), K(.3, 'out', rise=-.5, stretch=1.24, lids=(-80, 22), gaze=(0, 30), pupil=18),
+ K(.6, rise=-.9, stretch=1.04), K(1.0, base=DEAD)], breath=(0, 1), events={'launch': .28}, hair=1.4, role='react', state='approval'))
+ add(Clip('approval_deny', 1.0, [K(0, base=APPR), K(.15, 'snap', rise=-1.6, stretch=.88, lids=(6, 40)), K(.5, rise=-1.45, gaze=(0, -24), lids=(-20, 70)),
+ K(1.0, base=DEAD)], breath=(0, 1), events={'drop': .15}, role='react', state='approval'))
+
+ # ======================= blocked =======================
+ enter('blocked_in', 'blocked', 1.2, [K(0, base=DEAD), K(.25, stretch=.9, mid=(-6, 0, 0)), K(.45, 'out', stretch=1.16, rise=.24, head=(-14, 0, 0), gaze=(0, 22), lids=(-82, 86)),
+ K(.52, 'out', stretch=.82, rise=.04, lids=(10, 30), pupil=8, head=(6, 0, 0)), K(.8, rise=0, stretch=1.0), K(1.2, base=BLOCK)],
+ events={'bonk': .5}, hair=1.5)
+ seg('blocked_rest', 'blocked', 'rest', 5.6, BLOCK, [
+ K(1.7, stretch=1.1, mid=(0, 0, 3), neck=(2, 3, 3), head=(-2, 5, 0), lidsL=(-24, 80), lidsR=(-18, 80), gaze=(2, -8), poof=1.04),
+ K(3.0, stretch=.86, mid=(12, 0, 8), neck=(16, 9, 8), head=(10, 11, 0), lidsL=(10, 70), lidsR=(14, 70), gaze=(4, -40), poof=.92), K(3.6),
+ K(3.9, neck=(16, 9, 18)), K(4.2, neck=(16, 9, -2)), K(4.5, neck=(16, 9, 8))], breath=(0, 1), hair=1.3)
+ seg('blocked_try', 'blocked', 'beat', 3.2, BLOCK, [
+ K(.9, stretch=1.14, rise=.2, head=(-12, 0, 0), neck=(0, 0, 0), mid=(0, 0, 0), gaze=(0, 22), lids=(-82, 86), pupil=20),
+ K(1.0, 'out', stretch=.84, rise=.06, lids=(8, 30), pupil=8, head=(6, 0, 0)), K(1.5, stretch=1.0, rise=0), K(2.1, lids=(6, 70))],
+ breath=(0, 1), events={'bonk': 1.0}, hair=1.5)
+
+ # ======================= compacting, waiting =======================
+ enter('compacting_in', 'compacting', .8, [K(0, base=DEAD), K(.15, 'snap', stretch=1.08, lids=(-88, 88), pupil=12), K(.6, base=SQUASH, stretch=.7), K(.8, base=SQUASH)], hair=1.3)
+ seg('compacting_rest', 'compacting', 'rest', 3.6, SQUASH, [
+ K(.6, 'snap', gaze=(-22, 0)), K(1.1), K(1.25, 'snap', gaze=(22, 0)), K(1.6, stretch=.8, poof=.88), K(2.1, stretch=.69, poof=.78), K(2.4, 'snap', gaze=(0, 0))],
+ hold_in=.3, hold_out=.5, breath=(0, 1), sway=(5, 0, .9))
+ add(Clip('compact_out', .8, [K(0, base=SQUASH), K(.25, 'out', stretch=1.26, rise=.12, poof=1.2, lids=(-80, 85), pupil=19), K(.5, stretch=.94, rise=0),
+ K(.8, base=DEAD)], breath=(0, 1), hair=1.5, role='react', state='compacting'))
+ seg('waiting_rest', 'waiting', 'rest', 4.4, WAIT, [
+ K(1.0, gaze=(28, 34), head=(-14, 6, 0), neck=(-4, 4, 0), lids=(-44, 80)), K(2.0), K(2.4, gaze=(4, -6), head=(0, 0, 0), neck=(3, -2, 0), lids=(4, 68)),
+ K(3.0, stretch=.9, poof=.95, mid=(6, 0, 0)), K(3.5, stretch=1.0, poof=1.0, mid=(2, -3, 0))], blinks=[1.45, 2.75], sway=(2, 2, 4.4))
+ tap = []
+ for i, t in enumerate([.6, .9, 1.2, 1.5, 1.8]):
+ tap += [K(t, 'out', neck=(9, -2, 0), head=(4, 0, 0)), K(t + .15, neck=(3, -2, 0), head=(0, 0, 0))]
+ seg('waiting_tap', 'waiting', 'beat', 2.6, WAIT, tap + [K(.5, gaze=(10, -10))])
+
+ # ======================= dizzy (one-shot) =======================
+ def dizzy_extra(t, p):
+ p = dict(p)
+ T = 3.2
+ if t < T:
+ env = math.exp(-t * .85); a = 20 * math.sin(t * 9.5) * env; sw = 32 * env
+ p['mid'] = (0, a * .5, 0); p['neck'] = (0, a * .8, 0); p['head'] = (0, a * .6, 0); p['turn'] = a * .5
+ p['gazeL'] = (sw * math.cos(t * 7.5), sw * math.sin(t * 7.5)); p['gazeR'] = (sw * math.cos(-t * 7.5 + 2), sw * math.sin(-t * 7.5 + 2))
+ p['pupilL'] = 19 - 7 * env; p['pupilR'] = 19 + 3 * env
+ p['lidsR'] = (p['lidsR'][0] + 20 * env, p['lidsR'][1] - 20 * env)
+ elif t < T + .5:
+ s = 16 * math.sin((t - T) * 2 * math.pi * 6) * (1 - (t - T) / .5)
+ p['neck'] = (3, s, 0); p['head'] = (0, s * .7, 0); p['lidsL'] = p['lidsR'] = (8, 30)
+ return p
+ add(Clip('dizzy', 4.8, [K(0, base=DEAD), K(3.2, base=DEAD, lids=(-60, 80)), K(3.7, base=DEAD, lids=(8, 30)), K(4.0, 'back', base=DEAD, lids=(-50, 85)), K(4.8, base=DEAD)],
+ breath=(0, 1), blinks=[4.2], extra=dizzy_extra, hair=1.6, role='once', state='dizzy'))
+
+ # ======================= sleep =======================
+ enter('sleep_in', 'sleep', 2.8, [K(0, base=DEAD), K(.6, stretch=1.2, rise=.12, lids=(8, 20), head=(-14, 0, 0), neck=(-4, 0, 0), poof=1.12), K(1.0),
+ K(1.4, 'back', stretch=.93, lids=CLOSED, head=(4, 0, 0), neck=(4, 0, 0), poof=1.0), K(2.8, base=SLEEP)], hair=1.2)
+ seg('sleep_rest', 'sleep', 'rest', 4.0, SLEEP, [K(2.75, base=SLEEP), K(2.85, 'snap', rise=-2.6), K(3.05, rise=-2.7)], hold_in=.3, hold_out=.4,
+ extra=lambda t, p: {**p, 'rise': p['rise'] + .07 * math.sin(2 * math.pi * t / 4.0)})
+ seg('sleep_twitch', 'sleep', 'beat', 2.4, SLEEP, [K(.8, 'snap', hairtilt=(10, -8, 0), poof=1.06), K(1.1, hairtilt=(0, 0, 0), poof=1.0)], hold_in=.3, hold_out=.4, hair=1.6)
+
+ # ======================= popping up and the touch reactions =======================
+ add(Clip('popup', 1.8, [K(0, base=DEAD, rise=-4.2, lids=(-88, 88), gaze=(0, 0), pupil=10), K(.35, 'out', rise=.32, stretch=1.18),
+ K(.48, 'in', rise=0, stretch=.88), K(.6, stretch=1.0), K(.72, 'snap', gaze=(-32, 0), lids=(-80, 88), pupil=14, mid=(0, 5, 0), turn=-8), K(1.0),
+ K(1.1, 'snap', gaze=(32, 0), mid=(0, -5, 0), turn=8), K(1.3), K(1.8, base=DEAD)], breath=(0, 1), events={'land': .48}, hair=1.4, role='react'))
+ add(Clip('poke', 1.5, [K(0, base=DEAD), K(.06, 'out', stretch=.8, lids=CLOSED, poof=.88), K(.2, 'out', stretch=1.12, toward=-.3, lids=(-88, 88), pupil=6, poof=1.12),
+ K(.8, stretch=1.02), K(1.0, lids=(-40, 70), pupil=14, toward=0), K(1.5, base=DEAD)], breath=(0, 1), hair=1.5, role='react'))
+ add(Clip('pet', 1.8, [K(0, base=DEAD), K(.22, lids=(4, 40), mid=(0, 12, 0), neck=(0, 10, 0), head=(0, 8, 0), stretch=.95, toward=.3),
+ K(.5, mid=(0, 4, 0), neck=(0, 4, 0)), K(.75, mid=(0, 12, 0), neck=(0, 10, 0)), K(1.0, mid=(0, 4, 0), neck=(0, 4, 0), lids=(6, 42)),
+ K(1.3, 'io', lids=(-70, 28), stretch=1.06, poof=1.08, mid=(0, 0, 0), neck=(0, 0, 0), head=(0, 0, 0), toward=0), K(1.8, base=DEAD)],
+ breath=(0, 1), hair=1.3, role='react'))
+ return C
+
+
+CLIPS = build()
+SKIP = '--skip' in sys.argv
+
+
+def frames_of(clip):
+ if clip.scrub:
+ return [clip.scrub(i / (clip.n - 1)) for i in range(clip.n)]
+ ts = [i / FPS for i in range(clip.n)]
+ return springs(clip, [overlay(clip, t, clip.primary(t)) for t in ts])
+
+
+def preview_mode(on):
+ """motion review: no hair strands, the surface material instead of the gel volume, no bloom. About 1 s a frame."""
+ for m in D.objects['HairCloud'].modifiers:
+ if m.type == 'PARTICLE_SYSTEM': m.show_render = not on
+ D.objects['Body'].material_slots[0].material = D.materials['Skin' if on else 'Gel']
+ sc.render.use_compositing = not on
+
+
+def render(names, step=1, samples=128, pct=50, out='anim'):
+ meta_path = bpy.path.abspath('//renders/clips.json')
+ meta = json.load(open(meta_path)) if os.path.exists(meta_path) else {'fps': FPS, 'clips': {}}
+ t0 = time.time()
+ for name in names:
+ clip = CLIPS[name]
+ poses = frames_of(clip)
+ data = []
+ for i, p in enumerate(poses):
+ apply(p, clip.helpers)
+ data.append(anchors(p))
+ path = bpy.path.abspath(f'//renders/{out}/{name}_{i:03d}.png')
+ if i % step == 0 and not (SKIP and os.path.exists(path)): shot(f'{out}/{name}_{i:03d}', samples, pct)
+ if out == 'anim':
+ ev = {k: ([round(x * FPS) for x in v] if isinstance(v, list) else round(v * FPS)) for k, v in clip.events.items()}
+ meta['beat_chance'] = BEAT_CHANCE
+ meta['clips'][name] = {'n': len(poses), 'loop': clip.loop, 'scrub': bool(clip.scrub), 'events': ev, 'role': clip.role, 'state': clip.state,
+ 'anchors': ['hairX', 'hairY', 'faceX', 'faceY', 'roll', 'press', 'rise'], 'frames': data}
+ json.dump(meta, open(meta_path, 'w'), separators=(',', ':'))
+ print(f'{name}: {len(poses)} frames, {time.time() - t0:.0f} s', flush=True)
+ apply(frames_of(CLIPS['idle_rest'])[0], False)
+
+
+if __name__ in ('__main__', '<run_path>') or 'animate' in sys.argv[0:1]:
+ argv = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else []
+ opts = {'step': 1, 'samples': 128, 'out': 'anim'}
+ names = []
+ i = 0
+ while i < len(argv):
+ a = argv[i]
+ if a in ('--preview', '--skip'): opts[a[2:]] = True; i += 1
+ elif a.startswith('--'): opts[a[2:]] = argv[i + 1]; i += 2
+ else: names.append(a); i += 1
+ if not names or names == ['all']: names = list(CLIPS)
+ if 'preview' in opts or '--preview' in argv:
+ preview_mode(True)
+ try: render(names, step=int(opts.get('step', 3)), samples=8, pct=25, out='preview')
+ finally: preview_mode(False)
+ else:
+ render(names, step=int(opts['step']), samples=int(opts['samples']), out=opts['out'])
diff --git a/design/noodle/noodle.blend b/design/noodle/noodle.blend
new file mode 100644
index 0000000..a4cd334
Binary files /dev/null and b/design/noodle/noodle.blend differ
diff --git a/design/noodle/noodle_rig.py b/design/noodle/noodle_rig.py
new file mode 100644
index 0000000..89a730b
--- /dev/null
+++ b/design/noodle/noodle_rig.py
@@ -0,0 +1,206 @@
+"""Noodle: pose and render helpers for noodle.blend.
+
+Open noodle.blend, then run this file from Blender's Text editor (it is also stored inside the .blend as
+the text block "noodle_rig.py"). It registers the helpers in bpy.app.driver_namespace so they can be called
+from the Python console or over the Blender MCP:
+
+ ns = bpy.app.driver_namespace
+ ns['pose'](**ns['STATES']['idle']) # pose the character
+ ns['shot']('st_idle', samples=128, pct=50) # render one still to OUT/st_idle.png
+ ns['render_states']() # every state + hero
+ ns['render_gags']() # every gag loop, OUT/anim/<gag>_NN.png
+
+Then tools/noodle-watch.sh turns the PNGs into the watch's clips.
+
+The rig
+ Rig (armature) bones Base / Mid / Neck / Head bend the body; Mid's Y scale is the stretch
+ Rig location rise (z, negative sinks it below the screen edge), toward (-y, toward the camera)
+ Eye{L,R}Upper/Lower felt lid shells, rotated about X. Upper: about -88 wide open … 14 closed.
+ Lower: 88 open … 6 closed. (14, 6) is the clean closed pair; more overlap z-fights.
+ Lids are hidden when fully open, and their back half is masked in the LidSkin/LidFur
+ shaders so no rim shows around the eyeball.
+ Eye{L,R}Ball the eyeball; gaze rotates it (yaw, pitch in degrees) and the pupil shader moves with it
+ EyeWhite{L,R} pupil and iris size are shader masks (pupil_size in degrees, 19 = normal)
+ HairCloud pink hairdo; poof scales it, hairtilt rotates it around the crown
+ Helper0-2 collection instances of "Noodle" used for the subagents shot
+
+Look notes (2026-10-01, v4: gel)
+ The body is a glowing gel, not a surface shader. Material "Gel" on Body:
+ Surface: Principled BSDF, Transmission 1, Roughness .3 (frosted), IOR 1.38, mixed with a Transparent BSDF
+ on shadow rays (Light Path > Is Shadow Ray), so lights outside reach the inside of the volume.
+ Volume: Volume Scatter (color 1/.48/.14, density 4, anisotropy .35) + Volume Absorption (color 1/.32/.06,
+ density 3.5). Thin parts glow orange; thick parts go deep red. Lower densities wash out to pale pink.
+ The body mesh is capped at the bottom (off-screen) so the volume is watertight.
+ "Core": a warm point light (700 W, 1/.52/.16) inside the neck, parented to the Neck bone and hidden from
+ camera/reflections: the glow from inside. CoreH0-2 are the same for the subagent minis (only on in that shot).
+ Lids stay opaque silicone (LidSkin*, old Skin look) tuned to the gel's orange: gel lids show the pupils
+ through closed lids. The silicone material "Skin" is kept for comparison.
+ Fur on body and lids is off (particle modifiers disabled). Hair keeps its fur.
+ Lighting: Key 700 (big softbox), Fill 40, Top 120. Back/KickL/KickR at ~14% of before (1365/588/294),
+ saturated orange, silicone-only: too much backlight blows the gel to pink-white. Hair has its own rim
+ lights (HairOnly). EyeKey 220 + Catch 260 light the eyeballs only (EyesOnly).
+ Color: Khronos PBR Neutral view transform (AgX desaturated the glow to white), exposure -2.0.
+ Compositor "NoodleComp": Bloom (threshold 2.5, strength .22, size .45) for the halo; the eyeballs
+ (pass_index 7) are masked out so pupils stay pure black, and the background stays true black for OLED.
+ Volumes are noisier: gag loops were rendered at 64 samples.
+"""
+import bpy, math
+
+OUT = bpy.path.abspath('//renders') # next to noodle.blend; change before rendering if needed
+ns = bpy.app.driver_namespace
+D = bpy.data
+sc = bpy.context.scene
+arm = D.objects['Rig']
+cloud = D.objects['HairCloud']
+for pb in arm.pose.bones: pb.rotation_mode = 'XYZ'
+
+# the hairdo's rest transform is stored on the object so poof/hairtilt are always relative to it
+if 'rest_loc' not in cloud:
+ cloud['rest_loc'] = list(cloud.location); cloud['rest_rot'] = list(cloud.rotation_euler); cloud['rest_scale'] = list(cloud.scale)
+
+
+def lids(side, up, lo):
+ u = D.objects['Eye' + side + 'Upper']; l = D.objects['Eye' + side + 'Lower']
+ u.rotation_euler = (math.radians(up), 0, 0); l.rotation_euler = (math.radians(lo), 0, 0)
+ u.hide_render = up <= -50; l.hide_render = lo >= 60 # an open lid tucks away
+
+
+def gaze(side, yaw, pitch):
+ # the pupil is painted in the eyeball's own coordinates, so rotating the ball moves it. (The shader used to read
+ # the Gaze empty's coordinates; collection instances like the subagent minis then lost their pupils.)
+ r = (math.radians(pitch), 0, math.radians(yaw))
+ D.objects['Eye' + side + 'Gaze'].rotation_euler = r
+ D.objects['Eye' + side + 'Ball'].rotation_euler = r
+
+
+def pupil_size(side, deg):
+ m = D.materials['EyeWhite' + side].node_tree.nodes
+ for name, extra, soft in (('PupilMask', 0, 0.004), ('IrisMask', 4.5, 0.012)):
+ c = math.cos(math.radians(deg + extra)); n = m[name]
+ n.inputs['From Min'].default_value = c - soft; n.inputs['From Max'].default_value = c + soft
+
+
+def bend(base=(0, 0, 0), mid=(0, 0, 0), neck=(0, 0, 0), head=(0, 0, 0), stretch=1.0):
+ for n, r in (('Base', base), ('Mid', mid), ('Neck', neck), ('Head', head)):
+ pb = arm.pose.bones[n]; pb.rotation_euler = tuple(math.radians(a) for a in r); pb.scale = (1, 1, 1)
+ arm.pose.bones['Mid'].scale = (1 / math.sqrt(stretch), stretch, 1 / math.sqrt(stretch))
+
+
+def pose(base=(0, 0, 0), mid=(0, 0, 0), neck=(0, 0, 0), head=(0, 0, 0), stretch=1.0, rise=0.0, turn=0.0, toward=0.0,
+ lidsL=(-10, 80), lidsR=(-10, 80), gazeL=(4, -6), gazeR=(4, -6), pupil=19, pupilL=None, pupilR=None,
+ poof=1.0, hairtilt=(0, 0, 0)):
+ bend(base, mid, neck, head, stretch)
+ arm.location = (0, -toward, rise); arm.rotation_euler = (0, 0, math.radians(turn))
+ lids('L', *lidsL); lids('R', *lidsR); gaze('L', *gazeL); gaze('R', *gazeR)
+ pupil_size('L', pupilL or pupil); pupil_size('R', pupilR or pupil)
+ cloud.location = tuple(cloud['rest_loc']); cloud.scale = tuple(s * poof for s in cloud['rest_scale'])
+ cloud.rotation_euler = tuple(r + math.radians(a) for r, a in zip(cloud['rest_rot'], hairtilt))
+ bpy.context.view_layer.update()
+
+
+def shot(name, samples=64, pct=50):
+ sc.cycles.samples = samples; sc.render.resolution_percentage = pct
+ sc.render.filepath = f'{OUT}/{name}.png'
+ bpy.ops.render.render(write_still=True)
+
+
+def seq(name, n, fn, samples=64, pct=40):
+ for f in range(n):
+ pose(**fn(f)); shot(f'anim/{name}_{f:02d}', samples, pct)
+ pose()
+
+
+STATES = {
+ 'idle': dict(mid=(2, -3, 0), neck=(3, -2, 0), lidsL=(-10, 80), lidsR=(-6, 80), gazeL=(6, -4), gazeR=(6, -4)),
+ 'listening': dict(mid=(6, 0, 0), neck=(8, 0, 0), head=(4, 0, 0), stretch=1.1, lidsL=(-85, 85), lidsR=(-85, 85), gazeL=(0, 0), gazeR=(0, 0), pupil=24, poof=1.06),
+ 'thinking': dict(mid=(0, 8, 0), neck=(-4, 12, 0), head=(-6, 10, 0), lidsL=(-55, 80), lidsR=(-2, 80), gazeL=(22, 24), gazeR=(22, 24)),
+ 'working': dict(mid=(6, 0, 0), neck=(10, 0, 0), head=(8, 0, 0), lidsL=(-22, 40), lidsR=(-22, 40), gazeL=(-8, -26), gazeR=(-8, -26)),
+ 'speaking': dict(mid=(0, -6, 0), neck=(-2, -6, 0), head=(0, 9, 0), stretch=0.97, lidsL=(-34, 80), lidsR=(-30, 80), gazeL=(0, 2), gazeR=(0, 2), pupil=21),
+ 'done': dict(stretch=1.16, mid=(-4, 0, 0), lidsL=(-80, 22), lidsR=(-80, 22), gazeL=(0, 10), gazeR=(0, 10), poof=1.18),
+ 'needs': dict(toward=3.0, rise=-1.0, lidsL=(-88, 88), lidsR=(-88, 88), gazeL=(0, 4), gazeR=(0, 4), pupil=7),
+ 'blocked': dict(mid=(8, 0, 6), neck=(12, 6, 6), head=(6, 8, 0), lidsL=(6, 80), lidsR=(12, 80), gazeL=(4, -34), gazeR=(0, -34), poof=.95, hairtilt=(8, 6, 0)),
+ 'dizzy': dict(mid=(0, -10, 0), neck=(0, 14, 0), head=(0, -12, 0), lidsL=(-70, 80), lidsR=(-30, 50), gazeL=(-28, 24), gazeR=(26, -22), pupilL=13, pupilR=22),
+ 'sleep': dict(rise=-2.75, lidsL=(14, 6), lidsR=(14, 6)),
+}
+
+
+def subagents(samples=128, pct=50):
+ """The main one side-eyes three small instances of itself popping up in front."""
+ H = [D.objects[f'Helper{i}'] for i in range(3)] + [o for o in D.objects if o.name.startswith('CoreH')]
+ pose(gazeL=(-26, -8), gazeR=(-26, -8), lidsL=(-10, 80), lidsR=(-6, 80))
+ arm.location = (0.25, 0.8, 0.15)
+ for h in H: h.hide_render = False
+ bpy.context.view_layer.update(); shot('st_subagents', samples, pct)
+ for h in H: h.hide_render = True
+ arm.location = (0, 0, 0); pose()
+
+
+def render_states(samples=128, pct=50):
+ for k, v in STATES.items():
+ pose(**v); shot('st_' + k, samples, pct)
+ subagents(samples, pct)
+ pose(**STATES['idle']); shot('hero', 256, 100)
+
+
+# ---------- gag loops (12 fps) ----------
+def ease(k): k = max(0.0, min(1.0, k)); return k * k * (3 - 2 * k)
+def lerp(a, b, k): return a + (b - a) * k
+DEAD = dict(lidsL=(-10, 80), lidsR=(-6, 80), gazeL=(6, -4), gazeR=(6, -4))
+
+
+def popup(f): # rises from below the edge, overshoots, double take, deadpan
+ if f < 6: k = ease(f / 5); return dict(rise=lerp(-4.2, 0.35, k), stretch=1 + 0.12 * k, lidsL=(-88, 88), lidsR=(-88, 88), gazeL=(0, 0), gazeR=(0, 0), pupil=10)
+ if f < 9: k = ease((f - 6) / 2); return dict(rise=lerp(0.35, 0.0, k), stretch=lerp(1.12, 0.94, k) if f < 8 else 1.0, lidsL=(-88, 88), lidsR=(-88, 88), gazeL=(0, 0), gazeR=(0, 0), pupil=10)
+ if f < 12: return dict(lidsL=(-80, 88), lidsR=(-80, 88), gazeL=(-30, 0), gazeR=(-30, 0), pupil=14, mid=(0, 3, 0))
+ if f < 15: return dict(lidsL=(-80, 88), lidsR=(-80, 88), gazeL=(30, 0), gazeR=(30, 0), pupil=14, mid=(0, -3, 0))
+ k = ease((f - 15) / 4); return dict(lidsL=(lerp(-80, -10, k), 80), lidsR=(lerp(-80, -6, k), 80), gazeL=(6 * k, -4 * k), gazeR=(6 * k, -4 * k), pupil=lerp(14, 19, k))
+
+
+def poke(f): # flinch, frozen pinprick stare, lids come back down slowly
+ if f < 3: return dict(DEAD)
+ if f == 3: return dict(stretch=0.9, lidsL=(-88, 88), lidsR=(-88, 88), gazeL=(0, 0), gazeR=(0, 0), pupil=7)
+ if f < 16: return dict(stretch=1.06, lidsL=(-88, 88), lidsR=(-88, 88), gazeL=(0, 0), gazeR=(0, 0), pupil=7)
+ if f < 19: k = ease((f - 16) / 2); return dict(stretch=lerp(1.06, 1.0, k), lidsL=(lerp(-88, -42, k), 80), lidsR=(lerp(-88, -40, k), 80), gazeL=(0, 0), gazeR=(0, 0), pupil=lerp(7, 15, k))
+ if f < 21: return dict(lidsL=(-42, 80), lidsR=(-40, 80), gazeL=(0, 0), gazeR=(0, 0), pupil=15)
+ k = ease((f - 21) / 5); return dict(lidsL=(lerp(-42, -10, k), 80), lidsR=(lerp(-40, -6, k), 80), gazeL=(6 * k, -4 * k), gazeR=(6 * k, -4 * k), pupil=lerp(15, 19, k))
+
+
+def sleep(f): # eyes close, then it sinks until only the hair is out
+ if f < 9: k = ease(f / 8); return dict(lidsL=(lerp(-10, 14, k), lerp(80, 6, k)), lidsR=(lerp(-6, 14, k), lerp(80, 6, k)), mid=(3 * k, 0, 0), neck=(4 * k, 0, 0))
+ k = ease((f - 9) / 13); return dict(rise=lerp(0, -2.75, k) + 0.08 * math.sin(f * 1.3) * (1 - k), lidsL=(14, 6), lidsR=(14, 6), mid=(4, 0, 0), neck=(4, 0, 0), head=(4 * k, 0, 0))
+
+
+def press(f): # face on the glass, looks left and right for you, slides down
+ if f < 6: k = ease(f / 5); return dict(toward=3.0 * k, rise=-1.0 * k, lidsL=(-88, 88), lidsR=(-88, 88), gazeL=(0, 4), gazeR=(0, 4), pupil=lerp(19, 7, k))
+ if f < 15:
+ dx = [0, -24, -24, 24, 24, 0, 0, 0, 0][f - 6]
+ return dict(toward=3.0, rise=-1.0, lidsL=(-88, 88), lidsR=(-88, 88), gazeL=(dx, 4), gazeR=(dx, 4), pupil=7)
+ k = ease((f - 15) / 6); return dict(toward=3.0, rise=lerp(-1.0, -1.45, k), lidsL=(-88, 88), lidsR=(-88, 88), gazeL=(0, 10), gazeR=(0, 10), pupil=7, head=(-6 * k, 0, 0))
+
+
+def dizzy(f): # head wobbles, each eye goes its own way, settles
+ t = f / 12.0; env = math.exp(-t * 1.3); a = 16 * math.sin(t * 11) * env; sw = 30 * env
+ gl = (sw * math.cos(t * 9), sw * math.sin(t * 9)); gr = (sw * math.cos(-t * 9 + 2), sw * math.sin(-t * 9 + 2)); lid = (lerp(-60, -10, 1 - env), 80)
+ return dict(mid=(0, a * 0.5, 0), neck=(0, a * 0.8, 0), head=(0, a * 0.6, 0), lidsL=lid, lidsR=(lid[0] + 20 * env, 60 + 20 * (1 - env)),
+ gazeL=gl, gazeR=gr, pupilL=lerp(19, 12, env), pupilR=lerp(19, 22, env), hairtilt=(0, a * 0.4, 0))
+
+
+def think(f): # one lid drops, the eyes roll up and across
+ if f < 5: k = ease(f / 4); return dict(lidsL=(lerp(-10, -60, k), 80), lidsR=(lerp(-6, -60, k), 80), gazeL=(-22 * k, 24 * k), gazeR=(-22 * k, 24 * k), mid=(0, 4 * k, 0), neck=(0, 6 * k, 0))
+ if f < 11: k = ease((f - 5) / 3); return dict(lidsL=(-60, 80), lidsR=(lerp(-60, -4, k), 80), gazeL=(-22, 24), gazeR=(-22, 24), mid=(0, 4, 0), neck=(0, 6, 0))
+ if f < 17: k = ease((f - 11) / 3); return dict(lidsL=(-60, 80), lidsR=(-4, 80), gazeL=(lerp(-22, 24, k), 24), gazeR=(lerp(-22, 24, k), 24), mid=(0, lerp(4, -4, k), 0), neck=(0, lerp(6, -6, k), 0))
+ k = ease((f - 17) / 5); return dict(lidsL=(lerp(-60, -10, k), 80), lidsR=(lerp(-4, -6, k), 80), gazeL=(lerp(24, 6, k), lerp(24, -4, k)), gazeR=(lerp(24, 6, k), lerp(24, -4, k)), mid=(0, -4 * (1 - k), 0), neck=(0, -6 * (1 - k), 0))
+
+
+GAGS = [('popup', 22, popup), ('poke', 30, poke), ('sleep', 26, sleep), ('press', 22, press), ('dizzy', 28, dizzy), ('think', 24, think)]
+
+
+def render_gags(names=None):
+ for name, n, fn in GAGS:
+ if names is None or name in names: seq(name, n, fn)
+
+
+ns.update(dict(lids=lids, gaze=gaze, pupil_size=pupil_size, bend=bend, pose=pose, shot=shot, seq=seq, STATES=STATES,
+ GAGS=GAGS, subagents=subagents, render_states=render_states, render_gags=render_gags,
+ mpose=pose, mshot=shot))
+print('noodle rig ready; renders go to', OUT)
diff --git a/design/noodle/player.part b/design/noodle/player.part
new file mode 100644
index 0000000..8950f6d
--- /dev/null
+++ b/design/noodle/player.part
@@ -0,0 +1,245 @@
+ // Noodle: a gel puppet rendered in Blender (noodle/noodle.blend), animated in noodle/animate.py at 24 fps.
+ // Each state is a pool of segments: a calm rest loop and several beats that start and end on the same pose. The
+ // player chains them at random (never the same beat twice in a row), so a minute of listening or thinking doesn't
+ // repeat. clips.json says, frame by frame, where its hair top, face and the glass contact are on screen, so the
+ // screen plays along: the approval card rides on its hair, tool calls drop on its head and get bonked away, the glass
+ // fogs and ripples where it knocks.
+ const NOODLE = (() => {
+ const META = /*NOODLE_CLIPS*/null;
+ const FPS = META?.fps ?? 24, FW = META?.w ?? 396, FH = META?.h ?? 484, COLS = 8, PAGE = 64, EXT = META?.ext ?? 'avif', DIR = 'noodle/renders/';
+ const CL = META?.clips ?? {}, CHANCE = META?.beat_chance ?? {};
+ const pages = {};
+ const page = (name, p) => { const k = name + '-' + p; let im = pages[k]; if (!im) { im = new Image(); im.decoding = 'async'; im.src = `${DIR}clip-${name}-${p}.${EXT}`; pages[k] = im; } return im; };
+ const stills = {};
+ const still = s => { let im = stills[s]; if (!im) { im = new Image(); im.src = `${DIR}state-${s}.${EXT}`; stills[s] = im; } return im; };
+ const ready = name => { const c = CL[name]; if (!c) return false; for (let p = 0; p * PAGE < c.n; p++) { const im = page(name, p); if (!im.complete || !im.naturalWidth) return false; } return true; };
+ const load = name => { const c = CL[name]; if (c) for (let p = 0; p * PAGE < c.n; p++) page(name, p); };
+ const of = (state, role) => Object.keys(CL).filter(k => CL[k].state === state && CL[k].role === role);
+ const KIND = { read: 'work_read', search: 'work_search', edit: 'work_edit', run: 'work_run' };
+ const CALLS = [['read', 'Read hub.mjs'], ['search', 'Grep onSpoken'], ['edit', 'Edit hub.mjs'], ['run', 'Bash npm test'],
+ ['read', 'Read Voice.swift'], ['search', 'Glob **/*.swift'], ['edit', 'Edit Voice.swift'], ['run', 'Bash swift build']];
+ const n = { clip: 'idle_rest', f: 0, queue: [], fade: null, bags: {}, last: null, work: 'work_read', callT: 3, callI: 0,
+ tool: null, card: null, fx: [], fog: 0, zT: 0, held: false, flex: 0 };
+ const meta = name => CL[name];
+ const count = name => CL[name]?.n ?? 1;
+ const isLoop = name => !!CL[name]?.loop;
+ const restFor = s => s === 'working' ? n.work : of(s, 'rest')[0] ?? 'idle_rest';
+ const frameNo = () => {
+ if (n.held) return Math.round(clamp(hold, 0, 1) * (count('approval_hold') - 1));
+ const c = count(n.clip); return isLoop(n.clip) ? Math.floor(n.f) % c : Math.min(c - 1, Math.floor(n.f));
+ };
+ const clipNow = () => n.held ? 'approval_hold' : n.clip;
+ // where things are on screen this frame: hair top, face, roll, how hard it presses the glass
+ function anchors() {
+ const fr = CL[clipNow()]?.frames?.[frameNo()];
+ return fr ? { hx: fr[0], hy: fr[1], fx: fr[2], fy: fr[3], roll: fr[4], press: fr[5], rise: fr[6] } : { hx: 120, hy: 40, fx: 96, fy: 120, roll: 0, press: 0, rise: 0 };
+ }
+ function current() {
+ const name = clipNow(), f = frameNo(), p = Math.floor(f / PAGE), i = f % PAGE, im = page(name, p);
+ if (im.complete && im.naturalWidth) return { im, sx: (i % COLS) * FW, sy: Math.floor(i / COLS) * FH, sw: FW, sh: FH };
+ const s = still(state === 'approval' ? 'working' : state);
+ return { im: s, sx: 0, sy: 0, sw: s.naturalWidth || FW, sh: s.naturalHeight || FH };
+ }
+ function play(name, { from = 0, then = [], dissolve = true } = {}) {
+ if (!meta(name)) return;
+ if (dissolve) n.fade = { fr: current(), t: 0 };
+ n.clip = name; n.f = from; n.queue = then; n.held = false;
+ if (name === 'approval_in') n.card = { phase: 'fall', x: 99, y: 38, rot: 0 };
+ if (name === 'bump') { const [kind, text] = CALLS[n.callI++ % CALLS.length]; n.tool = { text, phase: 'fall', kind }; }
+ }
+ // the next segment of the state's pool: its rest loop again, or a beat (never the same one twice in a row)
+ function nextSegment() {
+ const beats = of(state, 'beat').filter(ready);
+ if (beats.length && Math.random() < (CHANCE[state] ?? .4)) {
+ let bag = n.bags[state];
+ if (!bag?.length) { bag = n.bags[state] = [...beats].sort(() => Math.random() - .5); if (bag.length > 1 && bag[bag.length - 1] === n.last) bag.unshift(bag.pop()); }
+ n.last = bag.pop(); return play(n.last, { dissolve: false });
+ }
+ play(restFor(state), { dissolve: false });
+ }
+ function next() {
+ const q = n.queue.shift();
+ if (q) return play(q, { then: n.queue, dissolve: false });
+ const r = meta(n.clip)?.role;
+ // segments of the current state end on its rest pose; anything else (a reaction, another state's clip) dissolves in
+ const seamless = meta(n.clip)?.state === state && ['rest', 'beat', 'enter'].includes(r) || (n.clip === 'bump' && state === 'working');
+ if (seamless) return nextSegment();
+ play(restFor(state), { dissolve: true });
+ }
+ function event(name, kind) {
+ const a = anchors();
+ if (kind === 'contact') { n.fx.push({ k: 'glass', x: a.fx, y: a.fy + 6, t: 0 }); n.flex = 1; click(true); }
+ if (kind === 'apex') for (let i = 0; i < 22; i++) {
+ const ang = -Math.PI / 2 + (Math.random() - .5) * 2.4, sp = 70 + Math.random() * 110;
+ n.fx.push({ k: 'confetti', x: a.hx, y: a.hy + 10, vx: Math.cos(ang) * sp, vy: Math.sin(ang) * sp, r: Math.random() * TAU, vr: (Math.random() - .5) * 12,
+ c: ['#FFB020', '#FF5FAE', '#F4F5F6', '#FF7A3D', '#7FE0B0'][i % 5], t: 0 });
+ }
+ if (kind === 'bonk') { n.fx.push({ k: 'bonk', x: a.hx - 8, y: a.hy, t: 0 }); click(true); }
+ if (kind === 'land' && name === 'bump' && n.tool) { n.tool.phase = 'ride'; click(); }
+ if (kind === 'launch' && name === 'bump' && n.tool) Object.assign(n.tool, { phase: 'fly', vx: 170, vy: -150, vr: 5, rot: 0 });
+ if (kind === 'land' && name === 'approval_in' && n.card) { n.card.phase = 'ride'; click(true); }
+ if (kind === 'launch' && name === 'approval_allow' && n.card) Object.assign(n.card, { phase: 'fly', vx: 40, vy: -420, vr: 3.2 });
+ if (kind === 'drop' && name === 'approval_deny' && n.card) Object.assign(n.card, { phase: 'drop', vx: -30, vy: 20, vr: -2.4 });
+ }
+ // cards come in and leave from under the status row, as if from behind the bezel
+ function card(ctx, c, w, h, draw) {
+ ctx.save(); ctx.beginPath(); ctx.rect(0, 38, 198, 204); ctx.clip(); ctx.translate(c.x, c.y); ctx.rotate((c.rot ?? 0)); ctx.translate(-w / 2, -h); draw(); ctx.restore();
+ }
+ // a knock on the glass: a ring of liquid glass runs out from the contact and refracts the frame under it.
+ // Each thin band of the ring redraws what's under it magnified or shrunk around the contact point (a lens ridge:
+ // magnified on the inner slope, compressed on the outer), with a specular edge where it catches the light.
+ let snap = null;
+ function glass(ctx, q) {
+ const k = q.t / 1.1; if (k >= 1) return;
+ const R = 16 + 150 * outC(k), wid = 16 + 26 * k, A = .16 * Math.pow(1 - k, 1.5);
+ const cv = ctx.canvas;
+ if (!snap || snap.width !== cv.width || snap.height !== cv.height) { snap = document.createElement('canvas'); snap.width = cv.width; snap.height = cv.height; }
+ const sg = snap.getContext('2d'); sg.setTransform(1, 0, 0, 1, 0, 0); sg.clearRect(0, 0, snap.width, snap.height); sg.drawImage(cv, 0, 0);
+ const lens = (r0, r1, s) => { ctx.save(); ctx.beginPath(); ctx.arc(q.x, q.y, r1, 0, TAU); if (r0 > 0) ctx.arc(q.x, q.y, r0, 0, TAU, true); ctx.clip();
+ ctx.translate(q.x, q.y); ctx.scale(s, s); ctx.translate(-q.x, -q.y); ctx.drawImage(snap, 0, 0, 198, 242); ctx.restore(); };
+ // the contact point bulges toward you for an instant
+ if (k < .3) lens(0, Math.max(4, R - wid / 2), 1 + .05 * (1 - k / .3));
+ // the ridge: magnified on its inner slope, compressed on the outer one
+ const BANDS = 18;
+ for (let i = 0; i < BANDS; i++) {
+ const u0 = i / BANDS, u1 = (i + 1) / BANDS, um = (u0 + u1) / 2;
+ lens(Math.max(0, R - wid / 2 + wid * u0), R - wid / 2 + wid * u1, 1 + A * Math.cos(Math.PI * um));
+ }
+ // shading across the ridge, so it reads as a bump of glass even over black: a soft highlight, then a soft shade
+ const a = (1 - k) * (1 - k), r0 = Math.max(0, R - wid / 2), r1 = R + wid / 2;
+ const g = ctx.createRadialGradient(q.x, q.y, r0, q.x, q.y, r1);
+ g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(.32, `rgba(255,255,255,${.16 * a})`); g.addColorStop(.5, 'rgba(255,255,255,0)');
+ g.addColorStop(.7, `rgba(0,0,0,${.22 * a})`); g.addColorStop(1, 'rgba(0,0,0,0)');
+ ctx.save(); ctx.beginPath(); ctx.arc(q.x, q.y, r1, 0, TAU); ctx.arc(q.x, q.y, r0, 0, TAU, true); ctx.fillStyle = g; ctx.fill('evenodd'); ctx.restore();
+ }
+ return {
+ name: 'Noodle', blurb: 'A glowing gel puppet held below the screen’s edge. Rendered in Blender; acts out every state.',
+ own: true, modes: ['portrait'], ownsApproval: true, captions: true,
+ captionTop: () => state === 'needs',
+ clockLook: () => n.clip === 'waiting_rest' && frameNo() >= 20 && frameNo() <= 52,
+ hold: { done: 4.4, dizzy: 4.8 },
+ onState(s, prev) {
+ if (s === prev && prev !== null) return;
+ for (const k of [...of(s, 'rest'), ...of(s, 'beat'), ...of(s, 'enter'), ...of(s, 'react'), ...of(s, 'once')]) load(k);
+ if (n.tool && n.tool.phase !== 'fly') Object.assign(n.tool, { phase: 'fly', vx: 60, vy: -200, vr: 3, rot: 0 });
+ if (prev === 'approval' && s === 'done' && variant) return play('approval_allow', { then: ['done_in'] });
+ if (prev === 'approval' && s !== 'approval' && n.card?.phase === 'ride') Object.assign(n.card, { phase: 'drop', vx: -30, vy: 20, vr: -2.4 });
+ const enter = of(s, 'enter');
+ if (prev === 'compacting' && s !== 'compacting') return play('compact_out', { then: enter });
+ if (prev === 'sleep' && s !== 'sleep') {
+ const fr = CL.popup?.frames ?? [], from = Math.max(0, fr.findIndex(r => r[6] >= -2.75));
+ return play('popup', { from, then: enter });
+ }
+ if (s === 'idle' && ['react', 'once'].includes(meta(n.clip)?.role) && n.clip !== 'dizzy') { n.queue = []; return; } // finish the reaction, then idle
+ if (s === 'working') { n.callT = 2.5; n.work = 'work_read'; }
+ if (s === 'dizzy') return play('dizzy');
+ if (enter.length) return play(enter[0]);
+ play(restFor(s));
+ },
+ transition() { if (n.clip !== 'popup') play('popup', { dissolve: false }); },
+ poke() { play('poke'); },
+ pet() { if (n.clip !== 'pet') play('pet'); },
+ react(kind) { play(kind === 'interrupt' ? 'interrupted' : 'oops'); },
+ deny() { play('approval_deny'); },
+ step(dt) {
+ if (n.fade && (n.fade.t += dt) > .15) n.fade = null;
+ n.flex = Math.max(0, n.flex - dt * 9);
+ // holding the card: the hold sequence follows your finger instead of time
+ const holding = state === 'approval' && hold > .02 && meta(n.clip)?.state === 'approval' && ['rest', 'beat'].includes(meta(n.clip)?.role);
+ if (holding !== n.held) { n.fade = { fr: current(), t: 0 }; n.held = holding; }
+ if (!n.held) {
+ const before = n.f; n.f += dt * FPS;
+ const m = meta(n.clip);
+ if (m) {
+ const c = m.n;
+ for (const [kind, at] of Object.entries(m.events ?? {})) for (const f of [].concat(at)) if (before < f && n.f >= f) event(n.clip, kind);
+ if (n.f >= c) {
+ if (n.clip === 'bump' && n.tool) n.work = KIND[n.tool.kind] ?? 'work_read';
+ if (n.clip === 'approval_deny') n.card = null;
+ if (n.clip === 'dizzy' && state === 'dizzy' && !n.queue.length) n.f = c - 1; // it stays shaken off until the state moves on
+ else next();
+ }
+ }
+ }
+ // the work: tool calls land on its head every few seconds
+ if (state === 'working' && n.clip.startsWith('work_') && (n.callT -= dt) <= 0) { n.callT = 3.5 + Math.random() * 3; play('bump', { dissolve: true }); }
+ // effects
+ const a = anchors();
+ n.fog += ((a.press > .9 ? 1 : 0) - n.fog) * Math.min(1, dt * (a.press > .9 ? 3 : .7));
+ if (meta(n.clip)?.state === 'sleep' && ['rest', 'beat'].includes(meta(n.clip)?.role) && (n.zT -= dt) <= 0) { n.zT = 1.5; n.fx.push({ k: 'z', x: a.hx + 14, y: a.hy + 6, t: 0 }); }
+ for (const q of n.fx) { q.t += dt; if (q.vx !== undefined) { q.x += q.vx * dt; q.y += q.vy * dt; q.vy += 260 * dt; q.r += q.vr * dt; } }
+ n.fx = n.fx.filter(q => q.t < (q.k === 'z' ? 2.6 : q.k === 'confetti' ? 1.8 : q.k === 'glass' ? 1.1 : 1.0));
+ for (const c of [n.tool, n.card]) if (c && (c.phase === 'fly' || c.phase === 'drop')) {
+ c.x += c.vx * dt; c.y += c.vy * dt; c.vy += (c.phase === 'drop' ? 900 : 380) * dt; c.rot = (c.rot ?? 0) + c.vr * dt;
+ }
+ if (n.tool && (n.tool.y < 20 || n.tool.y > 300 || n.tool.x > 290)) n.tool = null;
+ if (n.card && (n.card.phase === 'fly' || n.card.phase === 'drop') && (n.card.y < -80 || n.card.y > 340)) n.card = null;
+ if (n.card && n.card.phase !== 'fly' && n.card.phase !== 'drop' && state !== 'approval' && !['approval_allow', 'approval_deny'].includes(n.clip)) n.card = null;
+ },
+ draw(ctx, p) {
+ if (p.thumb) { const s = still(state === 'approval' ? 'working' : state); if (s.complete && s.naturalWidth) ctx.drawImage(s, 0, 0, 198, 242); return; }
+ const blit = (fr, al) => { if (!fr.im.complete || !fr.im.naturalWidth) return; ctx.globalAlpha = al; ctx.drawImage(fr.im, fr.sx, fr.sy, fr.sw, fr.sh, 0, 0, 198, 242); ctx.globalAlpha = 1; };
+ ctx.save(); if (p.ao) ctx.filter = 'grayscale(1) brightness(.45)';
+ // the glass flexes a hair toward you on a knock
+ if (n.flex > 0) { const s = 1 + .012 * n.flex, a = anchors(); ctx.translate(a.fx, a.fy); ctx.scale(s, s); ctx.translate(-a.fx, -a.fy); }
+ if (n.fade) { blit(n.fade.fr, 1); blit(current(), clamp(n.fade.t / .15, 0, 1)); } else blit(current(), 1);
+ ctx.restore();
+ },
+ // what it shares the screen with, drawn over the frame
+ front(ctx) {
+ const a = anchors();
+ // the glass fogs where its face presses, and ripples like liquid glass where it knocks
+ if (n.fog > .02) {
+ const g = ctx.createRadialGradient(a.fx, a.fy + 8, 4, a.fx, a.fy + 8, 78);
+ g.addColorStop(0, `rgba(235,240,245,${.16 * n.fog})`); g.addColorStop(.55, `rgba(235,240,245,${.07 * n.fog})`); g.addColorStop(1, 'rgba(235,240,245,0)');
+ ctx.fillStyle = g; ctx.fillRect(0, 0, 198, 242);
+ }
+ for (const q of n.fx) if (q.k === 'glass') glass(ctx, q);
+ for (const q of n.fx) {
+ if (q.k === 'confetti') { ctx.save(); ctx.globalAlpha = clamp(1.8 - q.t, 0, 1); ctx.translate(q.x, q.y); ctx.rotate(q.r); ctx.fillStyle = q.c; ctx.fillRect(-3, -1.5, 6, 3); ctx.restore(); }
+ if (q.k === 'bonk') { const k = q.t; ctx.strokeStyle = `rgba(255,255,255,${1 - k})`; ctx.lineWidth = 1.6; ctx.lineCap = 'round';
+ for (let i = 0; i < 6; i++) { const th = -Math.PI / 2 + (i - 2.5) * .45, r0 = 8 + k * 10, r1 = 16 + k * 14; ctx.beginPath(); ctx.moveTo(q.x + Math.cos(th) * r0, q.y + Math.sin(th) * r0); ctx.lineTo(q.x + Math.cos(th) * r1, q.y + Math.sin(th) * r1); ctx.stroke(); } }
+ if (q.k === 'z') { ctx.globalAlpha = clamp(1 - q.t / 2.6, 0, 1); ctx.fillStyle = COL.gray; ctx.font = `600 ${10 + q.t * 4}px "Schibsted Grotesk", sans-serif`; ctx.textAlign = 'left'; ctx.fillText('z', q.x + q.t * 9, q.y - q.t * 16); ctx.globalAlpha = 1; }
+ }
+ // compacting: a press comes down onto its hair and holds it squashed; it lifts away when compaction ends
+ if (['compacting_in', 'compacting_rest', 'compact_out'].includes(n.clip)) {
+ const k = n.clip === 'compacting_in' ? clamp(n.f / count('compacting_in'), 0, 1) : n.clip === 'compact_out' ? 1 - clamp(n.f / 8, 0, 1) : 1;
+ const y = lerp(-14, a.hy + 2, outC(k));
+ ctx.fillStyle = '#2A2E33'; ctx.fillRect(95, 30, 8, Math.max(0, y - 40));
+ ctx.fillStyle = '#3A3F46'; roundRect(ctx, 12, y - 10, 174, 10, 3); ctx.fill();
+ ctx.fillStyle = '#5A6069'; ctx.fillRect(14, y - 10, 170, 2);
+ }
+ // a tool call drops on its head and gets bonked off
+ const t = n.tool;
+ if (t) {
+ ctx.font = '500 10.5px "IBM Plex Mono", monospace'; const w = ctx.measureText(t.text).width + 16, h = 20;
+ if (t.phase === 'fall') { const land = [].concat(CL.bump?.events?.land ?? 6)[0], k = clamp(n.f / land, 0, 1); t.x = a.hx; t.y = lerp(36, a.hy + 4, k * k); t.rot = 0; }
+ if (t.phase === 'ride') { t.x = a.hx; t.y = a.hy + 4; t.rot = a.roll * DEG * .5; }
+ card(ctx, t, w, h, () => { ctx.fillStyle = COL.card; roundRect(ctx, 0, 0, w, h, 7); ctx.fill(); ctx.strokeStyle = '#2C3035'; ctx.lineWidth = 1; ctx.stroke();
+ ctx.fillStyle = t.kind === 'run' ? COL.amber : COL.white; ctx.textAlign = 'left'; ctx.fillText(t.text, 8, 14); });
+ }
+ // the approval card rides on its hair; holding pushes it up; allow launches it, deny drops it
+ const c = n.card;
+ if (c) {
+ const w = 152, h = 60;
+ if (c.phase === 'fall') { const land = CL.approval_in?.events?.land ?? 8, k = clamp(n.f / land, 0, 1); c.x = clamp(a.hx, 82, 116); c.y = lerp(38, a.hy + 6, k * k); c.rot = 0; }
+ if (c.phase === 'ride') { c.x = clamp(a.hx, 82, 116); c.y = a.hy + 6; c.rot = a.roll * DEG * .6; }
+ card(ctx, c, w, h, () => {
+ ctx.fillStyle = COL.card; roundRect(ctx, 0, 0, w, h, 13); ctx.fill(); ctx.strokeStyle = '#2C3035'; ctx.lineWidth = 1; ctx.stroke();
+ ctx.textAlign = 'left'; ctx.fillStyle = COL.white; ctx.font = '500 14px "IBM Plex Mono", monospace'; ctx.fillText('rm -rf build', 12, 22);
+ ctx.fillStyle = hold > 0 ? COL.amber : COL.gray; ctx.font = '500 10.5px "IBM Plex Mono", monospace'; ctx.fillText(hold > 0 ? 'keep holding' : 'hold to allow', 12, 39);
+ ctx.fillStyle = '#26292D'; roundRect(ctx, 12, 47, w - 24, 3, 1.5); ctx.fill();
+ if (hold > 0) { ctx.fillStyle = COL.amber; roundRect(ctx, 12, 47, (w - 24) * hold, 3, 1.5); ctx.fill(); }
+ });
+ if (state === 'approval') {
+ ctx.fillStyle = '#1A1C1F'; ctx.beginPath(); ctx.arc(36, 210, 13, 0, TAU); ctx.fill();
+ ctx.strokeStyle = COL.gray; ctx.lineWidth = 1.8; ctx.lineCap = 'round'; ctx.beginPath(); ctx.moveTo(31.5, 205.5); ctx.lineTo(40.5, 214.5); ctx.moveTo(40.5, 205.5); ctx.lineTo(31.5, 214.5); ctx.stroke();
+ }
+ }
+ },
+ hit: pt => { const a = anchors(); return Math.hypot((pt.x - a.fx) / 56, (pt.y - (a.fy - 24)) / 64) < 1; },
+ extents: { hx: 50, top: 60, bottom: 60 },
+ preload() { for (const k of [...of('idle', 'rest'), ...of('idle', 'beat'), 'popup', 'poke', 'pet']) load(k); },
+ debug: () => ({ clip: n.clip, frame: frameNo(), held: n.held, loaded: Object.values(pages).filter(im => im.complete && im.naturalWidth).length }),
+ };
+ })();
diff --git a/design/noodle/renders/clips.json b/design/noodle/renders/clips.json
new file mode 100644
index 0000000..5cc90d7
--- /dev/null
+++ b/design/noodle/renders/clips.json
@@ -0,0 +1 @@
+{"fps":24,"clips":{"idle_rest":{"n":144,"loop":true,"scrub":false,"events":{},"role":"rest","state":"idle","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.3,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.5,96.3,120.5,-0.1,0.0,0.0],[119.5,37.3,96.6,120.3,-0.1,0.0,0.0],[119.9,37.0,96.7,120.2,-0.1,0.0,0.0],[119.0,36.8,96.8,120.1,0.0,0.0,0.0],[119.4,36.5,96.9,120.0,-0.1,0.0,0.0],[118.9,36.3,97.1,119.8,-0.1,0.0,0.0],[118.9,36.1,97.2,119.7,0.0,0.0,0.0],[119.2,35.8,97.3,119.6,0.0,0.0,0.0],[119.2,35.6,97.4,119.5,0.0,0.0,0.0],[118.8,35.5,97.5,119.4,0.0,0.0,0.0],[118.9,35.3,97.6,119.3,0.0,0.0,0.0],[118.9,35.1,97.7,119.2,0.0,0.0,0.0],[118.9,35.0,97.8,119.2,-0.1,0.0,0.0],[118.9,34.9,97.8,119.1,0.0,0.0,0.0],[119.0,34.8,97.7,119.0,-0.1,0.0,0.0],[118.9,34.7,97.5,119.0,0.0,0.0,0.0],[119.0,34.7,97.5,119.0,0.0,0.0,0.0],[119.7,34.6,97.3,119.0,0.0,0.0,0.0],[120.1,34.6,97.1,119.0,0.0,0.0,0.0],[120.5,34.6,96.9,119.0,0.0,0.0,0.0],[120.5,34.6,96.7,119.0,0.1,0.0,0.0],[120.6,34.7,96.5,119.1,0.0,0.0,0.0],[120.7,34.7,96.2,119.2,0.1,0.0,0.0],[120.9,34.8,96.0,119.2,0.0,0.0,0.0],[121.6,34.9,95.8,119.3,0.0,0.0,0.0],[121.3,35.1,95.7,119.4,0.0,0.0,0.0],[122.0,35.2,95.5,119.5,0.0,0.0,0.0],[122.0,35.4,95.5,119.6,0.0,0.0,0.0],[122.0,35.6,95.5,119.7,0.0,0.0,0.0],[121.7,35.9,95.3,119.8,0.1,0.0,0.0],[121.9,36.1,95.3,120.0,0.1,0.0,0.0],[122.0,36.4,95.3,120.1,0.0,0.0,0.0],[121.6,36.7,95.3,120.2,0.1,0.0,0.0],[121.6,37.0,95.2,120.4,0.0,0.0,0.0],[121.9,37.2,95.2,120.5,0.1,0.0,0.0],[122.0,37.5,95.2,120.7,0.0,0.0,0.0],[122.0,37.8,95.2,120.8,0.1,0.0,0.0],[121.9,38.1,95.2,121.0,0.1,0.0,0.0],[121.6,38.4,95.2,121.2,0.1,0.0,0.0],[121.3,38.7,95.1,121.2,0.1,0.0,0.0],[121.9,38.9,95.1,121.4,0.0,0.0,0.0],[121.3,39.2,95.1,121.5,0.1,0.0,0.0],[120.7,39.5,95.2,121.7,0.1,0.0,0.0],[121.1,39.7,95.2,121.8,0.0,0.0,0.0],[121.3,39.9,95.2,121.9,0.0,0.0,0.0],[120.9,40.1,95.3,122.0,0.0,0.0,0.0],[120.8,40.3,95.4,122.1,0.0,0.0,0.0],[120.7,40.5,95.5,122.2,0.1,0.0,0.0],[120.8,40.7,95.5,122.2,0.0,0.0,0.0],[120.7,40.8,95.7,122.3,0.0,0.0,0.0],[120.7,40.9,95.8,122.3,0.0,0.0,0.0],[120.4,41.0,95.9,122.3,0.1,0.0,0.0],[119.7,41.1,96.0,122.4,0.0,0.0,0.0],[119.6,41.1,96.2,122.4,0.0,0.0,0.0],[119.6,41.1,96.3,122.4,0.0,0.0,0.0],[119.5,41.1,96.6,122.3,0.1,0.0,0.0],[119.3,41.1,96.8,122.3,0.0,0.0,0.0],[119.3,41.0,96.9,122.3,0.0,0.0,0.0],[118.9,41.0,97.2,122.2,0.0,0.0,0.0],[118.9,40.9,97.3,122.2,0.0,0.0,0.0],[118.6,40.8,97.6,122.1,0.0,0.0,0.0],[118.5,40.6,97.8,122.0,0.0,0.0,0.0],[118.2,40.5,98.0,121.9,0.0,0.0,0.0],[118.2,40.3,98.2,121.8,0.0,0.0,0.0],[118.1,40.1,98.4,121.7,0.0,0.0,0.0],[117.7,39.9,98.7,121.5,0.0,0.0,0.0],[117.6,39.7,98.9,121.4,0.0,0.0,0.0],[116.9,39.5,99.2,121.3,0.0,0.0,0.0],[116.9,39.2,99.4,121.1,0.0,0.0,0.0],[116.7,39.0,99.6,121.0,0.0,0.0,0.0],[116.6,38.7,99.8,120.8,0.0,0.0,0.0],[116.5,38.5,100.0,120.7,0.0,0.0,0.0],[116.5,38.2,100.2,120.5,0.0,0.0,0.0],[116.5,37.9,100.4,120.4,0.0,0.0,0.0],[116.1,37.7,100.6,120.2,0.0,0.0,0.0],[116.0,37.4,100.8,120.1,0.0,0.0,0.0],[116.1,37.2,100.9,120.0,0.0,0.0,0.0],[115.8,37.0,101.1,119.8,0.0,0.0,0.0],[115.9,36.7,101.2,119.7,0.0,0.0,0.0],[115.8,36.5,101.3,119.6,0.0,0.0,0.0],[115.8,36.3,101.5,119.5,0.0,0.0,0.0],[115.8,36.1,101.5,119.4,0.0,0.0,0.0],[115.2,36.0,101.6,119.3,0.0,0.0,0.0],[115.5,35.8,101.7,119.2,0.0,0.0,0.0],[115.3,35.7,101.8,119.1,0.0,0.0,0.0],[115.1,35.6,101.8,119.1,0.0,0.0,0.0],[115.4,35.5,101.8,119.0,0.0,0.0,0.0],[115.6,35.4,101.8,119.0,0.0,0.0,0.0],[115.4,35.4,101.8,119.0,0.0,0.0,0.0],[115.7,35.3,101.8,119.0,0.0,0.0,0.0],[115.6,35.3,101.8,119.0,0.0,0.0,0.0],[115.6,35.4,101.8,119.0,0.0,0.0,0.0],[115.6,35.4,101.7,119.0,-0.1,0.0,0.0],[115.5,35.5,101.7,119.1,0.0,0.0,0.0],[115.6,35.6,101.6,119.2,-0.1,0.0,0.0],[115.6,35.7,101.5,119.2,0.0,0.0,0.0],[115.9,35.8,101.5,119.3,0.0,0.0,0.0],[115.8,36.0,101.3,119.4,0.0,0.0,0.0],[115.9,36.2,101.2,119.5,0.0,0.0,0.0],[115.8,36.4,101.2,119.6,0.0,0.0,0.0],[115.9,36.6,101.0,119.7,0.0,0.0,0.0],[115.9,36.8,100.8,119.8,-0.1,0.0,0.0],[116.2,37.0,100.7,120.0,-0.1,0.0,0.0],[116.8,37.2,100.3,120.1,0.0,0.0,0.0],[116.7,37.5,100.1,120.2,-0.1,0.0,0.0],[117.1,37.7,99.8,120.3,-0.1,0.0,0.0],[116.8,38.0,99.5,120.5,-0.1,0.0,0.0],[117.4,38.2,99.2,120.7,-0.1,0.0,0.0],[117.5,38.4,98.8,120.8,-0.1,0.0,0.0],[118.0,38.6,98.5,121.0,-0.1,0.0,0.0],[118.1,38.9,98.1,121.2,-0.1,0.0,0.0],[118.3,39.1,97.7,121.2,-0.1,0.0,0.0],[118.3,39.3,97.3,121.4,-0.3,0.0,0.0],[118.8,39.5,96.9,121.5,-0.1,0.0,0.0],[119.4,39.7,96.5,121.7,-0.1,0.0,0.0],[119.7,39.8,96.2,121.8,-0.3,0.0,0.0],[119.7,40.0,95.8,121.9,-0.3,0.0,0.0],[120.3,40.1,95.5,122.0,-0.3,0.0,0.0],[119.9,40.3,95.3,122.1,-0.3,0.0,0.0],[120.4,40.4,95.0,122.2,-0.3,0.0,0.0],[120.9,40.5,94.9,122.2,-0.3,0.0,0.0],[121.0,40.6,94.7,122.3,-0.3,0.0,0.0],[121.0,40.6,94.6,122.3,-0.3,0.0,0.0],[121.1,40.7,94.5,122.4,-0.3,0.0,0.0],[121.1,40.7,94.4,122.4,-0.3,0.0,0.0],[121.1,40.7,94.4,122.4,-0.3,0.0,0.0],[121.1,40.7,94.4,122.4,-0.3,0.0,0.0],[121.2,40.7,94.4,122.4,-0.3,0.0,0.0],[121.1,40.7,94.5,122.3,-0.3,0.0,0.0],[121.1,40.6,94.6,122.3,-0.3,0.0,0.0],[121.0,40.5,94.7,122.2,-0.3,0.0,0.0],[120.5,40.4,94.8,122.2,-0.3,0.0,0.0],[120.1,40.3,94.8,122.1,-0.3,0.0,0.0],[120.6,40.1,94.9,122.0,-0.3,0.0,0.0],[120.6,39.9,95.1,121.9,-0.3,0.0,0.0],[120.1,39.8,95.2,121.8,-0.3,0.0,0.0],[120.1,39.6,95.3,121.7,-0.1,0.0,0.0],[120.2,39.3,95.4,121.5,-0.1,0.0,0.0],[120.2,39.1,95.6,121.4,-0.3,0.0,0.0],[120.2,38.9,95.7,121.2,-0.1,0.0,0.0],[120.2,38.6,95.8,121.2,-0.1,0.0,0.0],[120.2,38.3,95.9,121.0,-0.1,0.0,0.0],[120.3,38.1,96.1,120.8,-0.1,0.0,0.0]]},"idle_look":{"n":96,"loop":false,"scrub":false,"events":{},"role":"beat","state":"idle","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.6,96.2,120.5,-0.1,0.0,0.0],[120.1,37.4,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.9,96.2,120.2,-0.1,0.0,0.0],[120.1,36.7,96.2,120.2,-0.1,0.0,0.0],[120.2,36.5,96.2,120.0,-0.1,0.0,0.0],[120.2,36.3,96.2,120.0,-0.1,0.0,0.0],[120.2,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[122.4,33.8,94.0,119.2,-0.3,0.0,0.0],[126.9,29.9,89.3,118.0,-0.7,0.0,0.0],[126.6,27.2,85.6,117.2,-1.3,0.0,0.0],[125.5,24.5,82.8,116.5,-1.5,0.0,0.0],[124.7,22.8,80.7,116.0,-2.0,0.0,0.0],[124.5,22.1,79.2,115.5,-2.3,0.0,0.0],[123.9,21.4,78.2,115.2,-2.6,0.0,0.0],[122.9,21.3,77.5,114.9,-2.9,0.0,0.0],[122.0,21.7,77.2,114.8,-3.0,0.0,0.0],[122.0,22.3,77.0,114.7,-3.0,0.01,0.0],[122.8,23.0,77.0,114.7,-2.7,0.01,0.0],[123.3,23.5,77.3,114.7,-2.7,0.01,0.0],[123.7,23.8,77.5,114.7,-2.9,0.01,0.0],[123.7,23.9,77.8,114.8,-2.6,0.02,0.0],[123.8,23.8,78.2,114.8,-2.8,0.02,0.0],[123.5,23.5,78.4,114.8,-2.5,0.02,0.0],[123.2,23.0,78.5,114.8,-2.5,0.03,0.0],[123.8,22.5,78.5,114.8,-2.5,0.03,0.0],[124.4,22.0,78.5,114.8,-2.5,0.03,0.0],[124.5,21.7,78.5,114.8,-2.5,0.04,0.0],[124.4,21.5,78.5,114.8,-2.5,0.04,0.0],[124.5,21.5,78.5,114.9,-2.5,0.05,0.0],[124.5,21.6,78.6,114.9,-2.5,0.05,0.0],[124.6,21.8,78.7,115.1,-2.3,0.06,0.0],[124.7,22.2,78.8,115.2,-2.2,0.06,0.0],[124.4,22.7,79.0,115.3,-2.4,0.07,0.0],[124.4,23.2,79.2,115.5,-2.2,0.07,0.0],[124.5,23.7,79.5,115.7,-2.2,0.08,0.0],[124.9,24.2,79.7,116.0,-2.0,0.08,0.0],[124.9,24.7,80.0,116.2,-2.1,0.09,0.0],[125.3,25.2,80.3,116.5,-1.9,0.09,0.0],[125.4,25.8,80.7,116.8,-1.9,0.1,0.0],[125.6,26.3,81.0,117.0,-1.7,0.1,0.0],[125.8,26.8,81.4,117.3,-1.5,0.1,0.0],[125.9,27.4,81.9,117.7,-1.5,0.11,0.0],[126.1,27.9,82.2,118.0,-1.4,0.11,0.0],[126.2,28.5,82.7,118.3,-1.3,0.12,0.0],[126.3,29.0,83.1,118.6,-1.2,0.12,0.0],[126.7,29.6,83.5,118.9,-1.2,0.12,0.0],[126.8,30.1,83.8,119.2,-1.1,0.12,0.0],[126.9,30.6,84.1,119.4,-1.1,0.13,0.0],[126.6,31.0,84.5,119.7,-0.9,0.13,0.0],[127.0,31.5,84.7,119.9,-1.0,0.13,0.0],[127.0,31.8,84.9,120.2,-1.0,0.13,0.0],[127.0,32.2,85.1,120.3,-1.0,0.13,0.0],[127.0,32.5,85.2,120.5,-0.9,0.13,0.0],[126.9,32.8,85.3,120.7,-0.9,0.13,0.0],[126.8,33.0,85.3,120.8,-0.9,0.13,0.0],[126.8,33.2,85.4,120.9,-0.9,0.13,0.0],[126.8,33.4,85.4,121.0,-0.9,0.13,0.0],[126.9,33.5,85.4,121.1,-0.9,0.13,0.0],[126.8,33.7,85.4,121.2,-0.7,0.13,0.0],[126.7,33.9,85.3,121.2,-0.7,0.13,0.0],[126.9,34.0,85.3,121.3,-0.9,0.13,0.0],[126.9,34.2,85.3,121.3,-0.7,0.13,0.0],[126.9,34.3,85.3,121.5,-0.7,0.13,0.0],[127.0,34.4,85.3,121.5,-0.7,0.13,0.0],[127.0,34.5,85.3,121.5,-0.9,0.13,0.0],[127.0,34.6,85.3,121.5,-0.7,0.13,0.0],[126.8,34.6,85.3,121.5,-0.7,0.13,0.0],[126.8,34.7,85.3,121.6,-0.9,0.13,0.0],[126.7,34.8,85.5,121.7,-0.7,0.13,0.0],[126.9,35.2,86.0,121.7,-0.7,0.13,0.0],[126.6,35.9,86.9,121.8,-0.7,0.11,0.0],[125.5,36.8,88.2,121.8,-0.6,0.1,0.0],[124.3,37.9,89.8,121.9,-0.6,0.08,0.0],[122.0,39.0,91.4,121.9,-0.4,0.06,0.0],[120.1,40.0,93.1,122.1,-0.3,0.04,0.0],[118.4,40.7,94.4,122.1,-0.3,0.02,0.0],[118.0,41.0,95.4,122.2,-0.1,0.01,0.0],[117.9,41.0,96.0,122.2,-0.1,0.0,0.0],[118.7,40.7,96.2,122.2,-0.1,0.0,0.0],[119.4,40.3,96.2,122.0,-0.1,0.0,0.0],[119.9,40.0,96.2,122.0,-0.1,0.0,0.0],[120.0,39.7,96.2,121.8,-0.1,0.0,0.0],[120.1,39.5,96.2,121.8,-0.1,0.0,0.0],[120.3,39.3,96.2,121.8,-0.1,0.0,0.0],[120.6,39.2,96.2,121.7,-0.1,0.0,0.0],[120.9,39.1,96.2,121.5,-0.1,0.0,0.0],[120.8,39.0,96.2,121.5,-0.1,0.0,0.0],[120.3,38.9,96.2,121.3,-0.1,0.0,0.0],[120.3,38.8,96.2,121.2,-0.1,0.0,0.0],[119.6,38.7,96.2,121.2,-0.1,0.0,0.0],[119.3,38.5,96.2,121.0,-0.1,0.0,0.0],[119.3,38.3,96.2,121.0,-0.1,0.0,0.0],[119.3,38.1,96.2,120.8,-0.3,0.0,0.0]]},"idle_shake":{"n":77,"loop":false,"scrub":false,"events":{},"role":"beat","state":"idle","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.5,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.2,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.1,0.0,0.0],[120.1,36.5,96.2,120.0,-0.1,0.0,0.0],[120.2,36.2,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.5,96.2,119.5,-0.1,0.0,0.0],[120.2,35.2,96.3,119.5,-0.1,0.0,0.0],[120.8,38.2,98.0,122.5,-0.1,0.0,0.0],[117.1,45.8,102.3,127.8,-0.3,0.0,0.0],[114.9,51.6,106.7,129.9,-0.4,0.0,0.0],[112.9,50.8,112.3,127.4,-0.5,0.0,0.0],[113.4,48.9,121.3,124.6,-0.4,0.0,0.0],[109.3,44.1,121.4,122.0,0.0,0.0,0.0],[95.7,38.2,100.4,119.4,0.0,0.0,0.0],[85.2,38.0,77.5,117.7,-0.7,0.0,0.0],[99.5,29.5,77.8,115.8,-0.9,0.0,0.0],[131.9,16.7,100.1,114.0,0.1,0.0,0.0],[134.8,13.9,118.8,113.0,1.0,0.0,0.0],[126.1,14.5,116.8,111.8,1.0,0.0,0.0],[120.8,9.9,94.2,110.6,-0.3,0.0,0.0],[106.2,13.1,80.0,110.2,-1.2,0.0,0.0],[118.6,9.7,83.3,109.5,-1.1,0.0,0.0],[122.5,12.6,103.5,109.0,0.3,0.0,0.0],[120.5,14.3,113.6,108.9,1.0,0.0,0.0],[117.1,15.1,109.8,108.7,0.6,0.0,0.0],[112.7,11.9,95.1,108.7,-0.1,0.0,0.0],[107.8,12.6,89.5,108.8,-0.6,0.0,0.0],[114.6,11.2,92.5,109.0,-0.3,0.0,0.0],[120.3,11.9,100.8,109.2,0.1,0.0,0.0],[121.7,12.8,103.2,109.6,0.3,0.0,0.0],[121.8,13.1,102.0,110.0,0.1,0.0,0.0],[122.2,13.3,99.5,110.3,0.1,0.0,0.0],[121.6,14.3,99.0,110.8,0.0,0.0,0.0],[121.6,15.4,99.0,111.2,0.0,0.0,0.0],[121.6,16.4,99.0,111.6,0.0,0.0,0.0],[121.7,17.4,99.0,112.0,0.0,0.0,0.0],[121.3,18.2,99.0,112.3,0.0,0.0,0.0],[121.2,18.8,99.0,112.6,0.0,0.0,0.0],[121.3,19.2,99.0,112.7,0.0,0.0,0.0],[121.5,19.4,99.0,112.9,0.0,0.0,0.0],[121.6,19.6,99.0,113.0,0.0,0.0,0.0],[121.6,19.8,99.0,113.1,0.0,0.0,0.0],[121.1,20.0,99.0,113.3,0.0,0.0,0.0],[120.7,20.2,99.0,113.4,0.0,0.0,0.0],[121.0,20.4,99.0,113.5,0.0,0.0,0.0],[121.3,20.6,99.0,113.6,0.0,0.0,0.0],[121.4,20.8,99.0,113.7,0.0,0.0,0.0],[121.4,21.0,99.0,113.8,0.0,0.0,0.0],[121.3,21.2,99.0,113.8,0.0,0.0,0.0],[121.3,21.3,99.0,113.9,0.0,0.0,0.0],[121.3,21.4,99.0,114.0,0.0,0.0,0.0],[121.3,21.5,99.0,114.0,0.0,0.0,0.0],[121.3,21.7,99.0,114.1,0.0,0.0,0.0],[120.6,23.2,98.8,114.9,0.0,0.0,0.0],[120.1,26.4,98.2,116.5,0.0,0.0,0.0],[119.0,31.0,97.5,118.7,-0.1,0.0,0.0],[118.7,35.7,96.8,120.6,0.0,0.0,0.0],[118.7,39.4,96.4,121.8,-0.1,0.0,0.0],[118.8,41.4,96.2,122.2,-0.1,0.0,0.0],[119.0,42.2,96.2,122.2,-0.1,0.0,0.0],[119.6,42.4,96.2,122.2,-0.1,0.0,0.0],[120.2,42.0,96.2,122.0,-0.1,0.0,0.0],[120.4,41.3,96.2,122.0,-0.1,0.0,0.0],[120.4,40.4,96.2,122.0,-0.1,0.0,0.0],[120.4,39.7,96.2,121.8,-0.1,0.0,0.0],[120.5,39.1,96.2,121.8,-0.1,0.0,0.0],[120.4,38.8,96.2,121.5,-0.1,0.0,0.0],[119.8,38.7,96.2,121.5,-0.1,0.0,0.0],[120.1,38.6,96.2,121.3,-0.1,0.0,0.0],[119.5,38.7,96.2,121.2,-0.1,0.0,0.0],[120.0,38.6,96.2,121.0,-0.1,0.0,0.0],[120.0,38.5,96.2,121.0,-0.1,0.0,0.0],[120.0,38.3,96.2,120.8,-0.3,0.0,0.0]]},"idle_sideeye":{"n":86,"loop":false,"scrub":false,"events":{},"role":"beat","state":"idle","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.5,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.3,0.0,0.0],[120.1,36.6,96.2,120.0,-0.1,0.0,0.0],[120.1,36.3,96.2,120.0,-0.1,0.0,0.0],[120.0,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.5,96.2,119.5,-0.1,0.0,0.0],[120.1,35.4,96.3,119.5,-0.1,0.0,0.0],[119.2,35.4,96.7,119.3,-0.1,0.0,0.0],[118.7,35.5,97.3,119.3,0.0,0.0,0.0],[117.2,35.8,98.3,119.2,0.0,0.0,0.0],[115.8,36.2,99.7,119.2,0.0,0.0,0.0],[114.0,36.6,101.3,119.2,0.1,0.0,0.0],[112.7,37.1,103.2,119.1,0.3,0.0,0.0],[111.8,37.5,105.2,119.1,0.4,0.0,0.0],[111.1,37.9,107.1,119.1,0.6,0.0,0.0],[110.3,37.8,108.8,119.0,0.7,0.0,0.0],[109.7,37.7,110.5,119.1,0.9,0.0,0.0],[109.3,37.6,111.6,119.1,0.9,0.0,0.0],[108.8,37.6,112.6,119.2,1.1,0.0,0.0],[108.7,37.5,113.1,119.2,1.1,0.0,0.0],[108.9,37.2,113.5,119.2,1.3,0.0,0.0],[108.6,36.9,113.5,119.2,1.1,0.0,0.0],[108.8,36.8,113.5,119.2,1.1,0.0,0.0],[109.3,36.8,113.5,119.3,1.1,0.0,0.0],[109.1,37.0,113.5,119.3,1.1,0.0,0.0],[109.1,37.3,113.5,119.4,1.1,0.0,0.0],[109.3,37.6,113.5,119.6,1.1,0.0,0.0],[109.4,37.9,113.5,119.6,1.3,0.0,0.0],[109.5,38.3,113.5,119.7,1.1,0.0,0.0],[109.2,38.6,113.5,119.8,1.1,0.0,0.0],[108.9,38.9,113.5,119.8,1.1,0.0,0.0],[109.0,39.1,113.5,119.9,1.1,0.0,0.0],[108.7,39.4,113.6,120.1,1.1,0.0,0.0],[108.7,39.6,113.6,120.2,1.1,0.0,0.0],[108.8,39.7,113.6,120.3,1.1,0.0,0.0],[108.9,39.9,113.6,120.4,1.1,0.0,0.0],[108.9,40.1,113.6,120.6,1.1,0.0,0.0],[109.0,40.3,113.6,120.7,1.1,0.0,0.0],[109.1,40.5,113.6,120.8,1.0,0.0,0.0],[109.1,40.7,113.6,120.9,1.1,0.0,0.0],[109.3,40.9,113.6,121.1,1.1,0.0,0.0],[109.4,41.1,113.6,121.2,1.1,0.0,0.0],[109.0,41.4,113.6,121.3,1.0,0.0,0.0],[109.2,41.6,113.6,121.4,1.0,0.0,0.0],[109.3,41.8,113.7,121.5,0.9,0.0,0.0],[109.0,42.1,113.7,121.6,0.9,0.0,0.0],[109.0,42.3,113.7,121.8,1.1,0.0,0.0],[108.9,42.5,113.7,121.8,1.1,0.0,0.0],[108.9,42.7,113.7,121.9,0.9,0.0,0.0],[109.1,42.8,113.7,122.0,0.9,0.0,0.0],[108.9,43.0,113.7,122.1,0.9,0.0,0.0],[109.1,43.1,113.7,122.2,0.9,0.0,0.0],[108.8,43.3,113.7,122.2,1.1,0.0,0.0],[108.8,43.4,113.7,122.3,0.9,0.0,0.0],[108.8,43.5,113.7,122.4,0.9,0.0,0.0],[108.8,43.6,113.7,122.4,0.9,0.0,0.0],[109.1,43.6,113.7,122.4,1.1,0.0,0.0],[108.9,43.7,113.7,122.5,0.9,0.0,0.0],[109.1,43.7,113.7,122.5,0.9,0.0,0.0],[109.1,43.7,113.7,122.5,0.9,0.0,0.0],[108.8,43.8,113.7,122.5,0.9,0.0,0.0],[109.4,43.5,113.2,122.5,0.9,0.0,0.0],[110.5,42.5,110.9,122.5,0.7,0.0,0.0],[114.2,41.1,107.1,122.4,0.6,0.0,0.0],[116.5,39.8,102.5,122.3,0.3,0.0,0.0],[122.1,39.0,98.7,122.3,0.0,0.0,0.0],[123.9,38.7,96.7,122.2,-0.1,0.0,0.0],[122.1,39.2,96.2,122.2,-0.1,0.0,0.0],[122.2,39.8,96.2,122.0,-0.1,0.0,0.0],[120.1,40.5,96.2,122.0,-0.1,0.0,0.0],[118.3,40.9,96.2,122.0,-0.1,0.0,0.0],[117.0,41.1,96.2,121.8,-0.1,0.0,0.0],[116.3,41.1,96.2,121.8,-0.1,0.0,0.0],[116.4,40.8,96.2,121.7,-0.1,0.0,0.0],[116.2,40.5,96.2,121.5,-0.1,0.0,0.0],[117.2,40.0,96.2,121.5,-0.1,0.0,0.0],[118.2,39.5,96.2,121.3,-0.1,0.0,0.0],[118.8,39.0,96.2,121.2,-0.1,0.0,0.0],[119.8,38.6,96.2,121.2,-0.1,0.0,0.0],[119.8,38.2,96.2,121.0,-0.1,0.0,0.0],[120.6,37.8,96.2,120.8,-0.1,0.0,0.0]]},"idle_yawn":{"n":86,"loop":false,"scrub":false,"events":{},"role":"beat","state":"idle","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.9,96.2,120.8,-0.1,0.0,0.0],[120.4,38.6,96.3,121.3,0.0,0.0,0.0],[120.6,39.7,96.6,122.2,-0.1,0.0,0.0],[120.7,41.4,96.8,123.2,0.0,0.0,0.01],[119.9,43.5,97.1,124.4,0.0,0.0,0.01],[119.9,45.7,97.5,125.4,0.0,0.0,0.02],[119.5,47.6,97.8,126.0,0.1,0.0,0.02],[118.8,49.1,98.1,126.2,0.0,0.0,0.03],[118.0,49.9,98.2,125.8,0.1,0.0,0.04],[116.7,50.2,98.3,124.8,0.1,0.0,0.05],[115.3,50.0,98.4,123.5,0.1,0.0,0.06],[114.7,49.5,98.5,122.0,0.0,0.0,0.07],[113.9,48.3,98.5,120.0,0.0,0.0,0.09],[113.7,45.8,98.7,117.3,0.0,0.0,0.1],[114.9,42.1,98.7,113.9,0.0,0.0,0.11],[113.8,37.4,98.8,109.8,0.0,0.0,0.12],[112.6,32.0,98.8,105.3,0.0,0.0,0.13],[110.3,26.0,98.9,100.5,-0.1,0.0,0.14],[109.0,19.6,98.9,95.5,-0.1,0.0,0.15],[109.1,13.2,98.9,90.8,0.0,0.0,0.16],[109.1,7.2,98.9,86.5,0.0,0.0,0.17],[108.9,1.9,98.9,82.7,0.0,0.0,0.17],[108.9,-2.5,99.0,79.7,0.0,0.0,0.18],[108.9,-5.7,99.0,77.6,0.0,0.0,0.18],[108.9,-7.7,99.0,76.2,0.0,0.0,0.18],[108.8,-8.5,99.0,75.6,0.0,0.0,0.18],[108.8,-8.5,99.0,75.5,0.0,0.0,0.18],[108.6,-8.1,99.0,75.5,0.0,0.0,0.18],[108.7,-7.7,99.0,75.5,0.0,0.0,0.18],[108.6,-7.2,99.0,75.5,0.0,0.0,0.18],[108.5,-6.9,99.0,75.5,0.0,0.0,0.18],[108.5,-6.8,99.0,75.5,0.0,0.0,0.18],[108.6,-6.9,99.0,75.5,0.0,0.0,0.18],[108.5,-7.1,99.0,75.5,0.0,0.0,0.18],[108.6,-7.3,99.0,75.5,0.0,0.0,0.18],[108.6,-7.5,99.0,75.5,0.0,0.0,0.18],[108.6,-7.6,99.0,75.5,0.0,0.0,0.18],[108.6,-7.4,99.0,75.5,0.0,0.0,0.18],[109.6,9.2,99.0,96.3,0.0,0.0,0.11],[109.9,26.0,99.0,112.1,0.0,0.0,0.06],[114.4,39.0,98.9,123.2,0.0,0.0,0.02],[115.1,48.9,98.9,130.3,0.0,0.0,-0.01],[120.5,54.4,98.8,134.0,0.0,0.0,-0.02],[121.0,57.4,98.8,135.1,0.0,0.0,-0.02],[121.7,56.9,98.7,134.4,0.0,0.0,-0.02],[121.7,54.7,98.6,132.6,0.0,0.0,-0.01],[122.4,50.6,98.4,130.5,0.0,0.0,-0.01],[124.2,46.5,98.3,128.8,0.0,0.0,-0.0],[125.4,44.1,98.2,128.2,0.0,0.0,0.0],[125.2,43.4,98.0,128.1,-0.1,0.0,0.0],[120.7,43.6,97.8,127.8,-0.1,0.0,0.0],[118.5,44.1,97.7,127.2,-0.1,0.0,0.0],[117.2,44.4,97.4,126.5,0.0,0.0,0.0],[117.6,44.3,97.2,125.7,-0.1,0.0,0.0],[117.8,43.8,97.0,124.7,-0.1,0.0,0.0],[118.8,42.8,96.8,123.7,-0.1,0.0,0.0],[118.8,41.5,96.6,122.7,-0.1,0.0,0.0],[120.2,40.0,96.5,121.8,-0.1,0.0,0.0],[121.8,38.6,96.3,121.2,-0.1,0.0,0.0],[121.4,37.6,96.3,120.8,-0.1,0.0,0.0],[121.1,37.0,96.2,120.8,-0.1,0.0,0.0],[121.3,36.8,96.2,120.7,-0.1,0.0,0.0],[120.4,37.0,96.2,120.7,-0.1,0.0,0.0],[120.2,37.2,96.2,120.7,-0.1,0.0,0.0],[119.9,37.6,96.2,120.7,-0.1,0.0,0.0],[119.7,37.9,96.2,120.7,-0.1,0.0,0.0],[119.5,38.1,96.2,120.7,-0.1,0.0,0.0],[119.9,38.1,96.2,120.7,-0.1,0.0,0.0],[120.0,38.1,96.2,120.7,-0.1,0.0,0.0],[120.0,38.0,96.2,120.7,-0.1,0.0,0.0],[120.2,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.6,96.2,120.7,-0.1,0.0,0.0],[120.2,37.6,96.2,120.7,-0.1,0.0,0.0],[120.2,37.6,96.2,120.7,-0.1,0.0,0.0]]},"idle_hum":{"n":86,"loop":false,"scrub":false,"events":{},"role":"beat","state":"idle","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.6,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.3,0.0,0.0],[120.1,36.6,96.2,120.0,-0.1,0.0,0.0],[120.1,36.3,96.2,120.0,-0.1,0.0,0.0],[120.0,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.5,96.2,119.5,-0.1,0.0,0.0],[120.4,35.3,96.5,119.5,-0.1,0.0,0.0],[120.4,35.2,97.4,119.3,-0.1,0.0,0.0],[120.5,35.2,98.9,119.3,0.0,0.0,0.0],[119.6,35.3,100.8,119.2,0.1,0.0,0.0],[118.5,35.5,103.0,119.2,0.3,0.0,0.0],[116.7,35.7,104.8,119.2,0.4,0.0,0.0],[114.4,36.0,106.2,119.2,0.4,0.0,0.0],[111.9,36.3,106.9,119.1,0.4,0.0,0.0],[110.6,36.5,107.0,119.1,0.4,0.0,0.0],[109.6,36.6,107.0,119.1,0.4,0.0,0.0],[109.1,36.6,106.7,119.1,0.4,0.0,0.0],[109.3,36.5,105.7,119.1,0.4,0.0,0.0],[109.8,36.3,104.1,119.0,0.3,0.0,0.0],[110.4,36.1,102.0,119.0,0.1,0.0,0.0],[112.9,35.7,99.5,119.0,0.0,0.0,0.0],[115.4,35.3,97.0,119.0,-0.1,0.0,0.0],[119.3,34.8,94.7,119.1,-0.3,0.0,0.0],[121.2,34.3,92.9,119.2,-0.3,0.0,0.0],[124.7,33.8,91.7,119.2,-0.4,0.0,0.0],[126.4,33.5,91.1,119.3,-0.4,0.0,0.0],[126.9,33.4,91.0,119.4,-0.6,0.0,0.0],[126.9,33.5,91.0,119.5,-0.6,0.0,0.0],[127.0,33.8,91.3,119.6,-0.4,0.0,0.0],[126.8,34.2,92.3,119.7,-0.4,0.0,0.0],[125.4,34.7,93.9,119.7,-0.3,0.0,0.0],[123.7,35.4,96.0,119.8,-0.1,0.0,0.0],[122.2,36.1,98.5,120.0,-0.1,0.0,0.0],[119.3,36.9,101.1,120.0,0.1,0.0,0.0],[116.3,37.7,103.3,120.2,0.3,0.0,0.0],[113.5,38.4,105.2,120.3,0.3,0.0,0.0],[111.3,39.0,106.4,120.4,0.4,0.0,0.0],[110.1,39.4,107.0,120.6,0.4,0.0,0.0],[108.8,39.8,107.1,120.7,0.4,0.0,0.0],[108.6,40.1,107.1,120.8,0.4,0.0,0.0],[108.7,40.2,106.8,120.9,0.4,0.0,0.0],[109.6,40.4,105.9,121.1,0.4,0.0,0.0],[110.3,40.4,104.5,121.2,0.3,0.0,0.0],[111.4,40.3,102.7,121.2,0.1,0.0,0.0],[113.6,40.2,100.5,121.4,0.0,0.0,0.0],[115.5,40.1,98.3,121.5,0.0,0.0,0.0],[118.2,39.8,96.3,121.6,0.0,0.0,0.0],[119.9,39.6,94.7,121.7,-0.3,0.0,0.0],[122.6,39.3,93.6,121.8,-0.3,0.0,0.0],[123.5,39.2,93.1,121.9,-0.3,0.0,0.0],[124.6,39.2,93.0,122.0,-0.3,0.0,0.0],[124.9,39.3,93.0,122.1,-0.3,0.0,0.0],[124.6,39.5,93.2,122.1,-0.3,0.0,0.0],[123.8,39.7,93.5,122.2,-0.3,0.0,0.0],[123.0,40.1,94.0,122.2,-0.1,0.0,0.0],[121.6,40.4,94.6,122.3,-0.3,0.0,0.0],[120.8,40.7,95.2,122.3,-0.1,0.0,0.0],[120.1,40.9,95.7,122.3,-0.1,0.0,0.0],[118.9,41.1,96.1,122.3,-0.1,0.0,0.0],[118.5,41.2,96.2,122.3,-0.1,0.0,0.0],[118.1,41.3,96.2,122.3,-0.1,0.0,0.0],[118.1,41.3,96.2,122.3,-0.1,0.0,0.0],[118.5,41.2,96.2,122.3,-0.1,0.0,0.0],[118.7,41.1,96.2,122.3,-0.1,0.0,0.0],[118.8,41.0,96.2,122.3,-0.1,0.0,0.0],[120.1,40.8,96.2,122.2,-0.1,0.0,0.0],[120.3,40.7,96.2,122.2,-0.1,0.0,0.0],[120.3,40.5,96.2,122.2,-0.1,0.0,0.0],[120.2,40.4,96.2,122.0,-0.1,0.0,0.0],[120.2,40.3,96.2,122.0,-0.1,0.0,0.0],[120.3,40.2,96.2,122.0,-0.1,0.0,0.0],[120.1,40.0,96.2,121.8,-0.1,0.0,0.0],[120.1,39.8,96.2,121.8,-0.1,0.0,0.0],[119.8,39.7,96.2,121.7,-0.1,0.0,0.0],[119.8,39.5,96.2,121.5,-0.1,0.0,0.0],[119.8,39.3,96.2,121.5,-0.1,0.0,0.0],[120.1,39.0,96.2,121.3,-0.1,0.0,0.0],[120.1,38.8,96.2,121.2,-0.1,0.0,0.0],[120.1,38.6,96.2,121.2,-0.1,0.0,0.0],[120.1,38.3,96.2,121.0,-0.1,0.0,0.0],[120.1,38.1,96.2,120.8,-0.1,0.0,0.0]]},"idle_peek":{"n":86,"loop":false,"scrub":false,"events":{},"role":"beat","state":"idle","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.5,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.3,0.0,0.0],[120.1,36.6,96.2,120.0,-0.1,0.0,0.0],[120.1,36.3,96.2,120.0,-0.1,0.0,0.0],[120.0,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.5,96.2,119.5,-0.1,0.0,0.0],[120.1,35.3,96.2,119.5,-0.1,0.0,0.0],[120.3,34.9,96.2,119.7,-0.3,0.0,0.0],[120.3,34.4,96.2,120.2,-0.1,0.01,0.0],[121.1,33.6,96.3,120.8,-0.3,0.02,0.0],[123.6,32.6,96.3,121.8,-0.1,0.03,0.0],[126.0,31.3,96.3,122.8,-0.1,0.04,0.0],[126.0,29.9,96.4,124.2,-0.1,0.05,0.0],[126.1,28.5,96.5,125.5,0.0,0.07,0.0],[126.5,27.4,96.6,126.8,-0.1,0.08,0.0],[126.3,26.5,96.7,127.8,-0.1,0.09,0.0],[126.4,25.9,96.7,128.6,-0.1,0.09,0.0],[126.7,25.5,96.8,129.1,-0.1,0.1,0.0],[126.7,25.3,96.8,129.3,0.0,0.1,0.0],[126.7,25.3,96.8,129.4,-0.1,0.1,0.0],[126.4,25.7,96.7,127.8,-0.1,0.09,0.0],[126.1,26.2,96.6,126.5,-0.1,0.07,0.0],[125.8,27.1,96.5,125.5,-0.1,0.06,0.0],[126.0,28.0,96.4,124.5,0.0,0.05,0.0],[126.0,29.2,96.4,123.7,0.0,0.05,0.0],[125.8,30.5,96.3,123.0,-0.1,0.04,0.0],[125.7,31.7,96.3,122.5,-0.1,0.03,0.0],[125.1,32.8,96.3,122.0,-0.1,0.03,0.0],[123.4,33.6,96.3,121.7,-0.1,0.02,0.0],[120.9,34.3,96.3,121.2,-0.1,0.02,0.0],[120.8,34.7,96.2,121.0,-0.1,0.01,0.0],[120.9,35.1,96.3,120.8,-0.1,0.01,0.0],[121.1,35.4,96.3,120.8,-0.1,0.01,0.0],[121.3,35.7,96.2,120.7,-0.1,0.01,0.0],[121.5,36.0,96.2,120.7,-0.1,0.01,0.0],[121.9,36.3,96.2,120.7,-0.1,0.0,0.0],[121.1,36.7,96.2,120.7,-0.1,0.0,0.0],[120.7,37.1,96.2,120.8,-0.1,0.0,0.0],[120.2,37.5,96.2,120.8,-0.1,0.0,0.0],[120.2,37.8,96.2,120.8,-0.1,0.0,0.0],[120.1,38.2,96.2,121.0,-0.1,0.0,0.0],[120.1,38.5,96.2,121.0,-0.1,0.0,0.0],[120.1,38.7,96.2,121.2,-0.1,0.0,0.0],[119.7,39.0,96.2,121.2,-0.1,0.0,0.0],[119.8,39.2,96.2,121.3,-0.1,0.0,0.0],[119.8,39.4,96.2,121.5,-0.1,0.0,0.0],[120.1,39.5,96.2,121.7,-0.1,0.0,0.0],[120.1,39.7,96.2,121.8,-0.1,0.0,0.0],[120.1,39.9,96.2,121.8,-0.3,0.0,0.0],[120.0,40.1,96.2,121.8,-0.1,0.0,0.0],[120.1,40.2,96.2,122.0,-0.1,0.0,0.0],[119.8,40.4,96.2,122.0,-0.1,0.0,0.0],[120.1,40.5,96.2,122.2,-0.1,0.0,0.0],[119.7,40.7,96.2,122.2,-0.1,0.0,0.0],[119.7,40.8,96.2,122.2,-0.1,0.0,0.0],[119.7,40.9,96.2,122.2,-0.1,0.0,0.0],[120.1,40.9,96.2,122.3,-0.1,0.0,0.0],[119.8,41.0,96.2,122.3,-0.1,0.0,0.0],[120.1,41.0,96.2,122.3,-0.1,0.0,0.0],[119.7,41.1,96.2,122.3,-0.1,0.0,0.0],[119.7,41.1,96.2,122.3,-0.1,0.0,0.0],[119.2,41.1,96.2,122.3,-0.1,0.0,0.0],[120.1,41.0,96.2,122.3,-0.1,0.0,0.0],[119.7,41.0,96.2,122.3,-0.1,0.0,0.0],[119.8,40.9,96.2,122.3,-0.1,0.0,0.0],[120.1,40.8,96.2,122.2,-0.1,0.0,0.0],[120.1,40.7,96.2,122.2,-0.1,0.0,0.0],[120.1,40.6,96.2,122.2,-0.1,0.0,0.0],[119.8,40.5,96.2,122.0,-0.1,0.0,0.0],[119.7,40.4,96.2,122.0,-0.1,0.0,0.0],[120.1,40.2,96.2,122.0,-0.1,0.0,0.0],[120.1,40.0,96.2,121.8,-0.1,0.0,0.0],[120.1,39.8,96.2,121.8,-0.1,0.0,0.0],[119.8,39.7,96.2,121.7,-0.1,0.0,0.0],[120.1,39.4,96.2,121.5,-0.1,0.0,0.0],[120.1,39.2,96.2,121.5,-0.1,0.0,0.0],[120.1,39.0,96.2,121.3,-0.1,0.0,0.0],[120.1,38.8,96.2,121.2,-0.1,0.0,0.0],[120.1,38.6,96.2,121.2,-0.1,0.0,0.0],[120.1,38.3,96.2,121.0,-0.1,0.0,0.0],[120.1,38.1,96.2,120.8,-0.1,0.0,0.0]]},"listening_in":{"n":19,"loop":false,"scrub":false,"events":{},"role":"enter","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.4,35.8,96.5,122.5,-0.1,0.03,0.0],[121.8,36.2,97.2,125.8,-0.1,0.05,0.0],[124.8,38.5,97.9,130.0,0.0,0.07,0.0],[130.6,40.8,98.8,133.4,0.0,0.08,0.0],[132.0,41.6,99.1,134.8,0.0,0.09,0.0],[127.4,32.1,99.2,127.2,0.0,0.09,0.0],[125.5,20.4,99.2,120.0,0.0,0.09,0.0],[125.1,12.9,99.2,116.0,0.0,0.09,0.0],[126.8,5.7,99.1,114.5,0.0,0.09,0.0],[129.0,1.3,99.1,114.5,0.0,0.09,0.0],[130.6,0.2,99.0,115.3,0.0,0.09,0.0],[131.2,1.6,99.0,116.1,0.0,0.08,0.0],[130.7,3.8,99.0,116.2,0.0,0.08,0.0],[129.7,7.2,99.0,116.5,0.0,0.08,0.0],[128.7,11.5,99.0,117.4,0.0,0.08,0.0],[127.8,15.8,99.0,118.5,0.0,0.08,0.0],[127.2,19.3,99.0,119.6,0.0,0.08,0.0],[126.7,21.2,99.0,120.3,0.0,0.08,0.0]]},"listening_rest":{"n":115,"loop":true,"scrub":false,"events":{},"role":"rest","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.1,99.0,120.4,0.0,0.08,0.0],[127.6,18.9,99.0,120.3,0.0,0.08,0.0],[127.6,18.8,99.0,120.3,0.0,0.08,0.0],[127.6,18.6,99.0,120.2,0.0,0.08,0.0],[127.6,18.4,99.0,120.1,0.0,0.08,0.0],[127.6,18.3,99.0,120.1,0.0,0.08,0.0],[127.6,18.1,99.0,120.0,0.0,0.08,0.0],[127.6,18.0,99.0,119.9,0.0,0.08,0.0],[127.6,17.9,99.0,119.8,0.0,0.08,0.0],[127.6,17.7,99.0,119.8,0.0,0.08,0.0],[127.6,17.6,99.0,119.7,0.0,0.08,0.0],[127.7,17.5,99.0,119.7,0.0,0.08,0.0],[127.6,17.3,99.0,119.7,0.0,0.08,0.0],[127.6,17.2,99.0,119.7,0.0,0.08,0.0],[127.7,17.1,99.0,119.7,0.0,0.08,0.0],[127.7,16.9,99.0,119.8,0.0,0.08,0.0],[127.7,16.8,99.0,120.0,0.0,0.08,0.0],[127.8,16.6,99.0,120.1,0.0,0.08,0.0],[127.8,16.4,99.0,120.3,0.0,0.08,0.0],[127.9,16.2,99.0,120.5,0.0,0.08,0.0],[127.9,16.0,99.0,120.8,0.0,0.08,0.0],[128.0,15.9,99.0,121.0,0.0,0.08,0.0],[128.1,15.7,99.0,121.3,0.0,0.08,0.0],[128.1,15.5,99.0,121.6,0.0,0.08,0.0],[128.2,15.4,99.0,121.8,0.0,0.08,0.0],[128.2,15.3,99.0,122.1,0.0,0.08,0.0],[128.3,15.2,99.0,122.3,0.0,0.08,0.0],[128.3,15.1,99.0,122.6,0.0,0.08,0.0],[128.4,15.1,99.0,122.8,0.0,0.08,0.0],[128.4,15.0,99.0,122.9,0.0,0.08,0.0],[128.4,15.0,99.0,123.1,0.0,0.08,0.0],[128.5,15.0,99.0,123.2,0.0,0.08,0.0],[128.5,15.0,99.0,123.3,0.0,0.08,0.0],[128.5,15.1,99.0,123.3,0.0,0.08,0.0],[128.5,15.1,99.0,123.3,0.0,0.08,0.0],[128.5,15.2,99.0,123.4,0.0,0.08,0.0],[128.5,15.3,99.0,123.4,0.0,0.08,0.0],[128.5,15.3,99.0,123.3,0.0,0.08,0.0],[128.4,15.4,99.0,123.2,0.0,0.08,0.0],[128.4,15.5,99.0,122.9,0.0,0.08,0.0],[128.3,15.6,99.0,122.6,0.0,0.08,0.0],[128.2,15.8,99.0,122.1,0.0,0.08,0.0],[128.1,16.1,99.0,121.6,0.0,0.08,0.0],[128.0,16.3,99.0,121.2,0.0,0.08,0.0],[127.9,16.7,99.0,120.7,0.0,0.08,0.0],[127.8,17.1,99.0,120.4,0.0,0.08,0.0],[127.7,17.4,99.0,120.1,0.0,0.08,0.0],[127.7,17.8,99.0,119.9,0.0,0.08,0.0],[127.6,18.1,99.0,119.9,0.0,0.08,0.0],[127.6,18.3,99.0,119.9,0.0,0.08,0.0],[127.6,18.5,99.0,120.0,0.0,0.08,0.0],[127.6,18.6,99.0,120.1,0.0,0.08,0.0],[127.6,18.7,99.0,120.1,0.0,0.08,0.0],[127.6,18.7,99.0,120.2,0.0,0.08,0.0],[127.6,18.8,99.0,120.3,0.0,0.08,0.0],[127.6,18.9,99.0,120.4,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.4,99.0,120.6,0.0,0.08,0.0],[127.6,19.5,99.0,120.7,0.0,0.08,0.0],[127.6,19.7,99.0,120.7,0.0,0.08,0.0],[127.6,19.9,99.0,120.8,0.0,0.08,0.0],[127.6,20.1,99.0,120.9,0.0,0.08,0.0],[127.6,20.2,99.0,120.9,0.0,0.08,0.0],[127.6,20.4,99.0,121.0,0.0,0.08,0.0],[127.6,20.5,99.0,121.1,0.0,0.08,0.0],[127.6,20.7,99.0,121.1,0.0,0.08,0.0],[127.6,20.8,99.0,121.2,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,21.0,99.0,121.3,0.0,0.08,0.0],[127.6,21.1,99.0,121.4,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,21.4,99.0,121.5,0.0,0.08,0.0],[127.6,21.5,99.0,121.5,0.0,0.08,0.0],[127.6,21.6,99.0,121.6,0.0,0.08,0.0],[127.6,21.6,99.0,121.6,0.0,0.08,0.0],[127.6,21.7,99.0,121.7,0.0,0.08,0.0],[127.6,21.8,99.0,121.7,0.0,0.08,0.0],[127.6,21.9,99.0,121.7,0.0,0.08,0.0],[127.6,21.9,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,21.9,99.0,121.8,0.0,0.08,0.0],[127.6,21.9,99.0,121.7,0.0,0.08,0.0],[127.6,21.8,99.0,121.7,0.0,0.08,0.0],[127.6,21.7,99.0,121.7,0.0,0.08,0.0],[127.6,21.6,99.0,121.6,0.0,0.08,0.0],[127.6,21.5,99.0,121.6,0.0,0.08,0.0],[127.6,21.4,99.0,121.5,0.0,0.08,0.0],[127.6,21.3,99.0,121.5,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,21.1,99.0,121.4,0.0,0.08,0.0],[127.6,21.0,99.0,121.3,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,20.7,99.0,121.2,0.0,0.08,0.0],[127.6,20.6,99.0,121.1,0.0,0.08,0.0],[127.6,20.5,99.0,121.1,0.0,0.08,0.0],[127.6,20.3,99.0,121.0,0.0,0.08,0.0],[127.6,20.2,99.0,120.9,0.0,0.08,0.0],[127.6,20.0,99.0,120.9,0.0,0.08,0.0],[127.6,19.9,99.0,120.8,0.0,0.08,0.0],[127.6,19.7,99.0,120.7,0.0,0.08,0.0],[127.6,19.6,99.0,120.6,0.0,0.08,0.0],[127.6,19.4,99.0,120.6,0.0,0.08,0.0]]},"listen_nod":{"n":58,"loop":false,"scrub":false,"events":{},"role":"beat","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.3,0.0,0.08,0.0],[127.6,18.7,99.0,120.2,0.0,0.08,0.0],[127.6,18.4,99.0,120.1,0.0,0.08,0.0],[127.6,18.1,99.0,119.9,0.0,0.08,0.0],[127.6,17.8,99.0,119.8,0.0,0.08,0.0],[127.7,17.5,99.0,119.7,0.0,0.08,0.0],[127.6,17.2,99.0,119.5,0.0,0.08,0.0],[127.7,17.0,99.0,119.4,0.0,0.08,0.0],[127.7,16.8,99.0,119.4,0.0,0.08,0.0],[127.9,17.0,99.0,120.6,0.0,0.08,0.0],[128.4,17.7,99.0,123.5,0.0,0.08,0.0],[128.8,18.5,99.0,126.1,0.0,0.08,0.0],[129.2,19.2,99.0,128.4,0.0,0.08,0.0],[129.5,19.9,99.0,130.3,0.0,0.08,0.0],[129.8,20.6,99.0,131.8,0.0,0.08,0.0],[130.1,21.3,99.0,132.9,0.0,0.08,0.0],[130.2,21.9,99.0,133.6,0.0,0.08,0.0],[130.4,22.3,99.0,133.8,0.0,0.08,0.0],[130.4,22.2,99.0,133.6,0.0,0.08,0.0],[130.1,21.2,99.0,131.9,0.0,0.08,0.0],[129.6,19.5,99.0,128.8,0.0,0.08,0.0],[129.0,17.8,99.0,125.2,0.0,0.08,0.0],[128.4,16.8,99.0,122.0,0.0,0.08,0.0],[128.0,16.8,99.0,120.3,0.0,0.08,0.0],[127.8,17.7,99.0,119.9,0.0,0.08,0.0],[128.0,18.9,99.0,121.9,0.0,0.08,0.0],[128.2,19.8,99.0,124.1,0.0,0.08,0.0],[128.4,19.9,99.0,125.9,0.0,0.08,0.0],[128.5,19.5,99.0,127.5,0.0,0.08,0.0],[128.8,19.1,99.0,128.7,0.0,0.08,0.0],[129.1,19.0,99.0,129.6,0.0,0.08,0.0],[129.3,19.1,99.0,130.0,0.0,0.08,0.0],[129.5,19.4,99.0,130.2,0.0,0.08,0.0],[129.6,19.5,99.0,129.8,0.0,0.08,0.0],[129.5,19.4,99.0,128.7,0.0,0.08,0.0],[129.2,19.2,99.0,127.0,0.0,0.08,0.0],[128.8,19.3,99.0,125.1,0.0,0.08,0.0],[128.4,19.8,99.0,123.4,0.0,0.08,0.0],[127.9,20.7,99.0,122.3,0.0,0.08,0.0],[127.6,21.9,99.0,121.8,0.0,0.08,0.0],[127.5,23.1,99.0,121.8,0.0,0.08,0.0],[126.3,23.8,99.0,121.8,0.0,0.08,0.0],[125.7,24.0,99.0,121.8,0.0,0.08,0.0],[127.4,23.7,99.0,121.8,0.0,0.08,0.0],[127.5,23.1,99.0,121.8,0.0,0.08,0.0],[127.5,22.5,99.0,121.8,0.0,0.08,0.0],[127.6,21.9,99.0,121.7,0.0,0.08,0.0],[127.6,21.5,99.0,121.7,0.0,0.08,0.0],[127.7,21.1,99.0,121.6,0.0,0.08,0.0],[127.7,20.9,99.0,121.5,0.0,0.08,0.0],[127.7,20.7,99.0,121.4,0.0,0.08,0.0],[127.7,20.5,99.0,121.3,0.0,0.08,0.0],[127.6,20.4,99.0,121.1,0.0,0.08,0.0],[127.6,20.3,99.0,121.0,0.0,0.08,0.0],[127.6,20.1,99.0,120.9,0.0,0.08,0.0],[127.6,19.9,99.0,120.7,0.0,0.08,0.0],[127.6,19.6,99.0,120.6,0.0,0.08,0.0]]},"listen_tilt_l":{"n":72,"loop":false,"scrub":false,"events":{},"role":"beat","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,18.8,99.0,120.2,0.0,0.08,0.0],[127.6,18.6,99.0,120.1,0.0,0.08,0.0],[127.6,18.3,99.0,120.0,0.0,0.08,0.0],[127.6,18.0,99.0,119.9,0.0,0.08,0.0],[127.6,17.8,99.0,119.8,0.0,0.08,0.0],[127.6,17.5,99.0,119.7,0.0,0.08,0.0],[127.6,17.3,99.0,119.6,0.0,0.08,0.0],[127.7,17.2,99.0,119.5,0.0,0.08,0.0],[127.6,17.0,99.0,119.4,0.0,0.08,0.0],[127.6,16.8,98.8,119.4,0.0,0.08,0.0],[127.5,16.6,98.4,119.3,0.0,0.08,0.0],[127.3,16.4,97.4,119.2,0.1,0.08,0.0],[126.9,16.0,95.9,119.2,0.3,0.08,0.0],[126.6,15.7,94.1,119.2,0.4,0.08,0.0],[126.1,15.3,92.0,119.2,0.7,0.08,0.0],[125.7,14.9,89.7,119.2,0.7,0.08,0.0],[125.4,14.6,87.5,119.2,1.0,0.08,0.0],[124.9,14.3,85.5,119.1,1.2,0.08,0.0],[124.3,14.0,84.0,119.2,1.4,0.08,0.0],[123.8,13.9,82.8,119.2,1.6,0.08,0.0],[123.3,13.9,82.2,119.2,1.6,0.08,0.0],[123.0,13.9,81.8,119.2,1.8,0.08,0.0],[122.9,14.1,81.8,119.3,1.8,0.08,0.0],[122.9,14.2,81.8,119.3,1.8,0.08,0.0],[123.1,14.4,81.8,119.5,1.8,0.08,0.0],[123.0,14.5,81.8,119.5,1.8,0.08,0.0],[123.1,14.7,81.8,119.7,1.8,0.08,0.0],[123.1,14.9,81.8,119.8,1.8,0.08,0.0],[123.1,15.2,81.8,119.8,1.8,0.08,0.0],[123.1,15.4,81.8,120.0,1.8,0.08,0.0],[123.1,15.6,81.8,120.0,1.8,0.08,0.0],[123.1,15.9,81.8,120.2,1.8,0.08,0.0],[123.1,16.1,81.8,120.2,1.8,0.08,0.0],[123.2,16.4,81.7,120.3,1.8,0.08,0.0],[123.1,16.6,81.7,120.5,1.8,0.08,0.0],[123.1,16.9,81.8,120.6,1.9,0.08,0.0],[123.1,17.2,81.8,120.7,1.9,0.08,0.0],[123.1,17.4,81.8,120.8,1.8,0.08,0.0],[123.1,17.7,81.8,121.0,1.8,0.08,0.0],[123.1,17.9,81.7,121.0,1.8,0.08,0.0],[123.1,18.1,81.7,121.2,1.8,0.08,0.0],[123.1,18.4,81.7,121.2,1.8,0.08,0.0],[123.1,18.6,81.7,121.3,1.8,0.08,0.0],[123.1,18.8,81.7,121.5,1.8,0.08,0.0],[123.1,18.9,81.7,121.5,1.9,0.08,0.0],[123.1,19.1,81.7,121.6,1.9,0.08,0.0],[123.1,19.2,81.7,121.7,1.8,0.08,0.0],[123.2,19.4,81.8,121.7,1.9,0.08,0.0],[123.7,19.6,82.7,121.8,1.7,0.08,0.0],[124.8,19.9,84.5,121.8,1.5,0.08,0.0],[126.4,20.4,87.3,121.8,1.2,0.08,0.0],[128.2,21.0,90.7,121.8,0.7,0.08,0.0],[129.3,21.5,94.0,121.8,0.4,0.08,0.0],[129.4,21.8,96.7,121.8,0.1,0.08,0.0],[128.5,22.0,98.3,121.8,0.0,0.08,0.0],[127.0,22.0,98.9,121.8,0.0,0.08,0.0],[125.8,21.9,99.0,121.8,0.0,0.08,0.0],[124.9,21.8,99.0,121.7,0.0,0.08,0.0],[124.8,21.6,99.0,121.7,0.0,0.08,0.0],[125.4,21.5,99.0,121.6,0.0,0.08,0.0],[126.1,21.4,99.0,121.5,0.0,0.08,0.0],[127.0,21.2,99.0,121.4,0.0,0.08,0.0],[127.7,21.1,99.0,121.4,0.0,0.08,0.0],[128.2,20.9,99.0,121.3,0.0,0.08,0.0],[128.4,20.7,99.0,121.2,0.0,0.08,0.0],[128.5,20.5,99.0,121.1,0.0,0.08,0.0],[128.3,20.2,99.0,120.9,0.0,0.08,0.0],[128.1,20.0,99.0,120.8,0.0,0.08,0.0],[127.9,19.7,99.0,120.7,0.0,0.08,0.0],[127.6,19.5,99.0,120.6,0.0,0.08,0.0]]},"listen_tilt_r":{"n":72,"loop":false,"scrub":false,"events":{},"role":"beat","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,18.8,99.0,120.2,0.0,0.08,0.0],[127.6,18.6,99.0,120.1,0.0,0.08,0.0],[127.6,18.3,99.0,120.0,0.0,0.08,0.0],[127.6,18.0,99.0,119.9,0.0,0.08,0.0],[127.6,17.8,99.0,119.8,0.0,0.08,0.0],[127.6,17.5,99.0,119.7,0.0,0.08,0.0],[127.6,17.3,99.0,119.6,0.0,0.08,0.0],[127.7,17.2,99.0,119.5,0.0,0.08,0.0],[127.6,17.0,99.0,119.4,0.0,0.08,0.0],[127.7,16.9,99.2,119.4,0.0,0.08,0.0],[127.7,16.8,99.6,119.3,0.0,0.08,0.0],[128.1,16.9,100.6,119.2,-0.1,0.08,0.0],[128.2,17.0,102.1,119.2,-0.3,0.08,0.0],[126.1,17.2,103.9,119.2,-0.4,0.08,0.0],[125.8,17.5,106.0,119.2,-0.7,0.08,0.0],[123.7,17.7,108.3,119.2,-0.7,0.08,0.0],[121.9,18.0,110.5,119.2,-1.0,0.08,0.0],[120.8,18.3,112.5,119.1,-1.2,0.08,0.0],[119.6,18.4,114.0,119.2,-1.4,0.08,0.0],[118.1,18.5,115.2,119.2,-1.6,0.08,0.0],[116.7,18.6,115.8,119.2,-1.6,0.08,0.0],[115.3,18.7,116.2,119.2,-1.8,0.08,0.0],[116.4,18.7,116.2,119.3,-1.8,0.08,0.0],[115.8,18.9,116.2,119.3,-1.8,0.08,0.0],[115.1,19.1,116.2,119.5,-1.8,0.08,0.0],[115.4,19.3,116.2,119.5,-1.8,0.08,0.0],[115.1,19.6,116.2,119.7,-1.8,0.08,0.0],[115.9,19.8,116.2,119.8,-1.8,0.08,0.0],[115.4,20.1,116.2,119.8,-1.8,0.08,0.0],[115.5,20.3,116.2,120.0,-1.8,0.08,0.0],[115.7,20.5,116.2,120.0,-1.8,0.08,0.0],[116.2,20.7,116.2,120.2,-1.8,0.08,0.0],[115.0,21.0,116.2,120.2,-1.8,0.08,0.0],[115.3,21.2,116.3,120.3,-1.8,0.08,0.0],[115.4,21.4,116.3,120.5,-1.8,0.08,0.0],[115.5,21.6,116.2,120.6,-1.9,0.08,0.0],[115.2,21.9,116.2,120.7,-1.9,0.08,0.0],[115.2,22.1,116.2,120.8,-1.8,0.08,0.0],[115.0,22.4,116.2,121.0,-1.8,0.08,0.0],[115.3,22.6,116.3,121.0,-1.8,0.08,0.0],[115.4,22.8,116.3,121.2,-1.8,0.08,0.0],[115.4,23.0,116.3,121.2,-1.8,0.08,0.0],[115.5,23.2,116.3,121.3,-1.8,0.08,0.0],[115.5,23.4,116.3,121.5,-1.8,0.08,0.0],[115.3,23.6,116.3,121.5,-1.9,0.08,0.0],[115.5,23.7,116.3,121.6,-1.9,0.08,0.0],[115.5,23.9,116.3,121.7,-1.8,0.08,0.0],[115.7,23.9,116.2,121.7,-1.9,0.08,0.0],[116.9,23.9,115.3,121.8,-1.7,0.08,0.0],[118.0,23.6,113.5,121.8,-1.5,0.08,0.0],[117.9,23.3,110.7,121.8,-1.2,0.08,0.0],[120.7,22.9,107.3,121.8,-0.7,0.08,0.0],[121.9,22.6,104.0,121.8,-0.4,0.08,0.0],[124.7,22.3,101.3,121.8,-0.1,0.08,0.0],[126.5,22.1,99.7,121.8,0.0,0.08,0.0],[128.2,22.0,99.1,121.8,0.0,0.08,0.0],[129.2,22.0,99.0,121.8,0.0,0.08,0.0],[129.7,21.9,99.0,121.7,0.0,0.08,0.0],[129.7,21.8,99.0,121.7,0.0,0.08,0.0],[129.4,21.7,99.0,121.6,0.0,0.08,0.0],[128.8,21.5,99.0,121.5,0.0,0.08,0.0],[128.1,21.3,99.0,121.4,0.0,0.08,0.0],[127.5,21.1,99.0,121.4,0.0,0.08,0.0],[127.0,20.9,99.0,121.3,0.0,0.08,0.0],[126.7,20.6,99.0,121.2,0.0,0.08,0.0],[126.7,20.4,99.0,121.1,0.0,0.08,0.0],[126.8,20.2,99.0,120.9,0.0,0.08,0.0],[127.1,20.0,99.0,120.8,0.0,0.08,0.0],[127.3,19.7,99.0,120.7,0.0,0.08,0.0],[127.6,19.5,99.0,120.6,0.0,0.08,0.0]]},"listen_lean":{"n":77,"loop":false,"scrub":false,"events":{},"role":"beat","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,18.8,99.0,120.3,0.0,0.08,0.0],[127.6,18.6,99.0,120.2,0.0,0.08,0.0],[127.6,18.3,99.0,120.1,0.0,0.08,0.0],[127.6,18.1,99.0,119.9,0.0,0.08,0.0],[127.6,17.9,99.0,119.8,0.0,0.08,0.0],[127.6,17.6,99.0,119.8,0.0,0.08,0.0],[127.6,17.4,99.0,119.7,0.0,0.08,0.0],[127.7,17.3,99.0,119.6,0.0,0.08,0.0],[127.6,17.1,99.0,119.5,0.0,0.08,0.0],[127.7,16.9,99.0,119.4,0.0,0.08,0.0],[127.7,16.6,99.0,119.4,0.0,0.09,0.0],[127.8,16.1,99.0,119.4,0.0,0.1,0.0],[127.9,15.5,99.0,119.4,0.0,0.11,0.0],[128.2,14.6,99.0,119.4,0.0,0.13,0.0],[128.4,13.6,99.0,119.5,0.0,0.15,0.0],[128.8,12.4,99.0,119.6,0.0,0.17,0.0],[129.1,11.1,99.0,119.7,0.0,0.19,0.0],[129.5,9.8,99.0,119.9,0.0,0.22,0.0],[129.8,8.6,99.0,120.0,0.0,0.24,0.0],[130.1,7.5,99.0,120.2,0.0,0.26,0.0],[130.4,6.6,99.0,120.3,0.0,0.27,0.0],[130.5,6.0,99.0,120.4,0.0,0.29,0.0],[130.7,5.6,99.0,120.5,0.0,0.29,0.0],[130.7,5.5,99.0,120.6,0.0,0.3,0.0],[130.8,5.5,99.0,120.7,0.0,0.3,0.0],[130.8,5.7,99.0,120.8,0.0,0.3,0.0],[130.7,5.9,99.0,120.8,0.0,0.3,0.0],[130.7,6.1,99.0,120.9,0.0,0.3,0.0],[130.7,6.3,99.0,121.0,0.0,0.3,0.0],[130.7,6.6,99.0,121.1,0.0,0.3,0.0],[130.7,6.8,99.0,121.2,0.0,0.3,0.0],[130.7,7.1,99.0,121.3,0.0,0.3,0.0],[130.7,7.3,99.0,121.4,0.0,0.3,0.0],[130.7,7.5,99.0,121.5,0.0,0.3,0.0],[130.7,7.8,99.0,121.6,0.0,0.3,0.0],[130.7,8.0,99.0,121.8,0.0,0.3,0.0],[130.7,8.3,99.0,121.9,0.0,0.3,0.0],[130.7,8.5,99.0,122.0,0.0,0.3,0.0],[130.7,8.8,99.0,122.1,0.0,0.3,0.0],[130.7,9.0,99.0,122.2,0.0,0.3,0.0],[130.7,9.3,99.0,122.3,0.0,0.3,0.0],[130.7,9.5,99.0,122.5,0.0,0.3,0.0],[130.7,9.8,99.0,122.6,0.0,0.3,0.0],[130.7,10.0,99.0,122.7,0.0,0.3,0.0],[130.7,10.2,99.0,122.8,0.0,0.3,0.0],[130.6,10.4,99.0,122.9,0.0,0.3,0.0],[130.6,10.6,99.0,122.9,0.0,0.3,0.0],[130.6,10.8,99.0,123.0,0.0,0.3,0.0],[130.6,11.0,99.0,123.1,0.0,0.3,0.0],[130.6,11.1,99.0,123.2,0.0,0.3,0.0],[130.6,11.2,99.0,123.2,0.0,0.3,0.0],[130.6,11.3,99.0,123.3,0.0,0.3,0.0],[130.6,11.6,99.0,123.3,0.0,0.3,0.0],[130.4,12.3,99.0,123.2,0.0,0.28,0.0],[130.0,13.7,99.0,123.0,0.0,0.25,0.0],[129.4,15.5,99.0,122.7,0.0,0.22,0.0],[128.8,17.5,99.0,122.4,0.0,0.17,0.0],[128.3,19.3,99.0,122.2,0.0,0.14,0.0],[127.9,20.8,99.0,121.9,0.0,0.11,0.0],[127.7,21.7,99.0,121.8,0.0,0.09,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.7,0.0,0.08,0.0],[127.6,22.0,99.0,121.7,0.0,0.08,0.0],[127.6,21.9,99.0,121.6,0.0,0.08,0.0],[127.6,21.7,99.0,121.5,0.0,0.08,0.0],[127.6,21.4,99.0,121.5,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,20.7,99.0,121.2,0.0,0.08,0.0],[127.6,20.4,99.0,121.1,0.0,0.08,0.0],[127.6,20.2,99.0,121.0,0.0,0.08,0.0],[127.6,20.0,99.0,120.9,0.0,0.08,0.0],[127.6,19.8,99.0,120.8,0.0,0.08,0.0],[127.6,19.6,99.0,120.7,0.0,0.08,0.0],[127.6,19.4,99.0,120.6,0.0,0.08,0.0]]},"listen_oh":{"n":62,"loop":false,"scrub":false,"events":{},"role":"beat","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.3,0.0,0.08,0.0],[127.6,18.8,99.0,120.2,0.0,0.08,0.0],[127.6,18.5,99.0,120.1,0.0,0.08,0.0],[127.6,18.2,99.0,120.0,0.0,0.08,0.0],[127.6,17.9,99.0,119.8,0.0,0.08,0.0],[127.6,17.6,99.0,119.7,0.0,0.08,0.0],[127.6,17.3,99.0,119.6,0.0,0.08,0.0],[127.7,17.1,99.0,119.5,0.0,0.08,0.0],[127.7,16.9,99.0,119.4,0.0,0.08,0.0],[127.7,13.9,99.0,116.9,0.0,0.08,0.0],[127.7,8.9,99.0,112.7,0.0,0.08,0.0],[128.0,6.1,99.0,110.4,0.0,0.08,0.0],[128.4,4.9,99.0,109.4,0.0,0.08,0.0],[126.7,4.7,99.0,109.1,0.0,0.08,0.0],[122.7,5.1,99.0,109.0,0.0,0.08,0.0],[121.3,5.7,99.0,109.0,0.0,0.08,0.0],[120.6,6.2,99.0,109.0,0.0,0.08,0.0],[121.2,6.5,99.0,109.0,0.0,0.08,0.0],[121.1,6.7,99.0,109.1,0.0,0.08,0.0],[122.5,6.7,99.0,109.1,0.0,0.08,0.0],[123.9,6.6,99.0,109.2,0.0,0.08,0.0],[126.3,6.4,99.0,109.3,0.0,0.08,0.0],[127.0,6.3,99.0,109.4,0.0,0.08,0.0],[127.7,6.3,99.0,109.5,0.0,0.08,0.0],[127.8,6.3,99.0,109.6,0.0,0.08,0.0],[126.6,6.5,99.0,109.7,0.0,0.08,0.0],[126.6,6.8,99.0,109.9,0.0,0.08,0.0],[125.6,7.3,99.0,110.0,0.0,0.08,0.0],[124.2,7.7,99.0,110.1,0.0,0.08,0.0],[124.1,8.2,99.0,110.3,0.0,0.08,0.0],[124.1,8.6,99.0,110.4,0.0,0.08,0.0],[123.7,9.0,99.0,110.6,0.0,0.08,0.0],[124.2,9.3,99.0,110.7,0.0,0.08,0.0],[124.0,9.5,99.0,110.9,0.0,0.08,0.0],[124.2,9.9,99.0,111.1,0.0,0.08,0.0],[124.2,10.4,99.0,111.5,0.0,0.08,0.0],[125.4,11.1,99.0,112.2,0.0,0.08,0.0],[125.5,12.2,99.0,113.1,0.0,0.08,0.0],[125.4,13.6,99.0,114.2,0.0,0.08,0.0],[126.4,15.1,99.0,115.5,0.0,0.08,0.0],[127.4,16.7,99.0,116.9,0.0,0.08,0.0],[127.9,18.3,99.0,118.3,0.0,0.08,0.0],[127.8,19.6,99.0,119.5,0.0,0.08,0.0],[127.6,20.8,99.0,120.5,0.0,0.08,0.0],[127.5,21.6,99.0,121.2,0.0,0.08,0.0],[127.4,22.1,99.0,121.6,0.0,0.08,0.0],[127.4,22.2,99.0,121.8,0.0,0.08,0.0],[127.4,22.1,99.0,121.8,0.0,0.08,0.0],[127.5,21.9,99.0,121.8,0.0,0.08,0.0],[127.6,21.7,99.0,121.8,0.0,0.08,0.0],[127.6,21.6,99.0,121.7,0.0,0.08,0.0],[127.7,21.5,99.0,121.7,0.0,0.08,0.0],[127.7,21.4,99.0,121.6,0.0,0.08,0.0],[127.6,21.3,99.0,121.5,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,21.1,99.0,121.3,0.0,0.08,0.0],[127.6,20.9,99.0,121.2,0.0,0.08,0.0],[127.6,20.6,99.0,121.1,0.0,0.08,0.0],[127.6,20.3,99.0,120.9,0.0,0.08,0.0],[127.6,20.0,99.0,120.8,0.0,0.08,0.0],[127.6,19.6,99.0,120.7,0.0,0.08,0.0]]},"listen_mhm":{"n":67,"loop":false,"scrub":false,"events":{},"role":"beat","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,19.0,99.0,120.4,0.0,0.08,0.0],[127.6,18.8,99.0,120.2,0.0,0.08,0.0],[127.6,18.5,99.0,120.1,0.0,0.08,0.0],[127.6,18.2,99.0,120.0,0.0,0.08,0.0],[127.6,18.0,99.0,119.9,0.0,0.08,0.0],[127.6,17.7,99.0,119.8,0.0,0.08,0.0],[127.6,17.4,99.0,119.7,0.0,0.08,0.0],[127.7,17.2,99.0,119.6,0.0,0.08,0.0],[127.7,17.0,99.0,119.5,0.0,0.08,0.0],[127.7,16.9,99.0,119.4,0.0,0.08,0.0],[127.7,16.8,99.0,119.4,0.0,0.08,0.0],[127.7,16.8,99.0,119.8,0.0,0.08,0.0],[127.9,17.0,99.0,120.6,0.0,0.08,0.0],[128.1,17.3,99.0,121.8,0.0,0.08,0.0],[128.4,17.9,99.0,123.4,0.0,0.08,0.0],[128.7,18.6,99.0,125.5,0.0,0.08,0.0],[129.1,19.6,99.0,127.7,0.0,0.08,0.0],[129.5,20.8,99.0,130.1,0.0,0.08,0.0],[130.0,22.1,99.0,132.4,0.0,0.08,0.0],[130.3,23.6,99.0,134.5,0.0,0.08,0.0],[130.7,25.1,99.0,136.2,0.0,0.08,0.0],[130.9,26.4,99.0,137.6,0.0,0.08,0.0],[131.1,27.4,99.0,138.4,0.0,0.08,0.0],[131.2,28.0,99.0,138.9,0.0,0.08,0.0],[131.3,28.3,99.0,139.0,0.0,0.08,0.0],[131.3,28.3,99.0,139.1,0.0,0.08,0.0],[131.3,28.4,99.0,139.2,0.0,0.08,0.0],[131.3,28.4,99.0,139.3,0.0,0.08,0.0],[131.3,28.5,99.0,139.4,0.0,0.08,0.0],[131.3,28.7,99.0,139.5,0.0,0.08,0.0],[131.2,28.9,99.0,139.6,0.0,0.08,0.0],[131.2,29.2,99.0,139.7,0.0,0.08,0.0],[131.1,29.5,99.0,139.8,0.0,0.08,0.0],[131.1,29.8,99.0,139.9,0.0,0.08,0.0],[131.1,30.2,99.0,140.0,0.0,0.08,0.0],[131.1,30.5,99.0,140.1,0.0,0.08,0.0],[131.2,30.7,99.0,140.2,0.0,0.08,0.0],[131.2,31.0,99.0,140.3,0.0,0.08,0.0],[131.2,31.2,99.0,140.4,0.0,0.08,0.0],[131.1,31.1,99.0,139.9,0.0,0.08,0.0],[130.9,30.4,99.0,138.5,0.0,0.08,0.0],[130.5,29.3,99.0,136.1,0.0,0.08,0.0],[129.9,28.0,99.0,133.0,0.0,0.08,0.0],[129.3,26.7,99.0,129.9,0.0,0.08,0.0],[128.7,25.9,99.0,127.1,0.0,0.08,0.0],[128.1,25.3,99.0,124.9,0.0,0.08,0.0],[127.8,25.1,99.0,123.6,0.0,0.08,0.0],[127.6,25.0,99.0,122.9,0.0,0.08,0.0],[127.5,24.7,99.0,122.5,0.0,0.08,0.0],[125.9,24.2,99.0,122.1,0.0,0.08,0.0],[126.4,23.6,99.0,121.9,0.0,0.08,0.0],[127.7,22.9,99.0,121.8,0.0,0.08,0.0],[127.7,22.3,99.0,121.8,0.0,0.08,0.0],[127.7,21.8,99.0,121.8,0.0,0.08,0.0],[127.7,21.5,99.0,121.7,0.0,0.08,0.0],[127.6,21.3,99.0,121.7,0.0,0.08,0.0],[127.6,21.2,99.0,121.6,0.0,0.08,0.0],[127.6,21.1,99.0,121.5,0.0,0.08,0.0],[127.6,21.0,99.0,121.4,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,20.8,99.0,121.2,0.0,0.08,0.0],[127.6,20.6,99.0,121.1,0.0,0.08,0.0],[127.6,20.4,99.0,121.0,0.0,0.08,0.0],[127.6,20.2,99.0,120.9,0.0,0.08,0.0],[127.6,19.9,99.0,120.8,0.0,0.08,0.0],[127.6,19.7,99.0,120.6,0.0,0.08,0.0]]},"listen_blink":{"n":38,"loop":false,"scrub":false,"events":{},"role":"beat","state":"listening","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,19.2,99.0,120.5,0.0,0.08,0.0],[127.6,18.8,99.0,120.3,0.0,0.08,0.0],[127.5,18.4,99.0,120.1,0.0,0.08,0.0],[127.6,18.0,99.0,119.8,0.0,0.08,0.0],[127.6,17.6,99.0,119.7,0.0,0.08,0.0],[127.6,17.2,99.0,119.5,0.0,0.08,0.0],[127.7,16.8,99.0,119.4,0.0,0.08,0.0],[127.7,16.5,99.0,119.3,0.0,0.08,0.0],[127.7,16.3,99.0,119.2,0.0,0.08,0.0],[127.7,16.2,99.0,119.1,0.0,0.08,0.0],[127.7,16.2,99.0,119.1,0.0,0.08,0.0],[127.7,16.3,99.0,119.2,0.0,0.08,0.0],[127.7,16.5,99.0,119.2,0.0,0.08,0.0],[127.7,16.7,99.0,119.3,0.0,0.08,0.0],[127.7,17.0,99.0,119.5,0.0,0.08,0.0],[127.7,17.4,99.0,119.6,0.0,0.08,0.0],[127.7,17.8,99.0,119.8,0.0,0.08,0.0],[127.7,18.2,99.0,120.0,0.0,0.08,0.0],[127.6,18.6,99.0,120.2,0.0,0.08,0.0],[127.6,19.1,99.0,120.4,0.0,0.08,0.0],[127.6,19.6,99.0,120.7,0.0,0.08,0.0],[127.6,20.0,99.0,120.9,0.0,0.08,0.0],[127.6,20.5,99.0,121.1,0.0,0.08,0.0],[127.6,20.9,99.0,121.3,0.0,0.08,0.0],[127.6,21.3,99.0,121.4,0.0,0.08,0.0],[127.6,21.6,99.0,121.6,0.0,0.08,0.0],[127.6,21.8,99.0,121.7,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.1,99.0,121.8,0.0,0.08,0.0],[127.6,22.0,99.0,121.8,0.0,0.08,0.0],[127.6,21.8,99.0,121.7,0.0,0.08,0.0],[127.6,21.5,99.0,121.5,0.0,0.08,0.0],[127.6,21.2,99.0,121.4,0.0,0.08,0.0],[127.6,20.8,99.0,121.2,0.0,0.08,0.0],[127.6,20.4,99.0,121.0,0.0,0.08,0.0],[127.6,19.9,99.0,120.8,0.0,0.08,0.0]]},"thinking_in":{"n":24,"loop":false,"scrub":false,"events":{},"role":"enter","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.8,96.5,120.7,-0.1,0.0,0.0],[119.9,38.0,97.0,120.5,-0.1,0.0,0.0],[119.3,38.2,97.8,120.2,0.0,0.0,0.0],[118.7,38.6,98.8,119.8,-0.1,0.0,0.0],[117.3,39.2,99.8,119.5,0.1,0.0,0.0],[115.6,40.0,100.9,119.0,0.0,0.0,0.0],[113.3,40.8,101.9,118.5,0.1,0.0,0.0],[111.1,41.7,102.8,118.1,0.3,0.0,0.0],[109.7,42.7,103.7,117.7,0.6,0.0,0.0],[108.6,43.4,104.3,117.2,0.7,0.0,0.0],[107.5,43.9,105.1,116.8,0.7,0.0,0.0],[106.5,44.3,105.8,116.4,1.0,0.0,0.0],[105.3,44.8,106.4,116.1,1.2,0.0,0.0],[104.4,45.2,107.1,115.8,1.4,0.0,0.0],[103.1,45.7,107.7,115.5,1.7,0.0,0.0],[101.8,46.1,108.2,115.2,2.0,0.0,0.0],[100.6,46.4,108.7,114.9,2.1,0.0,0.0],[99.4,46.7,109.1,114.8,2.3,0.0,0.0],[98.7,46.9,109.3,114.7,2.5,0.0,0.0],[98.2,47.1,109.5,114.6,2.7,0.0,0.0],[97.6,47.3,109.7,114.6,2.8,0.0,0.0],[97.0,47.3,109.7,114.5,2.7,0.0,0.0]]},"thinking_rest":{"n":120,"loop":true,"scrub":false,"events":{},"role":"rest","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.8,0.0,0.0],[97.8,46.9,109.7,114.4,2.7,0.0,0.0],[97.9,46.8,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.6,109.7,114.2,2.7,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.9,46.3,109.7,114.1,2.8,0.0,0.0],[97.9,46.2,109.7,114.0,2.7,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.8,46.0,109.7,113.8,2.9,0.0,0.0],[97.8,45.9,109.7,113.8,2.9,0.0,0.0],[97.8,45.8,109.7,113.8,2.9,0.0,0.0],[97.9,45.7,109.7,113.7,2.7,0.0,0.0],[97.8,45.6,109.7,113.7,2.9,0.0,0.0],[97.7,45.5,109.7,113.7,2.9,0.0,0.0],[97.8,45.5,109.7,113.6,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.9,45.3,109.7,113.4,2.9,0.0,0.0],[97.7,45.2,109.7,113.4,2.9,0.0,0.0],[97.8,45.2,109.7,113.4,3.0,0.0,0.0],[97.8,45.1,109.7,113.3,2.9,0.0,0.0],[97.8,45.1,109.8,113.3,2.9,0.0,0.0],[97.7,45.0,109.8,113.3,2.9,0.0,0.0],[97.8,45.0,109.8,113.3,3.0,0.0,0.0],[97.7,44.9,109.8,113.2,2.9,0.0,0.0],[97.6,44.9,109.8,113.2,2.9,0.0,0.0],[97.6,44.9,109.8,113.2,2.9,0.0,0.0],[97.7,44.9,109.8,113.2,2.9,0.0,0.0],[97.7,44.9,109.9,113.2,2.9,0.0,0.0],[97.6,44.9,109.9,113.2,2.9,0.0,0.0],[97.5,44.9,109.9,113.2,2.9,0.0,0.0],[97.5,44.9,109.9,113.2,2.9,0.0,0.0],[97.5,44.9,110.0,113.3,3.1,0.0,0.0],[97.5,44.9,110.0,113.3,3.1,0.0,0.0],[97.6,45.0,110.0,113.3,3.1,0.0,0.0],[97.5,45.0,110.0,113.3,3.1,0.0,0.0],[97.5,45.1,110.1,113.3,3.1,0.0,0.0],[97.4,45.1,110.2,113.4,3.1,0.0,0.0],[97.4,45.2,110.2,113.4,3.1,0.0,0.0],[97.4,45.2,110.2,113.4,3.1,0.0,0.0],[97.3,45.3,110.2,113.5,3.3,0.0,0.0],[97.4,45.3,110.2,113.5,3.1,0.0,0.0],[97.4,45.4,110.2,113.5,3.3,0.0,0.0],[97.3,45.5,110.3,113.6,3.1,0.0,0.0],[97.3,45.6,110.3,113.7,3.3,0.0,0.0],[97.3,45.7,110.3,113.7,3.1,0.0,0.0],[97.2,45.8,110.3,113.8,3.3,0.0,0.0],[97.2,45.9,110.3,113.8,3.1,0.0,0.0],[97.2,46.0,110.3,113.8,3.3,0.0,0.0],[97.2,46.1,110.3,113.9,3.1,0.0,0.0],[97.2,46.2,110.3,114.0,3.3,0.0,0.0],[97.2,46.3,110.4,114.0,3.1,0.0,0.0],[97.1,46.4,110.4,114.1,3.1,0.0,0.0],[97.1,46.5,110.4,114.2,3.3,0.0,0.0],[97.2,46.6,110.4,114.2,3.1,0.0,0.0],[97.2,46.7,110.4,114.3,3.1,0.0,0.0],[97.2,46.9,110.4,114.3,3.3,0.0,0.0],[97.2,47.0,110.4,114.4,3.1,0.0,0.0],[97.1,47.1,110.4,114.5,3.1,0.0,0.0],[97.1,47.2,110.4,114.5,3.3,0.0,0.0],[97.2,47.3,110.4,114.6,3.1,0.0,0.0],[97.2,47.5,110.4,114.7,3.1,0.0,0.0],[97.2,47.6,110.3,114.8,2.9,0.0,0.0],[97.2,47.7,110.3,114.8,3.1,0.0,0.0],[97.4,47.8,110.3,114.9,3.1,0.0,0.0],[97.3,47.9,110.2,114.9,2.9,0.0,0.0],[97.4,48.0,110.2,115.0,3.1,0.0,0.0],[97.3,48.2,110.2,115.1,2.9,0.0,0.0],[97.4,48.3,110.2,115.2,2.9,0.0,0.0],[97.4,48.4,110.1,115.2,2.9,0.0,0.0],[97.7,48.4,110.0,115.2,2.9,0.0,0.0],[97.7,48.5,110.0,115.3,2.7,0.0,0.0],[97.7,48.6,109.9,115.3,2.8,0.0,0.0],[97.7,48.7,109.9,115.4,2.7,0.0,0.0],[97.7,48.8,109.8,115.4,2.8,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[97.9,48.9,109.8,115.5,2.7,0.0,0.0],[97.9,49.0,109.8,115.6,2.7,0.0,0.0],[97.7,49.1,109.8,115.6,2.7,0.0,0.0],[97.9,49.1,109.8,115.6,2.7,0.0,0.0],[97.8,49.2,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.5,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.9,49.4,109.8,115.8,2.7,0.0,0.0],[97.6,49.5,109.8,115.8,2.7,0.0,0.0],[97.6,49.5,109.8,115.8,2.7,0.0,0.0],[97.7,49.5,109.8,115.8,2.7,0.0,0.0],[97.6,49.5,109.8,115.8,2.7,0.0,0.0],[97.7,49.5,109.8,115.8,2.7,0.0,0.0],[97.9,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.5,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.8,49.2,109.8,115.7,2.7,0.0,0.0],[97.7,49.2,109.8,115.6,2.7,0.0,0.0],[97.7,49.1,109.8,115.6,2.7,0.0,0.0],[97.9,49.0,109.8,115.6,2.7,0.0,0.0],[97.7,49.0,109.8,115.5,2.7,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[97.7,48.8,109.8,115.4,2.7,0.0,0.0],[97.8,48.7,109.8,115.4,2.7,0.0,0.0],[97.9,48.6,109.8,115.3,2.7,0.0,0.0],[97.9,48.5,109.8,115.3,2.7,0.0,0.0],[97.9,48.4,109.8,115.2,2.7,0.0,0.0],[97.9,48.3,109.8,115.2,2.7,0.0,0.0],[97.9,48.2,109.8,115.1,2.7,0.0,0.0],[97.9,48.1,109.8,115.1,2.8,0.0,0.0],[97.9,48.0,109.8,115.0,2.7,0.0,0.0],[97.8,47.9,109.8,114.9,2.7,0.0,0.0],[97.8,47.8,109.8,114.8,2.8,0.0,0.0],[97.8,47.6,109.8,114.8,2.7,0.0,0.0],[97.8,47.5,109.7,114.7,2.7,0.0,0.0],[97.9,47.4,109.7,114.7,2.8,0.0,0.0],[97.9,47.3,109.7,114.6,2.7,0.0,0.0]]},"think_swap":{"n":91,"loop":false,"scrub":false,"events":{},"role":"beat","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.8,0.0,0.0],[97.9,46.9,109.7,114.3,2.8,0.0,0.0],[97.8,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.6,109.7,114.2,2.8,0.0,0.0],[97.8,46.4,109.7,114.1,2.8,0.0,0.0],[97.8,46.2,109.7,114.0,2.7,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.8,45.9,109.7,113.8,2.9,0.0,0.0],[97.8,45.8,109.7,113.8,2.9,0.0,0.0],[97.8,45.7,109.7,113.7,2.7,0.0,0.0],[97.9,45.6,109.5,113.6,2.7,0.0,0.0],[98.2,45.6,109.0,113.5,2.6,0.0,0.0],[98.4,45.7,107.8,113.4,2.2,0.0,0.0],[99.5,45.8,106.0,113.2,1.8,0.0,0.0],[101.5,45.9,103.5,113.1,1.0,0.0,0.0],[103.9,45.8,100.8,112.8,0.4,0.0,0.0],[108.0,45.5,97.7,112.7,-0.3,0.0,0.0],[113.1,45.1,94.8,112.6,-0.9,0.0,0.0],[117.2,44.6,92.2,112.5,-1.7,0.0,0.0],[123.7,43.9,90.2,112.5,-2.3,0.0,0.0],[129.9,43.4,88.8,112.5,-2.7,0.0,0.0],[133.4,41.4,88.0,112.5,-3.1,0.0,0.0],[137.1,39.7,87.6,112.5,-3.4,0.0,0.0],[139.5,39.0,87.6,112.5,-3.4,0.0,0.0],[139.7,39.2,87.6,112.5,-3.2,0.0,0.0],[136.6,40.1,87.6,112.5,-3.4,0.0,0.0],[134.0,41.4,87.6,112.5,-3.4,0.0,0.0],[132.1,42.8,87.6,112.5,-3.4,0.0,0.0],[130.8,43.6,87.6,112.6,-3.2,0.0,0.0],[129.6,43.8,87.6,112.7,-3.4,0.0,0.0],[129.1,43.9,87.6,112.7,-3.4,0.0,0.0],[129.2,44.0,87.6,112.8,-3.4,0.0,0.0],[129.4,44.0,87.6,112.8,-3.2,0.0,0.0],[130.3,44.1,87.5,112.8,-3.4,0.0,0.0],[130.9,44.1,87.5,112.9,-3.2,0.0,0.0],[131.3,44.2,87.5,113.0,-3.2,0.0,0.0],[131.5,44.1,87.5,113.0,-3.3,0.0,0.0],[131.8,44.1,87.5,113.2,-3.3,0.0,0.0],[131.5,44.3,87.5,113.2,-3.2,0.0,0.0],[131.4,44.5,87.5,113.3,-3.2,0.0,0.0],[131.2,44.8,87.5,113.4,-3.2,0.0,0.0],[131.2,45.1,87.5,113.5,-3.3,0.0,0.0],[131.2,45.2,87.5,113.5,-3.3,0.0,0.0],[131.2,45.4,87.5,113.7,-3.3,0.0,0.0],[131.1,45.6,87.5,113.7,-3.2,0.0,0.0],[130.9,45.7,87.5,113.8,-3.2,0.0,0.0],[131.1,45.9,87.5,113.9,-3.2,0.0,0.0],[131.0,46.1,87.5,114.0,-3.2,0.0,0.0],[131.1,46.2,87.5,114.1,-3.2,0.0,0.0],[131.2,46.4,87.5,114.2,-3.2,0.0,0.0],[131.3,46.5,87.5,114.3,-3.2,0.0,0.0],[131.3,46.6,87.5,114.3,-3.2,0.0,0.0],[131.3,46.8,87.4,114.4,-3.2,0.0,0.0],[131.3,46.9,87.4,114.5,-3.2,0.0,0.0],[131.2,47.1,87.4,114.6,-3.2,0.0,0.0],[131.2,47.2,87.4,114.6,-3.2,0.0,0.0],[131.2,47.3,87.4,114.7,-3.2,0.0,0.0],[131.3,47.4,87.4,114.8,-3.0,0.0,0.0],[131.3,47.5,87.5,114.8,-3.1,0.0,0.0],[130.9,47.6,87.8,114.8,-2.9,0.0,0.0],[130.7,47.6,88.2,114.9,-2.7,0.0,0.0],[130.3,47.5,89.0,115.0,-2.5,0.0,0.0],[129.7,47.5,90.2,115.0,-2.2,0.0,0.0],[128.3,47.8,91.7,115.0,-1.7,0.0,0.0],[126.7,48.1,93.5,115.1,-1.2,0.0,0.0],[123.6,48.3,95.6,115.2,-0.7,0.0,0.0],[119.5,48.5,97.8,115.2,-0.3,0.0,0.0],[114.1,48.7,100.2,115.3,0.3,0.0,0.0],[109.3,48.9,102.4,115.4,0.9,0.0,0.0],[107.3,49.1,104.5,115.5,1.2,0.0,0.0],[102.9,49.3,106.2,115.5,1.7,0.0,0.0],[100.0,49.5,107.5,115.7,2.0,0.0,0.0],[98.3,49.6,108.6,115.7,2.2,0.0,0.0],[96.3,49.7,109.2,115.7,2.4,0.0,0.0],[95.6,49.7,109.6,115.7,2.6,0.0,0.0],[95.5,49.7,109.8,115.6,2.7,0.0,0.0],[95.6,49.5,109.8,115.6,2.7,0.0,0.0],[96.1,49.3,109.8,115.5,2.7,0.0,0.0],[97.3,49.1,109.8,115.5,2.7,0.0,0.0],[97.8,48.8,109.8,115.4,2.7,0.0,0.0],[97.9,48.6,109.8,115.3,2.8,0.0,0.0],[98.3,48.4,109.8,115.3,2.7,0.0,0.0],[99.0,48.2,109.8,115.2,2.7,0.0,0.0],[98.8,48.1,109.8,115.1,2.7,0.0,0.0],[98.2,48.0,109.8,115.1,2.8,0.0,0.0],[98.1,47.9,109.8,115.0,2.7,0.0,0.0],[97.9,47.8,109.8,114.9,2.7,0.0,0.0],[97.8,47.7,109.8,114.8,2.7,0.0,0.0],[97.7,47.6,109.7,114.7,2.7,0.0,0.0],[97.7,47.4,109.7,114.6,2.7,0.0,0.0]]},"think_squint":{"n":82,"loop":false,"scrub":false,"events":{},"role":"beat","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.9,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.9,46.0,109.7,113.8,2.9,0.0,0.0],[97.9,45.8,109.7,113.8,2.9,0.0,0.0],[97.8,45.7,109.7,113.7,2.9,0.0,0.0],[97.7,45.5,109.7,113.7,2.9,0.0,0.0],[98.0,45.3,109.7,113.7,2.7,0.0,0.0],[98.6,44.9,109.7,114.2,2.3,0.01,0.0],[100.0,44.1,109.6,115.2,1.8,0.01,0.0],[101.9,43.0,109.2,116.9,1.1,0.02,0.0],[104.9,41.9,108.5,119.2,0.4,0.04,0.0],[107.7,40.9,107.3,122.2,-0.3,0.06,0.0],[111.6,39.2,105.7,125.5,-0.5,0.07,0.0],[120.4,37.3,103.8,128.8,-0.5,0.09,0.0],[127.4,36.1,101.9,131.8,-0.4,0.1,0.0],[129.1,35.8,100.3,133.9,-0.1,0.11,0.0],[130.4,35.9,99.4,135.3,0.0,0.11,0.0],[130.7,36.3,99.1,135.9,-0.1,0.12,0.0],[130.7,36.4,99.0,135.9,0.0,0.12,0.0],[130.8,36.4,99.0,135.9,0.0,0.12,0.0],[130.8,36.1,99.0,136.0,0.0,0.12,0.0],[130.8,36.0,99.0,136.0,0.0,0.12,0.0],[130.3,35.9,99.0,136.1,0.0,0.12,0.0],[129.6,36.0,99.0,136.1,0.0,0.12,0.0],[129.1,36.2,99.0,136.2,0.0,0.12,0.0],[128.8,36.4,99.0,136.2,0.0,0.12,0.0],[128.7,36.6,99.0,136.3,0.0,0.12,0.0],[128.8,36.8,99.0,136.4,0.0,0.12,0.0],[129.2,37.0,99.0,136.4,0.0,0.12,0.0],[129.4,37.2,99.0,136.5,0.0,0.12,0.0],[129.6,37.3,99.0,136.6,0.0,0.12,0.0],[129.8,37.5,99.0,136.7,0.0,0.12,0.0],[129.9,37.7,99.0,136.8,0.0,0.12,0.0],[129.9,37.8,99.0,136.9,0.0,0.12,0.0],[129.9,38.0,99.0,137.0,0.0,0.12,0.0],[129.8,38.2,99.0,137.1,0.0,0.12,0.0],[129.7,38.4,99.0,137.1,0.0,0.12,0.0],[129.6,38.7,99.0,137.2,0.0,0.12,0.0],[129.6,38.9,99.0,137.3,0.0,0.12,0.0],[129.5,39.1,99.0,137.4,0.0,0.12,0.0],[129.5,39.3,99.0,137.5,0.0,0.12,0.0],[129.5,39.5,99.0,137.6,0.0,0.12,0.0],[129.5,39.7,99.0,137.7,0.0,0.12,0.0],[129.6,39.9,99.0,137.8,0.0,0.12,0.0],[129.6,40.0,99.0,137.9,0.0,0.12,0.0],[129.6,40.2,99.0,137.9,0.0,0.12,0.0],[129.6,40.3,99.0,138.0,0.0,0.12,0.0],[129.7,40.5,99.2,137.9,-0.1,0.12,0.0],[129.9,40.5,99.7,137.2,-0.1,0.11,0.0],[130.1,40.5,100.4,136.2,-0.3,0.11,0.0],[130.1,40.4,101.6,134.6,-0.4,0.1,0.0],[127.9,40.4,103.1,132.4,-0.5,0.09,0.0],[125.5,40.5,104.6,129.9,-0.7,0.08,0.0],[123.2,41.0,106.1,127.3,-0.4,0.07,0.0],[119.8,42.0,107.4,124.8,-0.3,0.06,0.0],[111.7,43.6,108.4,122.5,0.1,0.04,0.0],[107.2,45.7,109.1,120.4,0.6,0.03,0.0],[103.8,47.2,109.5,118.7,1.2,0.02,0.0],[101.3,48.1,109.7,117.5,1.8,0.01,0.0],[98.4,48.9,109.8,116.6,2.1,0.01,0.0],[97.8,49.5,109.8,116.0,2.5,0.0,0.0],[97.4,49.9,109.8,115.8,2.7,0.0,0.0],[97.2,50.0,109.8,115.7,2.7,0.0,0.0],[97.4,49.8,109.8,115.6,2.7,0.0,0.0],[97.4,49.6,109.8,115.6,2.7,0.0,0.0],[97.1,49.2,109.8,115.5,2.7,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[98.1,48.7,109.8,115.4,2.7,0.0,0.0],[98.6,48.4,109.8,115.3,2.7,0.0,0.0],[98.7,48.2,109.8,115.2,2.7,0.0,0.0],[98.6,48.1,109.8,115.2,2.8,0.0,0.0],[98.4,48.0,109.8,115.1,2.8,0.0,0.0],[98.1,47.8,109.8,115.0,2.7,0.0,0.0],[97.9,47.7,109.8,114.9,2.7,0.0,0.0],[97.7,47.6,109.8,114.8,2.7,0.0,0.0],[97.6,47.5,109.7,114.7,2.7,0.0,0.0],[97.6,47.4,109.7,114.6,2.7,0.0,0.0]]},"think_hm":{"n":67,"loop":false,"scrub":false,"events":{},"role":"beat","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.9,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.8,109.7,114.2,2.8,0.0,0.0],[97.9,46.6,109.7,114.2,2.8,0.0,0.0],[97.9,46.4,109.7,114.1,2.8,0.0,0.0],[97.9,46.2,109.7,113.9,2.9,0.0,0.0],[97.8,45.9,109.7,113.8,2.9,0.0,0.0],[97.7,45.7,109.7,113.8,2.9,0.0,0.0],[97.8,45.6,109.7,113.7,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.6,45.0,109.5,113.2,2.9,0.0,0.0],[97.4,44.6,109.4,112.9,2.9,0.0,0.0],[97.9,44.8,109.2,113.2,2.9,0.0,0.0],[97.5,45.9,109.2,113.8,2.8,0.0,0.0],[97.8,47.5,109.2,114.8,2.7,0.0,0.0],[98.1,49.3,109.2,115.8,2.6,0.0,0.0],[98.6,51.0,109.2,116.5,2.5,0.0,0.0],[99.2,52.1,109.2,117.0,2.5,0.0,0.0],[99.1,52.5,109.2,117.0,2.5,0.0,0.0],[97.3,42.8,108.7,107.8,3.3,0.0,0.0],[97.5,35.7,108.6,103.0,3.8,0.0,0.0],[99.1,30.6,108.5,101.3,3.9,0.0,0.0],[99.7,27.4,108.5,101.5,3.9,0.0,0.0],[100.2,26.3,108.5,102.5,3.9,0.0,0.0],[100.4,26.3,108.6,103.2,3.7,0.0,0.0],[100.5,27.0,108.6,103.2,3.7,0.0,0.0],[100.1,28.6,108.6,103.3,3.7,0.0,0.0],[99.9,30.3,108.7,103.5,3.7,0.0,0.0],[98.5,31.9,108.7,103.5,3.7,0.0,0.0],[98.4,32.9,108.7,103.7,3.7,0.0,0.0],[98.4,33.4,108.6,103.8,3.7,0.0,0.0],[98.5,33.4,108.6,104.0,3.7,0.0,0.0],[99.5,33.1,108.6,104.0,3.7,0.0,0.0],[99.6,32.7,108.6,104.2,3.5,0.0,0.0],[99.9,32.5,108.7,104.3,3.7,0.0,0.0],[99.9,32.4,108.7,104.5,3.7,0.0,0.0],[99.9,32.5,108.7,104.6,3.5,0.0,0.0],[99.9,32.8,108.7,104.7,3.5,0.0,0.0],[99.6,33.3,108.7,104.8,3.7,0.0,0.0],[99.6,33.7,108.7,105.0,3.7,0.0,0.0],[99.6,34.2,108.7,105.2,3.5,0.0,0.0],[99.6,34.9,108.7,105.6,3.5,0.0,0.0],[99.4,35.9,108.8,106.3,3.5,0.0,0.0],[99.0,37.2,108.9,107.3,3.4,0.0,0.0],[99.2,38.7,109.0,108.5,3.3,0.0,0.0],[98.5,40.6,109.2,109.8,3.1,0.0,0.0],[98.6,42.5,109.3,111.2,3.0,0.0,0.0],[97.8,44.5,109.4,112.5,3.0,0.0,0.0],[97.9,46.4,109.5,113.7,2.9,0.0,0.0],[97.5,47.9,109.7,114.6,2.7,0.0,0.0],[97.7,49.0,109.7,115.3,2.7,0.0,0.0],[97.8,49.7,109.8,115.6,2.7,0.0,0.0],[98.1,49.9,109.8,115.8,2.7,0.0,0.0],[98.1,49.8,109.8,115.8,2.7,0.0,0.0],[97.9,49.6,109.8,115.7,2.7,0.0,0.0],[97.9,49.3,109.8,115.7,2.7,0.0,0.0],[97.9,49.1,109.8,115.6,2.7,0.0,0.0],[97.8,48.9,109.8,115.6,2.7,0.0,0.0],[97.8,48.7,109.8,115.5,2.7,0.0,0.0],[97.7,48.6,109.8,115.4,2.7,0.0,0.0],[97.6,48.5,109.8,115.3,2.7,0.0,0.0],[97.7,48.4,109.8,115.2,2.7,0.0,0.0],[97.7,48.3,109.8,115.1,2.7,0.0,0.0],[97.8,48.1,109.8,115.0,2.7,0.0,0.0],[97.9,47.9,109.8,114.9,2.7,0.0,0.0],[97.9,47.7,109.8,114.8,2.7,0.0,0.0],[97.9,47.5,109.7,114.7,2.8,0.0,0.0]]},"think_count":{"n":82,"loop":false,"scrub":false,"events":{},"role":"beat","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.9,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.9,46.0,109.7,113.8,2.9,0.0,0.0],[97.9,45.8,109.7,113.8,2.9,0.0,0.0],[97.9,45.7,109.7,113.7,2.9,0.0,0.0],[98.7,45.1,110.2,114.4,2.7,0.0,0.0],[100.3,44.1,111.2,116.3,2.0,0.0,0.0],[102.2,43.3,112.2,118.0,1.5,0.0,0.0],[104.4,42.7,113.1,119.7,1.0,0.0,0.0],[105.5,42.4,113.7,121.2,0.5,0.0,0.0],[107.8,41.2,114.2,122.4,0.3,0.0,0.0],[110.2,40.1,114.6,123.4,0.0,0.0,0.0],[110.7,39.2,115.0,124.2,-0.2,0.0,0.0],[112.3,38.8,115.1,124.7,-0.5,0.0,0.0],[112.7,38.5,115.2,124.8,-0.5,0.0,0.0],[112.1,38.4,115.0,124.1,-0.3,0.0,0.0],[108.5,39.0,113.2,119.8,0.8,0.0,0.0],[103.9,41.1,110.7,115.0,2.3,0.0,0.0],[100.2,43.4,109.7,113.2,2.9,0.0,0.0],[101.3,42.9,111.4,116.3,1.8,0.0,0.0],[104.1,42.5,113.3,120.2,0.8,0.0,0.0],[106.4,42.6,114.5,123.1,0.0,0.0,0.0],[107.7,42.5,115.1,124.7,-0.3,0.0,0.0],[108.5,42.6,115.2,124.9,-0.5,0.0,0.0],[108.6,41.1,114.0,122.1,0.3,0.0,0.0],[105.9,41.3,111.7,117.0,1.7,0.0,0.0],[102.5,42.9,109.8,114.0,2.7,0.0,0.0],[101.9,43.3,110.5,115.1,2.3,0.0,0.0],[103.6,43.2,112.7,119.2,1.2,0.0,0.0],[106.4,42.9,114.1,122.6,0.3,0.0,0.0],[107.9,43.1,115.0,124.8,-0.3,0.0,0.0],[108.2,43.5,115.2,125.6,-0.5,0.0,0.0],[109.1,42.5,114.8,124.3,-0.2,0.0,0.0],[106.9,42.3,112.7,119.8,1.2,0.0,0.0],[103.0,44.0,110.4,115.5,2.3,0.0,0.0],[100.7,45.5,109.7,114.4,2.8,0.0,0.0],[102.5,45.1,112.0,118.5,1.5,0.0,0.0],[105.1,44.5,113.7,122.2,0.5,0.0,0.0],[107.3,44.6,114.8,124.8,-0.2,0.0,0.0],[108.5,44.9,115.3,126.2,-0.5,0.0,0.0],[108.9,44.4,115.2,126.1,-0.5,0.0,0.0],[108.7,43.5,113.8,122.6,0.5,0.0,0.0],[104.7,44.5,111.2,117.7,1.8,0.0,0.0],[101.9,46.3,109.8,115.3,2.7,0.0,0.0],[100.0,47.5,109.8,115.3,2.7,0.0,0.0],[99.2,48.2,109.8,115.4,2.7,0.0,0.0],[97.7,48.6,109.8,115.4,2.7,0.0,0.0],[99.1,49.2,109.8,115.5,2.7,0.0,0.0],[99.8,49.7,109.8,115.6,2.7,0.0,0.0],[99.6,50.0,109.8,115.6,2.7,0.0,0.0],[100.0,50.0,109.8,115.7,2.7,0.0,0.0],[98.8,49.9,109.8,115.7,2.7,0.0,0.0],[98.3,49.7,109.8,115.7,2.7,0.0,0.0],[97.8,49.5,109.8,115.8,2.7,0.0,0.0],[98.1,49.4,109.8,115.8,2.7,0.0,0.0],[98.2,49.3,109.8,115.8,2.7,0.0,0.0],[98.0,49.2,109.8,115.8,2.7,0.0,0.0],[98.2,49.2,109.8,115.8,2.7,0.0,0.0],[98.2,49.2,109.8,115.8,2.7,0.0,0.0],[97.8,49.3,109.8,115.8,2.7,0.0,0.0],[97.8,49.3,109.8,115.8,2.7,0.0,0.0],[97.6,49.3,109.8,115.7,2.7,0.0,0.0],[97.6,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.6,2.7,0.0,0.0],[97.7,49.2,109.8,115.6,2.7,0.0,0.0],[97.7,49.0,109.8,115.5,2.7,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[97.8,48.7,109.8,115.4,2.7,0.0,0.0],[97.8,48.6,109.8,115.3,2.7,0.0,0.0],[97.8,48.4,109.8,115.2,2.7,0.0,0.0],[97.8,48.3,109.8,115.2,2.8,0.0,0.0],[97.9,48.1,109.8,115.1,2.8,0.0,0.0],[98.0,47.9,109.8,115.0,2.7,0.0,0.0],[97.8,47.8,109.8,114.9,2.7,0.0,0.0],[97.9,47.6,109.8,114.8,2.7,0.0,0.0],[97.8,47.5,109.7,114.7,2.7,0.0,0.0],[97.8,47.3,109.7,114.6,2.7,0.0,0.0]]},"think_sigh":{"n":82,"loop":false,"scrub":false,"events":{},"role":"beat","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.9,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.9,46.0,109.7,113.8,2.9,0.0,0.0],[97.8,45.8,109.7,113.8,2.9,0.0,0.0],[97.8,45.7,109.7,113.7,2.9,0.0,0.0],[97.7,45.5,109.7,113.7,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.8,45.1,109.7,113.3,2.9,0.0,0.0],[97.9,44.5,109.6,112.9,2.9,0.0,0.0],[97.8,43.8,109.5,112.4,2.9,0.0,0.0],[97.9,42.7,109.5,111.8,3.0,0.0,0.0],[97.9,41.4,109.5,111.0,3.0,0.0,0.0],[98.2,39.8,109.4,110.1,3.1,0.0,0.0],[98.4,38.1,109.5,109.2,2.9,0.0,0.0],[98.4,36.2,109.4,108.2,3.1,0.0,0.0],[98.5,34.4,109.3,107.2,3.1,0.0,0.0],[98.8,32.7,109.3,106.3,2.9,0.0,0.0],[99.2,31.1,109.3,105.6,3.1,0.0,0.0],[99.2,29.8,109.2,104.9,2.9,0.0,0.0],[99.5,28.7,109.3,104.6,2.9,0.0,0.0],[99.6,28.0,109.3,104.3,2.8,0.0,0.0],[99.7,27.6,109.4,104.2,2.6,0.0,0.0],[99.8,27.4,109.4,104.2,2.6,0.0,0.0],[99.8,27.3,109.4,104.4,2.4,0.0,0.0],[99.9,27.3,109.5,104.6,2.2,0.0,0.0],[99.9,27.6,109.6,104.9,2.0,0.0,0.0],[100.3,28.1,109.7,105.5,1.9,0.0,0.0],[100.5,29.0,109.7,106.2,1.7,0.0,0.0],[100.3,30.4,109.8,107.2,1.5,0.0,0.0],[100.1,32.3,109.8,108.5,1.3,0.0,0.0],[100.1,34.6,109.9,110.0,1.0,0.0,0.0],[100.0,37.3,110.0,111.8,0.8,0.0,0.0],[100.2,40.3,110.1,113.5,0.7,0.0,0.0],[100.5,43.6,110.2,115.4,0.3,0.0,0.0],[100.3,46.9,110.2,117.3,0.2,0.0,0.0],[100.3,50.2,110.3,119.2,-0.2,0.0,0.0],[100.5,53.3,110.4,121.0,-0.3,0.0,0.0],[100.2,56.1,110.5,122.7,-0.5,0.0,0.0],[99.9,58.5,110.5,124.0,-0.8,0.0,0.0],[99.9,60.5,110.6,125.2,-0.8,0.0,0.0],[99.8,62.1,110.6,126.2,-0.9,0.0,0.0],[99.9,63.2,110.7,126.8,-1.1,0.0,0.0],[99.8,63.9,110.7,127.3,-0.9,0.0,0.0],[99.9,64.2,110.7,127.5,-0.9,0.0,0.0],[99.8,64.4,110.7,127.7,-1.1,0.0,0.0],[99.8,64.4,110.7,127.7,-0.9,0.0,0.0],[99.8,64.4,110.7,127.8,-1.1,0.0,0.0],[99.8,64.4,110.7,127.8,-1.1,0.0,0.0],[99.8,64.5,110.7,127.8,-1.1,0.0,0.0],[99.8,64.6,110.7,128.0,-1.1,0.0,0.0],[99.8,64.7,110.7,128.0,-1.1,0.0,0.0],[99.8,64.8,110.7,128.1,-1.1,0.0,0.0],[99.8,64.9,110.7,128.1,-1.1,0.0,0.0],[99.8,65.0,110.7,128.1,-1.1,0.0,0.0],[99.8,65.0,110.7,128.2,-1.1,0.0,0.0],[99.8,65.0,110.7,128.2,-1.1,0.0,0.0],[99.8,64.7,110.7,127.8,-1.1,0.0,0.0],[99.6,63.2,110.7,126.3,-0.5,0.0,0.0],[99.7,60.2,110.5,123.6,0.3,0.0,0.0],[99.5,56.4,110.3,120.4,1.1,0.0,0.0],[98.9,52.8,110.0,117.7,2.0,0.0,0.0],[98.6,50.0,109.8,116.2,2.5,0.0,0.0],[97.9,48.6,109.8,115.7,2.7,0.0,0.0],[98.1,47.9,109.8,115.6,2.7,0.0,0.0],[98.1,47.7,109.8,115.6,2.7,0.0,0.0],[98.1,47.9,109.8,115.5,2.7,0.0,0.0],[98.0,48.3,109.8,115.5,2.7,0.0,0.0],[97.3,48.7,109.8,115.4,2.7,0.0,0.0],[97.5,48.9,109.8,115.3,2.7,0.0,0.0],[97.7,49.0,109.8,115.2,2.7,0.0,0.0],[97.9,48.9,109.8,115.2,2.8,0.0,0.0],[97.8,48.6,109.8,115.1,2.8,0.0,0.0],[98.0,48.2,109.8,115.0,2.7,0.0,0.0],[98.0,47.8,109.8,114.9,2.7,0.0,0.0],[97.9,47.5,109.8,114.8,2.7,0.0,0.0],[98.0,47.2,109.7,114.7,2.7,0.0,0.0],[97.8,47.0,109.7,114.6,2.7,0.0,0.0]]},"think_roll":{"n":86,"loop":false,"scrub":false,"events":{},"role":"beat","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.8,0.0,0.0],[97.9,46.9,109.7,114.3,2.8,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.8,46.5,109.7,114.2,2.8,0.0,0.0],[97.9,46.4,109.7,114.1,2.8,0.0,0.0],[97.8,46.2,109.7,113.9,2.9,0.0,0.0],[97.8,46.0,109.7,113.9,2.7,0.0,0.0],[97.8,45.9,109.7,113.8,2.7,0.0,0.0],[97.7,45.7,109.7,113.8,2.9,0.0,0.0],[97.8,45.6,109.7,113.7,2.9,0.0,0.0],[97.9,45.5,109.7,113.6,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.9,45.3,109.7,113.4,2.9,0.0,0.0],[97.8,45.2,109.7,113.4,2.9,0.0,0.0],[97.7,45.1,109.7,113.3,2.9,0.0,0.0],[97.8,45.1,109.7,113.3,2.9,0.0,0.0],[97.9,45.0,109.7,113.2,2.9,0.0,0.0],[97.9,44.9,109.7,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.8,44.9,109.6,113.2,2.9,0.0,0.0],[97.9,44.9,109.7,113.2,2.9,0.0,0.0],[97.8,45.0,109.7,113.2,2.9,0.0,0.0],[97.9,45.0,109.7,113.3,2.9,0.0,0.0],[97.8,45.1,109.7,113.3,2.9,0.0,0.0],[97.8,45.2,109.7,113.4,2.9,0.0,0.0],[97.8,45.3,109.7,113.4,2.9,0.0,0.0],[97.8,45.4,109.7,113.6,2.9,0.0,0.0],[97.8,45.5,109.7,113.6,2.9,0.0,0.0],[97.8,45.6,109.7,113.7,2.9,0.0,0.0],[97.8,45.7,109.7,113.8,2.9,0.0,0.0],[97.9,45.9,109.7,113.8,2.7,0.0,0.0],[97.8,46.0,109.7,113.8,2.9,0.0,0.0],[97.9,46.2,109.7,113.9,2.9,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.6,109.7,114.2,2.8,0.0,0.0],[97.9,46.8,109.7,114.3,2.7,0.0,0.0],[97.9,47.0,109.7,114.4,2.7,0.0,0.0],[97.8,47.1,109.7,114.5,2.7,0.0,0.0],[97.9,47.3,109.7,114.6,2.7,0.0,0.0],[97.8,47.5,109.7,114.7,2.7,0.0,0.0],[97.8,47.6,109.8,114.8,2.7,0.0,0.0],[97.9,47.8,109.8,114.9,2.7,0.0,0.0],[97.8,48.0,109.8,114.9,2.8,0.0,0.0],[97.9,48.1,109.8,115.1,2.8,0.0,0.0],[97.8,48.3,109.8,115.1,2.7,0.0,0.0],[97.9,48.4,109.8,115.2,2.7,0.0,0.0],[97.9,48.5,109.8,115.3,2.7,0.0,0.0],[97.7,48.7,109.8,115.4,2.7,0.0,0.0],[97.7,48.8,109.8,115.4,2.7,0.0,0.0],[97.8,48.9,109.8,115.5,2.7,0.0,0.0],[97.8,49.0,109.8,115.6,2.7,0.0,0.0],[97.8,49.1,109.8,115.6,2.7,0.0,0.0],[97.7,49.2,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.8,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.8,49.4,109.8,115.8,2.7,0.0,0.0],[97.9,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.5,109.8,115.8,2.7,0.0,0.0],[97.6,49.5,109.8,115.8,2.7,0.0,0.0],[97.7,49.5,109.8,115.8,2.7,0.0,0.0],[97.9,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.9,49.2,109.8,115.7,2.7,0.0,0.0],[97.7,49.2,109.8,115.6,2.7,0.0,0.0],[97.7,49.1,109.8,115.6,2.7,0.0,0.0],[97.7,49.0,109.8,115.5,2.7,0.0,0.0],[97.7,48.9,109.8,115.5,2.7,0.0,0.0],[97.9,48.7,109.8,115.4,2.7,0.0,0.0],[97.9,48.6,109.8,115.3,2.7,0.0,0.0],[97.8,48.5,109.8,115.3,2.7,0.0,0.0],[97.9,48.3,109.8,115.2,2.7,0.0,0.0],[97.9,48.2,109.8,115.1,2.7,0.0,0.0],[97.9,48.0,109.8,115.0,2.7,0.0,0.0],[97.9,47.9,109.8,114.9,2.7,0.0,0.0],[97.9,47.7,109.8,114.8,2.8,0.0,0.0],[97.8,47.6,109.7,114.8,2.8,0.0,0.0],[97.9,47.4,109.7,114.7,2.8,0.0,0.0]]},"think_down":{"n":82,"loop":false,"scrub":false,"events":{},"role":"beat","state":"thinking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[97.9,47.2,109.7,114.5,2.7,0.0,0.0],[97.8,47.0,109.7,114.4,2.7,0.0,0.0],[97.9,46.9,109.7,114.3,2.7,0.0,0.0],[97.9,46.7,109.7,114.2,2.8,0.0,0.0],[97.9,46.5,109.7,114.2,2.8,0.0,0.0],[97.8,46.3,109.7,114.1,2.8,0.0,0.0],[97.8,46.1,109.7,113.9,2.9,0.0,0.0],[97.9,46.0,109.7,113.8,2.9,0.0,0.0],[97.9,45.8,109.7,113.8,2.9,0.0,0.0],[97.8,45.7,109.7,113.7,2.9,0.0,0.0],[97.7,45.5,109.7,113.7,2.9,0.0,0.0],[98.0,45.3,109.7,113.7,2.9,0.0,0.0],[98.4,44.8,109.7,114.0,2.5,0.0,0.0],[99.6,44.0,109.5,114.6,2.1,0.0,0.0],[101.1,42.7,109.3,115.6,1.6,0.0,0.0],[103.9,41.2,108.7,117.2,0.9,0.0,0.0],[106.4,39.6,107.8,119.2,0.4,0.0,0.0],[109.0,37.6,106.5,121.5,-0.1,0.0,0.0],[115.8,34.8,104.8,124.0,-0.3,0.0,0.0],[123.3,32.4,103.0,126.3,-0.4,0.0,0.0],[126.9,31.0,101.5,128.5,-0.3,0.0,0.0],[128.1,30.5,100.2,130.1,-0.1,0.0,0.0],[128.6,30.5,99.4,131.1,-0.1,0.0,0.0],[128.7,30.7,99.1,131.5,0.0,0.0,0.0],[129.0,30.9,99.0,131.6,0.0,0.0,0.0],[129.0,30.9,99.0,131.6,0.0,0.0,0.0],[128.6,30.9,99.1,131.6,0.0,0.0,0.0],[128.3,30.8,99.1,131.6,0.0,0.0,0.0],[128.1,30.8,99.2,131.6,0.0,0.0,0.0],[127.7,30.9,99.2,131.5,0.0,0.0,0.0],[127.3,31.1,99.4,131.4,-0.1,0.0,0.0],[127.2,31.3,99.7,131.1,-0.1,0.0,0.0],[127.3,31.5,99.9,130.9,0.0,0.0,0.0],[127.5,31.7,100.2,130.6,-0.1,0.0,0.0],[127.8,31.9,100.6,130.2,-0.3,0.0,0.0],[128.0,32.2,101.0,129.8,-0.1,0.0,0.0],[128.1,32.5,101.5,129.2,-0.3,0.0,0.0],[127.5,32.8,102.0,128.7,-0.3,0.0,0.0],[127.0,33.2,102.5,128.1,-0.4,0.0,0.0],[126.2,33.6,103.1,127.4,-0.3,0.0,0.0],[124.3,34.1,103.7,126.8,-0.4,0.0,0.0],[123.8,34.8,104.3,126.0,-0.3,0.0,0.0],[122.3,35.5,104.8,125.3,-0.3,0.0,0.0],[121.3,36.3,105.4,124.5,-0.1,0.0,0.0],[119.5,37.2,106.0,123.8,-0.3,0.0,0.0],[117.4,38.2,106.5,123.0,-0.1,0.0,0.0],[113.2,39.2,107.0,122.4,0.0,0.0,0.0],[111.3,40.2,107.5,121.7,0.1,0.0,0.0],[109.8,41.3,107.8,121.0,0.3,0.0,0.0],[108.6,42.3,108.2,120.3,0.4,0.0,0.0],[107.5,43.3,108.6,119.8,0.6,0.0,0.0],[105.7,44.4,108.8,119.2,0.8,0.0,0.0],[105.2,45.1,109.1,118.8,1.1,0.0,0.0],[104.4,45.7,109.2,118.2,1.1,0.0,0.0],[103.4,46.2,109.4,117.8,1.4,0.0,0.0],[102.5,46.8,109.5,117.5,1.6,0.0,0.0],[101.4,47.3,109.5,117.2,1.8,0.0,0.0],[100.9,47.8,109.7,116.9,1.9,0.0,0.0],[100.2,48.2,109.7,116.7,2.1,0.0,0.0],[99.4,48.6,109.8,116.4,2.3,0.0,0.0],[98.6,48.9,109.8,116.2,2.5,0.0,0.0],[98.4,49.1,109.8,116.1,2.3,0.0,0.0],[98.0,49.3,109.8,116.0,2.5,0.0,0.0],[97.8,49.4,109.8,115.9,2.7,0.0,0.0],[97.7,49.4,109.8,115.8,2.7,0.0,0.0],[97.6,49.4,109.8,115.8,2.7,0.0,0.0],[97.7,49.4,109.8,115.7,2.7,0.0,0.0],[97.7,49.3,109.8,115.7,2.7,0.0,0.0],[97.7,49.2,109.8,115.6,2.7,0.0,0.0],[97.7,49.1,109.8,115.6,2.7,0.0,0.0],[97.8,49.0,109.8,115.5,2.7,0.0,0.0],[97.9,48.8,109.8,115.5,2.7,0.0,0.0],[97.8,48.7,109.8,115.4,2.7,0.0,0.0],[97.8,48.6,109.8,115.3,2.7,0.0,0.0],[97.9,48.4,109.8,115.2,2.7,0.0,0.0],[97.8,48.3,109.8,115.2,2.8,0.0,0.0],[97.9,48.1,109.8,115.1,2.8,0.0,0.0],[97.8,48.0,109.8,115.0,2.7,0.0,0.0],[97.9,47.8,109.8,114.9,2.7,0.0,0.0],[97.8,47.6,109.8,114.8,2.7,0.0,0.0],[97.8,47.5,109.7,114.7,2.7,0.0,0.0],[97.9,47.3,109.7,114.6,2.7,0.0,0.0]]},"working_in":{"n":19,"loop":false,"scrub":false,"events":{},"role":"enter","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.8,96.2,120.7,-0.1,0.0,0.0],[120.4,41.5,96.7,129.0,0.0,0.0,-0.11],[121.8,46.9,97.2,137.5,0.0,0.0,-0.2],[126.8,53.8,97.7,146.1,0.1,0.0,-0.27],[128.5,60.9,98.1,153.6,0.1,0.0,-0.34],[128.9,67.2,98.5,159.3,0.0,0.0,-0.39],[128.0,71.6,98.8,163.0,0.0,0.0,-0.43],[126.2,71.3,99.1,162.7,0.0,0.0,-0.46],[125.6,69.8,99.3,162.4,-0.1,0.0,-0.48],[126.1,66.9,99.5,161.9,0.0,0.0,-0.5],[126.9,63.2,99.4,161.3,0.0,0.0,-0.5],[128.2,59.4,99.5,160.6,0.0,0.0,-0.5],[128.8,56.3,99.5,159.9,0.0,0.0,-0.5],[129.4,54.3,99.4,159.2,0.0,0.0,-0.5],[129.4,53.5,99.3,158.4,-0.1,0.0,-0.49],[129.1,53.7,99.2,157.8,0.0,0.0,-0.48],[128.6,54.5,99.2,157.2,0.0,0.0,-0.47],[128.1,55.5,99.1,156.8,0.0,0.0,-0.46],[127.6,56.4,99.0,156.4,-0.1,0.0,-0.45]]},"work_read":{"n":144,"loop":true,"scrub":false,"events":{},"role":"rest","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.6,56.0,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.2,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.8,54.8,99.0,155.7,0.0,0.0,-0.45],[125.8,53.9,97.7,155.7,0.0,0.0,-0.45],[123.3,53.1,96.1,155.6,0.1,0.0,-0.45],[123.2,53.0,95.7,155.6,0.1,0.0,-0.45],[123.8,53.3,95.7,155.6,0.1,0.0,-0.45],[124.8,53.7,95.8,155.6,0.1,0.0,-0.45],[125.6,54.1,96.1,155.5,0.0,0.0,-0.45],[126.3,54.4,96.2,155.4,0.1,0.0,-0.45],[126.8,54.6,96.4,155.4,0.1,0.0,-0.45],[127.2,54.7,96.7,155.4,0.1,0.0,-0.45],[127.3,54.7,96.9,155.4,0.1,0.0,-0.45],[127.2,54.6,97.2,155.5,0.0,0.0,-0.45],[127.3,54.6,97.4,155.5,0.0,0.0,-0.45],[127.3,54.5,97.6,155.5,0.0,0.0,-0.45],[127.3,54.5,97.8,155.6,0.1,0.0,-0.45],[127.2,54.5,98.0,155.6,0.0,0.0,-0.45],[127.3,54.5,98.3,155.6,0.0,0.0,-0.45],[127.4,54.6,98.5,155.7,0.0,0.0,-0.45],[127.5,54.7,98.8,155.7,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.9,55.0,99.2,155.8,0.0,0.0,-0.45],[128.1,55.2,99.5,155.9,0.0,0.0,-0.45],[128.3,55.4,99.7,155.9,-0.1,0.0,-0.45],[128.6,55.6,99.8,156.0,0.0,0.0,-0.45],[128.8,55.8,100.0,156.1,0.0,0.0,-0.45],[129.0,56.0,100.3,156.1,-0.1,0.0,-0.45],[129.2,56.2,100.5,156.2,-0.1,0.0,-0.45],[129.3,56.4,100.8,156.3,0.0,0.0,-0.45],[129.5,56.6,101.0,156.4,-0.1,0.0,-0.45],[129.7,56.8,101.2,156.4,-0.1,0.0,-0.45],[129.8,56.9,101.5,156.6,-0.1,0.0,-0.45],[130.0,57.1,101.7,156.6,-0.1,0.0,-0.45],[130.1,57.3,101.9,156.6,-0.1,0.0,-0.45],[130.3,57.4,102.1,156.8,-0.1,0.0,-0.45],[130.5,57.6,102.3,156.8,-0.1,0.0,-0.45],[125.8,56.0,99.5,156.9,-0.1,0.0,-0.45],[122.9,55.2,97.2,156.9,0.1,0.0,-0.45],[122.1,55.2,96.2,157.0,0.0,0.0,-0.45],[122.4,55.7,95.7,157.1,0.1,0.0,-0.45],[123.4,56.4,95.6,157.1,0.1,0.0,-0.45],[124.4,57.1,95.6,157.1,0.1,0.0,-0.45],[125.7,57.8,95.8,157.2,0.1,0.0,-0.45],[126.6,58.3,96.0,157.2,0.1,0.0,-0.45],[127.3,58.6,96.2,157.4,0.1,0.0,-0.45],[125.8,58.7,96.5,157.4,0.1,0.0,-0.45],[126.0,58.7,96.7,157.4,0.1,0.0,-0.45],[127.5,58.5,96.9,157.4,0.0,0.0,-0.45],[127.4,58.4,97.2,157.4,0.0,0.0,-0.45],[127.2,58.1,97.3,157.4,0.0,0.0,-0.45],[127.1,57.9,97.6,157.4,0.0,0.0,-0.45],[127.0,57.8,97.8,157.4,0.0,0.0,-0.45],[127.0,57.6,98.0,157.4,0.0,0.0,-0.45],[127.0,57.5,98.3,157.4,0.0,0.0,-0.45],[127.2,57.4,98.5,157.4,0.1,0.0,-0.45],[127.4,57.3,98.7,157.3,0.0,0.0,-0.45],[127.6,57.3,99.0,157.3,0.0,0.0,-0.45],[127.9,57.2,99.2,157.3,0.0,0.0,-0.45],[128.2,57.2,99.4,157.2,0.0,0.0,-0.45],[128.5,57.1,99.7,157.2,0.0,0.0,-0.45],[128.7,57.0,99.8,157.1,-0.1,0.0,-0.45],[129.0,56.9,100.1,157.1,0.0,0.0,-0.45],[129.2,56.8,100.3,157.1,-0.1,0.0,-0.45],[129.4,56.7,100.5,157.0,0.0,0.0,-0.45],[129.6,56.6,100.8,156.9,-0.1,0.0,-0.45],[129.7,56.4,101.0,156.9,0.0,0.0,-0.45],[129.9,56.3,101.2,156.9,-0.1,0.0,-0.45],[129.9,56.1,101.5,156.8,0.0,0.0,-0.45],[130.2,56.0,101.8,156.8,-0.1,0.0,-0.45],[130.4,55.9,102.0,156.8,-0.1,0.0,-0.45],[130.5,55.8,102.2,156.6,-0.1,0.0,-0.45],[130.7,55.7,102.4,156.6,-0.1,0.0,-0.45],[126.1,53.8,99.5,156.6,0.0,0.0,-0.45],[122.9,52.7,97.2,156.6,0.1,0.0,-0.45],[122.0,52.5,96.1,156.6,0.1,0.0,-0.45],[122.6,52.8,95.7,156.6,0.1,0.0,-0.45],[123.5,53.4,95.6,156.5,0.3,0.0,-0.45],[124.6,53.9,95.6,156.4,0.1,0.0,-0.45],[125.7,54.5,95.7,156.4,0.1,0.0,-0.45],[126.6,54.9,96.0,156.4,0.1,0.0,-0.45],[127.1,55.1,96.2,156.5,0.0,0.0,-0.45],[127.5,55.2,96.4,156.5,0.0,0.0,-0.45],[127.6,55.2,96.7,156.6,0.1,0.0,-0.45],[127.6,55.1,96.8,156.6,0.1,0.0,-0.45],[127.4,54.9,97.1,156.6,0.0,0.0,-0.45],[127.2,54.8,97.3,156.6,0.1,0.0,-0.45],[127.2,54.7,97.5,156.6,0.1,0.0,-0.45],[127.1,54.6,97.8,156.7,0.0,0.0,-0.45],[127.1,54.6,98.0,156.8,0.0,0.0,-0.45],[127.2,54.7,98.2,156.9,0.1,0.0,-0.45],[127.3,54.8,98.5,156.9,0.0,0.0,-0.45],[127.6,54.9,98.7,157.0,0.0,0.0,-0.45],[127.8,55.1,99.0,157.1,0.0,0.0,-0.45],[128.1,55.3,99.2,157.1,0.0,0.0,-0.45],[128.4,55.5,99.4,157.2,0.0,0.0,-0.45],[128.5,55.7,99.7,157.3,0.0,0.0,-0.45],[128.9,56.0,99.9,157.4,0.0,0.0,-0.45],[129.2,56.2,100.1,157.5,0.0,0.0,-0.45],[129.4,56.4,100.3,157.6,0.0,0.0,-0.45],[129.6,56.6,100.5,157.6,-0.1,0.0,-0.45],[129.8,56.8,100.8,157.8,-0.1,0.0,-0.45],[129.8,56.9,101.0,157.9,-0.1,0.0,-0.45],[130.0,57.1,101.2,157.9,-0.1,0.0,-0.45],[130.3,57.3,101.5,158.1,-0.1,0.0,-0.45],[130.4,57.5,101.8,158.1,-0.1,0.0,-0.45],[130.4,57.6,102.0,158.2,-0.1,0.0,-0.45],[130.6,57.8,102.2,158.4,-0.1,0.0,-0.45],[130.9,58.0,102.5,158.4,-0.3,0.0,-0.45],[130.8,58.0,102.5,158.4,-0.1,0.0,-0.45],[130.7,58.0,102.5,158.4,-0.1,0.0,-0.45],[130.3,58.0,102.3,158.4,-0.1,0.0,-0.45],[129.9,57.9,102.1,158.4,-0.1,0.0,-0.45],[129.5,57.8,101.8,158.2,-0.1,0.0,-0.45],[128.9,57.7,101.4,158.1,-0.1,0.0,-0.45],[128.4,57.6,100.9,157.9,-0.1,0.0,-0.45],[128.0,57.6,100.5,157.8,0.0,0.0,-0.45],[127.7,57.5,100.0,157.6,0.0,0.0,-0.45],[127.4,57.6,99.6,157.4,0.0,0.0,-0.45],[127.4,57.6,99.3,157.3,0.0,0.0,-0.45],[127.5,57.7,99.2,157.2,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.9,58.0,99.0,157.1,0.0,0.0,-0.45],[128.0,58.0,99.0,157.1,0.0,0.0,-0.45],[128.1,58.0,99.0,157.1,0.0,0.0,-0.45],[128.2,57.9,99.0,157.0,0.0,0.0,-0.45],[128.1,57.8,99.0,157.0,0.0,0.0,-0.45],[128.0,57.6,99.0,156.9,0.0,0.0,-0.45],[127.9,57.5,99.0,156.9,0.0,0.0,-0.45],[127.8,57.3,99.0,156.8,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.6,56.9,99.0,156.7,0.0,0.0,-0.45],[127.6,56.8,99.0,156.7,0.0,0.0,-0.45],[127.6,56.6,99.0,156.6,0.0,0.0,-0.45],[127.6,56.5,99.0,156.5,0.0,0.0,-0.45],[127.6,56.3,99.0,156.4,0.0,0.0,-0.45],[127.6,56.2,99.0,156.4,0.0,0.0,-0.45]]},"work_edit":{"n":125,"loop":true,"scrub":false,"events":{},"role":"rest","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,56.0,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.1,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.5,99.0,156.1,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,155.9,0.0,0.0,-0.45],[127.9,55.8,99.0,156.8,0.0,0.0,-0.45],[128.2,57.2,99.0,158.7,0.0,0.0,-0.45],[128.5,58.3,99.0,160.1,0.0,0.0,-0.45],[128.6,59.2,99.0,161.0,0.0,0.0,-0.45],[128.6,59.8,99.0,161.4,0.0,0.0,-0.45],[128.5,60.0,99.0,161.3,0.0,0.0,-0.45],[128.3,59.2,99.0,160.2,0.0,0.0,-0.45],[127.9,57.5,99.0,158.1,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,54.8,99.0,155.6,0.0,0.0,-0.45],[128.2,55.5,99.0,157.3,0.0,0.0,-0.45],[128.6,56.6,99.0,159.0,0.0,0.0,-0.45],[128.7,57.7,99.0,160.2,0.0,0.0,-0.45],[128.7,58.5,99.0,161.0,0.0,0.0,-0.45],[128.6,59.1,99.0,161.2,0.0,0.0,-0.45],[128.4,59.2,99.0,160.8,0.0,0.0,-0.45],[128.0,58.2,99.0,159.2,0.0,0.0,-0.45],[127.7,56.6,99.0,157.0,0.0,0.0,-0.45],[127.6,55.2,99.0,155.7,0.0,0.0,-0.45],[127.8,54.8,99.0,155.9,0.0,0.0,-0.45],[128.4,55.8,99.0,157.9,0.0,0.0,-0.45],[128.7,56.8,99.0,159.5,0.0,0.0,-0.45],[128.8,57.8,99.0,160.5,0.0,0.0,-0.45],[128.8,58.6,99.0,161.0,0.0,0.0,-0.45],[128.6,59.1,99.0,161.1,0.0,0.0,-0.45],[128.3,58.8,99.0,160.3,0.0,0.0,-0.45],[127.9,57.5,99.0,158.3,0.0,0.0,-0.45],[127.6,56.0,99.0,156.4,0.0,0.0,-0.45],[127.6,54.9,99.0,155.6,0.0,0.0,-0.45],[128.0,55.3,99.0,156.9,0.0,0.0,-0.45],[128.5,56.4,99.0,158.7,0.0,0.0,-0.45],[128.7,57.5,99.0,160.0,0.0,0.0,-0.45],[128.8,58.4,99.0,160.9,0.0,0.0,-0.45],[128.7,59.1,99.0,161.3,0.0,0.0,-0.45],[128.5,59.4,99.0,161.1,0.0,0.0,-0.45],[128.2,58.8,99.0,159.8,0.0,0.0,-0.45],[127.8,57.3,99.0,157.6,0.0,0.0,-0.45],[127.6,55.9,99.0,156.1,0.0,0.0,-0.45],[127.7,55.2,99.0,155.8,0.0,0.0,-0.45],[128.2,56.3,99.0,157.9,0.0,0.0,-0.45],[128.6,57.4,99.0,159.5,0.0,0.0,-0.45],[128.8,58.5,99.0,160.7,0.0,0.0,-0.45],[128.8,59.4,99.0,161.4,0.0,0.0,-0.45],[128.6,60.0,99.0,161.6,0.0,0.0,-0.45],[128.4,60.0,99.0,161.0,0.0,0.0,-0.45],[128.0,58.9,99.0,159.3,0.0,0.0,-0.45],[127.6,57.4,99.0,157.2,0.0,0.0,-0.45],[127.6,56.3,99.0,156.2,0.0,0.0,-0.45],[127.8,55.9,99.0,156.3,0.0,0.0,-0.45],[128.0,56.0,99.0,156.9,0.0,0.0,-0.45],[128.1,56.3,99.0,157.4,0.0,0.0,-0.45],[128.2,56.7,99.0,157.9,0.0,0.0,-0.45],[128.2,57.3,99.0,158.3,0.0,0.0,-0.45],[128.1,58.0,99.0,158.8,0.0,0.0,-0.45],[128.1,58.6,99.0,159.2,0.0,0.0,-0.45],[128.1,59.2,99.0,159.6,0.0,0.0,-0.45],[128.1,59.6,99.0,160.0,0.0,0.0,-0.45],[128.2,60.0,99.0,160.3,0.0,0.0,-0.45],[128.3,60.3,99.0,160.6,0.0,0.0,-0.45],[128.4,60.6,99.0,160.9,0.0,0.0,-0.45],[128.5,60.8,99.0,161.2,0.0,0.0,-0.45],[128.5,61.0,99.0,161.5,0.0,0.0,-0.45],[128.6,61.2,99.0,161.7,0.0,0.0,-0.45],[128.6,61.4,99.0,161.9,0.0,0.0,-0.45],[128.6,61.6,99.0,162.0,0.0,0.0,-0.45],[128.6,61.9,99.0,162.2,0.0,0.0,-0.45],[128.6,62.1,99.0,162.3,0.0,0.0,-0.45],[128.6,62.2,99.0,162.4,0.0,0.0,-0.45],[128.6,62.3,99.0,162.5,0.0,0.0,-0.45],[128.6,62.4,99.0,162.5,0.0,0.0,-0.45],[128.6,62.3,99.0,162.3,0.0,0.0,-0.45],[128.3,61.3,99.0,161.0,0.0,0.0,-0.45],[127.9,59.6,99.0,158.9,0.0,0.0,-0.45],[127.7,58.2,99.0,157.4,0.0,0.0,-0.45],[127.7,57.7,99.0,157.0,0.0,0.0,-0.45],[128.2,59.0,99.0,159.1,0.0,0.0,-0.45],[128.5,60.2,99.0,160.8,0.0,0.0,-0.45],[128.6,61.3,99.0,161.9,0.0,0.0,-0.45],[128.6,62.2,99.0,162.5,0.0,0.0,-0.45],[128.5,62.7,99.0,162.7,0.0,0.0,-0.45],[128.3,62.7,99.0,162.1,0.0,0.0,-0.45],[127.9,61.5,99.0,160.4,0.0,0.0,-0.45],[127.6,59.8,99.0,158.3,0.0,0.0,-0.45],[127.6,58.6,99.0,157.2,0.0,0.0,-0.45],[127.9,58.6,99.0,158.0,0.0,0.0,-0.45],[128.4,59.6,99.0,159.9,0.0,0.0,-0.45],[128.7,60.6,99.0,161.3,0.0,0.0,-0.45],[128.7,61.6,99.0,162.2,0.0,0.0,-0.45],[128.6,62.3,99.0,162.7,0.0,0.0,-0.45],[128.5,62.7,99.0,162.6,0.0,0.0,-0.45],[128.2,62.1,99.0,161.5,0.0,0.0,-0.45],[127.8,60.7,99.0,159.4,0.0,0.0,-0.45],[127.5,59.1,99.0,157.6,0.0,0.0,-0.45],[127.6,58.1,99.0,157.0,0.0,0.0,-0.45],[127.8,57.6,99.0,157.0,0.0,0.0,-0.45],[127.9,57.2,99.0,157.0,0.0,0.0,-0.45],[127.9,57.1,99.0,157.0,0.0,0.0,-0.45],[127.8,57.1,99.0,157.0,0.0,0.0,-0.45],[127.8,57.2,99.0,156.9,0.0,0.0,-0.45],[127.7,57.3,99.0,156.9,0.0,0.0,-0.45],[127.6,57.4,99.0,156.9,0.0,0.0,-0.45],[127.6,57.4,99.0,156.8,0.0,0.0,-0.45],[127.6,57.4,99.0,156.8,0.0,0.0,-0.45],[127.6,57.3,99.0,156.8,0.0,0.0,-0.45],[127.6,57.1,99.0,156.7,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.7,0.0,0.0,-0.45],[127.7,56.7,99.0,156.6,0.0,0.0,-0.45],[127.7,56.6,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.5,0.0,0.0,-0.45],[127.7,56.3,99.0,156.4,0.0,0.0,-0.45],[127.7,56.3,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.3,0.0,0.0,-0.45]]},"work_run":{"n":144,"loop":true,"scrub":false,"events":{},"role":"rest","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.8,99.0,155.7,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.6,99.0,155.6,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.7,54.4,99.0,155.6,0.0,0.0,-0.45],[127.7,54.3,99.0,155.5,0.0,0.0,-0.45],[127.7,54.3,99.0,155.5,0.0,0.0,-0.45],[127.7,54.2,99.0,155.5,0.0,0.0,-0.45],[127.7,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.1,99.0,155.6,0.0,0.0,-0.45],[127.8,54.1,99.0,155.6,0.0,0.01,-0.45],[127.8,54.2,99.0,155.6,0.0,0.01,-0.45],[127.8,54.2,99.0,155.7,0.0,0.01,-0.45],[127.8,54.2,99.0,155.8,0.0,0.01,-0.45],[127.9,54.2,99.0,155.8,0.0,0.01,-0.45],[127.9,54.3,99.0,155.9,0.0,0.01,-0.45],[127.9,54.3,99.0,156.0,0.0,0.02,-0.45],[127.9,54.4,99.0,156.1,0.0,0.02,-0.45],[128.0,54.4,99.0,156.2,0.0,0.02,-0.45],[128.0,54.5,99.0,156.3,0.0,0.02,-0.45],[128.1,54.6,99.0,156.4,0.0,0.03,-0.45],[128.1,54.6,99.0,156.6,0.0,0.03,-0.45],[128.1,54.7,99.0,156.7,0.0,0.03,-0.45],[128.2,54.7,99.0,156.8,0.0,0.04,-0.45],[128.2,54.8,99.0,157.0,0.0,0.04,-0.45],[128.3,54.9,99.0,157.1,0.0,0.05,-0.45],[128.3,54.9,99.0,157.3,0.0,0.05,-0.45],[128.4,55.0,99.0,157.4,0.0,0.05,-0.45],[128.4,55.0,99.0,157.6,0.0,0.06,-0.45],[128.5,55.1,99.0,157.7,0.0,0.06,-0.45],[128.5,55.1,99.0,157.9,0.0,0.07,-0.45],[128.6,55.1,99.0,158.0,0.0,0.07,-0.45],[128.7,55.1,99.0,158.2,0.0,0.08,-0.45],[128.7,55.1,99.0,158.3,0.0,0.08,-0.45],[128.8,55.1,99.0,158.5,0.0,0.09,-0.45],[128.9,55.1,99.0,158.6,0.0,0.09,-0.45],[128.9,55.1,99.0,158.8,0.0,0.1,-0.45],[129.0,55.0,99.0,158.9,0.0,0.1,-0.45],[129.0,55.0,99.0,159.0,0.0,0.1,-0.45],[129.1,54.9,99.0,159.2,0.0,0.11,-0.45],[129.1,54.8,99.0,159.3,0.0,0.11,-0.45],[129.2,54.7,99.0,159.4,0.0,0.12,-0.45],[129.3,54.6,99.0,159.5,0.0,0.12,-0.45],[129.3,54.5,99.0,159.6,0.0,0.13,-0.45],[129.4,54.4,99.0,159.7,0.0,0.13,-0.45],[129.5,54.2,99.0,159.8,0.0,0.14,-0.45],[129.5,54.1,99.0,159.8,0.0,0.14,-0.45],[129.6,53.9,99.0,159.9,0.0,0.15,-0.45],[129.7,53.7,99.0,160.0,0.0,0.15,-0.45],[129.7,53.5,99.0,160.0,0.0,0.15,-0.45],[129.8,53.3,99.0,160.1,0.0,0.16,-0.45],[129.8,53.1,99.0,160.1,0.0,0.16,-0.45],[129.9,52.9,99.0,160.1,0.0,0.17,-0.45],[129.9,52.7,99.0,160.1,0.0,0.17,-0.45],[130.0,52.5,99.0,160.1,0.0,0.17,-0.45],[130.0,52.2,99.0,160.1,0.0,0.18,-0.45],[130.1,52.0,99.0,160.1,0.0,0.18,-0.45],[130.1,51.8,99.0,160.1,0.0,0.18,-0.45],[130.1,51.5,99.0,160.1,0.0,0.18,-0.45],[130.2,51.3,99.0,160.1,0.0,0.19,-0.45],[130.2,51.1,99.0,160.0,0.0,0.19,-0.45],[130.2,50.8,99.0,160.0,0.0,0.19,-0.45],[130.3,50.6,99.0,160.0,0.0,0.19,-0.45],[130.3,50.4,99.0,159.9,0.0,0.19,-0.45],[130.3,50.2,99.0,159.9,0.0,0.19,-0.45],[130.3,50.0,99.0,159.8,0.0,0.2,-0.45],[130.3,49.8,99.0,159.8,0.0,0.2,-0.45],[130.4,49.6,99.0,159.7,0.0,0.2,-0.45],[130.4,49.5,99.0,159.7,0.0,0.2,-0.45],[130.4,49.3,99.0,159.6,0.0,0.2,-0.45],[130.4,49.2,99.0,159.6,0.0,0.2,-0.45],[130.4,49.0,99.0,159.5,0.0,0.2,-0.45],[130.4,48.9,99.0,159.5,0.0,0.2,-0.45],[130.4,48.8,99.0,159.4,0.0,0.2,-0.45],[130.4,48.8,99.0,159.4,0.0,0.2,-0.45],[130.4,48.7,99.0,159.4,0.0,0.2,-0.45],[130.4,48.6,99.0,159.4,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.6,99.0,159.3,0.0,0.2,-0.45],[130.4,48.7,99.0,159.3,0.0,0.2,-0.45],[130.4,48.7,99.0,159.3,0.0,0.2,-0.45],[130.4,48.8,99.0,159.2,0.0,0.2,-0.45],[130.4,48.8,99.0,159.2,0.0,0.2,-0.45],[130.3,48.9,99.0,159.2,0.0,0.2,-0.45],[130.3,49.0,99.0,159.2,0.0,0.2,-0.45],[130.3,49.1,99.0,159.1,0.0,0.2,-0.45],[130.3,49.2,99.0,159.1,0.0,0.2,-0.45],[130.3,49.4,99.0,159.1,0.0,0.2,-0.45],[130.3,49.5,99.0,159.1,0.0,0.2,-0.45],[130.2,49.6,99.0,159.0,0.0,0.2,-0.45],[130.2,49.8,99.0,159.0,0.0,0.2,-0.45],[130.2,49.9,99.0,158.9,0.0,0.2,-0.45],[130.2,50.1,99.0,158.9,0.0,0.2,-0.45],[130.1,50.2,99.0,158.9,0.0,0.2,-0.45],[130.1,50.4,99.0,158.8,0.0,0.2,-0.45],[130.1,50.5,99.0,158.8,0.0,0.2,-0.45],[129.2,53.0,99.0,158.2,0.0,0.13,-0.45],[128.3,55.6,99.0,157.7,0.0,0.04,-0.45],[127.8,57.1,99.0,157.3,0.0,-0.0,-0.45],[127.6,57.7,99.0,157.2,0.0,-0.02,-0.45],[127.5,57.8,99.0,157.2,0.0,-0.02,-0.45],[127.6,57.7,99.0,157.2,0.0,-0.01,-0.45],[127.7,57.5,99.0,157.2,0.0,-0.0,-0.45],[127.7,57.5,99.0,157.2,0.0,0.0,-0.45],[127.7,57.6,99.0,157.2,0.0,0.0,-0.45],[127.7,57.7,99.0,157.2,0.0,0.0,-0.45],[127.7,57.7,99.0,157.2,0.0,0.0,-0.45],[127.7,57.8,99.0,157.2,0.0,0.0,-0.45],[127.7,57.8,99.0,157.2,0.0,0.0,-0.45],[127.7,57.9,99.0,157.2,0.0,0.0,-0.45],[127.7,57.9,99.0,157.2,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.6,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.7,99.0,157.1,0.0,0.0,-0.45],[127.7,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,156.9,0.0,0.0,-0.45],[127.7,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.2,99.0,156.8,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.7,0.0,0.0,-0.45],[127.7,56.7,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.4,0.0,0.0,-0.45]]},"work_search":{"n":144,"loop":true,"scrub":false,"events":{},"role":"rest","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.8,99.0,155.7,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.4,54.4,98.8,155.6,0.0,0.0,-0.45],[126.9,54.1,98.4,155.6,0.1,0.0,-0.45],[126.2,53.9,97.9,155.5,0.0,0.0,-0.45],[125.3,53.5,97.1,155.5,0.0,0.0,-0.45],[124.1,53.2,96.1,155.4,0.1,0.0,-0.45],[122.8,52.9,94.8,155.4,0.1,0.0,-0.45],[121.3,52.6,93.5,155.4,0.1,0.0,-0.45],[119.9,52.4,92.0,155.5,0.3,0.0,-0.45],[118.7,52.2,90.3,155.4,0.4,0.0,-0.45],[117.3,52.1,88.8,155.4,0.4,0.0,-0.45],[116.1,52.2,87.3,155.5,0.6,0.0,-0.45],[115.0,52.2,85.8,155.5,0.6,0.0,-0.45],[113.9,52.4,84.6,155.5,0.6,0.0,-0.45],[113.2,52.6,83.5,155.6,0.7,0.0,-0.45],[112.6,52.9,82.5,155.6,0.7,0.0,-0.45],[112.3,53.2,81.8,155.7,0.7,0.0,-0.45],[112.2,53.5,81.4,155.7,0.7,0.0,-0.45],[112.2,53.8,81.1,155.7,0.9,0.0,-0.45],[112.4,54.0,81.0,155.8,0.7,0.0,-0.45],[112.2,54.3,80.9,155.8,0.7,0.0,-0.45],[112.3,54.4,80.9,155.9,0.9,0.0,-0.45],[112.2,54.5,80.9,155.9,0.7,0.0,-0.45],[112.2,54.5,81.0,156.1,0.7,0.0,-0.45],[111.9,54.6,81.0,156.1,0.9,0.0,-0.45],[111.7,54.6,81.0,156.2,0.9,0.0,-0.45],[111.5,54.7,81.0,156.2,0.7,0.0,-0.45],[111.4,54.8,81.0,156.3,0.9,0.0,-0.45],[111.3,54.9,80.9,156.4,0.9,0.0,-0.45],[111.2,55.0,80.9,156.5,0.9,0.0,-0.45],[111.2,55.2,80.9,156.5,0.9,0.0,-0.45],[111.3,55.3,80.9,156.6,0.9,0.0,-0.45],[111.3,55.5,80.9,156.7,0.7,0.0,-0.45],[111.4,55.7,80.9,156.7,0.9,0.0,-0.45],[111.4,55.8,80.9,156.8,0.9,0.0,-0.45],[111.5,55.9,80.9,156.8,0.9,0.0,-0.45],[111.6,56.1,80.9,156.9,0.9,0.0,-0.45],[111.5,56.1,80.9,156.9,0.9,0.0,-0.45],[111.5,56.2,80.9,156.9,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.6,56.4,80.9,157.0,0.9,0.0,-0.45],[111.5,56.4,80.9,157.0,0.9,0.0,-0.45],[111.5,56.4,80.9,157.0,0.9,0.0,-0.45],[111.5,56.4,80.9,157.0,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.5,56.3,80.9,157.0,0.9,0.0,-0.45],[111.6,56.2,81.0,156.9,0.9,0.0,-0.45],[112.1,56.3,81.3,156.9,0.9,0.0,-0.45],[113.1,56.4,82.0,156.9,0.9,0.0,-0.45],[114.7,56.7,83.0,156.8,0.7,0.0,-0.45],[116.8,57.1,84.5,156.8,0.6,0.0,-0.45],[119.4,57.5,86.4,156.8,0.6,0.0,-0.45],[122.3,57.9,88.8,156.8,0.4,0.0,-0.45],[120.5,58.4,91.5,156.7,0.3,0.0,-0.45],[118.8,58.7,94.5,156.6,0.1,0.0,-0.45],[119.5,59.0,97.7,156.6,0.0,0.0,-0.45],[121.1,59.2,100.9,156.6,-0.1,0.0,-0.45],[122.3,59.2,104.1,156.4,-0.1,0.0,-0.45],[123.9,59.1,107.0,156.3,-0.4,0.0,-0.45],[125.7,58.9,109.7,156.2,-0.4,0.0,-0.45],[127.3,58.6,112.0,156.2,-0.6,0.0,-0.45],[128.8,58.2,113.8,156.1,-0.7,0.0,-0.45],[130.1,57.8,115.2,155.9,-0.7,0.0,-0.45],[132.5,57.3,116.2,155.9,-0.9,0.0,-0.45],[135.6,56.9,116.8,155.8,-0.7,0.0,-0.45],[135.5,56.5,117.0,155.8,-0.7,0.0,-0.45],[136.7,56.2,117.1,155.7,-0.9,0.0,-0.45],[136.8,56.1,117.1,155.7,-0.7,0.0,-0.45],[135.6,56.1,117.1,155.6,-0.9,0.0,-0.45],[136.0,56.2,117.1,155.6,-0.7,0.0,-0.45],[133.7,56.4,117.1,155.5,-0.9,0.0,-0.45],[131.9,56.6,117.1,155.4,-0.7,0.0,-0.45],[130.8,56.7,117.1,155.4,-0.7,0.0,-0.45],[130.8,56.8,117.1,155.4,-0.9,0.0,-0.45],[130.6,56.9,117.1,155.4,-0.9,0.0,-0.45],[130.7,56.9,117.1,155.3,-0.7,0.0,-0.45],[130.3,56.9,117.1,155.3,-0.7,0.0,-0.45],[130.8,56.8,117.1,155.3,-0.7,0.0,-0.45],[131.0,56.8,117.1,155.3,-0.7,0.0,-0.45],[130.7,56.7,117.1,155.3,-0.7,0.0,-0.45],[130.8,56.7,117.1,155.4,-0.9,0.0,-0.45],[131.1,56.7,117.1,155.4,-0.9,0.0,-0.45],[131.1,56.7,117.1,155.4,-0.7,0.0,-0.45],[131.0,56.8,117.1,155.4,-0.7,0.0,-0.45],[131.0,56.8,117.1,155.5,-0.9,0.0,-0.45],[131.2,56.9,117.1,155.6,-0.7,0.0,-0.45],[131.0,57.0,117.1,155.6,-0.9,0.0,-0.45],[131.1,57.2,117.1,155.7,-0.7,0.0,-0.45],[131.1,57.3,117.1,155.7,-0.9,0.0,-0.45],[130.9,57.5,117.1,155.8,-0.7,0.0,-0.45],[131.0,57.7,117.1,155.8,-0.7,0.0,-0.45],[128.0,53.1,107.9,156.0,-0.3,0.0,-0.45],[121.3,51.5,101.8,156.1,-0.1,0.0,-0.45],[120.7,52.0,99.5,156.2,0.0,0.0,-0.45],[123.1,53.3,99.0,156.2,0.0,0.0,-0.45],[125.8,54.9,99.0,156.3,0.0,0.0,-0.45],[128.3,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,57.5,99.0,156.4,0.0,0.0,-0.45],[122.6,58.3,99.0,156.5,0.0,0.0,-0.45],[121.9,58.6,99.0,156.6,0.0,0.0,-0.45],[122.2,58.6,99.0,156.7,0.0,0.0,-0.45],[124.2,58.4,99.0,156.7,0.0,0.0,-0.45],[127.2,58.1,99.0,156.8,0.0,0.0,-0.45],[128.8,57.8,99.0,156.8,0.0,0.0,-0.45],[128.0,57.6,99.0,156.9,0.0,0.0,-0.45],[127.5,57.4,99.0,156.9,0.0,0.0,-0.45],[127.1,57.3,99.0,157.0,0.0,0.0,-0.45],[126.9,57.2,99.0,157.0,0.0,0.0,-0.45],[126.9,57.3,99.0,157.1,0.0,0.0,-0.45],[126.9,57.4,99.0,157.1,0.0,0.0,-0.45],[127.1,57.5,99.0,157.1,0.0,0.0,-0.45],[127.3,57.6,99.0,157.1,0.0,0.0,-0.45],[127.4,57.7,99.0,157.1,0.0,0.0,-0.45],[127.6,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.8,57.9,99.0,157.1,0.0,0.0,-0.45],[127.8,57.9,99.0,157.1,0.0,0.0,-0.45],[127.8,57.9,99.0,157.1,0.0,0.0,-0.45],[127.8,57.8,99.0,157.1,0.0,0.0,-0.45],[127.8,57.7,99.0,157.0,0.0,0.0,-0.45],[127.8,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,156.9,0.0,0.0,-0.45],[127.7,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.2,99.0,156.8,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.7,0.0,0.0,-0.45],[127.7,56.7,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.4,0.0,0.0,-0.45]]},"work_nod":{"n":58,"loop":false,"scrub":false,"events":{},"role":"beat","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.1,0.0,0.0,-0.45],[127.7,55.5,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.8,99.0,155.7,0.0,0.0,-0.45],[127.7,54.6,99.0,155.7,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.7,54.4,99.0,155.6,0.0,0.0,-0.45],[127.8,54.4,99.0,155.8,0.0,0.0,-0.45],[127.9,54.6,99.0,156.5,0.0,0.0,-0.45],[128.0,54.9,99.0,157.8,0.0,0.0,-0.45],[128.2,55.4,99.0,159.4,0.0,0.0,-0.45],[128.5,56.0,99.0,161.0,0.0,0.0,-0.45],[128.7,56.6,99.0,162.2,0.0,0.0,-0.45],[128.9,57.1,99.0,162.8,0.0,0.0,-0.45],[129.1,57.4,99.0,162.9,0.0,0.0,-0.45],[129.1,57.6,99.0,162.7,0.0,0.0,-0.45],[129.1,57.2,99.0,161.6,0.0,0.0,-0.45],[128.8,56.3,99.0,159.4,0.0,0.0,-0.45],[128.4,55.3,99.0,156.9,0.0,0.0,-0.45],[127.9,54.6,99.0,154.8,0.0,0.0,-0.45],[127.6,54.5,99.0,153.5,0.0,0.0,-0.45],[127.2,55.1,99.0,153.3,0.0,0.0,-0.45],[127.0,55.7,99.0,153.4,0.0,0.0,-0.45],[127.0,56.4,99.0,153.9,0.0,0.0,-0.45],[127.0,56.8,99.0,155.0,0.0,0.0,-0.45],[127.2,57.1,99.0,156.3,0.0,0.0,-0.45],[127.5,57.3,99.0,157.7,0.0,0.0,-0.45],[127.8,57.4,99.0,158.6,0.0,0.0,-0.45],[128.1,57.4,99.0,159.1,0.0,0.0,-0.45],[128.2,57.6,99.0,159.3,0.0,0.0,-0.45],[128.3,57.8,99.0,159.3,0.0,0.0,-0.45],[128.3,57.9,99.0,159.1,0.0,0.0,-0.45],[128.2,57.9,99.0,158.6,0.0,0.0,-0.45],[128.1,57.7,99.0,158.0,0.0,0.0,-0.45],[127.9,57.6,99.0,157.5,0.0,0.0,-0.45],[127.8,57.7,99.0,157.2,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.6,57.9,99.0,157.1,0.0,0.0,-0.45],[127.5,58.1,99.0,157.1,0.0,0.0,-0.45],[127.5,58.1,99.0,157.1,0.0,0.0,-0.45],[127.5,58.1,99.0,157.1,0.0,0.0,-0.45],[127.6,58.0,99.0,157.1,0.0,0.0,-0.45],[127.6,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.7,99.0,157.1,0.0,0.0,-0.45],[127.7,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,157.0,0.0,0.0,-0.45],[127.7,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.2,99.0,156.9,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,56.9,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.6,0.0,0.0,-0.45],[127.7,56.6,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.4,0.0,0.0,-0.45]]},"work_squint":{"n":72,"loop":false,"scrub":false,"events":{},"role":"beat","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.1,0.0,0.0,-0.45],[127.7,55.5,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.6,99.0,155.7,0.0,0.0,-0.45],[127.7,54.5,99.0,155.7,0.0,0.0,-0.45],[127.8,54.2,99.0,155.8,0.0,0.01,-0.45],[128.0,53.8,99.0,156.0,0.0,0.02,-0.45],[128.3,53.1,99.0,156.3,0.0,0.05,-0.45],[128.6,52.3,99.0,156.8,0.0,0.07,-0.45],[129.1,51.4,99.0,157.4,0.0,0.11,-0.45],[129.5,50.4,99.0,158.1,0.0,0.14,-0.45],[130.0,49.4,99.0,158.8,0.0,0.17,-0.45],[130.5,48.4,99.0,159.4,0.0,0.21,-0.45],[130.9,47.7,99.0,160.0,0.0,0.23,-0.45],[131.2,47.1,99.0,160.4,0.0,0.25,-0.45],[131.4,46.8,99.0,160.7,0.0,0.26,-0.45],[131.5,46.7,99.0,160.9,0.0,0.27,-0.45],[131.5,46.8,99.0,160.9,0.0,0.27,-0.45],[131.5,46.9,99.0,161.0,0.0,0.27,-0.45],[131.5,47.0,99.0,161.0,0.0,0.27,-0.45],[131.5,47.1,99.0,161.1,0.0,0.27,-0.45],[131.5,47.3,99.0,161.1,0.0,0.27,-0.45],[131.4,47.4,99.0,161.2,0.0,0.27,-0.45],[131.4,47.6,99.0,161.2,0.0,0.27,-0.45],[131.4,47.7,99.0,161.3,0.0,0.27,-0.45],[131.4,47.9,99.0,161.4,0.0,0.27,-0.45],[131.4,48.1,99.0,161.5,0.0,0.27,-0.45],[131.4,48.2,99.0,161.5,0.0,0.27,-0.45],[131.4,48.4,99.0,161.6,0.0,0.27,-0.45],[131.4,48.6,99.0,161.7,0.0,0.27,-0.45],[131.4,48.8,99.0,161.8,0.0,0.27,-0.45],[131.4,48.9,99.0,161.9,0.0,0.27,-0.45],[131.4,49.1,99.0,161.9,0.0,0.27,-0.45],[131.4,49.3,99.0,162.0,0.0,0.27,-0.45],[131.4,49.5,99.0,162.1,0.0,0.27,-0.45],[131.4,49.6,99.0,162.1,0.0,0.27,-0.45],[131.4,49.8,99.0,162.2,0.0,0.27,-0.45],[131.4,49.9,99.0,162.3,0.0,0.27,-0.45],[131.4,50.0,99.0,162.3,0.0,0.27,-0.45],[131.4,50.2,99.0,162.4,0.0,0.27,-0.45],[131.4,50.3,99.0,162.4,0.0,0.27,-0.45],[131.4,50.4,99.0,162.5,0.0,0.27,-0.45],[131.4,50.4,99.0,162.5,0.0,0.27,-0.45],[131.4,50.5,99.0,162.5,0.0,0.27,-0.45],[131.4,50.6,99.0,162.5,0.0,0.27,-0.45],[131.1,51.2,99.0,162.1,0.0,0.25,-0.45],[130.4,52.6,99.0,161.1,0.0,0.2,-0.45],[129.5,54.4,99.0,159.7,0.0,0.13,-0.45],[128.6,56.1,99.0,158.4,0.0,0.07,-0.45],[128.0,57.3,99.0,157.5,0.0,0.02,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.6,57.8,99.0,157.1,0.0,0.0,-0.45],[127.6,57.8,99.0,157.1,0.0,0.0,-0.45],[127.6,57.7,99.0,157.0,0.0,0.0,-0.45],[127.6,57.7,99.0,157.0,0.0,0.0,-0.45],[127.6,57.5,99.0,156.9,0.0,0.0,-0.45],[127.6,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.3,99.0,156.8,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.7,0.0,0.0,-0.45],[127.7,56.7,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.7,56.4,99.0,156.4,0.0,0.0,-0.45],[127.7,56.2,99.0,156.4,0.0,0.0,-0.45]]},"work_ponder":{"n":77,"loop":false,"scrub":false,"events":{},"role":"beat","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.9,99.0,156.2,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,55.7,99.0,156.1,0.0,0.0,-0.45],[127.7,55.5,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,156.0,0.0,0.0,-0.45],[127.7,55.2,99.0,155.9,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,54.8,99.0,155.7,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.8,54.6,99.1,155.5,0.0,0.0,-0.45],[127.9,54.4,99.5,154.9,-0.3,0.0,-0.45],[128.0,54.2,100.2,153.8,-0.4,0.0,-0.45],[127.9,54.1,101.0,152.2,-0.7,0.0,-0.45],[127.4,54.0,102.1,150.4,-1.1,0.0,-0.45],[126.4,54.2,103.1,148.4,-1.5,0.0,-0.45],[124.8,54.7,104.0,146.7,-1.7,0.0,-0.45],[121.5,55.7,104.7,145.2,-1.9,0.0,-0.45],[119.0,56.9,105.2,144.2,-2.1,0.0,-0.45],[113.6,58.2,105.4,143.6,-2.1,0.0,-0.45],[111.0,59.1,105.5,143.4,-2.3,0.0,-0.45],[109.3,59.6,105.5,143.4,-2.3,0.0,-0.45],[109.3,59.7,105.5,143.4,-2.3,0.0,-0.45],[109.8,59.5,105.5,143.4,-2.1,0.0,-0.45],[111.3,59.1,105.5,143.4,-2.1,0.0,-0.45],[112.5,58.7,105.6,143.5,-2.3,0.0,-0.45],[114.4,58.3,105.6,143.6,-2.1,0.0,-0.45],[116.0,58.0,105.6,143.6,-2.3,0.0,-0.45],[117.1,57.9,105.6,143.7,-2.1,0.0,-0.45],[116.7,58.0,105.6,143.7,-2.3,0.0,-0.45],[116.4,58.2,105.6,143.8,-2.1,0.0,-0.45],[116.0,58.4,105.6,143.8,-2.3,0.0,-0.45],[115.3,58.7,105.6,143.8,-2.1,0.0,-0.45],[114.7,59.0,105.6,143.9,-2.1,0.0,-0.45],[113.8,59.3,105.6,144.0,-2.3,0.0,-0.45],[113.6,59.5,105.6,144.1,-2.3,0.0,-0.45],[113.7,59.6,105.6,144.2,-2.1,0.0,-0.45],[113.8,59.7,105.6,144.2,-2.3,0.0,-0.45],[114.0,59.8,105.5,144.3,-2.2,0.0,-0.45],[114.1,59.9,105.5,144.4,-2.2,0.0,-0.45],[114.0,60.0,105.5,144.4,-2.1,0.0,-0.45],[114.0,60.1,105.5,144.5,-2.2,0.0,-0.45],[114.3,60.2,105.5,144.6,-2.2,0.0,-0.45],[114.6,60.3,105.5,144.7,-2.1,0.0,-0.45],[114.6,60.4,105.5,144.8,-2.2,0.0,-0.45],[114.4,60.5,105.5,145.1,-2.1,0.0,-0.45],[114.9,60.5,105.2,145.4,-2.1,0.0,-0.45],[115.8,60.4,105.1,146.1,-2.1,0.0,-0.45],[117.1,60.2,104.8,146.8,-1.9,0.0,-0.45],[118.8,59.8,104.3,147.7,-1.9,0.0,-0.45],[120.9,59.4,103.8,148.8,-1.8,0.0,-0.45],[121.8,58.9,103.2,149.9,-1.5,0.0,-0.45],[124.4,58.4,102.5,151.1,-1.3,0.0,-0.45],[125.4,58.0,101.9,152.3,-1.1,0.0,-0.45],[126.1,57.8,101.2,153.4,-0.9,0.0,-0.45],[126.9,57.7,100.7,154.5,-0.5,0.0,-0.45],[127.3,57.7,100.1,155.4,-0.5,0.0,-0.45],[127.7,57.7,99.7,156.1,-0.3,0.0,-0.45],[128.0,57.8,99.3,156.6,-0.1,0.0,-0.45],[128.1,57.9,99.1,156.9,0.0,0.0,-0.45],[128.1,57.9,99.0,157.1,0.0,0.0,-0.45],[128.2,57.8,99.0,157.1,0.0,0.0,-0.45],[128.0,57.8,99.0,157.1,0.0,0.0,-0.45],[127.9,57.7,99.0,157.0,0.0,0.0,-0.45],[127.8,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,156.9,0.0,0.0,-0.45],[127.6,57.4,99.0,156.9,0.0,0.0,-0.45],[127.5,57.3,99.0,156.9,0.0,0.0,-0.45],[127.5,57.1,99.0,156.8,0.0,0.0,-0.45],[127.5,57.0,99.0,156.7,0.0,0.0,-0.45],[127.6,56.9,99.0,156.7,0.0,0.0,-0.45],[127.6,56.8,99.0,156.6,0.0,0.0,-0.45],[127.7,56.6,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45],[127.8,56.3,99.0,156.4,0.0,0.0,-0.45],[127.8,56.2,99.0,156.4,0.0,0.0,-0.45]]},"work_blink":{"n":38,"loop":false,"scrub":false,"events":{},"role":"beat","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.7,55.8,99.0,156.2,0.0,0.0,-0.45],[127.7,55.6,99.0,156.0,0.0,0.0,-0.45],[127.7,55.3,99.0,155.9,0.0,0.0,-0.45],[127.7,55.0,99.0,155.8,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.7,54.3,99.0,155.6,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.8,54.2,99.0,155.5,0.0,0.0,-0.45],[127.7,54.2,99.0,155.5,0.0,0.0,-0.45],[127.7,54.3,99.0,155.5,0.0,0.0,-0.45],[127.7,54.5,99.0,155.6,0.0,0.0,-0.45],[127.7,54.7,99.0,155.7,0.0,0.0,-0.45],[127.7,54.9,99.0,155.8,0.0,0.0,-0.45],[127.7,55.1,99.0,155.9,0.0,0.0,-0.45],[127.7,55.4,99.0,156.0,0.0,0.0,-0.45],[127.7,55.7,99.0,156.1,0.0,0.0,-0.45],[127.7,56.0,99.0,156.3,0.0,0.0,-0.45],[127.7,56.3,99.0,156.4,0.0,0.0,-0.45],[127.7,56.6,99.0,156.5,0.0,0.0,-0.45],[127.7,56.9,99.0,156.7,0.0,0.0,-0.45],[127.7,57.1,99.0,156.8,0.0,0.0,-0.45],[127.7,57.4,99.0,156.9,0.0,0.0,-0.45],[127.7,57.6,99.0,157.0,0.0,0.0,-0.45],[127.7,57.7,99.0,157.0,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.9,99.0,157.1,0.0,0.0,-0.45],[127.7,57.8,99.0,157.1,0.0,0.0,-0.45],[127.7,57.7,99.0,157.0,0.0,0.0,-0.45],[127.7,57.5,99.0,156.9,0.0,0.0,-0.45],[127.7,57.3,99.0,156.9,0.0,0.0,-0.45],[127.7,57.0,99.0,156.7,0.0,0.0,-0.45],[127.7,56.8,99.0,156.6,0.0,0.0,-0.45],[127.7,56.5,99.0,156.5,0.0,0.0,-0.45]]},"bump":{"n":24,"loop":false,"scrub":false,"events":{"land":6,"launch":10},"role":"react","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.7,56.1,99.0,156.3,0.0,0.0,-0.45],[127.6,55.8,99.0,155.5,0.0,0.0,-0.45],[127.4,55.2,99.0,152.4,0.0,0.0,-0.45],[127.0,55.1,99.0,148.9,0.0,0.0,-0.45],[126.5,55.7,99.0,147.5,0.0,0.0,-0.45],[126.3,68.7,99.0,160.7,0.0,0.0,-0.48],[124.2,84.3,99.0,173.9,0.0,0.0,-0.51],[124.4,91.8,99.0,179.3,0.0,0.0,-0.52],[122.8,70.1,99.0,156.4,0.0,0.0,-0.44],[123.9,46.2,99.0,135.9,0.0,0.0,-0.37],[123.7,33.5,99.0,124.4,0.0,0.0,-0.33],[123.9,29.8,99.0,121.7,0.0,0.0,-0.32],[127.3,26.7,99.0,124.1,0.0,0.0,-0.33],[117.5,38.2,99.0,131.6,0.0,0.0,-0.37],[111.7,51.4,99.0,140.7,0.0,0.0,-0.42],[110.8,58.2,99.0,146.2,0.0,0.0,-0.45],[113.5,59.7,99.0,148.2,0.0,0.0,-0.45],[113.0,65.2,99.0,150.0,0.0,0.0,-0.45],[115.6,67.2,99.0,151.8,0.0,0.0,-0.45],[122.4,65.1,99.0,153.4,0.0,0.0,-0.45],[123.3,63.8,99.0,154.6,0.0,0.0,-0.45],[125.0,61.8,99.0,155.5,0.0,0.0,-0.45],[126.9,58.3,99.0,156.1,0.0,0.0,-0.45],[128.6,55.3,99.0,156.3,0.0,0.0,-0.45]]},"oops":{"n":26,"loop":false,"scrub":false,"events":{},"role":"react","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.8,56.6,99.0,156.3,0.0,0.0,-0.45],[113.7,68.6,83.2,173.6,1.3,0.02,-0.45],[105.6,75.2,79.5,177.4,1.8,0.04,-0.45],[105.1,80.2,79.2,177.8,1.8,0.06,-0.45],[106.4,84.3,79.8,177.4,1.7,0.07,-0.45],[111.2,85.1,82.7,175.1,1.3,0.08,-0.45],[104.9,81.2,87.7,171.0,0.8,0.09,-0.45],[106.7,73.6,93.2,166.4,0.4,0.09,-0.45],[110.1,64.8,97.2,162.9,0.1,0.1,-0.45],[115.5,57.4,98.8,161.2,0.0,0.1,-0.45],[125.3,50.6,99.0,160.7,0.0,0.1,-0.45],[133.9,45.7,99.0,160.2,0.0,0.1,-0.45],[130.6,43.7,99.0,159.8,0.0,0.1,-0.45],[128.2,44.1,99.0,159.3,0.0,0.1,-0.45],[126.5,45.9,99.0,158.8,0.0,0.1,-0.45],[125.5,48.3,99.0,158.4,0.0,0.1,-0.45],[125.3,50.5,99.0,158.1,0.0,0.1,-0.45],[125.7,52.2,99.0,157.7,0.0,0.1,-0.45],[126.5,53.2,99.0,157.4,0.0,0.09,-0.45],[127.3,53.8,99.0,157.1,0.0,0.08,-0.45],[128.0,54.2,99.0,156.9,0.0,0.06,-0.45],[128.5,54.4,99.0,156.7,0.0,0.04,-0.45],[128.9,54.7,99.0,156.5,0.0,0.03,-0.45],[129.1,55.1,99.0,156.4,0.0,0.02,-0.45],[128.9,55.5,99.0,156.4,0.0,0.01,-0.45],[128.5,55.8,99.0,156.3,0.0,0.0,-0.45]]},"interrupted":{"n":29,"loop":false,"scrub":false,"events":{},"role":"react","state":"working","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[127.8,55.8,99.0,156.3,0.0,0.0,-0.45],[121.3,45.8,99.0,129.1,0.0,-0.09,-0.45],[122.0,42.2,99.0,127.8,0.0,-0.1,-0.45],[122.2,41.2,99.0,127.8,0.0,-0.1,-0.45],[112.3,43.3,99.0,127.8,0.0,-0.1,-0.45],[109.5,43.2,99.0,127.8,0.0,-0.1,-0.45],[108.4,44.0,99.0,127.8,0.0,-0.1,-0.45],[108.3,44.9,99.0,127.8,0.0,-0.1,-0.45],[108.1,45.5,99.0,127.8,0.0,-0.1,-0.45],[111.0,46.0,99.0,127.8,0.0,-0.1,-0.45],[112.4,46.4,99.0,127.8,0.0,-0.1,-0.45],[112.8,45.8,99.0,127.8,0.0,-0.1,-0.45],[114.5,44.7,99.0,127.8,0.0,-0.1,-0.45],[116.3,43.8,99.0,127.8,0.0,-0.1,-0.45],[116.7,43.2,99.0,127.8,0.0,-0.1,-0.45],[116.5,42.9,99.0,127.7,0.0,-0.1,-0.44],[115.6,42.9,98.9,127.5,0.0,-0.1,-0.43],[114.4,43.1,98.8,127.1,0.0,-0.09,-0.41],[113.7,43.3,98.5,126.6,0.0,-0.08,-0.37],[112.8,43.4,98.3,126.0,0.0,-0.07,-0.33],[112.8,43.1,98.0,125.2,0.0,-0.06,-0.28],[113.1,42.5,97.7,124.4,0.0,-0.05,-0.23],[114.4,41.6,97.4,123.5,0.0,-0.04,-0.17],[115.4,40.5,97.1,122.7,0.0,-0.03,-0.12],[116.8,39.5,96.8,122.0,0.0,-0.02,-0.08],[119.1,38.5,96.5,121.5,-0.1,-0.01,-0.04],[120.7,37.7,96.4,121.0,-0.1,-0.0,-0.02],[122.1,37.2,96.2,120.8,-0.1,-0.0,-0.01],[124.2,36.9,96.2,120.7,-0.3,-0.0,-0.0]]},"subagents_in":{"n":58,"loop":false,"scrub":false,"events":{},"role":"enter","state":"subagents","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.8,96.3,120.7,-0.1,-0.0,0.0],[120.8,37.9,97.1,120.3,-0.1,-0.02,0.01],[121.9,38.2,98.6,119.7,-0.1,-0.05,0.03],[122.3,38.6,100.7,118.7,-0.3,-0.09,0.05],[124.3,38.8,103.0,117.7,-0.1,-0.14,0.08],[125.9,39.0,105.2,116.7,-0.1,-0.19,0.11],[127.2,39.0,106.9,115.9,-0.3,-0.23,0.13],[127.8,38.9,108.0,115.5,-0.2,-0.26,0.14],[128.0,38.7,108.3,115.2,-0.2,-0.27,0.15],[128.2,37.8,108.3,114.8,-0.2,-0.27,0.15],[128.1,36.1,108.3,113.5,-0.2,-0.27,0.15],[128.1,34.5,108.3,112.5,-0.3,-0.27,0.15],[127.9,33.1,108.3,111.6,-0.3,-0.27,0.15],[127.9,31.7,108.3,110.8,-0.3,-0.27,0.15],[128.7,30.4,108.3,110.2,-0.2,-0.27,0.15],[127.9,29.4,108.3,109.6,-0.3,-0.27,0.15],[128.4,28.5,108.3,109.1,-0.3,-0.27,0.15],[128.4,27.8,108.3,108.8,-0.3,-0.27,0.15],[128.9,27.2,108.3,108.5,-0.2,-0.27,0.15],[128.4,26.9,108.3,108.2,-0.3,-0.27,0.15],[128.8,26.6,108.4,108.0,-0.3,-0.27,0.15],[128.8,26.4,108.4,107.9,-0.3,-0.27,0.15],[128.7,26.3,108.4,107.8,-0.2,-0.27,0.15],[128.7,26.2,108.3,107.7,-0.3,-0.27,0.15],[128.7,26.1,108.3,107.6,-0.3,-0.27,0.15],[128.5,26.1,108.3,107.6,-0.3,-0.27,0.15],[128.7,26.0,108.3,107.6,-0.3,-0.27,0.15],[128.4,26.0,108.3,107.5,-0.3,-0.27,0.15],[128.7,25.9,108.3,107.5,-0.3,-0.27,0.15],[128.7,25.9,108.3,107.5,-0.3,-0.27,0.15],[128.7,25.9,108.3,107.5,-0.3,-0.27,0.15],[128.7,25.9,108.3,107.5,-0.3,-0.27,0.15],[128.7,26.0,108.3,107.6,-0.3,-0.27,0.15],[128.8,26.5,108.4,107.9,-0.3,-0.27,0.15],[128.4,27.9,108.4,108.9,-0.3,-0.27,0.15],[128.7,30.1,108.3,110.4,-0.3,-0.27,0.15],[128.2,32.9,108.3,112.1,-0.3,-0.27,0.15],[128.3,35.6,108.3,113.7,-0.2,-0.27,0.15],[128.2,37.9,108.3,114.8,-0.2,-0.27,0.15],[128.4,39.2,108.3,115.2,-0.3,-0.27,0.15],[127.9,39.8,108.3,115.2,-0.2,-0.27,0.15],[127.6,40.0,108.3,115.2,-0.2,-0.27,0.15],[127.7,39.9,108.3,115.2,-0.2,-0.27,0.15],[127.8,39.6,108.3,115.2,-0.2,-0.27,0.15],[128.0,39.2,108.3,115.2,-0.2,-0.27,0.15],[128.3,38.9,108.3,115.2,-0.2,-0.27,0.15],[128.3,38.7,108.3,115.2,-0.2,-0.27,0.15],[128.4,38.6,108.3,115.2,-0.2,-0.27,0.15],[128.3,38.7,108.3,115.2,-0.2,-0.27,0.15],[128.3,38.8,108.3,115.2,-0.2,-0.27,0.15],[127.9,39.0,108.3,115.2,-0.2,-0.27,0.15],[128.1,39.1,108.3,115.2,-0.2,-0.27,0.15],[128.4,39.1,108.3,115.2,-0.2,-0.27,0.15],[128.0,39.2,108.3,115.2,-0.2,-0.27,0.15],[128.0,39.2,108.3,115.2,-0.2,-0.27,0.15],[128.0,39.1,108.3,115.2,-0.2,-0.27,0.15],[127.9,39.1,108.3,115.2,-0.2,-0.27,0.15]]},"subagents_rest":{"n":115,"loop":true,"scrub":false,"events":{},"role":"rest","state":"subagents","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[128.4,38.9,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.9,108.3,115.2,-0.3,-0.27,0.15],[128.2,38.8,108.3,115.2,-0.2,-0.27,0.15],[128.2,38.7,108.3,115.1,-0.3,-0.27,0.15],[128.3,38.6,108.3,115.0,-0.2,-0.27,0.15],[128.4,38.5,108.3,115.0,-0.3,-0.27,0.15],[128.4,38.4,108.3,115.0,-0.2,-0.27,0.15],[128.4,38.3,108.3,114.9,-0.3,-0.27,0.15],[128.4,38.2,108.3,114.8,-0.2,-0.27,0.15],[128.4,38.1,108.3,114.8,-0.3,-0.27,0.15],[128.0,38.1,108.3,114.8,-0.2,-0.27,0.15],[128.4,37.9,108.3,114.7,-0.3,-0.27,0.15],[129.1,37.7,108.2,114.7,-0.3,-0.27,0.15],[129.2,37.5,107.9,114.7,-0.2,-0.27,0.15],[129.8,37.2,107.6,114.6,-0.3,-0.27,0.15],[129.9,36.9,107.2,114.6,-0.3,-0.27,0.15],[130.3,36.6,106.7,114.6,-0.5,-0.27,0.15],[130.9,36.3,106.1,114.6,-0.5,-0.27,0.15],[131.2,36.1,105.6,114.5,-0.6,-0.27,0.15],[131.2,36.0,105.2,114.4,-0.5,-0.27,0.15],[131.4,36.0,104.7,114.4,-0.6,-0.27,0.15],[131.2,36.1,104.5,114.4,-0.6,-0.27,0.15],[131.1,36.3,104.2,114.4,-0.6,-0.27,0.15],[130.5,36.5,104.2,114.4,-0.6,-0.27,0.15],[130.6,36.6,104.2,114.3,-0.8,-0.27,0.15],[130.1,36.8,104.2,114.3,-0.8,-0.27,0.15],[129.9,36.8,104.2,114.3,-0.8,-0.27,0.15],[130.4,36.7,104.2,114.3,-0.8,-0.27,0.15],[130.2,36.7,104.2,114.3,-0.8,-0.27,0.15],[130.5,36.6,104.2,114.3,-0.8,-0.27,0.15],[130.5,36.5,104.2,114.3,-0.8,-0.27,0.15],[130.7,36.4,104.2,114.3,-0.8,-0.27,0.15],[131.1,36.3,104.2,114.3,-0.8,-0.27,0.15],[131.0,36.3,104.2,114.3,-0.8,-0.27,0.15],[131.2,36.3,104.2,114.3,-0.8,-0.27,0.15],[131.1,36.3,104.2,114.4,-0.6,-0.27,0.15],[131.0,36.4,104.2,114.4,-0.6,-0.27,0.15],[131.2,36.4,104.2,114.5,-0.8,-0.27,0.15],[131.1,36.5,104.2,114.5,-0.8,-0.27,0.15],[130.5,36.6,104.2,114.5,-0.6,-0.27,0.15],[131.3,36.6,104.2,114.5,-0.6,-0.27,0.15],[130.9,36.7,104.2,114.5,-0.8,-0.27,0.15],[130.5,36.9,104.2,114.6,-0.6,-0.27,0.15],[129.9,37.4,104.8,114.6,-0.6,-0.27,0.15],[127.3,38.2,105.8,114.7,-0.5,-0.27,0.15],[125.2,38.9,106.8,114.7,-0.5,-0.27,0.15],[124.5,39.3,107.8,114.7,-0.3,-0.27,0.15],[124.8,39.2,108.2,114.8,-0.2,-0.27,0.15],[126.2,38.8,108.3,114.8,-0.3,-0.27,0.15],[127.6,38.4,108.3,114.8,-0.2,-0.27,0.15],[129.2,38.0,108.3,114.8,-0.2,-0.27,0.15],[129.4,37.9,108.3,115.0,-0.2,-0.27,0.15],[129.6,37.8,108.3,115.0,-0.2,-0.27,0.15],[129.4,37.9,108.3,115.0,-0.2,-0.27,0.15],[129.7,38.0,108.3,115.0,-0.2,-0.27,0.15],[129.4,38.3,108.3,115.2,-0.2,-0.27,0.15],[129.3,38.5,108.3,115.2,-0.3,-0.27,0.15],[128.7,38.8,108.3,115.2,-0.2,-0.27,0.15],[128.3,39.0,108.3,115.3,-0.3,-0.27,0.15],[128.2,39.2,108.3,115.3,-0.2,-0.27,0.15],[127.4,39.4,108.3,115.4,-0.3,-0.27,0.15],[127.5,39.5,108.3,115.5,-0.2,-0.27,0.15],[127.5,39.6,108.3,115.5,-0.3,-0.27,0.15],[127.5,39.7,108.3,115.5,-0.2,-0.27,0.15],[127.4,39.8,108.3,115.6,-0.3,-0.27,0.15],[127.3,39.9,108.3,115.7,-0.2,-0.27,0.15],[128.0,39.9,108.3,115.7,-0.3,-0.27,0.15],[127.9,40.0,108.3,115.8,-0.2,-0.27,0.15],[127.9,40.1,108.4,115.8,-0.3,-0.27,0.15],[127.0,40.4,108.8,115.8,-0.2,-0.27,0.15],[125.5,41.1,109.6,115.8,-0.2,-0.27,0.15],[123.5,41.9,110.6,115.9,0.0,-0.27,0.15],[122.8,42.4,111.7,116.0,0.2,-0.27,0.15],[122.8,42.5,112.3,116.0,0.3,-0.27,0.15],[123.0,42.2,112.5,116.0,0.3,-0.27,0.15],[123.8,41.7,112.6,116.0,0.2,-0.27,0.15],[125.2,41.3,112.6,116.1,0.3,-0.27,0.15],[126.0,41.0,112.6,116.1,0.3,-0.27,0.15],[126.5,40.9,112.6,116.2,0.2,-0.27,0.15],[126.4,40.9,112.6,116.2,0.2,-0.27,0.15],[126.5,40.9,112.6,116.2,0.3,-0.27,0.15],[126.2,41.1,112.6,116.2,0.3,-0.27,0.15],[126.0,41.2,112.6,116.2,0.3,-0.27,0.15],[125.8,41.4,112.6,116.2,0.3,-0.27,0.15],[125.6,41.5,112.6,116.2,0.3,-0.27,0.15],[125.1,41.7,112.6,116.2,0.2,-0.27,0.15],[124.7,41.8,112.6,116.2,0.2,-0.27,0.15],[124.8,41.8,112.6,116.2,0.2,-0.27,0.15],[124.7,41.8,112.6,116.2,0.2,-0.27,0.15],[124.7,41.8,112.6,116.2,0.3,-0.27,0.15],[125.1,41.7,112.5,116.2,0.3,-0.27,0.15],[125.0,41.6,112.4,116.2,0.3,-0.27,0.15],[125.8,41.3,112.0,116.2,0.2,-0.27,0.15],[126.7,40.9,111.5,116.2,0.2,-0.27,0.15],[128.5,40.5,111.0,116.2,0.2,-0.27,0.15],[128.8,40.2,110.3,116.1,0.0,-0.27,0.15],[129.0,39.9,109.6,116.1,0.0,-0.27,0.15],[129.2,39.8,109.1,116.0,-0.2,-0.27,0.15],[129.2,39.9,108.7,116.0,-0.2,-0.27,0.15],[129.4,40.0,108.4,116.0,-0.2,-0.27,0.15],[128.2,40.3,108.3,116.0,-0.2,-0.27,0.15],[127.5,40.5,108.3,116.0,-0.2,-0.27,0.15],[126.8,40.7,108.3,115.9,-0.3,-0.27,0.15],[126.6,40.7,108.3,115.8,-0.2,-0.27,0.15],[126.7,40.6,108.3,115.8,-0.2,-0.27,0.15],[126.6,40.5,108.3,115.8,-0.2,-0.27,0.15],[126.9,40.3,108.3,115.8,-0.2,-0.27,0.15],[127.5,40.1,108.3,115.7,-0.3,-0.27,0.15],[127.5,39.9,108.3,115.7,-0.2,-0.27,0.15],[128.0,39.7,108.3,115.6,-0.3,-0.27,0.15],[128.4,39.5,108.3,115.5,-0.2,-0.27,0.15],[128.1,39.4,108.3,115.5,-0.3,-0.27,0.15],[128.6,39.2,108.3,115.5,-0.2,-0.27,0.15],[128.6,39.1,108.3,115.4,-0.3,-0.27,0.15],[128.3,39.0,108.3,115.3,-0.2,-0.27,0.15]]},"subagents_hop":{"n":58,"loop":false,"scrub":false,"events":{},"role":"beat","state":"subagents","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[128.3,39.0,108.3,115.2,-0.2,-0.27,0.15],[128.4,38.8,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.7,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.5,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.3,108.3,114.8,-0.2,-0.27,0.15],[128.3,38.0,108.3,114.8,-0.2,-0.27,0.15],[128.1,37.9,108.3,114.7,-0.2,-0.27,0.15],[128.3,37.7,108.3,114.6,-0.3,-0.27,0.15],[128.3,37.5,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.4,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.3,108.3,114.4,-0.3,-0.27,0.15],[128.3,37.2,108.3,114.3,-0.2,-0.27,0.15],[128.3,37.2,108.3,114.3,-0.2,-0.27,0.15],[128.3,37.1,108.3,114.3,-0.3,-0.27,0.15],[128.3,37.1,108.3,114.3,-0.3,-0.27,0.15],[128.3,37.1,108.3,114.3,-0.3,-0.27,0.15],[128.3,37.1,108.3,114.3,-0.3,-0.27,0.15],[128.3,37.2,108.3,114.3,-0.2,-0.27,0.15],[128.3,37.2,108.3,114.3,-0.2,-0.27,0.15],[128.3,37.3,108.3,114.4,-0.3,-0.27,0.15],[128.3,37.4,108.3,114.5,-0.2,-0.27,0.15],[128.3,37.6,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.7,108.3,114.6,-0.3,-0.27,0.15],[128.3,37.9,108.3,114.7,-0.3,-0.27,0.15],[128.1,38.1,108.3,114.8,-0.3,-0.27,0.15],[128.3,38.2,108.3,114.8,-0.2,-0.27,0.15],[128.4,38.4,108.3,115.0,-0.2,-0.27,0.15],[128.4,38.6,108.3,115.0,-0.2,-0.27,0.15],[127.9,38.9,108.3,115.2,-0.3,-0.27,0.15],[128.1,39.1,108.3,115.3,-0.3,-0.27,0.15],[128.1,39.3,108.3,115.4,-0.3,-0.27,0.15],[128.1,39.5,108.3,115.5,-0.3,-0.27,0.15],[128.1,39.7,108.3,115.6,-0.3,-0.27,0.15],[127.9,39.9,108.3,115.7,-0.3,-0.27,0.15],[127.9,40.1,108.3,115.8,-0.3,-0.27,0.15],[128.1,40.2,108.3,115.8,-0.2,-0.27,0.15],[127.9,40.4,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.5,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.6,108.3,116.1,-0.3,-0.27,0.15],[128.1,40.7,108.3,116.2,-0.2,-0.27,0.15],[128.1,40.8,108.3,116.2,-0.2,-0.27,0.15],[127.9,40.9,108.3,116.2,-0.3,-0.27,0.15],[128.1,40.9,108.3,116.2,-0.2,-0.27,0.15],[128.1,40.9,108.3,116.2,-0.2,-0.27,0.15],[128.1,40.9,108.3,116.2,-0.2,-0.27,0.15],[128.1,40.9,108.3,116.2,-0.3,-0.27,0.15],[127.9,40.9,108.3,116.2,-0.3,-0.27,0.15],[127.9,40.8,108.3,116.2,-0.2,-0.27,0.15],[127.9,40.7,108.3,116.1,-0.3,-0.27,0.15],[127.9,40.6,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.4,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.3,108.3,115.9,-0.3,-0.27,0.15],[128.1,40.1,108.3,115.8,-0.2,-0.27,0.15],[128.4,39.9,108.3,115.8,-0.2,-0.27,0.15],[127.9,39.8,108.3,115.7,-0.2,-0.27,0.15],[127.9,39.6,108.3,115.5,-0.2,-0.27,0.15],[127.9,39.4,108.3,115.5,-0.2,-0.27,0.15],[127.9,39.2,108.3,115.3,-0.2,-0.27,0.15]]},"subagents_sigh":{"n":58,"loop":false,"scrub":false,"events":{},"role":"beat","state":"subagents","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[128.3,39.0,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.9,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.7,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.5,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.3,108.3,114.8,-0.2,-0.27,0.15],[128.1,38.1,108.3,114.8,-0.2,-0.27,0.15],[128.1,37.9,108.3,114.7,-0.2,-0.27,0.15],[128.3,37.7,108.3,114.6,-0.3,-0.27,0.15],[128.3,37.5,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.4,108.3,114.5,-0.2,-0.27,0.15],[128.3,37.3,108.3,114.4,-0.3,-0.27,0.15],[128.4,37.0,108.3,114.2,-0.2,-0.27,0.15],[128.4,36.1,108.3,113.8,-0.2,-0.27,0.15],[128.3,34.6,108.3,112.9,-0.3,-0.27,0.15],[129.2,32.4,108.3,111.7,-0.3,-0.27,0.15],[129.4,29.8,108.3,110.4,-0.3,-0.27,0.15],[129.5,26.9,108.4,109.1,-0.3,-0.27,0.15],[129.7,24.3,108.4,108.0,-0.3,-0.27,0.15],[130.3,22.2,108.3,107.2,-0.3,-0.27,0.15],[130.8,20.8,108.4,106.8,-0.3,-0.27,0.15],[130.9,20.3,108.4,106.7,-0.3,-0.27,0.15],[130.7,20.4,108.4,106.8,-0.3,-0.27,0.15],[130.6,21.1,108.4,107.0,-0.3,-0.27,0.15],[130.5,22.6,108.3,107.7,-0.3,-0.27,0.15],[129.9,25.0,108.3,108.8,-0.3,-0.27,0.15],[130.0,28.2,108.3,110.4,-0.3,-0.27,0.15],[129.7,32.2,108.3,112.4,-0.3,-0.27,0.15],[128.8,36.8,108.3,114.7,-0.3,-0.27,0.15],[128.3,41.6,108.3,117.0,-0.1,-0.27,0.15],[127.4,46.3,108.3,119.3,-0.1,-0.27,0.15],[127.0,50.6,108.3,121.5,-0.1,-0.27,0.15],[126.2,54.2,108.3,123.2,-0.1,-0.27,0.15],[126.3,56.8,108.2,124.3,-0.1,-0.27,0.15],[126.1,58.5,108.2,125.1,0.0,-0.27,0.15],[126.1,59.2,108.2,125.5,-0.1,-0.27,0.15],[126.2,59.3,108.2,125.5,-0.1,-0.27,0.15],[126.2,59.2,108.2,125.6,0.0,-0.27,0.15],[126.4,59.0,108.2,125.7,-0.1,-0.27,0.15],[126.6,58.8,108.2,125.8,-0.1,-0.27,0.15],[126.7,58.7,108.2,125.8,-0.1,-0.27,0.15],[126.7,58.4,108.2,125.7,0.0,-0.27,0.15],[126.1,54.3,108.2,123.0,-0.1,-0.27,0.15],[126.2,46.9,108.3,118.2,-0.1,-0.27,0.15],[127.1,42.7,108.3,116.2,-0.2,-0.27,0.15],[128.0,41.0,108.3,116.2,-0.2,-0.27,0.15],[128.4,39.8,108.3,116.2,-0.3,-0.27,0.15],[128.6,39.2,108.3,116.2,-0.3,-0.27,0.15],[128.7,39.1,108.3,116.2,-0.2,-0.27,0.15],[128.5,39.4,108.3,116.1,-0.3,-0.27,0.15],[128.3,39.9,108.3,116.0,-0.2,-0.27,0.15],[128.1,40.4,108.3,116.0,-0.2,-0.27,0.15],[127.9,40.7,108.3,115.9,-0.3,-0.27,0.15],[127.7,40.8,108.3,115.8,-0.2,-0.27,0.15],[127.9,40.6,108.3,115.8,-0.2,-0.27,0.15],[127.8,40.3,108.3,115.7,-0.2,-0.27,0.15],[128.0,39.8,108.3,115.5,-0.2,-0.27,0.15],[128.1,39.4,108.3,115.5,-0.2,-0.27,0.15],[128.1,39.0,108.3,115.3,-0.2,-0.27,0.15]]},"subagents_lean":{"n":58,"loop":false,"scrub":false,"events":{},"role":"beat","state":"subagents","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[128.3,39.0,108.3,115.2,-0.2,-0.27,0.15],[128.4,38.8,108.3,115.2,-0.2,-0.27,0.15],[128.1,38.7,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.5,108.3,115.0,-0.2,-0.27,0.15],[128.1,38.3,108.3,114.8,-0.2,-0.27,0.15],[128.3,38.0,108.3,114.8,-0.2,-0.27,0.15],[128.1,37.9,108.3,114.7,-0.2,-0.27,0.15],[128.3,37.7,108.3,114.6,-0.3,-0.27,0.15],[128.3,37.5,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.4,108.3,114.5,-0.2,-0.27,0.15],[128.4,37.3,108.3,114.4,-0.3,-0.27,0.15],[128.6,37.0,108.2,114.3,-0.2,-0.26,0.15],[130.0,36.1,107.6,114.3,-0.3,-0.25,0.15],[130.8,34.7,106.5,114.3,-0.5,-0.23,0.15],[133.9,32.8,104.8,114.4,-0.6,-0.2,0.15],[135.8,30.7,102.8,114.5,-0.8,-0.17,0.15],[135.8,28.7,100.6,114.6,-0.9,-0.13,0.15],[135.4,27.1,98.6,114.8,-1.1,-0.1,0.15],[134.4,26.0,97.1,114.8,-1.1,-0.08,0.15],[132.1,25.7,96.2,114.9,-1.1,-0.07,0.15],[132.2,26.1,96.0,115.0,-1.2,-0.07,0.15],[133.2,26.7,96.0,115.1,-1.2,-0.07,0.15],[133.9,27.2,96.0,115.2,-1.2,-0.07,0.15],[134.1,27.7,96.0,115.3,-1.2,-0.07,0.15],[134.3,28.0,95.9,115.4,-1.2,-0.07,0.15],[134.2,28.3,95.9,115.5,-1.2,-0.07,0.15],[134.0,28.4,95.9,115.6,-1.2,-0.07,0.15],[133.7,28.5,95.9,115.7,-1.2,-0.07,0.15],[133.3,28.6,95.9,115.8,-1.2,-0.07,0.15],[133.0,28.6,95.9,115.9,-1.2,-0.07,0.15],[132.7,28.7,95.9,116.1,-1.1,-0.07,0.15],[132.5,28.8,95.9,116.2,-1.1,-0.07,0.15],[132.4,28.9,95.9,116.2,-1.1,-0.07,0.15],[132.3,29.1,95.9,116.3,-1.1,-0.07,0.15],[132.4,29.3,95.9,116.4,-1.1,-0.07,0.15],[132.4,29.5,95.9,116.6,-1.1,-0.07,0.15],[132.5,29.7,95.9,116.7,-1.1,-0.07,0.15],[132.6,29.9,95.9,116.7,-1.2,-0.07,0.15],[132.7,30.1,95.9,116.8,-1.2,-0.07,0.15],[132.8,30.3,95.9,116.8,-1.1,-0.07,0.15],[132.9,30.4,95.9,116.9,-1.2,-0.07,0.15],[132.8,30.6,96.0,116.9,-1.2,-0.07,0.15],[127.8,37.6,102.8,116.5,-0.6,-0.17,0.15],[123.1,43.3,108.2,116.2,-0.2,-0.27,0.15],[123.3,43.5,108.3,116.2,-0.2,-0.27,0.15],[123.6,42.6,108.3,116.2,-0.3,-0.27,0.15],[125.4,41.8,108.3,116.2,-0.3,-0.27,0.15],[126.5,41.1,108.3,116.2,-0.2,-0.27,0.15],[127.9,40.5,108.3,116.1,-0.3,-0.27,0.15],[128.8,40.0,108.3,116.0,-0.2,-0.27,0.15],[129.2,39.6,108.3,116.0,-0.2,-0.27,0.15],[129.6,39.4,108.3,115.9,-0.3,-0.27,0.15],[129.4,39.2,108.3,115.8,-0.2,-0.27,0.15],[129.7,39.1,108.3,115.8,-0.2,-0.27,0.15],[130.0,39.1,108.3,115.7,-0.2,-0.27,0.15],[129.5,39.2,108.3,115.5,-0.2,-0.27,0.15],[128.8,39.2,108.3,115.5,-0.2,-0.27,0.15],[128.1,39.2,108.3,115.3,-0.2,-0.27,0.15]]},"speak_a":{"n":77,"loop":false,"scrub":false,"events":{},"role":"beat","state":"speaking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.7,43.6,98.2,118.3,0.1,0.03,0.0],[117.8,42.7,97.1,118.1,0.0,0.03,0.0],[121.3,41.5,95.4,117.5,-0.1,0.03,0.0],[123.1,40.6,94.3,116.4,-0.4,0.03,0.0],[123.3,40.4,94.2,115.2,-0.4,0.03,0.0],[123.1,40.4,94.5,113.8,-0.4,0.03,0.0],[122.2,40.8,94.7,112.4,-0.4,0.03,0.0],[120.7,40.4,94.8,111.4,-0.4,0.03,0.0],[118.3,40.2,94.9,110.8,-0.4,0.03,0.0],[117.1,40.2,95.0,110.4,-0.4,0.03,0.0],[116.2,40.4,95.0,110.3,-0.4,0.03,0.0],[114.1,40.9,94.8,111.7,-0.4,0.03,0.0],[113.4,42.4,94.1,115.8,-0.4,0.03,0.0],[115.2,43.5,93.7,118.3,-0.4,0.03,0.0],[118.9,43.5,93.8,117.7,-0.4,0.03,0.0],[120.1,41.2,94.6,112.6,-0.4,0.03,0.0],[120.3,39.9,95.0,110.3,-0.4,0.03,0.0],[122.3,40.2,94.8,111.7,-0.4,0.03,0.0],[121.6,41.7,94.1,115.8,-0.4,0.03,0.0],[120.7,42.5,93.7,118.3,-0.4,0.03,0.0],[121.8,41.9,94.0,116.8,-0.4,0.03,0.0],[122.7,37.2,95.7,107.3,-0.4,0.03,0.0],[122.8,36.3,96.5,103.3,-0.3,0.03,0.0],[118.0,36.5,96.0,105.6,-0.3,0.03,0.0],[112.9,39.9,94.6,113.3,-0.3,0.03,0.0],[111.9,43.0,93.7,118.2,-0.4,0.03,0.0],[112.7,43.0,93.8,117.7,-0.4,0.03,0.0],[119.5,41.7,94.6,112.6,-0.4,0.03,0.0],[120.8,41.3,95.0,110.3,-0.4,0.03,0.0],[121.0,41.4,94.8,111.7,-0.4,0.03,0.0],[120.9,42.4,94.1,115.8,-0.4,0.03,0.0],[120.9,43.2,93.7,118.3,-0.4,0.03,0.0],[120.8,42.7,93.8,118.2,-0.4,0.03,0.0],[120.8,41.1,94.2,115.4,-0.4,0.03,0.0],[120.6,39.7,94.7,111.8,-0.4,0.03,0.0],[121.9,39.6,95.0,110.3,-0.4,0.03,0.0],[121.0,40.2,94.8,111.1,-0.4,0.03,0.0],[117.8,41.2,94.2,114.8,-0.4,0.03,0.0],[116.4,42.7,93.8,118.2,-0.4,0.03,0.0],[118.1,43.0,93.8,118.2,-0.4,0.03,0.0],[120.8,41.9,94.5,113.7,-0.4,0.03,0.0],[120.9,40.8,95.0,110.4,-0.6,0.03,0.0],[120.8,41.0,94.8,111.1,-0.4,0.03,0.0],[119.7,41.8,94.2,114.8,-0.4,0.03,0.0],[119.0,42.8,93.8,118.2,-0.4,0.03,0.0],[120.0,43.1,93.7,118.4,-0.6,0.03,0.0],[121.0,43.2,93.7,118.4,-0.6,0.03,0.0],[121.7,42.7,93.7,118.4,-0.6,0.03,0.0],[120.1,42.3,93.7,118.4,-0.6,0.03,0.0],[120.2,42.1,93.7,118.4,-0.6,0.03,0.0],[120.9,41.9,93.7,118.4,-0.6,0.03,0.0],[120.3,41.9,93.7,118.4,-0.6,0.03,0.0],[120.3,41.9,93.7,118.4,-0.6,0.03,0.0],[119.3,42.5,94.3,118.4,-0.3,0.03,0.0],[114.7,44.0,96.5,118.3,-0.1,0.03,0.0],[113.8,44.4,98.2,118.3,0.1,0.03,0.0],[113.7,44.3,98.3,118.3,0.1,0.03,0.0],[113.3,44.2,98.3,118.3,0.1,0.03,0.0],[113.1,44.1,98.3,118.3,0.1,0.03,0.0],[113.4,44.0,98.3,118.3,0.1,0.03,0.0],[114.1,43.6,98.3,118.3,0.1,0.03,0.0],[115.5,43.3,98.3,118.3,0.1,0.03,0.0],[116.1,43.1,98.3,118.3,0.1,0.03,0.0],[116.6,43.0,98.3,118.3,0.1,0.03,0.0],[116.7,43.0,98.3,118.3,0.1,0.03,0.0],[115.7,43.1,98.3,118.3,0.1,0.03,0.0],[114.7,43.3,98.3,118.3,0.1,0.03,0.0],[114.0,43.4,98.3,118.3,0.1,0.03,0.0],[113.7,43.6,98.3,118.3,0.1,0.03,0.0]]},"speak_b":{"n":91,"loop":false,"scrub":false,"events":{},"role":"beat","state":"speaking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.3,43.8,98.5,118.3,0.1,0.03,0.0],[112.3,44.1,99.7,118.1,0.3,0.03,0.0],[111.4,44.3,101.4,117.4,0.4,0.03,0.0],[109.7,44.2,102.6,116.5,0.7,0.03,0.0],[109.1,43.5,102.8,115.2,0.7,0.03,0.0],[108.8,42.6,102.8,113.8,0.9,0.03,0.0],[108.3,41.9,102.7,112.4,1.0,0.03,0.0],[108.1,41.3,102.6,111.4,1.0,0.03,0.0],[108.4,40.9,102.5,110.8,1.0,0.03,0.0],[106.7,40.8,102.5,110.4,1.0,0.03,0.0],[106.5,40.9,102.5,110.3,1.0,0.03,0.0],[106.0,41.3,102.6,111.7,1.0,0.03,0.0],[106.7,42.9,102.9,115.8,0.7,0.03,0.0],[108.5,44.0,103.0,118.3,0.6,0.03,0.0],[109.6,44.0,102.9,117.3,0.7,0.03,0.0],[108.3,42.6,102.6,111.8,1.0,0.03,0.0],[108.0,42.0,102.5,110.4,1.2,0.03,0.0],[108.5,42.1,102.7,112.4,1.0,0.03,0.0],[109.4,43.0,103.0,116.7,0.7,0.03,0.0],[110.0,43.6,103.0,118.4,0.6,0.03,0.0],[109.4,43.0,102.9,116.2,0.7,0.03,0.0],[108.3,41.6,102.6,110.9,1.0,0.03,0.0],[108.4,41.4,102.5,110.6,1.0,0.03,0.0],[109.1,42.0,102.7,113.4,1.0,0.03,0.0],[109.1,43.4,102.9,117.5,0.7,0.03,0.0],[110.1,44.0,103.0,118.3,0.7,0.03,0.0],[109.0,43.0,102.8,114.8,0.9,0.03,0.0],[108.0,41.9,102.5,110.4,1.0,0.03,0.0],[108.4,41.7,102.6,110.9,1.0,0.03,0.0],[109.3,42.4,102.8,114.5,0.9,0.03,0.0],[110.4,43.5,103.0,118.0,0.7,0.03,0.0],[110.3,43.7,103.0,118.2,0.7,0.03,0.0],[109.1,41.5,102.7,113.3,0.9,0.03,0.0],[107.6,38.6,102.2,105.6,1.5,0.03,0.0],[107.3,37.2,102.0,103.3,1.5,0.03,0.0],[106.5,37.3,102.2,105.6,1.5,0.03,0.0],[107.1,40.8,102.7,113.3,0.9,0.03,0.0],[107.6,43.8,103.0,118.2,0.7,0.03,0.0],[107.5,43.7,102.9,117.3,0.7,0.03,0.0],[108.3,42.3,102.6,111.8,1.0,0.03,0.0],[108.2,42.2,102.5,110.4,1.2,0.03,0.0],[108.6,42.6,102.7,112.4,1.0,0.03,0.0],[109.6,43.7,103.0,116.7,0.7,0.03,0.0],[109.9,44.2,103.0,118.4,0.6,0.03,0.0],[109.2,43.5,103.0,116.7,0.7,0.03,0.0],[108.2,41.8,102.6,111.6,1.0,0.03,0.0],[108.1,41.3,102.5,110.4,1.2,0.03,0.0],[108.6,41.4,102.7,112.4,1.0,0.03,0.0],[110.0,42.7,103.0,116.7,0.7,0.03,0.0],[109.6,43.6,103.0,118.4,0.6,0.03,0.0],[109.5,43.5,103.0,117.0,0.8,0.03,0.0],[108.6,42.3,102.7,112.2,1.0,0.03,0.0],[108.3,41.8,102.5,110.3,1.0,0.03,0.0],[108.3,41.8,102.6,111.7,1.0,0.03,0.0],[109.9,42.9,102.9,115.8,0.7,0.03,0.0],[110.1,43.8,103.0,118.3,0.6,0.03,0.0],[110.0,44.0,103.0,118.4,0.6,0.03,0.0],[109.9,44.3,103.0,118.4,0.6,0.03,0.0],[109.5,44.5,103.0,118.4,0.6,0.03,0.0],[109.6,44.4,103.0,118.4,0.6,0.03,0.0],[109.6,44.2,103.0,118.4,0.6,0.03,0.0],[109.6,44.0,103.0,118.4,0.6,0.03,0.0],[109.6,44.0,103.0,118.4,0.6,0.03,0.0],[109.8,44.0,103.0,118.4,0.6,0.03,0.0],[109.9,44.1,102.8,118.4,0.6,0.03,0.0],[110.4,43.9,102.2,118.4,0.6,0.03,0.0],[111.6,43.6,101.2,118.3,0.4,0.03,0.0],[115.4,43.1,100.0,118.4,0.3,0.03,0.0],[117.7,42.9,99.0,118.3,0.1,0.03,0.0],[118.3,43.0,98.4,118.3,0.1,0.03,0.0],[116.8,43.3,98.3,118.3,0.1,0.03,0.0],[114.7,43.6,98.3,118.3,0.1,0.03,0.0],[113.6,43.8,98.3,118.3,0.1,0.03,0.0],[113.6,44.0,98.3,118.3,0.1,0.03,0.0],[113.4,44.1,98.3,118.3,0.1,0.03,0.0],[113.2,44.1,98.3,118.3,0.1,0.03,0.0],[113.1,44.1,98.3,118.3,0.1,0.03,0.0],[113.4,44.0,98.3,118.3,0.1,0.03,0.0],[113.2,43.9,98.3,118.3,0.1,0.03,0.0],[113.1,43.9,98.3,118.3,0.1,0.03,0.0],[113.3,43.8,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.6,43.6,98.3,118.3,0.1,0.03,0.0]]},"speak_c":{"n":62,"loop":false,"scrub":false,"events":{},"role":"beat","state":"speaking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.3,43.8,98.5,118.3,0.1,0.03,0.0],[112.3,44.1,99.7,118.1,0.3,0.03,0.0],[111.4,44.3,101.4,117.4,0.4,0.03,0.0],[109.7,44.2,102.6,116.5,0.7,0.03,0.0],[109.1,43.5,102.8,115.2,0.7,0.03,0.0],[108.8,42.6,102.8,113.8,0.9,0.03,0.0],[108.3,41.9,102.7,112.4,1.0,0.03,0.0],[108.1,41.3,102.6,111.4,1.0,0.03,0.0],[108.4,40.9,102.5,110.8,1.0,0.03,0.0],[106.7,40.8,102.5,110.4,1.0,0.03,0.0],[106.5,40.9,102.5,110.3,1.0,0.03,0.0],[106.0,41.3,102.6,111.7,1.0,0.03,0.0],[106.7,42.9,102.9,115.8,0.7,0.03,0.0],[108.5,44.0,103.0,118.3,0.6,0.03,0.0],[109.7,44.1,102.9,117.7,0.7,0.03,0.0],[108.3,42.9,102.7,112.6,0.9,0.03,0.0],[108.1,41.9,102.5,110.3,1.0,0.03,0.0],[108.4,41.9,102.6,111.7,1.0,0.03,0.0],[109.2,42.7,102.9,115.8,0.7,0.03,0.0],[110.0,43.5,103.0,118.3,0.6,0.03,0.0],[109.6,43.6,103.0,118.0,0.7,0.03,0.0],[109.2,42.6,102.8,114.5,0.9,0.03,0.0],[108.1,41.8,102.6,110.9,1.0,0.03,0.0],[108.2,41.4,102.5,110.4,1.2,0.03,0.0],[108.8,41.8,102.7,112.6,0.9,0.03,0.0],[108.6,43.2,103.0,116.8,0.7,0.03,0.0],[109.3,43.9,103.0,118.4,0.6,0.03,0.0],[108.9,42.8,102.8,114.6,0.9,0.03,0.0],[108.2,41.7,102.5,110.3,1.0,0.03,0.0],[108.6,41.8,102.6,111.7,1.0,0.03,0.0],[109.5,42.9,102.9,115.8,0.7,0.03,0.0],[110.3,43.8,103.0,118.3,0.6,0.03,0.0],[109.7,44.0,103.0,118.4,0.6,0.03,0.0],[109.9,44.3,103.0,118.4,0.6,0.03,0.0],[109.7,44.5,103.0,118.4,0.6,0.03,0.0],[109.7,44.4,103.0,118.4,0.6,0.03,0.0],[109.7,44.2,103.0,118.4,0.6,0.03,0.0],[109.6,44.1,103.0,118.4,0.6,0.03,0.0],[109.7,44.1,103.0,118.4,0.6,0.03,0.0],[109.7,44.2,103.0,118.4,0.6,0.03,0.0],[114.2,42.8,100.7,118.3,0.4,0.03,0.0],[118.7,41.8,98.4,118.3,0.1,0.03,0.0],[118.6,42.3,98.3,118.3,0.1,0.03,0.0],[118.2,42.9,98.3,118.3,0.1,0.03,0.0],[116.0,43.4,98.3,118.3,0.1,0.03,0.0],[114.1,43.9,98.3,118.3,0.1,0.03,0.0],[113.4,44.1,98.3,118.3,0.1,0.03,0.0],[113.7,44.2,98.3,118.3,0.1,0.03,0.0],[113.5,44.2,98.3,118.3,0.1,0.03,0.0],[113.3,44.2,98.3,118.3,0.1,0.03,0.0],[113.0,44.2,98.3,118.3,0.1,0.03,0.0],[113.3,44.0,98.3,118.3,0.1,0.03,0.0],[113.2,43.9,98.3,118.3,0.1,0.03,0.0],[113.1,43.8,98.3,118.3,0.1,0.03,0.0]]},"speak_d":{"n":106,"loop":false,"scrub":false,"events":{},"role":"beat","state":"speaking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.7,43.6,98.2,118.3,0.1,0.03,0.0],[117.8,42.7,97.1,118.1,0.0,0.03,0.0],[121.3,41.5,95.4,117.5,-0.1,0.03,0.0],[123.1,40.6,94.3,116.4,-0.4,0.03,0.0],[123.3,40.4,94.2,115.2,-0.4,0.03,0.0],[123.1,40.4,94.5,113.8,-0.4,0.03,0.0],[122.2,40.8,94.7,112.4,-0.4,0.03,0.0],[120.7,40.4,94.8,111.4,-0.4,0.03,0.0],[118.3,40.2,94.9,110.8,-0.4,0.03,0.0],[117.1,40.2,95.0,110.4,-0.4,0.03,0.0],[116.2,40.4,95.0,110.3,-0.4,0.03,0.0],[114.1,40.9,94.8,111.7,-0.4,0.03,0.0],[113.4,42.4,94.1,115.8,-0.4,0.03,0.0],[115.2,43.5,93.7,118.3,-0.4,0.03,0.0],[118.9,43.4,93.8,117.4,-0.6,0.03,0.0],[120.1,40.9,94.7,111.8,-0.4,0.03,0.0],[120.2,40.0,95.0,110.3,-0.4,0.03,0.0],[121.8,40.6,94.7,112.4,-0.4,0.03,0.0],[121.7,42.1,94.0,116.7,-0.4,0.03,0.0],[121.2,42.6,93.7,118.4,-0.6,0.03,0.0],[122.1,41.0,94.2,115.1,-0.4,0.03,0.0],[122.9,36.4,96.0,105.4,-0.3,0.03,0.0],[122.3,36.1,96.5,103.3,-0.3,0.03,0.0],[116.9,37.0,95.7,107.1,-0.3,0.03,0.0],[112.6,41.0,94.2,115.1,-0.4,0.03,0.0],[111.9,43.1,93.7,118.4,-0.6,0.03,0.0],[114.4,42.9,93.9,117.1,-0.4,0.03,0.0],[120.0,41.8,94.7,112.2,-0.4,0.03,0.0],[120.8,41.2,95.0,110.3,-0.4,0.03,0.0],[121.1,41.3,94.8,111.7,-0.4,0.03,0.0],[120.7,42.3,94.1,115.8,-0.4,0.03,0.0],[120.8,43.1,93.7,118.3,-0.4,0.03,0.0],[121.0,42.8,93.7,118.3,-0.4,0.03,0.0],[121.5,42.0,93.8,117.4,-0.4,0.03,0.0],[120.5,41.0,94.2,115.4,-0.4,0.03,0.0],[120.8,40.2,94.5,113.2,-0.4,0.03,0.0],[121.9,39.9,94.8,111.2,-0.4,0.03,0.0],[121.2,40.1,95.0,110.4,-0.4,0.03,0.0],[119.7,40.0,95.0,110.4,-0.4,0.03,0.0],[116.1,40.8,94.5,113.2,-0.4,0.03,0.0],[113.0,42.5,93.9,117.2,-0.4,0.03,0.0],[116.2,43.3,93.7,118.4,-0.6,0.03,0.0],[119.7,42.5,94.2,115.3,-0.4,0.03,0.0],[120.7,40.9,94.9,110.6,-0.4,0.03,0.0],[120.9,40.8,94.9,110.8,-0.4,0.03,0.0],[121.0,41.7,94.3,114.2,-0.4,0.03,0.0],[119.8,42.7,93.8,117.8,-0.4,0.03,0.0],[120.8,42.9,93.7,118.3,-0.4,0.03,0.0],[121.0,41.6,94.2,115.2,-0.4,0.03,0.0],[121.3,39.9,94.9,110.8,-0.4,0.03,0.0],[120.9,40.1,95.0,110.4,-0.4,0.03,0.0],[119.9,40.9,94.5,113.2,-0.4,0.03,0.0],[118.3,42.3,93.9,117.2,-0.4,0.03,0.0],[118.3,43.0,93.7,118.4,-0.6,0.03,0.0],[120.4,41.2,94.4,114.4,-0.4,0.03,0.0],[122.2,37.2,96.0,105.5,-0.3,0.03,0.0],[121.6,36.5,96.5,103.3,-0.3,0.03,0.0],[117.4,36.9,95.8,106.6,-0.3,0.03,0.0],[112.8,40.5,94.3,114.6,-0.4,0.03,0.0],[112.0,42.9,93.7,118.3,-0.4,0.03,0.0],[115.4,42.5,94.0,116.7,-0.4,0.03,0.0],[120.4,41.2,94.8,111.2,-0.4,0.03,0.0],[120.9,41.1,95.0,110.4,-0.4,0.03,0.0],[120.9,41.8,94.5,113.2,-0.4,0.03,0.0],[120.7,42.9,93.9,117.2,-0.4,0.03,0.0],[121.2,43.3,93.7,118.4,-0.6,0.03,0.0],[120.8,40.0,94.8,111.4,-0.4,0.03,0.0],[121.6,39.8,94.9,110.8,-0.4,0.03,0.0],[121.2,41.1,94.3,113.9,-0.4,0.03,0.0],[119.5,42.4,93.8,117.8,-0.4,0.03,0.0],[119.9,42.9,93.7,118.4,-0.6,0.03,0.0],[120.8,43.2,93.7,118.4,-0.6,0.03,0.0],[120.7,43.3,93.7,118.4,-0.6,0.03,0.0],[121.2,42.9,93.7,118.4,-0.6,0.03,0.0],[119.7,42.5,93.7,118.4,-0.6,0.03,0.0],[120.1,42.3,93.7,118.4,-0.6,0.03,0.0],[120.4,42.0,93.7,118.4,-0.6,0.03,0.0],[120.1,41.9,93.7,118.4,-0.6,0.03,0.0],[120.3,42.0,93.7,118.4,-0.6,0.03,0.0],[119.6,42.4,94.2,118.4,-0.3,0.03,0.0],[116.3,43.2,95.1,118.4,-0.3,0.03,0.0],[115.2,43.9,96.2,118.3,-0.1,0.03,0.0],[114.2,44.2,97.3,118.4,0.0,0.03,0.0],[113.6,44.3,98.1,118.3,0.1,0.03,0.0],[113.3,44.3,98.3,118.3,0.1,0.03,0.0],[113.2,44.2,98.3,118.3,0.1,0.03,0.0],[113.1,44.0,98.3,118.3,0.1,0.03,0.0],[113.8,43.6,98.3,118.3,0.1,0.03,0.0],[115.3,43.3,98.3,118.3,0.1,0.03,0.0],[115.9,43.1,98.3,118.3,0.1,0.03,0.0],[116.4,43.0,98.3,118.3,0.1,0.03,0.0],[116.2,43.1,98.3,118.3,0.1,0.03,0.0],[115.4,43.2,98.3,118.3,0.1,0.03,0.0],[114.7,43.3,98.3,118.3,0.1,0.03,0.0],[114.4,43.5,98.3,118.3,0.1,0.03,0.0],[113.7,43.6,98.3,118.3,0.1,0.03,0.0],[113.5,43.8,98.3,118.3,0.1,0.03,0.0],[113.4,43.8,98.3,118.3,0.1,0.03,0.0]]},"speaking_rest":{"n":43,"loop":true,"scrub":false,"events":{},"role":"rest","state":"speaking","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[113.4,43.7,98.3,118.3,0.1,0.03,0.0],[113.5,43.4,98.3,118.2,0.1,0.03,0.0],[113.6,43.1,98.3,118.0,0.1,0.03,0.0],[113.6,42.8,98.3,118.0,0.1,0.03,0.0],[113.5,42.6,98.3,117.8,0.0,0.03,0.0],[113.4,42.4,98.3,117.7,0.1,0.03,0.0],[113.6,42.1,98.4,117.5,0.1,0.03,0.0],[113.7,42.0,98.3,117.5,0.1,0.03,0.0],[113.7,41.8,98.3,117.4,0.0,0.03,0.0],[113.5,41.8,98.3,117.3,0.1,0.03,0.0],[113.7,41.7,98.3,117.3,0.1,0.03,0.0],[113.7,41.7,98.3,117.3,0.1,0.03,0.0],[113.7,41.7,98.3,117.3,0.1,0.03,0.0],[113.7,41.8,98.3,117.3,0.1,0.03,0.0],[113.7,41.9,98.3,117.5,0.1,0.03,0.0],[113.7,42.0,98.3,117.5,0.0,0.03,0.0],[113.7,42.2,98.3,117.6,0.0,0.03,0.0],[113.6,42.4,98.3,117.8,0.1,0.03,0.0],[113.5,42.7,98.3,117.8,0.1,0.03,0.0],[113.6,42.9,98.3,118.0,0.1,0.03,0.0],[113.6,43.2,98.3,118.2,0.1,0.03,0.0],[113.5,43.5,98.3,118.2,0.1,0.03,0.0],[113.5,43.8,98.3,118.5,0.1,0.03,0.0],[113.4,44.1,98.3,118.6,0.0,0.03,0.0],[113.4,44.4,98.3,118.8,0.1,0.03,0.0],[113.5,44.6,98.3,118.8,0.1,0.03,0.0],[113.4,44.9,98.3,119.0,0.0,0.03,0.0],[113.3,45.1,98.3,119.2,0.1,0.03,0.0],[113.3,45.3,98.3,119.2,0.1,0.03,0.0],[113.4,45.4,98.3,119.3,0.0,0.03,0.0],[113.5,45.5,98.3,119.3,0.1,0.03,0.0],[113.4,45.6,98.3,119.5,0.1,0.03,0.0],[113.3,45.7,98.3,119.5,0.1,0.03,0.0],[113.3,45.7,98.3,119.5,0.1,0.03,0.0],[113.4,45.6,98.3,119.4,0.0,0.03,0.0],[113.4,45.5,98.3,119.3,0.1,0.03,0.0],[113.4,45.4,98.3,119.3,0.0,0.03,0.0],[113.5,45.2,98.3,119.2,0.0,0.03,0.0],[113.4,45.0,98.3,119.1,0.0,0.03,0.0],[113.5,44.8,98.3,119.0,0.1,0.03,0.0],[113.4,44.6,98.3,118.8,0.1,0.03,0.0],[113.5,44.3,98.3,118.7,0.0,0.03,0.0],[113.5,44.0,98.3,118.5,0.1,0.03,0.0]]},"done_in":{"n":53,"loop":false,"scrub":false,"events":{"apex":17,"land":36},"role":"enter","state":"done","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.7,38.3,96.4,120.3,-0.1,0.0,-0.0],[120.7,41.2,96.7,121.8,-0.1,0.0,-0.01],[119.7,47.1,97.0,125.7,0.0,0.0,-0.03],[118.0,55.8,97.5,131.2,0.0,0.0,-0.06],[116.2,65.5,97.9,137.2,0.0,0.0,-0.09],[115.0,74.3,98.3,142.2,0.0,0.0,-0.12],[113.5,80.5,98.6,145.1,0.0,0.0,-0.14],[112.4,83.6,98.8,145.8,0.0,0.0,-0.14],[111.1,69.4,98.8,132.5,0.0,0.0,-0.05],[112.9,44.4,98.9,113.3,0.0,0.0,0.07],[112.6,24.1,98.9,97.6,0.0,0.0,0.18],[111.5,8.7,99.0,85.0,0.0,0.0,0.27],[111.3,-8.6,99.0,75.3,0.0,0.0,0.35],[110.0,-25.6,99.0,68.4,0.0,0.0,0.4],[110.1,-31.9,99.0,64.0,0.0,0.0,0.43],[110.0,-33.6,99.0,62.0,0.0,0.0,0.45],[110.0,-32.7,99.1,61.9,0.0,0.0,0.45],[110.4,-30.5,100.0,62.1,1.0,0.0,0.45],[110.8,-23.9,101.6,62.8,2.6,0.0,0.44],[101.3,-15.2,103.2,64.0,4.3,0.0,0.43],[97.8,-11.1,103.9,65.7,5.2,0.0,0.41],[95.9,-10.6,104.1,67.8,5.0,0.0,0.39],[99.2,-11.9,103.4,70.3,3.9,0.0,0.36],[119.5,-16.2,101.2,73.0,1.8,0.0,0.33],[120.6,-27.2,98.1,75.8,-0.6,0.0,0.29],[119.9,-29.7,95.4,78.5,-2.5,0.0,0.26],[127.1,-28.0,94.2,81.2,-3.3,0.0,0.24],[139.3,-21.4,94.0,83.2,-3.3,0.0,0.22],[137.3,-5.6,94.9,84.8,-2.5,0.0,0.2],[117.7,4.7,97.2,86.0,-1.0,0.0,0.19],[111.3,12.3,99.7,86.7,0.5,0.0,0.18],[97.7,13.9,100.8,87.0,1.0,0.0,0.18],[112.1,12.9,100.8,88.4,0.9,0.0,0.18],[112.5,17.2,100.6,95.7,0.6,0.0,0.14],[115.8,29.4,100.1,109.5,0.3,0.0,0.09],[111.3,57.6,99.0,130.0,0.0,0.0,0.0],[119.3,36.2,99.0,111.6,0.0,0.0,0.0],[122.0,15.7,99.0,100.6,0.0,0.0,0.0],[123.4,5.8,99.0,95.2,0.0,0.0,0.0],[121.4,4.0,99.0,93.8,0.0,0.0,0.0],[120.4,1.1,99.0,94.9,0.0,0.0,0.0],[118.5,-2.9,99.0,96.8,0.0,0.0,0.0],[113.1,-1.0,99.0,98.2,0.0,0.0,0.0],[113.7,-0.6,99.0,98.4,0.0,0.0,0.0],[114.8,-0.2,99.0,98.6,0.0,0.0,0.0],[115.1,4.0,99.0,99.0,0.0,0.0,0.0],[114.9,8.1,99.0,99.4,0.0,0.0,0.0],[113.4,11.2,99.0,99.8,0.0,0.0,0.0],[113.0,12.9,99.0,100.2,0.0,0.0,0.0],[113.5,13.2,99.0,100.6,0.0,0.0,0.0],[114.3,12.5,99.0,100.8,0.0,0.0,0.0],[115.5,11.2,99.0,100.9,0.0,0.0,0.0]]},"done_rest":{"n":86,"loop":true,"scrub":false,"events":{},"role":"rest","state":"done","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[116.1,9.7,99.0,100.9,0.0,0.0,0.0],[115.2,9.6,99.2,100.8,0.0,0.0,0.0],[114.6,9.4,99.5,100.7,0.3,0.0,0.0],[114.1,9.2,99.8,100.6,0.3,0.0,0.0],[113.6,9.0,100.0,100.5,0.3,0.0,0.0],[113.3,8.8,100.2,100.4,0.3,0.0,0.0],[112.6,8.7,100.4,100.3,0.5,0.0,0.0],[112.3,8.5,100.6,100.2,0.5,0.0,0.0],[112.0,8.3,100.8,100.1,0.6,0.0,0.0],[111.8,8.2,101.0,100.0,0.8,0.0,0.0],[111.5,7.8,101.0,99.8,0.6,0.0,0.0],[111.3,7.2,101.2,99.2,0.8,0.0,0.01],[111.1,6.5,101.2,98.8,0.8,0.0,0.01],[110.9,5.7,101.3,98.2,0.9,0.0,0.01],[110.7,4.9,101.3,97.8,0.8,0.0,0.02],[110.6,4.1,101.3,97.3,1.0,0.0,0.02],[110.6,3.3,101.3,96.8,0.8,0.0,0.02],[110.6,2.7,101.3,96.5,0.8,0.0,0.02],[110.8,2.1,101.2,96.0,0.8,0.0,0.03],[110.8,1.6,101.2,95.7,1.0,0.0,0.03],[110.9,1.2,101.2,95.4,1.0,0.0,0.03],[111.0,0.8,101.0,95.0,0.8,0.0,0.03],[111.6,0.4,101.0,94.8,0.8,0.0,0.04],[111.6,0.1,100.8,94.5,0.8,0.0,0.04],[112.0,-0.2,100.8,94.3,0.8,0.0,0.04],[112.0,-0.4,100.7,94.2,0.8,0.0,0.04],[112.6,-0.7,100.5,94.0,0.6,0.0,0.04],[113.1,-0.9,100.4,93.8,0.6,0.0,0.04],[112.9,-1.0,100.3,93.7,0.6,0.0,0.05],[113.1,-1.1,100.2,93.7,0.5,0.0,0.05],[113.6,-1.2,100.0,93.6,0.5,0.0,0.05],[113.8,-1.2,100.0,93.5,0.3,0.0,0.05],[114.1,-1.2,99.8,93.5,0.3,0.0,0.05],[114.0,-1.1,99.8,93.5,0.3,0.0,0.05],[114.2,-1.0,99.7,93.5,0.2,0.0,0.05],[114.6,-0.9,99.5,93.6,0.3,0.0,0.05],[114.7,-0.7,99.5,93.7,0.2,0.0,0.05],[114.8,-0.3,99.4,94.0,0.2,0.0,0.05],[115.1,0.5,99.3,94.7,0.2,0.0,0.05],[114.9,2.0,99.2,95.8,0.0,0.0,0.04],[115.6,4.0,99.2,97.3,0.0,0.0,0.03],[115.3,6.8,99.2,99.2,0.2,0.0,0.03],[115.5,10.3,99.1,101.6,0.0,0.0,0.02],[115.9,14.4,99.0,104.3,0.0,0.0,0.0],[115.7,16.7,98.9,105.0,0.0,0.0,0.0],[115.6,17.7,98.8,104.7,0.0,0.0,0.0],[115.5,17.4,98.8,104.0,0.0,0.0,0.0],[115.3,16.1,98.8,103.1,0.0,0.0,0.0],[115.5,14.1,98.7,102.2,-0.2,0.0,0.0],[116.2,12.1,98.7,101.7,0.0,0.0,0.0],[117.1,10.6,98.5,101.5,-0.2,0.0,0.0],[116.9,9.7,98.5,101.7,-0.2,0.0,0.0],[117.1,9.5,98.3,101.8,-0.2,0.0,0.0],[117.6,9.7,98.2,101.8,-0.3,0.0,0.0],[117.8,10.3,98.2,101.9,-0.3,0.0,0.0],[117.7,11.0,98.0,102.0,-0.3,0.0,0.0],[117.7,11.7,98.0,102.0,-0.3,0.0,0.0],[117.7,12.1,97.8,102.1,-0.3,0.0,0.0],[118.0,12.3,97.7,102.2,-0.5,0.0,0.0],[118.1,12.3,97.5,102.2,-0.5,0.0,0.0],[118.2,12.1,97.4,102.2,-0.5,0.0,0.0],[118.7,11.9,97.3,102.2,-0.5,0.0,0.0],[119.4,11.7,97.2,102.3,-0.6,0.0,0.0],[119.6,11.5,97.0,102.3,-0.6,0.0,0.0],[119.8,11.4,97.0,102.3,-0.6,0.0,0.0],[120.2,11.4,96.8,102.3,-0.6,0.0,0.0],[120.3,11.4,96.7,102.3,-0.6,0.0,0.0],[120.4,11.5,96.7,102.3,-0.6,0.0,0.0],[120.4,11.5,96.6,102.2,-0.8,0.0,0.0],[120.5,11.5,96.6,102.2,-0.8,0.0,0.0],[120.6,11.5,96.6,102.2,-0.8,0.0,0.0],[120.4,11.4,96.6,102.2,-0.8,0.0,0.0],[120.4,11.4,96.6,102.2,-0.8,0.0,0.0],[119.9,11.3,96.6,102.0,-0.8,0.0,0.0],[119.6,11.2,96.7,102.0,-0.8,0.0,0.0],[119.6,11.1,96.8,102.0,-0.8,0.0,0.0],[119.6,11.0,96.8,101.9,-0.6,0.0,0.0],[119.6,10.9,97.0,101.8,-0.6,0.0,0.0],[119.5,10.8,97.2,101.7,-0.6,0.0,0.0],[119.0,10.7,97.3,101.7,-0.5,0.0,0.0],[118.9,10.6,97.5,101.6,-0.5,0.0,0.0],[118.7,10.5,97.7,101.4,-0.5,0.0,0.0],[118.2,10.4,97.9,101.3,-0.5,0.0,0.0],[118.1,10.2,98.2,101.2,-0.2,0.0,0.0],[117.7,10.1,98.4,101.2,-0.2,0.0,0.0],[116.9,9.9,98.7,101.0,-0.2,0.0,0.0]]},"done_wiggle":{"n":67,"loop":false,"scrub":false,"events":{},"role":"beat","state":"done","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[116.5,9.6,99.0,100.9,0.0,0.0,0.0],[116.5,9.4,99.0,100.8,0.0,0.0,0.0],[116.5,9.2,99.0,100.6,0.0,0.0,0.0],[116.3,9.0,99.0,100.5,0.0,0.0,0.0],[116.5,8.7,99.0,100.4,0.0,0.0,0.0],[116.5,8.4,99.0,100.3,0.0,0.0,0.0],[116.7,8.1,99.0,100.2,0.0,0.0,0.0],[116.6,7.9,99.0,100.1,0.0,0.0,0.0],[116.2,7.6,99.0,100.0,0.0,0.0,0.0],[116.6,7.5,99.0,99.9,0.0,0.0,0.0],[116.2,7.3,99.0,99.8,0.0,0.0,0.0],[116.4,7.1,99.5,99.7,0.3,0.0,0.0],[115.7,6.9,100.9,99.7,0.8,0.0,0.0],[114.9,6.8,102.7,99.7,1.4,0.0,0.0],[113.2,6.9,104.1,99.6,2.0,0.0,0.0],[110.2,7.2,104.8,99.6,2.3,0.0,0.0],[106.1,7.7,104.8,99.6,2.3,0.0,0.0],[103.9,8.1,104.4,99.6,2.1,0.0,0.0],[102.8,8.5,103.2,99.6,1.6,0.0,0.0],[103.2,8.7,101.0,99.5,0.8,0.0,0.0],[105.4,8.6,98.5,99.5,-0.2,0.0,0.0],[109.6,8.1,96.0,99.7,-1.1,0.0,0.0],[116.3,7.4,94.2,99.8,-1.8,0.0,0.0],[120.9,6.4,93.3,99.8,-2.1,0.0,0.0],[129.6,3.8,93.2,99.9,-2.3,0.0,0.0],[136.3,2.1,93.3,100.0,-2.3,0.0,0.0],[138.3,1.3,94.2,100.0,-1.8,0.0,0.0],[137.2,1.4,96.0,100.2,-1.1,0.0,0.0],[136.0,2.5,98.5,100.2,-0.3,0.0,0.0],[127.2,4.6,101.1,100.3,0.8,0.0,0.0],[116.6,7.5,103.2,100.5,1.6,0.0,0.0],[110.8,9.2,104.5,100.7,2.1,0.0,0.0],[103.6,10.5,104.8,100.8,2.3,0.0,0.0],[99.7,11.6,104.8,100.9,2.3,0.0,0.0],[98.0,11.9,104.4,101.1,2.1,0.0,0.0],[98.1,12.1,103.2,101.1,1.6,0.0,0.0],[100.4,12.6,101.4,101.2,0.8,0.0,0.0],[104.1,12.3,99.3,101.3,0.2,0.0,0.0],[109.3,11.7,97.3,101.5,-0.6,0.0,0.0],[116.7,11.1,96.0,101.7,-1.1,0.0,0.0],[121.8,9.8,95.4,101.7,-1.3,0.0,0.0],[128.3,7.9,95.3,101.8,-1.4,0.0,0.0],[132.3,6.9,95.5,101.9,-1.3,0.0,0.0],[133.5,6.8,95.9,102.1,-1.1,0.0,0.0],[131.3,7.5,96.8,102.0,-0.8,0.0,0.0],[126.7,8.7,97.7,102.2,-0.5,0.0,0.0],[120.9,10.4,98.5,102.2,-0.2,0.0,0.0],[116.9,12.0,98.9,102.2,0.0,0.0,0.0],[114.2,12.6,99.0,102.3,0.0,0.0,0.0],[112.4,12.9,99.0,102.3,0.0,0.0,0.0],[110.7,13.1,99.0,102.3,0.0,0.0,0.0],[110.8,13.1,99.0,102.3,0.0,0.0,0.0],[112.4,12.9,99.0,102.3,0.0,0.0,0.0],[113.8,12.7,99.0,102.3,0.0,0.0,0.0],[115.0,12.4,99.0,102.2,0.0,0.0,0.0],[116.4,12.1,99.0,102.2,0.0,0.0,0.0],[116.9,11.8,99.0,102.1,0.0,0.0,0.0],[116.8,11.6,99.0,102.0,0.0,0.0,0.0],[116.9,11.5,99.0,102.0,0.0,0.0,0.0],[116.9,11.3,99.0,101.9,0.0,0.0,0.0],[116.8,11.2,99.0,101.8,0.0,0.0,0.0],[116.4,11.1,99.0,101.7,0.0,0.0,0.0],[116.5,10.9,99.0,101.6,0.0,0.0,0.0],[115.8,10.7,99.0,101.4,0.0,0.0,0.0],[115.7,10.5,99.0,101.3,0.0,0.0,0.0],[115.3,10.3,99.0,101.2,0.0,0.0,0.0],[115.7,10.0,99.0,101.1,0.0,0.0,0.0]]},"done_hop":{"n":58,"loop":false,"scrub":false,"events":{},"role":"beat","state":"done","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[116.5,9.6,99.0,100.9,0.0,0.0,0.0],[116.5,9.4,99.0,100.8,0.0,0.0,0.0],[116.6,9.1,99.0,100.6,0.0,0.0,0.0],[116.3,8.9,99.0,100.5,0.0,0.0,0.0],[116.7,8.5,99.0,100.3,0.0,0.0,0.0],[116.5,8.2,99.0,100.2,0.0,0.0,0.0],[116.6,7.9,99.0,100.1,0.0,0.0,0.0],[116.2,7.6,99.0,99.9,0.0,0.0,0.0],[116.6,7.4,99.0,99.8,0.0,0.0,0.0],[116.2,7.2,99.0,99.7,0.0,0.0,0.0],[116.6,7.4,99.0,99.8,0.0,0.0,-0.0],[116.2,11.8,99.0,104.1,0.0,0.0,-0.01],[116.4,24.3,99.0,114.4,0.0,0.0,-0.03],[117.0,41.5,99.0,124.7,0.0,0.0,-0.05],[117.9,49.9,99.0,129.2,0.0,0.0,-0.06],[112.9,46.1,99.0,119.2,0.0,0.0,0.01],[115.0,24.9,99.0,104.7,0.0,0.0,0.11],[115.2,8.9,99.0,93.4,0.0,0.0,0.18],[114.5,-2.1,99.0,85.0,0.0,0.0,0.24],[113.7,-10.6,99.0,79.6,0.0,0.0,0.28],[114.0,-24.3,99.0,77.1,0.0,0.0,0.3],[111.8,-26.4,99.0,77.4,0.0,0.0,0.3],[110.1,-21.7,99.0,80.4,0.0,0.0,0.28],[110.3,-13.3,99.0,86.0,0.0,0.0,0.24],[112.5,-1.2,99.0,94.2,0.0,0.0,0.19],[114.7,14.8,99.0,105.1,0.0,0.0,0.12],[116.8,35.0,99.0,118.8,0.0,0.0,0.04],[113.1,38.7,99.0,114.6,0.0,0.0,0.0],[116.2,19.3,99.0,103.7,0.0,0.0,0.0],[116.7,11.4,99.0,98.9,0.0,0.0,0.0],[114.9,11.1,99.0,98.2,0.0,0.0,0.0],[114.4,11.5,99.0,99.6,0.0,0.0,0.0],[115.4,5.2,99.0,101.2,0.0,0.0,0.0],[114.5,4.0,99.0,101.5,0.0,0.0,0.0],[114.4,4.3,99.0,101.7,0.0,0.0,0.0],[114.5,4.5,99.0,101.8,0.0,0.0,0.0],[115.9,7.0,99.0,101.9,0.0,0.0,0.0],[115.9,10.9,99.0,102.0,0.0,0.0,0.0],[114.8,14.1,99.0,102.1,0.0,0.0,0.0],[114.4,15.9,99.0,102.2,0.0,0.0,0.0],[114.3,16.3,99.0,102.2,0.0,0.0,0.0],[114.6,15.6,99.0,102.3,0.0,0.0,0.0],[114.9,14.2,99.0,102.3,0.0,0.0,0.0],[115.7,12.8,99.0,102.3,0.0,0.0,0.0],[116.2,11.6,99.0,102.3,0.0,0.0,0.0],[116.1,10.9,99.0,102.3,0.0,0.0,0.0],[115.9,10.7,99.0,102.2,0.0,0.0,0.0],[116.0,10.9,99.0,102.2,0.0,0.0,0.0],[116.0,11.3,99.0,102.1,0.0,0.0,0.0],[116.2,11.8,99.0,102.0,0.0,0.0,0.0],[116.3,12.0,99.0,101.9,0.0,0.0,0.0],[115.6,12.1,99.0,101.8,0.0,0.0,0.0],[115.6,11.9,99.0,101.7,0.0,0.0,0.0],[115.9,11.5,99.0,101.6,0.0,0.0,0.0],[116.1,11.0,99.0,101.4,0.0,0.0,0.0],[116.2,10.5,99.0,101.3,0.0,0.0,0.0],[116.3,10.0,99.0,101.1,0.0,0.0,0.0],[116.4,9.6,99.0,101.0,0.0,0.0,0.0]]},"needs_in":{"n":19,"loop":false,"scrub":false,"events":{"contact":11},"role":"enter","state":"needs","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.6,39.3,96.2,122.2,-0.1,0.01,-0.01],[121.9,44.7,96.2,127.5,-0.1,0.04,-0.04],[123.3,50.2,96.3,133.0,0.0,0.1,-0.09],[123.6,53.2,96.5,136.7,0.0,0.17,-0.16],[124.3,55.2,96.8,140.6,0.1,0.27,-0.25],[125.0,56.3,97.0,144.9,0.1,0.39,-0.35],[128.2,55.8,97.3,150.1,0.1,0.53,-0.48],[129.8,53.6,97.8,156.1,0.1,0.69,-0.63],[131.2,49.2,98.3,163.4,0.1,0.88,-0.8],[132.3,43.0,99.0,172.9,0.0,1.08,-0.98],[134.2,73.3,99.0,198.6,0.0,1.08,-1.0],[134.9,88.5,99.0,207.8,0.0,1.07,-1.0],[129.8,80.4,99.0,196.1,0.0,1.07,-1.0],[127.2,74.8,99.0,189.0,0.0,1.07,-1.0],[127.8,69.4,99.0,185.4,0.0,1.07,-1.0],[127.8,66.3,99.0,184.4,0.0,1.07,-1.0],[129.4,62.7,99.0,184.9,0.0,1.07,-1.0],[130.4,60.4,99.0,186.1,0.0,1.07,-1.0]]},"needs_rest":{"n":96,"loop":true,"scrub":false,"events":{"contact":[15,22]},"role":"rest","state":"needs","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[130.9,63.3,99.0,186.9,0.0,1.07,-1.0],[130.9,63.2,99.0,186.8,0.0,1.07,-1.0],[130.9,63.1,99.0,186.8,0.0,1.07,-1.0],[130.9,63.0,99.0,186.7,0.0,1.07,-1.0],[130.4,62.9,99.0,186.6,0.0,1.07,-1.0],[130.9,62.7,99.0,186.6,0.0,1.07,-1.0],[130.9,62.6,99.0,186.5,0.0,1.07,-1.0],[131.0,62.5,99.0,186.4,0.0,1.07,-1.0],[132.0,62.2,98.5,181.2,0.0,1.0,-1.0],[131.5,62.0,98.1,176.4,0.1,0.92,-1.0],[128.5,62.0,97.8,173.1,0.1,0.87,-1.0],[125.2,62.2,97.4,171.2,0.1,0.84,-1.0],[122.6,62.6,97.2,170.6,0.2,0.83,-1.0],[122.1,64.8,96.8,173.7,0.3,0.86,-1.0],[122.4,70.1,96.4,183.3,0.4,0.94,-1.0],[125.4,81.4,95.8,201.3,0.6,1.07,-1.0],[125.6,77.6,95.8,188.8,0.5,0.99,-1.0],[127.1,72.5,96.0,177.6,0.4,0.9,-1.0],[126.9,68.8,95.9,171.8,0.4,0.86,-1.0],[127.1,66.0,95.8,170.8,0.3,0.85,-1.0],[127.1,66.2,95.7,175.7,0.5,0.89,-1.0],[127.6,71.6,95.2,187.4,0.5,0.98,-1.0],[130.2,83.0,94.7,204.1,0.8,1.09,-1.0],[132.2,82.7,94.6,203.0,0.8,1.09,-1.0],[134.0,80.7,94.7,198.9,0.8,1.08,-1.0],[137.0,76.2,94.7,193.2,0.7,1.07,-1.0],[136.3,70.6,94.8,188.2,0.6,1.07,-1.0],[136.7,65.8,94.8,186.1,0.6,1.07,-1.0],[138.6,62.3,94.8,185.8,0.6,1.07,-1.0],[140.2,59.3,94.8,185.9,0.5,1.07,-1.0],[139.1,57.6,94.8,185.9,0.6,1.07,-1.0],[135.5,57.2,94.8,185.9,0.6,1.07,-1.0],[133.8,57.8,94.7,185.9,0.6,1.07,-1.0],[133.5,59.1,94.7,186.1,0.6,1.07,-1.0],[133.1,60.6,94.8,186.1,0.6,1.07,-1.0],[132.5,61.8,94.8,186.2,0.6,1.07,-1.0],[132.1,62.7,94.8,186.2,0.6,1.07,-1.0],[133.9,63.0,94.8,186.2,0.6,1.07,-1.0],[134.4,62.9,94.8,186.2,0.6,1.07,-1.0],[135.5,62.5,94.8,186.3,0.6,1.07,-1.0],[135.5,62.0,94.8,186.3,0.6,1.07,-1.0],[135.7,61.6,94.8,186.4,0.6,1.07,-1.0],[135.9,61.4,94.8,186.4,0.6,1.07,-1.0],[135.3,61.4,94.8,186.6,0.6,1.07,-1.0],[135.9,61.5,94.8,186.7,0.6,1.07,-1.0],[135.4,61.8,94.8,186.7,0.6,1.07,-1.0],[121.6,65.8,97.9,186.8,0.2,1.07,-1.0],[111.0,67.3,102.1,186.8,-0.4,1.07,-1.0],[112.6,67.5,103.2,186.8,-0.6,1.07,-1.0],[117.3,67.6,103.3,186.9,-0.6,1.07,-1.0],[120.2,66.2,103.3,187.1,-0.6,1.07,-1.0],[126.0,64.6,103.3,187.1,-0.6,1.07,-1.0],[127.9,63.4,103.2,187.2,-0.6,1.07,-1.0],[129.9,62.7,103.2,187.2,-0.6,1.07,-1.0],[129.6,62.4,103.2,187.2,-0.6,1.07,-1.0],[129.6,62.5,103.2,187.3,-0.6,1.07,-1.0],[130.2,62.8,103.2,187.4,-0.7,1.07,-1.0],[129.3,63.4,103.2,187.4,-0.6,1.07,-1.0],[128.0,64.0,103.2,187.5,-0.7,1.07,-1.0],[127.9,64.7,103.2,187.6,-0.6,1.07,-1.0],[127.0,65.2,103.2,187.7,-0.6,1.07,-1.0],[132.4,62.3,100.2,187.7,-0.2,1.07,-1.0],[133.1,62.1,99.2,187.7,0.0,1.07,-1.0],[133.9,63.0,99.0,187.8,0.0,1.07,-1.0],[133.0,64.0,99.0,187.8,0.0,1.07,-1.0],[131.0,65.0,99.0,187.8,0.0,1.07,-1.0],[129.8,65.6,99.0,187.9,0.0,1.07,-1.0],[128.4,66.0,99.0,187.9,0.0,1.07,-1.0],[127.6,66.2,99.0,187.9,0.0,1.07,-1.0],[127.5,66.2,99.0,187.9,0.0,1.07,-1.0],[128.2,66.1,99.0,187.9,0.0,1.07,-1.0],[129.0,65.9,99.0,187.9,0.0,1.07,-1.0],[130.7,65.6,99.0,187.9,0.0,1.07,-1.0],[130.4,65.4,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.7,64.9,99.0,187.9,0.0,1.07,-1.0],[130.8,64.8,99.0,187.9,0.0,1.07,-1.0],[130.9,64.7,99.0,187.9,0.0,1.07,-1.0],[130.9,64.7,99.0,187.9,0.0,1.07,-1.0],[130.7,64.7,99.0,187.8,0.0,1.07,-1.0],[130.6,64.7,99.0,187.8,0.0,1.07,-1.0],[130.7,64.7,99.0,187.8,0.0,1.07,-1.0],[130.8,64.7,99.0,187.7,0.0,1.07,-1.0],[130.9,64.7,99.0,187.7,0.0,1.07,-1.0],[131.0,64.6,99.0,187.6,0.0,1.07,-1.0],[130.7,64.6,99.0,187.6,0.0,1.07,-1.0],[131.1,64.5,99.0,187.5,0.0,1.07,-1.0],[131.1,64.4,99.0,187.5,0.0,1.07,-1.0],[131.1,64.3,99.0,187.4,0.0,1.07,-1.0],[130.7,64.2,99.0,187.4,0.0,1.07,-1.0],[130.5,64.1,99.0,187.3,0.0,1.07,-1.0],[131.0,63.9,99.0,187.2,0.0,1.07,-1.0],[130.9,63.8,99.0,187.2,0.0,1.07,-1.0],[130.9,63.7,99.0,187.1,0.0,1.07,-1.0],[130.9,63.5,99.0,187.0,0.0,1.07,-1.0],[130.9,63.4,99.0,187.0,0.0,1.07,-1.0]]},"needs_slide":{"n":77,"loop":false,"scrub":false,"events":{},"role":"beat","state":"needs","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[130.9,63.3,99.0,186.9,0.0,1.07,-1.0],[130.9,63.2,99.0,186.8,0.0,1.07,-1.0],[130.9,63.1,99.0,186.7,0.0,1.07,-1.0],[130.9,62.9,99.0,186.7,0.0,1.07,-1.0],[130.9,62.8,99.0,186.6,0.0,1.07,-1.0],[130.9,62.6,99.0,186.5,0.0,1.07,-1.0],[130.9,62.5,99.0,186.4,0.0,1.07,-1.0],[131.0,62.3,99.0,186.3,0.0,1.07,-1.0],[131.0,62.2,99.0,186.3,0.0,1.07,-1.0],[131.0,62.2,99.0,186.3,0.0,1.07,-1.0],[130.5,62.5,99.0,186.6,0.0,1.07,-1.01],[131.1,63.0,99.0,187.1,0.0,1.07,-1.01],[131.1,64.0,99.0,188.0,0.0,1.07,-1.02],[131.2,65.5,99.0,189.2,0.0,1.07,-1.04],[131.2,67.5,99.0,190.7,0.0,1.07,-1.06],[130.6,70.1,99.0,192.6,0.0,1.07,-1.08],[130.1,73.1,99.0,194.7,0.0,1.07,-1.1],[130.2,76.5,99.0,197.0,0.0,1.07,-1.13],[129.7,80.2,99.0,199.6,0.0,1.07,-1.16],[128.7,84.1,99.0,202.2,0.0,1.07,-1.19],[127.9,88.0,99.0,204.8,0.0,1.07,-1.22],[127.4,91.9,99.0,207.4,0.0,1.07,-1.26],[127.0,95.5,99.0,209.9,0.0,1.07,-1.28],[125.3,98.9,99.0,212.2,0.0,1.07,-1.31],[124.4,101.9,99.0,214.3,0.0,1.07,-1.33],[123.6,104.5,99.0,216.1,0.0,1.07,-1.36],[123.3,106.6,99.0,217.5,0.0,1.07,-1.37],[123.3,108.2,99.0,218.6,0.0,1.07,-1.38],[123.3,109.3,99.0,219.4,0.0,1.07,-1.39],[123.3,110.0,99.0,219.9,0.0,1.07,-1.4],[123.3,110.3,99.0,220.2,0.0,1.07,-1.4],[123.6,110.4,99.0,220.3,0.0,1.07,-1.4],[123.4,110.3,99.0,220.3,0.0,1.07,-1.4],[123.7,110.3,99.0,220.4,0.0,1.07,-1.4],[123.5,110.2,99.0,220.5,0.0,1.07,-1.4],[123.5,110.2,99.0,220.6,0.0,1.07,-1.4],[123.8,110.3,99.0,220.7,0.0,1.07,-1.4],[123.5,110.4,99.0,220.7,0.0,1.07,-1.4],[123.7,110.6,99.0,220.8,0.0,1.07,-1.4],[123.7,110.8,99.0,220.9,0.0,1.07,-1.4],[123.7,111.0,99.0,221.0,0.0,1.07,-1.4],[123.7,111.2,99.0,221.1,0.0,1.07,-1.4],[123.7,111.3,99.0,221.2,0.0,1.07,-1.4],[123.8,111.2,99.0,221.2,0.0,1.07,-1.4],[122.1,101.0,99.0,210.1,0.0,1.07,-1.27],[121.1,89.0,99.0,199.5,0.0,1.07,-1.14],[122.0,77.9,99.0,192.1,0.0,1.07,-1.05],[124.6,67.9,99.0,187.3,0.0,1.07,-1.0],[130.0,59.9,99.0,184.7,0.0,1.07,-0.96],[135.2,54.8,99.0,183.7,0.0,1.07,-0.95],[140.6,52.8,99.0,184.0,0.0,1.07,-0.95],[140.7,53.8,99.0,185.0,0.0,1.07,-0.97],[140.1,56.7,99.0,186.3,0.0,1.07,-0.98],[138.9,60.5,99.0,187.4,0.0,1.07,-0.99],[137.8,63.9,99.0,187.9,0.0,1.07,-1.0],[134.0,66.3,99.0,187.9,0.0,1.07,-1.0],[130.0,67.7,99.0,187.9,0.0,1.07,-1.0],[129.0,68.1,99.0,187.9,0.0,1.07,-1.0],[128.8,67.8,99.0,187.9,0.0,1.07,-1.0],[128.8,66.9,99.0,187.9,0.0,1.07,-1.0],[129.6,65.9,99.0,187.9,0.0,1.07,-1.0],[129.9,65.0,99.0,187.9,0.0,1.07,-1.0],[130.3,64.3,99.0,187.9,0.0,1.07,-1.0],[131.4,64.0,99.0,187.8,0.0,1.07,-1.0],[131.6,64.0,99.0,187.8,0.0,1.07,-1.0],[131.7,64.2,99.0,187.8,0.0,1.07,-1.0],[133.4,64.4,99.0,187.7,0.0,1.07,-1.0],[132.0,64.6,99.0,187.6,0.0,1.07,-1.0],[131.3,64.7,99.0,187.6,0.0,1.07,-1.0],[130.8,64.7,99.0,187.5,0.0,1.07,-1.0],[130.8,64.5,99.0,187.5,0.0,1.07,-1.0],[130.9,64.3,99.0,187.4,0.0,1.07,-1.0],[130.4,64.1,99.0,187.3,0.0,1.07,-1.0],[130.4,63.9,99.0,187.2,0.0,1.07,-1.0],[130.5,63.7,99.0,187.1,0.0,1.07,-1.0],[131.0,63.5,99.0,187.1,0.0,1.07,-1.0],[130.5,63.4,99.0,187.0,0.0,1.07,-1.0]]},"needs_tap":{"n":58,"loop":false,"scrub":false,"events":{"contact":[13,19,25]},"role":"beat","state":"needs","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[130.9,63.3,99.0,186.9,0.0,1.07,-1.0],[130.9,63.2,99.0,186.8,0.0,1.07,-1.0],[130.9,63.0,99.0,186.7,0.0,1.07,-1.0],[130.9,62.8,99.0,186.6,0.0,1.07,-1.0],[130.9,62.6,99.0,186.5,0.0,1.07,-1.0],[130.9,62.4,99.0,186.4,0.0,1.07,-1.0],[130.9,62.2,99.0,186.3,0.0,1.07,-1.0],[130.4,62.1,99.0,186.2,0.0,1.07,-1.0],[129.7,64.2,99.0,184.5,0.0,1.0,-1.0],[128.9,66.0,99.0,183.1,0.0,0.94,-1.0],[128.4,66.9,99.0,182.3,0.0,0.91,-1.0],[128.3,67.1,99.0,182.1,0.0,0.9,-1.0],[128.8,65.9,99.0,182.9,0.0,0.94,-1.0],[130.4,62.8,99.0,185.0,0.0,1.03,-1.0],[130.4,62.8,99.0,185.0,0.0,1.03,-1.0],[129.5,65.3,99.0,183.2,0.0,0.95,-1.0],[128.5,66.7,99.0,182.3,0.0,0.91,-1.0],[128.8,67.0,99.0,182.1,0.0,0.9,-1.0],[129.3,65.9,99.0,182.9,0.0,0.94,-1.0],[130.4,63.0,99.0,185.1,0.0,1.03,-1.0],[130.4,63.1,99.0,185.1,0.0,1.03,-1.0],[129.5,65.7,99.0,183.4,0.0,0.95,-1.0],[128.5,67.2,99.0,182.6,0.0,0.91,-1.0],[128.8,67.6,99.0,182.5,0.0,0.9,-1.0],[128.8,66.7,99.0,183.4,0.0,0.94,-1.0],[130.1,63.9,99.0,185.6,0.0,1.03,-1.0],[131.3,62.1,99.0,187.1,0.0,1.09,-1.0],[131.2,62.4,99.0,187.2,0.0,1.08,-1.0],[130.9,62.7,99.0,187.1,0.0,1.08,-1.0],[131.0,63.2,99.0,187.1,0.0,1.07,-1.0],[131.0,63.5,99.0,187.1,0.0,1.07,-1.0],[130.9,63.8,99.0,187.1,0.0,1.07,-1.0],[130.9,63.9,99.0,187.3,0.0,1.07,-1.0],[130.9,64.1,99.0,187.4,0.0,1.07,-1.0],[130.9,64.3,99.0,187.5,0.0,1.07,-1.0],[130.9,64.5,99.0,187.6,0.0,1.07,-1.0],[130.9,64.6,99.0,187.6,0.0,1.07,-1.0],[130.9,64.7,99.0,187.7,0.0,1.07,-1.0],[130.9,64.9,99.0,187.8,0.0,1.07,-1.0],[130.9,65.0,99.0,187.8,0.0,1.07,-1.0],[130.9,65.0,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.1,99.0,187.9,0.0,1.07,-1.0],[130.9,65.0,99.0,187.9,0.0,1.07,-1.0],[130.9,64.9,99.0,187.8,0.0,1.07,-1.0],[130.9,64.8,99.0,187.7,0.0,1.07,-1.0],[130.9,64.7,99.0,187.7,0.0,1.07,-1.0],[130.9,64.5,99.0,187.6,0.0,1.07,-1.0],[130.9,64.4,99.0,187.5,0.0,1.07,-1.0],[130.9,64.2,99.0,187.4,0.0,1.07,-1.0],[130.9,64.0,99.0,187.3,0.0,1.07,-1.0],[130.9,63.8,99.0,187.2,0.0,1.07,-1.0],[130.9,63.6,99.0,187.1,0.0,1.07,-1.0],[130.9,63.4,99.0,187.0,0.0,1.07,-1.0]]},"approval_in":{"n":22,"loop":false,"scrub":false,"events":{"land":8},"role":"enter","state":"approval","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,38.0,96.2,120.7,-0.1,0.0,0.0],[122.1,46.5,97.0,127.0,-0.1,0.0,-0.1],[121.8,56.0,97.5,132.8,-0.1,0.0,-0.18],[118.2,66.2,98.0,138.1,0.0,0.0,-0.26],[115.2,76.3,98.4,142.8,0.0,0.0,-0.33],[113.6,85.5,98.7,147.0,0.0,0.0,-0.39],[112.9,93.2,98.8,150.5,0.0,0.0,-0.44],[111.8,98.8,99.0,153.4,0.0,0.0,-0.48],[111.0,102.8,99.1,155.6,0.0,0.0,-0.51],[109.9,105.2,99.1,157.2,0.0,0.0,-0.53],[110.0,106.3,99.2,158.1,-0.1,0.0,-0.55],[110.1,106.2,99.2,158.2,0.0,0.0,-0.55],[110.2,105.9,99.2,159.5,0.0,0.0,-0.6],[110.5,106.0,99.2,164.0,0.0,0.0,-0.76],[111.6,106.5,99.2,170.7,0.0,0.0,-0.99],[113.0,107.3,99.2,176.9,0.0,0.0,-1.21],[111.8,108.6,99.1,180.2,0.0,0.0,-1.32],[111.5,109.4,99.1,179.9,0.0,0.0,-1.32],[111.5,108.4,99.1,177.1,0.0,0.0,-1.26],[111.5,107.7,99.0,176.1,0.0,0.0,-1.24],[111.7,106.9,99.0,176.1,0.0,0.0,-1.24],[112.0,106.2,99.0,176.6,0.0,0.0,-1.25]]},"approval_rest":{"n":101,"loop":true,"scrub":false,"events":{},"role":"rest","state":"approval","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[111.8,105.5,99.0,176.7,0.0,0.0,-1.25],[111.5,105.4,99.2,176.6,0.0,0.0,-1.25],[111.3,105.3,99.3,176.6,-0.1,0.0,-1.25],[111.0,105.2,99.5,176.4,-0.1,0.0,-1.25],[110.5,105.1,99.7,176.4,-0.3,0.0,-1.25],[110.2,105.0,99.8,176.4,-0.1,0.0,-1.25],[110.0,104.8,100.0,176.3,-0.3,0.0,-1.25],[109.7,104.7,100.2,176.2,-0.3,0.0,-1.25],[109.5,104.6,100.3,176.2,-0.4,0.0,-1.25],[109.3,104.5,100.5,176.1,-0.4,0.0,-1.25],[109.1,104.3,100.5,176.2,-0.4,0.01,-1.25],[109.0,104.1,100.7,176.3,-0.6,0.03,-1.25],[108.7,103.8,100.8,176.4,-0.4,0.04,-1.25],[108.6,103.6,100.9,176.6,-0.6,0.06,-1.25],[108.4,103.3,100.9,176.7,-0.6,0.07,-1.25],[108.3,103.1,101.0,176.8,-0.6,0.08,-1.25],[108.3,103.0,101.1,176.9,-0.6,0.09,-1.25],[108.2,102.8,101.2,176.9,-0.7,0.1,-1.25],[108.2,102.7,101.2,177.0,-0.6,0.11,-1.25],[108.1,102.6,101.2,177.1,-0.7,0.11,-1.25],[108.1,102.5,101.2,177.1,-0.6,0.12,-1.25],[108.2,102.4,101.2,177.1,-0.6,0.12,-1.25],[108.4,102.3,101.2,177.2,-0.7,0.12,-1.25],[108.3,102.3,101.2,177.2,-0.7,0.13,-1.25],[108.6,102.2,101.2,177.2,-0.6,0.13,-1.25],[108.7,102.2,101.0,177.2,-0.6,0.13,-1.25],[108.7,102.2,101.0,177.2,-0.6,0.13,-1.25],[108.8,102.2,100.9,177.2,-0.6,0.13,-1.25],[109.0,102.2,100.9,177.2,-0.4,0.13,-1.25],[109.0,102.3,100.8,177.2,-0.4,0.13,-1.25],[109.1,102.3,100.8,177.3,-0.5,0.13,-1.25],[109.3,102.3,100.7,177.3,-0.5,0.13,-1.25],[109.4,102.4,100.6,177.3,-0.4,0.13,-1.25],[109.7,102.4,100.4,177.3,-0.4,0.13,-1.25],[109.8,102.5,100.4,177.4,-0.4,0.13,-1.25],[109.9,102.6,100.3,177.4,-0.4,0.13,-1.25],[110.2,102.6,100.2,177.5,-0.3,0.13,-1.25],[110.3,102.7,100.0,177.6,-0.4,0.13,-1.25],[110.4,102.8,100.0,177.6,-0.3,0.13,-1.25],[110.6,102.9,99.9,177.6,-0.3,0.13,-1.25],[110.7,103.0,99.8,177.7,-0.3,0.13,-1.25],[110.9,103.1,99.7,177.8,-0.1,0.13,-1.25],[111.0,103.2,99.7,177.9,-0.1,0.13,-1.25],[111.2,103.3,99.6,177.9,-0.1,0.13,-1.25],[111.3,103.4,99.5,177.9,-0.1,0.13,-1.25],[111.4,103.6,99.4,178.1,-0.1,0.13,-1.25],[111.5,103.7,99.3,178.1,0.0,0.13,-1.25],[111.6,103.8,99.2,178.1,-0.1,0.13,-1.25],[111.7,103.9,99.2,178.2,0.0,0.13,-1.25],[111.9,104.0,99.1,178.3,0.0,0.13,-1.25],[112.0,104.2,99.0,178.4,0.0,0.13,-1.25],[112.1,104.3,99.0,178.4,0.0,0.13,-1.25],[112.2,104.4,98.9,178.5,0.0,0.13,-1.25],[112.3,104.5,98.8,178.6,0.0,0.13,-1.25],[112.4,104.6,98.7,178.6,0.1,0.13,-1.25],[112.5,104.7,98.7,178.8,0.1,0.13,-1.25],[112.6,105.7,98.6,177.6,0.1,0.05,-1.25],[112.5,106.2,98.5,177.2,0.1,0.01,-1.25],[112.6,106.4,98.4,177.1,0.1,0.0,-1.25],[113.1,106.5,98.3,177.2,0.1,0.0,-1.25],[113.1,106.6,98.2,177.3,0.3,0.0,-1.25],[113.1,106.6,98.2,177.4,0.1,0.0,-1.25],[113.5,106.7,98.1,177.4,0.3,0.0,-1.25],[114.0,106.8,98.1,177.5,0.3,0.0,-1.25],[114.1,106.9,97.9,177.5,0.3,0.0,-1.25],[114.2,106.9,97.8,177.6,0.4,0.0,-1.25],[114.4,107.0,97.8,177.6,0.3,0.0,-1.25],[114.8,107.1,97.7,177.7,0.4,0.0,-1.25],[114.6,107.1,97.6,177.7,0.4,0.0,-1.25],[115.1,107.2,97.5,177.7,0.4,0.0,-1.25],[115.2,107.2,97.4,177.7,0.6,0.0,-1.25],[115.4,107.2,97.3,177.8,0.4,0.0,-1.25],[115.5,107.2,97.2,177.8,0.4,0.0,-1.25],[115.7,107.3,97.2,177.8,0.4,0.0,-1.25],[115.7,107.3,97.1,177.8,0.6,0.0,-1.25],[115.8,107.3,97.0,177.8,0.6,0.0,-1.25],[115.8,107.3,97.0,177.8,0.6,0.0,-1.25],[116.0,107.3,97.0,177.8,0.7,0.0,-1.25],[116.1,107.3,96.8,177.8,0.7,0.0,-1.25],[116.1,107.2,96.8,177.8,0.7,0.0,-1.25],[116.2,107.2,96.8,177.7,0.6,0.0,-1.25],[116.1,107.2,96.8,177.7,0.6,0.0,-1.25],[116.2,107.1,96.8,177.7,0.6,0.0,-1.25],[116.1,107.1,96.8,177.7,0.7,0.0,-1.25],[115.8,107.0,96.9,177.6,0.6,0.0,-1.25],[115.9,107.0,97.0,177.6,0.6,0.0,-1.25],[115.6,106.9,97.0,177.6,0.7,0.0,-1.25],[115.5,106.9,97.0,177.5,0.6,0.0,-1.25],[115.5,106.8,97.2,177.4,0.4,0.0,-1.25],[115.3,106.7,97.2,177.4,0.6,0.0,-1.25],[115.1,106.6,97.3,177.3,0.4,0.0,-1.25],[114.6,106.5,97.5,177.3,0.6,0.0,-1.25],[114.8,106.5,97.6,177.2,0.4,0.0,-1.25],[114.2,106.4,97.7,177.2,0.3,0.0,-1.25],[114.0,106.3,97.8,177.1,0.3,0.0,-1.25],[113.5,106.2,98.0,177.1,0.3,0.0,-1.25],[113.1,106.1,98.2,177.0,0.3,0.0,-1.25],[112.9,106.0,98.3,176.9,0.1,0.0,-1.25],[112.7,105.8,98.5,176.9,0.1,0.0,-1.25],[112.4,105.7,98.7,176.8,0.0,0.0,-1.25],[112.0,105.6,98.8,176.7,0.0,0.0,-1.25]]},"approval_wobble":{"n":58,"loop":false,"scrub":false,"events":{},"role":"beat","state":"approval","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[111.7,105.5,99.0,176.7,0.0,0.0,-1.25],[111.7,105.3,99.0,176.6,0.0,0.0,-1.25],[111.7,105.2,99.0,176.4,0.0,0.0,-1.25],[111.7,105.0,99.0,176.3,0.0,0.0,-1.25],[111.7,104.7,99.0,176.2,0.0,0.0,-1.25],[111.8,104.5,99.0,176.1,0.0,0.0,-1.25],[111.8,104.3,99.0,176.0,0.0,0.0,-1.25],[111.7,104.1,99.0,175.9,0.0,0.0,-1.25],[111.7,104.0,99.0,175.8,0.0,0.0,-1.25],[111.8,103.9,99.0,175.8,0.0,0.0,-1.25],[111.7,103.8,99.0,175.7,0.0,0.0,-1.25],[111.5,103.7,99.2,175.6,-0.1,0.0,-1.25],[111.9,103.5,99.8,175.6,-0.3,0.0,-1.25],[111.6,103.4,100.8,175.6,-0.4,0.0,-1.25],[111.5,103.3,101.8,175.6,-0.7,0.0,-1.25],[109.0,103.4,102.5,175.6,-0.7,0.0,-1.25],[106.5,103.6,102.8,175.6,-0.9,0.0,-1.25],[105.2,103.8,102.8,175.6,-0.9,0.0,-1.25],[104.8,104.0,102.7,175.6,-0.9,0.0,-1.25],[104.6,104.3,102.1,175.7,-0.7,0.0,-1.25],[105.2,104.6,100.8,175.8,-0.4,0.0,-1.25],[107.0,104.8,99.2,175.9,-0.1,0.0,-1.25],[109.9,104.8,97.5,175.9,0.3,0.0,-1.25],[113.0,104.8,96.2,176.0,0.6,0.0,-1.25],[115.4,104.6,95.6,176.1,0.9,0.0,-1.25],[120.5,104.3,95.4,176.2,0.9,0.0,-1.25],[123.7,103.6,95.4,176.3,0.9,0.0,-1.25],[124.3,103.3,95.6,176.4,0.7,0.0,-1.25],[124.4,103.4,96.1,176.6,0.7,0.0,-1.25],[123.0,103.7,96.8,176.7,0.4,0.0,-1.25],[121.5,104.3,97.5,176.8,0.3,0.0,-1.25],[118.6,105.1,98.2,176.9,0.1,0.0,-1.25],[114.2,106.0,98.8,177.1,-0.1,0.0,-1.25],[110.6,106.4,99.2,177.1,-0.1,0.0,-1.25],[109.6,106.8,99.3,177.2,-0.1,0.0,-1.25],[108.8,107.0,99.4,177.4,-0.1,0.0,-1.25],[108.7,107.2,99.4,177.4,-0.1,0.0,-1.25],[109.1,107.3,99.3,177.6,-0.1,0.0,-1.25],[109.8,107.4,99.2,177.6,0.0,0.0,-1.25],[110.5,107.4,99.0,177.7,0.0,0.0,-1.25],[111.1,107.4,99.0,177.7,0.0,0.0,-1.25],[112.6,107.3,99.0,177.7,0.0,0.0,-1.25],[113.5,107.3,99.0,177.8,0.0,0.0,-1.25],[114.2,107.3,99.0,177.8,0.0,0.0,-1.25],[113.7,107.3,99.0,177.8,0.0,0.0,-1.25],[113.4,107.3,99.0,177.8,0.0,0.0,-1.25],[112.9,107.3,99.0,177.7,0.0,0.0,-1.25],[112.2,107.2,99.0,177.7,0.0,0.0,-1.25],[111.3,107.2,99.0,177.6,0.0,0.0,-1.25],[111.2,107.1,99.0,177.6,0.0,0.0,-1.25],[111.1,107.0,99.0,177.5,0.0,0.0,-1.25],[111.3,106.8,99.0,177.4,0.0,0.0,-1.25],[111.1,106.7,99.0,177.3,0.0,0.0,-1.25],[111.3,106.5,99.0,177.2,0.0,0.0,-1.25],[111.7,106.3,99.0,177.1,0.0,0.0,-1.25],[111.7,106.0,99.0,177.0,0.0,0.0,-1.25],[111.7,105.8,99.0,176.9,0.0,0.0,-1.25],[111.7,105.6,99.0,176.7,0.0,0.0,-1.25]]},"approval_hold":{"n":13,"loop":false,"scrub":true,"events":{},"role":"scrub","state":"approval","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[111.9,105.5,98.8,176.7,0.0,0.0,-1.25],[111.2,102.7,99.2,174.1,-0.1,0.0,-1.22],[111.8,99.9,98.8,171.4,0.0,0.0,-1.2],[110.3,97.2,99.3,168.8,0.0,0.0,-1.17],[111.6,94.4,98.6,166.1,0.1,0.0,-1.14],[109.9,91.7,99.5,163.6,-0.1,0.0,-1.12],[111.6,88.9,98.4,160.9,0.1,0.0,-1.09],[109.5,86.2,99.5,158.4,-0.1,0.0,-1.06],[112.0,83.4,98.3,155.7,0.0,0.0,-1.04],[109.2,80.8,99.7,153.1,0.0,0.0,-1.01],[112.0,78.0,98.2,150.5,0.0,0.0,-0.98],[108.9,75.4,99.8,147.9,0.0,0.0,-0.96],[112.2,72.6,98.1,145.3,0.0,0.0,-0.93]]},"approval_allow":{"n":24,"loop":false,"scrub":false,"events":{"launch":7},"role":"react","state":"approval","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[111.9,72.8,98.1,145.3,0.0,0.0,-0.93],[113.2,78.4,98.1,151.4,0.2,0.0,-0.98],[114.5,98.9,98.0,170.0,0.3,0.0,-1.13],[114.6,127.2,97.8,192.2,0.4,0.0,-1.29],[111.5,95.5,98.0,158.9,0.1,0.0,-0.96],[110.9,65.8,98.0,135.0,0.0,0.0,-0.72],[110.3,47.6,98.0,120.2,-0.2,0.0,-0.56],[110.1,40.4,98.0,114.3,-0.3,0.0,-0.5],[111.2,33.8,97.8,115.0,-0.2,0.0,-0.5],[109.7,32.5,97.8,119.2,-0.2,0.0,-0.54],[110.0,41.9,97.5,127.8,-0.2,0.0,-0.62],[111.9,54.2,97.4,139.0,0.0,0.0,-0.72],[115.0,65.5,97.2,149.6,0.0,0.0,-0.82],[116.6,72.3,97.0,156.9,0.1,0.0,-0.88],[115.8,80.0,96.9,159.8,0.1,0.0,-0.9],[117.2,82.1,96.8,160.4,0.3,0.0,-0.9],[120.2,79.7,96.7,159.6,0.3,0.0,-0.87],[120.4,75.7,96.5,156.3,0.3,0.0,-0.79],[120.5,69.9,96.4,150.4,0.1,0.0,-0.65],[120.7,63.0,96.4,142.9,0.1,0.0,-0.49],[122.3,52.3,96.3,135.1,0.0,0.0,-0.31],[123.4,42.3,96.3,128.2,0.0,0.0,-0.16],[123.0,35.2,96.2,123.3,-0.1,0.0,-0.06],[122.7,32.6,96.2,121.0,-0.1,0.0,-0.01]]},"approval_deny":{"n":24,"loop":false,"scrub":false,"events":{"drop":4},"role":"react","state":"approval","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[111.3,105.9,99.0,176.7,0.0,0.0,-1.25],[113.8,127.1,99.0,199.3,0.0,0.0,-1.5],[114.2,135.8,99.0,206.6,0.0,0.0,-1.59],[113.5,139.6,99.0,207.9,0.0,0.0,-1.6],[112.4,142.0,98.9,208.1,0.0,0.0,-1.6],[112.1,143.1,98.8,208.0,0.0,0.0,-1.59],[111.8,142.5,98.8,207.4,0.1,0.0,-1.58],[111.9,140.2,98.7,206.1,0.0,0.0,-1.55],[112.6,136.7,98.6,204.4,0.1,0.0,-1.52],[114.0,132.6,98.4,202.8,0.1,0.0,-1.49],[114.9,128.6,98.2,201.3,0.3,0.0,-1.46],[116.4,125.1,98.1,200.4,0.3,0.0,-1.45],[118.0,122.3,97.8,199.9,0.4,0.0,-1.45],[119.6,119.6,97.7,199.2,0.4,0.0,-1.44],[120.5,115.9,97.4,196.3,0.4,0.0,-1.4],[121.1,110.3,97.2,190.8,0.4,0.0,-1.3],[121.3,102.2,97.0,182.2,0.4,0.0,-1.15],[121.5,91.8,96.8,171.4,0.3,0.0,-0.95],[120.7,79.7,96.6,159.4,0.3,0.0,-0.72],[121.5,66.9,96.5,147.4,0.1,0.0,-0.5],[121.8,54.8,96.3,136.9,0.0,0.0,-0.3],[121.6,44.7,96.3,128.6,-0.1,0.0,-0.15],[122.4,37.6,96.2,123.5,-0.1,0.0,-0.05],[122.4,34.0,96.2,121.0,-0.1,0.0,-0.01]]},"blocked_in":{"n":29,"loop":false,"scrub":false,"events":{"bonk":12},"role":"enter","state":"blocked","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[121.0,37.0,96.3,117.5,-0.1,0.0,0.04],[122.3,38.6,96.8,115.8,-0.3,0.0,0.08],[120.8,42.9,97.3,115.4,-0.3,0.0,0.11],[117.9,48.6,97.8,115.7,-0.4,0.0,0.14],[116.5,53.7,97.9,115.3,-0.5,0.0,0.17],[112.1,55.5,97.9,114.1,-0.5,0.0,0.19],[108.4,45.4,97.8,103.0,-0.7,0.0,0.21],[105.6,34.3,97.8,94.4,-1.0,0.0,0.22],[104.7,26.6,97.5,88.6,-1.5,0.0,0.23],[104.3,19.0,97.1,85.4,-1.9,0.0,0.24],[104.8,23.1,96.6,96.6,-2.4,0.0,0.2],[104.7,68.3,96.4,133.8,-2.2,0.0,0.06],[104.1,69.0,95.9,138.6,-2.8,0.0,0.04],[114.0,63.8,95.4,138.2,-3.5,0.0,0.04],[114.0,63.0,94.8,136.0,-4.4,0.0,0.03],[111.9,53.9,94.2,132.7,-5.5,0.0,0.02],[109.4,46.3,93.5,129.7,-6.7,0.0,0.01],[107.0,41.4,92.9,128.2,-7.9,0.0,0.0],[104.5,39.8,92.5,128.6,-9.0,0.0,0.0],[105.1,31.7,92.3,129.7,-10.2,0.0,0.0],[104.3,26.4,92.2,130.7,-11.3,0.0,0.0],[101.7,26.7,92.0,131.5,-12.3,0.0,0.0],[99.1,26.9,92.0,132.2,-13.2,0.0,0.0],[97.9,27.4,92.0,132.8,-14.1,0.0,0.0],[96.5,30.6,92.0,133.2,-14.6,0.0,0.0],[96.5,33.5,92.0,133.6,-15.1,0.0,0.0],[95.1,35.6,92.0,133.7,-15.3,0.0,0.0],[94.3,36.4,92.0,133.8,-15.3,0.0,0.0]]},"blocked_rest":{"n":134,"loop":true,"scrub":false,"events":{},"role":"rest","state":"blocked","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[94.2,32.8,92.0,133.8,-15.3,0.0,0.0],[94.1,32.9,92.0,133.8,-15.3,0.0,0.0],[94.2,32.9,92.0,133.8,-15.3,0.0,0.0],[94.2,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.2,0.0,0.0],[94.3,32.8,92.0,133.6,-15.2,0.0,0.0],[94.3,32.6,92.0,133.4,-15.2,0.0,0.0],[94.4,32.3,92.0,133.1,-15.1,0.0,0.0],[94.5,31.9,92.0,132.7,-15.0,0.0,0.0],[94.6,31.3,92.0,131.9,-14.7,0.0,0.0],[94.7,30.6,91.9,131.2,-14.5,0.0,0.0],[95.0,29.8,91.9,130.1,-13.9,0.0,0.0],[95.4,28.8,92.0,129.0,-13.6,0.0,0.0],[95.8,27.9,92.0,127.8,-13.2,0.0,0.0],[96.1,26.8,91.9,126.3,-12.7,0.0,0.0],[96.8,25.9,91.9,124.8,-12.2,0.0,0.0],[97.6,24.9,92.0,123.3,-11.7,0.0,0.0],[98.2,24.1,92.1,121.8,-11.2,0.0,0.0],[99.1,23.3,92.2,120.2,-10.6,0.0,0.0],[99.9,22.7,92.2,118.6,-10.0,0.0,0.0],[101.0,22.2,92.3,117.1,-9.5,0.0,0.0],[102.2,21.8,92.5,115.6,-8.9,0.0,0.0],[103.2,21.5,92.7,114.3,-8.4,0.0,0.0],[103.9,21.2,92.8,113.0,-8.0,0.0,0.0],[104.5,21.1,93.0,111.9,-7.6,0.0,0.0],[104.0,21.1,93.1,111.0,-7.2,0.0,0.0],[103.7,21.1,93.2,110.1,-6.8,0.0,0.0],[103.7,21.1,93.3,109.4,-6.8,0.0,0.0],[103.6,21.2,93.5,108.8,-6.4,0.0,0.0],[103.6,21.3,93.5,108.4,-6.2,0.0,0.0],[102.9,21.4,93.5,108.1,-6.2,0.0,0.0],[103.1,21.4,93.6,108.0,-6.1,0.0,0.0],[103.3,21.5,93.6,107.8,-6.1,0.0,0.0],[103.1,21.5,93.6,107.8,-5.9,0.0,0.0],[103.0,21.4,93.6,107.8,-5.9,0.0,0.0],[103.0,21.4,93.6,107.8,-6.1,0.0,0.0],[102.8,21.3,93.6,108.0,-6.1,0.0,0.0],[103.5,21.4,93.6,108.2,-6.2,0.0,0.0],[103.5,21.6,93.5,108.6,-6.2,0.0,0.0],[103.5,22.0,93.4,109.3,-6.5,0.0,0.0],[103.4,22.5,93.3,110.2,-6.8,0.0,0.0],[103.4,23.1,93.2,111.3,-7.2,0.0,0.0],[103.7,24.0,93.0,112.8,-7.6,0.0,0.0],[103.7,25.0,92.8,114.5,-8.1,0.0,0.0],[103.9,26.2,92.7,116.5,-8.8,0.0,0.0],[103.3,27.6,92.6,118.8,-9.4,0.0,0.0],[101.6,29.2,92.5,121.2,-10.2,0.0,0.0],[100.7,31.0,92.4,123.9,-10.9,0.0,0.0],[99.3,33.0,92.4,126.7,-12.0,0.0,0.0],[98.2,35.4,92.5,129.7,-12.8,0.0,0.0],[97.2,37.9,92.5,132.6,-13.8,0.0,0.0],[96.5,40.7,92.7,135.6,-14.8,0.0,0.0],[97.5,43.6,93.0,138.6,-15.6,0.0,0.0],[98.0,46.6,93.2,141.4,-16.5,0.0,0.0],[97.5,49.5,93.5,144.1,-17.4,0.0,0.0],[97.8,52.3,93.8,146.6,-18.3,0.0,0.0],[98.3,55.0,94.2,148.9,-18.9,0.0,0.0],[99.7,57.4,94.4,150.9,-19.6,0.0,0.0],[99.4,59.6,94.7,152.6,-20.2,0.0,0.0],[99.7,61.4,94.9,153.9,-20.6,0.0,0.0],[100.0,62.8,95.2,155.0,-21.0,0.0,0.0],[100.2,63.9,95.2,155.8,-21.2,0.0,0.0],[100.6,64.6,95.3,156.3,-21.4,0.0,0.0],[100.9,64.9,95.4,156.6,-21.5,0.0,0.0],[100.9,65.0,95.4,156.7,-21.5,0.0,0.0],[101.0,64.9,95.4,156.7,-21.7,0.0,0.0],[101.0,64.8,95.4,156.7,-21.7,0.0,0.0],[100.5,64.7,95.4,156.7,-21.7,0.0,0.0],[100.4,64.7,95.4,156.7,-21.7,0.0,0.0],[100.4,64.7,95.4,156.7,-21.7,0.0,0.0],[100.3,64.7,95.4,156.7,-21.7,0.0,0.0],[100.3,64.7,95.4,156.7,-21.7,0.0,0.0],[100.2,64.7,95.4,156.7,-21.7,0.0,0.0],[100.4,64.8,95.4,156.7,-21.7,0.0,0.0],[100.2,64.8,95.4,156.7,-21.7,0.0,0.0],[100.3,64.8,95.4,156.7,-21.7,0.0,0.0],[100.3,64.8,95.4,156.7,-21.7,0.0,0.0],[100.3,64.8,95.4,156.7,-21.7,0.0,0.0],[100.2,64.8,95.4,156.7,-21.7,0.0,0.0],[100.4,64.8,95.4,156.7,-21.7,0.0,0.0],[100.3,64.8,95.4,156.7,-21.6,0.0,0.0],[99.0,64.9,94.8,156.7,-22.2,0.0,0.0],[96.4,65.4,93.3,156.7,-23.5,0.0,0.0],[93.1,66.1,91.2,156.8,-25.4,0.0,0.0],[88.7,66.7,89.0,156.8,-27.2,0.0,0.0],[85.3,66.9,87.5,156.7,-28.7,0.0,0.0],[83.7,66.0,86.8,156.4,-29.1,0.0,0.0],[84.3,64.4,86.8,155.9,-29.2,0.0,0.0],[84.7,62.3,87.6,155.2,-28.2,0.0,0.0],[89.1,59.5,90.1,154.1,-25.7,0.0,0.0],[96.8,56.8,94.1,153.0,-21.7,0.0,0.0],[104.3,55.1,98.2,152.1,-17.5,0.0,0.0],[111.4,53.7,101.3,151.3,-14.1,0.0,0.0],[113.6,52.4,102.8,150.5,-12.4,0.0,0.0],[111.4,51.7,102.8,149.5,-11.9,0.0,0.0],[113.9,51.1,102.4,148.3,-11.9,0.0,0.0],[113.6,50.5,101.2,147.1,-12.8,0.0,0.0],[111.2,49.8,99.2,145.8,-14.4,0.0,0.0],[107.0,48.8,97.0,144.6,-16.5,0.0,0.0],[102.6,47.2,95.1,143.4,-18.2,0.0,0.0],[99.0,45.0,94.1,142.4,-18.9,0.0,0.0],[96.6,42.5,93.8,141.4,-19.1,0.0,0.0],[94.6,40.1,93.8,140.5,-18.9,0.0,0.0],[92.7,38.0,93.7,139.6,-18.7,0.0,0.0],[95.0,36.2,93.5,138.7,-18.5,0.0,0.0],[94.9,34.7,93.3,137.8,-18.0,0.0,0.0],[95.8,33.6,93.0,136.8,-17.4,0.0,0.0],[96.3,32.8,92.8,136.0,-17.0,0.0,0.0],[95.8,32.3,92.6,135.2,-16.4,0.0,0.0],[95.7,32.1,92.3,134.7,-16.0,0.0,0.0],[96.3,32.2,92.2,134.2,-15.6,0.0,0.0],[95.9,32.5,92.1,133.9,-15.4,0.0,0.0],[94.6,32.8,92.1,133.8,-15.4,0.0,0.0],[94.5,33.1,92.0,133.8,-15.3,0.0,0.0],[95.1,33.4,92.0,133.8,-15.3,0.0,0.0],[95.3,33.5,92.0,133.8,-15.3,0.0,0.0],[95.3,33.5,92.0,133.8,-15.3,0.0,0.0],[95.1,33.4,92.0,133.8,-15.3,0.0,0.0],[94.9,33.2,92.0,133.8,-15.3,0.0,0.0],[94.7,33.1,92.0,133.8,-15.3,0.0,0.0],[94.5,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.8,92.0,133.8,-15.3,0.0,0.0],[94.2,32.8,92.0,133.8,-15.3,0.0,0.0],[94.2,32.7,92.0,133.8,-15.3,0.0,0.0],[94.1,32.7,92.0,133.8,-15.3,0.0,0.0],[94.0,32.8,92.0,133.8,-15.3,0.0,0.0],[94.0,32.8,92.0,133.8,-15.3,0.0,0.0]]},"blocked_try":{"n":77,"loop":false,"scrub":false,"events":{"bonk":24},"role":"beat","state":"blocked","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.4,32.4,92.0,133.1,-15.1,0.0,0.0],[94.9,30.8,92.0,130.8,-14.1,0.0,0.01],[96.0,28.0,92.1,126.6,-12.7,0.0,0.03],[97.9,24.3,92.4,120.7,-10.6,0.0,0.05],[100.5,20.2,93.2,113.7,-8.3,0.0,0.08],[104.1,16.5,94.2,106.3,-5.9,0.0,0.11],[108.6,14.2,95.5,99.8,-3.6,0.0,0.14],[111.3,13.9,96.9,94.4,-2.1,0.0,0.17],[112.0,15.2,98.0,90.7,-0.9,0.0,0.19],[106.0,15.0,98.8,88.7,-0.2,0.0,0.2],[107.4,16.3,99.0,88.0,0.0,0.0,0.2],[110.0,31.6,99.0,102.3,0.0,0.0,0.16],[112.3,61.4,99.0,126.7,0.0,0.0,0.08],[112.7,68.0,99.0,134.7,0.0,0.0,0.06],[112.5,69.1,99.0,134.7,0.0,0.0,0.06],[111.8,70.4,98.9,134.4,-0.1,0.0,0.06],[115.2,66.8,98.8,133.5,-0.3,0.0,0.05],[117.0,63.5,98.7,132.2,-0.4,0.0,0.05],[117.1,59.8,98.5,130.4,-0.5,0.0,0.04],[118.3,55.5,98.3,128.6,-0.7,0.0,0.03],[121.3,47.7,98.2,126.7,-0.9,0.0,0.02],[122.4,41.4,97.8,125.0,-1.2,0.0,0.01],[121.0,37.5,97.6,123.9,-1.6,0.0,0.01],[116.6,35.8,97.2,123.3,-1.9,0.0,0.0],[114.9,35.7,97.0,123.3,-2.5,0.0,0.0],[113.8,36.6,96.5,123.6,-3.0,0.0,0.0],[113.1,37.6,96.2,124.0,-3.4,0.0,0.0],[114.4,38.4,95.9,124.5,-4.1,0.0,0.0],[113.1,38.7,95.6,125.0,-4.7,0.0,0.0],[111.8,38.4,95.2,125.5,-5.3,0.0,0.0],[110.5,37.7,94.9,126.1,-6.0,0.0,0.0],[109.5,36.6,94.6,126.7,-6.6,0.0,0.0],[108.7,35.4,94.2,127.3,-7.4,0.0,0.0],[107.4,34.3,94.0,127.9,-8.1,0.0,0.0],[106.2,33.5,93.7,128.5,-8.7,0.0,0.0],[104.7,33.0,93.5,129.1,-9.4,0.0,0.0],[103.3,32.9,93.2,129.7,-10.2,0.0,0.0],[102.0,33.0,93.0,130.2,-10.9,0.0,0.0],[100.6,33.2,92.9,130.8,-11.6,0.0,0.0],[99.4,33.3,92.7,131.2,-12.1,0.0,0.0],[98.3,33.4,92.6,131.8,-12.7,0.0,0.0],[97.4,33.4,92.5,132.2,-13.2,0.0,0.0],[96.8,33.4,92.3,132.5,-13.7,0.0,0.0],[96.1,33.2,92.3,132.8,-14.1,0.0,0.0],[95.6,33.0,92.2,133.1,-14.5,0.0,0.0],[95.1,32.8,92.2,133.3,-14.8,0.0,0.0],[94.8,32.7,92.2,133.5,-15.1,0.0,0.0],[94.6,32.6,92.1,133.6,-15.1,0.0,0.0],[94.3,32.6,92.1,133.7,-15.4,0.0,0.0],[94.2,32.7,92.1,133.8,-15.2,0.0,0.0],[94.1,32.7,92.0,133.8,-15.3,0.0,0.0],[94.1,32.8,92.0,133.8,-15.3,0.0,0.0],[94.2,32.8,92.0,133.8,-15.3,0.0,0.0],[94.1,32.9,92.0,133.8,-15.3,0.0,0.0],[94.1,32.9,92.0,133.8,-15.3,0.0,0.0],[94.2,32.9,92.0,133.8,-15.3,0.0,0.0],[94.2,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0],[94.3,32.9,92.0,133.8,-15.3,0.0,0.0]]},"compacting_in":{"n":19,"loop":false,"scrub":false,"events":{},"role":"enter","state":"compacting","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.6,96.2,120.7,-0.1,0.0,0.0],[118.8,30.3,96.3,114.5,-0.3,0.0,-0.0],[118.9,26.8,96.3,112.6,-0.3,0.0,-0.0],[119.8,25.2,96.5,112.5,-0.1,0.0,-0.01],[119.8,24.9,96.8,112.8,-0.1,0.0,-0.02],[119.1,26.6,97.1,113.8,-0.1,0.0,-0.03],[118.9,31.6,97.3,116.5,-0.1,0.0,-0.04],[117.1,40.4,97.7,121.3,-0.1,0.0,-0.06],[115.9,52.2,98.0,127.8,0.0,0.0,-0.07],[114.3,65.8,98.3,135.1,0.0,0.0,-0.09],[113.2,79.5,98.5,142.4,0.0,0.0,-0.1],[112.9,91.4,98.8,148.8,0.0,0.0,-0.11],[113.3,100.3,98.9,153.4,0.0,0.0,-0.12],[112.9,105.6,99.0,155.9,0.0,0.0,-0.12],[112.2,107.6,99.0,156.7,0.0,0.0,-0.12],[112.4,107.5,99.0,156.6,0.0,0.0,-0.12],[112.6,105.7,99.0,155.8,0.0,0.0,-0.12],[112.9,102.5,99.0,154.2,0.0,0.0,-0.12],[112.8,99.3,99.0,152.8,0.0,0.0,-0.12]]},"compacting_rest":{"n":86,"loop":true,"scrub":false,"events":{},"role":"rest","state":"compacting","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[113.9,97.8,99.0,152.3,0.0,0.0,-0.12],[113.5,97.9,99.8,152.4,-0.1,0.0,-0.12],[112.7,98.0,100.5,152.4,-0.1,0.0,-0.12],[112.0,98.1,101.0,152.4,-0.1,0.0,-0.12],[111.7,98.2,101.5,152.4,-0.1,0.0,-0.12],[111.1,98.2,101.7,152.4,-0.1,0.0,-0.12],[110.6,98.2,101.6,152.4,-0.1,0.0,-0.12],[110.6,98.2,101.4,152.4,-0.1,0.0,-0.12],[111.1,98.2,101.0,152.4,-0.1,0.0,-0.12],[111.6,98.2,100.3,152.4,-0.1,0.0,-0.12],[111.8,98.1,99.6,152.3,0.0,0.0,-0.12],[112.7,98.1,98.8,152.3,0.0,0.0,-0.12],[113.3,98.0,98.1,152.4,0.1,0.0,-0.12],[113.9,97.9,97.5,152.4,0.1,0.0,-0.12],[114.3,97.8,96.8,152.4,0.1,0.0,-0.12],[115.1,97.8,96.5,152.4,0.1,0.0,-0.12],[115.3,97.7,96.3,152.4,0.1,0.0,-0.12],[115.3,97.7,96.4,152.4,0.1,0.0,-0.12],[115.3,97.7,96.7,152.4,0.1,0.0,-0.12],[115.1,97.7,97.2,152.4,0.1,0.0,-0.12],[114.8,97.8,97.8,152.4,0.1,0.0,-0.12],[114.1,97.8,98.5,152.3,0.0,0.0,-0.12],[113.7,97.9,99.3,152.3,0.0,0.0,-0.12],[113.1,98.0,100.0,152.4,-0.1,0.0,-0.12],[112.5,98.1,100.8,152.4,-0.1,0.0,-0.12],[111.6,98.1,101.2,152.4,-0.1,0.0,-0.12],[111.5,98.2,101.5,152.4,-0.1,0.0,-0.12],[111.1,98.2,101.7,152.4,-0.1,0.0,-0.12],[110.7,98.0,101.5,152.2,-0.1,0.0,-0.12],[110.6,97.4,101.2,151.9,-0.1,0.0,-0.12],[110.8,96.4,100.7,151.2,-0.1,0.0,-0.12],[110.9,94.9,100.0,150.4,-0.1,0.0,-0.12],[111.4,93.1,99.3,149.5,0.0,0.0,-0.12],[112.0,91.1,98.5,148.5,0.0,0.0,-0.12],[113.2,89.2,97.8,147.6,0.1,0.0,-0.12],[113.9,87.5,97.2,146.8,0.1,0.0,-0.12],[114.8,86.2,96.8,146.2,0.0,0.0,-0.12],[115.3,85.5,96.5,145.9,0.1,0.0,-0.12],[115.9,85.2,96.5,145.9,0.1,0.0,-0.12],[116.1,85.2,96.6,145.9,0.1,0.0,-0.12],[115.9,85.7,97.0,146.1,0.0,0.0,-0.12],[115.2,86.9,97.4,146.7,0.0,0.0,-0.12],[114.8,89.0,98.2,147.8,0.0,0.0,-0.12],[114.4,91.8,98.8,149.3,0.0,0.0,-0.12],[113.3,95.1,99.6,151.1,-0.1,0.0,-0.12],[112.8,98.6,100.3,152.9,0.0,0.0,-0.12],[112.4,101.9,101.0,154.6,-0.1,0.0,-0.12],[112.1,104.6,101.4,156.1,-0.1,0.0,-0.12],[111.7,106.6,101.7,157.1,-0.2,0.0,-0.12],[111.5,107.7,101.8,157.6,-0.2,0.0,-0.12],[111.9,108.1,101.5,157.8,-0.2,0.0,-0.12],[112.0,108.1,101.2,157.8,-0.1,0.0,-0.12],[112.1,107.9,100.5,157.8,-0.1,0.0,-0.12],[112.5,107.6,99.8,157.7,0.0,0.0,-0.12],[113.1,107.3,99.0,157.6,0.0,0.0,-0.12],[113.8,106.9,98.2,157.5,0.0,0.0,-0.12],[114.4,106.5,97.5,157.4,0.1,0.0,-0.12],[114.8,106.0,96.9,157.1,0.1,0.0,-0.12],[115.1,105.5,96.5,156.8,0.1,0.0,-0.12],[115.4,104.9,96.2,156.4,0.2,0.0,-0.12],[115.5,104.3,96.3,156.1,0.1,0.0,-0.12],[115.4,103.6,96.5,155.6,0.1,0.0,-0.12],[115.1,102.9,97.0,155.2,0.1,0.0,-0.12],[114.9,102.2,97.7,154.8,0.0,0.0,-0.12],[114.5,101.5,98.4,154.4,0.0,0.0,-0.12],[114.0,100.8,99.2,154.0,0.0,0.0,-0.12],[113.2,100.2,99.9,153.6,0.0,0.0,-0.12],[112.6,99.7,100.6,153.2,-0.1,0.0,-0.12],[112.1,99.2,101.2,152.9,-0.1,0.0,-0.12],[111.7,98.9,101.5,152.8,-0.1,0.0,-0.12],[111.2,98.6,101.7,152.6,-0.1,0.0,-0.12],[111.0,98.4,101.6,152.4,-0.1,0.0,-0.12],[111.0,98.3,101.3,152.4,-0.1,0.0,-0.12],[111.2,98.2,100.8,152.4,-0.1,0.0,-0.12],[111.4,98.1,100.2,152.4,-0.1,0.0,-0.12],[112.2,98.1,99.5,152.3,0.0,0.0,-0.12],[112.6,98.0,98.7,152.3,0.0,0.0,-0.12],[113.4,98.0,98.0,152.4,0.1,0.0,-0.12],[114.0,97.9,97.2,152.4,0.1,0.0,-0.12],[114.5,97.8,96.8,152.4,0.1,0.0,-0.12],[115.1,97.8,96.5,152.4,0.1,0.0,-0.12],[115.3,97.7,96.3,152.4,0.1,0.0,-0.12],[115.3,97.7,96.5,152.4,0.1,0.0,-0.12],[115.3,97.7,96.8,152.4,0.1,0.0,-0.12],[115.1,97.7,97.2,152.4,0.1,0.0,-0.12],[114.8,97.8,98.0,152.4,0.1,0.0,-0.12]]},"compact_out":{"n":19,"loop":false,"scrub":false,"events":{},"role":"react","state":"compacting","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[113.3,97.6,99.0,152.3,0.0,0.0,-0.12],[111.3,67.6,99.0,131.5,0.0,0.0,-0.05],[114.5,38.9,98.9,114.7,0.0,0.0,0.01],[115.6,16.5,98.9,101.7,0.0,0.0,0.06],[115.3,-0.6,98.8,92.6,0.0,0.0,0.09],[117.1,-20.5,98.8,87.2,-0.2,0.0,0.11],[115.6,-28.0,98.6,85.5,-0.2,0.0,0.12],[114.9,-25.8,98.4,87.0,-0.2,0.0,0.12],[115.1,-14.3,98.2,94.0,-0.2,0.0,0.09],[116.4,5.0,98.0,105.8,-0.1,0.0,0.06],[120.7,24.5,97.6,117.5,0.0,0.0,0.03],[120.7,37.1,97.3,124.8,-0.1,0.0,0.0],[119.0,49.4,97.1,126.3,-0.1,0.0,0.0],[121.9,49.6,96.8,126.5,-0.1,0.0,0.0],[122.7,49.1,96.5,125.9,0.0,0.0,0.0],[122.1,47.8,96.4,124.7,-0.1,0.0,0.0],[120.4,46.1,96.3,123.2,-0.1,0.0,0.0],[120.3,41.9,96.2,121.8,-0.1,0.0,0.0],[122.0,36.1,96.2,121.0,-0.1,0.0,0.0]]},"waiting_rest":{"n":106,"loop":true,"scrub":false,"events":{},"role":"rest","state":"waiting","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.0,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.6,96.3,120.7,-0.1,0.0,0.0],[119.9,37.5,96.6,120.5,-0.1,0.0,0.0],[119.8,37.4,96.7,120.5,-0.1,0.0,0.0],[119.2,37.3,96.8,120.3,-0.1,0.0,0.0],[119.0,37.2,96.9,120.3,-0.1,0.0,0.0],[119.0,37.1,97.1,120.2,-0.1,0.0,0.0],[119.1,36.9,97.2,120.2,-0.1,0.0,0.0],[119.1,36.8,97.2,120.1,0.0,0.0,0.0],[118.9,36.7,97.3,120.0,-0.1,0.0,0.0],[118.9,36.6,97.4,120.0,-0.1,0.0,0.0],[118.9,36.5,97.6,119.8,0.0,0.0,0.0],[118.9,36.5,97.8,119.5,0.0,0.0,0.0],[118.6,36.7,98.2,118.8,-0.1,0.0,0.0],[117.4,37.2,98.7,118.0,0.0,0.0,0.0],[116.1,38.0,99.3,116.9,0.0,0.0,0.0],[114.4,39.3,100.0,115.7,0.0,0.0,0.0],[111.8,41.0,100.6,114.5,0.1,0.0,0.0],[110.7,42.4,101.1,113.3,0.3,0.0,0.0],[110.0,43.6,101.6,112.3,0.4,0.0,0.0],[107.3,44.8,101.8,111.6,0.6,0.0,0.0],[105.6,46.0,102.1,111.0,0.6,0.0,0.0],[105.2,46.8,102.2,110.7,0.6,0.0,0.0],[105.1,47.4,102.2,110.5,0.7,0.0,0.0],[104.9,47.6,102.2,110.5,0.7,0.0,0.0],[105.0,47.5,102.1,110.5,0.6,0.0,0.0],[105.1,47.3,102.1,110.5,0.6,0.0,0.0],[105.2,47.0,102.1,110.5,0.6,0.0,0.0],[105.2,46.7,102.0,110.5,0.6,0.0,0.0],[105.4,46.5,101.9,110.5,0.6,0.0,0.0],[105.4,46.4,101.9,110.5,0.6,0.0,0.0],[105.6,46.4,101.8,110.5,0.7,0.0,0.0],[105.5,46.4,101.8,110.5,0.7,0.0,0.0],[105.6,46.5,101.8,110.6,0.6,0.0,0.0],[105.6,46.6,101.7,110.6,0.6,0.0,0.0],[105.6,46.8,101.7,110.7,0.6,0.0,0.0],[105.5,46.9,101.6,110.7,0.6,0.0,0.0],[105.6,47.1,101.6,110.8,0.7,0.0,0.0],[105.6,47.2,101.5,110.8,0.6,0.0,0.0],[105.7,47.3,101.5,110.8,0.6,0.0,0.0],[105.8,47.4,101.5,110.9,0.6,0.0,0.0],[105.7,47.4,101.5,111.0,0.6,0.0,0.0],[105.8,47.5,101.5,111.0,0.6,0.0,0.0],[105.9,47.6,101.4,111.1,0.6,0.0,0.0],[105.9,47.7,101.4,111.2,0.6,0.0,0.0],[105.8,47.8,101.4,111.2,0.6,0.0,0.0],[105.9,47.9,101.4,111.3,0.6,0.0,0.0],[105.9,48.0,101.4,111.4,0.6,0.0,0.0],[106.0,48.2,101.4,111.4,0.4,0.0,0.0],[106.0,48.3,101.3,111.6,0.6,0.0,0.0],[106.3,48.0,101.2,112.2,0.4,0.0,0.0],[106.9,47.3,100.8,113.2,0.3,0.0,0.0],[107.7,46.3,100.0,114.9,0.0,0.0,0.0],[109.4,45.2,99.1,117.0,0.0,0.0,0.0],[112.6,44.5,98.1,119.3,-0.1,0.0,0.0],[112.4,44.3,97.3,121.5,-0.1,0.0,0.0],[116.1,43.2,96.8,123.2,-0.1,0.0,0.0],[121.9,42.9,96.6,124.5,0.0,0.0,0.0],[126.3,43.3,96.7,125.5,0.0,0.0,0.0],[126.4,44.5,96.8,126.6,0.0,0.0,0.0],[126.3,46.2,96.9,127.7,0.0,0.0,0.0],[124.7,48.1,97.1,128.8,0.0,0.0,0.0],[124.6,50.1,97.1,129.9,0.1,0.0,0.0],[124.5,52.0,97.2,130.9,0.1,0.0,0.0],[121.4,53.8,97.3,131.9,0.1,0.0,0.0],[119.8,55.3,97.3,132.6,0.1,0.0,0.0],[118.4,56.5,97.4,133.4,0.1,0.0,0.0],[118.5,57.3,97.4,133.9,0.1,0.0,0.0],[119.8,57.8,97.4,134.4,0.3,0.0,0.0],[120.3,58.1,97.3,134.7,0.3,0.0,0.0],[120.7,58.2,97.3,134.9,0.3,0.0,0.0],[121.4,58.2,97.2,135.0,0.3,0.0,0.0],[122.9,58.1,97.1,135.1,0.1,0.0,0.0],[123.3,58.0,97.0,135.0,0.3,0.0,0.0],[123.2,57.5,96.8,134.6,0.3,0.0,0.0],[124.0,56.3,96.6,133.6,0.1,0.0,0.0],[123.7,54.5,96.3,132.2,0.1,0.0,0.0],[123.6,52.0,96.0,130.4,0.1,0.0,0.0],[122.6,49.3,95.8,128.4,0.0,0.0,0.0],[122.7,46.4,95.5,126.4,0.0,0.0,0.0],[121.6,43.8,95.2,124.7,-0.1,0.0,0.0],[121.3,41.6,95.1,123.2,-0.1,0.0,0.0],[120.6,40.2,95.0,122.4,-0.3,0.0,0.0],[120.6,39.4,94.8,122.0,-0.3,0.0,0.0],[120.5,39.3,94.8,121.9,-0.3,0.0,0.0],[120.6,39.3,94.8,121.9,-0.3,0.0,0.0],[120.6,39.5,94.8,121.9,-0.3,0.0,0.0],[120.5,39.7,94.8,121.8,-0.3,0.0,0.0],[120.7,39.8,94.8,121.8,-0.3,0.0,0.0],[120.9,39.8,94.8,121.8,-0.1,0.0,0.0],[120.9,39.7,94.8,121.7,-0.3,0.0,0.0],[121.0,39.6,94.8,121.7,-0.3,0.0,0.0],[121.1,39.4,94.8,121.6,-0.3,0.0,0.0],[121.1,39.2,94.8,121.6,-0.3,0.0,0.0],[121.2,39.0,94.9,121.5,-0.3,0.0,0.0],[120.6,38.9,95.0,121.5,-0.1,0.0,0.0],[120.7,38.8,95.1,121.4,-0.3,0.0,0.0],[120.7,38.7,95.2,121.3,-0.3,0.0,0.0],[120.2,38.7,95.2,121.2,-0.1,0.0,0.0],[120.2,38.6,95.3,121.2,-0.3,0.0,0.0],[120.2,38.5,95.6,121.1,-0.3,0.0,0.0],[120.2,38.4,95.7,121.0,-0.1,0.0,0.0],[120.2,38.3,95.8,121.0,-0.1,0.0,0.0],[120.2,38.2,95.8,120.9,-0.3,0.0,0.0],[120.2,38.0,96.1,120.8,-0.1,0.0,0.0],[120.3,37.9,96.2,120.8,-0.1,0.0,0.0]]},"waiting_tap":{"n":62,"loop":false,"scrub":false,"events":{},"role":"beat","state":"waiting","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.5,96.2,120.5,-0.1,0.0,0.0],[120.1,37.3,96.2,120.5,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.1,36.8,96.2,120.2,-0.1,0.0,0.0],[120.1,36.6,96.2,120.0,-0.1,0.0,0.0],[120.1,36.3,96.2,120.0,-0.1,0.0,0.0],[120.0,36.1,96.2,119.8,-0.1,0.0,0.0],[120.1,35.9,96.2,119.8,-0.1,0.0,0.0],[120.1,35.7,96.2,119.7,-0.1,0.0,0.0],[120.1,35.3,96.2,120.5,-0.1,0.0,0.0],[120.4,34.6,95.9,122.2,-0.1,0.0,0.0],[123.7,33.7,95.8,123.7,-0.1,0.0,0.0],[125.2,32.7,95.7,124.5,-0.1,0.0,0.0],[125.3,31.8,95.7,125.0,0.0,0.0,0.0],[125.4,31.1,95.7,124.8,-0.1,0.0,0.0],[125.4,31.0,95.9,122.7,-0.1,0.0,0.0],[125.6,31.8,96.2,120.2,-0.1,0.0,0.0],[125.4,32.6,96.2,119.5,-0.1,0.0,0.0],[125.4,33.0,95.9,122.0,-0.1,0.0,0.0],[123.9,33.6,95.8,124.0,-0.1,0.0,0.0],[123.6,33.8,95.7,125.0,-0.1,0.0,0.0],[125.3,33.5,95.7,125.2,0.0,0.0,0.0],[125.3,33.1,95.8,123.5,-0.1,0.0,0.0],[125.5,33.5,96.2,121.0,-0.1,0.0,0.0],[125.5,34.2,96.2,120.0,-0.1,0.0,0.0],[125.4,34.4,96.0,122.2,-0.1,0.0,0.0],[125.4,34.6,95.8,124.2,-0.1,0.0,0.0],[125.4,34.6,95.7,125.5,-0.1,0.0,0.0],[125.2,34.4,95.7,126.0,-0.1,0.0,0.0],[125.3,34.2,95.8,124.8,-0.1,0.0,0.0],[125.4,34.6,96.0,122.2,-0.1,0.0,0.0],[125.5,35.5,96.2,120.8,-0.1,0.0,0.0],[125.4,36.0,96.0,122.5,-0.1,0.0,0.0],[125.1,36.4,95.8,124.8,-0.1,0.0,0.0],[124.8,36.6,95.7,126.2,-0.1,0.0,0.0],[125.2,36.5,95.7,126.8,-0.1,0.0,0.0],[125.2,36.2,95.7,126.2,-0.1,0.0,0.0],[125.4,36.3,96.0,123.5,-0.1,0.0,0.0],[125.5,37.1,96.2,121.8,-0.1,0.0,0.0],[125.4,37.5,96.1,122.8,-0.1,0.0,0.0],[125.3,37.8,95.8,125.1,0.0,0.0,0.0],[124.7,37.9,95.8,126.7,0.0,0.0,0.0],[125.2,37.7,95.7,127.4,0.0,0.0,0.0],[125.2,37.3,95.7,127.0,0.0,0.0,0.0],[125.3,37.1,96.0,124.6,0.0,0.0,0.0],[125.4,37.7,96.2,122.3,-0.1,0.0,0.0],[125.4,38.3,96.2,122.0,-0.1,0.0,0.0],[125.5,39.1,96.2,122.0,-0.1,0.0,0.0],[120.9,39.9,96.2,122.0,-0.1,0.0,0.0],[118.6,40.5,96.2,121.8,-0.1,0.0,0.0],[117.2,40.9,96.2,121.8,-0.1,0.0,0.0],[116.5,41.0,96.2,121.8,-0.1,0.0,0.0],[116.8,40.8,96.2,121.8,-0.1,0.0,0.0],[117.5,40.4,96.2,121.7,-0.1,0.0,0.0],[118.6,39.9,96.2,121.5,-0.1,0.0,0.0],[119.5,39.4,96.2,121.5,-0.1,0.0,0.0],[120.3,38.9,96.2,121.3,-0.1,0.0,0.0],[120.7,38.6,96.2,121.2,-0.1,0.0,0.0],[121.0,38.3,96.2,121.2,-0.1,0.0,0.0],[121.2,38.0,96.2,121.0,-0.1,0.0,0.0],[120.8,37.8,96.2,120.8,-0.1,0.0,0.0]]},"dizzy":{"n":115,"loop":false,"scrub":false,"events":{},"role":"once","state":"dizzy","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[113.1,41.7,99.0,118.4,0.0,0.0,0.0],[112.2,43.1,107.0,118.4,0.9,0.0,0.0],[110.2,43.6,112.8,118.5,1.9,0.0,0.0],[106.4,44.3,115.8,118.7,2.5,0.0,0.0],[102.3,44.0,116.3,118.7,2.6,0.0,0.0],[98.8,43.0,114.7,118.6,2.2,0.0,0.0],[96.3,42.9,110.8,118.5,1.4,0.0,0.0],[94.9,43.5,105.2,118.4,0.6,0.0,0.0],[97.3,43.3,98.5,118.4,0.0,0.0,0.0],[103.8,42.9,92.6,118.5,-0.7,0.0,0.0],[116.7,41.3,88.2,118.5,-1.3,0.0,0.0],[131.7,37.3,85.8,118.5,-1.7,0.0,0.0],[131.1,35.3,85.4,118.5,-1.9,0.0,0.0],[126.4,35.1,87.0,118.5,-1.5,0.0,0.0],[125.3,36.4,90.2,118.4,-1.1,0.0,0.0],[123.6,38.6,94.7,118.4,-0.6,0.0,0.0],[120.8,41.7,99.7,118.3,0.1,0.0,0.0],[115.7,43.2,104.2,118.4,0.6,0.0,0.0],[110.0,44.4,107.4,118.4,1.0,0.0,0.0],[104.9,44.1,109.2,118.5,1.2,0.0,0.0],[99.7,43.0,109.5,118.5,1.2,0.0,0.0],[97.2,42.7,108.2,118.4,1.1,0.0,0.0],[96.0,43.2,105.5,118.5,0.7,0.0,0.0],[97.5,43.4,102.0,118.4,0.3,0.0,0.0],[101.2,42.8,98.3,118.3,-0.1,0.0,0.0],[111.7,41.6,94.9,118.3,-0.4,0.0,0.0],[122.6,39.2,92.4,118.5,-0.7,0.0,0.0],[132.0,37.2,91.1,118.4,-0.9,0.0,0.0],[132.3,36.4,91.0,118.4,-0.9,0.0,0.0],[131.0,36.8,92.1,118.5,-0.7,0.0,0.0],[128.0,38.1,94.2,118.4,-0.6,0.0,0.0],[122.1,40.0,96.8,118.4,-0.3,0.0,0.0],[116.7,42.3,99.7,118.3,0.1,0.0,0.0],[114.3,43.2,102.2,118.4,0.3,0.0,0.0],[110.7,43.8,104.1,118.4,0.6,0.0,0.0],[107.3,43.9,105.0,118.4,0.6,0.0,0.0],[104.5,43.5,105.0,118.4,0.6,0.0,0.0],[102.7,43.5,104.1,118.4,0.6,0.0,0.0],[102.8,43.3,102.5,118.3,0.4,0.0,0.0],[104.3,42.8,100.5,118.3,0.1,0.0,0.0],[107.8,41.9,98.3,118.3,-0.1,0.0,0.0],[115.0,40.7,96.4,118.4,-0.3,0.0,0.0],[120.3,39.6,95.1,118.3,-0.4,0.0,0.0],[124.4,38.7,94.4,118.4,-0.6,0.0,0.0],[126.4,38.5,94.5,118.4,-0.6,0.0,0.0],[125.6,38.9,95.2,118.3,-0.4,0.0,0.0],[122.7,39.7,96.4,118.4,-0.3,0.0,0.0],[118.7,40.9,98.0,118.3,-0.1,0.0,0.0],[115.4,42.1,99.6,118.3,0.1,0.0,0.0],[113.1,42.9,101.0,118.4,0.3,0.0,0.0],[111.1,43.2,102.0,118.4,0.3,0.0,0.0],[109.3,43.3,102.5,118.3,0.4,0.0,0.0],[107.6,43.3,102.5,118.4,0.3,0.0,0.0],[107.0,43.2,101.8,118.4,0.3,0.0,0.0],[107.2,42.7,100.9,118.3,0.1,0.0,0.0],[108.2,42.2,99.7,118.3,0.1,0.0,0.0],[111.3,41.5,98.5,118.4,0.0,0.0,0.0],[115.0,40.9,97.4,118.3,-0.1,0.0,0.0],[118.4,40.3,96.7,118.4,-0.3,0.0,0.0],[120.2,39.9,96.3,118.4,-0.3,0.0,0.0],[121.1,39.9,96.4,118.4,-0.3,0.0,0.0],[119.8,40.1,96.9,118.4,-0.3,0.0,0.0],[118.4,40.6,97.7,118.3,-0.1,0.0,0.0],[116.9,41.3,98.5,118.4,0.0,0.0,0.0],[114.5,41.9,99.5,118.4,0.0,0.0,0.0],[112.8,42.4,100.2,118.3,0.1,0.0,0.0],[111.3,42.7,100.8,118.3,0.1,0.0,0.0],[110.5,42.8,101.0,118.4,0.3,0.0,0.0],[109.7,42.7,100.9,118.4,0.3,0.0,0.0],[109.4,42.5,100.6,118.3,0.1,0.0,0.0],[109.5,42.2,100.0,118.3,0.1,0.0,0.0],[110.8,41.9,99.3,118.4,0.0,0.0,0.0],[112.6,41.5,98.7,118.4,0.0,0.0,0.0],[114.8,41.1,98.0,118.3,-0.1,0.0,0.0],[116.0,40.8,97.7,118.3,-0.1,0.0,0.0],[117.1,40.6,97.5,118.3,-0.1,0.0,0.0],[117.2,40.6,97.6,118.3,-0.1,0.0,0.0],[115.1,40.8,101.3,120.7,-0.3,0.0,0.0],[118.5,39.6,108.5,120.7,-0.4,0.0,0.0],[109.2,39.9,93.9,120.7,0.0,0.0,0.0],[108.1,39.2,88.2,120.7,0.0,0.0,0.0],[122.0,37.4,100.0,120.7,-0.3,0.0,0.0],[127.6,36.5,104.5,120.7,-0.3,0.0,0.0],[120.1,37.3,95.2,120.7,0.0,0.0,0.0],[118.6,37.5,92.2,120.7,0.0,0.0,0.0],[124.6,36.9,98.5,120.7,-0.1,0.0,0.0],[124.5,37.0,100.2,120.7,-0.3,0.0,0.0],[119.9,37.7,96.7,120.7,-0.1,0.0,0.0],[118.9,38.0,96.4,120.7,-0.1,0.0,0.0],[117.9,38.2,96.2,120.7,-0.1,0.0,0.0],[118.2,38.2,96.2,120.7,-0.1,0.0,0.0],[119.0,38.1,96.2,120.7,-0.1,0.0,0.0],[119.2,38.0,96.2,120.7,-0.1,0.0,0.0],[120.0,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.5,37.6,96.2,120.7,-0.1,0.0,0.0],[120.5,37.6,96.2,120.7,-0.1,0.0,0.0],[120.5,37.6,96.2,120.7,-0.1,0.0,0.0],[120.5,37.6,96.2,120.7,-0.1,0.0,0.0],[120.3,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0],[120.2,37.7,96.2,120.7,-0.1,0.0,0.0]]},"sleep_in":{"n":67,"loop":false,"scrub":false,"events":{},"role":"enter","state":"sleep","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.6,96.2,120.5,-0.1,0.0,0.0],[120.1,37.0,96.3,119.8,-0.1,0.0,0.0],[120.1,35.4,96.4,118.2,-0.1,0.0,0.01],[119.8,32.9,96.5,115.5,-0.1,0.0,0.02],[119.8,29.4,96.7,112.0,-0.1,0.0,0.03],[118.4,25.4,96.9,107.6,-0.3,0.0,0.04],[116.6,21.0,97.2,102.8,-0.3,0.0,0.06],[114.8,17.0,97.4,98.0,-0.3,0.0,0.07],[113.7,12.2,97.5,93.4,-0.5,0.0,0.09],[110.6,8.1,97.7,89.6,-0.3,0.0,0.1],[109.4,5.2,97.8,86.7,-0.5,0.0,0.11],[109.6,3.7,97.9,84.7,-0.3,0.0,0.12],[109.8,3.2,97.9,83.7,-0.3,0.0,0.12],[109.8,3.3,97.9,83.4,-0.5,0.0,0.12],[109.7,3.8,97.9,83.4,-0.5,0.0,0.12],[109.6,4.2,97.9,83.4,-0.5,0.0,0.12],[109.4,4.5,97.9,83.4,-0.5,0.0,0.12],[109.3,4.6,97.9,83.4,-0.5,0.0,0.12],[109.3,4.5,97.9,83.4,-0.5,0.0,0.12],[109.2,4.3,97.9,83.4,-0.5,0.0,0.12],[109.2,4.0,97.9,83.4,-0.5,0.0,0.12],[109.1,3.6,97.9,83.4,-0.5,0.0,0.12],[109.3,3.4,97.9,83.4,-0.5,0.0,0.12],[109.1,3.5,97.9,83.4,-0.5,0.0,0.12],[110.6,17.3,97.6,101.2,-0.1,0.0,0.12],[110.1,31.4,97.3,114.2,-0.3,0.0,0.12],[113.4,41.1,97.2,123.0,-0.1,0.0,0.11],[116.0,48.8,97.1,128.2,0.0,0.0,0.1],[123.4,52.5,97.0,131.0,0.0,0.0,0.08],[122.3,54.9,97.1,132.1,-0.1,0.0,0.06],[123.3,55.0,97.2,132.5,0.0,0.0,0.03],[123.5,54.2,97.2,132.9,0.0,0.0,-0.01],[124.9,52.7,97.2,134.1,-0.1,0.0,-0.06],[126.5,52.7,97.2,136.9,0.0,0.0,-0.12],[127.9,54.3,97.3,140.4,0.0,0.0,-0.19],[128.5,57.7,97.3,144.3,0.0,0.0,-0.26],[125.8,62.4,97.4,148.6,0.1,0.0,-0.34],[122.9,67.8,97.5,153.4,0.1,0.0,-0.43],[123.3,73.4,97.5,158.4,0.0,0.0,-0.53],[124.7,79.0,97.6,163.8,0.1,0.0,-0.63],[124.7,84.5,97.7,169.4,0.1,0.0,-0.74],[124.3,89.8,97.7,175.1,0.3,0.0,-0.86],[125.1,95.0,97.8,181.1,0.1,0.0,-0.97],[125.2,100.0,97.9,187.1,0.3,0.0,-1.09],[125.3,105.0,97.9,193.2,0.3,0.0,-1.22],[126.5,110.0,98.1,199.4,0.1,0.0,-1.34],[126.7,115.0,98.2,205.4,0.3,0.0,-1.46],[126.7,120.2,98.2,211.4,0.1,0.0,-1.58],[126.6,125.4,98.3,217.2,0.3,0.0,-1.7],[126.5,130.5,98.3,222.9,0.1,0.0,-1.81],[126.3,135.4,98.5,228.2,0.1,0.0,-1.92],[126.1,140.1,98.5,233.4,0.1,0.0,-2.03],[126.0,144.5,98.6,238.1,0.1,0.0,-2.13],[125.9,148.5,98.7,242.6,0.1,0.0,-2.22],[125.8,152.0,98.7,246.8,0.1,0.0,-2.3],[125.8,155.2,98.8,250.4,0.1,0.0,-2.38],[125.8,157.9,98.8,253.8,0.1,0.0,-2.45],[125.8,160.3,98.8,256.6,0.0,0.0,-2.51],[125.8,162.3,98.9,259.0,0.0,0.0,-2.56],[125.8,164.0,98.9,261.0,0.0,0.0,-2.6],[125.8,165.3,99.0,262.6,0.0,0.0,-2.63],[125.7,166.4,99.0,263.9,0.0,0.0,-2.66],[125.7,167.1,99.0,264.7,0.0,0.0,-2.68],[125.7,167.6,99.0,265.3,0.0,0.0,-2.69],[125.7,167.8,99.0,265.6,0.0,0.0,-2.7],[125.7,167.9,99.0,265.8,0.0,0.0,-2.7]]},"sleep_rest":{"n":96,"loop":true,"scrub":false,"events":{},"role":"rest","state":"sleep","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[125.9,167.6,99.0,265.8,0.0,0.0,-2.7],[125.9,167.0,99.0,265.3,0.0,0.0,-2.7],[125.9,166.4,99.0,264.9,0.0,0.0,-2.69],[125.9,165.8,99.0,264.4,0.0,0.0,-2.69],[125.9,165.1,99.0,263.9,0.0,0.0,-2.68],[125.9,164.5,99.0,263.5,0.0,0.0,-2.68],[125.9,163.9,99.0,263.1,0.0,0.0,-2.67],[125.9,163.3,99.0,262.6,0.0,0.0,-2.67],[125.9,162.8,99.0,262.2,0.0,0.0,-2.67],[126.0,162.2,99.0,261.8,0.0,0.0,-2.66],[126.0,161.7,99.0,261.4,0.0,0.0,-2.66],[126.0,161.2,99.0,261.1,0.0,0.0,-2.65],[126.0,160.7,99.0,260.7,0.0,0.0,-2.65],[126.0,160.3,99.0,260.4,0.0,0.0,-2.65],[126.0,159.9,99.0,260.1,0.0,0.0,-2.64],[126.0,159.5,99.0,259.8,0.0,0.0,-2.64],[126.0,159.1,99.0,259.6,0.0,0.0,-2.64],[126.0,158.8,99.0,259.4,0.0,0.0,-2.64],[126.0,158.6,99.0,259.2,0.0,0.0,-2.64],[126.0,158.3,99.0,259.0,0.0,0.0,-2.63],[126.0,158.2,99.0,258.9,0.0,0.0,-2.63],[126.0,158.0,99.0,258.8,0.0,0.0,-2.63],[126.0,157.9,99.0,258.7,0.0,0.0,-2.63],[126.0,157.8,99.0,258.7,0.0,0.0,-2.63],[126.0,157.8,99.0,258.6,0.0,0.0,-2.63],[126.0,157.8,99.0,258.7,0.0,0.0,-2.63],[126.0,157.9,99.0,258.7,0.0,0.0,-2.63],[126.0,158.0,99.0,258.8,0.0,0.0,-2.63],[126.0,158.2,99.0,258.9,0.0,0.0,-2.63],[126.0,158.3,99.0,259.0,0.0,0.0,-2.63],[126.0,158.6,99.0,259.2,0.0,0.0,-2.64],[126.0,158.8,99.0,259.4,0.0,0.0,-2.64],[126.0,159.1,99.0,259.6,0.0,0.0,-2.64],[126.0,159.5,99.0,259.8,0.0,0.0,-2.64],[126.0,159.9,99.0,260.1,0.0,0.0,-2.64],[126.0,160.3,99.0,260.4,0.0,0.0,-2.65],[126.0,160.7,99.0,260.7,0.0,0.0,-2.65],[126.0,161.2,99.0,261.1,0.0,0.0,-2.65],[126.0,161.7,99.0,261.4,0.0,0.0,-2.66],[126.0,162.2,99.0,261.8,0.0,0.0,-2.66],[126.0,162.7,99.0,262.2,0.0,0.0,-2.67],[125.9,163.3,99.0,262.6,0.0,0.0,-2.67],[125.9,163.9,99.0,263.1,0.0,0.0,-2.67],[125.9,164.5,99.0,263.5,0.0,0.0,-2.68],[125.9,165.1,99.0,263.9,0.0,0.0,-2.68],[125.9,165.7,99.0,264.4,0.0,0.0,-2.69],[125.9,166.4,99.0,264.9,0.0,0.0,-2.69],[125.9,167.0,99.0,265.3,0.0,0.0,-2.7],[125.9,167.6,99.0,265.8,0.0,0.0,-2.7],[125.9,168.3,99.0,266.3,0.0,0.0,-2.7],[125.9,168.9,99.0,266.7,0.0,0.0,-2.71],[125.9,169.6,99.0,267.2,0.0,0.0,-2.71],[125.9,170.2,99.0,267.7,0.0,0.0,-2.72],[125.8,170.8,99.0,268.1,0.0,0.0,-2.72],[125.8,171.4,99.0,268.5,0.0,0.0,-2.73],[125.8,172.0,99.0,269.0,0.0,0.0,-2.73],[125.8,172.5,99.0,269.4,0.0,0.0,-2.74],[125.8,173.1,99.0,269.8,0.0,0.0,-2.74],[125.8,173.6,99.0,270.2,0.0,0.0,-2.74],[125.8,174.1,99.0,270.5,0.0,0.0,-2.75],[125.8,174.6,99.0,270.9,0.0,0.0,-2.75],[125.8,175.0,99.0,271.2,0.0,0.0,-2.75],[125.8,175.4,99.0,271.5,0.0,0.0,-2.76],[125.8,175.8,99.0,271.8,0.0,0.0,-2.76],[125.8,176.1,99.0,272.0,0.0,0.0,-2.76],[125.8,176.4,99.0,272.2,0.0,0.0,-2.76],[125.8,176.6,99.0,272.4,0.0,0.0,-2.76],[125.2,173.7,99.0,267.8,0.0,0.0,-2.68],[125.4,172.9,99.0,267.3,0.0,0.0,-2.67],[125.7,172.5,99.0,267.5,0.0,0.0,-2.67],[126.1,172.9,99.0,268.7,0.0,0.0,-2.69],[126.4,174.2,99.0,270.7,0.0,0.0,-2.73],[126.4,175.6,99.0,272.4,0.0,0.0,-2.76],[126.2,176.6,99.0,273.0,0.0,0.0,-2.77],[125.8,177.3,99.0,272.9,0.0,0.0,-2.77],[125.5,177.7,99.0,272.8,0.0,0.0,-2.77],[125.4,177.9,99.0,272.7,0.0,0.0,-2.77],[125.4,177.7,99.0,272.6,0.0,0.0,-2.77],[125.5,177.3,99.0,272.4,0.0,0.0,-2.76],[125.6,176.7,99.0,272.2,0.0,0.0,-2.76],[125.8,176.2,99.0,272.0,0.0,0.0,-2.76],[125.9,175.6,99.0,271.8,0.0,0.0,-2.76],[125.9,175.1,99.0,271.5,0.0,0.0,-2.76],[125.9,174.7,99.0,271.2,0.0,0.0,-2.75],[125.9,174.4,99.0,270.9,0.0,0.0,-2.75],[125.9,174.0,99.0,270.5,0.0,0.0,-2.75],[125.8,173.6,99.0,270.2,0.0,0.0,-2.74],[125.8,173.2,99.0,269.8,0.0,0.0,-2.74],[125.8,172.7,99.0,269.4,0.0,0.0,-2.74],[125.8,172.1,99.0,269.0,0.0,0.0,-2.73],[125.8,171.5,99.0,268.5,0.0,0.0,-2.73],[125.8,170.9,99.0,268.1,0.0,0.0,-2.72],[125.8,170.2,99.0,267.7,0.0,0.0,-2.72],[125.9,169.5,99.0,267.2,0.0,0.0,-2.71],[125.9,168.9,99.0,266.7,0.0,0.0,-2.71],[125.9,168.3,99.0,266.3,0.0,0.0,-2.7]]},"sleep_twitch":{"n":58,"loop":false,"scrub":false,"events":{},"role":"beat","state":"sleep","anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[125.9,167.6,99.0,265.8,0.0,0.0,-2.7],[125.8,167.2,99.0,265.4,0.0,0.0,-2.7],[125.8,166.6,99.0,265.1,0.0,0.0,-2.7],[125.8,165.9,99.0,264.7,0.0,0.0,-2.7],[125.8,165.2,99.0,264.4,0.0,0.0,-2.7],[125.9,164.5,99.0,264.0,0.0,0.0,-2.7],[126.0,163.8,99.0,263.7,0.0,0.0,-2.7],[126.0,163.1,99.0,263.5,0.0,0.0,-2.7],[127.1,161.8,99.0,263.2,0.0,0.0,-2.7],[127.8,160.6,99.0,263.0,0.0,0.0,-2.7],[128.1,159.7,99.0,262.8,0.0,0.0,-2.7],[128.4,159.2,99.0,262.6,0.0,0.0,-2.7],[128.6,158.8,99.0,262.5,0.0,0.0,-2.7],[129.0,158.5,99.0,262.4,0.0,0.0,-2.7],[129.1,158.4,99.0,262.4,0.0,0.0,-2.7],[129.1,158.4,99.0,262.4,0.0,0.0,-2.7],[129.1,158.4,99.0,262.5,0.0,0.0,-2.7],[129.1,158.5,99.0,262.5,0.0,0.0,-2.7],[129.2,158.8,99.0,262.7,0.0,0.0,-2.7],[129.2,159.1,99.0,262.8,0.0,0.0,-2.7],[129.2,159.5,99.0,263.0,0.0,0.0,-2.7],[128.9,160.1,99.0,263.2,0.0,0.0,-2.7],[128.2,161.1,99.0,263.5,0.0,0.0,-2.7],[127.7,162.4,99.0,263.8,0.0,0.0,-2.7],[126.9,163.7,99.0,264.1,0.0,0.0,-2.7],[126.2,164.9,99.0,264.4,0.0,0.0,-2.7],[126.0,165.7,99.0,264.8,0.0,0.0,-2.7],[125.9,166.4,99.0,265.1,0.0,0.0,-2.7],[125.9,167.1,99.0,265.5,0.0,0.0,-2.7],[125.9,167.8,99.0,265.9,0.0,0.0,-2.7],[125.9,168.5,99.0,266.2,0.0,0.0,-2.7],[125.9,169.2,99.0,266.6,0.0,0.0,-2.7],[125.8,169.8,99.0,267.0,0.0,0.0,-2.7],[125.8,170.5,99.0,267.3,0.0,0.0,-2.7],[125.8,171.1,99.0,267.6,0.0,0.0,-2.7],[125.8,171.7,99.0,267.9,0.0,0.0,-2.7],[125.8,172.2,99.0,268.2,0.0,0.0,-2.7],[125.8,172.6,99.0,268.4,0.0,0.0,-2.7],[125.8,173.0,99.0,268.7,0.0,0.0,-2.7],[125.8,173.4,99.0,268.8,0.0,0.0,-2.7],[125.7,173.7,99.0,269.0,0.0,0.0,-2.7],[125.7,173.9,99.0,269.1,0.0,0.0,-2.7],[125.7,174.0,99.0,269.2,0.0,0.0,-2.7],[125.7,174.1,99.0,269.2,0.0,0.0,-2.7],[125.7,174.0,99.0,269.2,0.0,0.0,-2.7],[125.7,173.9,99.0,269.1,0.0,0.0,-2.7],[125.7,173.8,99.0,269.0,0.0,0.0,-2.7],[125.8,173.5,99.0,268.9,0.0,0.0,-2.7],[125.8,173.2,99.0,268.7,0.0,0.0,-2.7],[125.8,172.8,99.0,268.5,0.0,0.0,-2.7],[125.8,172.4,99.0,268.3,0.0,0.0,-2.7],[125.8,171.9,99.0,268.0,0.0,0.0,-2.7],[125.8,171.4,99.0,267.7,0.0,0.0,-2.7],[125.8,170.8,99.0,267.4,0.0,0.0,-2.7],[125.8,170.1,99.0,267.1,0.0,0.0,-2.7],[125.8,169.5,99.0,266.7,0.0,0.0,-2.7],[125.8,168.8,99.0,266.4,0.0,0.0,-2.7],[125.9,168.1,99.0,266.0,0.0,0.0,-2.7]]},"popup":{"n":43,"loop":false,"scrub":false,"events":{"land":12},"role":"react","state":null,"anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[126.9,239.0,96.2,343.1,2.4,0.0,-4.2],[121.1,189.3,96.3,283.5,1.7,0.0,-3.19],[119.8,139.1,96.4,232.3,1.1,0.0,-2.3],[119.2,96.8,96.4,189.1,0.6,0.0,-1.55],[119.3,62.9,96.5,153.8,0.1,0.0,-0.92],[122.6,30.3,96.5,125.8,-0.2,0.0,-0.42],[117.5,6.5,96.6,105.2,-0.5,0.0,-0.05],[115.1,-4.8,96.7,91.7,-0.6,0.0,0.19],[113.6,-10.7,96.7,85.3,-0.6,0.0,0.31],[113.4,-8.5,96.6,86.5,-0.6,0.0,0.31],[114.7,7.0,96.6,97.2,-0.4,0.0,0.24],[117.0,36.5,96.4,117.7,-0.3,0.0,0.1],[116.0,56.3,96.3,131.9,-0.1,0.0,0.0],[113.9,54.4,96.3,125.7,-0.3,0.0,0.0],[118.6,44.0,96.5,120.0,-0.3,0.0,0.0],[119.6,43.4,96.5,119.8,-0.1,0.0,0.0],[119.5,43.6,96.5,119.8,-0.1,0.0,0.0],[116.8,44.2,96.5,119.8,-0.1,0.0,0.0],[118.6,39.6,96.5,119.8,-0.1,0.0,0.0],[119.8,34.7,96.5,119.8,-0.1,0.0,0.0],[118.9,34.4,96.5,119.8,-0.1,0.0,0.0],[118.9,34.4,96.5,119.8,-0.1,0.0,0.0],[119.1,34.2,96.5,119.8,-0.1,0.0,0.0],[119.1,36.4,96.5,119.8,-0.1,0.0,0.0],[119.5,38.7,96.5,119.8,-0.1,0.0,0.0],[102.5,43.7,99.2,119.7,0.0,0.0,0.0],[103.9,44.8,99.5,119.7,0.0,0.0,0.0],[108.8,44.9,99.5,119.7,0.0,0.0,0.0],[111.1,44.2,99.5,119.7,0.0,0.0,0.0],[114.7,41.2,99.5,119.7,0.0,0.0,0.0],[119.3,38.6,99.5,119.7,0.0,0.0,0.0],[121.3,36.9,99.5,119.7,0.0,0.0,0.0],[123.8,36.1,99.5,119.8,0.1,0.0,0.0],[123.5,36.0,99.5,119.8,0.1,0.0,0.0],[122.4,36.4,99.3,119.8,0.0,0.0,0.0],[121.7,36.9,99.0,119.9,0.0,0.0,0.0],[120.6,37.3,98.6,120.0,0.0,0.0,0.0],[119.9,37.6,98.1,120.2,-0.1,0.0,0.0],[119.7,37.7,97.6,120.3,0.0,0.0,0.0],[118.9,37.7,97.1,120.5,-0.1,0.0,0.0],[119.8,37.7,96.7,120.5,-0.1,0.0,0.0],[120.5,37.7,96.4,120.7,-0.1,0.0,0.0],[119.3,37.9,96.2,120.7,-0.1,0.0,0.0]]},"poke":{"n":36,"loop":false,"scrub":false,"events":{},"role":"react","state":null,"anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[119.9,38.3,96.2,120.7,-0.1,0.0,0.0],[116.4,71.8,96.0,140.1,0.0,-0.04,0.0],[117.7,58.7,96.2,131.8,0.0,-0.07,0.0],[120.3,38.3,96.3,118.3,-0.1,-0.09,0.0],[122.8,23.3,96.5,110.9,-0.3,-0.1,0.0],[122.5,20.1,96.5,109.1,-0.3,-0.1,0.0],[122.6,15.1,96.5,109.1,-0.3,-0.1,0.0],[122.5,10.2,96.4,109.3,-0.2,-0.1,0.0],[123.0,9.1,96.4,109.8,-0.3,-0.1,0.0],[122.9,10.5,96.5,110.5,-0.2,-0.09,0.0],[123.4,12.0,96.4,111.5,-0.1,-0.09,0.0],[123.0,16.2,96.4,112.7,-0.3,-0.08,0.0],[122.6,21.0,96.4,114.0,-0.1,-0.07,0.0],[122.2,25.4,96.3,115.2,-0.3,-0.06,0.0],[121.9,28.9,96.3,116.3,-0.1,-0.05,0.0],[121.8,31.1,96.3,117.3,-0.3,-0.04,0.0],[121.7,32.2,96.3,118.0,-0.1,-0.03,0.0],[122.2,32.3,96.3,118.5,-0.1,-0.03,0.0],[121.9,32.0,96.3,118.7,-0.1,-0.02,0.0],[122.2,31.4,96.2,118.7,-0.1,-0.01,0.0],[122.2,30.9,96.3,118.7,-0.1,-0.01,0.0],[122.1,30.8,96.2,118.6,-0.3,-0.0,0.0],[122.0,31.1,96.2,118.7,-0.1,-0.0,0.0],[121.8,31.7,96.2,118.8,-0.1,-0.0,0.0],[121.4,32.5,96.2,118.8,-0.1,0.0,0.0],[121.5,33.3,96.2,119.0,-0.1,0.0,0.0],[120.9,34.2,96.2,119.2,-0.1,0.0,0.0],[120.4,35.0,96.2,119.5,-0.1,0.0,0.0],[120.2,35.7,96.2,119.8,-0.1,0.0,0.0],[120.2,36.3,96.2,120.0,-0.1,0.0,0.0],[120.1,36.7,96.2,120.2,-0.1,0.0,0.0],[120.1,37.1,96.2,120.3,-0.1,0.0,0.0],[120.2,37.4,96.2,120.5,-0.3,0.0,0.0],[120.2,37.6,96.2,120.6,-0.3,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0],[120.1,37.7,96.2,120.7,-0.1,0.0,0.0]]},"pet":{"n":43,"loop":false,"scrub":false,"events":{},"role":"react","state":null,"anchors":["hairX","hairY","faceX","faceY","roll","press","rise"],"frames":[[120.1,37.8,96.2,120.7,-0.1,0.0,0.0],[120.3,38.0,97.2,120.8,-0.1,0.01,0.0],[121.5,39.2,101.5,121.3,0.0,0.03,0.0],[121.6,41.3,107.3,122.2,0.4,0.06,0.0],[116.8,44.2,111.5,122.9,1.1,0.09,0.0],[108.9,47.3,112.8,123.2,1.2,0.1,0.0],[104.1,49.4,112.8,123.2,1.2,0.1,0.0],[100.9,49.9,112.2,123.2,1.2,0.1,0.0],[99.0,49.8,110.9,123.1,1.0,0.1,0.0],[98.6,49.4,109.2,122.9,0.9,0.1,0.0],[100.0,48.7,107.5,122.6,0.8,0.1,0.0],[102.5,47.7,106.4,122.2,0.7,0.09,0.0],[106.2,46.2,106.2,121.8,0.6,0.09,0.0],[109.1,44.6,106.2,121.2,0.7,0.08,0.0],[111.5,42.6,107.1,120.7,0.9,0.08,0.0],[113.4,40.9,108.6,120.1,1.0,0.07,0.0],[112.9,39.8,110.1,119.3,1.2,0.07,0.0],[110.5,39.0,110.8,118.5,1.4,0.06,0.0],[107.9,38.5,110.7,117.8,1.4,0.05,0.0],[105.2,37.7,110.2,117.0,1.4,0.04,0.0],[103.1,36.6,108.8,116.2,1.2,0.04,0.0],[102.6,35.2,106.8,115.4,0.9,0.03,0.0],[102.9,34.1,104.8,114.7,0.7,0.02,0.0],[105.2,32.7,103.5,114.0,0.7,0.02,0.0],[108.0,31.3,103.0,113.5,0.6,0.01,0.0],[110.2,30.1,102.8,113.1,0.4,0.01,0.0],[113.0,28.8,102.3,112.7,0.4,0.01,0.0],[115.5,27.9,101.5,112.4,0.3,0.0,0.0],[116.8,27.3,100.5,112.2,0.3,0.0,0.0],[116.9,27.0,99.6,112.1,0.0,0.0,0.0],[116.9,26.9,99.1,112.1,0.0,0.0,0.0],[116.9,26.9,99.0,112.1,0.0,0.0,0.0],[116.9,27.1,99.0,112.1,0.0,0.0,0.0],[116.8,27.5,98.9,112.3,0.0,0.0,0.0],[116.4,28.3,98.8,112.8,0.0,0.0,0.0],[115.4,29.5,98.5,113.6,0.0,0.0,0.0],[115.3,30.9,98.2,114.8,-0.1,0.0,0.0],[115.3,32.5,97.8,116.0,-0.1,0.0,0.0],[115.5,34.2,97.4,117.3,-0.1,0.0,0.0],[116.3,35.7,97.0,118.5,-0.1,0.0,0.0],[118.0,36.8,96.7,119.6,-0.3,0.0,0.0],[119.6,37.6,96.4,120.2,-0.1,0.0,0.0],[120.6,37.9,96.2,120.7,-0.1,0.0,0.0]]}},"beat_chance":{"idle":0.45,"listening":0.5,"thinking":0.6,"working":0.35,"subagents":0.45,"speaking":0.85,"done":0.5,"needs":0.35,"approval":0.3,"blocked":0.35,"waiting":0.4,"sleep":0.15},"w":396,"h":484,"ext":"avif","page":64}
\ No newline at end of file
diff --git a/design/noodle/renders/hero.jpg b/design/noodle/renders/hero.jpg
new file mode 100644
index 0000000..ea1f285
Binary files /dev/null and b/design/noodle/renders/hero.jpg differ
diff --git a/design/pix/pix.js b/design/pix/pix.js
new file mode 100644
index 0000000..0168af6
--- /dev/null
+++ b/design/pix/pix.js
@@ -0,0 +1,579 @@
+/* Pix: a deadpan fruit sprite that knows it is a sprite. Its moods are render settings.
+ * Two species: an apple and a banana. Each pixel is a slightly different shade of an OKLab gradient,
+ * with a one-pixel bevel and a glint. Eyes are two pixels wide (white + black): permanent side-eye.
+ *
+ * thinking its resolution drops: all its pixels go to the brain
+ * done it renders in HD for two seconds (gloss, blush, sparkles, a mouth), then back to pixels
+ * blocked "Not Responding": dragged like a frozen window, a copy every frame; each copy a bit more
+ * overripe (the apple browns, the banana gets spots)
+ * sleep the bouncing screensaver; a different variety on every wall; it celebrates a corner
+ * dizzy shake the keys: pixels scatter, it reassembles upside down (and goes green)
+ * subagents it splits into half-resolution copies of other varieties
+ * speaking an RPG dialog box types the reply out
+ * working walks in place; each tool call floats up like an RPG damage number
+ * needs you "!" over its head; it stares, and slowly leans closer to the glass
+ * compacting squashed flat under a press, JPEG'd into blocks, the file size dropping
+ * waiting rate limited: taps a foot under an hourglass, looks up at the clock, counts down
+ *
+ * PIX.draw(ctx, { species, cx, cy, px, t, state, stateT, look, voice, text, tools, subagents, screen, room, eyeMode })
+ * screen the area it may use (below the watch's status row); room max height when it leans in; bang false hides the ! in needs; eyeMode force the eyes (e.g. 'cam')
+ * draw() is a pure function of its input, so the watch port can render any frame.
+ */
+(function (root) {
+ 'use strict';
+
+ // ---------- color ----------
+ const PAL = {
+ apple: ['#FFC27A', '#FF5A4E', '#E3243F', '#8E1240'],
+ greenApple: ['#F4FFA8', '#B8F05E', '#62C93C', '#2E8A3A'],
+ golden: ['#FFF6B0', '#FFDA4A', '#FFAF1F', '#E2701A'],
+ pinkLady: ['#FFD9C8', '#FF8E8A', '#F0507A', '#A8306E'],
+ rot: ['#C8A47C', '#9A6C45', '#6E462A', '#4B2D1C'],
+ banana: ['#FFF8B8', '#FFE65C', '#FFC928', '#E39A1A'],
+ greenBanana: ['#EEFFB8', '#C2EC6E', '#86CB42', '#559C30'],
+ redBanana: ['#FFC9A8', '#F07F5E', '#C2454C', '#7E2A44'],
+ ripe: ['#FFE9A0', '#FFC94A', '#F2A42A', '#C8781E'],
+ gray: ['#D5D8DD', '#A3A9B2', '#7A828D', '#59606B'],
+ };
+ const PART = { leaf: ['#C2F57E', '#5CC94F', '#2F8F43'], stem: ['#8A5A2E', '#5A3418'], bstem: ['#A8A04A', '#5E5524'], tip: ['#5A3A20', '#3A2414'] };
+
+ const hex = h => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
+ const toLin = c => { c /= 255; return c <= .04045 ? c / 12.92 : Math.pow((c + .055) / 1.055, 2.4); };
+ const toSrgb = c => 255 * (c <= .0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - .055);
+ function oklab([r, g, b]) {
+ r = toLin(r); g = toLin(g); b = toLin(b);
+ const l = Math.cbrt(.4122214708 * r + .5363325363 * g + .0514459929 * b), m = Math.cbrt(.2119034982 * r + .6806995451 * g + .1073969566 * b), s = Math.cbrt(.0883024619 * r + .2817188376 * g + .6299787005 * b);
+ return [.2104542553 * l + .793617785 * m - .0040720468 * s, 1.9779984951 * l - 2.428592205 * m + .4505937099 * s, .0259040371 * l + .7827717662 * m - .808675766 * s];
+ }
+ function srgb([L, a, b]) {
+ const l = (L + .3963377774 * a + .2158037573 * b) ** 3, m = (L - .1055613458 * a - .0638541728 * b) ** 3, s = (L - .0894841775 * a - 1.291485548 * b) ** 3;
+ return [toSrgb(4.0767416621 * l - 3.3077115913 * m + .2309699292 * s), toSrgb(-1.2684380046 * l + 2.6097574011 * m - .3413193965 * s), toSrgb(-.0041960863 * l - .7034186147 * m + 1.707614701 * s)].map(v => Math.max(0, Math.min(255, v)));
+ }
+ const LAB = {}; for (const k in PAL) LAB[k] = PAL[k].map(h => oklab(hex(h)));
+ const PLAB = {}; for (const k in PART) PLAB[k] = PART[k].map(h => oklab(hex(h)));
+ function grad(stops, u) {
+ u = Math.max(0, Math.min(.9999, u)) * (stops.length - 1); const i = Math.floor(u), f = u - i, a = stops[i], b = stops[i + 1];
+ return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f];
+ }
+ const mix = (a, b, k) => [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k];
+ const hash = (x, y, s) => { const v = Math.sin(x * 127.1 + y * 311.7 + s * 74.7) * 43758.5453; return v - Math.floor(v); };
+ const css = (lab, a = 1) => { const c = srgb(lab); return a >= 1 ? `rgb(${c[0] | 0},${c[1] | 0},${c[2] | 0})` : `rgba(${c[0] | 0},${c[1] | 0},${c[2] | 0},${a})`; };
+ const WHITE = '#FFFFFF', INK = '#0A0A0C';
+ const clamp01 = v => Math.max(0, Math.min(1, v));
+ const ease = k => { k = clamp01(k); return k * k * (3 - 2 * k); };
+ const step = (v, n) => Math.floor(v * n) / n;
+
+ // ---------- species ----------
+ const cellsOf = rows => { const out = []; rows.forEach((r, y) => [...r].forEach((c, x) => { if (c !== '.') out.push([x, y, c]); })); return out; };
+
+ const APPLE = {
+ key: 'apple', name: 'APPLE', W: 15, H: 17,
+ rows: [
+ '...............', '...............', '...............',
+ '..XXXX...XXXX..', '.XXXXXXXXXXXXX.',
+ 'XXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXX',
+ '.XXXXXXXXXXXXX.', '.XXXXXXXXXXXXX.', '..XXXXXXXXXXX..', '...XXXXXXXXX...', '....XXX.XXX....',
+ ],
+ parts: { // S stem, L leaf
+ curl: [[8, 0, 'S'], [7, 1, 'S'], [7, 2, 'S'], [7, 3, 'S'], [10, 0, 'L'], [11, 0, 'L'], [9, 1, 'L'], [10, 1, 'L'], [11, 1, 'L'], [12, 1, 'L'], [8, 2, 'L'], [9, 2, 'L'], [10, 2, 'L']],
+ antenna: [[7, 0, 'S'], [7, 1, 'S'], [7, 2, 'S'], [7, 3, 'S'], [8, 2, 'L'], [9, 2, 'L'], [9, 1, 'L'], [10, 1, 'L'], [10, 2, 'L'], [11, 1, 'L']],
+ droop: [[7, 3, 'S'], [7, 2, 'S'], [6, 2, 'L'], [5, 2, 'L'], [4, 2, 'L'], [3, 2, 'L'], [5, 1, 'L'], [4, 1, 'L']],
+ },
+ stemKind: 'stem',
+ eyes: [4, 9], eyeY: 8, mouth: [6, 10, 3],
+ legs: {
+ stand: [[5, 15], [5, 16], [4, 16], [9, 15], [9, 16], [8, 16]],
+ stepL: [[5, 15], [4, 15], [3, 15], [9, 15], [9, 16], [8, 16]],
+ stepR: [[5, 15], [5, 16], [4, 16], [9, 15], [8, 15], [7, 15]],
+ },
+ legsHD: [[5.5, 14.6, 16.45, 4.3], [9.5, 14.6, 16.45, 8.3]],
+ shine: [[2, 5], [3, 5], [2, 6]],
+ tip: [7.5, .5], bangX: 7.5, badge: [2.2, .7],
+ base: 'apple', moods: { needs: 'golden', dizzy: 'greenApple' }, cycle: ['apple', 'greenApple', 'golden', 'pinkLady'],
+ };
+
+ const BANANA = {
+ // a ")" crescent: long tapered neck up to the stem, belly bowing right, blunt bottom with a dark nub
+ key: 'banana', name: 'BANANA', W: 15, H: 23, pxScale: 6 / 7, visW: 13, blushDX: 1.1,
+ rows: [ // rasterized from the HD outline so both versions are the same banana
+ '...............', '...XX..........', '..XXXXX........', '...XXXXXX......', '....XXXXXX.....', '....XXXXXXX....',
+ '.....XXXXXXX...', '.....XXXXXXXX..', '......XXXXXXX..', '......XXXXXXXX.', '......XXXXXXXX.', '......XXXXXXXX.',
+ '.....XXXXXXXXX.', '.....XXXXXXXX..', '.....XXXXXXXX..', '....XXXXXXXXX..', '....XXXXXXXX...', '...XXXXXXXX....',
+ '...XXXXXXX.....', '..XXXXXXX......', '..TTXXX........',
+ ],
+ parts: {
+ curl: [[3, 0, 'S'], [2, 0, 'N']],
+ antenna: [[3, 0, 'S'], [2, 0, 'N']],
+ droop: [[2, 1, 'S'], [1, 1, 'N']],
+ },
+ stemKind: 'bstem',
+ eyes: [7, 11], eyeY: 11, mouth: [8, 13, 2],
+ legs: {
+ stand: [[4, 21], [4, 22], [3, 22], [6, 21], [6, 22], [5, 22]],
+ stepL: [[4, 21], [3, 21], [2, 21], [6, 21], [6, 22], [5, 22]],
+ stepR: [[4, 21], [4, 22], [3, 22], [6, 21], [7, 21]],
+ },
+ legsHD: [[4.5, 20.6, 22.45, 3.3], [6.5, 20.6, 22.45, 5.3]],
+ shine: [[6, 6], [7, 6], [6, 7]],
+ tip: [3.5, .5], bangX: 3.5, badge: [12.6, 4.2],
+ base: 'banana', moods: { needs: 'ripe', dizzy: 'greenBanana' }, cycle: ['banana', 'greenBanana', 'redBanana', 'ripe'],
+ };
+
+ for (const sp of [APPLE, BANANA]) {
+ sp.cells = cellsOf(sp.rows);
+ sp.isBody = (x, y) => y >= 0 && y < sp.rows.length && x >= 0 && x < sp.W && sp.rows[y][x] !== '.';
+ sp.span = sp.rows.map(r => { const a = r.search(/[^.]/); if (a < 0) return null; let b = r.length - 1; while (r[b] === '.') b--; return [a, b]; });
+ }
+ const SPECIES = { apple: APPLE, banana: BANANA };
+
+ // the shade of one cell: gradient + per-pixel jitter + bevel + glint, then rot / spots
+ function shadeBody(sp, mood, x, y, boost, rot, spots) {
+ const st = LAB[mood] || LAB[sp.base], W = sp.W, H = sp.H, ch = sp.rows[y][x];
+ if (ch === 'T') { const c = grad(PLAB.tip, (x + y) / 30); return [c[0] + boost * .5, c[1], c[2]]; }
+ let c = grad(st, (x / W) * .42 + (y / H) * .58);
+ if (rot > 0) c = mix(c, grad(LAB.rot, (x / W) * .42 + (y / H) * .58), rot);
+ let L = c[0] + (hash(x, y, 3) - .5) * .035 + boost;
+ if (!sp.isBody(x + 1, y) || !sp.isBody(x, y + 1)) L -= .065;
+ else if (!sp.isBody(x - 1, y) || !sp.isBody(x, y - 1)) L += .045;
+ if (sp.shine.some(([sx, sy]) => sx === x && sy === y)) L += .12;
+ if (sp.key === 'banana' && sp.span[y] && y >= 5 && y <= 17 && x === sp.span[y][1] - 2) L -= .035; // the banana's ridge
+ c = [L, c[1], c[2]];
+ if (spots > 0 && hash(x, y, 5) < spots * .32) c = mix(c, grad(PLAB.tip, .3), .8);
+ return c;
+ }
+ function shadePart(sp, kind, x, y, boost, rot) {
+ if (kind === 'L') {
+ let c = grad(PLAB.leaf, clamp01((y + (x - 8) * .25) / 3.2));
+ if (rot > 0) c = mix(c, grad(LAB.rot, .5), rot * .8);
+ return [c[0] + boost + (hash(x, y, 9) - .5) * .03, c[1], c[2]];
+ }
+ if (kind === 'N') { const c = grad(PLAB.tip, .4); return [c[0] + boost, c[1], c[2]]; }
+ const c = grad(PLAB[sp.stemKind], y / 3); return [c[0] + boost, c[1], c[2]];
+ }
+ const MEMO = new Map();
+ function color(key, f) { let c = MEMO.get(key); if (!c) { c = css(f()); if (MEMO.size > 30000) MEMO.clear(); MEMO.set(key, c); } return c; }
+ const legColor = (sp, mood) => { const c = grad(LAB[mood] || LAB[sp.base], .9); return css([c[0] * .7, c[1] * .85, c[2] * .85]); };
+
+ // ---------- crisp cells: snap both edges to device pixels so neighbours share an edge at any scale ----------
+ function snapper(g) {
+ const m = g.getTransform(), sx = m.a || 1, sy = m.d || 1, ex = m.e, fy = m.f;
+ return (x, y, w, h) => {
+ const x0 = Math.round(x * sx + ex), x1 = Math.round((x + w) * sx + ex), y0 = Math.round(y * sy + fy), y1 = Math.round((y + h) * sy + fy);
+ if (x1 > x0 && y1 > y0) g.fillRect((x0 - ex) / sx, (y0 - fy) / sy, (x1 - x0) / sx, (y1 - y0) / sy);
+ };
+ }
+
+ // ---------- pixel font, 3 × 5 ----------
+ const FONT = {
+ A: [2, 5, 7, 5, 5], B: [6, 5, 6, 5, 6], C: [3, 4, 4, 4, 3], D: [6, 5, 5, 5, 6], E: [7, 4, 6, 4, 7], F: [7, 4, 6, 4, 4], G: [3, 4, 5, 5, 3],
+ H: [5, 5, 7, 5, 5], I: [7, 2, 2, 2, 7], J: [1, 1, 1, 5, 2], K: [5, 5, 6, 5, 5], L: [4, 4, 4, 4, 7], M: [5, 7, 7, 5, 5], N: [6, 5, 5, 5, 5],
+ O: [2, 5, 5, 5, 2], P: [6, 5, 6, 4, 4], Q: [2, 5, 5, 6, 3], R: [6, 5, 6, 5, 5], S: [3, 4, 2, 1, 6], T: [7, 2, 2, 2, 2], U: [5, 5, 5, 5, 7],
+ V: [5, 5, 5, 5, 2], W: [5, 5, 7, 7, 5], X: [5, 5, 2, 5, 5], Y: [5, 5, 2, 2, 2], Z: [7, 1, 2, 4, 7],
+ 0: [7, 5, 5, 5, 7], 1: [2, 6, 2, 2, 7], 2: [6, 1, 2, 4, 7], 3: [6, 1, 2, 1, 6], 4: [5, 5, 7, 1, 1], 5: [7, 4, 6, 1, 6], 6: [3, 4, 6, 5, 2],
+ 7: [7, 1, 2, 2, 2], 8: [2, 5, 2, 5, 2], 9: [2, 5, 3, 1, 6], '+': [0, 2, 7, 2, 0], '-': [0, 0, 7, 0, 0], '.': [0, 0, 0, 0, 2], '!': [2, 2, 2, 0, 2],
+ '?': [6, 1, 2, 0, 2], ':': [0, 2, 0, 2, 0], "'": [2, 2, 0, 0, 0], '/': [1, 1, 2, 4, 4], ',': [0, 0, 0, 2, 4], '(': [1, 2, 2, 2, 1], ')': [4, 2, 2, 2, 4], ' ': [0, 0, 0, 0, 0],
+ };
+ const textWidth = (str, s) => Math.max(0, String(str).length * 4 * s - s);
+ function text(g, str, x, y, s, col, align = 'left') {
+ str = String(str).toUpperCase();
+ let cx = align === 'center' ? x - textWidth(str, s) / 2 : align === 'right' ? x - textWidth(str, s) : x;
+ g.fillStyle = col; const R = snapper(g);
+ for (const ch of str) {
+ const gl = FONT[ch] || FONT[' '];
+ for (let r = 0; r < 5; r++) for (let c = 0; c < 3; c++) if (gl[r] & (4 >> c)) R(cx + c * s, y + r * s, s, s);
+ cx += 4 * s;
+ }
+ }
+
+ // ---------- the sprite ----------
+ // o: { sp, ox, oy, px, mood, eyes: { mode, look }, legs, dy, flip, stem, mouth, boost, rot, spots, offset(x, y) }
+ function paint(g, o) {
+ const sp = o.sp, { ox, oy, px } = o, mood = o.mood || sp.base, dy = o.dy || 0, H = sp.H;
+ const b = Math.round((o.boost || 0) * 200) / 200, rot = Math.round((o.rot || 0) * 20) / 20, spots = Math.round((o.spots || 0) * 20) / 20;
+ const Y = y => (o.flip ? H - 1 - y : y), R = snapper(g), lift = dy * (o.flip ? -1 : 1);
+ const cell = (x, y, col, lifted) => {
+ const off = o.offset ? o.offset(x, y) : [0, 0];
+ g.fillStyle = col; R(ox + (x + off[0]) * px, oy + (Y(y) + off[1] + (lifted ? lift : 0)) * px, px, px);
+ };
+ const leg = legColor(sp, mood);
+ for (const [x, y] of sp.legs[o.legs || 'stand']) cell(x, y, leg, false);
+ for (const [x, y, k] of sp.parts[o.stem || 'curl']) cell(x, y, color(`${sp.key}${k}${x},${y},${b},${rot}`, () => shadePart(sp, k, x, y, b, rot)), true);
+ for (const [x, y] of sp.cells) cell(x, y, color(`${sp.key}${mood}${x},${y},${b},${rot},${spots}`, () => shadeBody(sp, mood, x, y, b, rot, spots)), true);
+ eyes(g, o, Y);
+ if (o.mouth) {
+ const [mx, my, mw] = sp.mouth, top = oy + (Y(my) + lift) * px, h = o.mouth === 1 ? px * .45 : px;
+ g.fillStyle = INK; R(ox + mx * px, top + (px - h) / 2, px * mw, h);
+ }
+ }
+
+ function eyes(g, o, Y) {
+ const sp = o.sp, { ox, oy, px } = o, e = o.eyes || {}, mode = e.mode || 'side', look = e.look ?? 1, dy = (o.dy || 0) * (o.flip ? -1 : 1), EY = sp.eyeY;
+ if (mode === 'none') return;
+ const R = snapper(g);
+ const box = (cx, cy, col, fx = 0, fy = 0, fw = 1, fh = 1) => { g.fillStyle = col; R(ox + (cx + fx) * px, oy + (Y(cy) + dy + fy) * px, fw * px, fh * px); };
+ sp.eyes.forEach((ex, i) => {
+ if (mode === 'closed') { box(ex, EY, 'rgba(10,10,12,.82)', 0, .55, 2, .3); return; }
+ if (mode === 'happy') { box(ex, EY, WHITE, 0, 0, 2, .42); return; }
+ if (mode === 'cam') { box(ex, EY, INK, 0, 0, 2, 1); box(ex, EY, WHITE, .18, .16, .32, .32); return; }
+ if (mode === 'up') { box(ex, EY, WHITE, 0, 0, 2, 1); box(ex, EY - 1, WHITE, 0, 0, 2, 1); box(ex + (look > 0 ? 1 : 0), EY - 1, INK); return; }
+ let right = look > 0;
+ if (mode === 'cross') right = i === 0;
+ if (mode === 'squint') { box(ex, EY, right ? WHITE : INK, 0, .5, 1, .5); box(ex + 1, EY, right ? INK : WHITE, 0, .5, 1, .5); return; }
+ box(ex, EY, right ? WHITE : INK); box(ex + 1, EY, right ? INK : WHITE);
+ });
+ }
+
+ // ---------- HD: the same fruit as smooth shapes, with everything the pixels could not afford ----------
+ function smooth(g, pts) { // a closed curve through the midpoints of a point list
+ const n = pts.length, mid = (a, b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
+ const m = mid(pts[n - 1], pts[0]); g.moveTo(m[0], m[1]);
+ for (let i = 0; i < n; i++) { const p = pts[i], q = mid(pts[i], pts[(i + 1) % n]); g.quadraticCurveTo(p[0], p[1], q[0], q[1]); }
+ g.closePath();
+ }
+ const HD = {
+ apple: {
+ back(g, X, Y, px) {
+ g.strokeStyle = PART.stem[1]; g.lineWidth = px * .9;
+ g.beginPath(); g.moveTo(X(7.5), Y(4.2)); g.quadraticCurveTo(X(7.1), Y(2.0), X(8.4), Y(.5)); g.stroke();
+ const lg = g.createLinearGradient(X(8), Y(2.4), X(13), Y(.6)); lg.addColorStop(0, PART.leaf[2]); lg.addColorStop(1, PART.leaf[0]);
+ g.beginPath(); g.moveTo(X(8.2), Y(2.3)); g.quadraticCurveTo(X(9.4), Y(-.3), X(13.1), Y(.8)); g.quadraticCurveTo(X(11.6), Y(3.1), X(8.2), Y(2.3)); g.fillStyle = lg; g.fill();
+ g.beginPath(); g.moveTo(X(8.6), Y(2.1)); g.quadraticCurveTo(X(10.4), Y(1.2), X(12.4), Y(.95)); g.lineWidth = px * .16; g.strokeStyle = 'rgba(20,80,30,.55)'; g.stroke();
+ },
+ body(g, X, Y) {
+ g.beginPath(); g.moveTo(X(7.5), Y(4.1));
+ g.bezierCurveTo(X(8.6), Y(2.7), X(12.6), Y(2.4), X(14.2), Y(5.2));
+ g.bezierCurveTo(X(15.5), Y(8.2), X(14.6), Y(12.8), X(11.6), Y(14.5));
+ g.bezierCurveTo(X(10.2), Y(15.3), X(8.7), Y(14.7), X(7.5), Y(14.8));
+ g.bezierCurveTo(X(6.3), Y(14.7), X(4.8), Y(15.3), X(3.4), Y(14.5));
+ g.bezierCurveTo(X(.4), Y(12.8), X(-.5), Y(8.2), X(.8), Y(5.2));
+ g.bezierCurveTo(X(2.4), Y(2.4), X(6.4), Y(2.7), X(7.5), Y(4.1)); g.closePath();
+ },
+ front(g, X, Y, px) {
+ g.save(); g.translate(X(3.6), Y(5.8)); g.rotate(-.7); g.beginPath(); g.ellipse(0, 0, px * 1.7, px * .7, 0, 0, Math.PI * 2); g.fillStyle = 'rgba(255,255,255,.72)'; g.fill(); g.restore();
+ },
+ bounds: [-.6, 2.3, 15.6, 15.4],
+ },
+ banana: {
+ // centerline: a quadratic from the stem end (top left) bowing right to the blunt end (bottom left)
+ P: [[2.6, 1.7], [16.6, 10.6], [2.9, 20.9]],
+ at(t) {
+ const [a, b, c] = HD.banana.P, u = 1 - t;
+ const x = u * u * a[0] + 2 * u * t * b[0] + t * t * c[0], y = u * u * a[1] + 2 * u * t * b[1] + t * t * c[1];
+ const dx = 2 * u * (b[0] - a[0]) + 2 * t * (c[0] - b[0]), dy = 2 * u * (b[1] - a[1]) + 2 * t * (c[1] - b[1]), l = Math.hypot(dx, dy) || 1;
+ let w = 1.5 + 6.6 * Math.pow(Math.sin(Math.PI * Math.pow(Math.min(t, .985), 1.18)), .62);
+ if (t > .86) w = Math.max(w, 4.6 - (t - .86) * 7); // the blunt end
+ return { x, y, nx: -dy / l, ny: dx / l, w }; // n points to the concave (left) side
+ },
+ back(g, X, Y, px) {
+ g.strokeStyle = PART.bstem[1]; g.lineWidth = px * 1.0; g.lineCap = 'butt';
+ g.beginPath(); g.moveTo(X(3.0), Y(2.4)); g.quadraticCurveTo(X(2.1), Y(1.0), X(1.0), Y(.4)); g.stroke(); g.lineCap = 'round';
+ g.beginPath(); g.ellipse(X(1.0), Y(.4), px * .5, px * .55, .5, 0, Math.PI * 2); g.fillStyle = PART.tip[1]; g.fill();
+ },
+ body(g, X, Y) {
+ const N = 28, L = [], R = [];
+ for (let i = 0; i <= N; i++) { const p = HD.banana.at(i / N); L.push([X(p.x + p.nx * p.w / 2), Y(p.y + p.ny * p.w / 2)]); R.push([X(p.x - p.nx * p.w / 2), Y(p.y - p.ny * p.w / 2)]); }
+ g.beginPath(); smooth(g, [...R, ...L.reverse()]);
+ },
+ front(g, X, Y, px) {
+ const e = HD.banana.at(1);
+ g.beginPath(); g.ellipse(X(e.x), Y(e.y), px * 1.3, px * .75, Math.atan2(e.ny, e.nx), 0, Math.PI * 2); g.fillStyle = PART.tip[0]; g.fill();
+ const line = (t0, t1, off, w, col) => { g.beginPath(); for (let i = 0; i <= 20; i++) { const p = HD.banana.at(t0 + (t1 - t0) * i / 20), x = X(p.x + p.nx * p.w * off), y = Y(p.y + p.ny * p.w * off); i ? g.lineTo(x, y) : g.moveTo(x, y); } g.lineWidth = px * w; g.strokeStyle = col; g.stroke(); };
+ line(.22, .9, -.22, .2, 'rgba(160,100,0,.22)'); // the ridge on the back
+ line(.3, .62, .3, .5, 'rgba(255,255,255,.6)'); // gloss
+ },
+ bounds: [0, 0, 15, 22],
+ },
+ };
+
+ function paintHD(g, o, t) {
+ const sp = o.sp, { ox, oy, px } = o, mood = o.mood || sp.base, P = PAL[mood] || PAL[sp.base], look = o.eyes?.look ?? 1, by = o.by || 0, hd = HD[sp.key];
+ const X = c => ox + c * px, Y = r => oy + r * px + by;
+ g.save(); g.lineCap = 'round'; g.lineJoin = 'round';
+ g.strokeStyle = legColor(sp, mood); g.lineWidth = px * .78;
+ for (const [lx, y0, y1, fx] of sp.legsHD) { g.beginPath(); g.moveTo(X(lx), Y(y0)); g.lineTo(X(lx), Y(y1)); g.lineTo(X(fx), Y(y1)); g.stroke(); }
+ hd.back(g, X, Y, px);
+ const [bx0, by0, bx1, by1] = hd.bounds;
+ const lg = g.createLinearGradient(X(bx0), Y(by0), X(bx0 + (bx1 - bx0) * .9), Y(by1 * 1.02)); P.forEach((c, i) => lg.addColorStop(i / (P.length - 1), c));
+ hd.body(g, X, Y); g.fillStyle = lg; g.fill();
+ g.save(); hd.body(g, X, Y); g.clip();
+ let rg = g.createRadialGradient(X(bx0 + 3.4), Y(by0 + 2.6), 0, X(bx0 + 3.4), Y(by0 + 2.6), 9 * px); rg.addColorStop(0, 'rgba(255,255,255,.4)'); rg.addColorStop(1, 'rgba(255,255,255,0)');
+ g.fillStyle = rg; g.fillRect(X(bx0), Y(by0), (bx1 - bx0) * px, (by1 - by0) * px);
+ rg = g.createLinearGradient(0, Y(by0 + (by1 - by0) * .45), 0, Y(by1)); rg.addColorStop(0, 'rgba(60,0,40,0)'); rg.addColorStop(1, 'rgba(60,0,40,.3)');
+ g.fillStyle = rg; g.fillRect(X(bx0), Y(by0), (bx1 - bx0) * px, (by1 - by0) * px);
+ g.restore();
+ hd.body(g, X, Y); g.lineWidth = px * .14; g.strokeStyle = 'rgba(255,255,255,.35)'; g.stroke();
+ hd.front(g, X, Y, px);
+ // face
+ const ec = sp.eyes.map(ex => [ex + 1, sp.eyeY + .5]);
+ const bdx = sp.blushDX || 1.45; ec.forEach(([cx, cy], i) => { g.beginPath(); g.ellipse(X(cx + (i ? bdx : -bdx)), Y(cy + 2.0), px * 1.0, px * .48, 0, 0, Math.PI * 2); g.fillStyle = 'rgba(255,80,130,.42)'; g.fill(); });
+ for (const [cx, cy] of ec) {
+ g.beginPath(); g.ellipse(X(cx), Y(cy), px * 1.05, px * 1.3, 0, 0, Math.PI * 2); g.fillStyle = WHITE; g.fill();
+ const pxp = X(cx) + look * px * .32;
+ g.beginPath(); g.ellipse(pxp, Y(cy) + px * .12, px * .66, px * .8, 0, 0, Math.PI * 2); g.fillStyle = INK; g.fill();
+ g.beginPath(); g.arc(pxp - px * .24, Y(cy) - px * .22, px * .26, 0, Math.PI * 2); g.fillStyle = WHITE; g.fill();
+ g.beginPath(); g.arc(pxp + px * .24, Y(cy) + px * .38, px * .11, 0, Math.PI * 2); g.fill();
+ }
+ const [mx, my, mw] = sp.mouth, mcx = mx + mw / 2;
+ g.beginPath(); g.moveTo(X(mcx - .9), Y(my + .35)); g.quadraticCurveTo(X(mcx), Y(my + 1.1), X(mcx + .9), Y(my + .35)); g.lineWidth = px * .32; g.strokeStyle = INK; g.stroke();
+ // sparkles
+ const spark = (x, y, s) => { if (s <= 0) return; g.beginPath(); g.moveTo(x, y - s); g.quadraticCurveTo(x, y, x + s, y); g.quadraticCurveTo(x, y, x, y + s); g.quadraticCurveTo(x, y, x - s, y); g.quadraticCurveTo(x, y, x, y - s); g.fillStyle = WHITE; g.fill(); };
+ [[-.6, by0 + 1.5, 0], [bx1 + .2, by0 + 3, 1.3], [bx1 - .8, by0 - 1.2, 2.1], [-.2, by1 - 2.5, 3.2], [bx1 + .6, by1 - 3.5, .7]].forEach(([sx, sy, ph]) => spark(X(sx), Y(sy), px * .9 * Math.max(0, Math.sin(t * 5 + ph))));
+ // badge
+ const bx = X(sp.badge[0]), byy = Y(sp.badge[1]);
+ g.font = `800 ${px * 1.15}px ui-rounded, system-ui, sans-serif`; g.textAlign = 'center'; g.textBaseline = 'middle';
+ g.beginPath(); if (g.roundRect) g.roundRect(bx - px * 1.35, byy - px * .75, px * 2.7, px * 1.5, px * .45); else g.rect(bx - px * 1.35, byy - px * .75, px * 2.7, px * 1.5);
+ g.fillStyle = WHITE; g.fill(); g.fillStyle = INK; g.fillText('HD', bx, byy + px * .06);
+ g.restore();
+ }
+
+ // ---------- resolution: draw something, then show it at `block` pt per sample, with hard pixel edges ----------
+ const pool = {};
+ function surface(key, w, h, opts) {
+ let c = pool[key];
+ if (!c || c.width !== w || c.height !== h) {
+ c = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(w, h) : document.createElement('canvas');
+ c.width = w; c.height = h; c._ctx = c.getContext('2d', opts); pool[key] = c;
+ }
+ return c;
+ }
+ function atRes(ctx, x, y, w, h, block, draw) {
+ const s = Math.hypot(ctx.getTransform().a, ctx.getTransform().b) || 1;
+ const hi = surface('hi', Math.ceil(w * s), Math.ceil(h * s)), hg = hi._ctx;
+ hg.setTransform(1, 0, 0, 1, 0, 0); hg.clearRect(0, 0, hi.width, hi.height); hg.setTransform(s, 0, 0, s, -x * s, -y * s); draw(hg);
+ if (block * s <= 1.01) { ctx.drawImage(hi, x, y, w, h); return; }
+ const lw = Math.max(1, Math.round(w / block)), lh = Math.max(1, Math.round(h / block));
+ let src = hi, sw = hi.width, sh = hi.height, k = 0;
+ while (sw / 2 >= lw && sh / 2 >= lh) {
+ const nw = Math.max(lw, Math.round(sw / 2)), nh = Math.max(lh, Math.round(sh / 2)), c = surface('half' + (k++ % 2), nw, nh), cg = c._ctx;
+ cg.setTransform(1, 0, 0, 1, 0, 0); cg.clearRect(0, 0, nw, nh); cg.imageSmoothingEnabled = true; cg.drawImage(src, 0, 0, sw, sh, 0, 0, nw, nh);
+ src = c; sw = nw; sh = nh;
+ }
+ const lo = surface('lo', lw, lh, { willReadFrequently: true }), lg = lo._ctx;
+ lg.setTransform(1, 0, 0, 1, 0, 0); lg.clearRect(0, 0, lw, lh); lg.imageSmoothingEnabled = true; lg.imageSmoothingQuality = 'high'; lg.drawImage(src, 0, 0, sw, sh, 0, 0, lw, lh);
+ const im = lg.getImageData(0, 0, lw, lh), d = im.data;
+ for (let i = 3; i < d.length; i += 4) d[i] = d[i] > 96 ? 255 : 0;
+ lg.putImageData(im, 0, 0);
+ const was = ctx.imageSmoothingEnabled; ctx.imageSmoothingEnabled = false;
+ ctx.drawImage(lo, 0, 0, lw, lh, x, y, lw * block, lh * block);
+ ctx.imageSmoothingEnabled = was;
+ }
+
+ // ---------- states ----------
+ const blinkAt = (t, seed = 0) => ((t + seed * .7) % 3.7) < .11;
+
+ function draw(ctx, p) {
+ const sp = SPECIES[p.species] || APPLE, W = sp.W, H = sp.H;
+ const st = p.state || 'idle', T = p.stateT || 0, t = p.t || 0, px0 = Math.round((p.px || 7) * (sp.pxScale || 1));
+ const scr = p.screen || { x: 0, y: 0, w: 198, h: 242 };
+ const mood0 = p.palette || sp.moods[st] || sp.base;
+ const base = (px, cx = p.cx, cy = p.cy) => ({ sp, ox: Math.round(cx - W * px / 2), oy: Math.round(cy - H * px / 2), px, mood: mood0 });
+ const idleBob = Math.floor(t * 1.25) % 2;
+ ctx.save();
+
+ if (st === 'idle') {
+ const ph = t % 8, look = p.look ?? (ph < 2.6 ? 1 : ph < 5.2 ? -1 : 1);
+ const mode = p.eyeMode || (blinkAt(t) ? 'closed' : (ph > 5.2 && ph < 6.5) ? 'cam' : 'side');
+ paint(ctx, { ...base(px0), dy: p.eyeMode ? 0 : idleBob, eyes: { mode, look } });
+ }
+
+ else if (st === 'listening') {
+ const v = clamp01(p.voice ?? (.5 + .5 * Math.sin(t * 9) * Math.sin(t * 2.3)));
+ const px = px0 + 1, o = { ...base(px), stem: 'antenna', boost: v * .05, eyes: { mode: blinkAt(t) ? 'closed' : 'cam' } };
+ paint(ctx, o);
+ // the stem is an antenna: ((( · ))) like a broadcast icon, one arc per loudness step
+ const c = Math.max(3, Math.round(px * .5)), tipx = o.ox + sp.tip[0] * px, tipy = o.oy + sp.tip[1] * px, n = Math.ceil(v * 3);
+ ctx.fillStyle = WHITE;
+ for (let i = 0; i < n; i++) {
+ ctx.globalAlpha = 1 - i * .22;
+ const hh = i + 1;
+ for (let j = -hh; j <= hh; j++) for (const side of [-1, 1]) {
+ const dx = (2 * i + 2.2 - (Math.abs(j) === hh ? 1 : 0)) * c * side;
+ ctx.fillRect(Math.round(tipx + dx - c / 2), Math.round(tipy + j * c - c / 2), c, c);
+ }
+ }
+ ctx.globalAlpha = 1;
+ }
+
+ else if (st === 'thinking') {
+ const c = T % 4.6, block = c < .45 ? 1 : c < 1.3 ? 2 : c < 2.4 ? 3 : c < 4.0 ? 4 : 1;
+ const lk = Math.floor(T / 1.15) % 2 ? -1 : 1;
+ const o = { ...base(px0), eyes: { mode: 'up', look: lk } };
+ if (block === 1) paint(ctx, { ...o, eyes: { mode: c >= 4.0 ? 'cam' : 'up', look: lk } });
+ else { atRes(ctx, o.ox, o.oy, W * o.px, H * o.px, o.px * block, g => paint(g, { ...o, eyes: { mode: 'none' } })); eyes(ctx, o, y => y); }
+ }
+
+ else if (st === 'working') {
+ const stepI = Math.floor(T / .2), legs = stepI % 2 ? 'stepL' : 'stepR';
+ const o = { ...base(px0), legs, dy: stepI % 2, eyes: { mode: blinkAt(t) ? 'closed' : 'squint', look: 1 } };
+ paint(ctx, o);
+ const tools = (p.tools && p.tools.length ? p.tools : ['Read', 'Edit', 'Bash', 'Grep', 'Edit', 'Test']).map(s => String(s).toUpperCase());
+ const every = .75, k0 = Math.floor(T / every);
+ for (let k = Math.max(0, k0 - 2); k <= k0; k++) {
+ const age = T - k * every; if (age < 0 || age > 1.5) continue;
+ const label = '+1 ' + tools[k % tools.length], rise = step(age / 1.5, 10) * Math.max(8, Math.min(34, o.oy - 20 - scr.y));
+ const x = o.ox + W * o.px / 2 + (k % 2 ? 30 : -30), y = o.oy - 14 - rise;
+ ctx.globalAlpha = age > 1.1 ? .5 : 1;
+ text(ctx, label, x + 1, y + 1, 2, 'rgba(120,40,0,.9)', 'center'); text(ctx, label, x, y, 2, '#FFE66B', 'center');
+ }
+ ctx.globalAlpha = 1;
+ if (stepI % 4 === 1) { ctx.fillStyle = '#8FD8FF'; const sx = o.ox + W * o.px + 2, sy = o.oy + 5 * o.px; ctx.fillRect(sx, sy, 3, 3); ctx.fillRect(sx, sy + 3, 2, 2); }
+ }
+
+ else if (st === 'speaking') {
+ const msg = (p.text || 'All 14 tests pass. I also fixed a typo you made in 2019.').toUpperCase();
+ const bx = scr.x + 8, bw = scr.w - 16, bh = 82, by = scr.y + scr.h - bh - 8, cpl = Math.floor((bw - 18) / 8);
+ const lines = []; let line = '';
+ for (const w of msg.split(' ')) { if ((line + ' ' + w).trim().length > cpl) { lines.push(line.trim()); line = w; } else line += ' ' + w; }
+ if (line.trim()) lines.push(line.trim());
+ const shown = Math.floor(T * 22); let left = shown;
+ const typed = lines.map(l => { const n = Math.max(0, Math.min(l.length, left)); left -= l.length; return l.slice(0, n); });
+ const doneTyping = shown >= lines.join('').length;
+ const lastCh = (typed.filter(Boolean).pop() || ' ').slice(-1);
+ const mouth = doneTyping ? 0 : (/[AEIOU]/.test(lastCh) ? 2 : Math.floor(T * 11) % 2);
+ const px = Math.round(5 * (sp.pxScale || 1)), o = { ...base(px, scr.x + scr.w / 2, by - H * px / 2 - 8), dy: doneTyping ? idleBob : Math.floor(T * 6) % 2, mouth, eyes: { mode: blinkAt(t) ? 'closed' : 'cam' } };
+ paint(ctx, o);
+ ctx.fillStyle = '#0D0D1A'; ctx.fillRect(bx, by, bw, bh);
+ ctx.fillStyle = WHITE; ctx.fillRect(bx, by, bw, 2); ctx.fillRect(bx, by + bh - 2, bw, 2); ctx.fillRect(bx, by, 2, bh); ctx.fillRect(bx + bw - 2, by, 2, bh);
+ ctx.fillStyle = '#5B5BFF'; ctx.fillRect(bx + 4, by + 4, bw - 8, 1); ctx.fillRect(bx + 4, by + bh - 5, bw - 8, 1);
+ const tw = textWidth(sp.name, 2) + 12, ty = by - 15; ctx.fillStyle = '#0D0D1A'; ctx.fillRect(bx + 10, ty, tw, 17);
+ ctx.fillStyle = WHITE; ctx.fillRect(bx + 10, ty, tw, 2); ctx.fillRect(bx + 10, ty, 2, 17); ctx.fillRect(bx + 10 + tw - 2, ty, 2, 17);
+ text(ctx, sp.name, bx + 16, ty + 5, 2, '#FFE66B');
+ typed.slice(0, 5).forEach((l, i) => text(ctx, l, bx + 9, by + 12 + i * 13, 2, WHITE));
+ if (doneTyping && Math.floor(t * 2.5) % 2) { ctx.fillStyle = WHITE; const ax = bx + bw - 16, ay = by + bh - 14; ctx.fillRect(ax, ay, 8, 2); ctx.fillRect(ax + 2, ay + 2, 4, 2); ctx.fillRect(ax + 3, ay + 4, 2, 2); }
+ }
+
+ else if (st === 'done') {
+ const c = T % 4.2, o = { ...base(px0), mood: sp.base };
+ const up = [.14, .23, .32, .41], down = [2.55, 2.62, 2.69, 2.76], blocks = [1, .5, .25, .125];
+ const region = (g, b) => atRes(ctx, o.ox - o.px, o.oy - 3 * o.px, (W + 2) * o.px, (H + 3) * o.px, o.px * b, g);
+ if (c < .14) paint(ctx, { ...o, dy: -1, eyes: { mode: 'happy' } });
+ else if (c < .5) { const i = up.findIndex(v => c < v + .09); region(g => paintHD(g, o, t), blocks[Math.max(0, i)]); }
+ else if (c < 2.55) paintHD(ctx, { ...o, by: Math.sin((c - .5) * 3.2) * 2.2 }, t);
+ else if (c < 2.83) { const i = down.findIndex(v => c < v + .07); region(g => paintHD(g, o, t), blocks[3 - Math.max(0, i)]); }
+ else paint(ctx, { ...o, dy: idleBob, eyes: { mode: c < 3.4 ? 'happy' : 'side', look: 1 } });
+ }
+
+ else if (st === 'needs') {
+ const lean = Math.max(0, Math.min(3, Math.floor((p.room || 172) / H) - px0, Math.floor(Math.max(0, T - 1.4) / 1.4)));
+ const px = px0 + lean, hop = T < .26 ? -Math.round(Math.sin(T / .26 * Math.PI) * 2) : 0;
+ const o = { ...base(px, p.cx, p.cy + lean * 4), dy: hop, eyes: { mode: blinkAt(t, 2) && T > 1 ? 'closed' : 'cam' } };
+ paint(ctx, o);
+ if (p.bang === false) { ctx.restore(); return; }
+ const pop = T < .1 ? T / .1 : 1, bob = Math.floor(t * 2) % 2, s = Math.max(2, Math.round(px * .62 * pop));
+ const ex = o.ox + sp.bangX * px - s, ey = o.oy - 1.5 * px + hop * px - bob * 2 - 7 * s;
+ ctx.fillStyle = WHITE; ctx.fillRect(ex - s / 2, ey - s / 2, s * 3, s * 5.5); ctx.fillRect(ex - s / 2, ey + 5.5 * s, s * 3, s * 2.5);
+ ctx.fillStyle = '#FF3B30'; ctx.fillRect(ex, ey, s * 2, s * 4.5); ctx.fillRect(ex, ey + 6 * s, s * 2, s * 1.5);
+ }
+
+ else if (st === 'blocked') {
+ // dragged around like a frozen window: a stamp every frame, 15 pt apart, each one a bit more overripe
+ const c = T % 6.5, px = Math.max(3, Math.round(4 * (sp.pxScale || 1))), frames = Math.min(Math.floor(c * 9), 26);
+ const P = [[62, 96], [136, 104], [70, 160], [138, 178]].map(([x, y]) => [scr.x + x * scr.w / 198, scr.y + y * scr.h / 242]);
+ const seg = []; let tot = 0; for (let i = 1; i < P.length; i++) { const l = Math.hypot(P[i][0] - P[i - 1][0], P[i][1] - P[i - 1][1]); seg.push(l); tot += l; }
+ const path = k => { let d = Math.min(tot, k * 15); for (let i = 0; i < seg.length; i++) { if (d <= seg[i]) { const f = d / seg[i]; return [P[i][0] + (P[i + 1][0] - P[i][0]) * f, P[i][1] + (P[i + 1][1] - P[i][1]) * f]; } d -= seg[i]; } return P[P.length - 1]; };
+ for (let k = 0; k <= frames; k++) {
+ const [cx, cy] = path(k), age = k / 26;
+ paint(ctx, { ...base(px, cx, cy), mood: sp.base, stem: k > 13 ? 'droop' : 'curl', rot: sp.key === 'apple' ? age * .85 : age * .3, spots: sp.key === 'banana' ? age : 0, eyes: { mode: 'side', look: 1 } });
+ }
+ text(ctx, 'NOT RESPONDING', scr.x + scr.w / 2, scr.y + 18, 2, Math.floor(t * 1.6) % 2 ? WHITE : '#9AA1AA', 'center');
+ }
+
+ else if (st === 'dizzy') {
+ const c = T % 3.4, seed = 11;
+ const scatter = c < .45 ? ease(c / .45) : c < 1.0 ? 1 - ease((c - .45) / .55) : 0;
+ const flip = c >= .72 && c < 2.3;
+ const offset = scatter > 0 ? (x, y) => { const a = hash(x, y, seed) * Math.PI * 2, r = (2 + hash(y, x, seed) * 5) * scatter; return [Math.round(Math.cos(a) * r), Math.round(Math.sin(a) * r)]; } : null;
+ const look = Math.floor(t * 8) % 2 ? 1 : -1;
+ const eyesMode = c < 1.0 ? 'cross' : flip ? (c > 1.6 && c < 1.75 ? 'closed' : 'side') : c < 2.9 ? 'cross' : 'side';
+ if (c >= 2.3 && c < 2.42) {
+ const o = base(px0); ctx.save(); ctx.translate(0, p.cy); ctx.scale(1, .45); ctx.translate(0, -p.cy);
+ paint(ctx, { ...o, eyes: { mode: 'closed' } }); ctx.restore();
+ } else paint(ctx, { ...base(px0), flip, offset, eyes: { mode: eyesMode, look } });
+ }
+
+ else if (st === 'compacting') {
+ // the context is being compacted, so it is: squashed flat under a press, its pixels JPEG'd into blocks
+ const c = T % 2.4, squeeze = .56 + .05 * Math.sin(c / 2.4 * Math.PI * 2) - Math.min(.1, T * .12);
+ const o = base(px0), bottom = o.oy + H * px0;
+ ctx.save(); ctx.translate(p.cx, bottom); ctx.scale(1 + (1 - squeeze) * .4, squeeze); ctx.translate(-p.cx, -bottom);
+ atRes(ctx, o.ox - px0 * 2, o.oy - px0, (W + 4) * px0, (H + 1) * px0, px0 * 2, g => paint(g, { ...o, eyes: { mode: 'none' } }));
+ eyes(ctx, { ...o, eyes: { mode: 'cam' } }, y => y);
+ ctx.restore();
+ // the press rests on its head
+ const top = bottom - H * px0 * squeeze - 3, plateW = scr.w - 24;
+ ctx.fillStyle = '#3A3F46'; ctx.fillRect(scr.x + 12, top - 9, plateW, 9);
+ ctx.fillStyle = '#5A6069'; ctx.fillRect(scr.x + 12, top - 9, plateW, 2);
+ ctx.fillStyle = '#2A2E33'; ctx.fillRect(scr.x + scr.w / 2 - 3, scr.y, 6, top - 9 - scr.y);
+ const pct = 40 + Math.floor(T * 9) % 50;
+ text(ctx, `-${pct}%`, scr.x + scr.w - 16, top - 22, 2, '#FFE66B', 'right');
+ }
+
+ else if (st === 'waiting') {
+ // rate limited: it waits, tapping a foot under an hourglass, and keeps looking up at the clock
+ const ph = T % 4, clock = ph > 1.2 && ph < 2.6;
+ const o = { ...base(px0), legs: Math.floor(T * 2.2) % 2 ? 'stepR' : 'stand', dy: 0,
+ eyes: { mode: clock ? 'up' : blinkAt(t) ? 'closed' : 'squint', look: 1 } };
+ paint(ctx, o);
+ // the hourglass: 5 x 7 pixels, sand running down, turned over every 3 s
+ const hp = Math.max(2, Math.round(px0 * .55)), hx = o.ox + (W + 1) * px0, hy = o.oy + 2 * px0;
+ const run = (T % 3) / 3, flip = (T % 3) > 2.8;
+ const GL = ['XXXXX', '.X.X.', '..X..', '..X..', '.X.X.', 'X...X', 'XXXXX'];
+ ctx.save(); if (flip) { ctx.translate(hx + 2.5 * hp, hy + 3.5 * hp); ctx.rotate(Math.PI / 2); ctx.translate(-(hx + 2.5 * hp), -(hy + 3.5 * hp)); }
+ ctx.fillStyle = '#C9CDD2'; GL.forEach((r, j) => [...r].forEach((ch, i) => { if (ch === 'X') ctx.fillRect(hx + i * hp, hy + j * hp, hp, hp); }));
+ ctx.fillStyle = '#FFD23F';
+ const topN = Math.round((1 - run) * 3), botN = Math.round(run * 3);
+ if (topN > 0) ctx.fillRect(hx + hp, hy + hp, 3 * hp, hp * Math.min(1, topN));
+ if (topN > 1) ctx.fillRect(hx + 2 * hp, hy + 2 * hp, hp, hp);
+ if (Math.floor(T * 6) % 2) ctx.fillRect(hx + 2 * hp, hy + 3 * hp, hp, hp);
+ if (botN > 0) ctx.fillRect(hx + hp, hy + 5 * hp, 3 * hp, hp);
+ if (botN > 1) ctx.fillRect(hx + 2 * hp, hy + 4 * hp, hp, hp);
+ ctx.restore();
+ const left = Math.max(0, 33 * 60 - 1 - Math.floor(T)), mm = String(Math.floor(left / 60)).padStart(2, '0'), ss = String(left % 60).padStart(2, '0');
+ text(ctx, `BACK IN ${mm}:${ss}`, scr.x + scr.w / 2, o.oy + H * px0 + 10, 2, '#9AA1AA', 'center');
+ }
+
+ else if (st === 'sleep') {
+ const px = 4, sw = W * px, sh = H * px, m = 6, rx = scr.w - 2 * m - sw, ry = scr.h - 2 * m - sh;
+ const vx = rx / 2.5, vy = ry / 3.75, TT = T + 1.2; // first corner hit at T = 6.3 s
+ const tri = (d, r) => { const n = Math.floor(d / r), f = d - n * r; return [n % 2 ? r - f : f, n]; };
+ const [x, nx] = tri(TT * vx, rx), [y, ny] = tri(TT * vy, ry);
+ const corner = []; for (let k = 1; k < 8; k++) { const tc = 7.5 * k - 1.2; if (T >= tc && T - tc < 1.6) corner.push(T - tc); }
+ const o = { sp, ox: Math.round(scr.x + m + x), oy: Math.round(scr.y + m + y), px, mood: sp.cycle[(nx + ny) % sp.cycle.length], eyes: { mode: corner.length && corner[0] < .9 ? 'cam' : 'closed' }, stem: 'droop', boost: -.06 };
+ paint(ctx, o);
+ if (corner.length) { // it hit the corner. Everyone has waited years for this.
+ const a = corner[0];
+ for (let i = 0; i < 26; i++) {
+ const ang = hash(i, 3, 1) * Math.PI * 2, spd = 30 + hash(i, 9, 2) * 70, r0 = 22;
+ const gx = o.ox + sw / 2 + Math.cos(ang) * (r0 + spd * a), gy = o.oy + sh / 2 + Math.sin(ang) * (r0 + spd * a) + 40 * a * a;
+ ctx.fillStyle = css(grad(LAB[sp.cycle[i % sp.cycle.length]], .3)); ctx.fillRect(Math.round(gx), Math.round(gy), 4, 4);
+ }
+ text(ctx, 'CORNER!', scr.x + scr.w / 2, scr.y + scr.h / 2 - 6, 3, Math.floor(a * 8) % 2 ? WHITE : '#FFE66B', 'center');
+ } else {
+ const zt = T % 1.4;
+ ctx.globalAlpha = 1 - zt / 1.4; text(ctx, 'z', o.ox + sw - 2, o.oy - 4 - step(zt / 1.4, 6) * 16, 2, WHITE); ctx.globalAlpha = 1;
+ }
+ }
+
+ else if (st === 'subagents') {
+ const n = Math.max(1, Math.min(5, p.subagents ?? 3)), all = n + 1, c = T, o = base(px0);
+ if (c < .5) {
+ const jit = Math.floor(c * 24) % 2 ? 1 : -1;
+ paint(ctx, { ...o, ox: o.ox + (c > .2 ? jit : 0), eyes: { mode: c > .2 ? 'cam' : 'side', look: 1 } });
+ } else {
+ const k = ease((c - .5) / .45), gap = (scr.w - 16) / all, mpx = Math.max(2, Math.min(4, Math.floor(gap / ((sp.visW || W) + 1))));
+ for (let i = 0; i < all; i++) {
+ const qx = o.ox + ((i % 2) + .5) * W * px0 / 2, qy = o.oy + (Math.floor(i / 2) % 2 + .5) * H * px0 / 2;
+ const fx = scr.x + scr.w / 2 + (i - (all - 1) / 2) * gap, fy = p.cy + 16;
+ const cx = Math.round(qx + (fx - qx) * k), cy = Math.round(qy + (fy - qy) * k);
+ const walk = Math.floor((c * 5) + i * .5) % 2;
+ paint(ctx, { ...base(mpx, cx, cy), mood: sp.cycle[i % sp.cycle.length], legs: k >= 1 ? (walk ? 'stepL' : 'stepR') : 'stand', dy: k >= 1 ? walk : 0, eyes: { mode: blinkAt(t, i) ? 'closed' : 'side', look: i === 0 ? 1 : -1 } });
+ }
+ if (k >= 1) text(ctx, 'X' + all, scr.x + scr.w / 2, p.cy - 36, 2, '#FFE66B', 'center');
+ }
+ }
+
+ ctx.restore();
+ }
+
+ root.PIX = { draw, paint, paintHD, text, SPECIES, PAL, STATES: ['idle', 'listening', 'thinking', 'compacting', 'working', 'subagents', 'speaking', 'done', 'needs', 'waiting', 'blocked', 'dizzy', 'sleep'] };
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/design/pix/reference/README.md b/design/pix/reference/README.md
new file mode 100644
index 0000000..46c2df1
--- /dev/null
+++ b/design/pix/reference/README.md
@@ -0,0 +1,4 @@
+Reference frames of design/pix/pix.js, rendered in the Lab at 3× (198 × 242 design points → 594 × 726 px) on black:
+pix-<species>-<state>-<stateT>.png with t = 10 + stateT, cx 99, cy 118 (146 in needs, 134 in working), px 7, voice .6,
+text "ALL 14 TESTS PASS. I ALSO FIXED A TYPO.", tools READ/EDIT/BASH, subagents 3, screen {0, 36, 198, 206}, room 150.
+The watch port (app/ChumsWatch/Rig/Pix.swift) must render the same frames from the same inputs.
diff --git a/design/pix/reference/pix-apple-blocked-0_3.png b/design/pix/reference/pix-apple-blocked-0_3.png
new file mode 100644
index 0000000..92369b2
Binary files /dev/null and b/design/pix/reference/pix-apple-blocked-0_3.png differ
diff --git a/design/pix/reference/pix-apple-blocked-1.png b/design/pix/reference/pix-apple-blocked-1.png
new file mode 100644
index 0000000..4ecbb18
Binary files /dev/null and b/design/pix/reference/pix-apple-blocked-1.png differ
diff --git a/design/pix/reference/pix-apple-blocked-2.png b/design/pix/reference/pix-apple-blocked-2.png
new file mode 100644
index 0000000..a24a322
Binary files /dev/null and b/design/pix/reference/pix-apple-blocked-2.png differ
diff --git a/design/pix/reference/pix-apple-blocked-3_2.png b/design/pix/reference/pix-apple-blocked-3_2.png
new file mode 100644
index 0000000..e324938
Binary files /dev/null and b/design/pix/reference/pix-apple-blocked-3_2.png differ
diff --git a/design/pix/reference/pix-apple-compacting-0_3.png b/design/pix/reference/pix-apple-compacting-0_3.png
new file mode 100644
index 0000000..880bf92
Binary files /dev/null and b/design/pix/reference/pix-apple-compacting-0_3.png differ
diff --git a/design/pix/reference/pix-apple-compacting-1.png b/design/pix/reference/pix-apple-compacting-1.png
new file mode 100644
index 0000000..45a887c
Binary files /dev/null and b/design/pix/reference/pix-apple-compacting-1.png differ
diff --git a/design/pix/reference/pix-apple-compacting-2.png b/design/pix/reference/pix-apple-compacting-2.png
new file mode 100644
index 0000000..7e095cd
Binary files /dev/null and b/design/pix/reference/pix-apple-compacting-2.png differ
diff --git a/design/pix/reference/pix-apple-compacting-3_2.png b/design/pix/reference/pix-apple-compacting-3_2.png
new file mode 100644
index 0000000..7bfd891
Binary files /dev/null and b/design/pix/reference/pix-apple-compacting-3_2.png differ
diff --git a/design/pix/reference/pix-apple-dizzy-0_3.png b/design/pix/reference/pix-apple-dizzy-0_3.png
new file mode 100644
index 0000000..c9dd5b6
Binary files /dev/null and b/design/pix/reference/pix-apple-dizzy-0_3.png differ
diff --git a/design/pix/reference/pix-apple-dizzy-1.png b/design/pix/reference/pix-apple-dizzy-1.png
new file mode 100644
index 0000000..dba3504
Binary files /dev/null and b/design/pix/reference/pix-apple-dizzy-1.png differ
diff --git a/design/pix/reference/pix-apple-dizzy-2.png b/design/pix/reference/pix-apple-dizzy-2.png
new file mode 100644
index 0000000..dba3504
Binary files /dev/null and b/design/pix/reference/pix-apple-dizzy-2.png differ
diff --git a/design/pix/reference/pix-apple-dizzy-3_2.png b/design/pix/reference/pix-apple-dizzy-3_2.png
new file mode 100644
index 0000000..2b70aaf
Binary files /dev/null and b/design/pix/reference/pix-apple-dizzy-3_2.png differ
diff --git a/design/pix/reference/pix-apple-done-0_3.png b/design/pix/reference/pix-apple-done-0_3.png
new file mode 100644
index 0000000..d7a68a9
Binary files /dev/null and b/design/pix/reference/pix-apple-done-0_3.png differ
diff --git a/design/pix/reference/pix-apple-done-1.png b/design/pix/reference/pix-apple-done-1.png
new file mode 100644
index 0000000..006773a
Binary files /dev/null and b/design/pix/reference/pix-apple-done-1.png differ
diff --git a/design/pix/reference/pix-apple-done-2.png b/design/pix/reference/pix-apple-done-2.png
new file mode 100644
index 0000000..9c4e783
Binary files /dev/null and b/design/pix/reference/pix-apple-done-2.png differ
diff --git a/design/pix/reference/pix-apple-done-3_2.png b/design/pix/reference/pix-apple-done-3_2.png
new file mode 100644
index 0000000..a5a6dce
Binary files /dev/null and b/design/pix/reference/pix-apple-done-3_2.png differ
diff --git a/design/pix/reference/pix-apple-idle-0_3.png b/design/pix/reference/pix-apple-idle-0_3.png
new file mode 100644
index 0000000..e0989b0
Binary files /dev/null and b/design/pix/reference/pix-apple-idle-0_3.png differ
diff --git a/design/pix/reference/pix-apple-idle-1.png b/design/pix/reference/pix-apple-idle-1.png
new file mode 100644
index 0000000..0638ce2
Binary files /dev/null and b/design/pix/reference/pix-apple-idle-1.png differ
diff --git a/design/pix/reference/pix-apple-idle-2.png b/design/pix/reference/pix-apple-idle-2.png
new file mode 100644
index 0000000..0638ce2
Binary files /dev/null and b/design/pix/reference/pix-apple-idle-2.png differ
diff --git a/design/pix/reference/pix-apple-idle-3_2.png b/design/pix/reference/pix-apple-idle-3_2.png
new file mode 100644
index 0000000..08cdede
Binary files /dev/null and b/design/pix/reference/pix-apple-idle-3_2.png differ
diff --git a/design/pix/reference/pix-apple-listening-0_3.png b/design/pix/reference/pix-apple-listening-0_3.png
new file mode 100644
index 0000000..6273d2f
Binary files /dev/null and b/design/pix/reference/pix-apple-listening-0_3.png differ
diff --git a/design/pix/reference/pix-apple-listening-1.png b/design/pix/reference/pix-apple-listening-1.png
new file mode 100644
index 0000000..6273d2f
Binary files /dev/null and b/design/pix/reference/pix-apple-listening-1.png differ
diff --git a/design/pix/reference/pix-apple-listening-2.png b/design/pix/reference/pix-apple-listening-2.png
new file mode 100644
index 0000000..6273d2f
Binary files /dev/null and b/design/pix/reference/pix-apple-listening-2.png differ
diff --git a/design/pix/reference/pix-apple-listening-3_2.png b/design/pix/reference/pix-apple-listening-3_2.png
new file mode 100644
index 0000000..6273d2f
Binary files /dev/null and b/design/pix/reference/pix-apple-listening-3_2.png differ
diff --git a/design/pix/reference/pix-apple-needs-0_3.png b/design/pix/reference/pix-apple-needs-0_3.png
new file mode 100644
index 0000000..cda089e
Binary files /dev/null and b/design/pix/reference/pix-apple-needs-0_3.png differ
diff --git a/design/pix/reference/pix-apple-needs-1.png b/design/pix/reference/pix-apple-needs-1.png
new file mode 100644
index 0000000..cda089e
Binary files /dev/null and b/design/pix/reference/pix-apple-needs-1.png differ
diff --git a/design/pix/reference/pix-apple-needs-2.png b/design/pix/reference/pix-apple-needs-2.png
new file mode 100644
index 0000000..cda089e
Binary files /dev/null and b/design/pix/reference/pix-apple-needs-2.png differ
diff --git a/design/pix/reference/pix-apple-needs-3_2.png b/design/pix/reference/pix-apple-needs-3_2.png
new file mode 100644
index 0000000..7a19524
Binary files /dev/null and b/design/pix/reference/pix-apple-needs-3_2.png differ
diff --git a/design/pix/reference/pix-apple-sleep-0_3.png b/design/pix/reference/pix-apple-sleep-0_3.png
new file mode 100644
index 0000000..4185e77
Binary files /dev/null and b/design/pix/reference/pix-apple-sleep-0_3.png differ
diff --git a/design/pix/reference/pix-apple-sleep-1.png b/design/pix/reference/pix-apple-sleep-1.png
new file mode 100644
index 0000000..73eb6a9
Binary files /dev/null and b/design/pix/reference/pix-apple-sleep-1.png differ
diff --git a/design/pix/reference/pix-apple-sleep-2.png b/design/pix/reference/pix-apple-sleep-2.png
new file mode 100644
index 0000000..c2278d4
Binary files /dev/null and b/design/pix/reference/pix-apple-sleep-2.png differ
diff --git a/design/pix/reference/pix-apple-sleep-3_2.png b/design/pix/reference/pix-apple-sleep-3_2.png
new file mode 100644
index 0000000..5e0f8ec
Binary files /dev/null and b/design/pix/reference/pix-apple-sleep-3_2.png differ
diff --git a/design/pix/reference/pix-apple-speaking-0_3.png b/design/pix/reference/pix-apple-speaking-0_3.png
new file mode 100644
index 0000000..a5614ca
Binary files /dev/null and b/design/pix/reference/pix-apple-speaking-0_3.png differ
diff --git a/design/pix/reference/pix-apple-speaking-1.png b/design/pix/reference/pix-apple-speaking-1.png
new file mode 100644
index 0000000..e0884e7
Binary files /dev/null and b/design/pix/reference/pix-apple-speaking-1.png differ
diff --git a/design/pix/reference/pix-apple-speaking-2.png b/design/pix/reference/pix-apple-speaking-2.png
new file mode 100644
index 0000000..20f2056
Binary files /dev/null and b/design/pix/reference/pix-apple-speaking-2.png differ
diff --git a/design/pix/reference/pix-apple-speaking-3_2.png b/design/pix/reference/pix-apple-speaking-3_2.png
new file mode 100644
index 0000000..d1746f2
Binary files /dev/null and b/design/pix/reference/pix-apple-speaking-3_2.png differ
diff --git a/design/pix/reference/pix-apple-subagents-0_3.png b/design/pix/reference/pix-apple-subagents-0_3.png
new file mode 100644
index 0000000..b4d2631
Binary files /dev/null and b/design/pix/reference/pix-apple-subagents-0_3.png differ
diff --git a/design/pix/reference/pix-apple-subagents-1.png b/design/pix/reference/pix-apple-subagents-1.png
new file mode 100644
index 0000000..c0f6593
Binary files /dev/null and b/design/pix/reference/pix-apple-subagents-1.png differ
diff --git a/design/pix/reference/pix-apple-subagents-2.png b/design/pix/reference/pix-apple-subagents-2.png
new file mode 100644
index 0000000..5b8a2f1
Binary files /dev/null and b/design/pix/reference/pix-apple-subagents-2.png differ
diff --git a/design/pix/reference/pix-apple-subagents-3_2.png b/design/pix/reference/pix-apple-subagents-3_2.png
new file mode 100644
index 0000000..5b8a2f1
Binary files /dev/null and b/design/pix/reference/pix-apple-subagents-3_2.png differ
diff --git a/design/pix/reference/pix-apple-thinking-0_3.png b/design/pix/reference/pix-apple-thinking-0_3.png
new file mode 100644
index 0000000..d385e79
Binary files /dev/null and b/design/pix/reference/pix-apple-thinking-0_3.png differ
diff --git a/design/pix/reference/pix-apple-thinking-1.png b/design/pix/reference/pix-apple-thinking-1.png
new file mode 100644
index 0000000..6979a7f
Binary files /dev/null and b/design/pix/reference/pix-apple-thinking-1.png differ
diff --git a/design/pix/reference/pix-apple-thinking-2.png b/design/pix/reference/pix-apple-thinking-2.png
new file mode 100644
index 0000000..bd9c311
Binary files /dev/null and b/design/pix/reference/pix-apple-thinking-2.png differ
diff --git a/design/pix/reference/pix-apple-thinking-3_2.png b/design/pix/reference/pix-apple-thinking-3_2.png
new file mode 100644
index 0000000..da3b33a
Binary files /dev/null and b/design/pix/reference/pix-apple-thinking-3_2.png differ
diff --git a/design/pix/reference/pix-apple-waiting-0_3.png b/design/pix/reference/pix-apple-waiting-0_3.png
new file mode 100644
index 0000000..3304887
Binary files /dev/null and b/design/pix/reference/pix-apple-waiting-0_3.png differ
diff --git a/design/pix/reference/pix-apple-waiting-1.png b/design/pix/reference/pix-apple-waiting-1.png
new file mode 100644
index 0000000..49e3693
Binary files /dev/null and b/design/pix/reference/pix-apple-waiting-1.png differ
diff --git a/design/pix/reference/pix-apple-waiting-2.png b/design/pix/reference/pix-apple-waiting-2.png
new file mode 100644
index 0000000..7119f88
Binary files /dev/null and b/design/pix/reference/pix-apple-waiting-2.png differ
diff --git a/design/pix/reference/pix-apple-waiting-3_2.png b/design/pix/reference/pix-apple-waiting-3_2.png
new file mode 100644
index 0000000..660ab4c
Binary files /dev/null and b/design/pix/reference/pix-apple-waiting-3_2.png differ
diff --git a/design/pix/reference/pix-apple-working-0_3.png b/design/pix/reference/pix-apple-working-0_3.png
new file mode 100644
index 0000000..429bf5e
Binary files /dev/null and b/design/pix/reference/pix-apple-working-0_3.png differ
diff --git a/design/pix/reference/pix-apple-working-1.png b/design/pix/reference/pix-apple-working-1.png
new file mode 100644
index 0000000..f06eb0b
Binary files /dev/null and b/design/pix/reference/pix-apple-working-1.png differ
diff --git a/design/pix/reference/pix-apple-working-2.png b/design/pix/reference/pix-apple-working-2.png
new file mode 100644
index 0000000..4a27408
Binary files /dev/null and b/design/pix/reference/pix-apple-working-2.png differ
diff --git a/design/pix/reference/pix-apple-working-3_2.png b/design/pix/reference/pix-apple-working-3_2.png
new file mode 100644
index 0000000..597ce3f
Binary files /dev/null and b/design/pix/reference/pix-apple-working-3_2.png differ
diff --git a/design/pix/reference/pix-banana-blocked-0_3.png b/design/pix/reference/pix-banana-blocked-0_3.png
new file mode 100644
index 0000000..4c7e9c9
Binary files /dev/null and b/design/pix/reference/pix-banana-blocked-0_3.png differ
diff --git a/design/pix/reference/pix-banana-blocked-1.png b/design/pix/reference/pix-banana-blocked-1.png
new file mode 100644
index 0000000..f60978a
Binary files /dev/null and b/design/pix/reference/pix-banana-blocked-1.png differ
diff --git a/design/pix/reference/pix-banana-blocked-2.png b/design/pix/reference/pix-banana-blocked-2.png
new file mode 100644
index 0000000..009e776
Binary files /dev/null and b/design/pix/reference/pix-banana-blocked-2.png differ
diff --git a/design/pix/reference/pix-banana-blocked-3_2.png b/design/pix/reference/pix-banana-blocked-3_2.png
new file mode 100644
index 0000000..f9581d4
Binary files /dev/null and b/design/pix/reference/pix-banana-blocked-3_2.png differ
diff --git a/design/pix/reference/pix-banana-compacting-0_3.png b/design/pix/reference/pix-banana-compacting-0_3.png
new file mode 100644
index 0000000..a6466ad
Binary files /dev/null and b/design/pix/reference/pix-banana-compacting-0_3.png differ
diff --git a/design/pix/reference/pix-banana-compacting-1.png b/design/pix/reference/pix-banana-compacting-1.png
new file mode 100644
index 0000000..ff9df08
Binary files /dev/null and b/design/pix/reference/pix-banana-compacting-1.png differ
diff --git a/design/pix/reference/pix-banana-compacting-2.png b/design/pix/reference/pix-banana-compacting-2.png
new file mode 100644
index 0000000..551dd18
Binary files /dev/null and b/design/pix/reference/pix-banana-compacting-2.png differ
diff --git a/design/pix/reference/pix-banana-compacting-3_2.png b/design/pix/reference/pix-banana-compacting-3_2.png
new file mode 100644
index 0000000..24cd9ba
Binary files /dev/null and b/design/pix/reference/pix-banana-compacting-3_2.png differ
diff --git a/design/pix/reference/pix-banana-dizzy-0_3.png b/design/pix/reference/pix-banana-dizzy-0_3.png
new file mode 100644
index 0000000..4431108
Binary files /dev/null and b/design/pix/reference/pix-banana-dizzy-0_3.png differ
diff --git a/design/pix/reference/pix-banana-dizzy-1.png b/design/pix/reference/pix-banana-dizzy-1.png
new file mode 100644
index 0000000..9f4d9ea
Binary files /dev/null and b/design/pix/reference/pix-banana-dizzy-1.png differ
diff --git a/design/pix/reference/pix-banana-dizzy-2.png b/design/pix/reference/pix-banana-dizzy-2.png
new file mode 100644
index 0000000..9f4d9ea
Binary files /dev/null and b/design/pix/reference/pix-banana-dizzy-2.png differ
diff --git a/design/pix/reference/pix-banana-dizzy-3_2.png b/design/pix/reference/pix-banana-dizzy-3_2.png
new file mode 100644
index 0000000..a0b53b3
Binary files /dev/null and b/design/pix/reference/pix-banana-dizzy-3_2.png differ
diff --git a/design/pix/reference/pix-banana-done-0_3.png b/design/pix/reference/pix-banana-done-0_3.png
new file mode 100644
index 0000000..39eb28d
Binary files /dev/null and b/design/pix/reference/pix-banana-done-0_3.png differ
diff --git a/design/pix/reference/pix-banana-done-1.png b/design/pix/reference/pix-banana-done-1.png
new file mode 100644
index 0000000..9a6d5d6
Binary files /dev/null and b/design/pix/reference/pix-banana-done-1.png differ
diff --git a/design/pix/reference/pix-banana-done-2.png b/design/pix/reference/pix-banana-done-2.png
new file mode 100644
index 0000000..2c191e6
Binary files /dev/null and b/design/pix/reference/pix-banana-done-2.png differ
diff --git a/design/pix/reference/pix-banana-done-3_2.png b/design/pix/reference/pix-banana-done-3_2.png
new file mode 100644
index 0000000..00761e8
Binary files /dev/null and b/design/pix/reference/pix-banana-done-3_2.png differ
diff --git a/design/pix/reference/pix-banana-idle-0_3.png b/design/pix/reference/pix-banana-idle-0_3.png
new file mode 100644
index 0000000..5f9adad
Binary files /dev/null and b/design/pix/reference/pix-banana-idle-0_3.png differ
diff --git a/design/pix/reference/pix-banana-idle-1.png b/design/pix/reference/pix-banana-idle-1.png
new file mode 100644
index 0000000..c183693
Binary files /dev/null and b/design/pix/reference/pix-banana-idle-1.png differ
diff --git a/design/pix/reference/pix-banana-idle-2.png b/design/pix/reference/pix-banana-idle-2.png
new file mode 100644
index 0000000..c183693
Binary files /dev/null and b/design/pix/reference/pix-banana-idle-2.png differ
diff --git a/design/pix/reference/pix-banana-idle-3_2.png b/design/pix/reference/pix-banana-idle-3_2.png
new file mode 100644
index 0000000..8d876d2
Binary files /dev/null and b/design/pix/reference/pix-banana-idle-3_2.png differ
diff --git a/design/pix/reference/pix-banana-listening-0_3.png b/design/pix/reference/pix-banana-listening-0_3.png
new file mode 100644
index 0000000..0f167c9
Binary files /dev/null and b/design/pix/reference/pix-banana-listening-0_3.png differ
diff --git a/design/pix/reference/pix-banana-listening-1.png b/design/pix/reference/pix-banana-listening-1.png
new file mode 100644
index 0000000..0f167c9
Binary files /dev/null and b/design/pix/reference/pix-banana-listening-1.png differ
diff --git a/design/pix/reference/pix-banana-listening-2.png b/design/pix/reference/pix-banana-listening-2.png
new file mode 100644
index 0000000..0f167c9
Binary files /dev/null and b/design/pix/reference/pix-banana-listening-2.png differ
diff --git a/design/pix/reference/pix-banana-listening-3_2.png b/design/pix/reference/pix-banana-listening-3_2.png
new file mode 100644
index 0000000..0f167c9
Binary files /dev/null and b/design/pix/reference/pix-banana-listening-3_2.png differ
diff --git a/design/pix/reference/pix-banana-needs-0_3.png b/design/pix/reference/pix-banana-needs-0_3.png
new file mode 100644
index 0000000..7697f4a
Binary files /dev/null and b/design/pix/reference/pix-banana-needs-0_3.png differ
diff --git a/design/pix/reference/pix-banana-needs-1.png b/design/pix/reference/pix-banana-needs-1.png
new file mode 100644
index 0000000..7697f4a
Binary files /dev/null and b/design/pix/reference/pix-banana-needs-1.png differ
diff --git a/design/pix/reference/pix-banana-needs-2.png b/design/pix/reference/pix-banana-needs-2.png
new file mode 100644
index 0000000..7697f4a
Binary files /dev/null and b/design/pix/reference/pix-banana-needs-2.png differ
diff --git a/design/pix/reference/pix-banana-needs-3_2.png b/design/pix/reference/pix-banana-needs-3_2.png
new file mode 100644
index 0000000..7697f4a
Binary files /dev/null and b/design/pix/reference/pix-banana-needs-3_2.png differ
diff --git a/design/pix/reference/pix-banana-sleep-0_3.png b/design/pix/reference/pix-banana-sleep-0_3.png
new file mode 100644
index 0000000..1811438
Binary files /dev/null and b/design/pix/reference/pix-banana-sleep-0_3.png differ
diff --git a/design/pix/reference/pix-banana-sleep-1.png b/design/pix/reference/pix-banana-sleep-1.png
new file mode 100644
index 0000000..e0d384e
Binary files /dev/null and b/design/pix/reference/pix-banana-sleep-1.png differ
diff --git a/design/pix/reference/pix-banana-sleep-2.png b/design/pix/reference/pix-banana-sleep-2.png
new file mode 100644
index 0000000..59ade9b
Binary files /dev/null and b/design/pix/reference/pix-banana-sleep-2.png differ
diff --git a/design/pix/reference/pix-banana-sleep-3_2.png b/design/pix/reference/pix-banana-sleep-3_2.png
new file mode 100644
index 0000000..e415251
Binary files /dev/null and b/design/pix/reference/pix-banana-sleep-3_2.png differ
diff --git a/design/pix/reference/pix-banana-speaking-0_3.png b/design/pix/reference/pix-banana-speaking-0_3.png
new file mode 100644
index 0000000..0089acf
Binary files /dev/null and b/design/pix/reference/pix-banana-speaking-0_3.png differ
diff --git a/design/pix/reference/pix-banana-speaking-1.png b/design/pix/reference/pix-banana-speaking-1.png
new file mode 100644
index 0000000..e7d3b92
Binary files /dev/null and b/design/pix/reference/pix-banana-speaking-1.png differ
diff --git a/design/pix/reference/pix-banana-speaking-2.png b/design/pix/reference/pix-banana-speaking-2.png
new file mode 100644
index 0000000..3526d64
Binary files /dev/null and b/design/pix/reference/pix-banana-speaking-2.png differ
diff --git a/design/pix/reference/pix-banana-speaking-3_2.png b/design/pix/reference/pix-banana-speaking-3_2.png
new file mode 100644
index 0000000..c0d4dc7
Binary files /dev/null and b/design/pix/reference/pix-banana-speaking-3_2.png differ
diff --git a/design/pix/reference/pix-banana-subagents-0_3.png b/design/pix/reference/pix-banana-subagents-0_3.png
new file mode 100644
index 0000000..b96049f
Binary files /dev/null and b/design/pix/reference/pix-banana-subagents-0_3.png differ
diff --git a/design/pix/reference/pix-banana-subagents-1.png b/design/pix/reference/pix-banana-subagents-1.png
new file mode 100644
index 0000000..21643df
Binary files /dev/null and b/design/pix/reference/pix-banana-subagents-1.png differ
diff --git a/design/pix/reference/pix-banana-subagents-2.png b/design/pix/reference/pix-banana-subagents-2.png
new file mode 100644
index 0000000..be157a3
Binary files /dev/null and b/design/pix/reference/pix-banana-subagents-2.png differ
diff --git a/design/pix/reference/pix-banana-subagents-3_2.png b/design/pix/reference/pix-banana-subagents-3_2.png
new file mode 100644
index 0000000..be157a3
Binary files /dev/null and b/design/pix/reference/pix-banana-subagents-3_2.png differ
diff --git a/design/pix/reference/pix-banana-thinking-0_3.png b/design/pix/reference/pix-banana-thinking-0_3.png
new file mode 100644
index 0000000..f335710
Binary files /dev/null and b/design/pix/reference/pix-banana-thinking-0_3.png differ
diff --git a/design/pix/reference/pix-banana-thinking-1.png b/design/pix/reference/pix-banana-thinking-1.png
new file mode 100644
index 0000000..e2106c9
Binary files /dev/null and b/design/pix/reference/pix-banana-thinking-1.png differ
diff --git a/design/pix/reference/pix-banana-thinking-2.png b/design/pix/reference/pix-banana-thinking-2.png
new file mode 100644
index 0000000..78e5830
Binary files /dev/null and b/design/pix/reference/pix-banana-thinking-2.png differ
diff --git a/design/pix/reference/pix-banana-thinking-3_2.png b/design/pix/reference/pix-banana-thinking-3_2.png
new file mode 100644
index 0000000..df5858d
Binary files /dev/null and b/design/pix/reference/pix-banana-thinking-3_2.png differ
diff --git a/design/pix/reference/pix-banana-waiting-0_3.png b/design/pix/reference/pix-banana-waiting-0_3.png
new file mode 100644
index 0000000..45f7378
Binary files /dev/null and b/design/pix/reference/pix-banana-waiting-0_3.png differ
diff --git a/design/pix/reference/pix-banana-waiting-1.png b/design/pix/reference/pix-banana-waiting-1.png
new file mode 100644
index 0000000..3f35272
Binary files /dev/null and b/design/pix/reference/pix-banana-waiting-1.png differ
diff --git a/design/pix/reference/pix-banana-waiting-2.png b/design/pix/reference/pix-banana-waiting-2.png
new file mode 100644
index 0000000..3dc8b1c
Binary files /dev/null and b/design/pix/reference/pix-banana-waiting-2.png differ
diff --git a/design/pix/reference/pix-banana-waiting-3_2.png b/design/pix/reference/pix-banana-waiting-3_2.png
new file mode 100644
index 0000000..8506927
Binary files /dev/null and b/design/pix/reference/pix-banana-waiting-3_2.png differ
diff --git a/design/pix/reference/pix-banana-working-0_3.png b/design/pix/reference/pix-banana-working-0_3.png
new file mode 100644
index 0000000..77a1ed5
Binary files /dev/null and b/design/pix/reference/pix-banana-working-0_3.png differ
diff --git a/design/pix/reference/pix-banana-working-1.png b/design/pix/reference/pix-banana-working-1.png
new file mode 100644
index 0000000..018a5fe
Binary files /dev/null and b/design/pix/reference/pix-banana-working-1.png differ
diff --git a/design/pix/reference/pix-banana-working-2.png b/design/pix/reference/pix-banana-working-2.png
new file mode 100644
index 0000000..f377db3
Binary files /dev/null and b/design/pix/reference/pix-banana-working-2.png differ
diff --git a/design/pix/reference/pix-banana-working-3_2.png b/design/pix/reference/pix-banana-working-3_2.png
new file mode 100644
index 0000000..e522ab1
Binary files /dev/null and b/design/pix/reference/pix-banana-working-3_2.png differ
diff --git a/design/pix/sheet.html b/design/pix/sheet.html
new file mode 100644
index 0000000..276cd00
--- /dev/null
+++ b/design/pix/sheet.html
@@ -0,0 +1,25 @@
+<meta charset="utf-8">
+<title>Pix sheet</title>
+<body style="margin:0;background:#222">
+<canvas id="c"></canvas>
+<script src="pix.js"></script>
+<script>
+// renders a contact sheet: each cell is a 198 × 242 watch screen at 2×
+window.renderSheet = (cells, cols = 6) => {
+ const S = 2, w = 198, h = 242, pad = 8, lab = 14, rows = Math.ceil(cells.length / cols);
+ const c = document.getElementById('c'); c.width = cols * (w * S + pad) + pad; c.height = rows * (h * S + pad + lab) + pad;
+ const g = c.getContext('2d'); g.fillStyle = '#222'; g.fillRect(0, 0, c.width, c.height);
+ cells.forEach((cell, i) => {
+ const x = pad + (i % cols) * (w * S + pad), y = pad + Math.floor(i / cols) * (h * S + pad + lab);
+ g.fillStyle = '#ccc'; g.font = '12px monospace'; g.fillText(cell.label || cell.state, x, y + 11);
+ g.save(); g.translate(x, y + lab); g.scale(S, S);
+ g.fillStyle = '#000'; g.fillRect(0, 0, w, h);
+ g.beginPath(); g.rect(0, 0, w, h); g.clip();
+ (cell.extra || []).forEach(e => PIX.draw(g, e));
+ PIX.draw(g, { cx: 99, cy: 130, px: 7, t: 1, stateT: 1, look: 1, ...cell });
+ g.restore();
+ });
+ return c.toDataURL('image/png');
+};
+</script>
+</body>
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..1428c04
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,252 @@
+# How Chums works
+
+Chums has four parts:
+
+- **The watch app** (`app/ChumsWatch`, SwiftUI, watchOS 26): draws the character, records your voice, shows
+ approvals and replies, and polls the hub.
+- **The iPhone app** (`app/ChumsPhone`, iOS 26): the same agents and conversations through the same hub, with
+ widgets and a Talk control ([below](#the-iphone-app)).
+- **The hub** (`hub/hub.mjs`, Node.js, on your Mac): the only thing that talks to the coding agents. It keeps track of
+ sessions, routes what you say, holds approvals, transcribes speech and serves the watch API.
+- **The channel and hooks** (`channel/`): connect each Claude Code session to the hub. `bin/chums-claude` starts a
+ session with both. Codex CLI and GitHub Copilot CLI: see [other-agents.md](other-agents.md).
+
+```mermaid
+flowchart LR
+ subgraph Watch["Apple Watch"]
+ W["Chums app<br/>(SwiftUI)"]
+ end
+ subgraph Net["Internet"]
+ F["Tailscale Funnel<br/>https://&lt;machine&gt;.&lt;tailnet&gt;.ts.net"]
+ end
+ subgraph Mac["Your Mac"]
+ P["Hub, watch side<br/>127.0.0.1:7718 · /v1/… only"]
+ H["Hub<br/>127.0.0.1:7717"]
+ S["whisperkit-cli serve<br/>speech to text"]
+ K["Kokoro (MLX)<br/>the agents' voices"]
+ C1["chums-channel + hooks"]
+ C2["chums-channel + hooks"]
+ A1["Claude Code session"]
+ A2["Claude Code session"]
+ end
+ W -- "HTTPS, long polling<br/>watch token" --> F --> P --> H
+ H <--> S
+ H <--> K
+ C1 <-- "localhost HTTP<br/>local token" --> H
+ C2 <-- "localhost HTTP" --> H
+ A1 <-- "MCP (stdio)" --> C1
+ A2 <-- "MCP (stdio)" --> C2
+```
+
+## Network
+
+- watchOS does not support apps reaching a home-network address
+ ([TN3135](https://developer.apple.com/documentation/technotes/tn3135-low-level-networking-on-watchos)); it works only
+ when the iPhone happens to relay it. So the watch API goes on the internet through Tailscale Funnel
+ (`bin/chums-tunnel`). The watch reaches it over whatever network it has: the iPhone, Wi-Fi or cellular.
+- The public listener serves only `/v1/…`, on localhost, and only with the watch token. See [SECURITY.md](../SECURITY.md).
+- The watch uses plain HTTP long polling. watchOS allows WebSockets only while streaming audio.
+- The app's addresses are the public URL, then `http://127.0.0.1:7717`; it uses the first that answers. A real watch
+ drops the local one, so only the Simulator falls back to it.
+- `tailscaled` runs without admin rights (userspace networking), with its state in `~/.chums/tailscale`.
+
+## Keyring mode
+
+The watch can be carried on a keyring instead of worn. Keyring mode keeps Chums in front:
+
+- It runs a workout session (HealthKit) so watchOS doesn't suspend the app when the screen dims. Without it nothing
+ polls and nothing can tap your wrist. No workout is saved.
+- If Chums quits during the session, watchOS relaunches it.
+- When Chums isn't in front (after a crown press), approvals, questions, done and blocked arrive as local
+ notifications; tapping one opens Chums. The complication / Smart Stack widget (`app/ChumsWidget`) opens it in one tap.
+
+## Speech
+
+You hold the screen to talk. The watch records the clip and posts it to the hub. The hub transcribes it with a
+kept-alive `whisperkit-cli serve` (about 0.2 s per clip with the base model). Clips are padded with silence because
+Whisper drops clips under 1 s. Replies are short (the channel refuses replies over 15 words to the watch and 60 to
+the iPhone: each order carries the device it came from, `via="watch"` or `via="phone"`), and each agent speaks
+them in its own voice (below).
+
+## The agents' voices
+
+Each agent speaks in its own voice: Kokoro (82M parameters, Apache-2.0) on the Mac's GPU through MLX
+(`tools/kokoro-server.py`, installed by `bin/chums-setup` in `~/.chums/kokoro`). The hub starts it on
+`127.0.0.1:50062` with every agent's voice loaded and warmed, and restarts it if it stops. Nothing leaves the Mac.
+
+How a reply gets to the wrist fast:
+
+- The hub renders a reply the moment the agent sends it: about 0.15 s for a sentence, AAC at 32 kbit/s, about 20 KB.
+- After a quiet minute the chips slow down and a render takes about 0.45 s. A single word doesn't speed them up; a
+ sentence every 2 s does. So while an agent works on an order from the watch, Kokoro renders a sentence nobody hears
+ every 2 s, until the reply comes or for 45 s (about 5% of the GPU while you wait). Its threads also run at
+ user-interactive priority.
+- It holds the line until its audio is ready (never more than 1.5 s) and puts the audio in the same answer to the
+ watch's long poll that carries the line (`audioData`, base64), so the watch plays it without a second request
+ through Funnel. A line without inline audio is fetched from `/v1/speech/<id>`; without either, the watch reads it
+ with its own voice.
+- The hub's LaunchAgent is `Interactive`, so launchd doesn't throttle it, Whisper or Kokoro as background work.
+
+The voices are Kokoro's English ones (`/v1/voices`); an agent's is `voice` in `agents.json`, chosen on the watch (its
+soul screen, Voice, where each plays a sample). Other engines are a setting: `"tts": { "engine": "say", "voice":
+"Ava (Premium)" }` for a macOS voice, `"openai"` with a key, or `"watch"` for the watch's own voice.
+
+## The channel
+
+`channel/chums-channel.mjs` is a Claude Code channel: an MCP server that Claude Code loads with
+`--dangerously-load-development-channels server:chums` (channels are a research preview). One runs per session. It:
+
+- registers the session with the hub and long-polls for orders, which arrive in the session as channel messages;
+- relays permission requests to the hub and the verdicts back;
+- gives the session two tools: `chums_reply` (speak one short sentence on the watch) and `chums_show` (show a picture).
+
+`bin/chums-claude` writes `channel/mcp.json` and `channel/hooks.json` with this checkout's paths, keeps Remote Control
+on, and lets the session call `chums_reply` and read `~/.chums/uploads` without asking (it may not edit
+`~/.chums/souls`).
+
+## Hooks and states
+
+`bin/chums-claude` also installs Claude Code hooks (`channel/chums-hook.mjs`) for 15 events: tool calls and failures,
+permission requests, notifications, prompts, stops and stop failures, compaction, subagents, session start and end.
+The hub turns them into a status per session (`idle`, `working`, `waiting`, `blocked`, `limited`, `compacting`) and
+reactions. [design/STATES.md](../design/STATES.md) maps every hook event and Agent Client Protocol update to a state,
+a reaction, or nothing.
+
+## Artifacts: pictures from a session
+
+Ask from the watch to see something ("send me a screenshot of the desktop", "what does that page look like") and the
+session calls `chums_show`:
+
+- `screenshot: 'screen'` or an app's name (`'Safari'`): taken with `screencapture` from inside the session, so the app
+ the session runs in needs Screen Recording permission. Pages behind a login are screenshots of the browser.
+- `url`: a public page, rendered on the Mac by WebKit at phone width (`tools/page-shot.swift`, compiled to
+ `~/.chums/bin/page-shot` on first use). The watch has no web engine, so pages arrive as pictures.
+- `file`: a file of any kind below.
+
+Every artifact is a picture for the watch (`kind` in its `meta.json`, which the apps label it by):
+
+| What | `kind` | How it becomes a picture |
+| --- | --- | --- |
+| A URL, `.html`, `.htm` | `page` | WebKit at phone width, the whole page, once it has loaded and its animations have ended (`page-shot`, in a window in the screen's corner that can't be seen or clicked: WebKit runs a page's animations only on screen) |
+| `.svg`, and images (`.png`, `.jpg`, `.heic`, `.gif`, `.webp`, `.tiff`, `.bmp`) | `image` | An SVG like a page; an image as it is |
+| A screenshot | `screenshot` | As it is |
+| `.pdf` | `pdf` | Every page, top to bottom, drawn by PDFKit (`tools/pdf-shot.swift`): 1200 px wide, narrower (down to 900 px) for more pages; past 10 M pixels the rest is left out and the title says which pages it shows ("pages 1–9 of 14") |
+| `.md`, `.markdown` | `doc` | Made into a dark HTML page (`hub/render.mjs`: headings, lists, tables, code; links and images as their text), then WebKit |
+| `.csv`, `.tsv` | `table` | The same: a table of the first rows (up to 200, the columns that fit in 1300 pt); the title says how many of how many |
+| Code, logs, `.txt`, `.json` and any other UTF-8 text | `text` | The same: monospaced, the first lines that fit in one picture (up to 300); the title says "first 214 lines of 1,423" |
+| `.mov`, `.mp4`, `.m4v` | `video` | A still from a second in (`ffmpeg`; without it, Quick Look's) |
+| Anything else Quick Look has a picture of: Word, Excel, PowerPoint, Pages, Keynote, Numbers, RTF, EPUB, USDZ | `doc` | Quick Look's picture as Finder draws it, up to 1600 px (`tools/ql-shot.swift`): a document's first page, a presentation's first slide |
+
+A file with none of these is refused with the reason. Each conversion has a time limit and runs in a process of its
+own (the HTML pages too: `node hub/render.mjs`), so a large or odd file never holds up the hub. The pages the hub
+makes load nothing: no links, images or scripts.
+
+The hub keeps the last 60 in `~/.chums/artifacts/<id>/` (`full.jpg` up to 1200 px wide and 10 M pixels, `thumb.jpg`)
+and serves them at `/v1/artifact/<id>/full|thumb`. On the watch a tap opens one full screen: the crown or a drag
+scrolls, a double tap zooms, a drag down from the top or × closes it.
+
+For the iPhone, which opens an artifact itself, the folder also keeps the file as it was (`source.<ext>`, up to 25 MB)
+and, for Markdown, text and tables, the hub's HTML page of it (`view.html`, with more than the picture: up to 5,000
+lines or 1,000 rows). `meta.view` says what there is, and comes with the artifact in `/v1/state`:
+
+| `view.type` | For | `view.file` (what `/view` serves) |
+| --- | --- | --- |
+| `url` | A page shown by its URL (`view.url`; no file) | |
+| `html` | `.html`, `.htm`, `.svg` (`source.<ext>`); Markdown, CSV and TSV (`view.html`) | `source.html`, `source.svg` or `view.html` |
+| `pdf` | `.pdf` | `source.pdf` |
+| `image` | Images and screenshots | `source.<ext>` |
+| `text` | Code, logs and other text | `view.html` |
+| `doc` | What Quick Look opens: Office, iWork, RTF, EPUB, USDZ | `source.<ext>` |
+| `video` | `.mov`, `.mp4`, `.m4v` | `source.<ext>` |
+
+`view` also has `name` (the file's name), `ext`, `size` (bytes) and `source` (whether the original was kept: not over
+25 MB). `/v1/artifact/<id>/source` serves the original and `/v1/artifact/<id>/view` the file named in `view.file`,
+each with its type and file name, and byte ranges (a video player asks for them). An HTML page is served sandboxed
+(`Content-Security-Policy: sandbox allow-scripts`): its scripts run, in an origin of their own. Artifacts made before
+`view` existed have none; the apps show their picture.
+
+## Agents: one per character
+
+Every character is its own agent: its own soul, its own session and thread, its own conversation on the watch. A
+Claude Code agent (the default) is a session run in the background by a LaunchAgent (`bin/chums-agents install`; then
+`status`, `stop|start|restart <id>`, and `open <id>` to take one into a terminal); a Codex agent runs inside the hub.
+Which one is chosen per agent on the watch (its soul screen, Runs on) or on its card in the iPhone app: the hub
+stops one and starts the other
+(`POST /v1/agents/<id>/runtime`), and keeps each runtime's thread in `byRuntime` for a switch back.
+
+They are listed in `~/.chums/agents.json`, one per character, the id the character's, which the hub writes with
+defaults the first time and completes when a character has none ([tools/agents.example.json](../tools/agents.example.json)
+shows the shape): each in `~/.chums/agents/<id>` with your home folder. Three get a job in their first soul: Noodle
+code, Squint your Mac, Peeps design.
+
+`tools/agent-host.exp` gives each session a terminal of its own and answers only the two start-up screens it knows
+(trusting the agent's folder, confirming the development channel). `tools/agent-cmd.mjs` resumes the agent's thread,
+adds its standing instructions and folders, and refuses to start a thread that is already running.
+
+On the watch, the face at the top left is the agent you talk to, in front of up to two others (the most urgent
+first). A tap opens the list of agents (amber: needs you, white: working, red: stuck, gray: idle, dimmed: not running)
+with Settings below. Everything on screen, and everything you say, belongs to that agent. Another agent's news arrives
+as a tap on the wrist and a pill with its face; a tap on the pill switches to that agent.
+
+## Souls
+
+Each agent's identity (its name, what it looks after, what it hands to the others, its voice) is its soul:
+`~/.chums/souls/<id>.md`, in a git repository of its own. You change a soul by voice from the watch: swipe an agent in
+the list, hold "Hold to change" and say what should be different. A separate, tool-free model call on the Mac
+(`claude -p`, Sonnet, about 4 s) turns that into a targeted change and one sentence. You tap Save or Cancel; Undo goes
+back one change. On the iPhone, a tap on a part of the soul on the agent's card edits it as text, saved as typed
+(`POST /v1/agents/<id>/soul/set`) with no model call. An agent gets its current soul with the next order after a
+change, and again after it compacts.
+
+## The watch app
+
+One screen, drawn every frame (SwiftUI `Canvas` in a `TimelineView`):
+
+- `Rig/RigCore.swift`, `Rig.swift`, `Worlds.swift`: the shared rig (springs, blinks, gaze, states, camera, physics,
+ crown, shaking) and the character kinds.
+- `Rig/<Name>Stage.swift`: each character draws itself (Noodle, Stretch, Peeps, Squint, Ray, Tangle; Crunch and Nana
+ in `Pix.swift`).
+- `Controller.swift`: hub state to character state. `Screen.swift` (`ScreenModel`): gestures, motion, talking,
+ approvals and replies, shared with the iPhone. `Voice.swift`: recording and speech. `ChumsWatchApp.swift`: the
+ view, the crown, the overlays and Settings.
+- Stretch plays Blender renders as HEIC image sequences (`app/ChumsWatch/Noodle/*.heics`, made by
+ `tools/noodle-watch.sh`), decoded a frame at a time, since watchOS can't read frames out of video.
+
+[characters.md](characters.md) covers how each character is made.
+
+## The iPhone app
+
+`app/ChumsPhone` uses the watch's engine: the characters (`Rig/`), the hub client, talking, the conversation and
+`ScreenModel` (`Screen.swift`) are the same files, built for iOS (watch-only parts are `#if os(watchOS)`). With
+`rig.chrome` off, the renderer draws only the character; the iPhone draws the rest in SwiftUI: the agents button and
+panel, the conversation (with the character as its last row and its state lane beside it), the approval card, the
+composer and the agent's card. It polls the hub only while it is open, so it sends no notifications.
+
+Each device names itself to the hub (`X-Chums-Device` with a clip, `device` in `/v1/say`). An order remembers
+the device it came from, and the agent's reply is tagged with it: every device shows the line, only that device
+speaks it.
+
+Photos and files from the iPhone go to `/v1/upload`, which keeps them in `~/.chums/uploads` and makes an artifact of
+each, from you, as for `chums_show` (a file there is no picture of stays just a file). `/v1/say` then carries their paths in `files`: the order the agent
+gets ends with "Attached (files on this Mac; read them): …", and the echo of what you said shows the picture.
+
+The widgets (`app/ChumsPhoneWidgets`, views in `app/ChumsPhoneShared`) read `/v1/state` themselves with the same
+address and token, draw the watch's screen for an agent with the watch's rig (`WatchScreen`: the character settles into
+its state for 1.5 s, then one picture), answer approvals with `/v1/verdict` through an App Intent, and open the app
+with `chums://agent/<id>` or `chums://talk/<id>`. An Agent widget with no agent picked shows the hub's `focus`: the
+agent last talked to from any device, or the one the app shows (it posts `/v1/focus` when you change agents). The app
+reloads the widgets when you change agents, when it goes to the background, and when the hub's state changes, at most
+every 20 s. Debug builds draw every widget size to pictures with `-widgetShots YES`.
+
+An agent's model, picked on its card in the app: `GET /v1/models` lists Claude Code's aliases and the models in Codex's
+own cache (`~/.codex/models_cache.json`), with what each runtime uses by default; `POST /v1/agents/<id>/model` sets
+`model` in agents.json and restarts the agent on it (`bin/chums-agents restart`, or its runner in the hub).
+
+An agent's permission mode, picked on the watch and in the app: `GET /v1/permissions` lists each runtime's modes
+(Claude Code: Asks first, Edits on its own, Decides on its own; Codex: Asks first, Asks when it needs to, Never asks),
+with what each runtime uses when an agent has none (`permissions.defaultMode` in `~/.claude/settings.json`,
+`approval_policy` in `~/.codex/config.toml`, else `on-request`); `POST /v1/agents/<id>/permission` sets
+`permissionMode` (Claude Code, passed as `--permission-mode`) or `approvalPolicy` (Codex, on its thread) in agents.json
+and restarts the agent in it, the same way. When auto mode refuses a step (Claude Code's `PermissionDenied` hook), the
+agent's conversation gets a line of kind `refused`, "Auto mode refused: " and the step (at most one a minute per
+agent), which the apps show and don't read aloud.
diff --git a/docs/characters.md b/docs/characters.md
new file mode 100644
index 0000000..9d52852
--- /dev/null
+++ b/docs/characters.md
@@ -0,0 +1,70 @@
+# The characters
+
+Every character acts out the same states: idle, listening, thinking, working, subagents, speaking, done, needs you,
+approval, blocked, dizzy and sleep, plus reactions to a tool call and to your touches.
+[design/STATES.md](../design/STATES.md) maps what Claude Code and Codex report to each of them.
+
+| Character | What it is | Code |
+| --- | --- | --- |
+| Noodle | A soft 3D tube, blue at the tail through purple and pink to a yellow-orange head with two eyes. 64 points a fixed distance apart, moved between a library of shapes, lit and sliced live | `Rig/NoodleStage.swift`, `Rig/NoodleRest.swift`, `noodle-shapes.bin` |
+| Stretch | A glowing gel puppet rendered in Blender (Cycles). Each state is a pool of clips at 24 fps chained at random; per-frame data says where its hair, face and glass contact are, so the screen plays along | `Rig/StretchStage.swift`, `Rig/StretchFrames.swift`, `Noodle/`, `design/noodle/` |
+| Peeps | Two eyes on black. Everything is in how they move; they follow your finger | `Rig/PeepsStage.swift` |
+| Squint | A face drawn in white marker strokes, like a kaomoji. Each part is one stroke that changes shape and hangs on its own spring | `Rig/SquintStage.swift`, `Rig/Chalk.swift` |
+| Ray | A flat golden sun with ten wavy arms; the mood changes the arms' shape and speed | `Rig/RayStage.swift` |
+| Tangle | A ball of yarn drawn as one pale-blue marker line, with a face | `Rig/TangleStage.swift`, `Rig/Yarn.swift` |
+| Crunch | A deadpan pixel apple whose moods are render settings: low resolution while thinking, HD when done, a frozen window when stuck, a bouncing screensaver asleep | `Rig/Pix.swift` (port of `design/pix/pix.js`) |
+| Nana | The same as Crunch, as a pixel banana | `Rig/Pix.swift` |
+
+Paths are under `app/ChumsWatch/` unless they start with `design/`.
+
+## Gestures
+
+| Do this | It does |
+| --- | --- |
+| Hold the screen | Talk. Let go to send; slide onto × to cancel |
+| Tap the character | Poke it. Four in 3 s: Peeps, Squint, Ray and Tangle get annoyed, Noodle gets dizzy |
+| Stroke across it | Pet it |
+| Hold the approval card | Allow the command (1 s); tap × to deny |
+| Turn the Digital Crown | Each character reacts its own way: Stretch stretches, Nana ripens, Squint picks a face (and keeps it), Tangle unspools or winds itself, Peeps get bubbles (up) or a wind (down); Noodle and Ray, spun fast, get dizzy |
+| Tilt or shake the watch | Peeps and Tangle follow a tilt; a hard shake makes any character dizzy |
+| Tap the faces at the top left | The agents list (press and hold a row, then drag it, to change the order), with Settings below |
+
+
+## Stretch: the Blender pipeline
+
+Every clip is keyed acting in `design/noodle/animate.py`: a rest loop and beats per state, chained at random by the
+player. `noodle_rig.py` (also stored in the `.blend`) is the pose API.
+
+```bash
+cd design/noodle
+/Applications/Blender.app/Contents/MacOS/Blender -b noodle.blend -P animate.py -- --preview --step 4 speak_a # quick motion check
+/Applications/Blender.app/Contents/MacOS/Blender -b noodle.blend -P animate.py -- all # final: 396 × 484, 128 samples
+cd ../.. && tools/noodle-watch.sh # pack the frames as HEIC sequences for the watch (app/ChumsWatch/Noodle)
+```
+
+The final render takes several hours on a laptop GPU. The packed HEIC clips are committed, so you only need Blender
+to change Stretch.
+
+## Crunch and Nana: checking the port
+
+`app/ChumsWatch/Rig/Pix.swift` must render the same frames as `design/pix/pix.js`. `tools/pix-compare.sh` renders the
+104 reference frames on the Mac and compares them with `design/pix/reference`, pixel for pixel.
+`open design/pix/sheet.html` shows a contact sheet of the JavaScript version.
+
+## Recording
+
+`app/ChumsWatch/OfflineRender.swift` renders any character frame by frame in the Simulator from a JSON spec
+(`-render <base64 spec>`), so a state can be checked or recorded without a hub. `xcrun simctl io booted recordVideo`
+records the Simulator's screen. `tools/readme-loops.sh` renders each character's loop for the README with it (run
+`bin/chums-sim` once first).
+
+## Adding a character
+
+1. Add a case to `CharacterKind` in `app/ChumsWatch/Rig/RigCore.swift`, with its name. If it plays frames (like
+ Stretch, Crunch and Nana), make `framed` true for it there too: the screen then draws at 30 frames a second.
+2. Draw it in a `<Name>Stage.swift` (see `RayStage.swift`) and return it from the stage switch in `Rig/Rig.swift`.
+3. Add its id to `LOOKS` and `LOOK_NAMES` in `hub/hub.mjs`, a voice in `VOICES` there (else it gets `af_heart`), to
+ `looks` in `app/ChumsWatch/Soul.swift`, and to `order` in `app/ChumsPhoneShared/WidgetHub.swift` (the widgets' order).
+4. Add an `avatar-<id>` image to `app/Shared/Characters.xcassets`. If the picture goes to its edges (rendered, not pixel
+ art in the middle), add the id to `fullBleed` in `app/ChumsWatch/AgentFace.swift`.
+5. Check every state in the Simulator (`bin/chums-sim`, then the demo in Settings), and on the iPhone Simulator.
diff --git a/docs/media/characters/crunch.webp b/docs/media/characters/crunch.webp
new file mode 100644
index 0000000..9752fe4
Binary files /dev/null and b/docs/media/characters/crunch.webp differ
diff --git a/docs/media/characters/nana.webp b/docs/media/characters/nana.webp
new file mode 100644
index 0000000..ccbca5d
Binary files /dev/null and b/docs/media/characters/nana.webp differ
diff --git a/docs/media/characters/noodle.webp b/docs/media/characters/noodle.webp
new file mode 100644
index 0000000..9356126
Binary files /dev/null and b/docs/media/characters/noodle.webp differ
diff --git a/docs/media/characters/peeps.webp b/docs/media/characters/peeps.webp
new file mode 100644
index 0000000..5136c81
Binary files /dev/null and b/docs/media/characters/peeps.webp differ
diff --git a/docs/media/characters/ray.webp b/docs/media/characters/ray.webp
new file mode 100644
index 0000000..89956c7
Binary files /dev/null and b/docs/media/characters/ray.webp differ
diff --git a/docs/media/characters/squint.webp b/docs/media/characters/squint.webp
new file mode 100644
index 0000000..0bfc065
Binary files /dev/null and b/docs/media/characters/squint.webp differ
diff --git a/docs/media/characters/stretch.webp b/docs/media/characters/stretch.webp
new file mode 100644
index 0000000..f0da77f
Binary files /dev/null and b/docs/media/characters/stretch.webp differ
diff --git a/docs/media/characters/tangle.webp b/docs/media/characters/tangle.webp
new file mode 100644
index 0000000..3b24311
Binary files /dev/null and b/docs/media/characters/tangle.webp differ
diff --git a/docs/media/readme/counter.webp b/docs/media/readme/counter.webp
new file mode 100644
index 0000000..461259e
Binary files /dev/null and b/docs/media/readme/counter.webp differ
diff --git a/docs/media/readme/keys.webp b/docs/media/readme/keys.webp
new file mode 100644
index 0000000..094b163
Binary files /dev/null and b/docs/media/readme/keys.webp differ
diff --git a/docs/media/readme/lanyard.webp b/docs/media/readme/lanyard.webp
new file mode 100644
index 0000000..32ab43a
Binary files /dev/null and b/docs/media/readme/lanyard.webp differ
diff --git a/docs/media/readme/phone-artifact.webp b/docs/media/readme/phone-artifact.webp
new file mode 100644
index 0000000..c4deff8
Binary files /dev/null and b/docs/media/readme/phone-artifact.webp differ
diff --git a/docs/media/readme/phone-card.webp b/docs/media/readme/phone-card.webp
new file mode 100644
index 0000000..4650d22
Binary files /dev/null and b/docs/media/readme/phone-card.webp differ
diff --git a/docs/media/readme/phone-conversation.webp b/docs/media/readme/phone-conversation.webp
new file mode 100644
index 0000000..701bd97
Binary files /dev/null and b/docs/media/readme/phone-conversation.webp differ
diff --git a/docs/media/readme/stand.webp b/docs/media/readme/stand.webp
new file mode 100644
index 0000000..7550c31
Binary files /dev/null and b/docs/media/readme/stand.webp differ
diff --git a/docs/media/readme/watch-noodle.webp b/docs/media/readme/watch-noodle.webp
new file mode 100644
index 0000000..4542846
Binary files /dev/null and b/docs/media/readme/watch-noodle.webp differ
diff --git a/docs/media/readme/watch-ray.webp b/docs/media/readme/watch-ray.webp
new file mode 100644
index 0000000..e032446
Binary files /dev/null and b/docs/media/readme/watch-ray.webp differ
diff --git a/docs/media/readme/widget-agents.webp b/docs/media/readme/widget-agents.webp
new file mode 100644
index 0000000..4e3c5c2
Binary files /dev/null and b/docs/media/readme/widget-agents.webp differ
diff --git a/docs/media/readme/widget-asking.webp b/docs/media/readme/widget-asking.webp
new file mode 100644
index 0000000..df3e229
Binary files /dev/null and b/docs/media/readme/widget-asking.webp differ
diff --git a/docs/media/readme/wordmark-dark.svg b/docs/media/readme/wordmark-dark.svg
new file mode 100644
index 0000000..8d2288f
--- /dev/null
+++ b/docs/media/readme/wordmark-dark.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2097 794"><path fill="#111111" fill-rule="evenodd" d="M677.0 710.4C675.6 710.2 671.8 709.5 668.5 708.9C646.3 704.9 636.5 688.2 631.0 645.4C628.8 627.5 628.1 561.0 630.0 537.5C631.4 519.8 632.4 485.0 631.6 480.7C629.9 471.7 621.5 468.1 614.5 473.4C607.1 479.1 594.2 510.1 581.0 554.3C573.4 579.3 550.1 652.0 545.3 665.5C534.0 697.3 522.5 709.0 502.6 709.0C482.3 708.9 468.6 701.0 461.0 684.9C456.1 674.4 455.7 669.9 456.4 634.5C457.0 609.0 456.8 599.7 455.6 588.5C453.6 570.3 453.6 551.7 455.6 536.0C457.3 523.5 457.3 523.5 454.7 511.0C449.5 486.7 449.1 476.6 450.1 399.0C450.7 354.3 452.6 327.1 458.5 276.9C461.6 251.6 461.7 239.5 459.0 226.4C454.7 205.6 455.3 191.5 461.6 166.5C463.6 158.8 466.1 145.8 467.2 137.5C474.0 86.3 496.8 71.3 545.0 86.6C566.3 93.3 566.8 96.0 561.0 177.5C560.0 192.2 555.8 270.6 554.0 309.0C553.4 321.4 551.8 345.7 550.5 363.0C547.4 401.2 548.1 407.2 555.7 410.1C563.4 413.0 569.1 407.3 584.3 381.9C609.2 340.2 627.0 318.4 642.1 311.5C665.0 301.1 701.3 311.5 722.9 334.6C737.1 349.8 738.1 356.8 732.6 403.5C716.6 537.6 714.6 595.6 724.1 650.0C729.0 678.2 727.6 688.5 717.3 698.8C708.2 707.8 690.9 712.8 677.0 710.4ZM1846.0 699.4C1809.9 694.8 1776.7 677.2 1761.4 654.6C1749.3 636.8 1746.5 587.5 1756.5 570.4C1765.9 554.4 1788.7 547.3 1802.1 556.3C1806.9 559.5 1810.1 566.1 1815.9 585.3C1828.5 626.6 1838.0 638.2 1860.6 639.7C1881.9 641.1 1894.0 629.6 1894.0 608.1C1893.9 582.1 1878.4 558.7 1839.0 525.5C1808.5 499.7 1775.7 461.0 1765.4 438.5C1754.7 415.0 1754.2 381.7 1764.2 355.6C1772.1 335.1 1792.7 313.2 1812.4 304.5C1840.2 292.2 1888.3 294.0 1919.6 308.5C1967.8 330.7 2002.0 401.8 1979.7 433.4C1970.0 447.1 1931.8 441.9 1911.8 424.0C1903.7 416.8 1899.8 411.0 1890.4 392.2C1885.8 383.0 1881.3 374.6 1880.3 373.5C1868.4 360.2 1853.9 368.4 1854.0 388.4C1854.1 415.3 1868.1 440.6 1908.3 486.4C1966.7 552.9 1987.3 594.4 1979.9 630.2C1974.1 658.1 1935.7 688.4 1895.2 697.0C1885.7 699.1 1855.1 700.5 1846.0 699.4ZM252.5 695.3C245.5 694.2 215.2 686.8 211.6 685.4C209.4 684.6 203.5 681.5 198.6 678.6C193.6 675.6 186.3 671.5 182.5 669.5C178.1 667.0 173.5 663.5 170.0 659.6C167.0 656.3 160.6 649.7 155.9 645.0C146.4 635.5 143.7 631.0 136.5 612.6C129.0 593.5 127.0 585.1 125.9 568.7C125.4 560.6 123.0 540.8 120.5 524.6C115.0 488.6 114.8 481.4 119.0 462.8C120.6 455.5 122.6 445.0 123.5 439.5C124.9 430.7 128.4 417.5 135.2 396.0C140.8 378.5 156.1 349.5 166.8 336.0C191.9 304.5 196.6 302.0 234.2 299.0C269.6 296.2 304.9 305.8 322.1 323.0C345.6 346.5 365.0 430.0 354.4 462.2C350.0 475.5 319.7 487.7 304.9 482.1C295.1 478.4 282.6 465.2 275.5 451.1C269.6 439.3 269.6 439.2 269.5 414.5C269.5 387.4 267.6 380.9 258.2 374.9C236.2 360.9 222.4 391.2 215.9 467.8C211.3 522.4 219.6 568.1 240.6 603.7C259.3 635.4 275.4 633.5 298.3 596.7C310.9 576.4 320.0 569.8 336.0 569.6C356.5 569.4 363.1 589.4 352.2 619.0C340.2 651.6 332.5 665.0 318.1 678.3C306.9 688.8 270.3 698.3 252.5 695.3ZM947.9 685.1C943.2 684.1 932.6 681.2 924.4 678.7C916.2 676.2 905.0 673.0 899.5 671.5C874.3 665.0 865.9 660.9 854.3 649.5C835.5 631.0 834.9 621.9 846.0 521.0C847.6 506.4 849.4 485.3 850.0 474.0C850.6 462.7 851.7 447.2 852.5 439.5C853.3 431.8 854.6 416.9 855.5 406.3C859.8 352.1 870.5 332.5 899.7 325.3C910.9 322.6 925.7 323.0 936.0 326.4C967.2 336.7 971.9 344.5 964.6 373.2C957.7 400.3 949.4 442.8 945.0 473.5C943.9 481.2 941.9 494.2 940.5 502.5C939.2 510.8 937.8 521.1 937.5 525.5C937.2 529.9 936.2 539.5 935.3 546.9C931.3 581.8 935.7 597.0 949.8 597.0C963.1 597.0 972.8 584.1 980.9 555.5C985.2 540.2 988.1 532.0 996.0 513.0C998.8 506.1 1002.9 493.9 1005.0 485.8C1007.2 477.7 1010.3 466.5 1011.9 460.8C1014.8 450.7 1015.8 445.5 1018.0 427.6C1020.8 404.9 1029.1 379.1 1045.9 340.4C1058.1 312.3 1069.5 303.1 1090.4 304.2C1111.7 305.4 1117.9 317.6 1117.1 357.0C1116.7 374.3 1116.7 377.3 1117.3 422.5C1117.6 446.3 1118.3 459.5 1119.9 474.0C1121.1 484.7 1122.5 502.7 1123.0 514.0C1125.5 568.7 1132.3 602.0 1149.5 643.3C1155.4 657.5 1154.4 668.0 1146.4 674.9C1138.1 682.3 1105.5 684.2 1088.2 678.5C1069.6 672.3 1062.7 663.2 1054.9 634.8C1050.7 619.2 1046.2 612.1 1039.3 610.4C1032.2 608.6 1027.9 612.8 1017.9 631.7C997.4 670.6 992.2 677.8 980.0 684.0C973.7 687.2 959.8 687.7 947.9 685.1ZM1282.6 673.6C1272.2 669.7 1268.5 663.2 1256.6 628.4C1246.4 598.6 1243.7 588.5 1242.0 574.4C1241.5 569.5 1240.1 557.7 1239.0 548.1C1237.0 531.1 1235.8 511.8 1234.0 468.0C1233.6 456.2 1232.4 438.9 1231.5 429.5C1228.4 398.9 1231.1 348.7 1236.6 332.5C1239.2 324.9 1248.4 316.4 1260.6 310.3C1275.9 302.7 1298.1 303.4 1307.3 311.8C1314.6 318.4 1317.5 336.8 1321.1 401.5C1322.5 426.9 1325.1 434.0 1333.0 434.0C1339.4 434.0 1343.0 428.5 1350.5 407.0C1360.2 379.6 1379.5 339.2 1387.1 330.7C1396.7 319.8 1405.7 318.9 1427.2 326.9C1432.8 329.1 1444.1 332.2 1452.1 333.9C1486.8 341.2 1490.2 344.9 1489.9 375.6C1489.6 396.6 1492.0 403.1 1499.9 403.0C1506.3 402.9 1509.1 399.4 1517.4 381.3C1541.6 328.8 1564.6 313.7 1603.0 325.4C1632.5 334.3 1635.8 338.3 1637.1 367.0C1638.0 386.9 1638.1 387.8 1641.5 424.5C1644.8 459.0 1647.0 478.1 1647.8 479.4C1648.2 480.0 1648.8 493.6 1649.1 509.5C1649.6 535.6 1650.0 539.6 1652.3 550.0C1653.7 556.3 1655.3 565.8 1656.0 571.0C1656.6 576.2 1658.7 591.8 1660.7 605.5C1666.6 647.3 1664.7 657.2 1650.0 663.9C1641.1 668.0 1632.5 666.6 1611.4 657.6C1596.3 651.2 1587.4 642.6 1579.2 626.4C1574.2 616.6 1569.1 585.9 1563.5 533.0C1561.2 511.5 1547.6 508.3 1539.1 527.2C1537.5 530.7 1529.2 555.5 1520.6 582.4C1512.0 609.2 1503.8 633.5 1502.3 636.4C1495.5 650.0 1488.3 654.7 1472.2 656.1C1466.3 656.6 1459.1 657.5 1456.1 658.0C1436.2 661.6 1423.3 656.3 1418.0 642.4C1416.1 637.3 1415.7 633.5 1414.9 614.5C1414.4 602.4 1413.8 591.4 1413.4 590.0C1413.1 588.6 1412.5 570.4 1412.1 549.5C1411.4 516.4 1411.1 510.9 1409.5 507.2C1405.1 496.5 1395.4 496.3 1389.8 506.7C1386.0 513.7 1383.9 520.1 1364.5 582.6C1342.5 653.5 1340.6 657.8 1327.8 666.0C1317.0 673.0 1292.2 677.2 1282.6 673.6Z"/></svg>
\ No newline at end of file
diff --git a/docs/media/readme/wordmark-light.svg b/docs/media/readme/wordmark-light.svg
new file mode 100644
index 0000000..57e3269
--- /dev/null
+++ b/docs/media/readme/wordmark-light.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2097 794"><path fill="#ECECEC" fill-rule="evenodd" d="M677.0 710.4C675.6 710.2 671.8 709.5 668.5 708.9C646.3 704.9 636.5 688.2 631.0 645.4C628.8 627.5 628.1 561.0 630.0 537.5C631.4 519.8 632.4 485.0 631.6 480.7C629.9 471.7 621.5 468.1 614.5 473.4C607.1 479.1 594.2 510.1 581.0 554.3C573.4 579.3 550.1 652.0 545.3 665.5C534.0 697.3 522.5 709.0 502.6 709.0C482.3 708.9 468.6 701.0 461.0 684.9C456.1 674.4 455.7 669.9 456.4 634.5C457.0 609.0 456.8 599.7 455.6 588.5C453.6 570.3 453.6 551.7 455.6 536.0C457.3 523.5 457.3 523.5 454.7 511.0C449.5 486.7 449.1 476.6 450.1 399.0C450.7 354.3 452.6 327.1 458.5 276.9C461.6 251.6 461.7 239.5 459.0 226.4C454.7 205.6 455.3 191.5 461.6 166.5C463.6 158.8 466.1 145.8 467.2 137.5C474.0 86.3 496.8 71.3 545.0 86.6C566.3 93.3 566.8 96.0 561.0 177.5C560.0 192.2 555.8 270.6 554.0 309.0C553.4 321.4 551.8 345.7 550.5 363.0C547.4 401.2 548.1 407.2 555.7 410.1C563.4 413.0 569.1 407.3 584.3 381.9C609.2 340.2 627.0 318.4 642.1 311.5C665.0 301.1 701.3 311.5 722.9 334.6C737.1 349.8 738.1 356.8 732.6 403.5C716.6 537.6 714.6 595.6 724.1 650.0C729.0 678.2 727.6 688.5 717.3 698.8C708.2 707.8 690.9 712.8 677.0 710.4ZM1846.0 699.4C1809.9 694.8 1776.7 677.2 1761.4 654.6C1749.3 636.8 1746.5 587.5 1756.5 570.4C1765.9 554.4 1788.7 547.3 1802.1 556.3C1806.9 559.5 1810.1 566.1 1815.9 585.3C1828.5 626.6 1838.0 638.2 1860.6 639.7C1881.9 641.1 1894.0 629.6 1894.0 608.1C1893.9 582.1 1878.4 558.7 1839.0 525.5C1808.5 499.7 1775.7 461.0 1765.4 438.5C1754.7 415.0 1754.2 381.7 1764.2 355.6C1772.1 335.1 1792.7 313.2 1812.4 304.5C1840.2 292.2 1888.3 294.0 1919.6 308.5C1967.8 330.7 2002.0 401.8 1979.7 433.4C1970.0 447.1 1931.8 441.9 1911.8 424.0C1903.7 416.8 1899.8 411.0 1890.4 392.2C1885.8 383.0 1881.3 374.6 1880.3 373.5C1868.4 360.2 1853.9 368.4 1854.0 388.4C1854.1 415.3 1868.1 440.6 1908.3 486.4C1966.7 552.9 1987.3 594.4 1979.9 630.2C1974.1 658.1 1935.7 688.4 1895.2 697.0C1885.7 699.1 1855.1 700.5 1846.0 699.4ZM252.5 695.3C245.5 694.2 215.2 686.8 211.6 685.4C209.4 684.6 203.5 681.5 198.6 678.6C193.6 675.6 186.3 671.5 182.5 669.5C178.1 667.0 173.5 663.5 170.0 659.6C167.0 656.3 160.6 649.7 155.9 645.0C146.4 635.5 143.7 631.0 136.5 612.6C129.0 593.5 127.0 585.1 125.9 568.7C125.4 560.6 123.0 540.8 120.5 524.6C115.0 488.6 114.8 481.4 119.0 462.8C120.6 455.5 122.6 445.0 123.5 439.5C124.9 430.7 128.4 417.5 135.2 396.0C140.8 378.5 156.1 349.5 166.8 336.0C191.9 304.5 196.6 302.0 234.2 299.0C269.6 296.2 304.9 305.8 322.1 323.0C345.6 346.5 365.0 430.0 354.4 462.2C350.0 475.5 319.7 487.7 304.9 482.1C295.1 478.4 282.6 465.2 275.5 451.1C269.6 439.3 269.6 439.2 269.5 414.5C269.5 387.4 267.6 380.9 258.2 374.9C236.2 360.9 222.4 391.2 215.9 467.8C211.3 522.4 219.6 568.1 240.6 603.7C259.3 635.4 275.4 633.5 298.3 596.7C310.9 576.4 320.0 569.8 336.0 569.6C356.5 569.4 363.1 589.4 352.2 619.0C340.2 651.6 332.5 665.0 318.1 678.3C306.9 688.8 270.3 698.3 252.5 695.3ZM947.9 685.1C943.2 684.1 932.6 681.2 924.4 678.7C916.2 676.2 905.0 673.0 899.5 671.5C874.3 665.0 865.9 660.9 854.3 649.5C835.5 631.0 834.9 621.9 846.0 521.0C847.6 506.4 849.4 485.3 850.0 474.0C850.6 462.7 851.7 447.2 852.5 439.5C853.3 431.8 854.6 416.9 855.5 406.3C859.8 352.1 870.5 332.5 899.7 325.3C910.9 322.6 925.7 323.0 936.0 326.4C967.2 336.7 971.9 344.5 964.6 373.2C957.7 400.3 949.4 442.8 945.0 473.5C943.9 481.2 941.9 494.2 940.5 502.5C939.2 510.8 937.8 521.1 937.5 525.5C937.2 529.9 936.2 539.5 935.3 546.9C931.3 581.8 935.7 597.0 949.8 597.0C963.1 597.0 972.8 584.1 980.9 555.5C985.2 540.2 988.1 532.0 996.0 513.0C998.8 506.1 1002.9 493.9 1005.0 485.8C1007.2 477.7 1010.3 466.5 1011.9 460.8C1014.8 450.7 1015.8 445.5 1018.0 427.6C1020.8 404.9 1029.1 379.1 1045.9 340.4C1058.1 312.3 1069.5 303.1 1090.4 304.2C1111.7 305.4 1117.9 317.6 1117.1 357.0C1116.7 374.3 1116.7 377.3 1117.3 422.5C1117.6 446.3 1118.3 459.5 1119.9 474.0C1121.1 484.7 1122.5 502.7 1123.0 514.0C1125.5 568.7 1132.3 602.0 1149.5 643.3C1155.4 657.5 1154.4 668.0 1146.4 674.9C1138.1 682.3 1105.5 684.2 1088.2 678.5C1069.6 672.3 1062.7 663.2 1054.9 634.8C1050.7 619.2 1046.2 612.1 1039.3 610.4C1032.2 608.6 1027.9 612.8 1017.9 631.7C997.4 670.6 992.2 677.8 980.0 684.0C973.7 687.2 959.8 687.7 947.9 685.1ZM1282.6 673.6C1272.2 669.7 1268.5 663.2 1256.6 628.4C1246.4 598.6 1243.7 588.5 1242.0 574.4C1241.5 569.5 1240.1 557.7 1239.0 548.1C1237.0 531.1 1235.8 511.8 1234.0 468.0C1233.6 456.2 1232.4 438.9 1231.5 429.5C1228.4 398.9 1231.1 348.7 1236.6 332.5C1239.2 324.9 1248.4 316.4 1260.6 310.3C1275.9 302.7 1298.1 303.4 1307.3 311.8C1314.6 318.4 1317.5 336.8 1321.1 401.5C1322.5 426.9 1325.1 434.0 1333.0 434.0C1339.4 434.0 1343.0 428.5 1350.5 407.0C1360.2 379.6 1379.5 339.2 1387.1 330.7C1396.7 319.8 1405.7 318.9 1427.2 326.9C1432.8 329.1 1444.1 332.2 1452.1 333.9C1486.8 341.2 1490.2 344.9 1489.9 375.6C1489.6 396.6 1492.0 403.1 1499.9 403.0C1506.3 402.9 1509.1 399.4 1517.4 381.3C1541.6 328.8 1564.6 313.7 1603.0 325.4C1632.5 334.3 1635.8 338.3 1637.1 367.0C1638.0 386.9 1638.1 387.8 1641.5 424.5C1644.8 459.0 1647.0 478.1 1647.8 479.4C1648.2 480.0 1648.8 493.6 1649.1 509.5C1649.6 535.6 1650.0 539.6 1652.3 550.0C1653.7 556.3 1655.3 565.8 1656.0 571.0C1656.6 576.2 1658.7 591.8 1660.7 605.5C1666.6 647.3 1664.7 657.2 1650.0 663.9C1641.1 668.0 1632.5 666.6 1611.4 657.6C1596.3 651.2 1587.4 642.6 1579.2 626.4C1574.2 616.6 1569.1 585.9 1563.5 533.0C1561.2 511.5 1547.6 508.3 1539.1 527.2C1537.5 530.7 1529.2 555.5 1520.6 582.4C1512.0 609.2 1503.8 633.5 1502.3 636.4C1495.5 650.0 1488.3 654.7 1472.2 656.1C1466.3 656.6 1459.1 657.5 1456.1 658.0C1436.2 661.6 1423.3 656.3 1418.0 642.4C1416.1 637.3 1415.7 633.5 1414.9 614.5C1414.4 602.4 1413.8 591.4 1413.4 590.0C1413.1 588.6 1412.5 570.4 1412.1 549.5C1411.4 516.4 1411.1 510.9 1409.5 507.2C1405.1 496.5 1395.4 496.3 1389.8 506.7C1386.0 513.7 1383.9 520.1 1364.5 582.6C1342.5 653.5 1340.6 657.8 1327.8 666.0C1317.0 673.0 1292.2 677.2 1282.6 673.6Z"/></svg>
\ No newline at end of file
diff --git a/docs/media/watch-case.png b/docs/media/watch-case.png
new file mode 100644
index 0000000..a3e62b4
Binary files /dev/null and b/docs/media/watch-case.png differ
diff --git a/docs/other-agents.md b/docs/other-agents.md
new file mode 100644
index 0000000..0faaa2a
--- /dev/null
+++ b/docs/other-agents.md
@@ -0,0 +1,255 @@
+# Codex (and other agents)
+
+Chums started as a remote for Claude Code. An agent can now also run on **OpenAI Codex**, and gets the same things on
+the watch:
+
+- live status: working, idle, waiting for you, blocked, limited, compacting;
+- tool calls as events;
+- spoken orders in;
+- short spoken replies out;
+- approvals answered on the watch.
+
+Supported: **Claude Code and Codex.** GitHub Copilot and other Agent Client Protocol (ACP) agents also run, but they
+are **experimental**: built and tried once, not part of what Chums claims to support (see the end).
+
+Checked on 2026-10-10 with Codex CLI 0.160.0 (model `gpt-6-astra`).
+
+## The decision
+
+Codex is driven through **`codex app-server`**, OpenAI's own JSON-RPC protocol. It is the one Codex's IDE extension,
+desktop app and `--remote` terminal use. The hub is a client of it, and runs the agent's app-server itself
+(`hub/runtimes.mjs`). Claude Code keeps its own path: an interactive session in a terminal, with the channel and hooks.
+
+| Runtime | What runs it | Protocol | Status |
+| --- | --- | --- | --- |
+| `claude` (default) | `claude` in its own terminal (LaunchAgent, `bin/chums-agents`) | Claude Code channel + 15 hooks | supported (channels are a research preview) |
+| `codex` | the hub: `codex app-server --listen unix://…`, one per agent | Codex app-server JSON-RPC (WebSocket on a Unix socket) | supported. The CLI labels the app-server `[experimental]`. |
+| `copilot` | the hub, through `@github/copilot-sdk` | Copilot SDK JSON-RPC | experimental |
+| `acp` | the hub: any `command` that speaks ACP on stdio | Agent Client Protocol v1 | experimental |
+
+The hub turns Codex's events into Claude Code's hook vocabulary (`UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
+`Stop`, `StopFailure`, `PreCompact`, `SubagentStart`…), and Codex's tools into Claude Code's tool names (`Bash`,
+`Read`, `Edit`, `Grep`…). So the hub's status logic (`onHook`), the watch's tool events, and approval-card summaries
+are the same code for both.
+
+### Why the app-server
+
+Codex has five first-party surfaces. Only the app-server does all five jobs.
+
+| Surface | Status | Tool events | Approvals | Orders in | Replies out | Stability |
+| --- | --- | --- | --- | --- | --- | --- |
+| **app-server** (chosen) | `turn/*`, `thread/status/changed` (`waitingOnApproval`) | `item/started`, `item/completed` (commands, file changes, MCP, web search, compaction, subagents) | `item/commandExecution/requestApproval`, `item/fileChange/requestApproval`, `item/permissions/requestApproval`, answered by the client | `turn/start`, and `turn/steer` mid-turn | `agentMessage` `final_answer`, or the Chums MCP tool | `[experimental]` label, but it is what OpenAI's own Codex clients use |
+| Codex SDK (`@openai/codex-sdk`) | per run | `item.*` while streaming | none: a fixed `approvalPolicy`, no callback | a new `codex exec` per turn | `finalResponse` | It wraps `codex exec --experimental-json`, so it can't ask the watch. |
+| `codex exec --json` | per run | yes | none | one-shot | yes | Same limits as the SDK. |
+| hooks (`hooks.json`) + `notify` | yes, from an interactive session | `PreToolUse`, `PostToolUse` | a `PermissionRequest` hook can answer | **none**: nothing can put a prompt into a running terminal session, and Codex has no equivalent of Claude Code's channels | `Stop` carries the last message | Hooks need trust per hash. Only one `notify` program is allowed, and you may already have one. |
+| `codex mcp-server` | | | | | | Removed (it isn't in 0.160). |
+| ACP | | | | | | Codex has no native ACP. `@agentclientprotocol/codex-acp` wraps the app-server in a process of its own, which takes the thread's writer lock, so a Codex terminal can't share the thread. |
+
+Codex Remote / `codex remote-control` is OpenAI's channel to the ChatGPT apps, not an API. "Sign in with ChatGPT",
+the Apps SDK and AgentKit are for building apps on OpenAI's cloud; none of them drives a local Codex agent.
+
+### What works, tested against the real Codex (`node tools/e2e-runtimes.mjs codex`: 26 checks, all passing)
+
+- **It starts with the hub and shows on the watch as idle.**
+ - Its thread is kept in agents.json (`sessionId`).
+ - The thread is named "Chums: <agent>" in Codex's own lists.
+- **A question gets a spoken answer.**
+- **Commands ask on the watch.** Two runs:
+ - In the e2e (`approvalPolicy: "untrusted"`) a command shows an approval card with the command itself. "Yes" runs
+ it. "No" declines it: the command doesn't run, and the agent goes on and says so.
+ - With the default policy (`on-request`, `workspace-write` sandbox), it writes in its folder without asking. A
+ network call failed in the sandbox, so it asked to run it outside; the card carried its reason ("May I allow curl
+ network access…"), and on yes it ran.
+- **Tool calls are watch events in Claude Code's words.**
+ - Commands are `Bash …` (or `Read`, `Grep` when Codex parses them that way), and failures are marked.
+ - Patches are `Write notes.txt` / `Edit …`.
+- **Replies.**
+ - `chums_reply` (the Chums MCP server) speaks on the watch.
+ - When a turn from the watch ends without it, the hub speaks the first sentence of Codex's final answer (no
+ markdown, links or paths, 15 words at most; to an order from the iPhone, whole sentences up to 60 words).
+ - In the last run, 6 of 9 replies were Codex's own `chums_reply`.
+- **`chums_show` puts a picture on the watch.** It wrote an SVG and showed it; the watch fetched the thumbnail.
+- **An order said while it works joins the turn** (`turn/steer`): one turn, and both questions answered.
+- **`bin/chums-codex <id>` opens a Codex terminal on the agent's thread,** live, while the watch stays connected (see
+ below).
+- **When its app-server dies,** the agent goes offline, starts again in 5 s, resumes the same thread, and remembers
+ the conversation.
+- **When the hub is killed hard,** the next hub stops the app-server the old one left, resumes the thread, and
+ remembers.
+- **The status sequence the watch saw:** idle → working → waiting → working → idle, offline and back.
+
+Tested against a stand-in app-server only (`tools/test-runtimes.mjs`; these don't happen on demand):
+
+- a usage limit → `limited`;
+- compaction → `compacting`, and the soul is sent again;
+- a card answered in a Codex terminal → the card leaves the watch;
+- a file-change approval → the card says "edit a.js".
+
+Mapped from the protocol but never seen:
+
+- `item/permissions/requestApproval`;
+- subagents (`collabAgentToolCall`, `subAgentActivity`);
+- `item/tool/requestUserInput` (an experimental API Chums doesn't opt into): its question would be said on the watch,
+ and the next thing you say is the answer.
+
+### What to know before claiming it (the limits)
+
+- **On the Mac, a Codex terminal, not the apps.**
+ - Claude Code agents also show in the Claude app (Remote Control). A Codex agent shows live only in a Codex terminal
+ (`bin/chums-codex`).
+ - ChatGPT's Codex and the IDE extension list its thread, but can't continue it while the hub runs it (see below).
+- **The app-server is labelled experimental by OpenAI,** and its methods can change between Codex releases.
+ - Chums was written against 0.160's own generated schema (`codex app-server generate-ts`).
+ - After updating Codex, run `node tools/e2e-runtimes.mjs codex`.
+- **Codex's default model may not be on your plan.** Pick another under Model on the agent's card on the iPhone, or set
+ `"model"` (`gpt-6-astra` works on Plus).
+- **Approvals follow Codex's policy.**
+ - The default `on-request` + `workspace-write`: it works freely in its folder (and `addDirs`) and asks to leave
+ the sandbox (network, other folders).
+ - `untrusted` asks for nearly every command.
+ - "Yes" is always accept-once, never "for the session".
+- **Its replies are sometimes its final answer, said by the hub, not a `chums_reply`.** The line is then cut to its
+ first sentence, so a long answer is shortened, not summarized.
+- **A turn typed in a Codex terminal** shows its status and tool calls on the watch, but isn't spoken there: it isn't
+ the watch's turn.
+- **Not covered:**
+ - interrupting from the watch (as with Claude Code);
+ - the watch shows no Codex plan or todo list;
+ - permission-mode badges (planned for all agents, see `design/STATES.md`).
+- **`chums_show` screenshots** come from a process the hub started, so macOS asks for Screen Recording for Chums
+ when the hub runs as a LaunchAgent (`bin/chums-setup --launchd`, see
+ [Permissions on the Mac](setup.md#permissions-on-the-mac)), or for the terminal app that runs `bin/chums-hub`. The
+ e2e showed a file, not a screenshot.
+
+## Seeing a Codex agent on your Mac
+
+**A terminal: `bin/chums-codex <id>`** (also `bin/chums-agents open <id>`; with one Codex agent the id can be left out).
+
+- It runs `codex resume <thread> --remote unix://<socket>`: Codex's own terminal UI, connected to the app-server the
+ hub runs for that agent. Both are clients of one process, so there is no copy and no lock to fight over.
+- Tested end to end (`tools/e2e-runtimes.mjs codex`, the terminal in a pseudo-terminal):
+ - It opens on the conversation so far.
+ - An order said on the watch while it's open shows in it, with the answer, as it happens.
+ - A question typed in it goes to the same agent and is answered there.
+ - The watch shows that turn's status and tool calls, and doesn't speak it: only turns from the watch are spoken on
+ the watch. Codex knows which is which from the `[From the watch]` or `[From the iPhone]` mark the hub puts on their orders.
+ - Quitting the terminal leaves the agent running for the watch.
+ - Approvals show in both, and the first answer wins: answer in the terminal and the watch's card goes (tested with
+ the stand-in; Codex sends the same `serverRequest/resolved` to every client).
+- Like Claude Code agents, Codex agents run in the background and have no window of their own. `chums-codex` is how
+ you look in, from any terminal, as often as you like. Several terminals can be open at once.
+
+**ChatGPT's Codex (desktop app) and the Codex IDE extension:**
+
+- Each runs its own app-server, and they read the same `~/.codex`. The hub's threads are in the list Codex gives its
+ clients by default (`thread/list`, checked here): named "Chums: <agent>", from the agent's folder (Codex records
+ them as IDE-extension threads). The apps' own windows weren't looked at.
+- Opening one shows the conversation up to the last time it was read: it isn't live.
+- Continuing it there fails while the hub runs the agent. Codex allows one writer per thread, and a second app-server
+ gets "thread … already has an active writer" (tested: another app-server can `thread/read` it, not `thread/resume`).
+- To use the thread in the desktop app, stop the hub (or take the agent out of agents.json) first. After that, the
+ watch can't reach the agent until the hub runs it again. There is no handover like `chums-agents open` gives
+ Claude Code agents.
+- Neither app can be pointed at the hub's socket. So the live view is the terminal.
+- The e2e test archives the threads it makes (`codex unarchive <id>` brings one back).
+
+## agents.json
+
+Every character is its own agent, its `id` the character's. `runtime` picks how it runs: Claude Code without it, or
+Codex, switched on the watch (the agent's soul screen, Runs on) or on its card in the iPhone app, which stops one and
+starts the other. The hub fills in `sessionId` (the Codex thread, or the Claude Code session) the first time, and a `cwd` in
+`~/.chums/agents` when there is none, and resumes it after every restart;
+the other runtime's thread (and model) waits in `byRuntime` for a switch back.
+
+```json
+[
+ { "id": "noodle", "name": "Noodle", "character": "noodle", "cwd": "/Users/you/Developer/chums" },
+
+ { "id": "ray", "name": "Ray", "character": "ray", "runtime": "codex",
+ "cwd": "/Users/you/Developer/some-project", "model": "gpt-6-astra",
+ "approvalPolicy": "on-request", "sandbox": "workspace-write",
+ "addDirs": ["/Users/you/Developer/shared"],
+ "guide": "Show what you make on the watch with chums_show." }
+]
+```
+
+| Field | Meaning |
+| --- | --- |
+| `runtime` | `claude` (default), `codex`; experimental: `copilot`, `acp` |
+| `cwd`, `addDirs` | its folder, and other folders it may write to (Codex: the sandbox's writable roots) |
+| `model` | e.g. `gpt-6-astra`; set from the agent's card on the iPhone (Model). Claude Code agents take it too (`opus`, `sonnet`, …) |
+| `permissionMode` | Claude Code agents: how the session asks before acting, set from the watch and the iPhone app: `default` (Asks first: its requests come to the watch and the iPhone as Allow / Deny), `acceptEdits` (Edits on its own), `auto` (Decides on its own). Passed as `--permission-mode`, so it holds when the session is resumed. Without it, `permissions.defaultMode` from `~/.claude/settings.json` is passed the same way |
+| `approvalPolicy` | Codex agents: how it asks before acting, set from the watch and the iPhone app: `untrusted` (Asks first), `on-request` (Asks when it needs to), `never` (Never asks). Without it, `approval_policy` from `~/.codex/config.toml` when it is one of these, else `on-request` |
+| `sandbox` | `read-only`, `workspace-write` (default), `danger-full-access` |
+| `config` | more `-c key=value` overrides for its app-server, e.g. `["model_reasoning_effort=\"high\""]` |
+| `command` | another `codex` to run, e.g. `["/opt/homebrew/bin/codex"]` |
+| `chumsTools` | `false` leaves out the Chums MCP server (the hub then speaks final answers) |
+| `guide` | how to use its tools, added to its standing instructions |
+
+After editing agents.json, restart the hub.
+
+- `bin/chums-agents install` makes LaunchAgents for Claude Code agents only.
+- `status` lists all agents.
+- `open <id>` opens a Claude Code or Codex agent in this terminal (for Codex, the same as `chums-codex <id>`).
+
+## How it works
+
+- **Starting.** `hub/runtimes.mjs`, `startRunners`: one runner per agent with a `runtime`, started with the hub.
+ - It runs `codex app-server --listen unix:///tmp/chums-<uid>/<hub port>-<id>.sock` (a short path: a Unix socket's
+ path has room for 103 bytes), with your real `HOME` and a full `PATH`.
+ - It connects (`hub/jsonrpc.mjs`, a small WebSocket client), then `initialize` and `thread/resume` (or
+ `thread/start`).
+ - Thread settings: the model, `approvalPolicy`, `sandbox`, and the standing instructions as developer instructions
+ (`hub/standing.mjs`: who it is comes with its soul, plus the watch's rules).
+- **Joining the watch.** The runner joins the hub as a session with a `driver`, so `deliver()` hands it orders and
+ verdicts directly instead of a channel's inbox.
+ - An order becomes `turn/start` (or `turn/steer` while a turn runs), with `[From the watch]` (or `[From the iPhone]`) in front. A Codex
+ terminal on the same thread can tell which messages to answer on the watch.
+- **Chums tools.** `-c mcp_servers.chums.*` gives Codex the Chums MCP server (`channel/chums-channel.mjs` with
+ `CHUMS_SESSION`: tools only, bound to this session).
+- **Approvals.** Codex's approval requests become cards. The answer goes back as `accept` / `decline`.
+ `serverRequest/resolved` for a card still up means a Codex terminal answered it, and the card goes.
+- **Restarts and logs.**
+ - When the app-server exits, the agent goes offline and starts again after 5 s, doubling up to 2 min.
+ - `~/.chums/agents/<id>.runtime.json` holds its thread, socket and pid, for `chums-codex` and for stopping an
+ app-server a killed hub left behind.
+ - Log: `~/.chums/agents/<id>.host.log` (`CHUMS_RUNTIME_DEBUG=1` adds every event).
+
+## Tests
+
+```bash
+node tools/test-runtimes.mjs # stand-ins for a Codex app-server and an ACP agent: 70 checks, no model calls
+node tools/e2e-runtimes.mjs codex # the real Codex (gpt-6-astra): 26 checks, about 2.5 min and 14 turns
+```
+
+Both run a private hub with its own `HOME`, ports and agents, never `~/.chums` or the hub on 7717. The e2e uses your
+Codex login.
+
+## Experimental: GitHub Copilot and ACP agents
+
+Built and tried, not part of the claim.
+
+- **`runtime: "copilot"` runs Copilot through GitHub's SDK.** The SDK is GA and first-party: `onPermissionRequest`
+ for approvals, tool events, a system message, and the Chums MCP server.
+ - Its runtime (Copilot 1.0.95, about 130 MB) is an optional dependency, not installed by default:
+ `npm install --no-save @github/copilot-sdk`.
+ - One e2e run (`node tools/e2e-runtimes.mjs copilot`, `gpt-5-mini`) passed on 2026-10-10: answer, approve, deny,
+ `chums_reply` 4 of 4. In that run the model once claimed a denied `rm` had worked.
+ - No terminal view while the hub runs it. Orders said while it works are queued: its "immediate" mode lost one.
+ - Not tested: compaction, subagents, rate limits, the stand-in tests.
+- **`runtime: "acp"` runs any Agent Client Protocol agent from `command`**, e.g. `["copilot", "--acp"]` or
+ `["gemini", "--experimental-acp"]`.
+ - It passes the stand-in tests (`tools/test-runtimes.mjs`).
+ - Tried with `copilot --acp` (1.0.32): answer, approve and deny worked. But that version ignores a session's stdio
+ MCP servers, so there is no `chums_reply`/`chums_show`, and after a denial it ends its turn without a word.
+ - Gemini, `claude-agent-acp` and `codex-acp` are untested.
+
+Copilot's other first-party surfaces don't fit:
+
+- `copilot --acp` is in public preview;
+- hooks can't take orders in;
+- `-p --output-format json` can't ask for approvals;
+- `--remote` is GitHub's own UI.
+
+The research behind these tables is from GitHub's and OpenAI's docs as of 2026-10-10. Hook details (timeouts,
+fail-open) are as documented, not re-tested here.
diff --git a/docs/setup.md b/docs/setup.md
new file mode 100644
index 0000000..ee8ff4e
--- /dev/null
+++ b/docs/setup.md
@@ -0,0 +1,682 @@
+# Setup
+
+This guide goes from a fresh clone to talking to a coding agent from your Apple Watch.
+
+Chums is distributed as source code only. There is no App Store, TestFlight or hosted service:
+
+- you build the watch app in Xcode and sign it with your own Apple ID;
+- the hub runs on your own Mac;
+- Tailscale Funnel gives the hub a public HTTPS address, which is how the watch reaches it from any network.
+
+The first setup takes about 20–30 minutes of your time, plus waiting: Xcode can take 10 minutes or more to prepare a
+device the first time, and a new Funnel address can take up to half an hour to appear in public DNS. Step 5 starts that
+wait early.
+
+`bin/chums-doctor` checks every link of the chain (tools, sign-ins, hub, Funnel, Xcode, the watch) and prints the fix
+for each failure. It changes nothing, so run it whenever something is unclear. Problems and their fixes are in
+[troubleshooting.md](troubleshooting.md).
+
+| Step | What | Who |
+| --- | --- | --- |
+| [1](#1-what-you-need) | What you need | |
+| [2](#2-pick-your-agent) | Pick your agent: Claude Code, Codex, or both | |
+| [3](#3-get-the-code-and-check-the-mac) | Get the code and check the Mac | Terminal |
+| [4](#4-start-the-hub) | Start the hub | Terminal |
+| [5](#5-put-the-hub-on-the-internet-tailscale-funnel) | Put the hub on the internet (Tailscale Funnel) | Terminal, browser |
+| [6](#6-sign-in-to-xcode-with-your-apple-id) | Sign in to Xcode with your Apple ID | Xcode |
+| [7](#7-connect-the-iphone-and-the-watch-to-xcode) | Connect the iPhone and the watch to Xcode | iPhone, watch, Xcode |
+| [8](#8-turn-on-developer-mode) | Turn on Developer Mode on the iPhone and the watch | iPhone, watch |
+| [9](#9-build-and-install-the-apps) | Build and install the apps | Terminal |
+| [10](#10-start-the-agents) | Start the agents | Terminal, watch or iPhone |
+| [11](#11-talk-to-it-from-the-watch) | Talk to it from the watch | Watch |
+
+Optional, after that: [the watch app's settings](#the-watch-apps-settings), [the iPhone app](#the-iphone-app),
+[keyring mode](#keyring-mode), [background agents](#background-agents), [the agents' voices](#the-agents-voices),
+[the Simulator](#no-watch-the-simulator), [settings](#settings), [updating](#updating), [removing Chums](#removing-chums).
+
+## 1. What you need
+
+| What | Minimum | Why | How to get it |
+| --- | --- | --- | --- |
+| A Mac with Apple silicon | macOS 15.6 | Runs the hub, speech to text and the agents, and builds the app. Xcode 26 needs macOS 15.6 | System Settings › General › Software Update |
+| An Apple Watch | watchOS 26 | Runs Chums. watchOS 26 runs on Series 6 or later, SE (2nd generation) or later, and every Ultra | iPhone: Watch app › General › Software Update |
+| The iPhone the watch is paired with | iOS 26 | Xcode reaches the watch through it | Settings › General › Software Update |
+| A USB cable for that iPhone | | The first time, Xcode finds a watch only through its iPhone connected by cable | |
+| One Wi-Fi network for the Mac, the iPhone and the watch | | Xcode installs on the watch over the local network | |
+| Xcode | 26.0 | Builds, signs and installs the watch app | [Mac App Store](https://apps.apple.com/app/xcode/id497799835), then open it once |
+| An Apple ID signed in to Xcode | free or paid | Signs the app. See [Apple Developer account](#apple-developer-account) below | Xcode › Settings › Apple Accounts |
+| Homebrew | | Installs the tools below | [brew.sh](https://brew.sh) |
+| Node.js | 20.11 | Runs the hub and the Claude Code channel | `brew install node` |
+| XcodeGen | | Generates the Xcode project from `app/project.yml` | `brew install xcodegen` |
+| WhisperKit CLI and the Whisper base model (about 150 MB) | | Speech to text, on the Mac | `brew install whisperkit-cli`; `bin/chums-setup` downloads the model |
+| ffmpeg | | Converts each clip from the watch or the iPhone to the WAV that WhisperKit reads, and takes the still of a video shown on the watch | `brew install ffmpeg` |
+| uv (optional) | | Installs the agents' voices (Kokoro) in their own Python. Without it, the watch reads replies in its own voice | `brew install uv` |
+| Tailscale's command-line tools (`tailscale` and `tailscaled`) | 1.52 | Give the hub a public HTTPS address with Funnel | `brew install tailscale` |
+| A Tailscale account | the free Personal plan | Funnel is part of it | [login.tailscale.com/start](https://login.tailscale.com/start) |
+| Claude Code, signed in | a current version (last checked: 2.1.280) | A Claude Code agent. Needs a Pro, Max, Team or Enterprise plan, or a Console API key | `curl -fsSL https://claude.ai/install.sh \| bash`, then run `claude` and `/login` |
+| Codex CLI, signed in | 0.160 | A Codex agent. Signs in with ChatGPT or an API key | `npm install -g @openai/codex` (or `brew install --cask codex`), then `codex login` |
+| python3, git, curl, expect | | The scripts in `bin/` and `tools/`; expect runs the background Claude Code agents | Come with macOS and Xcode |
+
+You need Claude Code or Codex, not both: see step 2.
+
+### Apple Developer account
+
+Any Apple ID can sign Chums. Xcode gives every Apple ID a free **Personal Team**; the paid **Apple Developer Program**
+removes its limits. Chums uses HealthKit (for keyring mode) and background modes, which both kinds of team can sign.
+
+| | Free Personal Team | Apple Developer Program |
+| --- | --- | --- |
+| Cost | Free, with any Apple ID | $99 a year (or the local price) |
+| How long an install works | 7 days. Then Chums doesn't open until you run `bin/chums-install` again | 1 year, the life of the provisioning profile |
+| Devices | 3 registered devices | 100 per device type per membership year |
+| Apps | 3 apps installed per device from free teams | No such limit |
+| App IDs | 10 per 7 days. Each Chums bundle ID uses 4 (iPhone app, its widgets, watch app, watch widget) | No such limit |
+| Sign up | Xcode › Settings › Apple Accounts › + › Apple ID | [developer.apple.com/programs](https://developer.apple.com/programs/enroll/) |
+
+## 2. Pick your agent
+
+Each agent in Chums is one coding session that the watch talks to, and every character is its own agent. An agent
+runs on Claude Code or on Codex, and you can mix them. Every agent starts on Claude Code; you switch one to Codex from
+the watch or the iPhone in step 10.
+
+| | Claude Code | Codex |
+| --- | --- | --- |
+| Install and sign in | `curl -fsSL https://claude.ai/install.sh \| bash`, then `claude` and `/login` | `npm install -g @openai/codex`, then `codex login` |
+| How it connects | The Chums channel and hooks, loaded by `bin/chums-claude` | The hub runs `codex app-server` for it and is its client |
+| Where it runs | In the background (`bin/chums-agents install`), or in a terminal (`bin/chums-agents open <id>`) | Inside the hub, started with it |
+| Where you see it on the Mac | Its terminal, and the Claude app (Remote Control) | A Codex terminal on the same thread: `bin/chums-codex <id>` |
+| In `~/.chums/agents.json` | `"runtime": "claude"`, or no `runtime` | `"runtime": "codex"` |
+| Notes | Channels are a research preview. Team and Enterprise plans: an Owner enables channels (and Remote Control) in the organization's Claude Code settings. Remote Control needs a claude.ai login; with an API key, set `CHUMS_NO_RC=1` (export it before `bin/chums-agents install`, which keeps it for the background agents) | OpenAI labels the app-server experimental; Chums was written against 0.160. If Codex's default model isn't on your plan, set `"model"` |
+
+Changing an agent's soul by voice (its name, what it looks after, its voice) runs `claude -p` on the Mac, so that one
+feature needs Claude Code even when all your agents are Codex agents. A change typed on the iPhone doesn't.
+
+Details on Codex agents: [other-agents.md](other-agents.md).
+
+**How to know it worked:** `claude auth status` prints `"loggedIn": true`, or `codex login status` prints
+`Logged in`. `bin/chums-doctor` shows them under "2. Coding agents".
+
+## 3. Get the code and check the Mac
+
+```bash
+git clone <this repository's URL> chums && cd chums
+bin/chums-setup
+```
+
+`bin/chums-setup` checks macOS, Node.js, the coding agents, WhisperKit, ffmpeg, Tailscale, Xcode and XcodeGen, and prints
+`MISSING` with an install command for each one that isn't there. It also installs the npm packages (`npm ci`),
+downloads the Whisper base model (about 150 MB), and, when uv is installed, installs the agents' voices (Kokoro, about
+1.5 GB: [the agents' voices](#the-agents-voices)). It is safe to run again; run it until it prints `Ready`.
+
+**How to know it worked:** the last line is `Ready. Next: …`. `bin/chums-doctor` shows "1. This Mac" all `PASS`. The
+later sections fail until their steps are done.
+
+## 4. Start the hub
+
+The hub is the Node.js program on your Mac that the watch and the agents talk to.
+
+```bash
+bin/chums-hub
+```
+
+The first start writes `~/.chums/config.json` (ports and two random tokens, see [SECURITY.md](../SECURITY.md)),
+`~/.chums/agents.json` with one agent per character (every character on the watch is its own agent, on Claude Code),
+and each agent's soul in `~/.chums/souls/`. It keeps running in that terminal; leave it open.
+
+To run it in the background instead, started at login and restarted if it stops, first stop the hub in the terminal
+(Ctrl-C), then:
+
+```bash
+bin/chums-setup --launchd # LaunchAgents for the hub and Chums' tailscaled; hub log in ~/.chums/hub.log
+```
+
+As a LaunchAgent (`bin/chums-setup --launchd`), the hub runs under `caffeinate -s`, so the Mac stays awake while it
+is on power; `bin/chums-hub` in a terminal doesn't. On battery, a sleeping Mac is offline for the watch.
+
+**How to know it worked:** the hub prints `Chums hub on 127.0.0.1:7717`, `watch API for the tunnel on 127.0.0.1:7718`
+and, a few seconds later, `whisper warm in … s`. `bin/chums-doctor` shows "4. The hub" with the hub and speech to text
+`PASS` (the agents show as not running until step 10).
+
+## 5. Put the hub on the internet (Tailscale Funnel)
+
+watchOS doesn't support apps reaching an address on your home network
+([TN3135](https://developer.apple.com/documentation/technotes/tn3135-low-level-networking-on-watchos)), so the watch
+reaches the hub through a public HTTPS address. Tailscale Funnel provides it, without opening a port on your router.
+Only the hub's watch side (`127.0.0.1:7718`, paths under `/v1/`, with the watch token) is published. Read
+[SECURITY.md](../SECURITY.md) for what that exposes.
+
+1. Create a Tailscale account at [login.tailscale.com/start](https://login.tailscale.com/start). The free Personal
+ plan includes Funnel.
+2. Install the command-line tools: `brew install tailscale`. Chums runs its own `tailscaled` under your user, without
+ an admin password (userspace networking), with its state in `~/.chums/tailscale`. It doesn't use or change the
+ Tailscale app if you have one; it joins your tailnet as a separate machine named `chums-hub`.
+3. Run:
+
+ ```bash
+ bin/chums-tunnel
+ ```
+
+4. The first time, it prints a sign-in link (`https://login.tailscale.com/a/…`). Open it, sign in, and connect the
+ machine.
+5. If Funnel isn't on for your tailnet yet, it prints a second link (`https://login.tailscale.com/f/funnel?…`) and
+ waits. Open it and approve. That turns on HTTPS certificates for the tailnet and adds the `funnel` node attribute to
+ its access policy, the two things Funnel needs. (By hand: the admin console's DNS page › HTTPS Certificates, and
+ Access controls › the `funnel` node attribute.)
+6. It then publishes `127.0.0.1:7718` at `https://chums-hub.<your tailnet>.ts.net` and stores that URL as `publicURL`
+ in `~/.chums/config.json`. The URL is built into the watch app in step 9.
+
+Tailscale says a new Funnel name can take up to 10 minutes to appear in public DNS; it has taken about 25. The first
+HTTPS request to the name also waits a few seconds while Tailscale gets its certificate. Go on with steps 6–8 meanwhile.
+
+**How to know it worked:** check from outside the Mac's own network.
+
+```bash
+dig +short chums-hub.<your tailnet>.ts.net @1.1.1.1 # prints IP addresses once public DNS has the name
+curl -s https://chums-hub.<your tailnet>.ts.net/v1/ping # prints {"error":"unauthorized"} after about 1 s
+```
+
+`{"error":"unauthorized"}` is the hub refusing a request without the watch token, so Funnel reaches the hub. For a check
+that doesn't go through the Mac at all, open the same `/v1/ping` URL in Safari on your iPhone with Wi-Fi off. Then
+`bin/chums-doctor` shows "5. Tailscale Funnel" all `PASS`, including a request with the watch token through Funnel.
+
+## 6. Sign in to Xcode with your Apple ID
+
+1. Open Xcode once and let it install its components. Accept the license if it asks.
+2. Xcode › Settings › Apple Accounts › + › Apple ID, and sign in. A free Apple ID gets a Personal Team (see
+ [Apple Developer account](#apple-developer-account)).
+
+`bin/chums-install` picks the team itself (`tools/pick-team.py`): a paid team if Xcode has one, else your Personal Team.
+To choose one, add `"team": "<team ID>"` to `~/.chums/config.json` (or set `CHUMS_TEAM`). The team ID is the 10
+characters shown for the team in Xcode › Settings › Apple Accounts.
+
+**How to know it worked:** Xcode › Settings › Apple Accounts lists your Apple ID with a team under it.
+`bin/chums-doctor` shows a `signing team` line under "6. Building the watch app".
+
+## 7. Connect the iPhone and the watch to Xcode
+
+Xcode reaches an Apple Watch only through its paired iPhone, and the first time only through an iPhone connected by
+USB cable. After that, the iPhone and the watch stay known to Xcode, and installs go over Wi-Fi.
+
+1. Open Xcode, then Window › Devices and Simulators.
+2. Connect the iPhone to the Mac with a USB cable and unlock it.
+3. On the iPhone, tap **Trust** on "Trust This Computer?" and enter its passcode.
+4. The iPhone appears in Devices and Simulators. Xcode shows "Preparing iPhone for development" or copies symbols;
+ this can take several minutes. Wait until it finishes.
+5. Unlock the watch and keep it near the iPhone, on the same Wi-Fi network as the Mac. Wear it or put it on its
+ charger, and keep it awake: a locked or sleeping watch drops the connection.
+6. If the watch asks whether to trust this computer, tap **Trust**.
+7. The watch appears in Devices and Simulators, under the iPhone or on its own. "Preparing Apple Watch for development"
+ can take 10 minutes or more the first time. Keep the watch unlocked until it finishes.
+
+**How to know it worked:** Devices and Simulators lists the watch without a warning, and `bin/chums-doctor` shows
+`Apple Watch <name> (watchOS 26.x)` under "7. The Apple Watch". If the watch doesn't appear, see
+[troubleshooting.md](troubleshooting.md#the-watch-isnt-in-xcode).
+
+## 8. Turn on Developer Mode
+
+Both devices need Developer Mode. Each one restarts to turn it on.
+
+**On the iPhone:**
+
+1. Settings › Privacy & Security › Developer Mode (near the bottom). The switch appears after the iPhone has been
+ connected to a Mac with Xcode (step 7).
+2. Turn it on and tap **Restart**.
+3. After the restart, unlock the iPhone, tap **Turn On** in the alert, and enter the passcode.
+
+**On the watch:**
+
+1. On the watch: Settings › Privacy & Security › Developer Mode. The switch appears after Xcode has seen the watch
+ (step 7).
+2. Turn it on. The watch asks to restart: restart it from that prompt. (Restarting it another way can make the switch
+ disappear again.)
+3. After the restart, unlock the watch and confirm **Turn On**.
+
+If the watch's switch isn't there:
+
+1. The switch appears once Xcode lists the watch. Connect the iPhone by USB, unlock both devices, tap **Trust** on the
+ watch if it asks, and keep Window › Devices and Simulators open until the watch is listed. Then look again.
+2. Still missing? `tools/watch_devmode.py reveal` asks the watch to show it, through the iPhone on USB. It needs
+ [pymobiledevice3](https://github.com/doronz88/pymobiledevice3) (GPL-3.0, not part of Chums) and both devices'
+ UDIDs, which `xcrun xctrace list devices` shows:
+
+ ```bash
+ python3 -m venv ~/.chums/venv && ~/.chums/venv/bin/pip install pymobiledevice3
+ CHUMS_PHONE_UDID=<iPhone UDID> CHUMS_WATCH_UDID=<watch UDID> ~/.chums/venv/bin/python tools/watch_devmode.py reveal
+ ```
+
+ Then turn the switch on as above, restarting from the watch's own prompt.
+
+**How to know it worked:** `bin/chums-doctor` shows `Apple Watch <name> …: paired with this Mac, Developer Mode on`,
+and lists the iPhone with `Developer Mode enabled`.
+
+## 9. Build and install the apps
+
+```bash
+bin/chums-install
+```
+
+What it does:
+
+1. Finds the watch with `xcrun devicectl list devices`, and stops with instructions if Xcode doesn't know one or its
+ Developer Mode is off. It also finds the iPhone, for the iPhone app.
+2. Writes `app/ChumsWatch/HubConfig.swift` from `~/.chums/config.json`: the public URL and the watch token
+ (`tools/gen-config.sh`). The file is git-ignored; never commit it or share a built app, since the token can be read
+ from it.
+3. Picks the signing team (`tools/pick-team.py`): `"team"` in config.json or `CHUMS_TEAM` if set, else a paid team in
+ Xcode, else your free Personal Team.
+4. Picks the bundle ID: `"bundleId"` in config.json or `CHUMS_BUNDLE` if set, else `dev.chums.<team ID>` (the team
+ ID in lowercase). A bundle ID belongs to the team that registered it first, so the default includes your team's
+ ID. The iPhone app is `<bundle ID>`, its widgets `<bundle ID>.widgets`, the watch app `<bundle ID>.watchkitapp` and
+ the watch's widget `<bundle ID>.watchkitapp.widget`.
+5. Generates the Xcode project with XcodeGen and builds it in Release with automatic signing
+ (`-allowProvisioningUpdates`). The first build takes a few minutes.
+6. Installs the watch app with `xcrun devicectl device install app`. The wireless connection to the watch often drops
+ the first attempt or two, so it tries up to 5 times. Keep the watch unlocked and awake.
+7. Opens Chums on the watch.
+8. Installs the iPhone app on the iPhone (skipped, with a note, when Xcode doesn't know the iPhone or its Developer
+ Mode is off). The watch app is inside it, so it goes on after the watch has its copy.
+
+Keep the bundle ID once Chums is installed: if it changes (another team, or the default changed), the next install is a
+second copy of the app. To pin it, add the one you have to `~/.chums/config.json`:
+
+```json
+"bundleId": "dev.chums.abcde12345"
+```
+
+With a free Personal Team, the install stops working after 7 days; `bin/chums-install` prints the date. Run it again
+before then.
+
+If the build stops at "Your team has no devices from which to generate a provisioning profile", see
+[troubleshooting.md](troubleshooting.md#your-team-has-no-devices).
+
+**How to know it worked:** it prints `Chums is running on the watch.` and `Chums is installed on <your iPhone>.`, and
+the watch shows a character, not "HUB OFFLINE" (it says "NOT RUNNING" until its agent starts in step 10).
+`bin/chums-doctor` shows `the watch app (built …) has the hub's current token and address`.
+
+## 10. Start the agents
+
+Every character on the watch is its own agent. On its first start (step 4) the hub wrote eight to
+`~/.chums/agents.json`, one per character: `noodle`, `stretch`, `peeps`, `squint`, `ray`, `tangle`, `crunch` and
+`nana`. All start on Claude Code, each working in `~/.chums/agents/<id>` with access to your home folder. To give one
+other folders, edit its `cwd` and `addDirs` ([Background agents](#background-agents)).
+
+**Claude Code agents** run in the background, one LaunchAgent each. They run through a small Mac app, Chums.app,
+which this builds, signed with your Apple Development certificate for the same team as the watch app, so it keeps its
+permissions across rebuilds ([why](#permissions-on-the-mac)). Then:
+
+```bash
+bin/chums-agents install
+```
+
+A session's first start shows two screens: trust the folder, and confirm loading the development channel (channels
+are a research preview, so Claude Code asks). `bin/chums-agents` answers both. Each agent takes about 200 MB of memory
+while it waits; `bin/chums-agents stop <id>` stops one you don't use. Then grant the agents their permissions once, at
+the Mac: [Permissions on the Mac](#permissions-on-the-mac).
+
+**Codex agents.** Switch an agent to Codex on the watch (open the agents list, swipe the character's row left (Edit),
+pick **Runs on: Codex**) or on its card in the iPhone app (**Runs on**). The hub stops its Claude Code session and runs
+`codex app-server` for it instead; its soul stays, and each runtime keeps its own thread for when you switch back.
+Codex has to be installed and signed in on the Mac. If you use only Codex, skip `bin/chums-agents install` and switch
+the agents you want; the others show as not running, and `bin/chums-doctor` reports Claude Code as missing while any
+agent is on it. An agent's model and other settings:
+[other-agents.md](other-agents.md#agentsjson). To watch it work or type to it on the Mac: `bin/chums-codex <id>`
+opens a Codex terminal on the same thread.
+
+**One agent in a terminal.** `bin/chums-agents open <id>` takes a Claude Code agent's session into this terminal; it
+goes back to the background when you quit. To start a new session for an agent in another folder, stop its
+LaunchAgent (`bin/chums-agents stop <id>`), then:
+
+```bash
+cd ~/some/project && /path/to/chums/bin/chums-claude <id>
+```
+
+`<id>` is one of the ids above: the watch and the iPhone talk only to the agents in `agents.json`, and a session is an
+agent's when its name is the agent's id. `bin/chums-claude` adds the Chums channel and hooks, keeps Remote Control on
+(`CHUMS_NO_RC=1` turns it off), keeps the project's own `.mcp.json`, and lets the session call `chums_reply` and read
+the files you send from the iPhone (`~/.chums/uploads`) without asking. Its
+first start shows the two screens above; answer them in the terminal.
+
+To restart the hub: Ctrl-C and `bin/chums-hub` in its terminal, or
+`launchctl kickstart -k gui/$UID/dev.chums.hub` when it runs as a LaunchAgent.
+
+**How to know it worked:** `bin/chums-agents status` shows each Claude Code agent `running`. On the watch, tap the
+faces at the top left: the agents are in the list, not marked "Not running on your Mac". `bin/chums-doctor` lists each
+under "4. The hub" as `idle`.
+
+## 11. Talk to it from the watch
+
+1. The first time Chums opens, the watch asks for the microphone, for notifications, and for Health › Workouts:
+ allow all three. Notifications bring approvals, questions and finished work when Chums isn't in front; Workouts is
+ for [keyring mode](#keyring-mode).
+2. Hold the screen anywhere, say what you want, and let go. Slide onto × before letting go to cancel. A clip stops by
+ itself after 30 seconds.
+3. The hub transcribes the clip on the Mac and sends it to the agent on screen (its face is at the top left, in front
+ of the others'). Everything you say goes to that agent; to talk to another one, tap the faces and pick it in the
+ list.
+4. When the agent asks for permission, a card shows the request: hold the card to allow it, or tap × to deny it. You
+ can also say "yes" or "no".
+5. The agent answers in one short sentence, spoken on the watch and kept in the conversation (pull it up from the
+ bottom).
+
+**How to know it worked:** the character goes from listening to thinking to working to done, and you hear the reply.
+The hub logs each clip: `utterance … stt=…ms: "what you said" -> order`.
+
+## The watch app's settings
+
+Tap the faces at the top left; Settings is below the agents list. In that list, press and hold a row, then drag it, to
+change the order.
+
+| Setting | Default | What it does |
+| --- | --- | --- |
+| Voice: read replies aloud | on | Off: replies are text and a tap on the wrist |
+| Watch voice | | The watch's own voice, for replies the Mac doesn't voice ([the agents' voices](#the-agents-voices)). A tap plays a sample |
+| Stay on while held | on | While you hold the watch facing you, the screen stays on, up to 10 minutes without a touch. Put down, it sleeps after 20 seconds |
+| Keyring: stay on | on | [Keyring mode](#keyring-mode) |
+| Demo: play every state | off | The character plays every state in turn |
+
+## The iPhone app
+
+`bin/chums-install` puts it on the iPhone in step 9. It has the same agents, conversations and voices as the watch,
+through the same hub. It talks to the hub only while it is open: an agent that needs you while it is closed shows on
+the widgets and the watch, not as an iPhone notification. Open Chums on the iPhone:
+
+- The screen is for one agent. While its conversation is empty, it stands in the middle in a window the shape of the
+ watch's screen, with its name and what it's doing below, and takes the same touches: tap to poke, stroke to pet,
+ hold to talk. The crown on the window's side turns like the watch's Digital Crown: drag it up or down, or flick it.
+ A two-finger twist on the window turns it too. Tilting or shaking the iPhone moves it, as on the watch.
+- Once there's a conversation, the agent is its last row, at the left, and its newest line arrives right above it;
+ it scrolls with the conversation. Its name is at the top. Beside it, two lines say what it's doing:
+ - at work, the action (Thinking, Looking at your photo, Reading a file, Running tests, Running a command, Searching
+ the web, Running a helper agent, Finishing up), then exactly what on and how long it has been at it: `npm test · 1:04`, `photo-1.jpg ·
+ 0:42`. A command shows alone, in the code face: `npm test` for the hub's "Bash npm test";
+ - otherwise Needs you (with what it asks: "Asks to read photo-1.jpg"), Speaking (a tap stops it), Listening,
+ Sending your photo, Stuck, Rate limited, Not running on your Mac, or Can't reach your Mac;
+ - idle, nothing.
+
+ A tap on the agent brings it to the middle, in front of the conversation; a tap outside it, or a drag down, puts it
+ back. Press and hold it to open its card.
+- The button at the top left shows the other agents' faces. A tap on it, or a swipe in from the left edge, opens all
+ the agents in a panel; a tap outside it or a swipe left closes it. Each tile shows the agent's last line when it is
+ idle, and what it's doing otherwise. A ring around its face: white working, amber needs you or rate limited, red
+ stuck; a dimmed face isn't running. A tap talks to one. Press and hold a tile, then drag it, to change the order.
+- The agent's card opens from a tap on its name at the top, from … on its tile, or from … beside its name when it's in
+ front. Cards slide up from the bottom; drag one down to put it away. On the card:
+ - **Runs on**: Claude Code or Codex. The hub stops the one and starts the other, as Runs on does on the watch
+ ([step 10](#10-start-the-agents)). One that isn't installed on the Mac is dimmed.
+ - **Model**: Claude Code's models (Fable, Opus, Sonnet, Haiku) or the ones Codex lists for your account, after
+ Default (what Claude Code or Codex is set to use on the Mac). The agent restarts on the one you pick, on the same
+ conversation; when it is working, the app asks first.
+ - **Permissions**: how it asks before acting ([what it may do](#what-an-agent-may-do)).
+ - **Voice**: the voice it reads its replies in ([the agents' voices](#the-agents-voices)). A tap plays a sample and
+ picks it.
+ - **Soul**: its name, what it does, what it hands off to which agent, how it talks, and notes. Tap one to edit it,
+ then Save. A typed change is saved as you wrote it, with no model call. "Undo the last change" goes back
+ one.
+- Type a message, or talk: tap the microphone at the right of the box, talk, then ↑ to send or × to throw it away; or
+ hold it while you talk and let go to send (slide left first to cancel). The first tap asks for the microphone; tap
+ again to talk. A tap anywhere else puts the keyboard away.
+- + at the left of the box adds photos (the camera or the library, up to 6 at a time) and files (up to 25 MB each); a
+ tap or a scroll anywhere else closes it. They wait above the box, each with × to take it out, and go to the Mac
+ with your next message, kept in `~/.chums/uploads`. The agent gets their paths and reads them without asking (Claude
+ Code agents may read `~/.chums/uploads`), and a picture of each shows in the conversation: a page, a document, a PDF,
+ text or code, a table, an image, or a still from a video.
+- A reply to what you sent from the iPhone can be a few plain sentences (60 words at most), since the iPhone shows the
+ text; a reply to the watch stays one short line.
+- What an agent shows you opens on a card, live where the iPhone can: an HTML page it made runs (a chart you can
+ drag across, tabs, animations), a web page loads, a PDF scrolls page by page, Markdown, text and tables scroll, a
+ video plays, and Word, Excel, Pages, Keynote and other documents open in Quick Look. Anything else is its picture:
+ pinch and drag to look closer, double-tap to zoom in or out. Drag the card down to close it; Share (top right) sends
+ the original file, or the page's address.
+- Press and hold a message to copy it; on the agent's, Mute replies stops reading replies aloud (and brings it back).
+- When the agent asks for permission, a card shows the request with Allow and Deny. Saying "yes" or "no" answers it
+ too.
+- The dots at the top right open the app's settings: the connection to your Mac (the address, how fast it answers,
+ and Check the connection), reading replies aloud, and haptics. After you've changed the agents' order, a button
+ there puts it back.
+
+A reply is spoken on the device you asked from: the iPhone speaks what you said on the iPhone, the watch what you said
+on the watch. Both show every line.
+
+Widgets (Home Screen: touch and hold, then Edit › Add Widget › Chums. Lock Screen: touch and hold, then Customize):
+
+- **Agent** (small and medium; on the Lock Screen, circular, rectangular and inline): one agent, or, when none is
+ picked (touch and hold the widget › Edit Widget), the agent last talked to from any device or shown in the app. The
+ small one is the watch's screen for that agent, with a microphone in the corner that opens the app listening; when
+ the agent asks for permission, ✕ and ✓ there answer it without opening the app. The medium one adds its name, what
+ it's doing and its last line, with Talk, or Deny and Allow, below them. A tap anywhere else opens the agent.
+- **Agents** (medium, up to 5 agents; large, up to 9): the agents, the ones that need you first. A tap opens that
+ agent. The large one also shows the first open request, with ✕ and Allow.
+
+The widgets refresh every 5 minutes while an agent needs you or is working, otherwise every 15 (iOS can space them
+out more), and when the app changes agents, goes to the background, or sees the hub's state change.
+
+The **Talk to Chums** control opens Chums listening to the agent on screen. Add it in Control Center, on the Lock
+Screen, or to the Action Button (Settings › Action Button › Controls).
+
+Siri and Shortcuts: "Ask Chums" (or "Ask <agent> in Chums") sends what you say to an agent and reads its next line
+back. It waits up to 45 seconds; after that, the answer is in the app. "Talk to Chums" opens the app listening. In
+the Shortcuts app they are the actions Ask an agent and Talk to an agent.
+
+**How to know it worked:** the agent's state shows under its name in the middle (or beside it in the conversation),
+not "Can't reach your Mac", and a typed message gets an answer spoken on the iPhone.
+
+## Keyring mode
+
+Chums can be carried on a keyring instead of worn. Keyring mode ("Keyring: stay on" in the watch app's settings, on by
+default) keeps Chums in front and running: it runs a workout session, the one thing watchOS lets keep an app frontmost
+when the screen dims. No workout is saved to Health or Fitness.
+
+1. Allow Health › Workouts when Chums asks. watchOS asks once. If it was refused, see
+ [troubleshooting.md](troubleshooting.md#keyring-mode-doesnt-stay-on).
+2. On the watch: Settings › Passcode › Wrist Detection off, so it doesn't lock off a wrist.
+3. Settings › General › Return to Clock › Chums › After 1 hour, and Return to App (When in Session) on.
+4. Settings › Display & Brightness › Always On on. For a longer lit screen after a tap: Wake Duration › Wake for 70
+ Seconds.
+5. Add the Chums complication to the watch face, or Chums to the Smart Stack, to open it in one tap.
+
+**How to know it worked:** the screen dims but stays in Chums, and `~/.chums/watch-events.log` on the Mac has
+`keyring running`. A problem shows under the switch in the watch app's settings.
+
+## Background agents
+
+Every character is its own agent, with its own soul, session and conversation: a tap on it in the watch's list
+talks to it. Each Claude Code agent is a session run in the background by a LaunchAgent:
+
+```bash
+bin/chums-agents install # one LaunchAgent per Claude Code agent; run again after editing agents.json
+bin/chums-agents status
+bin/chums-agents open <id> # take one into this terminal; it goes back to the background when you quit
+bin/chums-agents stop|start|restart <id>
+```
+
+The hub writes one agent per character on its first start (its id is the character's: `noodle`, `squint`, `peeps`…),
+each in `~/.chums/agents/<id>` with your home folder. Three get a job in their first soul (Noodle code, Squint your
+Mac, Peeps design); the others do whatever you ask, and you shape each one's soul from the watch or the iPhone. Edit
+`agents.json` to change their folders (`cwd`, `addDirs`) or tool instructions (`guide`), then run `install` again.
+Codex agents (Runs on, on the watch or the iPhone) run inside the hub, not as LaunchAgents. Each Claude Code agent takes about 200 MB of memory while it
+waits; `bin/chums-agents stop <id>` stops one you don't use.
+
+On the watch, an agent's page (the agents list, swipe its row left, Edit) has tiles for what it runs on, its model,
+its permissions and its voice; each opens a list. Its soul is the text under them, and at the bottom you hold the
+button to change it by voice, or undo the last change.
+
+### What an agent may do
+
+Every agent starts the same: its folder and your home folder (`cwd` and `addDirs` in `agents.json`), the Chums tools,
+and the right to read the files you send it from the iPhone. How it asks before acting is its **Permissions**, on its
+card in the iPhone app or its page on the watch. Picking one restarts it, on the same conversation:
+
+| Claude Code | What it does |
+| --- | --- |
+| Default | What your Claude Code settings say (`permissions.defaultMode` in `~/.claude/settings.json`) |
+| Asks first | Anything it may not do on its own comes to the watch and the iPhone as Allow or Deny |
+| Edits on its own | Changes files in its folders without asking; asks before commands |
+| Decides on its own | Claude Code's auto mode: it acts, and refuses what looks risky without asking anyone |
+
+| Codex | What it does |
+| --- | --- |
+| Asks first | Asks before running anything but simple reads |
+| Asks when it needs to | Works in its folders and asks to go further (the default) |
+| Never asks | Runs without asking, inside its sandbox |
+
+When auto mode refuses an action, the conversation says so ("Auto mode refused: …") with **Ask first instead**, which
+switches that agent to Asks first. Without it, a refusal only reaches you as the agent saying it's blocked. The setting
+is `permissionMode` (Claude Code) or `approvalPolicy` (Codex) in `agents.json`; Claude Code gets it as
+`--permission-mode`, which holds when the agent's session is resumed.
+
+**How to know it worked:** `bin/chums-agents status` shows each one `running`, and the watch's agents list shows them.
+Each agent's log: `~/.chums/agents/<id>.host.log`.
+
+## Permissions on the Mac
+
+An agent working while you're away must not stop on a macOS dialog. macOS asks the first time a program reads your
+Desktop, Documents or Downloads, takes a screenshot, clicks in another app or controls one ("wants access to control
+Safari"), and it asks again after every update of a program it doesn't know by a stable name.
+
+So the hub and the background agents run through one small app, **Chums** (`~/Applications/Chums.app`, built from
+`tools/mac-app` by `bin/chums-setup --launchd` and `bin/chums-agents install`). Everything they and their tools ask for
+belongs to Chums, under that name and Noodle's icon, and stays granted when Claude Code, Codex or Node.js update.
+
+It needs no paid developer account. Chums.app is signed with your Apple Development certificate for the team the apps
+are signed with: `"team"` in `~/.chums/config.json` (or `CHUMS_TEAM`) if set, else the one `tools/pick-team.py` picks,
+as `bin/chums-install` does. The free Personal Team has a certificate too, made by Xcode the first time it signs the
+watch app ([step 9](#9-build-and-install-the-apps)).
+
+With that certificate, macOS keeps the permissions across rebuilds of Chums.app. With no team found, or no
+certificate yet, Chums.app is signed ad hoc: it works the same, but macOS ties the permissions to that one build. Once a certificate exists, the next `bin/chums-setup --launchd` or `bin/chums-agents install` signs Chums.app
+with it; grant the permissions again then (they belong to the new signature). The same goes for a rebuild after
+`tools/mac-app` changes in an update of Chums, when Chums.app is signed ad hoc.
+
+Grant it once, at the Mac, after [step 10](#10-start-the-agents): open **Chums** from
+`~/Applications` (or run `bin/chums-permissions`) and click **Allow All**. It goes one step at a time; what's already
+allowed passes without a dialog:
+
+1. **Your folders**: "Chums would like to access files in your Desktop folder", then Documents and Downloads. Click
+ Allow on each. (Full Disk Access, the optional last row, covers these too.)
+2. **Apps**: "Chums wants access to control Finder", then System Events, then each app in its list that is open right
+ now (Safari, Mail, Calendar, Notes, Messages, Reminders, Music, Contacts, Terminal, Chrome), and Codex Computer Use
+ when it's installed (Codex's helper, with no window). Click OK on each. Chums opens only apps with no window to ask;
+ any other app that isn't open asks once, as Chums, the first time an agent uses it.
+3. **Accessibility** (clicking and typing in other apps), then **Screen Recording** (screenshots): macOS shows an alert
+ with an Open System Settings button, and Chums is already in the list there. Switch it on. The window sees the
+ switch and goes on by itself. After Screen Recording (on macOS 15 and later "Screen & System Audio Recording"),
+ macOS may offer to quit and reopen Chums: click Later. Then Chums takes one screenshot, the way the agents do, and
+ macOS asks once more: "Chums is requesting to bypass the system private window picker". Click Allow.
+
+At the end the agents start again, so one that was refused something before has everything. **Full Disk Access** is
+optional (also Mail, Messages and Safari data, iCloud Drive, other disks): Open Settings shows the list and Chums in
+Finder; drag Chums into the list. Entries named `expect`, `caffeinate`, `node`, `tailscaled` or `claude` left in those
+lists from before can be removed.
+
+**How to know it worked:** every row in Chums's window shows Allowed (Full Disk Access is optional).
+`bin/chums-permissions check` and `bin/chums-doctor` show the same from Terminal. A Claude Code agent you start in a
+terminal (`bin/chums-claude`) still asks as that terminal app.
+
+## The agents' voices
+
+Each agent reads its replies in its own voice, made on the Mac by Kokoro, an open speech model (82M parameters,
+Apache-2.0) that runs on the Mac's GPU. Nothing goes to a server. `bin/chums-setup` installs it when
+[uv](https://docs.astral.sh/uv/) is installed (`brew install uv`): its Python in `~/.chums/kokoro` (about 1.1 GB), and
+the model and its voices in Hugging Face's cache, `~/.cache/huggingface` (about 0.35 GB). The hub starts it. It needs
+Apple Silicon; on an Intel Mac, or until it's installed, the watch reads replies with its own voice.
+
+To change an agent's voice: on the watch, swipe its row left in the agents list (Edit), then **Voice**; or on its card
+in the iPhone app, **Voice**. A tap plays a sample and picks it. There are 28 English voices: 20 American, 8 British.
+
+**How to know it worked:** `bin/chums-doctor` shows "the agents' voices (Kokoro) answer", and the hub log has a
+`speech kokoro <voice> <ms>` line for each reply.
+
+## No watch: the Simulator
+
+```bash
+bin/chums-sim
+```
+
+It builds the app for the watchOS Simulator (no signing, no Apple ID), creates a simulator named "Chums Watch" if
+needed, and runs Chums in it. The hub has to have started once (`bin/chums-hub`). The Simulator app tries the public
+URL first, if there is one, then the hub on `127.0.0.1:7717`. It needs the watchOS Simulator runtime
+(`xcodebuild -downloadPlatform watchOS`, several GB). Launch arguments play every state (`-demo YES`) and show a
+character whoever you talk to (`-testCharacter`, for that launch only):
+
+```bash
+xcrun simctl launch "Chums Watch" dev.chums.watchkitapp -demo YES -testCharacter squint
+```
+
+The app's ID is `dev.chums.watchkitapp`, or `<bundleId>.watchkitapp` when `~/.chums/config.json` sets `bundleId`.
+
+Shut the simulator down when you're done (`xcrun simctl shutdown "Chums Watch"`): a simulator left running without a
+window plays the watch's taps as sounds on the Mac.
+
+## Settings
+
+Each one is an environment variable, or a key in `~/.chums/config.json`, or the default.
+
+| Variable | config.json | Default | What it sets |
+| --- | --- | --- | --- |
+| | `port` | `7717` | The hub's local port |
+| | `publicPort` | `7718` | The watch API's port (what Funnel forwards to) |
+| | `publicURL` | set by `bin/chums-tunnel` | The address built into the watch app |
+| | `ownerName` | `the user` | What the agents call you, e.g. `"Sam"` |
+| | `diagnostics` | `false` | `true`: the apps log their frame rate and memory to the hub every 30 s (for working on them; run `bin/chums-install` after) |
+| `CHUMS_TEAM` | `team` | picked by `tools/pick-team.py` | Apple developer team for signing |
+| `CHUMS_BUNDLE` | `bundleId` | `dev.chums.<team>` (device), `dev.chums` (Simulator) | The app's bundle ID |
+| `CHUMS_LABEL_PREFIX` | `launchdPrefix` | `dev.chums` | LaunchAgent labels (`<prefix>.hub`, `<prefix>.tailscaled`, `<prefix>.agent.<id>`) |
+| `CHUMS_NODE` | `node` | `node` on your PATH | The node binary LaunchAgents run |
+| `CHUMS_WHISPER_MODEL` | | `~/Documents/huggingface/models/argmaxinc/whisperkit-coreml/openai_whisper-base` | Whisper model folder |
+| `CHUMS_CLAUDE_BIN` | | `claude` in `~/.local/bin`, `~/.npm-global/bin` or PATH | The claude CLI for the soul editor |
+| `CHUMS_NO_RC` | | unset | Set to `1` to start Claude Code sessions without Remote Control (set when `bin/chums-agents install` runs, it is kept for the background agents) |
+| | `tts` | `{ "engine": "kokoro" }` when installed | The voice replies are read in: `kokoro` (each agent's own), `say` (a macOS voice), `openai`, or `watch` |
+| `DEVELOPER_DIR` | | `/Applications/Xcode.app/Contents/Developer` | The Xcode the scripts use |
+
+Restart the hub after changing `config.json`. Run `bin/chums-install` again after changing `publicURL`, the tokens,
+`team` or `bundleId`, since those are built into the watch app.
+
+## Files Chums writes
+
+| Path | What |
+| --- | --- |
+| `~/.chums/config.json` | Ports, tokens, public URL (mode 0600) |
+| `~/.chums/agents.json`, `~/.chums/agents/` | The agents, their folders and logs |
+| `~/.chums/souls/` | Each agent's soul, a git repository |
+| `~/.chums/artifacts/` | The last 60 things sessions showed and you sent: their pictures, and for the iPhone the files as they were (up to 25 MB) and the pages the hub made of them |
+| `~/.chums/uploads/` | The last 40 photos and files sent from the iPhone |
+| `~/.chums/conversation.json` | The last 40 lines of each agent's conversation |
+| `~/.chums/hub.log`, `~/.chums/watch-events.log` | The hub's log (under launchd), and what the watch and the iPhone report (a new file past 10 MB) |
+| `~/.chums/watch-battery.csv` | The watch's battery level, a line every 5 minutes or 1% change |
+| `~/.chums/agents/<id>.runtime.json` | A Codex agent's running `app-server` (its process and socket) |
+| `~/.chums/bin/page-shot`, `pdf-shot`, `ql-shot` | What makes the pictures of pages, PDFs and other documents, compiled from `tools/page-shot.swift`, `tools/pdf-shot.swift` and `tools/ql-shot.swift` on first use |
+| `/tmp/chums-<uid>/` | The Codex agents' sockets (only your user can open the folder) |
+| `$TMPDIR/chums-speech/` | Spoken replies, as audio files, while they're recent |
+| `~/.chums/tailscale/` | Chums' `tailscaled` state and log |
+| `~/.chums/kokoro/` | The agents' voices: Kokoro's Python (`bin/chums-setup`) |
+| `~/.cache/huggingface/hub/models--mlx-community--Kokoro-82M-bf16/` | Kokoro's model and voices (`bin/chums-setup`) |
+| `~/Documents/huggingface/models/argmaxinc/whisperkit-coreml/openai_whisper-base/` | The Whisper model (`bin/chums-setup`; `CHUMS_WHISPER_MODEL` moves it) |
+| `~/Library/LaunchAgents/dev.chums.*.plist` | The hub's and `tailscaled`'s (`bin/chums-setup --launchd`), and one per Claude Code agent (`bin/chums-agents install`) |
+| `~/Applications/Chums.app` | The app the hub and the agents run through, so their permissions are Chums's ([permissions](#permissions-on-the-mac)) |
+| `app/ChumsWatch/HubConfig.swift`, `channel/mcp.json`, `channel/hooks.json` | Generated in the checkout; git-ignored |
+
+## Updating
+
+```bash
+git pull
+bin/chums-setup # new npm packages, if any
+```
+
+Then restart the hub, run `bin/chums-agents install` (it restarts the agents and rebuilds Chums.app when
+`tools/mac-app` changed), and run `bin/chums-install` to update the watch and iPhone apps. `bin/chums-doctor` confirms
+the chain.
+
+## Removing Chums
+
+1. Stop the hub.
+2. For each LaunchAgent in `~/Library/LaunchAgents/dev.chums.*`: `launchctl bootout gui/$UID/<label>`, then delete
+ the plist.
+3. Take the watch API off the internet: `tailscale --socket ~/.chums/tailscale/tailscaled.sock funnel reset`, and
+ remove the `chums-hub` machine in the Tailscale admin console.
+4. Delete `~/.chums` and `~/Applications/Chums.app`, then remove Chums from System Settings › Privacy & Security
+ (Full Disk Access, Screen & System Audio Recording, Accessibility, Automation).
+5. Delete the models, if nothing else uses them: the Whisper model in `~/Documents/huggingface/models/argmaxinc`, and
+ Kokoro's in `~/.cache/huggingface/hub/models--mlx-community--Kokoro-82M-bf16`.
+6. Delete Chums from the watch: touch and hold the app list, tap Edit Apps, then the delete button on Chums. Or from
+ the Mac: `xcrun devicectl device uninstall app --device "<watch name>" <bundle ID>.watchkitapp`.
+7. Delete Chums from the iPhone: touch and hold its icon, then Remove App.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
new file mode 100644
index 0000000..bec5914
--- /dev/null
+++ b/docs/troubleshooting.md
@@ -0,0 +1,470 @@
+# Troubleshooting
+
+Start with `bin/chums-doctor`. It checks the whole chain read-only and prints the fix for each failure; fix the first
+`FAIL` first, since later checks often fail because of it. The problems below are the ones seen while building and
+using Chums, each as symptom, cause and fix. Setup itself: [setup.md](setup.md).
+
+Logs:
+
+| Log | What's in it |
+| --- | --- |
+| The terminal running `bin/chums-hub`, or `~/.chums/hub.log` under launchd | The hub: sessions, each clip and its transcript, approvals, errors |
+| `~/.chums/watch-events.log` | What the watch reports: launches with their build stamp, keyring mode, screen, network |
+| `~/.chums/agents/<id>.host.log` | One agent: how it started, its runtime's errors |
+| `~/.chums/tailscale/tailscaled.log` | Chums' `tailscaled` |
+| The path `bin/chums-install` prints | The full build or install log after a failure |
+
+Contents:
+
+- Installing on the watch: [the watch isn't in Xcode](#the-watch-isnt-in-xcode) ·
+ [no Developer Mode switch](#the-developer-mode-switch-is-missing-on-the-watch) ·
+ [developer disk image](#the-developer-disk-image-could-not-be-mounted) ·
+ [device locked](#cant-launch-when-device-is-locked-passcode-locked-or-blocked) ·
+ [connection could not be established](#a-connection-to-this-device-could-not-be-established) ·
+ [team has no devices](#your-team-has-no-devices) ·
+ [no team can sign](#no-account-for-team-or-no-developer-team-can-sign) ·
+ [bundle ID or App ID limit](#the-bundle-id-is-taken-or-the-app-id-limit-is-reached) ·
+ [a coordinated install exists](#a-coordinated-install-exists-for-this-identity) ·
+ [two copies of Chums](#two-copies-of-chums-on-the-watch) ·
+ [stopped opening after 7 days](#chums-stopped-opening-after-7-days) ·
+ [xcrun can't find devicectl](#xcrun-cant-find-devicectl) ·
+ [Xcode license](#xcodes-license-or-first-launch)
+- The watch and the Mac: [HUB OFFLINE](#the-watch-shows-hub-offline-and-cant-reach-your-mac) ·
+ [Hub refused the token](#the-watch-shows-hub-refused-the-token) ·
+ [Funnel's name doesn't resolve](#funnels-name-doesnt-resolve-yet) ·
+ [bin/chums-tunnel waits at a link](#binchums-tunnel-waits-at-a-link) ·
+ [Not running on your Mac](#an-agent-shows-not-running-on-your-mac)
+- Talking: [slow first message](#the-first-thing-you-say-after-the-hub-starts-is-slow) ·
+ [nothing recorded](#holding-the-screen-records-nothing) · [screenshots fail](#screenshots-fail) ·
+ [the watch's voice](#replies-are-read-in-the-watchs-voice-not-the-agents) ·
+ [keyring mode](#keyring-mode-doesnt-stay-on)
+- The Mac: [a permission dialog stops an agent](#a-permission-dialog-on-the-mac-stops-an-agent) ·
+ [switched on but still refused](#chums-is-switched-on-but-still-refused) ·
+ [monthly screen recording question](#macos-asks-once-a-month-whether-chums-may-keep-recording-the-screen) ·
+ [address already in use](#the-hub-wont-start-address-already-in-use) ·
+ [a settings file isn't valid JSON](#the-hub-stops-at-start-a-settings-file-isnt-valid-json) ·
+ [whisperkit-cli didn't start](#whisperkit-cli-didnt-start-in-the-hub-log) ·
+ [a Codex agent doesn't start](#a-codex-agent-doesnt-start) ·
+ [a background Claude Code agent doesn't start](#a-background-claude-code-agent-doesnt-start) ·
+ [a ding keeps playing](#the-mac-keeps-playing-a-ding)
+
+## Installing on the watch
+
+### The watch isn't in Xcode
+
+**Symptom:** `bin/chums-install` says "Xcode doesn't know any Apple Watch yet", `bin/chums-doctor` fails "Xcode does not
+know any Apple Watch yet", or Window › Devices and Simulators lists the iPhone but not the watch.
+
+**Cause:** Xcode finds an Apple Watch only through its paired iPhone, and the first time only through an iPhone
+connected by USB cable (Xcode's device service lists a watch through the iPhone's USB connection). An iPhone that Xcode
+reaches over Wi-Fi alone never brings its watch in. A locked watch, or one that hasn't trusted the Mac, doesn't show
+either.
+
+**Fix:**
+
+1. Connect the iPhone to the Mac with a USB cable, unlock it, and tap **Trust** if it asks.
+2. Unlock the watch, keep it near the iPhone, and tap **Trust** on the watch if it asks.
+3. Keep Xcode › Window › Devices and Simulators open and wait. The watch appears under the iPhone or on its own;
+ "Preparing Apple Watch for development" can take 10 minutes or more the first time.
+4. The Mac, the iPhone and the watch must be on the same Wi-Fi network for installs after that.
+
+### The Developer Mode switch is missing on the watch
+
+**Symptom:** Settings › Privacy & Security on the watch has no Developer Mode.
+
+**Cause:** watchOS shows the switch only after Xcode has asked it to, which Xcode does once it lists the watch. When the
+watch never appeared in Xcode (see above), the switch never appears.
+
+**Fix:**
+
+1. Get the watch listed in Devices and Simulators: [the watch isn't in Xcode](#the-watch-isnt-in-xcode). Then look again.
+2. If it is listed and the switch is still missing, ask the watch to show it with `tools/watch_devmode.py reveal`
+ (iPhone on USB, both unlocked; setup: [setup.md, step 8](setup.md#8-turn-on-developer-mode)).
+3. Turn the switch on, then restart the watch **from the prompt it shows**. A restart done another way can clear the
+ revealed switch, and you start over. After the restart, unlock the watch and confirm **Turn On**.
+
+### "The developer disk image could not be mounted"
+
+**Symptom:** an install attempt fails with "The developer disk image could not be mounted on this device" (in the log:
+`kAMDMobileImageMounterDeviceLocked`), or Xcode shows it in Devices and Simulators.
+
+**Cause:** Xcode mounts a developer disk image on the watch before it installs, and the watch refuses while it is
+locked. It also fails while Xcode is still preparing the watch, and when the watch runs a watchOS version this Xcode
+doesn't support (a newer watchOS, or a beta, needs the matching Xcode).
+
+**Fix:**
+
+1. Unlock the watch and keep it awake (tap the screen), then run `bin/chums-install` again.
+2. Open Window › Devices and Simulators and wait until Xcode has finished preparing the watch.
+3. Compare the watch's watchOS version (`bin/chums-doctor` shows it) with your Xcode; update Xcode if the watch is newer.
+4. Still failing: restart the watch, then the iPhone, and try again.
+
+### "Can't launch when device is locked, passcode locked or blocked"
+
+**Symptom:** `bin/chums-install` installs the app, then says "Chums is installed, but it didn't open" with this error.
+
+**Cause:** the install worked; watchOS doesn't open an app on a locked watch.
+
+**Fix:** unlock the watch and open Chums from its app list. Nothing needs to be installed again. With keyring mode,
+turning off Wrist Detection (Settings › Passcode) keeps the watch unlocked off a wrist.
+
+### "A connection to this device could not be established"
+
+**Symptom:** install attempts fail with "A connection to this device could not be established", "Failed to allocate
+RSD device", or another tunnel or timeout error. `bin/chums-install` prints `install attempt N failed` and retries.
+
+**Cause:** Xcode reaches the watch over a wireless tunnel on the local network (CoreDevice's remote service discovery,
+RSD). The tunnel drops when the watch sleeps or locks, moves away from the iPhone or the Wi-Fi, or changes network. The
+first attempt or two often fail, which is why `bin/chums-install` tries 5 times, 6 seconds apart.
+
+**Fix:**
+
+1. Keep the watch unlocked and awake while it installs: tap the screen every few seconds, or put it on its charger.
+2. Keep the watch near the iPhone, and the Mac, iPhone and watch on the same Wi-Fi network, with Bluetooth on.
+3. Run `bin/chums-install` again.
+4. If it keeps failing: open Window › Devices and Simulators and wait until the watch shows as connected; turn the
+ watch's Wi-Fi off and on; restart the watch; connect the iPhone by USB.
+
+### Your team has no devices
+
+**Symptom:** the build stops with "Your team has no devices from which to generate a provisioning profile".
+`bin/chums-install` then prints how to register the devices.
+
+**Cause:** automatic signing makes a provisioning profile only for devices registered with the team. Xcode registers a
+device when you run an app on it from Xcode. `bin/chums-install` builds without a run destination, so on a team with no
+registered devices (often a new free Personal Team) there is nothing to make a profile for.
+
+**Fix:** register the devices once from Xcode, then go back to the script:
+
+1. Open `app/Chums.xcodeproj` (the first `bin/chums-install` run generated it, with your team and bundle ID).
+2. Choose the **Chums** scheme and your iPhone as the destination, and press Run (⌘R).
+3. Choose the **ChumsWatch** scheme and your watch as the destination, and press Run.
+4. If Xcode asks to download the watchOS platform first, accept (several GB).
+5. Run `bin/chums-install` again.
+
+A free Personal Team can register 3 devices.
+
+### "No Account for Team", or no developer team can sign
+
+**Symptom:** `bin/chums-install` says "Xcode isn't signed in to the Apple ID for team …" or "No developer team can sign".
+
+**Cause:** Xcode has no signed-in Apple ID with that team. Xcode also lists no team for an account while Apple converts
+its membership (for example from individual to organization), even though the Apple ID is signed in.
+
+**Fix:** Xcode › Settings › Apple Accounts › + › Apple ID, and sign in. Any Apple ID works: it has a free Personal Team.
+During a membership conversion, wait for Apple to finish, or sign in a second Apple ID and use its Personal Team. To
+force a team: `"team": "<team ID>"` in `~/.chums/config.json`, or `CHUMS_TEAM=<team ID> bin/chums-install`.
+
+### The bundle ID is taken, or the App ID limit is reached
+
+**Symptom:** the build fails with "cannot be registered to your development team because it is not available", or with
+"the '10' App ID limit in '7' days has been exceeded".
+
+**Cause:** a bundle ID belongs to the team that registered it first. A free Personal Team can register 10 App IDs in 7
+days, and each Chums bundle ID uses 4 (the iPhone app, its widgets, the watch app and the watch's widget), so trying a few bundle IDs or teams
+uses them up.
+
+**Fix:** for a taken ID, set one of your own, such as `"bundleId": "com.<you>.chums"`, in `~/.chums/config.json`. For
+the limit, wait until the oldest App IDs expire (7 days after they were made), then keep one bundle ID from then on.
+
+### "A coordinated install exists for this identity"
+
+**Symptom:** installing on the watch fails with `IXErrorDomain error 48`: "A coordinated install exists for this
+identity, but it's scoped to a different process."
+
+**Cause:** the iPhone app carries the watch app. When the iPhone app was installed before the watch had the same
+copy, the iPhone started installing it on the watch itself, and the direct install waits for that one.
+
+**Fix:** unlock the watch, keep it near the iPhone, and wait until the iPhone's install finishes (the Watch app on the
+iPhone › My Watch shows Chums installing). Then run `bin/chums-install` again: it installs the watch first, so this
+doesn't happen again.
+
+### Two copies of Chums on the watch
+
+**Symptom:** the watch has two Chums apps. One works; the other shows "HUB OFFLINE", "Hub refused the token", or doesn't
+open.
+
+**Cause:** the bundle ID changed between two installs, and each bundle ID is a separate app. The default bundle ID is
+`dev.chums.<team ID>`, so it changes when you sign with another team (for example from a free Personal Team to a paid
+one, or with another Apple ID), or when an earlier install used `CHUMS_BUNDLE` and a later one didn't. The old copy keeps
+the token and address it was built with, and on a free team it stops opening after 7 days.
+
+**Fix:**
+
+1. See which apps are on the watch: `xcrun devicectl device info apps --device "<watch name>"`.
+2. Pin the one to keep in `~/.chums/config.json`: `"bundleId": "<that ID without .watchkitapp>"`.
+3. Run `bin/chums-install`.
+4. Delete the other copy: on the watch, touch and hold the app list, tap Edit Apps, then the delete button. Or:
+ `xcrun devicectl device uninstall app --device "<watch name>" <old bundle ID>.watchkitapp`.
+5. If the app you kept doesn't show after that, step 1 says whether it is installed; run `bin/chums-install` again.
+
+### Chums stopped opening after 7 days
+
+**Symptom:** Chums worked, and a week later it doesn't open.
+
+**Cause:** an app signed with a free Personal Team has a provisioning profile that expires 7 days after the install.
+`bin/chums-install` prints the date.
+
+**Fix:** run `bin/chums-install` again (same Apple ID, same bundle ID): the app is replaced and works for another 7
+days. A paid Apple Developer Program membership signs for a year ([setup.md](setup.md#apple-developer-account)).
+
+### xcrun can't find devicectl
+
+**Symptom:** running `xcrun devicectl …` yourself prints `unable to find utility "devicectl"`.
+
+**Cause:** `xcode-select` points at the Command Line Tools, which don't include `devicectl`. Chums' scripts set
+`DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer` themselves, so they aren't affected.
+
+**Fix:** put `DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer` in front of the command, or switch for good with
+`sudo xcode-select -s /Applications/Xcode.app`.
+
+### Xcode's license or first launch
+
+**Symptom:** builds fail with "You have not agreed to the Xcode license agreements", or `bin/chums-doctor` says Xcode
+hasn't finished its first launch.
+
+**Cause:** Xcode needs its license accepted and its components installed once.
+
+**Fix:** open Xcode once and follow its prompts, or run `sudo xcodebuild -license accept` and
+`sudo xcodebuild -runFirstLaunch`.
+
+## The watch and the Mac
+
+### The watch shows HUB OFFLINE and "Can't reach your Mac"
+
+**Symptom:** the character sleeps, the top says HUB OFFLINE, and the line under it says "Can't reach your Mac". Talking
+gives "Can't reach your Mac".
+
+**Cause:** the watch can't get an answer from the hub's public URL. One of these is down:
+
+- the hub (not started, stopped, or the Mac is asleep: on battery a sleeping Mac is offline);
+- Chums' `tailscaled` or Funnel (not running after a restart of the Mac, signed out, or Funnel turned off);
+- public DNS for the Funnel name (a new name: [see below](#funnels-name-doesnt-resolve-yet));
+- the watch's own network (no iPhone nearby, no Wi-Fi or cellular).
+
+**Fix:** run `bin/chums-doctor`; sections 4 and 5 say which link fails. Then:
+
+- hub: `bin/chums-hub`, or `bin/chums-setup --launchd` to run it at login (it keeps the Mac awake while on power);
+- tunnel: `bin/chums-tunnel` (it starts `tailscaled`, and turns Funnel on again);
+- the watch retries on its own; a touch or raising the wrist retries at once.
+
+### The watch shows "Hub refused the token"
+
+**Symptom:** HUB OFFLINE with "Hub refused the token".
+
+**Cause:** the watch reaches a hub, and that hub doesn't accept the token built into the app. The hub's `watchToken`
+changed after the app was built: `~/.chums/config.json` was deleted or rotated, the app was built on another Mac or
+user account, or an old copy of the app is open ([two copies](#two-copies-of-chums-on-the-watch)).
+
+**Fix:** run `bin/chums-install` again: it builds the hub's current token into the app. `bin/chums-doctor` says whether
+the last build matches ("the watch app (built …) has the hub's current token and address").
+
+### Funnel's name doesn't resolve yet
+
+**Symptom:** right after `bin/chums-tunnel`, `bin/chums-doctor` fails "does not resolve in public DNS yet",
+`curl https://chums-hub.<tailnet>.ts.net/v1/ping` says "Could not resolve host", and the watch can't reach the Mac.
+
+**Cause:** Tailscale publishes the DNS record for a new Funnel name some time after Funnel is turned on: up to 10
+minutes, by Tailscale's documentation; it has taken about 25. A resolver that asked before the name existed (the Mac,
+the iPhone, a router or a carrier) can keep the "no such name" answer for a while after that.
+
+**Fix:** wait, and check with a public resolver: `dig +short chums-hub.<tailnet>.ts.net @1.1.1.1`. Once that prints
+addresses and the Mac still fails, flush its cache: `sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder`.
+On the iPhone, turn airplane mode on and off.
+
+### bin/chums-tunnel waits at a link
+
+**Symptom:** `bin/chums-tunnel` prints a `login.tailscale.com` link and doesn't finish.
+
+**Cause:** the first link (`…/a/…`) signs Chums' `tailscaled` in to your tailnet. The second (`…/f/funnel?…`) appears
+when the tailnet doesn't allow Funnel yet: Funnel needs HTTPS certificates on and the `funnel` node attribute in the
+tailnet's access policy.
+
+**Fix:** open the link, sign in or approve, and the script continues. If a policy change isn't allowed from that link
+(an organization's tailnet), an admin turns on HTTPS Certificates (DNS page) and adds the `funnel` node attribute
+(Access controls) in the admin console.
+
+### An agent shows "Not running on your Mac"
+
+**Symptom:** in the watch's agents list, an agent is gray and says "Not running on your Mac".
+
+**Cause:** the hub is reachable, but no session for that agent is connected to it.
+
+**Fix:**
+
+- A Claude Code agent: `bin/chums-agents status`, then `bin/chums-agents start <id>` (or `install`), or start it in a
+ terminal with `bin/chums-claude <id>` in its folder. Its log: `~/.chums/agents/<id>.host.log`.
+- A Codex agent: the hub runs it, so restart the hub. If it still doesn't start:
+ [a Codex agent doesn't start](#a-codex-agent-doesnt-start).
+
+## Talking
+
+### The first thing you say after the hub starts is slow
+
+**Symptom:** after starting or restarting the hub, the first clip takes 15–25 seconds to transcribe; later ones take
+a fraction of a second.
+
+**Cause:** `whisperkit-cli serve` loads the speech model on its first transcription. The hub now sends it a second of
+silence as it starts, so the model is loaded before you speak, and logs `whisper warm in … s` when it's done.
+
+**Fix:** nothing, unless the hub logs `whisper did not warm up in 90 s` or `whisper model missing at …`. Then run
+`bin/chums-setup` (it downloads the model) and restart the hub. A clip sent in the first seconds after a restart still
+waits for the warm-up.
+
+### Holding the screen records nothing
+
+**Symptom:** you hold the screen and talk, and nothing is sent, or the transcript is empty.
+
+**Cause:** Chums has no microphone permission on the watch (it was refused when Chums first opened; the watch then
+says "Allow the microphone for Chums in Settings."), or Whisper heard no speech: the hub drops what Whisper marks as
+non-speech, such as `[BLANK_AUDIO]`. A hold shorter than about a third of a second isn't sent.
+
+**Fix:** on the watch, Settings › Privacy & Security › Microphone › Chums on. Hold, speak, then let go; the hub log
+shows each clip with its transcript.
+
+### Screenshots fail
+
+**Symptom:** you ask for a screenshot and the agent says macOS refused it, or the picture shows only the desktop
+background.
+
+**Cause:** `chums_show` takes screenshots with `screencapture` from inside the agent's process, and macOS allows that only
+for apps with Screen Recording permission. Which app needs it depends on how the agent runs:
+
+| Agent | The app that needs Screen Recording |
+| --- | --- |
+| Claude Code in a terminal (`bin/chums-claude`) | That terminal app: Terminal, iTerm, Visual Studio Code… |
+| Claude Code in the background (`bin/chums-agents`) | Chums (`~/Applications/Chums.app`) |
+| Codex (run by the hub) | Chums, when the hub runs as a LaunchAgent (`bin/chums-setup --launchd`); the terminal app, when it runs in a terminal (`bin/chums-hub`) |
+
+**Fix:** for Chums, open Chums from `~/Applications` and click Allow All ([Permissions on the Mac](setup.md#permissions-on-the-mac)). For a
+terminal app: System Settings › Privacy & Security › Screen & System Audio Recording › +, and add it. Then restart the
+agent (or the hub): macOS applies the permission to processes started after it.
+
+### A permission dialog on the Mac stops an agent
+
+**Symptom:** something you asked for from the watch doesn't happen, and the Mac shows a dialog such as "expect would
+like to access files in your Documents folder" or "node wants access to control Finder". It comes back after Claude
+Code or Node.js updates.
+
+**Cause:** macOS asks on behalf of the program launchd started. Before Chums.app, that was `/usr/bin/expect` (background
+Claude Code agents) and `/usr/bin/caffeinate` with `node` (the hub and its Codex agents), and permissions given to a
+versioned Claude Code binary are lost when it updates.
+
+**Fix:** run `bin/chums-setup --launchd` and `bin/chums-agents install` (both restart what they install, so the watch's
+conversation is cut for a moment). Then, at the Mac, open Chums from `~/Applications` and click Allow All. From then on
+every dialog says "Chums" and is asked once. `bin/chums-doctor` shows what's still missing.
+
+### Chums is switched on but still refused
+
+**Symptom:** Chums's window shows Allow for Accessibility or Screen Recording, but in System Settings Chums is already
+in the list and switched on.
+
+**Cause:** Chums.app was signed again since (ad hoc after a rebuild, or with your Apple Development certificate once
+Xcode made one), and macOS keeps the switch of the old signature. `bin/chums-setup --launchd` and
+`bin/chums-agents install` say so when it happens.
+
+**Fix:** in that list, switch Chums off and on again (or select it, click −, then open Chums and click Allow All).
+
+### macOS asks once a month whether Chums may keep recording the screen
+
+**Symptom:** "Chums is requesting to bypass the system private window picker and directly access your screen and
+audio", or "Chums has been accessing your screen… Continue to Allow", on macOS 15 and later.
+
+**Cause:** macOS asks this of any app that takes screenshots without its window picker, which `screencapture`
+(screenshots for the watch) does: the first time one is taken (Allow All takes one, so it comes during setup), then
+about once a month. It doesn't stop the screenshot; the dialog waits on the Mac.
+
+**Fix:** click Allow (or Continue to Allow) when you're at the Mac. There is no setting to turn it off.
+
+### Replies are read in the watch's voice, not the agent's
+
+**Symptom:** the watch reads replies in its robotic voice, and every agent sounds the same.
+
+**Cause:** the agents' voices (Kokoro) aren't installed or aren't running: the hub then sends no audio and the watch
+uses its own voice. Kokoro needs Apple Silicon, and `uv` to install.
+
+**Fix:** run `bin/chums-setup` (it installs Kokoro; `brew install uv` first if it asks), then restart the hub.
+`bin/chums-doctor` says whether Kokoro answers; the hub log says why it stopped (`kokoro exited`).
+
+### Keyring mode doesn't stay on
+
+**Symptom:** with "Keyring: stay on" in the watch app's settings, Chums still goes back to the watch face when the screen
+dims, and the settings show "Keyring mode failed: …". `~/.chums/watch-events.log` has `keyring error: …` or
+`keyring health after asking: denied`.
+
+**Cause:** keyring mode runs a workout session, which needs Health › Workouts permission. watchOS asks once per install;
+if it was refused, or the first request came from a build without the HealthKit entitlement, it keeps the answer.
+watchOS can also report "denied" for an app that was allowed: the session starting is the real test (`keyring running`
+in the log).
+
+**Fix:** delete Chums from the watch, restart the watch, run `bin/chums-install`, and allow Workouts when Chums asks.
+
+## The Mac
+
+### The hub won't start: address already in use
+
+**Symptom:** `bin/chums-hub` stops with `chums: 127.0.0.1:7717 is in use, most likely by a hub that is already
+running` (or `:7718`).
+
+**Cause:** another hub is already running: usually the LaunchAgent from `bin/chums-setup --launchd`, plus one started by
+hand.
+
+**Fix:** `lsof -nP -iTCP:7717 -sTCP:LISTEN` shows which process holds the port. Keep one hub: stop the extra one, or use
+`launchctl kickstart -k gui/$UID/dev.chums.hub` to restart the LaunchAgent's instead of starting another.
+
+### The hub stops at start: a settings file isn't valid JSON
+
+**Symptom:** the hub stops with `chums: /Users/you/.chums/config.json is not a valid JSON object` or `… agents.json is not a
+valid JSON list of agents`.
+
+**Cause:** the file was edited by hand and has a typo. The hub stops instead of writing over it, so nothing is lost.
+
+**Fix:** fix the JSON (`bin/chums-doctor` says where it fails) and start the hub again. Moving the file away also works,
+at a cost: a new `config.json` has new tokens, so run `bin/chums-install` again; a new `agents.json` starts every
+agent's conversation over.
+
+### "whisperkit-cli didn't start" in the hub log
+
+**Cause:** the Whisper model is there but `whisperkit-cli` isn't on the hub's PATH: not installed, or the LaunchAgent
+was written before it was.
+
+**Fix:** `brew install whisperkit-cli`, then `bin/chums-setup --launchd` (it writes the LaunchAgent's PATH again), or
+start the hub from a shell that has it.
+
+### A Codex agent doesn't start
+
+**Symptom:** a Codex agent stays "Not running on your Mac"; `~/.chums/agents/<id>.host.log` says "not started".
+
+**Cause and fix**, by what the log says:
+
+- `codex app-server didn't open …` or a spawn error: the hub didn't find `codex`. It looks on its own PATH plus
+ `~/.npm-global/bin`, `/opt/homebrew/bin` and `/usr/local/bin`. Install Codex in one of those, or set
+ `"command": ["/path/to/codex"]` on the agent in `agents.json`.
+- A sign-in error: run `codex login`, then restart the hub.
+- A model error: the default model isn't on your plan. Set `"model"` on the agent (`gpt-6-astra` works on Plus).
+- After a Codex update, run `node tools/e2e-runtimes.mjs codex`: OpenAI labels the app-server experimental, and its
+ methods can change between releases.
+
+### A background Claude Code agent doesn't start
+
+**Symptom:** `bin/chums-agents status` shows an agent `not running`, or its `host.log` repeats `not started: …`.
+
+**Cause and fix**, by what the log says:
+
+- `…'s thread is already running (pid …)`: the same agent is open in another terminal (`bin/chums-agents open`, or a
+ `claude --resume` of its thread). One process per thread: quit that one.
+- `ended while starting`, or the session exits at once: Claude Code isn't found or isn't signed in. A LaunchAgent has no
+ shell PATH; agents look in the node folder, `~/.local/bin`, `~/.npm-global/bin`, `/opt/homebrew/bin` and
+ `/usr/local/bin`. Run `claude` once in a terminal to sign in.
+- `running (no development-channel screen seen in its first minute)`: the session started without the screen that
+ confirms the development channel. If orders from the watch don't reach it, check that channels are allowed for the
+ account: on Team and Enterprise plans an Owner enables them (Organization settings › Claude Code › Channels).
+ `bin/chums-agents open <id>` shows the session's screen.
+
+### The Mac keeps playing a ding
+
+**Symptom:** the Mac plays a short sound again and again, with no window explaining it.
+
+**Cause:** a watchOS Simulator is still running Chums without a Simulator window, and plays the watch's taps as sounds.
+
+**Fix:** `xcrun simctl shutdown all`.
diff --git a/hub/hub.mjs b/hub/hub.mjs
new file mode 100755
index 0000000..42d742d
--- /dev/null
+++ b/hub/hub.mjs
@@ -0,0 +1,1552 @@
+#!/usr/bin/env node
+// Chums Hub: the only thing that talks to the agents' sessions. The watch talks only to this.
+//
+// Two sides:
+// /channel/* — one chums-channel.mjs per Claude Code session registers here and long-polls for orders
+// /v1/* — the watch (HTTPS/HTTP only: watchOS forbids WebSockets) posts audio, long-polls state
+// Codex, Copilot and Agent Client Protocol agents are run by the hub itself (hub/runtimes.mjs): they become sessions
+// like a Claude Code one, and speak the same hook vocabulary.
+//
+// Speech-to-text runs in a kept-alive `whisperkit-cli serve` child so each utterance costs ~0.2 s.
+
+import http from 'node:http'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import crypto from 'node:crypto'
+import { spawn, execFile } from 'node:child_process'
+import { startRunners, startRunner, runByHub } from './runtimes.mjs'
+import { OWNER, Owner, PAGE_GUIDE } from './standing.mjs'
+
+const CONFIG_DIR = path.join(os.homedir(), '.chums')
+const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json')
+const WHISPER_PORT = 50061
+const KOKORO_PORT = 50062 // the agents' voices (tools/kokoro-server.py)
+const KOKORO_PY = path.join(os.homedir(), '.chums/kokoro/.venv/bin/python')
+const WHISPER_MODEL = process.env.CHUMS_WHISPER_MODEL || path.join(os.homedir(),
+ 'Documents/huggingface/models/argmaxinc/whisperkit-coreml/openai_whisper-base')
+const ROOT = path.join(import.meta.dirname, '..') // this checkout
+// the claude CLI for the soul editor: $CHUMS_CLAUDE_BIN, else the native installer's (~/.local/bin), else an npm prefix
+// install in ~/.npm-global, else PATH's (a LaunchAgent's PATH has neither of those folders)
+const CLAUDE_BIN = process.env.CHUMS_CLAUDE_BIN ||
+ ['.local/bin/claude', '.npm-global/bin/claude'].map(p => path.join(os.userInfo().homedir, p)).find(p => fs.existsSync(p)) || 'claude'
+
+// ---------- config ----------
+/// A settings file the hub keeps: its JSON, or `fallback` when there's no file yet. One that doesn't parse stops the
+/// hub with a message (writing over it would lose its settings, the tokens the apps were built with, the agents'
+/// conversations). The parser's message isn't shown: it quotes the file, which can hold a token.
+function readSettings(file, fallback, isShape, shape) {
+ let text
+ try { text = fs.readFileSync(file, 'utf8') } catch (e) { if (e.code === 'ENOENT') return fallback; throw e }
+ if (!text.trim()) return fallback
+ let v
+ try { v = JSON.parse(text) } catch { v = undefined }
+ if (v === undefined || !isShape(v)) {
+ console.error(`chums: ${file} is not ${shape}. Fix it (bin/chums-doctor says where), or move it away and start the hub again: it writes a new one.`)
+ process.exit(1)
+ }
+ return v
+}
+
+function loadConfig() {
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 })
+ fs.chmodSync(CONFIG_DIR, 0o700) // made earlier by something else (bin/chums-setup): still only yours
+ const cfg = readSettings(CONFIG_PATH, {}, v => v && typeof v === 'object' && !Array.isArray(v), 'a valid JSON object')
+ cfg.port ??= 7717
+ cfg.publicPort ??= 7718 // the watch API alone, for the tunnel
+ cfg.token ??= crypto.randomBytes(18).toString('base64url') // Claude Code sessions: channel and hooks, on this Mac
+ cfg.watchToken ??= crypto.randomBytes(18).toString('base64url') // the watch, over the internet (watch API only)
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), { mode: 0o600 })
+ fs.chmodSync(CONFIG_PATH, 0o600) // the mode above applies only to a new file
+ return cfg
+}
+const cfg = loadConfig()
+
+const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a)
+
+// ---------- state ----------
+let rev = 1
+const sessions = new Map() // id -> { id, name, cwd, status, lastLine, lastSeen, lastSpokeAt, inbox: [], waiter }
+const approvals = new Map() // requestId -> { requestId, sessionId, session, tool, description, preview, at }
+const spoken = [] // { id, session, text, kind, at }
+const tools = [] // { id, session, type, text, ok, at } — every tool call, from Claude Code hooks
+
+// ---------- agents: every character is its own agent ----------
+// One agent per character, each with its own soul, its own session and thread, and its own conversation on the watch.
+// ~/.chums/agents.json says, per agent, which runtime it runs on (Claude Code, the default, or Codex: switched from
+// its soul screen on the watch), where it works and how to use its tools; a character with no entry gets one with the
+// defaults below. Who it is lives in its soul (below). A session is an agent's when its name is the agent's id
+// (bin/chums-agents); everything said, shown, asked or done is tagged with the agent it came from.
+const AGENTS_PATH = path.join(os.homedir(), '.chums/agents.json')
+const HOME = os.homedir()
+/// The characters the watch draws, in order; each is an agent, its id the character's.
+const LOOKS = ['noodle', 'stretch', 'peeps', 'squint', 'ray', 'tangle', 'crunch', 'nana']
+const LOOK_NAMES = { noodle: 'Noodle', stretch: 'Stretch', peeps: 'Peeps', squint: 'Squint', ray: 'Ray', tangle: 'Tangle', crunch: 'Crunch', nana: 'Nana' }
+const GUIDE = "To see an app or a page, use chums_show with screenshot (and open: a URL to open it in Safari first). To show a file, use chums_show with file: a page, a document, a PDF, text or code, a table, an image or a video. The watch shows it as a picture (a video as a still); the iPhone opens the file itself. " + PAGE_GUIDE + " To read or click inside a page your owner is logged in to, run JavaScript in Safari with osascript (Safari's do JavaScript; it needs Develop › Allow JavaScript from Apple Events)."
+// the guide agents were given before; an agent that still has it gets the one above
+const OLD_GUIDES = ["To see an app or a page, use chums_show with screenshot (and open: a URL to open it in Safari first). To show a file, use chums_show with file: a page, a document, a PDF, text or code, a table, an image or a video. The watch shows it as a picture (a video as a still); the iPhone opens the file itself. An HTML page you make runs on the iPhone, its scripts and charts included, and is a picture on the watch: for a chart, a table to explore or anything visual, make one self-contained HTML file (the iPhone gets only that file, nothing beside it) and show it. To read or click inside a page your owner is logged in to, run JavaScript in Safari with osascript (Safari's do JavaScript; it needs Develop › Allow JavaScript from Apple Events).", "To see an app or a page, use chums_show with screenshot (and open: a URL to open it in Safari first). To show what you make (an HTML page, SVG, PDF or image), use chums_show with file. To read or click inside a page your owner is logged in to, run JavaScript in Safari with osascript (Safari's do JavaScript; it needs Develop › Allow JavaScript from Apple Events)."]
+/// Kokoro's English voices: id, name, accent, and its author's grade of it (VOICES.md in hexgrad/Kokoro-82M).
+const ENGLISH_VOICES = [
+ ['af_heart', 'Heart', 'A'], ['af_bella', 'Bella', 'A-'], ['af_nicole', 'Nicole', 'B-'], ['af_aoede', 'Aoede', 'C+'], ['af_kore', 'Kore', 'C+'],
+ ['af_sarah', 'Sarah', 'C+'], ['af_alloy', 'Alloy', 'C'], ['af_nova', 'Nova', 'C'], ['af_sky', 'Sky', 'C-'], ['af_jessica', 'Jessica', 'D'],
+ ['af_river', 'River', 'D'], ['am_fenrir', 'Fenrir', 'C+'], ['am_michael', 'Michael', 'C+'], ['am_puck', 'Puck', 'C+'], ['am_echo', 'Echo', 'D'],
+ ['am_eric', 'Eric', 'D'], ['am_liam', 'Liam', 'D'], ['am_onyx', 'Onyx', 'D'], ['am_santa', 'Santa', 'D-'], ['am_adam', 'Adam', 'F+'],
+ ['bf_emma', 'Emma', 'B-'], ['bf_isabella', 'Isabella', 'C'], ['bf_alice', 'Alice', 'D'], ['bf_lily', 'Lily', 'D'], ['bm_fable', 'Fable', 'C'],
+ ['bm_george', 'George', 'C'], ['bm_lewis', 'Lewis', 'D+'], ['bm_daniel', 'Daniel', 'D'],
+].map(([id, name, grade]) => ({ id, name, grade, accent: id[0] === 'b' ? 'British' : 'American', gender: id[1] === 'f' ? 'female' : 'male' }))
+/// Each character's voice (Kokoro's: a American, b British; f female, m male), changed per agent on the watch.
+const VOICES = {
+ noodle: 'af_heart', squint: 'bf_isabella', tangle: 'bf_alice', ray: 'am_fenrir',
+ stretch: 'bm_daniel', peeps: 'af_sky', crunch: 'am_echo', nana: 'am_michael' }
+const DEFAULT_VOICE = 'af_heart'
+const defaultAgent = c => ({ id: c, name: LOOK_NAMES[c], character: c, runtime: 'claude', voice: VOICES[c] ?? DEFAULT_VOICE,
+ cwd: `${HOME}/.chums/agents/${c}`, addDirs: [HOME], guide: GUIDE, sessionId: crypto.randomUUID() })
+const saveAgents = () => fs.writeFileSync(AGENTS_PATH, JSON.stringify(agents, null, 2))
+function loadAgents() {
+ const list = readSettings(AGENTS_PATH, [], v => Array.isArray(v) && v.every(a => a && typeof a === 'object' && typeof a.id === 'string'),
+ 'a valid JSON list of agents, each with an "id" (tools/agents.example.json)')
+ const missing = LOOKS.filter(c => !list.some(a => a.id === c))
+ let filled = false
+ for (const a of list) {
+ if (LOOKS.includes(a.id)) a.character = a.id // a character's agent is that character
+ if (!a.voice) { a.voice = VOICES[a.id] ?? DEFAULT_VOICE; filled = true }
+ if (OLD_GUIDES.includes(a.guide)) { a.guide = GUIDE; filled = true }
+ // an entry written by hand (docs/other-agents.md) may leave out its folder, and a Claude Code agent's session ID
+ // (its conversation; bin/chums-agents can't start one without it)
+ if (!a.cwd) { a.cwd = `${HOME}/.chums/agents/${a.id}`; filled = true }
+ if ((a.runtime ?? 'claude') === 'claude' && !a.sessionId) { a.sessionId = crypto.randomUUID(); filled = true }
+ }
+ if (missing.length || filled) {
+ list.push(...missing.map(defaultAgent))
+ fs.mkdirSync(path.dirname(AGENTS_PATH), { recursive: true })
+ fs.writeFileSync(AGENTS_PATH, JSON.stringify(list, null, 2))
+ }
+ return list
+}
+const agents = loadAgents()
+const agentNamed = id => agents.find(a => a.id === id)
+const sessionOf = id => [...sessions.values()].find(s => s.name === id)
+
+// ---------- souls: who each agent is (its name, what it looks after, what it refers to the others, its voice) ----------
+// ~/.chums/souls/<id>.md, a git repo of their own (every change a commit, outside the agents' working folders), shaped
+// by voice from the watch: a separate, tool-free model call turns what the owner said into a targeted change and a plain
+// summary; the owner sees it and saves it (only against the version they saw), or undoes the last one. An agent gets its current
+// soul, and the team's, with the next order it receives (again after it compacts its memory): saved changes apply from
+// its next order. Only identity lives here; how to use its tools stays in agents.json.
+const SOUL_DIR = path.join(CONFIG_DIR, 'souls')
+const SOUL_FIELDS = { name: 24, owns: 180, refers: 180, voice: 90, body: 2500 }
+// The first souls: three with a job, the rest whatever you give them. Shaped from the watch after that.
+const SEED_SOULS = {
+ noodle: { owns: 'Code in your projects, starting with the chums project (the watch app, hub and channel).',
+ refers: 'Your Mac, browser and accounts to Squint. Design work to Peeps.', voice: 'Brief and plain.', body: 'A coding agent.' },
+ squint: { owns: 'Your Mac: the apps and windows on it, Safari with your logins, your files, accounts and errands.',
+ refers: 'Code to Noodle. Design work to Peeps.', voice: 'Brief and warm.', body: 'An agent for your Mac.' },
+ peeps: { owns: 'Design: images, mockups, HTML pages, icons, design files.',
+ refers: 'Code to Noodle. Your Mac and browser to Squint.', voice: 'Brief and playful.', body: 'A design agent.' },
+}
+const seedOf = id => ({ owns: 'Whatever you ask it.', refers: 'Code to Noodle. Your Mac and browser to Squint. Design work to Peeps.',
+ voice: 'Brief.', body: 'An agent.', ...SEED_SOULS[id] })
+const git = (...args) => run('/usr/bin/git', ['-C', SOUL_DIR, ...args])
+const soulFile = id => path.join(SOUL_DIR, `${id}.md`)
+function parseSoul(text) {
+ const m = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/)
+ const soul = { body: (m?.[2] ?? text).trim() }
+ for (const line of (m?.[1] ?? '').split('\n')) { const k = line.match(/^(\w+):\s*(.*)$/); if (k && k[1] in SOUL_FIELDS) soul[k[1]] = k[2].trim() }
+ return soul
+}
+const renderSoul = s => `---\nname: ${s.name}\nowns: ${s.owns ?? ''}\nrefers: ${s.refers ?? ''}\nvoice: ${s.voice ?? ''}\n---\n${(s.body ?? '').trim()}\n`
+function soulOf(id) {
+ try { return parseSoul(fs.readFileSync(soulFile(id), 'utf8')) } catch { return { name: agentNamed(id)?.name ?? id, ...seedOf(id) } }
+}
+const soulRev = id => { try { return crypto.createHash('sha1').update(fs.readFileSync(soulFile(id))).digest('hex').slice(0, 10) } catch { return 'seed' } }
+const teamText = () => agents.map(a => { const s = soulOf(a.id); return `- ${s.name} (${a.id}) looks after: ${s.owns} Refers: ${s.refers}` }).join('\n')
+const teamRev = () => crypto.createHash('sha1').update(teamText()).digest('hex').slice(0, 10)
+let soulQueue = Promise.resolve() // one change at a time
+const serially = f => (soulQueue = soulQueue.then(f, f))
+async function seedSouls() {
+ fs.mkdirSync(SOUL_DIR, { recursive: true })
+ if (!fs.existsSync(path.join(SOUL_DIR, '.git'))) { await git('init', '-q'); await git('config', 'user.name', 'Chums hub'); await git('config', 'user.email', 'hub@localhost') }
+ const added = []
+ for (const a of agents) if (!fs.existsSync(soulFile(a.id))) {
+ fs.writeFileSync(soulFile(a.id), renderSoul({ name: a.name, ...seedOf(a.id) }))
+ added.push(`${a.id}.md`)
+ }
+ if (added.length) { await git('add', ...added); await git('commit', '-q', '-m', `Seed ${added.join(', ')}`) }
+}
+
+/// What a session should know about itself before an order: its soul and the team's, when it hasn't seen this version.
+function soulPrefix(s) {
+ const a = agentNamed(s.name)
+ if (!a) return ''
+ const rev = `${soulRev(a.id)}:${teamRev()}`
+ if (s.soulSent === rev) return ''
+ s.soulSent = rev
+ return `[Your soul, as ${OWNER} set it (version ${rev}). It replaces any earlier one, and anything said before about who you are:]\n${renderSoul(soulOf(a.id))}\n[The team, who looks after what:]\n${teamText()}\n\n[${Owner}'s order:]\n`
+}
+
+// the editor: a separate, tool-free call, with nothing of the agent's working thread in it
+const proposals = new Map() // id -> { agent, base, changes, summary, at }
+async function proposeSoul(agentId, said) {
+ const a = agentNamed(agentId)
+ if (!a) throw new Error('no such agent')
+ const cur = soulOf(agentId)
+ const others = agents.filter(x => x.id !== agentId).map(x => { const o = soulOf(x.id); return `- ${o.name}: looks after ${o.owns}` }).join('\n')
+ const prompt = `You edit the soul of one of ${OWNER}'s AI agents: its name, what it looks after, what it refers to the other agents, and its voice. ${Owner} just said this about it, by voice (a transcript, so expect recognition errors; read for intent):
+"${said}"
+
+The agent's current soul:
+name: ${cur.name}
+owns: ${cur.owns}
+refers: ${cur.refers}
+voice: ${cur.voice}
+body: ${cur.body}
+
+The other agents:
+${others}
+
+Change only what was asked; keep everything else word for word. Plain, literal, short words. Field limits: name ${SOUL_FIELDS.name} characters, owns ${SOUL_FIELDS.owns}, refers ${SOUL_FIELDS.refers}, voice ${SOUL_FIELDS.voice}, body ${SOUL_FIELDS.body}.
+Answer with one JSON object and nothing else:
+{"changes": {"<field>": "<its whole new value>"}, "summary": "<one short sentence saying what will change, about the agent by name, e.g. Noodle will also look after your calendar and talk more casually.>"}
+If it's unclear what's wanted, or it isn't about this agent's soul, answer {"clarify": "<one short question>"} instead.`
+ const t0 = Date.now()
+ const out = await new Promise((resolve, reject) => {
+ const p = spawn(CLAUDE_BIN,
+ ['-p', '--model', 'sonnet', '--effort', 'low', '--tools', '', '--no-session-persistence', '--strict-mcp-config', '--output-format', 'json'],
+ { cwd: SOUL_DIR, env: { ...process.env, HOME: os.userInfo().homedir } })
+ let o = '', e = ''
+ p.stdout.on('data', d => { o += d }); p.stderr.on('data', d => { e += d })
+ const t = setTimeout(() => { p.kill(); reject(new Error('the editor took too long')) }, 60_000)
+ p.on('error', err => { clearTimeout(t); reject(new Error(`it needs Claude Code, and ${CLAUDE_BIN} didn't start (${err.code})`)) })
+ p.on('close', code => { clearTimeout(t); code === 0 ? resolve(o) : reject(new Error(e.trim().split('\n').pop() || `editor exited ${code}`)) })
+ p.stdin.end(prompt)
+ })
+ const res = JSON.parse(out)
+ log(`soul editor: ${Date.now() - t0} ms (model ${res.duration_api_ms} ms, ${res.usage?.output_tokens} tokens out)`)
+ const text = String(res.result ?? '').replace(/^```(json)?|```$/gm, '').trim()
+ const r = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1))
+ if (r.clarify) return { clarify: String(r.clarify).slice(0, 160) }
+ const changes = {}
+ for (const [k, v] of Object.entries(r.changes ?? {})) {
+ if (!(k in SOUL_FIELDS) || typeof v !== 'string') continue
+ const val = v.replace(/\n/g, k === 'body' ? '\n' : ' ').trim()
+ if (!val && k === 'name') continue
+ if (val.length > SOUL_FIELDS[k]) throw new Error(`${k} came out too long`)
+ if (val !== (cur[k] ?? '')) changes[k] = val
+ }
+ if (!Object.keys(changes).length) return { clarify: "That wouldn't change anything. What should be different?" }
+ const id = crypto.randomBytes(6).toString('hex')
+ proposals.set(id, { agent: agentId, base: soulRev(agentId), changes, summary: String(r.summary ?? '').slice(0, 200), at: Date.now() })
+ for (const [k, v] of proposals) if (Date.now() - v.at > 15 * 60_000) proposals.delete(k)
+ return { proposal: id, summary: proposals.get(id).summary, soul: { ...cur, ...changes } }
+}
+
+const saveSoul = (agentId, proposalId) => serially(async () => {
+ const p = proposals.get(proposalId)
+ if (!p || p.agent !== agentId) throw Object.assign(new Error('That change is no longer open. Say it again.'), { code: 409 })
+ if (p.base !== soulRev(agentId)) { proposals.delete(proposalId); throw Object.assign(new Error('The soul changed since. Say it again.'), { code: 409 }) }
+ proposals.delete(proposalId)
+ fs.writeFileSync(soulFile(agentId), renderSoul({ ...soulOf(agentId), ...p.changes }))
+ await git('add', `${agentId}.md`); await git('commit', '-q', '-m', `${agentId}: ${p.summary || 'changed'}`)
+ log('soul saved:', agentId, p.summary); bump()
+ return soulCard(agentId)
+})
+
+/// One part of a soul, written as it is (the iPhone edits them one at a time; no model in between).
+const setSoul = (agentId, field, value) => serially(async () => {
+ if (!['name', 'owns', 'refers', 'voice', 'body'].includes(field)) throw Object.assign(new Error('No such part.'), { code: 400 })
+ const v = String(value ?? '').replace(/\r/g, '').replace(field === 'body' ? /(?!)/ : /\n/g, ' ').trim()
+ if (field === 'name' && !v) throw Object.assign(new Error('It needs a name.'), { code: 400 })
+ if (v.length > SOUL_FIELDS[field]) throw Object.assign(new Error(`That's longer than ${SOUL_FIELDS[field]} characters.`), { code: 400 })
+ const cur = soulOf(agentId)
+ if ((cur[field] ?? '') === v) return soulCard(agentId)
+ fs.writeFileSync(soulFile(agentId), renderSoul({ ...cur, [field]: v }))
+ await git('add', `${agentId}.md`); await git('commit', '-q', '-m', `${agentId}: ${field} set`)
+ log('soul set:', agentId, field); bump()
+ return soulCard(agentId)
+})
+
+const undoSoul = agentId => serially(async () => {
+ const log1 = (await git('log', '--format=%H %s', '--', `${agentId}.md`)).split('\n').filter(Boolean)
+ if (log1.length < 2) throw Object.assign(new Error('Nothing to undo.'), { code: 409 })
+ const [, prev] = log1.map(l => l.split(' ')[0])
+ fs.writeFileSync(soulFile(agentId), await git('show', `${prev}:${agentId}.md`) + '\n')
+ await git('add', `${agentId}.md`); await git('commit', '-q', '-m', `${agentId}: undo (${log1[0].slice(41)})`)
+ log('soul undone:', agentId); bump()
+ return soulCard(agentId)
+})
+
+async function soulCard(agentId) {
+ const s = soulOf(agentId)
+ const n = (await git('log', '--format=%H', '--', `${agentId}.md`).catch(() => '')).split('\n').filter(Boolean).length
+ return { id: agentId, name: s.name, owns: s.owns, refers: s.refers, voice: s.voice, body: s.body, canUndo: n > 1 }
+}
+const stateWaiters = new Set()
+
+function bump() {
+ rev++
+ for (const w of stateWaiters) w()
+ stateWaiters.clear()
+}
+
+// What a watch-sized approval card should say: the command for Bash, the file name for edits.
+// Built from input_preview (the real arguments), never only from Claude's own description.
+function summarize(tool, preview, description) {
+ let args = null
+ try { args = JSON.parse(preview) } catch {}
+ const field = k => args?.[k] ?? preview.match(new RegExp(`"${k}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`))?.[1]
+ const cmd = field('command')
+ if (cmd) return cmd.replace(/\\n/g, ' ').slice(0, 160)
+ const file = field('file_path') ?? field('notebook_path') ?? field('path')
+ if (file) {
+ const verb = { Write: 'write', Edit: 'edit', MultiEdit: 'edit', NotebookEdit: 'edit', Read: 'read' }[tool] ?? tool
+ return `${verb} ${file.split('/').pop()}`
+ }
+ const url = field('url')
+ if (url) return url.slice(0, 160)
+ return (description || tool).slice(0, 160)
+}
+
+// ---------- the watch's battery, from its polls: what keyring mode costs ----------
+// One line per 5 minutes (or per 1% change) in ~/.chums/watch-battery.csv: time, level 0–1, charging, screen on/dim, keyring.
+const BATTERY_LOG = path.join(CONFIG_DIR, 'watch-battery.csv')
+let lastBattery = { at: 0, level: -1 }
+function noteBattery(q) {
+ if (!q.has('battery')) return // the Simulator and tests don't send one
+ const level = Number(q.get('battery'))
+ if (!(level >= 0 && level <= 1)) return
+ const now = Date.now()
+ if (now - lastBattery.at < 5 * 60_000 && Math.abs(level - lastBattery.level) < 0.01) return
+ lastBattery = { at: now, level }
+ try { if (fs.statSync(BATTERY_LOG).size > 10e6) fs.renameSync(BATTERY_LOG, BATTERY_LOG + '.1') } catch {} // past 10 MB, a new file
+ if (!fs.existsSync(BATTERY_LOG)) fs.writeFileSync(BATTERY_LOG, 'time,level,charging,screen,keyring\n')
+ const field = k => oneLine(q.get(k), 12).replace(/[,"]/g, '')
+ fs.appendFileSync(BATTERY_LOG, [new Date(now).toISOString(), level, field('charging'), field('screen'), field('keyring')].join(',') + '\n')
+}
+/// What a client sent, for a log line or a file: one line of printable characters, at most n of them.
+const oneLine = (v, n) => String(v ?? '').replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, n)
+/// The device an order came from ("watch", "phone"): a short name, or none.
+const deviceOf = d => typeof d === 'string' && /^[\w-]{1,24}$/.test(d) ? d : null
+
+// "blocked" in a reply is a message: after a minute the session just waits
+const statusOf = s => s.status === 'blocked' && s.blockedReplyAt && Date.now() - s.blockedReplyAt > 60_000 ? 'idle' : s.status
+function publicState() {
+ return {
+ rev,
+ sessions: [...sessions.values()].map(s => ({
+ id: s.id, name: s.name, lastLine: s.lastLine ?? null, subagents: s.subagents ?? 0, status: statusOf(s),
+ })),
+ runtimes: available(), // what an agent can be switched to on this Mac
+ // every agent, running or not: the watch's switcher and its "needs you" badge
+ agents: agents.map(a => {
+ const s = sessionOf(a.id)
+ return { id: a.id, name: soulOf(a.id).name || a.name, owns: soulOf(a.id).owns ?? null, character: a.character, runtime: a.runtime ?? 'claude', model: a.model ?? null,
+ permission: permissionOf(a), voice: a.voice ?? null, status: s ? statusOf(s) : 'offline', line: s?.lastLine ?? null,
+ needs: s ? (approvalsFor(s) || statusOf(s) === 'waiting') : false }
+ }),
+ tools: tools.slice(-20),
+ reactions: reactions.slice(-10),
+ approvals: [...approvals.values()].map(a => ({
+ requestId: a.requestId, session: a.session, tool: a.tool,
+ description: a.description, preview: a.preview, summary: a.summary,
+ })),
+ spoken: newestPerAgent(SHOWN_PER_AGENT),
+ focus,
+ }
+}
+
+// the conversation outlives a hub restart: each agent's last 40 lines in ~/.chums/conversation.json (voices aren't kept)
+const CONVERSATION = path.join(CONFIG_DIR, 'conversation.json')
+try { spoken.push(...JSON.parse(fs.readFileSync(CONVERSATION, 'utf8')).map(l => ({ ...l, audio: undefined }))) } catch {}
+// The agent you last talked to or looked at on the iPhone, from any device: the widgets show it when none is picked.
+// It starts as the one the conversation last went to.
+let focus = spoken.findLast(l => l.kind === 'echo' && l.agent)?.agent ?? null
+function focusOn(id) {
+ if (!agentNamed(id) || focus === id) return
+ focus = id; bump()
+}
+let saveT = null
+const saveConversation = () => { clearTimeout(saveT); saveT = setTimeout(() => fs.writeFile(CONVERSATION, JSON.stringify(spoken.map(({ rev: _, ...l }) => l)), () => {}), 500) }
+// Each agent keeps its own lines (KEPT_PER_AGENT, the hub's own notes as one more), so a busy agent never pushes a
+// quiet one's conversation out; the apps get the newest SHOWN_PER_AGENT of each.
+const KEPT_PER_AGENT = 40, SHOWN_PER_AGENT = 20
+const whose = l => l.agent ?? l.session
+function newestPerAgent(n) {
+ const count = new Map(), keep = []
+ for (let i = spoken.length - 1; i >= 0; i--) {
+ const k = whose(spoken[i]), c = count.get(k) ?? 0
+ if (c < n) { count.set(k, c + 1); keep.push(spoken[i]) }
+ }
+ return keep.reverse()
+}
+function trimConversation() {
+ const kept = newestPerAgent(KEPT_PER_AGENT)
+ if (kept.length !== spoken.length) spoken.splice(0, spoken.length, ...kept)
+}
+
+function say(text, session = 'Chums', kind = 'info', extra = {}) {
+ const id = crypto.randomUUID()
+ const line = { id, session, text, kind, at: Date.now(), ...(agentNamed(session) ? { agent: session } : {}), ...extra }
+ const publish = () => {
+ line.rev = rev + 1 // the state it's new in: its voice rides along there
+ spoken.push(line)
+ trimConversation()
+ saveConversation()
+ bump()
+ }
+ // a line the watch reads aloud gets its agent's voice, rendered on the Mac. It goes out once that's ready (about
+ // 0.2 s), with the audio in the same answer the watch is waiting on: no second trip for it. Never held over 1.5 s.
+ if (!SPOKEN_KINDS.has(kind) || !tts.enabled()) return publish()
+ line.audio = `/v1/speech/${id}`
+ const job = tts.render(id, text, voiceOf(line))
+ Promise.race([job, new Promise(r => setTimeout(r, 1500))]).then(publish)
+}
+/// The voice a line is read in: its agent's (agents.json "voice"), else the first agent's.
+const voiceOf = line => agentNamed(line.agent)?.voice ?? agentNamed(LOOKS[0])?.voice ?? DEFAULT_VOICE
+
+// ---------- the voice: replies rendered on the Mac and played by the watch ----------
+// cfg.tts = { engine: 'say', voice: 'Ava (Premium)' } a macOS voice (download Premium ones in System Settings ›
+// Accessibility › Spoken Content › System Voice › Manage Voices)
+// or { engine: 'openai', voice: 'sage', model: 'gpt-4o-mini-tts', key: 'sk-…' } a neural voice
+// Without cfg.tts the watch speaks with its own voice.
+const SPOKEN_KINDS = new Set(['done', 'question', 'blocked', 'working', 'status', 'ask', 'info', 'artifact'])
+
+// ---------- artifacts: what a session shows you on the watch and the iPhone ----------
+// What a session shows with chums_show (a page by its URL, a file, a screenshot it took of the screen or an app's
+// window) and what you send from the iPhone, made into a picture: the watch has no web engine. Each kind's renderer:
+// page (a URL, .html, .htm) and .svg Safari's engine at phone width (tools/page-shot.swift)
+// pdf every page, stacked, as far as 10 M pixels go (tools/pdf-shot.swift)
+// doc (.md, .markdown) hub/render.mjs makes a dark HTML page of it, rendered like a page
+// text (code, logs, any UTF-8 text) the same: monospaced, the first lines that fit in one picture
+// table (.csv, .tsv) the same: a table of the first rows
+// video (.mov, .mp4, .m4v) a still from a second in (ffmpeg; Quick Look's without it)
+// doc (anything else) Quick Look's picture, as Finder draws it (tools/ql-shot.swift): Word, Excel,
+// PowerPoint, Pages, Keynote, Numbers, RTF, EPUB, USDZ…; with none, an error
+// image, screenshot as they are
+// Each is kept in ~/.chums/artifacts/<id>/ as full.jpg (what the viewer shows, zoomable), thumb.jpg (the pill in the
+// chat) and meta.json, and for the iPhone, which opens it itself: the file as it was (source.<ext>, up to 25 MB) and
+// the HTML page the hub made of it (view.html). meta.view says what the iPhone opens. The last 60 are kept.
+const ART_DIR = path.join(CONFIG_DIR, 'artifacts')
+const run = (cmd, args, timeout = 40_000) => new Promise((resolve, reject) =>
+ execFile(cmd, args, { timeout }, (e, out, errOut) => e ? reject(new Error(String(errOut || e.message).trim().split('\n').pop())) : resolve(String(out).trim())))
+/// A Swift helper in tools/, compiled to ~/.chums/bin/<name> on first use and again when its source changes (one
+/// compile at a time, written whole).
+const compiling = new Map()
+async function helper(name) {
+ const src = path.join(ROOT, 'tools', `${name}.swift`), bin = path.join(CONFIG_DIR, 'bin', name)
+ if (fs.existsSync(bin) && fs.statSync(bin).mtimeMs >= fs.statSync(src).mtimeMs) return bin
+ if (!compiling.has(name)) compiling.set(name, (async () => {
+ fs.mkdirSync(path.dirname(bin), { recursive: true })
+ await run('/usr/bin/swiftc', ['-O', '-o', `${bin}.new`, src], 180_000)
+ fs.renameSync(`${bin}.new`, bin)
+ })().finally(() => compiling.delete(name)))
+ await compiling.get(name)
+ return bin
+}
+/// A command in Homebrew's folders, ~/.local/bin, ~/.npm-global/bin or on PATH (a LaunchAgent's PATH is its plist's).
+const whichBin = cmd => [`${HOME}/.npm-global/bin`, `${HOME}/.local/bin`, '/opt/homebrew/bin', '/usr/local/bin', ...(process.env.PATH ?? '').split(':')]
+ .filter(Boolean).map(d => path.join(d, cmd)).find(f => fs.existsSync(f)) ?? null
+const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.heic', '.webp', '.tiff', '.tif', '.bmp'])
+const VIDEO_EXT = new Set(['.mov', '.mp4', '.m4v'])
+const MARKDOWN_EXT = new Set(['.md', '.markdown'])
+const TABLE_EXT = new Set(['.csv', '.tsv'])
+const TEXT_EXT = new Set(['.txt', '.log', '.json', '.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '.swift', '.py', '.sh', '.zsh', '.bash',
+ '.yml', '.yaml', '.toml', '.ini', '.css', '.scss', '.go', '.rs', '.rb', '.java', '.kt', '.c', '.h', '.cpp', '.hpp', '.m', '.mm',
+ '.sql', '.xml', '.plist', '.diff', '.patch'])
+const QUICK_LOOK_EXT = new Set(['.rtf']) // text, but what it shows is a document
+const TOP_KINDS = new Set(['page', 'pdf', 'doc', 'text', 'table']) // their pill shows the top, not the middle
+// sips reads a crop offset of 0 0 as none and crops the middle: 1 0 is the top (one row down)
+const TOP = ['--cropOffset', '1', '0']
+/// The Content-Type an original is served with (/v1/artifact/<id>/source), by its extension.
+const MIME = { html: 'text/html; charset=utf-8', htm: 'text/html; charset=utf-8', svg: 'image/svg+xml', pdf: 'application/pdf',
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', heic: 'image/heic', webp: 'image/webp', tiff: 'image/tiff',
+ tif: 'image/tiff', bmp: 'image/bmp', mov: 'video/quicktime', mp4: 'video/mp4', m4v: 'video/x-m4v', md: 'text/markdown; charset=utf-8',
+ markdown: 'text/markdown; charset=utf-8', csv: 'text/csv; charset=utf-8', tsv: 'text/tab-separated-values; charset=utf-8',
+ rtf: 'application/rtf', doc: 'application/msword', xls: 'application/vnd.ms-excel', ppt: 'application/vnd.ms-powerpoint',
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ pages: 'application/vnd.apple.pages', key: 'application/vnd.apple.keynote', numbers: 'application/vnd.apple.numbers',
+ epub: 'application/epub+zip', usdz: 'model/vnd.usdz+zip', odt: 'application/vnd.oasis.opendocument.text' }
+const size = async f => { const o = await run('/usr/bin/sips', ['-g', 'pixelWidth', '-g', 'pixelHeight', f]); return { w: +o.match(/pixelWidth: (\d+)/)[1], h: +o.match(/pixelHeight: (\d+)/)[1] } }
+/// The text of a file's first 64 KB when it is UTF-8 text (no NUL; a character cut at the end doesn't count), else null.
+async function textHead(file, bytes) {
+ const fh = await fs.promises.open(file)
+ try {
+ const buf = Buffer.alloc(Math.min(bytes, 65536)), { bytesRead } = await fh.read(buf, 0, buf.length, 0), head = buf.subarray(0, bytesRead)
+ if (head.includes(0)) return null
+ for (let cut = 0; cut <= (bytesRead < bytes ? 3 : 0); cut++) {
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(head.subarray(0, bytesRead - cut)) } catch {}
+ }
+ return null
+ } finally { await fh.close() }
+}
+/// A title with what the picture shows of it ("report.pdf, pages 1–7 of 14"), 60 characters at most, the note kept.
+const titled = (title, note) => {
+ const t = String(title)
+ if (!note) return t.slice(0, 60)
+ const room = 60 - note.length - 2
+ return `${t.length > room ? t.slice(0, Math.max(1, room - 1)) + '…' : t}, ${note}`
+}
+
+async function makeArtifact({ file, url, title, kind, from, name }) {
+ const id = crypto.randomBytes(6).toString('hex'), dir = path.join(ART_DIR, id)
+ fs.mkdirSync(dir, { recursive: true })
+ let src, k = kind, note = null, cutNote = null, cut = false, type, ext = '', st = null
+ // a page rendered by page-shot: its picture, and whether the page was taller than the picture
+ const shoot = async (target, ...more) => {
+ src = path.join(dir, 'page.png')
+ cut = / cut$/.test(await run(await helper('page-shot'), [target, src, ...more]))
+ }
+ try {
+ if (url) {
+ if (!/^https?:\/\//.test(url)) throw new Error('only http(s) pages')
+ await shoot(url); k ??= 'page'; type = 'url'
+ title ??= new URL(url).hostname.replace(/^www\./, '')
+ } else {
+ st = file ? await fs.promises.stat(file).catch(() => null) : null
+ if (!st) throw new Error(`no such file: ${file}`)
+ ext = path.extname(file).toLowerCase()
+ title ??= path.basename(file)
+ // made into HTML by hub/render.mjs, in its own process: the page the picture is made of, and what it shows
+ const render = async what => {
+ const r = JSON.parse(await run(process.execPath, [path.join(ROOT, 'hub/render.mjs'), what, file, dir, String(title)], 30_000))
+ await shoot(path.join(dir, r.shot), '390', '2', String(r.maxWidth ?? 390))
+ fs.rmSync(path.join(dir, 'shot.html'), { force: true })
+ note = r.note; cutNote = r.cutNote
+ }
+ if (st.isDirectory()) { if (!/\.\w+$/.test(file)) throw new Error(`${file} is a folder`) } // a bundle (.rtfd, .pages): Quick Look
+ else if (['.html', '.htm', '.svg'].includes(ext)) { await shoot(file); k ??= ext === '.svg' ? 'image' : 'page'; type = 'html' }
+ else if (ext === '.pdf') {
+ src = path.join(dir, 'page.png')
+ const [, shown, pages] = (await run(await helper('pdf-shot'), [file, src], 60_000)).split(' ').map(Number)
+ if (shown < pages) note = `pages 1–${shown} of ${pages}`
+ k ??= 'pdf'; type = 'pdf'
+ }
+ else if (IMAGE_EXT.has(ext)) { src = file; k ??= 'image'; type = 'image' }
+ else if (MARKDOWN_EXT.has(ext)) { await render('markdown'); k ??= 'doc'; type = 'html' }
+ else if (TABLE_EXT.has(ext)) { await render('table'); k ??= 'table'; type = 'html' }
+ else if (VIDEO_EXT.has(ext)) {
+ src = path.join(dir, 'still.png')
+ const ffmpeg = whichBin('ffmpeg')
+ // a second in (the first frame is often black); a shorter video, its first frame
+ for (const at of ffmpeg ? ['1', '0'] : []) {
+ await run(ffmpeg, ['-loglevel', 'error', '-protocol_whitelist', 'file', '-ss', at, '-i', file, '-frames:v', '1', '-y', src], 30_000).catch(() => {})
+ if (fs.statSync(src, { throwIfNoEntry: false })?.size) { note = at === '1' ? 'a still at 0:01' : 'a still'; break }
+ }
+ if (!fs.statSync(src, { throwIfNoEntry: false })?.size) { await run(await helper('ql-shot'), [file, src], 30_000); note = 'a still' }
+ k ??= 'video'; type = 'video'
+ }
+ else if (TEXT_EXT.has(ext) || (!QUICK_LOOK_EXT.has(ext) && await textHead(file, st.size) !== null)) { await render('text'); k ??= 'text'; type = 'text' }
+ if (!src) {
+ src = path.join(dir, 'page.png')
+ await run(await helper('ql-shot'), [file, src], 30_000)
+ .catch(() => { throw new Error(`can't show ${ext || 'that'} files: Quick Look has no picture of ${path.basename(file)}`) })
+ k ??= 'doc'; type = 'doc'
+ }
+ }
+ // the viewer's picture: up to 1200 px wide (a page rendered at 2× is 780), and never more than 10 M pixels tall
+ let { w, h } = await size(src)
+ const W = Math.min(w, k === 'page' ? 780 : 1200), H = Math.round(h * W / w), cap = Math.min(H, Math.floor(10_000_000 / W))
+ const full = path.join(dir, 'full.jpg')
+ await run('/usr/bin/sips', ['-s', 'format', 'jpeg', '-s', 'formatOptions', '78', '--resampleWidth', String(W), src, '--out', full])
+ if (cap < H) { await run('/usr/bin/sips', ['-c', String(cap), String(W), ...TOP, full, '--out', full]); cut = true }
+ if (cut && cutNote) note = cutNote
+ ;({ w, h } = await size(full))
+ // the pill's: a 160 px square, from the top of a page or a document, from the middle of anything else
+ const thumb = path.join(dir, 'thumb.jpg'), tall = h >= w
+ await run('/usr/bin/sips', ['-s', 'format', 'jpeg', '-s', 'formatOptions', '75', tall ? '--resampleWidth' : '--resampleHeight', '160', full, '--out', thumb])
+ const t = await size(thumb), across = Math.max(0, Math.round((t.w - 160) / 2))
+ await run('/usr/bin/sips', ['-c', '160', '160', ...(TOP_KINDS.has(k) ? (across ? ['--cropOffset', '0', String(across)] : TOP) : []), thumb, '--out', thumb])
+ if (src.startsWith(dir) && src !== full) fs.rmSync(src, { force: true })
+ // what the iPhone opens: the original (up to 25 MB) and the hub's HTML page of it
+ let view = null
+ if (url) view = { type, name: new URL(url).hostname, url }
+ else {
+ const source = st.isFile() && st.size <= UPLOAD_MAX ? `source${/^\.[a-z0-9]{1,12}$/.test(ext) ? ext : ''}` : null
+ if (source) await fs.promises.copyFile(file, path.join(dir, source), fs.constants.COPYFILE_FICLONE)
+ const html = fs.existsSync(path.join(dir, 'view.html')) ? 'view.html' : null
+ const named = name ?? (k === 'screenshot' ? `Screenshot${from && from !== 'screen' ? ` of ${from}` : ''}${ext}` : path.basename(file))
+ if (source || html) view = { type, name: named, ext: ext.slice(1), size: st.size, source: !!source, file: html ?? source }
+ }
+ const meta = { id, kind: k, title: titled(title, note), from: from ?? null, w, h, at: Date.now(), ...(view ? { view } : {}) }
+ fs.writeFileSync(path.join(dir, 'meta.json'), JSON.stringify(meta))
+ // keep the last 60
+ const all = fs.readdirSync(ART_DIR).map(d => ({ d, t: fs.statSync(path.join(ART_DIR, d)).mtimeMs })).sort((a, b) => b.t - a.t)
+ for (const { d } of all.slice(60)) fs.rmSync(path.join(ART_DIR, d), { recursive: true, force: true })
+ return meta
+ } catch (e) { fs.rmSync(dir, { recursive: true, force: true }); throw e }
+}
+
+// ---------- uploads: pictures and files sent from the iPhone ----------
+// Kept in ~/.chums/uploads (the last 40, at most 25 MB each). An order can carry them: the agent gets their paths, and
+// what the hub can make a picture of (makeArtifact) shows in the conversation as what you sent.
+const UPLOAD_DIR = path.join(CONFIG_DIR, 'uploads')
+const UPLOAD_MAX = 25 * 1024 * 1024
+async function upload(name, buf) {
+ fs.mkdirSync(UPLOAD_DIR, { recursive: true, mode: 0o700 })
+ const safe = String(name || 'file').normalize('NFKD').replace(/[^\w.\- ]+/g, '').trim().replace(/\s+/g, '-')
+ .replace(/^[.-]+/, '').slice(-80) || 'file'
+ const file = path.join(UPLOAD_DIR, `${Date.now()}-${crypto.randomBytes(3).toString('hex')}-${safe}`)
+ fs.writeFileSync(file, buf, { mode: 0o600 })
+ const all = fs.readdirSync(UPLOAD_DIR).sort().reverse()
+ for (const f of all.slice(40)) fs.rmSync(path.join(UPLOAD_DIR, f), { force: true })
+ let artifact = null
+ try { artifact = await makeArtifact({ file, title: safe, from: 'you', name: safe }) } catch {} // not a picture: just the file
+ if (artifact) { uploadArt.set(file, artifact); if (uploadArt.size > 40) uploadArt.delete(uploadArt.keys().next().value) }
+ log('upload', safe, `${buf.length}B`, artifact ? artifact.kind : 'file')
+ return { path: file, name: safe, artifact }
+}
+const uploadArt = new Map() // an upload's picture in the conversation, by path
+const artifactFor = f => uploadArt.get(f) ?? null
+/// The uploads an order names, kept only if they really are files in the uploads folder (by their resolved path: that
+/// is what the agent is given).
+const uploaded = files => (Array.isArray(files) ? files : []).map(f => path.resolve(String(f)))
+ .filter(f => path.dirname(f) === UPLOAD_DIR && fs.statSync(f, { throwIfNoEntry: false })?.isFile()).slice(0, 10)
+const SPEECH_DIR = path.join(os.tmpdir(), 'chums-speech')
+fs.mkdirSync(SPEECH_DIR, { recursive: true })
+// cfg.tts = { engine: 'kokoro' } the default when Kokoro is installed (bin/chums-setup): each agent its own voice
+// or { engine: 'say', voice: 'Ava (Premium)' } / { engine: 'openai', … } (above), or { engine: 'watch' }
+const ttsEngine = () => cfg.tts?.engine ?? (fs.existsSync(KOKORO_PY) ? 'kokoro' : 'watch')
+const tts = {
+ jobs: new Map(), // id -> Promise<file path | null>
+ data: new Map(), // id -> the m4a, for the long poll that carries the line
+ enabled() {
+ const e = ttsEngine()
+ return e === 'kokoro' ? kokoro.ready : e === 'say' ? !!cfg.tts.voice : e === 'openai' ? !!cfg.tts.key : false
+ },
+ render(id, text, voice) {
+ const out = path.join(SPEECH_DIR, `${id}.m4a`), t0 = Date.now(), e = ttsEngine()
+ const job = (e === 'kokoro' ? this.kokoro(text, voice, out) : e === 'openai' ? this.openai(text, out) : this.say(text, out))
+ .then(() => { log(`speech ${e}${e === 'kokoro' ? ` ${voice}` : ''} ${Date.now() - t0}ms`); this.data.set(id, fs.readFileSync(out)); return out })
+ .catch(err => { log('speech failed:', err.message); return null })
+ this.jobs.set(id, job)
+ if (this.jobs.size > 60) { const [old] = this.jobs.keys(); this.jobs.delete(old); this.data.delete(old); fs.rm(path.join(SPEECH_DIR, `${old}.m4a`), () => {}) }
+ return job
+ },
+ async kokoro(text, voice, out) {
+ const r = await fetch(`http://127.0.0.1:${KOKORO_PORT}/speak`, { method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text, voice }), signal: AbortSignal.timeout(10_000) })
+ if (!r.ok) throw new Error(`kokoro ${r.status}`)
+ fs.writeFileSync(out, Buffer.from(await r.arrayBuffer()))
+ },
+ say(text, out) {
+ const aiff = out.replace(/\.m4a$/, '.aiff')
+ const run = (cmd, args) => new Promise((ok, no) => spawn(cmd, args).on('error', no).on('exit', c => c === 0 ? ok() : no(new Error(`${cmd} exited ${c}`))))
+ return run('say', ['-v', cfg.tts.voice, '-o', aiff, text])
+ .then(() => run('afconvert', ['-f', 'm4af', '-d', 'aac', aiff, out]))
+ .finally(() => fs.rm(aiff, () => {}))
+ },
+ async openai(text, out) {
+ const r = await fetch('https://api.openai.com/v1/audio/speech', {
+ method: 'POST', headers: { authorization: `Bearer ${cfg.tts.key}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ model: cfg.tts.model ?? 'gpt-4o-mini-tts', voice: cfg.tts.voice ?? 'sage', input: text, response_format: 'aac',
+ instructions: cfg.tts.style ?? 'Warm, calm and brief, like a friendly assistant reading one short update.' }),
+ })
+ if (!r.ok) throw new Error(`openai ${r.status}`)
+ fs.writeFileSync(out, Buffer.from(await r.arrayBuffer()))
+ },
+}
+
+// ---------- the voices: Kokoro on this Mac (tools/kokoro-server.py), started with the hub, every agent's voice warm ----------
+const kokoro = {
+ proc: null, ready: false,
+ start() {
+ if (ttsEngine() !== 'kokoro' || !fs.existsSync(KOKORO_PY)) return
+ const voices = [...new Set([...agents.map(a => a.voice), DEFAULT_VOICE].filter(Boolean))]
+ this.proc = spawn(KOKORO_PY, [path.join(ROOT, 'tools/kokoro-server.py'), '--port', String(KOKORO_PORT), '--voices', voices.join(',')],
+ { stdio: ['ignore', 'ignore', 'pipe'], env: { ...process.env, HF_HUB_OFFLINE: process.env.CHUMS_KOKORO_ONLINE ? '' : '1', TOKENIZERS_PARALLELISM: 'false' } })
+ this.proc.stderr.on('data', d => { const m = String(d).match(/kokoro: .*/); if (m) log(m[0]) })
+ this.proc.on('error', e => { log(`kokoro didn't start (${e.code}): bin/chums-setup installs it again`); this.proc = null }) // no 'exit' follows
+ this.proc.on('exit', code => {
+ this.ready = false; this.proc = null
+ if (code !== 0 && code !== null) log('kokoro exited', code, '- restarting in 5 s')
+ if (!quitting) setTimeout(() => this.start(), 5000)
+ })
+ this.wait()
+ },
+ async wait() {
+ for (let i = 0; i < 180 && this.proc; i++) {
+ try { if ((await fetch(`http://127.0.0.1:${KOKORO_PORT}/health`)).ok) { this.ready = true; return } } catch {}
+ await new Promise(r => setTimeout(r, 1000))
+ }
+ },
+ /// After a quiet minute the chips slow down and a render takes about 0.45 s instead of 0.15 s; a single word doesn't
+ /// speed them up, a sentence every 2 s does (measured). So while an agent works on an order from the watch, Kokoro
+ /// says a sentence nobody hears every 2 s, until the reply comes (or for 45 s, for a long task): about 5% of the GPU
+ /// while you wait, and the reply renders at full speed.
+ warmUntil: 0, warmTimer: null,
+ keepWarm(voice) {
+ if (!this.ready || !voice) return
+ this.warmUntil = Date.now() + 45_000; this.warmVoice = voice
+ if (this.warmTimer) return
+ const tick = () => {
+ if (!this.ready || Date.now() > this.warmUntil) { this.stopWarm(); return }
+ fetch(`http://127.0.0.1:${KOKORO_PORT}/speak`, { method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text: 'Working on it, one moment please.', voice: this.warmVoice }), signal: AbortSignal.timeout(5000) })
+ .then(r => r.arrayBuffer()).catch(() => {})
+ }
+ tick(); this.warmTimer = setInterval(tick, 2000)
+ },
+ stopWarm() { clearInterval(this.warmTimer); this.warmTimer = null },
+}
+let quitting = false
+
+// Orders and verdicts stay in the session's inbox until its channel acknowledges them (the next /channel/next
+// carries ?ack=ids), so a response lost on the way is delivered again; the channel ignores ids it has seen.
+function deliver(session, item) {
+ item.id ??= crypto.randomUUID()
+ if (session.driver) return session.driver.deliver(item) // a session the hub runs itself (hub/runtimes.mjs)
+ session.inbox.push(item)
+ if (session.waiter) { session.waiter(); session.waiter = null }
+}
+
+// Sessions that stop polling are gone (Claude Code exited).
+setInterval(() => {
+ const now = Date.now()
+ for (const s of sessions.values()) {
+ if (s.driver) continue // the hub runs it: it leaves when its process exits
+ if (now - s.lastSeen > 60_000) {
+ sessions.delete(s.id)
+ for (const [id, a] of approvals) if (a.sessionId === s.id) approvals.delete(id)
+ log('session gone:', s.name)
+ bump()
+ }
+ }
+}, 15_000)
+
+// ---------- tool calls (hooks) ----------
+const TEST_CMD = /\b(test|tests|jest|vitest|pytest|xcodebuild test|swift test|go test|cargo test|rspec|mocha)\b/i
+const base = f => String(f ?? '').split('/').pop()
+/// A tool call in a few words ("Bash npm test", "Edit hub.mjs"), its argument cut to fit a line on the watch (or at n).
+function toolEvent(tool, input, n) {
+ const i = input ?? {}, cut = (v, fit) => String(v ?? '').slice(0, n ?? fit)
+ if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit'].includes(tool)) return { type: 'edit', text: `${tool === 'Write' ? 'Write' : 'Edit'} ${base(i.file_path ?? i.notebook_path)}` }
+ if (tool === 'Read') return { type: 'read', text: `Read ${base(i.file_path)}` }
+ if (tool === 'Grep') return { type: 'read', text: `Grep ${cut(i.pattern, 28)}` }
+ if (tool === 'Glob') return { type: 'read', text: `Glob ${cut(i.pattern, 28)}` }
+ if (tool === 'WebFetch' || tool === 'WebSearch') return { type: 'read', text: `${tool} ${cut(String(i.url ?? i.query ?? '').replace(/^https?:\/\//, ''), 26)}` }
+ if (tool === 'Bash') { const c = String(i.command ?? '').replace(/\s+/g, ' ').trim(); return { type: TEST_CMD.test(c) ? 'test' : 'bash', text: `Bash ${cut(c, 30)}` } }
+ if (tool === 'Task' || tool === 'Agent') return { type: 'agent', text: `Subagent ${cut(i.description, 26)}` }
+ return { type: 'bash', text: tool }
+}
+// A step auto mode refused is a line in the agent's conversation: shown on the watch and the iPhone, never read aloud
+// ('refused' isn't one of the SPOKEN_KINDS, nor of the kinds the apps speak). A burst of refusals is one line a minute.
+const refusedAt = new Map() // agent -> when its last such line was said
+function refused(who, tool, input) {
+ if (Date.now() - (refusedAt.get(who) ?? 0) < 60_000) return
+ refusedAt.set(who, Date.now())
+ const step = toolEvent(tool ?? 'a step', input).text, whole = toolEvent(tool ?? 'a step', input, Infinity).text
+ say(oneLine(`Auto mode refused: ${step}${whole.length > step.length ? '…' : ''}`, 120), who, 'refused')
+}
+function sessionFor(name, cwd) {
+ return [...sessions.values()].find(s => s.cwd === cwd && s.name === name)
+ ?? [...sessions.values()].find(s => s.name === name) ?? [...sessions.values()].find(s => s.cwd === cwd)
+}
+// What each Claude Code hook event means for the watch (design/STATES.md has the full map).
+// Statuses persist; reactions are one-shot (a tool failed, auto mode said no, you interrupted it).
+const LIMITS = new Set(['rate_limit', 'overloaded'])
+const ASKS = new Set(['idle_prompt', 'elicitation_dialog', 'elicitation_url_dialog', 'agent_needs_input', 'permission_prompt'])
+const reactions = [] // { id, session, kind, text, at }
+function react(who, kind, text = '') {
+ reactions.push({ id: crypto.randomUUID(), session: who, kind, text, at: Date.now() })
+ if (reactions.length > 30) reactions.shift()
+}
+function onHook({ name, cwd, event, tool, input, result, notification, message, error, trigger, agent, source, reason, session }) {
+ const s = session ?? sessionFor(name, cwd)
+ const who = s?.name ?? name
+ // Claude Code's own bookkeeping tools aren't work you'd want to see
+ if (tool?.startsWith('mcp__chums__') || ['ToolSearch', 'TodoWrite', 'TodoRead', 'EnterPlanMode', 'ListMcpResourcesTool', 'ReadMcpResourceTool'].includes(tool)) return
+ const agents = s ? (s.agents ??= new Set()) : null
+ const sync = () => { if (s) s.subagents = agents.size }
+ switch (event) {
+ case 'SessionStart':
+ if (s) { s.status = 'idle'; agents.clear(); sync() }
+ if (source === 'compact' && s) s.status = 'working'
+ react(who, 'wake', source ?? '')
+ break
+ case 'SessionEnd':
+ if (s) { s.status = 'idle'; agents.clear(); sync() }
+ react(who, 'sleep', reason ?? '')
+ break
+ case 'UserPromptSubmit':
+ if (s) { if (s.status === 'working') react(who, 'interrupt'); s.status = 'working'; s.lastLine = null; agents.clear(); sync() }
+ break
+ case 'PreToolUse': {
+ if (!tool) break
+ if (s && !['waiting', 'blocked'].includes(s.status)) s.status = 'working'
+ const ev = toolEvent(tool, input)
+ tools.push({ id: crypto.randomUUID(), session: who, ...ev, ok: null, at: Date.now() })
+ if (tools.length > 60) tools.shift()
+ break
+ }
+ case 'PostToolUse': {
+ const last = [...tools].reverse().find(t => t.session === who && t.ok === null)
+ const interrupted = result && /"interrupted"\s*:\s*true/.test(result)
+ if (last) last.ok = !(result && /"(is_?error|interrupted)"\s*:\s*true|\b[1-9]\d* (failed|failing)\b|\bFAIL\b|exit code [1-9]/i.test(result))
+ if (interrupted) react(who, 'interrupt')
+ if (s?.status === 'waiting' && !approvalsFor(s)) { s.status = 'working'; s.lastLine = null } // you answered in the terminal
+ break
+ }
+ case 'PostToolUseFailure': {
+ const last = [...tools].reverse().find(t => t.session === who && t.ok === null)
+ if (last) last.ok = false
+ react(who, 'fail', String(error ?? '').slice(0, 80))
+ break
+ }
+ case 'PermissionDenied':
+ react(who, 'denied', tool ?? '')
+ refused(who, tool, input)
+ break
+ case 'PermissionRequest':
+ // the channel relays the prompt itself (an approval card on the watch); this only keeps the status honest
+ if (s) s.status = 'waiting'
+ break
+ case 'Notification':
+ if (ASKS.has(notification) && s && s.status !== 'limited') { s.status = 'waiting'; if (message) s.lastLine = message }
+ if (notification === 'quota_auto_resume_fired' && s) { s.status = 'working'; s.lastLine = null }
+ if (notification === 'agent_completed') react(who, 'done', message ?? '')
+ break
+ case 'StopFailure':
+ if (s) { s.status = LIMITS.has(error) ? 'limited' : 'blocked'; s.lastLine = String(error ?? 'error').replace(/_/g, ' ') }
+ break
+ case 'PreCompact':
+ if (s) { s.beforeCompact = s.status; s.status = 'compacting' }
+ break
+ case 'PostCompact':
+ if (s) s.soulSent = null // its memory was summarized: send its soul again
+ if (s && s.status === 'compacting') s.status = s.beforeCompact === 'idle' ? 'idle' : 'working'
+ break
+ case 'SubagentStart':
+ if (agents && agent) { agents.add(agent); sync() }
+ break
+ case 'SubagentStop':
+ if (agents && agent) { agents.delete(agent); sync() }
+ break
+ case 'Stop':
+ if (s && ['working', 'compacting', 'waiting'].includes(s.status) && !approvalsFor(s)) s.status = 'idle'
+ if (agents) { agents.clear(); sync() }
+ tools.push({ id: crypto.randomUUID(), session: who, type: 'stop', text: `${who} stopped`, ok: true, at: Date.now() })
+ break
+ }
+ bump()
+}
+function approvalsFor(s) { for (const a of approvals.values()) if (a.sessionId === s.id) return true; return false }
+
+// ---------- routing ----------
+// A spoken verdict is the whole utterance ("yes, but don't run it" is not a yes), and it answers the approval card the
+// watch shows (its id comes with the clip); with no card id and more than one pending, Chums asks instead of guessing.
+const YES = /^(yes|yeah|yep|allow|allow it|approve|approved|approve it|do it|go ahead|sure|ok|okay)$/i
+const NO = /^(no|nope|deny|deny it|don't|do not|stop|cancel|reject)$/i
+const bare = t => t.toLowerCase().replace(/[^a-z' ]/g, ' ').replace(/\s+/g, ' ').trim()
+const STATUS_Q = /\b(what'?s running|status|what happened|anything (new|waiting)|how('s| is) (it|everything) going)\b/i
+
+function norm(s) { return s.toLowerCase().replace(/[^a-z0-9 ]/g, ' ') }
+
+function editDistance(a, b) {
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)])
+ for (let j = 1; j <= b.length; j++) d[0][j] = j
+ for (let i = 1; i <= a.length; i++)
+ for (let j = 1; j <= b.length; j++)
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))
+ return d[a.length][b.length]
+}
+
+// Exact name first; then a loose match per word, since speech-to-text can hear "chums" as "chalm".
+function findNamed(text) {
+ const t = ` ${norm(text)} `
+ const words = norm(text).split(/\s+/).filter(Boolean)
+ let best = null, bestScore = Infinity
+ for (const s of sessions.values()) {
+ const n = norm(s.name).trim()
+ if (!n) continue
+ if (t.includes(` ${n} `)) return s
+ if (n.length < 4 || n.includes(' ')) continue
+ const skel = x => x[0] + x.slice(1).replace(/[aeiouy]/g, '')
+ for (const w of words) {
+ if (w.length < 3 || w[0] !== n[0]) continue
+ const dist = editDistance(w, n)
+ const close = dist <= Math.ceil(n.length * 0.6) && editDistance(skel(w), skel(n)) <= 1
+ if (close && dist < bestScore) { best = s; bestScore = dist }
+ }
+ }
+ return best
+}
+
+function statusLine() {
+ if (sessions.size === 0) return 'No agents are connected. Start them on your Mac with chums-agents install.'
+ const parts = [...sessions.values()].map(s => {
+ const st = s.status === 'waiting' ? 'waiting on you' : s.status
+ return `${s.name} is ${st}`
+ })
+ return parts.join('. ') + '.'
+}
+
+// agentId: who the watch was talking to when the recording started (fixed then, whatever it shows now). With it, the
+// order goes to that agent's session and nowhere else, and a yes or no answers only that agent's requests.
+function route(text, shownApproval = null, agentId = null, device = null, files = [], shown = []) {
+ text = text.trim()
+ const fileNames = files.map(f => path.basename(f).replace(/^\d+-[0-9a-f]{6}-/, '')).join(', ')
+ const filesOnly = !text && files.length > 0 // sent without words: the order asks to look
+ if (filesOnly) text = files.length === 1 ? 'Look at the attached file.' : 'Look at the attached files.'
+ if (!text) return { kind: 'empty', echo: "I didn't catch that." }
+ const agent = agentId ? agentNamed(agentId) : null
+ const tag = agent ? { agent: agent.id } : {}
+
+ const pending = [...approvals.values()].filter(a => !agent || a.session === agent.id)
+ const yes = YES.test(bare(text)), no = NO.test(bare(text))
+ if (pending.length && (yes || no) && !files.length) {
+ const a = shownApproval ? approvals.get(shownApproval) : pending.length === 1 ? pending[0] : null
+ if (!a) {
+ const line = shownApproval ? 'That request is already closed.' : `${pending.length} requests are waiting. Hold the card for the one you mean.`
+ say(line, 'Chums', 'question', tag)
+ return { kind: 'ask', echo: line }
+ }
+ return verdict(a.requestId, yes ? 'allow' : 'deny')
+ }
+
+ if (!agent && !files.length && STATUS_Q.test(text) && !findNamed(text)) {
+ const line = statusLine()
+ say(line, 'Chums', 'status')
+ return { kind: 'status', echo: line }
+ }
+
+ const all = [...sessions.values()]
+ if (agent && !sessionOf(agent.id)) {
+ const line = `${agent.name} isn't running.`
+ say(line, 'Chums', 'ask', tag)
+ return { kind: 'ask', echo: line }
+ }
+ const named = agent ? null : findNamed(text)
+ const recent = all.filter(s => s.lastSpokeAt && Date.now() - s.lastSpokeAt < 10 * 60_000)
+ .sort((a, b) => b.lastSpokeAt - a.lastSpokeAt)[0]
+ const waiting = all.find(s => s.status === 'waiting')
+ const target = agent ? sessionOf(agent.id) : named ?? recent ?? waiting ?? (all.length === 1 ? all[0] : null)
+
+ if (!target) {
+ const line = all.length === 0
+ ? 'No sessions are connected.'
+ : `Which one: ${all.map(s => s.name).join(' or ')}?`
+ say(line, 'Chums', 'question')
+ return { kind: 'ask', echo: line }
+ }
+
+ const id = crypto.randomUUID()
+ const attached = files.length ? `\n\nAttached (files on this Mac; read them): ${files.join(', ')}` : ''
+ deliver(target, { type: 'order', text: soulPrefix(target) + text + attached, said: text, utteranceId: id, device: device ?? 'watch' })
+ target.replyTo = device // its answer is spoken on the device that asked
+ if (agentNamed(target.name)) focusOn(target.name)
+ kokoro.keepWarm(agentNamed(target.name)?.voice)
+ target.status = 'working'
+ // Echo what will happen, minus the routing words: "Tell demo to run the tests" -> "demo: run the tests"
+ const ask = text.replace(new RegExp(`^(please )?(tell|ask|have) (the )?${target.name}( session)?,? (to )?`, 'i'), '')
+ .replace(/^\S+[,:]\s+/, m => (norm(m).trim() === norm(target.name) ? '' : m))
+ const words = ask.split(/\s+/)
+ const said = `“${words.slice(0, 14).join(' ')}${words.length > 14 ? '…' : ''}”`
+ const echo = agent || sessions.size === 1 ? said : `${target.name}: ${said}`
+ const echoTag = agentNamed(target.name) ? { agent: target.name } : {}
+ // what you sent shows with what you said: the first picture on the line itself, any others on lines of their own
+ say(filesOnly ? shown[0]?.title ?? fileNames : echo, 'Chums', 'echo', { ...echoTag, ...(shown[0] ? { artifact: shown[0] } : {}) })
+ for (const a of shown.slice(1)) say(a.title, 'Chums', 'echo', { ...echoTag, artifact: a })
+ log('order ->', target.name, JSON.stringify(text), files.length ? `+ ${files.length} file${files.length > 1 ? 's' : ''}` : '')
+ return { kind: 'order', target: target.name, echo, id }
+}
+
+/// What the owner said on an agent's soul screen: a proposed change (or a question back), nothing saved yet.
+async function soulFromVoice(agentId, text) {
+ if (!agentNamed(agentId)) return { kind: 'soul', error: 'No such agent.' }
+ if (!text.trim()) return { kind: 'soul', error: "I didn't catch that." }
+ try { return { kind: 'soul', ...(await proposeSoul(agentId, text.trim())) } }
+ catch (e) { log('soul edit failed', agentId, e.message); return { kind: 'soul', error: `Couldn't write that change: ${e.message}` } }
+}
+
+/// One spoken line from a session: chums_reply (the channel's, or a hub-run agent's), or the hub speaking for it.
+function replyFrom(s, text, status) {
+ if (status !== 'working') kokoro.stopWarm() // its voice is rendered next: nothing in its way
+ s.lastLine = text
+ s.lastSpokeAt = Date.now()
+ s.status = status === 'working' ? 'working' : status === 'blocked' ? 'blocked'
+ : status === 'question' ? 'waiting' : 'idle'
+ // "blocked" in a reply is a message ("I can't, because…"): it shows for a minute, then the session just waits
+ s.blockedReplyAt = status === 'blocked' ? Date.now() : null
+ say(text, s.name, status ?? 'done', s.replyTo ? { device: s.replyTo } : {}) // tagged with its agent; spoken where it was asked
+ log('reply <-', s.name, `[${status}]`, text)
+}
+
+/// An approval card on the watch for a session's permission prompt.
+function askApproval(s, requestId, tool, description, inputPreview) {
+ approvals.set(requestId, {
+ requestId, sessionId: s.id, session: s.name, tool,
+ description, preview: String(inputPreview ?? '').slice(0, 600),
+ summary: summarize(tool, String(inputPreview ?? ''), description), at: Date.now(),
+ })
+ s.status = 'waiting'
+ log('approval? ', s.name, tool, description)
+ bump()
+}
+
+function verdict(requestId, behavior) {
+ const a = approvals.get(requestId)
+ if (!a) return { kind: 'verdict', echo: 'That request is already closed.' }
+ approvals.delete(requestId)
+ const s = sessions.get(a.sessionId)
+ if (s) {
+ deliver(s, { type: 'verdict', requestId, behavior })
+ s.status = 'working'
+ }
+ const who = agentNamed(a.session)?.name ?? a.session
+ const echo = behavior === 'allow' ? `Allowed. ${who} continues.` : `Denied. ${who} was told no.`
+ say(echo, 'Chums', 'verdict', agentNamed(a.session) ? { agent: a.session } : {})
+ log('verdict', behavior, a.tool, 'for', a.session)
+ return { kind: 'verdict', echo }
+}
+
+// ---------- speech-to-text ----------
+let whisper = null
+function startWhisper() {
+ if (!fs.existsSync(WHISPER_MODEL)) { log('whisper model missing at', WHISPER_MODEL); return }
+ whisper = spawn('whisperkit-cli', ['serve', '--model-path', WHISPER_MODEL, '--port', String(WHISPER_PORT)],
+ { stdio: ['ignore', 'ignore', 'pipe'] })
+ whisper.stderr.resume() // read and dropped: a full pipe would stop it mid-write
+ // not on PATH (a LaunchAgent's PATH is set in its plist): said once, with the fix; no 'exit' follows, so no retries
+ whisper.on('error', e => log(`whisperkit-cli didn't start (${e.code}): brew install whisperkit-cli, then bin/chums-setup --launchd (or start the hub from a shell that has it)`))
+ whisper.on('exit', code => { log('whisper exited', code, '- restarting in 3 s'); setTimeout(startWhisper, 3000) })
+ log('whisper server starting on', WHISPER_PORT)
+}
+
+// The first transcription after a start loads the model, which takes 15–25 s. Do it at once, on a second of silence,
+// so the first thing said on the watch after a restart is as quick as any other (about a second).
+async function warmWhisper() {
+ const t0 = Date.now(), n = 16000
+ const wav = Buffer.alloc(44 + n * 2) // 16 kHz mono 16-bit, all zeros
+ wav.write('RIFF', 0); wav.writeUInt32LE(36 + n * 2, 4); wav.write('WAVE', 8); wav.write('fmt ', 12)
+ wav.writeUInt32LE(16, 16); wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22); wav.writeUInt32LE(16000, 24)
+ wav.writeUInt32LE(32000, 28); wav.writeUInt16LE(2, 32); wav.writeUInt16LE(16, 34); wav.write('data', 36); wav.writeUInt32LE(n * 2, 40)
+ for (let i = 0; i < 90; i++) {
+ try {
+ const form = new FormData()
+ form.append('file', new Blob([wav], { type: 'audio/wav' }), 'warm.wav'); form.append('model', 'base'); form.append('language', 'en')
+ const res = await fetch(`http://localhost:${WHISPER_PORT}/v1/audio/transcriptions`, { method: 'POST', body: form })
+ if (res.ok) { log(`whisper warm in ${((Date.now() - t0) / 1000).toFixed(1)} s`); return }
+ } catch {} // not listening yet
+ await new Promise(r => setTimeout(r, 1000))
+ }
+ log('whisper did not warm up in 90 s')
+}
+
+// Whisper returns nothing for clips under ~1 s ("yes", "what's running?"), so every clip is padded
+// with silence and normalized to 16 kHz mono WAV first.
+function padToWav(buf) {
+ return new Promise((resolve, reject) => {
+ const ff = spawn('ffmpeg', ['-loglevel', 'error', '-i', 'pipe:0',
+ '-af', 'adelay=500:all=1,apad=pad_dur=1', '-ac', '1', '-ar', '16000', '-f', 'wav', 'pipe:1'])
+ const out = []
+ ff.stdout.on('data', c => out.push(c))
+ ff.on('error', reject)
+ ff.on('close', code => code === 0 ? resolve(Buffer.concat(out)) : reject(new Error(`ffmpeg ${code}`)))
+ ff.stdin.end(buf)
+ })
+}
+
+async function transcribe(buf) {
+ const wav = await padToWav(buf)
+ const form = new FormData()
+ form.append('file', new Blob([wav], { type: 'audio/wav' }), 'utterance.wav')
+ form.append('model', 'base')
+ form.append('language', 'en')
+ const names = [...sessions.values()].map(s => s.name)
+ form.append('prompt', ['Claude', ...names].join(', '))
+ const res = await fetch(`http://localhost:${WHISPER_PORT}/v1/audio/transcriptions`, { method: 'POST', body: form })
+ if (!res.ok) throw new Error(`whisper ${res.status}`)
+ const j = await res.json()
+ const text = (j.text ?? j.segments?.map(s => s.text).join('') ?? '')
+ // Whisper tags non-speech as [BEEP], [BLANK_AUDIO], (music) ... — never send those as orders.
+ return text.replace(/\[[^\]]*\]|\([^)]*\)|\*[^*]*\*/g, ' ').replace(/\s+/g, ' ').trim()
+}
+
+// ---------- http ----------
+function json(res, code, body) {
+ res.writeHead(code, { 'content-type': 'application/json' })
+ res.end(JSON.stringify(body))
+}
+/// A file as the answer. One deleted meanwhile (the last 60 are kept) is a 404, or a cut connection once it has
+/// started: an unhandled stream error would stop the hub. Given the request, one byte range of it is a 206 (a video
+/// player asks for them); several ranges get the whole file.
+function sendFile(res, file, type, headers = {}, req = null) {
+ let size
+ try { size = fs.statSync(file).size } catch { return json(res, 404, { error: 'gone' }) }
+ let start = 0, end = size - 1, code = 200
+ const range = /^bytes=(\d*)-(\d*)$/.exec(String(req?.headers.range ?? '').trim())
+ if (range && (range[1] || range[2])) {
+ if (range[1]) { start = Number(range[1]); end = range[2] ? Math.min(Number(range[2]), size - 1) : size - 1 }
+ else start = Math.max(0, size - Number(range[2])) // the last n bytes
+ if (start > end) { res.writeHead(416, { 'content-range': `bytes */${size}` }); return res.end() }
+ code = 206; headers = { ...headers, 'content-range': `bytes ${start}-${end}/${size}` }
+ }
+ res.writeHead(code, { 'content-type': type, 'content-length': end - start + 1, ...(req ? { 'accept-ranges': 'bytes' } : {}), ...headers })
+ if (req?.method === 'HEAD' || end < start) return res.end()
+ fs.createReadStream(file, { start, end }).on('error', () => res.destroy()).pipe(res)
+}
+/// A request's body, at most `limit` bytes. Past it: an error with status 413, and the rest isn't read (the answer
+/// closes the connection).
+function readBody(req, limit = 8 * 1024 * 1024) {
+ const tooLarge = () => Object.assign(new Error('too large'), { status: 413 })
+ if (Number(req.headers['content-length']) > limit) return Promise.reject(tooLarge())
+ return new Promise((resolve, reject) => {
+ const chunks = []; let n = 0
+ req.on('data', c => { n += c.length; if (n > limit) { req.removeAllListeners('data'); req.pause(); reject(tooLarge()) } else chunks.push(c) })
+ req.on('end', () => resolve(Buffer.concat(chunks)))
+ req.on('error', reject)
+ })
+}
+const readJSON = async req => {
+ const text = (await readBody(req)).toString('utf8') || '{}'
+ try { return JSON.parse(text) } catch { throw Object.assign(new Error('the body is not JSON'), { status: 400 }) }
+}
+
+function bearer(req) { const h = req.headers.authorization ?? ''; return h.startsWith('Bearer ') ? h.slice(7) : '' }
+// compared as SHA-256 digests: always 32 bytes each, so timingSafeEqual never throws (a header's characters can be
+// more bytes than the token's) and the time taken doesn't depend on what was sent
+const digest = s => crypto.createHash('sha256').update(String(s)).digest()
+const same = (t, k) => !!k && crypto.timingSafeEqual(digest(t), digest(k))
+/// The request's URL, or null when it doesn't parse (e.g. "//"): answered with a 400, never a crash.
+function urlOf(req) { try { return new URL(req.url, 'http://x') } catch { return null } }
+// on this Mac either token works (the Simulator uses the watch's); from the internet only the watch's
+function authed(req) { const t = bearer(req); return same(t, cfg.token) || same(t, cfg.watchToken) }
+function watchAuthed(req) { return same(bearer(req), cfg.watchToken) }
+
+const handle = async (req, res) => {
+ const url = urlOf(req)
+ if (!url) return json(res, 400, { error: 'bad request' })
+ const p = url.pathname
+ try {
+ if (!authed(req)) return json(res, 401, { error: 'unauthorized' })
+
+ // ----- channel side (one per Claude Code session) -----
+ if (p === '/channel/register' && req.method === 'POST') {
+ const { sessionId, name, cwd } = await readJSON(req)
+ const existing = sessions.get(sessionId)
+ if (!existing) {
+ // Same name + folder = that session was restarted; the old channel may not have said bye.
+ for (const s of sessions.values()) {
+ if (s.name === name && s.cwd === cwd) {
+ sessions.delete(s.id)
+ for (const [id, a] of approvals) if (a.sessionId === s.id) approvals.delete(id)
+ log('session replaced:', name)
+ }
+ }
+ }
+ sessions.set(sessionId, existing ?? { id: sessionId, name, cwd, status: 'idle', lastSeen: Date.now(), inbox: [], waiter: null })
+ sessions.get(sessionId).lastSeen = Date.now()
+ if (!existing) { log('session joined:', name, cwd); bump() }
+ return json(res, 200, { ok: true })
+ }
+ if (p === '/channel/next' && req.method === 'GET') {
+ const s = sessions.get(url.searchParams.get('sessionId'))
+ if (!s) return json(res, 404, { error: 'unknown session' })
+ s.lastSeen = Date.now()
+ const acked = new Set((url.searchParams.get('ack') ?? '').split(',').filter(Boolean))
+ if (acked.size) s.inbox = s.inbox.filter(it => !acked.has(it.id))
+ if (!s.inbox.length) {
+ await new Promise(r => { s.waiter = r; setTimeout(r, 25_000) })
+ }
+ s.lastSeen = Date.now()
+ return json(res, 200, { items: s.inbox })
+ }
+ if (p === '/channel/reply' && req.method === 'POST') {
+ const { sessionId, text, status } = await readJSON(req)
+ const s = sessions.get(sessionId)
+ if (!s) return json(res, 404, { error: 'unknown session' })
+ replyFrom(s, text, status)
+ return json(res, 200, { ok: true })
+ }
+ if (p === '/channel/artifact' && req.method === 'POST') {
+ const { sessionId, file, url: page, title, text, kind, from } = await readJSON(req)
+ const s = sessions.get(sessionId)
+ if (!s) return json(res, 404, { error: 'unknown session' })
+ try {
+ const a = await makeArtifact({ file, url: page, title, kind, from })
+ const line = String(text ?? '').trim() || a.title
+ s.lastLine = line; s.lastSpokeAt = Date.now(); s.status = 'idle'
+ say(line, s.name, 'artifact', { artifact: a })
+ log('artifact <-', s.name, a.kind, a.title, `${a.w}x${a.h}`)
+ return json(res, 200, { ok: true, ...a })
+ } catch (e) {
+ log('artifact failed', s.name, e.message)
+ return json(res, 422, { error: e.message })
+ }
+ }
+ if (p === '/channel/permission' && req.method === 'POST') {
+ const { sessionId, request_id, tool_name, description, input_preview } = await readJSON(req)
+ const s = sessions.get(sessionId)
+ if (!s) return json(res, 404, { error: 'unknown session' })
+ askApproval(s, request_id, tool_name, description, input_preview)
+ return json(res, 200, { ok: true })
+ }
+ if (p === '/channel/bye' && req.method === 'POST') {
+ const { sessionId } = await readJSON(req)
+ for (const [id, a] of approvals) if (a.sessionId === sessionId) approvals.delete(id)
+ if (sessions.delete(sessionId)) bump()
+ return json(res, 200, { ok: true })
+ }
+
+ if (p === '/hook' && req.method === 'POST') {
+ onHook(await readJSON(req))
+ return json(res, 200, { ok: true })
+ }
+
+ // ----- watch side -----
+ if (p === '/v1/ping') return json(res, 200, { ok: true }) // the watch probes which address answers
+ if (p.startsWith('/v1/speech/') && req.method === 'GET') { // a reply's voice, waited for while it renders
+ const file = await (tts.jobs.get(p.slice(11)) ?? Promise.resolve(null))
+ if (!file) return json(res, 404, { error: 'no speech' })
+ return sendFile(res, file, 'audio/mp4')
+ }
+ const art = p.match(/^\/v1\/artifact\/([0-9a-f]{12})\/(thumb|full|source|view)$/)
+ if (art && ['GET', 'HEAD'].includes(req.method)) {
+ const dir = path.join(ART_DIR, art[1]), forever = { 'cache-control': 'private, max-age=31536000, immutable' }
+ if (art[2] === 'thumb' || art[2] === 'full') { // its pictures: the pill's and the viewer's
+ const f = path.join(dir, `${art[2]}.jpg`)
+ if (!fs.existsSync(f)) return json(res, 404, { error: 'no such artifact' })
+ return sendFile(res, f, 'image/jpeg', forever, req)
+ }
+ // what the iPhone opens: the file as it was (source), or the hub's HTML page of it when there is one (view)
+ let view
+ try { view = JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8')).view ?? {} } catch { return json(res, 404, { error: 'no such artifact' }) }
+ const own = art[2] === 'view' && fs.existsSync(path.join(dir, 'view.html'))
+ const f = own ? 'view.html' : fs.readdirSync(dir).find(n => /^source(\.[a-z0-9]{1,12})?$/.test(n))
+ if (!f) return json(res, 404, { error: 'the hub kept no file of this one' })
+ const type = own ? 'text/html; charset=utf-8' : MIME[path.extname(f).slice(1)] ?? (view.type === 'text' ? 'text/plain; charset=utf-8' : 'application/octet-stream')
+ const name = own ? `${String(view.name ?? 'view').replace(/\.[^.]*$/, '')}.html` : String(view.name ?? f)
+ return sendFile(res, path.join(dir, f), type, {
+ ...forever, 'x-content-type-options': 'nosniff',
+ 'content-disposition': `inline; filename="${name.replace(/[^\x20-\x7e]|["\\]/g, '_')}"; filename*=UTF-8''${encodeURIComponent(name)}`,
+ // a page's scripts run, in an origin of their own: nothing of the hub's is theirs to read
+ ...(/html|svg/.test(type) ? { 'content-security-policy': 'sandbox allow-scripts' } : {}),
+ }, req)
+ }
+ if (p === '/v1/state' && req.method === 'GET') {
+ noteBattery(url.searchParams)
+ // one line a minute while the watch polls, so a silent watch is easy to tell from a disconnected one (only the
+ // watch's polls carry screen=; bin/chums-doctor's don't, so they don't pass for the watch's)
+ if (url.searchParams.has('screen') && Date.now() - (globalThis.lastPollLog ?? 0) > 60_000) { globalThis.lastPollLog = Date.now(); log('watch poll from', req.socket.remoteAddress, 'screen', oneLine(url.searchParams.get('screen'), 12), 'keyring', oneLine(url.searchParams.get('keyring'), 12)) }
+ const since = Number(url.searchParams.get('since') ?? 0)
+ if (since === rev) {
+ await new Promise(r => { const done = () => { stateWaiters.delete(done); r() }; stateWaiters.add(done); setTimeout(done, 20_000) })
+ }
+ // a line new to this watch carries its voice (base64 m4a), so it plays without a second request
+ const st = publicState()
+ // (a watch still on the numbering of a hub that has since restarted gets every line this hub has voiced)
+ if (since > 0) st.spoken = st.spoken.map(l => (l.rev > since || since > rev) && tts.data.has(l.id) ? { ...l, audioData: tts.data.get(l.id).toString('base64') } : l)
+ return json(res, 200, st)
+ }
+ if (p === '/v1/event' && req.method === 'POST') {
+ // what the watch did (launch, keyring, screen, crown, touches): logged so it can be checked from the Mac, in its
+ // own file only (the apps report every 30 s while on screen; the hub's log, which nothing rotates, stays the hub's)
+ const { text } = await readJSON(req)
+ const line = `${new Date().toISOString()} ${oneLine(text, 300)}`
+ const file = path.join(CONFIG_DIR, 'watch-events.log')
+ try { if (fs.statSync(file).size > 10e6) fs.renameSync(file, file + '.1') } catch {} // past 10 MB, a new file
+ fs.appendFileSync(file, line + '\n')
+ return json(res, 200, { ok: true })
+ }
+ if (p === '/v1/utterance' && req.method === 'POST') {
+ const t0 = Date.now()
+ const buf = await readBody(req)
+ const text = await transcribe(buf)
+ const t1 = Date.now()
+ // shaping an agent's soul: what was said becomes a proposed change to see and save
+ if (req.headers['x-chums-soul']) return json(res, 200, { transcript: text, ...(await soulFromVoice(req.headers['x-chums-soul'], text)) })
+ // the approval card on the watch while it recorded, and the agent it was talking to when it started
+ const r = route(text, req.headers['x-chums-approval'] || null, req.headers['x-chums-agent'] || null, deviceOf(req.headers['x-chums-device']))
+ log(`utterance ${buf.length}B stt=${t1 - t0}ms:`, JSON.stringify(text), '->', r.kind)
+ return json(res, 200, { transcript: text, ...r, sttMs: t1 - t0 })
+ }
+ if (p === '/v1/say' && req.method === 'POST') {
+ const body = await readJSON(req)
+ const { approval, agent, soul, device, files } = body
+ const text = typeof body.text === 'string' ? body.text.slice(0, 4000) : body.text // a message, not a document
+ if (soul) return json(res, 200, { transcript: text, ...(await soulFromVoice(soul, String(text ?? ''))) })
+ const paths = uploaded(files), shown = paths.map(artifactFor).filter(Boolean)
+ return json(res, 200, { transcript: text, ...route(String(text ?? ''), approval ?? null, agent ?? null, deviceOf(device), paths, shown) })
+ }
+ if (p === '/v1/focus' && req.method === 'POST') { // the agent the iPhone shows now
+ const { agent } = await readJSON(req)
+ if (!agentNamed(agent)) return json(res, 404, { error: 'no such agent' })
+ focusOn(agent)
+ return json(res, 200, { focus })
+ }
+ if (p === '/v1/upload' && req.method === 'POST') {
+ const buf = await readBody(req, UPLOAD_MAX) // past 25 MB: 413 (below)
+ if (!buf.length) return json(res, 400, { error: 'empty' })
+ return json(res, 200, await upload(url.searchParams.get('name'), buf))
+ }
+ const soulPath = p.match(/^\/v1\/agents\/([a-z0-9-]+)\/soul(\/save|\/undo|\/set)?$/)
+ if (soulPath && agentNamed(soulPath[1])) {
+ const id = soulPath[1]
+ try {
+ if (!soulPath[2] && req.method === 'GET') return json(res, 200, await soulCard(id))
+ if (soulPath[2] === '/save' && req.method === 'POST') return json(res, 200, await saveSoul(id, (await readJSON(req)).proposal))
+ if (soulPath[2] === '/undo' && req.method === 'POST') return json(res, 200, await undoSoul(id))
+ if (soulPath[2] === '/set' && req.method === 'POST') { const { field, value } = await readJSON(req); return json(res, 200, await setSoul(id, field, value)) }
+ } catch (e) { return json(res, e.code ?? 500, { error: e.message }) }
+ }
+ // the voices an agent can have, a sample of one, and an agent's (chosen on its soul screen)
+ if (p === '/v1/voices' && req.method === 'GET') return json(res, 200, { engine: ttsEngine(), ready: tts.enabled(), voices: ENGLISH_VOICES })
+ const sample = p.match(/^\/v1\/voices\/([a-z]{2}_[a-z]+)\/sample$/)
+ if (sample && req.method === 'GET') {
+ if (ttsEngine() !== 'kokoro' || !kokoro.ready) return json(res, 503, { error: "The voices aren't running on your Mac." })
+ if (!ENGLISH_VOICES.some(v => v.id === sample[1])) return json(res, 404, { error: 'no such voice' })
+ const out = path.join(SPEECH_DIR, `sample-${sample[1]}.m4a`)
+ if (!fs.existsSync(out)) await tts.kokoro('Two tests failed in the cart. Want me to fix them?', sample[1], out)
+ return sendFile(res, out, 'audio/mp4')
+ }
+ const voicePath = p.match(/^\/v1\/agents\/([a-z0-9-]+)\/voice$/)
+ if (voicePath && agentNamed(voicePath[1]) && req.method === 'POST') {
+ const voice = String((await readJSON(req)).voice ?? '')
+ if (!ENGLISH_VOICES.some(v => v.id === voice)) return json(res, 400, { error: 'no such voice' })
+ agentNamed(voicePath[1]).voice = voice; saveAgents()
+ kokoro.keepWarm(voice); setTimeout(() => kokoro.stopWarm(), 3000) // load it now: its first reply isn't slower
+ log(`${voicePath[1]}: voice ${voice}`); bump()
+ return json(res, 200, { id: voicePath[1], voice })
+ }
+ // the models each runtime offers, and what it uses when an agent has none of its own
+ if (p === '/v1/models' && req.method === 'GET') {
+ return json(res, 200, Object.fromEntries(SWITCHABLE.map(r => [r, { default: defaultModel(r), models: modelsFor(r) }])))
+ }
+ const modelPath = p.match(/^\/v1\/agents\/([a-z0-9-]+)\/model$/)
+ if (modelPath && agentNamed(modelPath[1]) && req.method === 'POST') {
+ try { return json(res, 200, await setModel(modelPath[1], (await readJSON(req)).model ?? null)) }
+ catch (e) { return json(res, e.code ?? 500, { error: e.message }) }
+ }
+ // how each runtime can ask before acting, and what it does when an agent has no mode of its own
+ if (p === '/v1/permissions' && req.method === 'GET') {
+ return json(res, 200, Object.fromEntries(Object.entries(PERMISSIONS).map(([r, { modes }]) => [r, { default: defaultPermission(r), modes }])))
+ }
+ const permissionPath = p.match(/^\/v1\/agents\/([a-z0-9-]+)\/permission$/)
+ if (permissionPath && agentNamed(permissionPath[1]) && req.method === 'POST') {
+ try { return json(res, 200, await setPermission(permissionPath[1], (await readJSON(req)).mode ?? null)) }
+ catch (e) { return json(res, e.code ?? 500, { error: e.message }) }
+ }
+ // which runtime an agent runs on (Claude Code or Codex), chosen on its soul screen
+ const runtimePath = p.match(/^\/v1\/agents\/([a-z0-9-]+)\/runtime$/)
+ if (runtimePath && agentNamed(runtimePath[1]) && req.method === 'POST') {
+ try { return json(res, 200, await setRuntime(runtimePath[1], String((await readJSON(req)).runtime ?? ''))) }
+ catch (e) { return json(res, e.code ?? 500, { error: e.message }) }
+ }
+ if (p === '/v1/verdict' && req.method === 'POST') {
+ const { requestId, behavior } = await readJSON(req)
+ return json(res, 200, verdict(requestId, behavior === 'allow' ? 'allow' : 'deny'))
+ }
+
+ json(res, 404, { error: 'not found' })
+ } catch (e) {
+ log('error', p, e.message)
+ if (res.headersSent) return
+ if (e.status === 413) res.setHeader('connection', 'close') // the rest of the body isn't read
+ json(res, e.status ?? 500, { error: e.message })
+ }
+}
+
+// The hub on this Mac only: Claude Code sessions (channel, hooks) and the Simulator.
+const server = http.createServer(handle)
+// The watch's door to the internet, for Tailscale Funnel (bin/chums-tunnel): only the watch's API (/v1/…), only on
+// localhost, and every wrong token costs a second.
+const publicServer = http.createServer(async (req, res) => {
+ try {
+ if (!urlOf(req)?.pathname.startsWith('/v1/')) return json(res, 404, { error: 'not found' })
+ if (!watchAuthed(req)) { await new Promise(r => setTimeout(r, 1000)); return json(res, 401, { error: 'unauthorized' }) }
+ } catch (e) { // anything thrown here would stop the hub
+ log('error at the public door:', e.message)
+ return res.headersSent ? res.destroy() : json(res, 500, { error: 'error' })
+ }
+ return handle(req, res)
+})
+
+// ---------- switching an agent's runtime (its soul screen on the watch) ----------
+// What belongs to a runtime (its thread, its model) is kept in byRuntime for when that runtime is chosen again. A
+// Claude Code agent is a LaunchAgent (bin/chums-agents add/remove); a Codex one runs inside the hub.
+const SWITCHABLE = ['claude', 'codex']
+const onPath = cmd => !!whichBin(cmd)
+const available = () => SWITCHABLE.filter(r => onPath(r))
+const setRuntime = (id, runtime) => serially(async () => {
+ const a = agentNamed(id)
+ if (!SWITCHABLE.includes(runtime)) throw Object.assign(new Error(`runtime is one of ${SWITCHABLE.join(', ')}`), { code: 400 })
+ if (!available().includes(runtime)) throw Object.assign(new Error(`${runtime === 'codex' ? 'Codex' : 'Claude Code'} isn't installed on this Mac`), { code: 409 })
+ const was = a.runtime ?? 'claude'
+ if (was === runtime) return { id, runtime }
+ a.byRuntime ??= {}
+ a.byRuntime[was] = { ...(a.sessionId ? { sessionId: a.sessionId } : {}), ...(a.model ? { model: a.model } : {}) }
+ const back = a.byRuntime[runtime] ?? {}
+ delete a.byRuntime[runtime]
+ if (!Object.keys(a.byRuntime).length) delete a.byRuntime
+ a.runtime = runtime
+ a.sessionId = back.sessionId ?? (runtime === 'claude' ? crypto.randomUUID() : undefined)
+ if (!a.sessionId) delete a.sessionId
+ if (back.model) a.model = back.model; else delete a.model
+ saveAgents()
+ // the old one stops, the new one starts
+ if (was === 'claude') await run(AGENTS_BIN, ['remove', id], 60_000).catch(e => log(`${id}: stopping its Claude Code session: ${e.message}`))
+ else { runners.get(id)?.stop(); runners.delete(id) }
+ const old = sessionOf(id)
+ if (old) { sessions.delete(old.id); for (const [rid, x] of approvals) if (x.sessionId === old.id) approvals.delete(rid) }
+ if (runtime === 'claude') await run(AGENTS_BIN, ['add', id], 120_000)
+ else runners.set(id, startRunner(a, runtimeHub))
+ log(`${id}: now on ${runtime}`); bump()
+ return { id, runtime }
+})
+// (the tests' private hub gets a stand-in, so they never restart a real LaunchAgent)
+const AGENTS_BIN = process.env.CHUMS_AGENTS_BIN || path.join(ROOT, 'bin/chums-agents')
+
+// ---------- an agent's model (its card on the iPhone) ----------
+// Claude Code takes an alias for the newest model of each family; Codex, the models its cache lists for the signed-in
+// account (~/.codex/models_cache.json, which Codex refreshes). No model: what the runtime itself is set to use.
+const CLAUDE_MODELS = ['fable', 'opus', 'sonnet', 'haiku'].map(id => ({ id, name: id[0].toUpperCase() + id.slice(1) }))
+const readJSONFile = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')) } catch { return null } }
+function codexModels() {
+ const list = readJSONFile(path.join(HOME, '.codex/models_cache.json'))?.models ?? []
+ return list.filter(m => m.visibility === 'list' && m.slug).sort((a, b) => (a.priority ?? 99) - (b.priority ?? 99))
+ .map(m => ({ id: m.slug, name: m.display_name || m.slug, about: m.description || null }))
+}
+/// What each runtime uses when an agent has no model of its own: "Opus, 1M context" from Claude Code's settings,
+/// Codex's from its config.toml.
+function defaultModel(runtime) {
+ if (runtime === 'claude') {
+ const m = readJSONFile(path.join(HOME, '.claude/settings.json'))?.model
+ if (!m) return null
+ const [, base, ctx] = String(m).match(/^([^[]+)(?:\[(\w+)\])?$/) ?? [, m]
+ const name = CLAUDE_MODELS.find(x => x.id === base)?.name ?? base
+ return ctx ? `${name}, ${ctx.toUpperCase()} context` : name
+ }
+ let toml = ''
+ try { toml = fs.readFileSync(path.join(HOME, '.codex/config.toml'), 'utf8') } catch { return null }
+ const slug = toml.split('\n[')[0].match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1]
+ return slug ? codexModels().find(m => m.id === slug)?.name ?? slug : null
+}
+const modelsFor = runtime => runtime === 'claude' ? CLAUDE_MODELS : runtime === 'codex' ? codexModels() : []
+/// An agent on another model (null: the runtime's own): it restarts on it, on the same conversation.
+const setModel = (id, model) => serially(async () => {
+ const a = agentNamed(id), runtime = a.runtime ?? 'claude'
+ model = model || null
+ if (model && !modelsFor(runtime).some(m => m.id === model)) throw Object.assign(new Error(`${model} isn't a model ${runtime === 'claude' ? 'Claude Code' : 'Codex'} offers here`), { code: 400 })
+ if ((a.model ?? null) === model) return { id, model }
+ if (model) a.model = model; else delete a.model
+ saveAgents()
+ await restartAgent(a)
+ log(`${id}: model ${model ?? `${runtime}'s own`}`); bump()
+ return { id, model }
+})
+/// An agent started again on what agents.json says now, on the same conversation: its runner in the hub, or its
+/// Claude Code session's LaunchAgent.
+async function restartAgent(a) {
+ if (runByHub(a)) { runners.get(a.id)?.stop(); runners.set(a.id, startRunner(a, runtimeHub)) }
+ else await run(AGENTS_BIN, ['restart', a.id], 60_000).catch(e => log(`${a.id}: restarting its Claude Code session: ${e.message}`))
+}
+
+// ---------- an agent's permission mode (the watch and the iPhone) ----------
+// How it asks before acting. A Claude Code agent's is permissionMode in agents.json, passed as --permission-mode
+// (tools/agent-cmd.mjs); a Codex agent's is approvalPolicy, on its thread (hub/runtimes.mjs). Without one, the
+// runtime's own setting: permissions.defaultMode in ~/.claude/settings.json, approval_policy in ~/.codex/config.toml.
+const PERMISSIONS = {
+ claude: { field: 'permissionMode', modes: [
+ { id: 'default', name: 'Asks first', about: 'Anything it may not do on its own comes to your watch and iPhone as Allow or Deny.' },
+ { id: 'acceptEdits', name: 'Edits on its own', about: 'Changes files in its folders without asking; asks before commands.' },
+ { id: 'auto', name: 'Decides on its own', about: "Claude Code's auto mode: it acts, and refuses what looks risky without asking you." },
+ ] },
+ codex: { field: 'approvalPolicy', modes: [
+ { id: 'untrusted', name: 'Asks first', about: 'Asks before running anything but simple reads.' },
+ { id: 'on-request', name: 'Asks when it needs to', about: 'Works in its folders and asks to go further.' },
+ { id: 'never', name: 'Never asks', about: 'Runs without asking, inside its sandbox.' },
+ ] },
+}
+/// Claude Code's modes the apps don't offer, which its settings can still give.
+const CLAUDE_OTHER_MODES = { plan: 'Plans only', bypassPermissions: 'Never asks' }
+const modeName = (runtime, id) => PERMISSIONS[runtime].modes.find(m => m.id === id)?.name ?? (runtime === 'claude' ? CLAUDE_OTHER_MODES[id] : null) ?? null
+const permissionOf = a => { const f = PERMISSIONS[a.runtime ?? 'claude']?.field; return f ? a[f] ?? null : null }
+/// The approval policy a Codex agent without one of its own runs on: approval_policy in ~/.codex/config.toml (outside
+/// its tables) when it is one of the three, else on-request.
+function codexPolicy() {
+ let toml = ''
+ try { toml = fs.readFileSync(path.join(HOME, '.codex/config.toml'), 'utf8') } catch {}
+ const id = `\n${toml}`.split('\n[')[0].match(/^\s*approval_policy\s*=\s*"([^"]+)"/m)?.[1]
+ return PERMISSIONS.codex.modes.some(m => m.id === id) ? id : 'on-request'
+}
+/// The name of the mode an agent with none of its own runs in, read when asked (null: one the hub has no name for).
+function defaultPermission(runtime) {
+ if (runtime === 'claude') return modeName('claude', readJSONFile(path.join(HOME, '.claude/settings.json'))?.permissions?.defaultMode ?? 'default')
+ return modeName(runtime, codexPolicy())
+}
+/// An agent's permission mode (null: its runtime's own setting): kept in agents.json, and it restarts in it.
+const setPermission = (id, mode) => serially(async () => {
+ const a = agentNamed(id), runtime = a.runtime ?? 'claude', p = PERMISSIONS[runtime]
+ mode = mode || null
+ if (mode !== null && !p?.modes.some(m => m.id === mode)) {
+ throw Object.assign(new Error(p ? `${runtime === 'claude' ? 'Claude Code' : 'Codex'}'s modes are ${p.modes.map(m => m.id).join(', ')}.`
+ : `An agent on ${runtime} has no modes to pick.`), { code: 400 })
+ }
+ if (!p || (a[p.field] ?? null) === mode) return { id, mode }
+ if (mode) a[p.field] = mode; else delete a[p.field]
+ saveAgents()
+ await restartAgent(a)
+ log(`${id}: permission mode ${mode ?? `${runtime}'s own`}`); bump()
+ return { id, mode }
+})
+
+// ---------- agents the hub runs itself (Codex, Copilot, ACP agents): hub/runtimes.mjs ----------
+// They join as sessions with a driver: orders and verdicts go to it, and it reports in the hooks' words.
+const runtimeHub = {
+ url: `http://127.0.0.1:${cfg.port}`, token: cfg.token, port: cfg.port, dir: CONFIG_DIR, log, bump, codexPolicy,
+ join({ id, name, cwd, driver }) {
+ for (const s of sessions.values()) if (s.name === name && s.cwd === cwd) { // its previous run, if still here
+ sessions.delete(s.id)
+ for (const [rid, a] of approvals) if (a.sessionId === s.id) approvals.delete(rid)
+ }
+ const s = { id, name, cwd, status: 'idle', lastSeen: Date.now(), inbox: [], waiter: null, driver }
+ sessions.set(id, s)
+ log('session joined:', name, cwd, `(${agentNamed(name)?.runtime ?? 'hub'})`); bump()
+ return s
+ },
+ leave(id) {
+ const s = sessions.get(id)
+ for (const [rid, a] of approvals) if (a.sessionId === id) approvals.delete(rid)
+ if (sessions.delete(id)) { log('session gone:', s.name); bump() }
+ },
+ hook: (s, event, fields = {}) => onHook({ ...fields, name: s.name, cwd: s.cwd, event, session: s }),
+ react: (s, kind, text) => { react(s.name, kind, text); bump() },
+ reply: (s, text, status, why) => { replyFrom(s, text, status); if (why) log(` (spoken for ${s.name}: its ${why})`) },
+ ask: (s, { requestId, tool, description, input }) => askApproval(s, requestId, tool, description, JSON.stringify(input ?? {})),
+ closeApproval(requestId) {
+ const a = approvals.get(requestId)
+ if (!a) return
+ approvals.delete(requestId)
+ const s = sessions.get(a.sessionId)
+ if (s && !approvalsFor(s)) s.status = 'working'
+ log('approval answered elsewhere:', a.session, a.tool); bump()
+ },
+ saveSessionId(agentId, id) {
+ const a = agentNamed(agentId)
+ if (!a || a.sessionId === id) return
+ a.sessionId = id
+ saveAgents()
+ },
+}
+const runners = new Map()
+
+// Everything else starts once both ports are the hub's: a second hub started by mistake (bin/chums-hub while the
+// LaunchAgent runs) stops there, before it touches the first one's speech servers, souls or Codex app-servers.
+function startAll() {
+ for (const [id, r] of startRunners(agents.filter(runByHub), runtimeHub)) runners.set(id, r)
+ if (!process.env.CHUMS_NO_WHISPER) { startWhisper(); warmWhisper(); kokoro.start() } // the tests' private hub neither hears nor speaks
+ seedSouls().catch(e => log('souls:', e.message))
+}
+let listening = 0
+for (const [srv, key] of [[server, 'port'], [publicServer, 'publicPort']]) srv.on('error', e => {
+ if (e.code !== 'EADDRINUSE') throw e
+ console.error(`chums: 127.0.0.1:${cfg[key]} is in use, most likely by a hub that is already running (bin/chums-doctor says how it runs; ` +
+ `lsof -nP -iTCP:${cfg[key]} -sTCP:LISTEN shows what it is). Stop that one first, or set "${key}" in ${CONFIG_PATH}.`)
+ process.exit(1)
+})
+server.listen(cfg.port, '127.0.0.1', () => { log(`Chums hub on 127.0.0.1:${cfg.port} config ${CONFIG_PATH}`); if (++listening === 2) startAll() })
+publicServer.listen(cfg.publicPort, '127.0.0.1', () => { log(`watch API for the tunnel on 127.0.0.1:${cfg.publicPort}${cfg.publicURL ? ` (${cfg.publicURL})` : ''}`); if (++listening === 2) startAll() })
+const quit = () => { quitting = true; whisper?.kill(); kokoro.proc?.kill(); for (const r of runners.values()) r?.stop(); setTimeout(() => process.exit(0), 300) }
+process.on('SIGTERM', quit)
+process.on('SIGINT', quit)
diff --git a/hub/jsonrpc.mjs b/hub/jsonrpc.mjs
new file mode 100644
index 0000000..21c6014
--- /dev/null
+++ b/hub/jsonrpc.mjs
@@ -0,0 +1,115 @@
+// JSON-RPC 2.0 for the hub's agent runtimes: the hub is the client of an agent that runs as a child process.
+// lines(child) one JSON message per line on the child's stdin/stdout (Agent Client Protocol, `copilot --acp`)
+// wsUnix(path) text frames of a WebSocket on a Unix socket (`codex app-server --listen unix://…`)
+// peer(transport) requests with ids and answers, notifications, and the agent's own requests to the hub
+// No dependencies: the WebSocket client is the few parts of RFC 6455 a local socket needs.
+import net from 'node:net'
+import crypto from 'node:crypto'
+import readline from 'node:readline'
+import { EventEmitter } from 'node:events'
+
+/// A child's stdin/stdout, one message per line. Emits 'message' (parsed object) and 'close'.
+export function lines(child) {
+ const t = new EventEmitter()
+ readline.createInterface({ input: child.stdout }).on('line', l => {
+ if (!l.trim()) return
+ let m; try { m = JSON.parse(l) } catch { t.emit('junk', l); return }
+ t.emit('message', m)
+ })
+ child.on('exit', () => t.emit('close'))
+ child.stdin.on('error', () => {})
+ t.send = m => { if (child.stdin.writable) child.stdin.write(JSON.stringify(m) + '\n') }
+ t.close = () => { try { child.stdin.end() } catch {} }
+ return t
+}
+
+/// A WebSocket client on a Unix socket. Resolves once the upgrade is done; emits 'message' and 'close'.
+export function wsUnix(socketPath, timeout = 5000) {
+ return new Promise((resolve, reject) => {
+ const t = new EventEmitter()
+ const c = net.createConnection(socketPath)
+ let buf = Buffer.alloc(0), open = false, parts = []
+ const timer = setTimeout(() => { c.destroy(); reject(new Error(`no answer on ${socketPath}`)) }, timeout)
+ const frame = (op, data) => {
+ const mask = crypto.randomBytes(4), n = data.length
+ const head = n < 126 ? Buffer.from([0x80 | op, 0x80 | n])
+ : n < 65536 ? Buffer.from([0x80 | op, 0x80 | 126, n >> 8, n & 255])
+ : Buffer.concat([Buffer.from([0x80 | op, 0x80 | 127]), (() => { const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(n)); return b })()])
+ const body = Buffer.alloc(n)
+ for (let i = 0; i < n; i++) body[i] = data[i] ^ mask[i & 3]
+ return Buffer.concat([head, mask, body])
+ }
+ c.on('connect', () => c.write(`GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
+ `Sec-WebSocket-Key: ${crypto.randomBytes(16).toString('base64')}\r\nSec-WebSocket-Version: 13\r\n\r\n`))
+ c.on('data', d => {
+ buf = Buffer.concat([buf, d])
+ if (!open) {
+ const end = buf.indexOf('\r\n\r\n')
+ if (end < 0) return
+ const status = buf.subarray(0, end).toString().split('\r\n')[0]
+ buf = buf.subarray(end + 4)
+ clearTimeout(timer)
+ if (!/^HTTP\/1\.1 101/.test(status)) { c.destroy(); return reject(new Error(`WebSocket refused: ${status}`)) }
+ open = true; resolve(t)
+ }
+ for (;;) {
+ if (buf.length < 2) return
+ const fin = buf[0] & 0x80, op = buf[0] & 15, masked = buf[1] & 0x80
+ let n = buf[1] & 127, off = 2
+ if (n === 126) { if (buf.length < 4) return; n = buf.readUInt16BE(2); off = 4 }
+ else if (n === 127) { if (buf.length < 10) return; n = Number(buf.readBigUInt64BE(2)); off = 10 }
+ const maskKey = masked ? buf.subarray(off, off + 4) : null
+ if (masked) off += 4
+ if (buf.length < off + n) return
+ let data = Buffer.from(buf.subarray(off, off + n))
+ if (maskKey) for (let i = 0; i < n; i++) data[i] ^= maskKey[i & 3]
+ buf = buf.subarray(off + n)
+ if (op === 8) { c.end(); continue } // close
+ if (op === 9) { c.write(frame(10, data)); continue } // ping -> pong
+ if (op === 10) continue
+ parts.push(data)
+ if (!fin) continue
+ const text = Buffer.concat(parts).toString('utf8'); parts = []
+ let m; try { m = JSON.parse(text) } catch { t.emit('junk', text); continue }
+ t.emit('message', m)
+ }
+ })
+ c.on('error', e => { clearTimeout(timer); if (!open) reject(e) })
+ c.on('close', () => { clearTimeout(timer); if (open) t.emit('close') })
+ t.send = m => { if (!c.destroyed) c.write(frame(1, Buffer.from(JSON.stringify(m)))) }
+ t.close = () => { try { c.write(frame(8, Buffer.alloc(0))) } catch {} c.end() }
+ })
+}
+
+/// Requests both ways over a transport. `onRequest(method, params)` answers the agent's requests (throw to send an
+/// error); `onNotification(method, params)` takes everything else. `jsonrpc: '2.0'` goes on every message (ACP needs
+/// it; Codex's app-server accepts it).
+export function peer(transport, { onRequest, onNotification, log = () => {} }) {
+ let next = 1
+ const waiting = new Map()
+ const p = new EventEmitter()
+ transport.on('message', async m => {
+ if (m.method && m.id !== undefined && m.id !== null) { // the agent asks the hub (ids can be 0)
+ try { transport.send({ jsonrpc: '2.0', id: m.id, result: (await onRequest(m.method, m.params ?? {}, m.id)) ?? null }) }
+ catch (e) { transport.send({ jsonrpc: '2.0', id: m.id, error: { code: e.code ?? -32603, message: e.message ?? String(e) } }) }
+ } else if (m.method) {
+ try { await onNotification(m.method, m.params ?? {}) } catch (e) { log('notification handler:', m.method, e.message) }
+ } else if (waiting.has(m.id)) {
+ const w = waiting.get(m.id); waiting.delete(m.id)
+ m.error ? w.reject(Object.assign(new Error(m.error.message ?? 'error'), { code: m.error.code, data: m.error.data })) : w.resolve(m.result)
+ }
+ })
+ transport.on('close', () => {
+ for (const w of waiting.values()) w.reject(Object.assign(new Error('the agent went away'), { code: 'closed' }))
+ waiting.clear(); p.emit('close')
+ })
+ p.request = (method, params, timeout = 0) => new Promise((resolve, reject) => {
+ const id = next++
+ const t = timeout ? setTimeout(() => { waiting.delete(id); reject(new Error(`${method} took over ${timeout / 1000} s`)) }, timeout) : null
+ waiting.set(id, { resolve: v => { clearTimeout(t); resolve(v) }, reject: e => { clearTimeout(t); reject(e) } })
+ transport.send({ jsonrpc: '2.0', id, method, params })
+ })
+ p.notify = (method, params) => transport.send({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) })
+ p.close = () => transport.close()
+ return p
+}
diff --git a/hub/render.mjs b/hub/render.mjs
new file mode 100644
index 0000000..8790138
--- /dev/null
+++ b/hub/render.mjs
@@ -0,0 +1,357 @@
+// Markdown, text and tables as HTML pages, dark like the iPhone's card: what the hub turns into pictures for the watch
+// (tools/page-shot.swift) and keeps as view.html for the iPhone. Everything from the file is escaped, and a page loads
+// nothing: links are their text, images their description, raw HTML is dropped, and its policy allows no fetch at all.
+// The hub runs it as its own process, with a time limit, so a large or odd file never holds up the hub:
+// node hub/render.mjs markdown|text|table <file> <dir> <title>
+// It writes <dir>/view.html (for the iPhone) and, when the picture shows less, <dir>/shot.html, and prints what the
+// hub needs as JSON: { shot: the page to render, note: what the title adds when the picture shows all of it, cutNote:
+// what it adds when the picture is cut, maxWidth: how wide page-shot may widen it }.
+import fs from 'node:fs'
+import path from 'node:path'
+import { StringDecoder } from 'node:string_decoder'
+
+export const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c])
+const count = n => n.toLocaleString('en-US')
+
+const STYLE = `
+:root { color-scheme: dark }
+html, body { background: #000 }
+body { margin: 0; padding: 20px 18px 28px; color: #e8e8ea; font: 16px/1.5 -apple-system, system-ui, sans-serif;
+ -webkit-text-size-adjust: 100%; overflow-wrap: break-word }
+h1, h2, h3, h4, h5, h6 { color: #fff; line-height: 1.25; margin: 1.3em 0 .5em }
+h1 { font-size: 1.6em } h2 { font-size: 1.35em } h3 { font-size: 1.15em } h4, h5, h6 { font-size: 1em }
+body > :first-child { margin-top: 0 }
+p, ul, ol, blockquote, pre, table, .front { margin: 0 0 .9em }
+ul, ol { padding-left: 1.4em } li { margin: .2em 0 } li > ul, li > ol { margin: .2em 0 }
+.link { color: #6cb6ff } .img { color: #8e8e93; font-style: italic } .box { color: #8e8e93 }
+code, pre { font-family: ui-monospace, "SF Mono", Menlo, monospace }
+code { font-size: .86em; background: #1c1c1e; border-radius: 5px; padding: .1em .35em }
+pre { font-size: 13px; line-height: 1.45; background: #1c1c1e; border-radius: 10px; padding: 12px 14px;
+ white-space: pre-wrap; overflow-wrap: anywhere }
+pre code { background: none; padding: 0; font-size: 1em }
+blockquote { padding-left: 14px; border-left: 3px solid #3a3a3c; color: #b4b4b8; margin-left: 0 }
+hr { border: 0; border-top: 1px solid #3a3a3c; margin: 1.4em 0 }
+table { border-collapse: collapse; font-size: 14px }
+th, td { border: 1px solid #3a3a3c; padding: 6px 9px; text-align: left; vertical-align: top }
+th { background: #1c1c1e; color: #fff; font-weight: 600 }
+td.n { text-align: right; font-variant-numeric: tabular-nums }
+.front { font-size: 12px; color: #8e8e93 }
+.note { color: #8e8e93; font-size: 13px; margin-top: 14px }
+body.text { padding: 14px 12px 20px; font: 11px/15px ui-monospace, "SF Mono", Menlo, monospace }
+body.text .l { white-space: pre-wrap; overflow-wrap: anywhere; padding-left: 2ch; text-indent: -2ch }
+body.text .note { font-family: -apple-system, system-ui, sans-serif }
+body.table { padding: 14px 12px 20px }
+body.table table.cut td, body.table table.cut th { white-space: nowrap; padding: 4px 8px; line-height: 18px }
+`
+
+/// A whole page: its title, the style above, and a policy that lets it load nothing.
+export function page(title, body, cls = 'doc') {
+ return `<!doctype html><html><head><meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>${esc(title)}</title><style>${STYLE}</style></head>
+<body class="${cls}">${body}</body></html>
+`
+}
+
+// ---------- Markdown ----------
+// CommonMark's common parts and GitHub's tables, strikethrough and task lists: headings (# and underlined), paragraphs,
+// emphasis, lists (nested), links and images (as text), inline code, code blocks (fenced and indented), block quotes,
+// tables, rules, and front matter (shown small, as it is).
+const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/
+const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/
+const RULE = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/
+const QUOTE = /^ {0,3}>/
+const ITEM = /^( *)([-*+]|\d{1,9}[.)])(?:( +)(.*))?$/
+const DELIM = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/
+const tableAt = (lines, i) => lines[i].includes('|') && (lines[i + 1] ?? '').includes('|') && DELIM.test(lines[i + 1]) // a header row, then its delimiter row
+const indentOf = l => l.match(/^ */)[0].length
+const startsBlock = l => FENCE.test(l) || ATX.test(l) || RULE.test(l) || QUOTE.test(l) || ITEM.test(l)
+
+export function markdown(src) {
+ const text = String(src).replace(/^/, '').replace(/\r\n?/g, '\n').replace(/\t/g, ' ').replace(/<!--[\s\S]*?-->/g, '')
+ const lines = text.split('\n')
+ let front = ''
+ if (lines[0] === '---') { // front matter: --- … --- (or …) at the very top
+ const end = lines.findIndex((l, i) => i > 0 && (l === '---' || l === '...'))
+ if (end > 0 && end < 200) { front = `<pre class="front">${esc(lines.slice(1, end).join('\n'))}</pre>`; lines.splice(0, end + 1) }
+ }
+ return front + blocks(lines)
+}
+
+function blocks(lines) {
+ let out = '', i = 0, m
+ while (i < lines.length) {
+ const l = lines[i]
+ if (!l.trim()) { i++; continue }
+ if ((m = l.match(FENCE)) && !(m[1][0] === '`' && m[2].includes('`'))) {
+ const fence = m[1], body = []
+ for (i++; i < lines.length && !new RegExp(`^ {0,3}${fence[0]}{${fence.length},}[ \\t]*$`).test(lines[i]); i++) body.push(lines[i])
+ i++
+ out += `<pre><code>${esc(body.join('\n'))}</code></pre>`
+ } else if ((m = l.match(ATX))) {
+ out += `<h${m[1].length}>${inline(m[2] ?? '')}</h${m[1].length}>`; i++
+ } else if (RULE.test(l)) {
+ out += '<hr>'; i++
+ } else if (QUOTE.test(l)) {
+ const body = []
+ // its lines, and the lines that carry on its paragraph without a > (lazy continuation)
+ while (i < lines.length && lines[i].trim() && (QUOTE.test(lines[i]) || !startsBlock(lines[i]))) body.push(lines[i++].replace(/^ {0,3}> ?/, ''))
+ out += `<blockquote>${blocks(body)}</blockquote>`
+ } else if (ITEM.test(l)) {
+ const [html, next] = list(lines, i); out += html; i = next
+ } else if (indentOf(l) >= 4) {
+ const body = []
+ while (i < lines.length && (indentOf(lines[i]) >= 4 || !lines[i].trim())) body.push(lines[i++].slice(4))
+ while (body.length && !body.at(-1).trim()) body.pop()
+ out += `<pre><code>${esc(body.join('\n'))}</code></pre>`
+ } else if (tableAt(lines, i)) {
+ const [html, next] = table(lines, i); out += html; i = next
+ } else {
+ const para = [l]
+ let heading = 0
+ for (i++; i < lines.length && lines[i].trim(); i++) {
+ if (/^ {0,3}=+[ \t]*$/.test(lines[i])) { heading = 1; i++; break } // a line under it: a heading
+ if (/^ {0,3}-+[ \t]*$/.test(lines[i])) { heading = 2; i++; break }
+ if (startsBlock(lines[i]) || tableAt(lines, i)) break
+ para.push(lines[i])
+ }
+ const html = inline(para.map(s => s.replace(/^ +/, '')).join('\n').trimEnd())
+ out += heading ? `<h${heading}>${html}</h${heading}>` : `<p>${html}</p>`
+ }
+ }
+ return out
+}
+
+function list(lines, i) {
+ const first = lines[i].match(ITEM), ordered = /\d/.test(first[2])
+ const start = ordered ? parseInt(first[2], 10) : 1
+ let html = ordered ? `<ol${start !== 1 ? ` start="${start}"` : ''}>` : '<ul>'
+ let m
+ while (i < lines.length && (m = lines[i].match(ITEM)) && /\d/.test(m[2]) === ordered) {
+ const content = m[1].length + m[2].length + Math.min(m[3]?.length ?? 1, 4) // where its text starts
+ const body = [m[4] ?? '']
+ for (i++; i < lines.length; i++) {
+ const l = lines[i]
+ if (!l.trim()) { // a blank line: the item goes on if what follows is indented
+ let j = i
+ while (j < lines.length && !lines[j].trim()) j++
+ if (j < lines.length && indentOf(lines[j]) >= content) { body.push(...Array(j - i).fill('')); i = j - 1; continue }
+ break
+ }
+ if (indentOf(l) >= content) body.push(l.slice(content))
+ else if (ITEM.test(l) || startsBlock(l)) break // the next item, or the end of the list
+ else body.push(l.trim()) // its paragraph, carried on without the indent
+ }
+ let inner = blocks(body)
+ const one = inner.match(/^<p>([\s\S]*?)<\/p>(?![\s\S]*<p>)([\s\S]*)$/)
+ if (one && !body.slice(1).some(x => !x.trim())) inner = one[1] + one[2] // a tight item: no paragraph around its text
+ inner = inner.replace(/^\[( |x|X)\] /, (_, x) => `<span class="box">${x === ' ' ? '☐' : '☑'}</span> `)
+ html += `<li>${inner}</li>`
+ let j = i // blank lines between items
+ while (j < lines.length && !lines[j].trim()) j++
+ if (j > i && j < lines.length && (m = lines[j].match(ITEM)) && /\d/.test(m[2]) === ordered && m[1].length < content) i = j
+ }
+ return [html + (ordered ? '</ol>' : '</ul>'), i]
+}
+
+function table(lines, i) {
+ const cells = l => l.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '').split(/(?<!\\)\|/).map(c => c.trim().replace(/\\\|/g, '|'))
+ const head = cells(lines[i])
+ const align = cells(lines[i + 1]).map(c => c.endsWith(':') ? (c.startsWith(':') ? 'center' : 'right') : '')
+ const cell = (tag, c, k) => `<${tag}${align[k] ? ` style="text-align:${align[k]}"` : ''}>${inline(c ?? '')}</${tag}>`
+ let html = `<table><tr>${head.map((c, k) => cell('th', c, k)).join('')}</tr>`
+ for (i += 2; i < lines.length && lines[i].trim() && !startsBlock(lines[i]); i++) {
+ const row = cells(lines[i])
+ html += `<tr>${head.map((_, k) => cell('td', row[k], k)).join('')}</tr>`
+ }
+ return [html + '</table>', i]
+}
+
+/// A paragraph's text: code spans, emphasis, links and images as text, line breaks; the rest escaped.
+export function inline(s) {
+ const held = []
+ const hold = html => `\u0000${held.push(html) - 1}\u0000`
+ s = String(s).replace(/\u0000/g, '')
+ .replace(/(`+)([\s\S]*?[^`])\1(?!`)/g, (_, __, c) => hold(`<code>${esc(c.replace(/\n/g, ' ').replace(/^ ([\s\S]*) $/, '$1'))}</code>`))
+ .replace(/\\([!-/:-@[-`{-~])/g, (_, c) => hold(esc(c)))
+ .replace(/<((?:https?|mailto|ftp):[^\s<>]+|[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+)>/gi, (_, u) => hold(`<span class="link">${esc(u)}</span>`))
+ .replace(/<br\s*\/?>/gi, () => hold('<br>'))
+ .replace(/<img\b[^>]*?\balt\s*=\s*"([^"]*)"[^>]*>/gi, (_, alt) => hold(`<span class="img">${esc(alt ? `Image: ${alt}` : 'Image')}</span>`))
+ .replace(/<\/?[A-Za-z][\w-]*(?:\s[^<>]*)?\/?>/g, '') // other HTML: dropped, its text kept
+ s = esc(s)
+ .replace(/!\[([^\]]*)\]\((?:[^()]|\([^)]*\))*\)/g, (_, alt) => `<span class="img">${alt ? `Image: ${alt}` : 'Image'}</span>`)
+ .replace(/!\[([^\]]*)\]\[[^\]]*\]/g, (_, alt) => `<span class="img">${alt ? `Image: ${alt}` : 'Image'}</span>`)
+ .replace(/\[([^\]]+)\]\((?:[^()]|\([^)]*\))*\)/g, '<span class="link">$1</span>')
+ .replace(/\[([^\]]+)\]\[[^\]]*\]/g, '<span class="link">$1</span>')
+ .replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, '<strong>$2</strong>')
+ .replace(/(?<![\w*])\*(?=[^\s*])([\s\S]*?[^\s*])\*(?![\w*])/g, '<em>$1</em>')
+ .replace(/(?<![\w_])_(?=[^\s_])([\s\S]*?[^\s_])_(?![\w_])/g, '<em>$1</em>')
+ .replace(/~~(?=\S)([\s\S]*?\S)~~/g, '<del>$1</del>')
+ .replace(/(?: {2,}|\\)\n/g, '<br>').replace(/\n/g, ' ')
+ return s.replace(/\u0000(\d+)\u0000/g, (_, n) => held[n])
+}
+
+// ---------- text and code ----------
+// Monospaced, each line wrapped at the page's width with its continuation indented; at most `cap` characters of a line.
+/// lines: the first lines of the file; total: how many it has (null when it wasn't counted).
+export function textBody(lines, total, cap) {
+ const rows = lines.map(l => `<div class="l">${esc(l.length > cap ? l.slice(0, cap) + '…' : l) || ' '}</div>`).join('')
+ const more = total == null ? `First ${count(lines.length)} lines.` : total > lines.length ? `First ${count(lines.length)} lines of ${count(total)}.` : ''
+ return rows + (more ? `<p class="note">${more}</p>` : '')
+}
+/// How many of these lines fit in `rows` rows of a text page 390 pt wide: 11 px SF Mono is 6.6 px a character, so 55
+/// to the first row of a line and 53 to each row it wraps onto, less what wrapping at a space leaves (counted as 51
+/// and 49). East Asian characters and emoji count two.
+export function linesThatFit(lines, rows, cap) {
+ let used = 0, n = 0
+ for (const l of lines) {
+ let w = 0
+ for (const ch of l.length > cap ? l.slice(0, cap + 1) : l) w += ch.codePointAt(0) >= 0x1100 ? 2 : 1
+ used += w <= 55 ? 1 : 1 + Math.ceil((w - 51) / 49)
+ if (used > rows) break
+ n++
+ }
+ return Math.max(1, n)
+}
+
+// ---------- tables (CSV, TSV) ----------
+/// rows: the first rows (the first one is the header); total: how many it has. A cut table keeps each cell on one line,
+/// at most `cap` characters, so its rows are the same height (the picture's); otherwise cells wrap at 22 em.
+export function tableBody(rows, total, cols, cap, oneLine) {
+ const width = Math.max(...rows.map(r => r.length), 1), shownCols = Math.min(width, cols)
+ const cut = c => { c = String(c ?? '').replace(/\s+/g, ' ').trim(); return c.length > cap ? c.slice(0, cap) + '…' : c }
+ const numeric = c => /^[-+]?[$€£]?[\d.,]+%?$/.test(c)
+ const [head = [], ...body] = rows
+ const tr = (r, tag) => `<tr>${Array.from({ length: shownCols }, (_, k) => {
+ const c = cut(r[k]); return `<${tag}${tag === 'td' && numeric(c) ? ' class="n"' : ''}${oneLine ? '' : ' style="max-width:22em"'}>${esc(c)}</${tag}>`
+ }).join('')}</tr>`
+ const notes = []
+ if (total > body.length) notes.push(`First ${count(body.length)} rows of ${count(total)}.`)
+ if (width > shownCols) notes.push(`First ${shownCols} columns of ${width}.`)
+ return `<table class="${oneLine ? 'cut' : ''}">${tr(head, 'th')}${body.map(r => tr(r, 'td')).join('')}</table>` +
+ (notes.length ? `<p class="note">${notes.join(' ')}</p>` : '')
+}
+
+// ---------- the files themselves (run by the hub as its own process) ----------
+const HEAD = { markdown: 256 * 1024, text: 1024 * 1024 } // what is read of a long file: more than any page shows
+const TEXT_LINES = 300, TEXT_ROWS = 380 // the picture: at most 300 lines in 380 rows
+const VIEW_LINES = 5000 // view.html
+const TABLE_COLS = 30, VIEW_ROWS = 1000, VIEW_COLS = 100
+const READ_ALL = 200e6 // past 200 MB, lines and rows aren't counted
+
+function head(file, n) {
+ const fd = fs.openSync(file, 'r')
+ try { const buf = Buffer.alloc(n); return buf.subarray(0, fs.readSync(fd, buf, 0, n, 0)) } finally { fs.closeSync(fd) }
+}
+/// Text without control characters other than tab and line breaks (a stray NUL or escape code shows as nothing).
+const clean = s => s.replace(/^/, '').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '')
+
+function lineCount(file, size) {
+ if (size > READ_ALL) return null
+ const fd = fs.openSync(file, 'r'), buf = Buffer.alloc(1 << 20)
+ let n = 0, last = 10
+ try {
+ for (let got; (got = fs.readSync(fd, buf, 0, buf.length, null)) > 0;) {
+ for (let k = buf.indexOf(10); k !== -1 && k < got; k = buf.indexOf(10, k + 1)) n++
+ last = buf[got - 1]
+ }
+ } finally { fs.closeSync(fd) }
+ return n + (last !== 10 ? 1 : 0)
+}
+
+/// The first `keep` rows of a CSV (quoted fields, "" inside them, line breaks in them) or TSV, and how many it has
+/// (null past 200 MB).
+function readTable(file, sep, keep, size) {
+ const fd = fs.openSync(file, 'r'), buf = Buffer.alloc(1 << 20), dec = new StringDecoder('utf8'), csv = sep === ','
+ const rows = []
+ let row = [], field = '', quoted = false, total = 0, read = 0, pending = false
+ const endField = () => { if (rows.length < keep) row.push(field.slice(0, 2000)); field = '' }
+ const endRow = () => { endField(); if (rows.length < keep) rows.push(row); row = []; total++ }
+ try {
+ for (let got; (got = fs.readSync(fd, buf, 0, buf.length, null)) > 0;) {
+ if ((read += got) > READ_ALL && rows.length >= keep) return { rows: rows.map(r => r.map(clean)), total: null }
+ const s = dec.write(buf.subarray(0, got))
+ for (let k = 0; k < s.length; k++) {
+ const c = s[k]
+ if (pending) { pending = false; if (c === '"') { field += '"'; continue } quoted = false } // a "" split by a read
+ if (quoted) {
+ if (c !== '"') { if (rows.length < keep) field += c }
+ else if (k + 1 === s.length) pending = true
+ else if (s[k + 1] === '"') { field += '"'; k++ }
+ else quoted = false
+ }
+ else if (c === '"' && csv && field === '') quoted = true
+ else if (c === sep) endField()
+ else if (c === '\n') endRow()
+ else if (c !== '\r' && rows.length < keep) field += c
+ }
+ }
+ } finally { fs.closeSync(fd) }
+ if (field || row.length) endRow()
+ return { rows: rows.map(r => r.map(clean)), total }
+}
+
+function render(kind, file, dir, title) {
+ const size = fs.statSync(file).size
+ if (kind === 'markdown') {
+ const buf = head(file, HEAD.markdown), whole = buf.length >= size
+ let text = clean(new TextDecoder().decode(buf))
+ if (!whole) text = text.slice(0, text.lastIndexOf('\n') + 1)
+ const more = whole ? '' : `<p class="note">The first ${count(HEAD.markdown / 1024)} KB of ${count(Math.round(size / 1024))} KB.</p>`
+ fs.writeFileSync(path.join(dir, 'view.html'), page(title, markdown(text) + more))
+ return { shot: 'view.html', note: whole ? null : 'first part', cutNote: 'first part' }
+ }
+ if (kind === 'text') {
+ const buf = head(file, HEAD.text), whole = buf.length >= size
+ let text = clean(new TextDecoder().decode(buf)).replace(/\r\n?/g, '\n').replace(/\t/g, ' ')
+ // minified JSON, laid out (its lines are then the laid-out ones)
+ if (whole && /\.json$/i.test(file) && text.length > 200 && text.split('\n', 4).length < 4) {
+ try { text = JSON.stringify(JSON.parse(text), null, 2) } catch {}
+ }
+ const lines = text.split('\n')
+ if (lines.at(-1) === '') lines.pop()
+ if (!whole && lines.length > 1) lines.pop() // a line cut by the read
+ const total = whole ? lines.length : lineCount(file, size)
+ const n = Math.min(lines.length, linesThatFit(lines.slice(0, TEXT_LINES), TEXT_ROWS, 1000))
+ fs.writeFileSync(path.join(dir, 'view.html'), page(title, textBody(lines.slice(0, VIEW_LINES), total, 5000), 'text'))
+ fs.writeFileSync(path.join(dir, 'shot.html'), page(title, textBody(lines.slice(0, n), total, 1000), 'text'))
+ return {
+ shot: 'shot.html',
+ note: total == null ? `first ${count(n)} lines` : n < total ? `first ${count(n)} lines of ${count(total)}` : null,
+ cutNote: total == null ? 'first part' : `first part of ${count(total)} lines`,
+ }
+ }
+ if (kind === 'table') {
+ const { rows, total: all } = readTable(file, /\.tsv$/i.test(file) ? '\t' : ',', VIEW_ROWS + 1, size)
+ const total = all == null ? null : Math.max(0, all - 1) // rows under the header
+ // the picture: each cell on one line, at most 40 characters (about 7.4 pt each, 18 pt of padding), the columns
+ // that fit in 1300 pt; page-shot widens the page to the table, up to 1600 pt, the picture at most 1200 px wide.
+ // Its rows, 27 pt each: as many as a picture of that width holds (10 M pixels, a page 9000 pt tall).
+ const allCols = Math.max(...rows.map(r => r.length), 1)
+ let cols = 0, wide = 24
+ for (; cols < Math.min(TABLE_COLS, allCols); cols++) {
+ const col = Math.max(1, ...rows.slice(0, 201).map(r => Math.min(40, (r[cols] ?? '').length))) * 7.4 + 18
+ if (cols && wide + col > 1300) break
+ wide += col
+ }
+ const w = Math.max(390, wide), px = Math.min(w * 2, Math.max(780, 1200))
+ const fit = Math.floor((Math.min(9000, 10e6 / px / (px / w)) - 90) / 27)
+ const shown = Math.max(0, Math.min(200, fit, rows.length - 1))
+ fs.writeFileSync(path.join(dir, 'view.html'), page(title, tableBody(rows, total ?? rows.length - 1, VIEW_COLS, 300, false), 'table'))
+ fs.writeFileSync(path.join(dir, 'shot.html'), page(title, tableBody(rows.slice(0, shown + 1), total ?? shown, cols, 40, true), 'table'))
+ const narrower = cols < allCols ? `, ${cols} of ${allCols} columns` : ''
+ return {
+ shot: 'shot.html', maxWidth: 1600,
+ note: total == null ? `first ${count(shown)} rows${narrower}` : shown < total ? `first ${count(shown)} rows of ${count(total)}${narrower}` : narrower.slice(2) || null,
+ cutNote: total == null ? 'first part' : `first part of ${count(total)} rows`,
+ }
+ }
+ throw new Error(`no such kind: ${kind}`)
+}
+
+if (process.argv[1] === import.meta.filename) {
+ const [kind, file, dir, title] = process.argv.slice(2)
+ try { process.stdout.write(JSON.stringify(render(kind, file, dir, title || path.basename(file)))) }
+ catch (e) { process.stderr.write(`render: ${e.message}\n`); process.exit(1) }
+}
diff --git a/hub/runtimes.mjs b/hub/runtimes.mjs
new file mode 100644
index 0000000..fe6388e
--- /dev/null
+++ b/hub/runtimes.mjs
@@ -0,0 +1,614 @@
+// Agents the hub runs itself: OpenAI Codex, GitHub Copilot, and any Agent Client Protocol agent. (Claude Code agents
+// are interactive sessions in a terminal of their own instead: bin/chums-agents, the channel and the hooks.)
+// docs/other-agents.md has the why; design/STATES.md has every signal's meaning on the watch.
+//
+// runtime 'codex' `codex app-server`: OpenAI's own JSON-RPC protocol, the one Codex's IDE extension, desktop app
+// and terminal use, on a Unix socket of the agent's own. The hub is a client of it, and a Codex
+// terminal can be one too, on the same thread at the same time (bin/chums-agents open).
+// runtime 'copilot' the GitHub Copilot SDK (@github/copilot-sdk): GitHub's own JSON-RPC client for the Copilot CLI
+// runtime, which it runs (its bundled runtime, or `command` for the installed `copilot`).
+// runtime 'acp' any Agent Client Protocol agent, from its `command`: ["copilot", "--acp"], ["gemini",
+// "--experimental-acp"], ["npx", "@agentclientprotocol/claude-agent-acp"]…
+//
+// Each run gives the watch what a Claude Code session gives it, in the same words: the hub's hook vocabulary
+// (UserPromptSubmit, PreToolUse, PostToolUse, Stop, StopFailure, PreCompact…), approval cards and spoken replies.
+// Orders arrive through deliver(); the agent replies with chums_reply / chums_show from the Chums MCP server
+// (channel/chums-channel.mjs in tools-only mode), and when a turn from the watch ends without one, the hub speaks the
+// first sentence of the agent's last message instead, so the watch never stays silent.
+import { spawn, execFileSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import crypto from 'node:crypto'
+import { lines, wsUnix, peer } from './jsonrpc.mjs'
+import { standingFor, WATCH_GUIDE, MAX_WORDS, Owner, markFor, wordsFor } from './standing.mjs'
+
+const ROOT = path.join(import.meta.dirname, '..')
+const CHANNEL = path.join(ROOT, 'channel/chums-channel.mjs')
+const REAL_HOME = os.userInfo().homedir // the CLIs' logins live there, whatever HOME the hub has
+const VERSION = '0.1.0'
+
+export const RUNTIMES = ['claude', 'codex', 'copilot', 'acp']
+/// Agents whose process the hub runs (not a Claude Code session in its own terminal).
+export const runByHub = a => !!a.runtime && a.runtime !== 'claude'
+
+const DEBUG = !!process.env.CHUMS_RUNTIME_DEBUG // every event the agent sends, in its host log
+const LIMIT = /rate.?limit|quota|too many requests|\b429\b|usage limit|allowance|overloaded|capacity|exceeded your/i
+const short = (t, n = 60) => { const s = String(t ?? '').replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1) + '…' : s }
+
+/// The first sentence of an agent's answer, said aloud: no markdown, code, links or paths, 15 words at most. With a
+/// longer limit (an order from the iPhone), as many whole sentences as fit in it.
+export function spokenLine(text, limit = MAX_WORDS) {
+ const t = String(text ?? '')
+ .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
+ .replace(/https?:\/\/\S+/g, 'a link')
+ .replace(/(^|\s)(~|\.{0,2})?\/[\w.\-/]+/g, (m, sp, _p, off, all) => sp + m.trim().split('/').filter(Boolean).pop())
+ .replace(/[`*]|^#+\s*|^\s*([-•]|\d+\.)\s+/gm, '')
+ .replace(/\s+/g, ' ').trim()
+ if (!t) return ''
+ // sentences end at . ! ? before a space or the end (so "notes.md" stays whole)
+ const sentences = (t.match(/.+?[.!?]+(?=\s|$)|.+$/g) ?? [t]).map(x => x.trim())
+ let first = sentences[0]
+ if (limit > MAX_WORDS) for (const s of sentences.slice(1)) { // the watch: the first sentence only
+ if ((first + ' ' + s).split(' ').length > limit) break
+ first += ' ' + s
+ }
+ const words = first.split(' ')
+ return words.length > limit ? words.slice(0, limit).join(' ').replace(/[,;:]$/, '') + '…' : first
+}
+
+/// What a shell command an agent runs looks like on the watch, in Claude Code's words (hub/hub.mjs toolEvent).
+function shellTool(command, actions) {
+ const a = actions?.length === 1 ? actions[0] : null
+ if (a?.type === 'read' && a.path) return { tool: 'Read', input: { file_path: a.path } }
+ if (a?.type === 'search') return { tool: 'Grep', input: { pattern: a.query ?? a.command } }
+ if (a?.type === 'listFiles') return { tool: 'Glob', input: { pattern: a.path ?? a.command } }
+ // codex wraps every command in the login shell: /bin/zsh -lc '…'
+ const plain = actions?.length ? actions.map(x => x.command).join(' && ') : String(command ?? '').replace(/^\S*\/(ba|z)?sh -l?c '([\s\S]*)'$/, '$2')
+ return { tool: 'Bash', input: { command: plain } }
+}
+
+/// An ACP tool call in Claude Code's words.
+function acpTool(tc) {
+ const input = tc.rawInput ?? {}, title = String(tc.title ?? '')
+ const file = tc.locations?.[0]?.path ?? input.path ?? input.file_path ?? input.filePath
+ switch (tc.kind) {
+ case 'read': return { tool: 'Read', input: { file_path: file ?? title } }
+ case 'edit': case 'delete': case 'move': return { tool: 'Edit', input: { file_path: file ?? title } }
+ case 'search': return { tool: 'Grep', input: { pattern: input.pattern ?? input.query ?? title } }
+ case 'fetch': return { tool: 'WebFetch', input: { url: input.url ?? input.query ?? title } }
+ case 'execute': return { tool: 'Bash', input: { command: input.command ?? input.commands?.join(' && ') ?? title } }
+ case 'think': return { tool: 'Task', input: { description: title } }
+ default: return { tool: short(title, 40) || 'Tool', input }
+ }
+}
+// the agent calling Chums' own tools: never an event or an approval card, like mcp__chums__* in Claude Code
+const CHUMS_TOOL = /chums[\w.-]*(reply|show)\b/i
+const isChums = tc => CHUMS_TOOL.test(`${tc.title ?? ''} ${tc.toolCallId ?? ''} ${JSON.stringify(tc._meta ?? '')}`)
+
+// ---------- one agent's process, kept running ----------
+class Runner {
+ constructor(agent, hub) {
+ this.a = agent; this.hub = hub
+ this.s = null // the hub's session while the agent is up
+ this.asks = new Map() // approval card id -> resolve(behavior)
+ this.turn = null // { startedAt, text, fromWatch, tools }
+ this.stopped = false; this.backoff = 5_000; this.upAt = 0; this.runs = 0; this.ended = 0
+ this.logFile = path.join(hub.dir, 'agents', `${agent.id}.host.log`)
+ fs.mkdirSync(path.dirname(this.logFile), { recursive: true })
+ }
+ note(...m) { fs.appendFileSync(this.logFile, `${new Date().toISOString().slice(0, 19).replace('T', ' ')} ${m.join(' ')}\n`) }
+ env(extra = {}) {
+ const PATH = [`${REAL_HOME}/.npm-global/bin`, '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin', process.env.PATH].filter(Boolean).join(':')
+ const env = { ...process.env, HOME: REAL_HOME, PATH, ...extra }
+ for (const k of ['CHUMS_NO_WHISPER', 'CHUMS_NAME', 'CHUMS_SESSION']) delete env[k]
+ return env
+ }
+ spawnAgent(cmd, args, stdio = ['pipe', 'pipe', 'pipe']) {
+ fs.mkdirSync(this.a.cwd, { recursive: true })
+ const child = spawn(cmd, args, { cwd: this.a.cwd, env: this.env(), stdio })
+ child.on('error', e => this.note('could not start:', e.message))
+ const out = fs.openSync(this.logFile, 'a')
+ child.stderr?.on('data', d => fs.writeSync(out, d))
+ child.on('exit', (code, sig) => { this.note(`exited (${sig ?? code})`); fs.closeSync(out); this.exited() })
+ this.child = child
+ return child
+ }
+ start() {
+ this.upAt = Date.now(); this.runs++
+ this.run().then(() => { this.note('running'); this.hub.log(`${this.a.id}: ${this.a.runtime} running`) })
+ .catch(e => { this.note('not started:', e.message); this.hub.log(`${this.a.id}: ${this.a.runtime} not started: ${e.message}`); this.kill(); this.exited() })
+ }
+ kill() { try { this.child?.kill() } catch {} }
+ /// The run is over (its process exited, or it never got going): the agent leaves the watch, and starts again later.
+ exited() {
+ if (this.ended === this.runs) return
+ this.ended = this.runs
+ if (this.s) { this.hub.leave(this.s.id); this.s = null }
+ this.asks.clear(); this.turn = null; this.child = null
+ if (this.stopped) return
+ if (Date.now() - this.upAt > 120_000) this.backoff = 5_000 // it had been up a while: a fresh start
+ const wait = this.backoff; this.backoff = Math.min(this.backoff * 2, 120_000)
+ this.note(`starting again in ${wait / 1000} s`)
+ setTimeout(() => !this.stopped && this.start(), wait).unref?.()
+ }
+ stop() { this.stopped = true; this.kill() }
+ join(source) {
+ this.s = this.hub.join({ id: this.sid, name: this.a.id, cwd: this.a.cwd, driver: this })
+ this.hub.hook(this.s, 'SessionStart', { source })
+ }
+
+ // the hub's side: an order or a verdict for this agent
+ deliver(item) {
+ if (item.type === 'order') this.device = item.device // its answer's length follows where it was asked
+ if (item.type === 'verdict') { const r = this.asks.get(item.requestId); if (r) { this.asks.delete(item.requestId); r(item.behavior) } }
+ else if (item.type === 'order') this.order(item)
+ }
+ /// An approval card on the watch; resolves 'allow' or 'deny' when it's answered.
+ ask(tool, description, input) {
+ const requestId = crypto.randomBytes(5).toString('hex')
+ return { requestId, answer: new Promise(resolve => { this.asks.set(requestId, resolve); this.hub.ask(this.s, { requestId, tool, description, input }) }) }
+ }
+ newTurn(fromWatch) {
+ this.turn = { startedAt: Date.now(), text: '', fromWatch, tools: new Map() }
+ this.hub.hook(this.s, 'UserPromptSubmit')
+ }
+ /// The turn ended. A turn from the watch that didn't speak gets its answer's first sentence said for it.
+ finish(how, error) {
+ const s = this.s, t = this.turn
+ this.turn = null
+ if (!s) return
+ if (how === 'interrupted') this.hub.react(s, 'interrupt')
+ if (how === 'done' || how === 'interrupted') {
+ const line = spokenLine(t?.text, wordsFor(this.device))
+ if (t?.fromWatch && line && !(s.lastSpokeAt > t.startedAt)) this.hub.reply(s, line, 'done', 'final message')
+ this.hub.hook(s, 'Stop')
+ } else this.hub.hook(s, 'StopFailure', { error: LIMIT.test(error) ? 'rate_limit' : short(error) || 'error' })
+ }
+}
+
+// ---------- Agent Client Protocol (`copilot --acp`, `gemini --experimental-acp`, the ACP adapters…) ----------
+class AcpRunner extends Runner {
+ command() {
+ if (!this.a.command?.length) throw new Error('an acp agent needs "command", e.g. ["copilot", "--acp"]')
+ return [...this.a.command, ...(this.a.args ?? [])]
+ }
+ async run() {
+ const [cmd, ...args] = this.command()
+ this.sid = crypto.randomUUID(); this.queue = []; this.busy = false; this.primed = false
+ const child = this.spawnAgent(cmd, args)
+ this.rpc = peer(lines(child), {
+ onRequest: (m, p) => this.request(m, p), onNotification: (m, p) => this.update(m, p), log: (...x) => this.note(...x),
+ })
+ const init = await this.rpc.request('initialize', {
+ protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
+ clientInfo: { name: 'chums', title: 'Chums', version: VERSION },
+ }, 60_000)
+ this.note(`initialized: ${init.agentInfo?.name ?? cmd} ${init.agentInfo?.version ?? ''} (protocol ${init.protocolVersion})`)
+ const env = { CHUMS_SESSION: this.sid, CHUMS_HUB: this.hub.url, CHUMS_TOKEN: this.hub.token, CHUMS_NAME: this.a.id }
+ const mcpServers = this.a.chumsTools === false ? [] : [{ name: 'chums', command: process.execPath, args: [CHANNEL], env: Object.entries(env).map(([name, value]) => ({ name, value })) }]
+ let resumed = false
+ if (this.a.sessionId && init.agentCapabilities?.loadSession) {
+ this.loading = true // the agent replays the conversation: none of it is news
+ try { await this.rpc.request('session/load', { sessionId: this.a.sessionId, cwd: this.a.cwd, mcpServers }, 120_000); resumed = true }
+ catch (e) { this.note(`couldn't load ${this.a.sessionId}: ${e.message}; starting a new one`) }
+ this.loading = false
+ }
+ if (!resumed) {
+ const r = await this.rpc.request('session/new', { cwd: this.a.cwd, mcpServers }, 120_000)
+ this.hub.saveSessionId(this.a.id, r.sessionId)
+ }
+ this.acpSession = this.a.sessionId
+ this.join(resumed ? 'resume' : 'startup')
+ }
+ order(item) { this.queue.push(item); if (!this.busy) this.pump() }
+ // one prompt at a time (the protocol's rule); orders said meanwhile wait their turn
+ async pump() {
+ this.busy = true
+ while (this.queue.length && this.s) {
+ const { text, device } = this.queue.shift()
+ const intro = this.primed ? '' : `[Standing instructions from Chums, for this whole conversation:]\n${standingFor(this.a)}\n${WATCH_GUIDE}\n\n`
+ this.primed = true
+ this.newTurn(true)
+ try {
+ const r = await this.rpc.request('session/prompt', { sessionId: this.acpSession, prompt: [{ type: 'text', text: `${intro}${markFor(device)} ${text}` }] })
+ const stop = r?.stopReason ?? 'end_turn'
+ if (stop === 'end_turn') this.finish('done')
+ else if (stop === 'cancelled') this.finish('interrupted')
+ else this.finish('failed', { max_tokens: 'max output tokens', max_turn_requests: 'too many turns', refusal: 'refused' }[stop] ?? stop)
+ } catch (e) {
+ if (e.code === 'closed') break
+ this.note('prompt failed:', e.message); this.finish('failed', e.message)
+ }
+ }
+ this.busy = false
+ }
+ update(method, p) {
+ if (DEBUG) this.note('<-', method, p.update?.sessionUpdate ?? '', this.loading ? '(loading)' : '')
+ if (method !== 'session/update' || this.loading || !this.s) return
+ const u = p.update ?? {}, s = this.s
+ this.turn ??= { startedAt: Date.now(), text: '', fromWatch: false, tools: new Map() }
+ const tools = this.turn.tools
+ switch (u.sessionUpdate) {
+ case 'agent_message_chunk':
+ if (u.content?.type === 'text') this.turn.text += u.content.text
+ break
+ case 'tool_call': {
+ if (tools.has(u.toolCallId)) break
+ this.turn.text = '' // its answer is what it says after its last tool call
+ if (isChums(u)) { tools.set(u.toolCallId, { chums: true }); break }
+ const { tool, input } = acpTool(u)
+ tools.set(u.toolCallId, { tool, kind: u.kind, title: u.title, rawInput: u.rawInput, locations: u.locations })
+ this.hub.hook(s, 'PreToolUse', { tool, input })
+ this.toolDone(u)
+ break
+ }
+ case 'tool_call_update': this.toolDone(u); break
+ }
+ }
+ toolDone(u) {
+ const t = this.turn?.tools.get(u.toolCallId)
+ if (!t || t.chums || t.done || !['completed', 'failed'].includes(u.status)) return
+ t.done = true
+ const said = (u.content ?? []).map(c => c.content?.text ?? '').join(' ')
+ if (u.status === 'failed') this.hub.hook(this.s, 'PostToolUseFailure', { tool: t.tool, error: short(said || 'failed', 80) })
+ else this.hub.hook(this.s, 'PostToolUse', { tool: t.tool, result: JSON.stringify(u.rawOutput ?? said).slice(-1500) })
+ }
+ async request(method, p) {
+ if (method !== 'session/request_permission') throw Object.assign(new Error(`${method} isn't offered`), { code: -32601 })
+ const known = this.turn?.tools.get(p.toolCall?.toolCallId) ?? {}
+ const tc = { ...known, ...p.toolCall, kind: p.toolCall?.kind ?? known.kind, rawInput: p.toolCall?.rawInput ?? known.rawInput }
+ const pick = (...kinds) => { for (const k of kinds) { const o = p.options?.find(x => x.kind === k); if (o) return { outcome: { outcome: 'selected', optionId: o.optionId } } } return { outcome: { outcome: 'cancelled' } } }
+ if (known.chums || isChums(tc)) return pick('allow_once', 'allow_always') // speaking to the watch is always allowed
+ const { tool, input } = acpTool(tc)
+ const behavior = await this.ask(tool, String(tc.title ?? tool), input).answer
+ return behavior === 'allow' ? pick('allow_once', 'allow_always') : pick('reject_once', 'reject_always')
+ }
+}
+
+// ---------- GitHub Copilot: its SDK ----------
+let copilotSdk = null
+const loadCopilotSdk = async () => copilotSdk ??= await import('@github/copilot-sdk')
+ .catch(e => { throw new Error(`runtime "copilot" needs the Copilot SDK, an optional dependency (about 130 MB): cd ${ROOT} && npm install --no-save @github/copilot-sdk (${e.message})`) })
+
+/// A Copilot CLI tool call in Claude Code's words.
+function copilotTool(name, args, d = {}) {
+ const i = args ?? {}, n = String(name ?? '').toLowerCase()
+ const file = i.path ?? i.file_path ?? i.filePath ?? i.file
+ if (d.shellToolInfo || ['bash', 'shell', 'powershell', 'zsh'].includes(n)) return { tool: 'Bash', input: { command: i.command ?? i.fullCommandText ?? name } }
+ if (['view', 'read', 'read_file', 'show_file'].includes(n)) return { tool: 'Read', input: { file_path: file } }
+ if (['create', 'write', 'write_file', 'create_file'].includes(n)) return { tool: 'Write', input: { file_path: file } }
+ if (/edit|replace|patch/.test(n)) return { tool: 'Edit', input: { file_path: file } }
+ if (['grep', 'rg', 'search', 'search_code'].includes(n)) return { tool: 'Grep', input: { pattern: i.pattern ?? i.query } }
+ if (n === 'glob') return { tool: 'Glob', input: { pattern: i.pattern } }
+ if (/fetch/.test(n)) return { tool: 'WebFetch', input: { url: i.url } }
+ if (/web_?search/.test(n)) return { tool: 'WebSearch', input: { query: i.query } }
+ if (['task', 'agent', 'subagent'].includes(n)) return { tool: 'Task', input: { description: i.description ?? i.prompt } }
+ return { tool: short(d.toolTitle ?? (d.mcpServerName ? `${d.mcpServerName} ${d.mcpToolName ?? name}` : name), 40) || 'Tool', input: i }
+}
+
+class CopilotRunner extends Runner {
+ async run() {
+ const { CopilotClient, RuntimeConnection } = await loadCopilotSdk()
+ const a = this.a
+ this.sid = crypto.randomUUID(); this.calls = new Map()
+ fs.mkdirSync(a.cwd, { recursive: true })
+ const env = this.env()
+ // the SDK's own Copilot runtime (pinned with the SDK), or the installed CLI when `command` names it
+ this.client = new CopilotClient({
+ workingDirectory: a.cwd, logLevel: 'error',
+ ...(a.command?.length ? { connection: RuntimeConnection.forStdio({ path: a.command[0], args: a.command.slice(1), env }) } : { env }),
+ })
+ await this.client.start()
+ // the SDK watches its runtime's process this way itself; when it exits, so does this run
+ this.client.processExitPromise?.catch(e => { this.note(e.message); this.exited() })
+ const chums = { CHUMS_SESSION: this.sid, CHUMS_HUB: this.hub.url, CHUMS_TOKEN: this.hub.token, CHUMS_NAME: a.id }
+ const config = {
+ ...(a.model ? { model: a.model } : {}),
+ workingDirectory: a.cwd, additionalDirectories: a.addDirs ?? [],
+ systemMessage: { mode: 'append', content: `${standingFor(a)}\n\n${WATCH_GUIDE}` },
+ mcpServers: a.chumsTools === false ? {} : { chums: { type: 'local', command: process.execPath, args: [CHANNEL], env: chums, tools: ['*'] } },
+ onPermissionRequest: req => this.permission(req),
+ }
+ let session = null, resumed = false
+ if (a.sessionId) {
+ try { session = await this.client.resumeSession(a.sessionId, config); resumed = true }
+ catch (e) { this.note(`couldn't resume ${a.sessionId}: ${e.message}; starting a new session`) }
+ }
+ if (!session) {
+ session = await this.client.createSession(config)
+ this.hub.saveSessionId(a.id, session.sessionId)
+ }
+ this.session = session
+ session.on(ev => { try { this.event(ev) } catch (e) { this.note('event:', ev.type, e.message) } })
+ this.join(resumed ? 'resume' : 'startup')
+ this.note(`session ${session.sessionId}`)
+ }
+ kill() { const c = this.client; this.client = null; c?.forceStop?.().catch(() => {}) }
+
+ async order(item) {
+ // said while it works, the order waits for the turn to end (the SDK's queue, as typing into its terminal would);
+ // it becomes a turn of its own when the runtime takes it up (user.message). Its `immediate` mode, which would
+ // push it into the turn in progress, can lose a message said just as a turn ends.
+ if (!this.turn) this.newTurn(true)
+ try { await this.session.send({ prompt: `${markFor(item.device)} ${item.text}` }) }
+ catch (e) { this.note('send failed:', e.message); this.finish('failed', e.message) }
+ }
+ event(ev) {
+ if (DEBUG && !/delta|usage|model\.|background_tasks/.test(ev.type)) this.note('<-', ev.type, `turn: ${!!this.turn}`)
+ const s = this.s, d = ev.data ?? {}
+ if (!s) return
+ switch (ev.type) {
+ case 'tool.execution_start': {
+ if (d.mcpServerName === 'chums' || CHUMS_TOOL.test(d.toolName)) { this.calls.set(d.toolCallId, { chums: true }); break }
+ const { tool, input } = copilotTool(d.toolName, d.arguments, d)
+ this.calls.set(d.toolCallId, { tool })
+ this.turn ??= { startedAt: Date.now(), text: '', fromWatch: false, tools: new Map() }
+ this.hub.hook(s, 'PreToolUse', { tool, input })
+ break
+ }
+ case 'tool.execution_complete': {
+ const c = this.calls.get(d.toolCallId)
+ if (!c || c.chums) break
+ this.calls.delete(d.toolCallId)
+ const failed = !d.success || (d.shellExecution?.exitCode ?? 0) !== 0
+ if (!d.success && d.error && !/denied|declined|reject/i.test(d.error.message)) this.hub.hook(s, 'PostToolUseFailure', { tool: c.tool, error: short(d.error.message, 80) })
+ else this.hub.hook(s, 'PostToolUse', { tool: c.tool, result: JSON.stringify({ is_error: failed }) })
+ break
+ }
+ case 'user.message': if (!this.turn) this.newTurn(true); break // a queued order, taken up now
+ // its answer: the last message that isn't on its way to a tool call
+ case 'assistant.message': if (this.turn && d.content?.trim() && !d.toolRequests?.length) this.turn.text = d.content; break
+ case 'session.error':
+ if (this.turn) this.finish('failed', ['rate_limit', 'quota'].includes(d.errorType) ? 'rate limit' : d.message ?? d.errorType)
+ break
+ case 'session.idle': if (this.turn) this.finish(d.aborted ? 'interrupted' : 'done'); break
+ case 'session.compaction_start': this.hub.hook(s, 'PreCompact', { trigger: 'auto' }); break
+ case 'session.compaction_complete': this.hub.hook(s, 'PostCompact'); break
+ case 'subagent.started': this.hub.hook(s, 'SubagentStart', { agent: d.toolCallId }); break
+ case 'subagent.completed': case 'subagent.failed': this.hub.hook(s, 'SubagentStop', { agent: d.toolCallId }); break
+ }
+ }
+ async permission(req) {
+ if ((req.kind === 'mcp' && req.serverName === 'chums') || (req.kind === 'custom-tool' && CHUMS_TOOL.test(req.toolName))) return { kind: 'approve-once' }
+ const [tool, description, input] =
+ req.kind === 'shell' ? ['Bash', req.intention, { command: req.fullCommandText }]
+ : req.kind === 'write' ? [req.newFileContents != null && !req.diff ? 'Write' : 'Edit', req.intention, { file_path: req.fileName }]
+ : req.kind === 'read' ? ['Read', req.intention, { file_path: req.path }]
+ : req.kind === 'url' ? ['WebFetch', req.intention, { url: req.url }]
+ : req.kind === 'mcp' ? [`${req.serverName} ${req.toolName}`, req.toolTitle, req.args ?? {}]
+ : [req.kind, req.intention ?? req.toolName ?? req.kind, req.args ?? {}]
+ const ok = await this.ask(tool, String(description || tool), input).answer
+ return ok === 'allow' ? { kind: 'approve-once' } : { kind: 'reject', feedback: `${Owner} said no, on the watch.` }
+ }
+}
+
+// ---------- OpenAI Codex: its app-server ----------
+const SOCK_DIR = `/tmp/chums-${process.getuid?.() ?? 'u'}` // short: a Unix socket's path has room for 103 bytes
+const toml = v => JSON.stringify(v) // TOML's strings and arrays of strings are JSON's
+
+class CodexRunner extends Runner {
+ socket() { return path.join(SOCK_DIR, `${this.hub.port}-${this.a.id}.sock`) }
+ /// An app-server a previous hub left running on this socket (a hub killed hard can't stop it): stop it first.
+ stale(sock) {
+ try {
+ const { pid } = JSON.parse(fs.readFileSync(path.join(this.hub.dir, 'agents', `${this.a.id}.runtime.json`), 'utf8'))
+ const cmd = execFileSync('/bin/ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' })
+ if (cmd.includes('app-server') && cmd.includes(sock)) { process.kill(pid); this.note(`stopped the app-server a previous run left (pid ${pid})`) }
+ } catch {}
+ }
+ async run() {
+ const a = this.a, sock = this.socket()
+ fs.mkdirSync(SOCK_DIR, { recursive: true, mode: 0o700 })
+ // a folder of our own, not a link to one, that only we can open (one made earlier with other modes is closed)
+ const dir = fs.lstatSync(SOCK_DIR)
+ if (!dir.isDirectory() || dir.uid !== process.getuid()) throw new Error(`${SOCK_DIR} isn't ours`)
+ if (dir.mode & 0o077) fs.chmodSync(SOCK_DIR, 0o700)
+ this.stale(sock)
+ fs.rmSync(sock, { force: true })
+ this.sid = crypto.randomUUID(); this.files = new Map(); this.byRpc = new Map(); this.activeTurn = null
+ // the token's file, not the token: Codex's -c arguments are in the process list, which every user of the Mac can read
+ const env = `{ CHUMS_SESSION = ${toml(this.sid)}, CHUMS_HUB = ${toml(this.hub.url)}, CHUMS_CONFIG = ${toml(path.join(this.hub.dir, 'config.json'))}, CHUMS_NAME = ${toml(a.id)} }`
+ const config = [
+ ...(a.chumsTools === false ? [] : [
+ `mcp_servers.chums.command=${toml(process.execPath)}`, `mcp_servers.chums.args=[${toml(CHANNEL)}]`, `mcp_servers.chums.env=${env}`,
+ ]),
+ ...(a.addDirs?.length ? [`sandbox_workspace_write.writable_roots=[${a.addDirs.map(toml).join(', ')}]`] : []),
+ ...(a.config ?? []),
+ ]
+ const [bin = 'codex', ...more] = a.command ?? []
+ this.spawnAgent(bin, [...more, 'app-server', '--listen', `unix://${sock}`, ...config.flatMap(c => ['-c', c])], ['ignore', 'ignore', 'pipe'])
+ let transport = null
+ for (let i = 0; i < 150 && !transport && this.child; i++) {
+ await new Promise(r => setTimeout(r, 100))
+ if (fs.existsSync(sock)) transport = await wsUnix(sock).catch(() => null)
+ }
+ if (!transport) throw new Error(`codex app-server didn't open ${sock}`)
+ this.rpc = peer(transport, {
+ onRequest: (m, p, id) => this.request(m, p, id), onNotification: (m, p) => this.event(m, p), log: (...x) => this.note(...x),
+ })
+ this.rpc.on('close', () => this.kill())
+ const init = await this.rpc.request('initialize', { clientInfo: { name: 'chums', title: 'Chums', version: VERSION }, capabilities: null }, 60_000)
+ this.rpc.notify('initialized')
+ this.note(`initialized: ${init.userAgent}`)
+ const params = {
+ cwd: a.cwd, model: a.model ?? null, approvalPolicy: a.approvalPolicy ?? this.hub.codexPolicy(), sandbox: a.sandbox ?? 'workspace-write',
+ developerInstructions: `${standingFor(a)}\n\n${WATCH_GUIDE}`,
+ }
+ let thread = null
+ if (a.sessionId) {
+ try { thread = (await this.rpc.request('thread/resume', { threadId: a.sessionId, ...params, excludeTurns: true }, 120_000)).thread }
+ catch (e) { this.note(`couldn't resume ${a.sessionId}: ${e.message}; starting a new thread`) }
+ }
+ if (!thread) {
+ thread = (await this.rpc.request('thread/start', params, 120_000)).thread
+ this.hub.saveSessionId(a.id, thread.id)
+ }
+ this.threadId = thread.id
+ this.nameThread()
+ // what bin/chums-agents open needs to put a Codex terminal on this same thread
+ fs.writeFileSync(path.join(this.hub.dir, 'agents', `${a.id}.runtime.json`),
+ JSON.stringify({ runtime: 'codex', thread: thread.id, socket: sock, cwd: a.cwd, pid: this.child?.pid }, null, 2))
+ this.join(a.sessionId === thread.id && thread.status?.type !== 'notLoaded' ? 'resume' : 'startup')
+ }
+
+ /// Its name in Codex's own lists (`codex resume`, the desktop app): "Chums: <agent>". A new thread can only be
+ /// named once it has a first turn on disk, so it's tried again after each turn until it takes.
+ nameThread() {
+ const name = `Chums: ${this.a.name ?? this.a.id}`
+ this.rpc.request('thread/name/set', { threadId: this.threadId, name }, 30_000)
+ .then(() => { this.named = true }, e => DEBUG && this.note('naming the thread:', e.message))
+ }
+
+ async order(item) {
+ const s = this.s
+ if (this.answerNext) { const r = this.answerNext; this.answerNext = null; return r(item.said ?? item.text) }
+ const input = [{ type: 'text', text: `${markFor(item.device)} ${item.text}`, text_elements: [] }]
+ if (this.activeTurn) {
+ // it's working: the order joins the turn in progress, as typing into its terminal would
+ try {
+ await this.rpc.request('turn/steer', { threadId: this.threadId, input, expectedTurnId: this.activeTurn })
+ if (this.turn) Object.assign(this.turn, { fromWatch: true, startedAt: Date.now(), text: '' }) // what counts is the answer to this
+ return
+ }
+ catch (e) { this.note('steer refused:', e.message) }
+ }
+ this.watchTurn = true
+ try { await this.rpc.request('turn/start', { threadId: this.threadId, input }) }
+ catch (e) {
+ this.watchTurn = false
+ // a turn was still ending (too late to steer, too early to start): it goes once that turn is over
+ if (this.activeTurn) { this.note('order waits for the turn to end:', e.message); (this.waitingOrders ??= []).push(item); return }
+ this.note('turn failed to start:', e.message); if (s === this.s) this.finish('failed', e.message)
+ }
+ }
+
+ event(method, p) {
+ if (DEBUG && !/delta|tokenUsage|rateLimits|startupStatus/.test(method)) this.note('<-', method, p.item?.type ?? '')
+ const s = this.s
+ if (!s || (p.threadId && p.threadId !== this.threadId)) return
+ switch (method) {
+ case 'turn/started':
+ this.activeTurn = p.turn.id
+ this.newTurn(this.watchTurn); this.watchTurn = false // a turn typed in a Codex terminal isn't the watch's
+ break
+ case 'turn/completed': {
+ this.activeTurn = null
+ if (!this.named) this.nameThread()
+ if (this.waitingOrders?.length) setTimeout(() => this.order(this.waitingOrders.shift()), 0)
+ const t = p.turn
+ if (t.status === 'failed') {
+ const info = t.error?.codexErrorInfo, code = typeof info === 'string' ? info : Object.keys(info ?? {})[0]
+ this.finish('failed', ['usageLimitExceeded', 'rateLimitExceeded', 'serverOverloaded', 'sessionBudgetExceeded'].includes(code) ? 'rate limit' : t.error?.message ?? code)
+ } else this.finish(t.status === 'interrupted' ? 'interrupted' : 'done')
+ break
+ }
+ case 'item/started': this.itemStarted(p.item); break
+ case 'item/completed': this.itemCompleted(p.item); break
+ case 'thread/status/changed':
+ if (p.status?.activeFlags?.includes('waitingOnUserInput')) { s.status = 'waiting'; this.hub.bump() }
+ break
+ case 'mcpServer/startupStatus/updated':
+ if (p.name === 'chums' && p.status !== 'starting') this.note(`chums tools: ${p.status}${p.error ? ` (${p.error})` : ''}`)
+ break
+ case 'serverRequest/resolved': {
+ // answered in a Codex terminal on the same thread: the card on the watch goes
+ const id = this.byRpc.get(p.requestId); this.byRpc.delete(p.requestId)
+ if (id && this.asks.has(id)) { this.asks.delete(id); this.hub.closeApproval(id) }
+ break
+ }
+ }
+ }
+ itemStarted(item) {
+ const s = this.s, hook = (tool, input) => this.hub.hook(s, 'PreToolUse', { tool, input })
+ switch (item.type) {
+ case 'commandExecution': { const t = shellTool(item.command, item.commandActions); hook(t.tool, t.input); break }
+ case 'fileChange':
+ this.files.set(item.id, item.changes ?? [])
+ hook(item.changes?.length === 1 && item.changes[0].kind?.type === 'add' ? 'Write' : 'Edit', { file_path: item.changes?.[0]?.path })
+ break
+ case 'mcpToolCall': if (item.server !== 'chums') hook(`${item.server} ${item.tool}`, item.arguments); break
+ case 'dynamicToolCall': hook(item.tool, item.arguments); break
+ case 'webSearch': hook('WebSearch', { query: item.query }); break
+ case 'imageView': hook('Read', { file_path: item.path }); break
+ case 'contextCompaction': this.hub.hook(s, 'PreCompact', { trigger: 'auto' }); break
+ case 'subAgentActivity': if (item.kind === 'started') this.hub.hook(s, 'SubagentStart', { agent: item.agentThreadId }); break
+ }
+ }
+ itemCompleted(item) {
+ const s = this.s, done = failed => this.hub.hook(s, 'PostToolUse', { result: JSON.stringify({ is_error: !!failed }) })
+ switch (item.type) {
+ case 'commandExecution': // couldn't run at all: a failure; ran and exited non-zero: marked
+ if (item.status === 'failed' && item.exitCode == null) this.hub.hook(s, 'PostToolUseFailure', { error: short(item.aggregatedOutput || 'failed', 80) })
+ else done(item.status !== 'completed' || (item.exitCode ?? 0) !== 0)
+ break
+ case 'fileChange': done(item.status !== 'completed'); break
+ case 'mcpToolCall': if (item.server !== 'chums') done(item.status === 'failed'); break
+ case 'dynamicToolCall': done(item.success === false); break
+ case 'webSearch': case 'imageView': done(false); break
+ case 'contextCompaction': this.hub.hook(s, 'PostCompact'); break
+ case 'subAgentActivity': if (item.kind !== 'started' && item.kind !== 'interacted') this.hub.hook(s, 'SubagentStop', { agent: item.agentThreadId }); break
+ case 'collabAgentToolCall':
+ for (const id of item.receiverThreadIds ?? []) {
+ if (item.tool === 'spawnAgent' && item.status === 'completed') this.hub.hook(s, 'SubagentStart', { agent: id })
+ if (item.tool === 'closeAgent') this.hub.hook(s, 'SubagentStop', { agent: id })
+ }
+ break
+ case 'agentMessage': if (this.turn && item.phase !== 'commentary') this.turn.text = item.text ?? ''; break
+ }
+ }
+ async request(method, p, rpcId) {
+ const card = (tool, description, input) => { const c = this.ask(tool, description, input); this.byRpc.set(rpcId, c.requestId); return c.answer }
+ switch (method) {
+ case 'item/commandExecution/requestApproval': {
+ const t = shellTool(p.command, p.commandActions)
+ const ok = await card('Bash', p.reason ?? 'Run a command', { command: t.tool === 'Bash' ? t.input.command : p.commandActions?.map(x => x.command).join(' && ') ?? p.command })
+ // decline: the command doesn't run and the turn goes on, so the agent can say so (cancel would end the turn).
+ // Codex 0.160 takes it even when availableDecisions leaves it out.
+ return { decision: ok === 'allow' ? 'accept' : 'decline' }
+ }
+ case 'item/fileChange/requestApproval': {
+ const changes = this.files.get(p.itemId) ?? []
+ const ok = await card(changes.length === 1 && changes[0].kind?.type === 'add' ? 'Write' : 'Edit',
+ p.reason ?? `Change ${changes.length || 'some'} file${changes.length === 1 ? '' : 's'}`, { file_path: changes[0]?.path ?? p.grantRoot })
+ return { decision: ok === 'allow' ? 'accept' : 'decline' }
+ }
+ case 'item/permissions/requestApproval': {
+ const want = p.permissions ?? {}
+ const what = [want.network && 'network access', want.fileSystem && 'more file access'].filter(Boolean).join(' and ') || 'more access'
+ const ok = await card('Permissions', p.reason ?? `Allow ${what}`, { description: p.reason ?? what })
+ const grant = {}
+ if (ok === 'allow') { if (want.network) grant.network = want.network; if (want.fileSystem) grant.fileSystem = want.fileSystem }
+ return { permissions: grant, scope: 'turn' }
+ }
+ case 'mcpServer/elicitation/request': {
+ if (p.serverName === 'chums') return { action: 'accept', content: {}, _meta: null }
+ const ok = await card(p.serverName, short(p.message, 160), { url: p.url, description: p.message })
+ return { action: ok === 'allow' ? 'accept' : 'decline', content: ok === 'allow' ? {} : null, _meta: null }
+ }
+ case 'item/tool/requestUserInput': {
+ // a question: said on the watch, and what's said next is the answer
+ this.hub.reply(this.s, spokenLine(p.questions?.map(q => q.question).join(' ')) || 'A question for you.', 'question')
+ const said = await new Promise(r => { this.answerNext = r })
+ return { answers: Object.fromEntries((p.questions ?? []).map(q => [q.id, { answers: [said] }])) }
+ }
+ }
+ throw Object.assign(new Error(`${method} isn't offered`), { code: -32601 })
+ }
+}
+
+/// Starts one agent the hub runs (null for a runtime it doesn't know).
+export function startRunner(a, hub) {
+ if (!RUNTIMES.includes(a.runtime) || !runByHub(a)) { hub.log(`${a.id}: unknown runtime ${a.runtime} (one of ${RUNTIMES.join(', ')})`); return null }
+ const r = new { codex: CodexRunner, copilot: CopilotRunner, acp: AcpRunner }[a.runtime](a, hub)
+ r.start()
+ return r
+}
+
+/// Starts every agent the hub runs; returns them by agent id.
+export function startRunners(agents, hub) {
+ const runners = new Map()
+ for (const a of agents.filter(runByHub)) { const r = startRunner(a, hub); if (r) runners.set(a.id, r) }
+ return runners
+}
diff --git a/hub/standing.mjs b/hub/standing.mjs
new file mode 100644
index 0000000..d546732
--- /dev/null
+++ b/hub/standing.mjs
@@ -0,0 +1,45 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+// What every agent is told once and keeps (whatever runs it): that its soul comes with its owner's orders, and how to use
+// its tools. Claude Code gets it with --append-system-prompt (tools/agent-cmd.mjs); Codex as developer instructions;
+// an Agent Client Protocol agent at the top of the first order of each run. Who it is lives in its soul.
+
+export const MAX_WORDS = 15 // a chums_reply longer than this is refused (the watch)
+export const PHONE_WORDS = 60 // to a message from the iPhone, which shows the text: a few sentences
+/// The mark an order carries, by where it was said.
+export const markFor = device => device === 'phone' ? '[From the iPhone]' : '[From the watch]'
+/// The longest chums_reply to an order from this device.
+export const wordsFor = device => device === 'phone' ? PHONE_WORDS : MAX_WORDS
+
+/// Who the agents work for, as they should call them: `ownerName` in ~/.chums/config.json (e.g. "Sam"), else "the user".
+export const OWNER = (() => {
+ try { return JSON.parse(fs.readFileSync(path.join(os.homedir(), '.chums', 'config.json'), 'utf8')).ownerName || 'the user' } catch { return 'the user' }
+})()
+/// The same, to start a sentence with.
+export const Owner = OWNER[0].toUpperCase() + OWNER.slice(1)
+
+/// How to make a page that shows well: it runs on the iPhone, and the watch shows a picture of it.
+export const PAGE_GUIDE = 'For a chart, a table to explore or anything visual, make one HTML file and show it. It runs on the iPhone, ' +
+ 'its scripts, animations and touch included; the watch shows a picture of it once it has loaded and its animations have ended. ' +
+ 'Make it for a phone: the screen\'s width (a viewport meta tag, no fixed width), a black background with light text, large ' +
+ 'numbers, things to tap or drag instead of hover. ' +
+ 'Put its CSS, data and pictures in the file, since the iPhone gets only that file; a library such as Chart.js or D3 can load from ' +
+ 'a CDN by its https address.'
+
+export function standingFor(a) {
+ return `You are one of ${OWNER}'s agents (id: ${a.id}). Who you are (your name, what you look after, what you refer to the other agents, your voice) is your soul, which the hub sends with ${OWNER}'s orders as a versioned snapshot; the latest one replaces anything said earlier about who you are, here included. Only ${OWNER} changes it, from the watch: don't edit ~/.chums/souls yourself. ${Owner} talks to you from an Apple Watch: reply there with chums_reply, show things with chums_show. ${a.guide ?? ''}`.trim()
+}
+
+/// The watch's rules, for agents that don't load the Chums channel (its MCP instructions say the same to Claude Code).
+export const WATCH_GUIDE = [
+ `Messages marked [From the watch] are voice transcripts from the Apple Watch ${OWNER} carries, often away from the desk: expect recognition errors and read for intent, and do the work as if it had been typed.`,
+ `When you finish work ${OWNER} asked for from the watch, or you need ${OWNER}, call the chums_reply tool once: one short spoken sentence, like a text message, about 8 words and`,
+ `${MAX_WORDS} at most (the tool refuses longer). Result first, plain words, no preamble, no code, file paths, URLs, markdown or lists: it is read aloud.`,
+ "Set status 'done' when finished, 'question' when you need an answer, 'blocked' when you cannot continue.",
+ 'If there is more to say, it stays on the Mac: say "Details on your Mac." If the chums tools are missing, make your final message that one short sentence instead.',
+ `When ${OWNER} asks to see something (the screen, an app, a web page, or a file: a page, a document, a PDF, text or code, a table, an image or a video), call chums_show instead of chums_reply.`,
+ `Messages marked [From the iPhone] come from the Chums iPhone app, which shows your reply as text (and may read it aloud): answer with chums_reply in plain sentences, ${PHONE_WORDS} words at most, giving the answer itself rather than "Details on your Mac"; still no code, file paths, URLs, markdown or lists.`,
+ 'Never start replies with a name or give yourself one. Messages without a mark were typed on the Mac: answer those normally, not with chums_reply.',
+].join(' ')
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..043c8d1
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,1215 @@
+{
+ "name": "chums",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "chums",
+ "version": "0.1.0",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.20.0",
+ "zod": "^3.25.0"
+ },
+ "engines": {
+ "node": ">=20.11"
+ },
+ "peerDependencies": {
+ "@github/copilot-sdk": "^1.0.19"
+ },
+ "peerDependenciesMeta": {
+ "@github/copilot-sdk": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@hono/node-server": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.1.tgz",
+ "integrity": "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ },
+ "peerDependencies": {
+ "hono": "^4"
+ }
+ },
+ "node_modules/@modelcontextprotocol/sdk": {
+ "version": "1.31.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.31.0.tgz",
+ "integrity": "sha512-UvTMgnNlnIBO/22ob2RcVGDlcvOslQs8T59+FTGdA0L27a39fdGF/EDETNtDVK4DZGpwomlsYpRdA8UXcVL/pw==",
+ "license": "MIT",
+ "dependencies": {
+ "@hono/node-server": "^1.19.9 || ^2.0.5",
+ "ajv": "^8.17.1",
+ "ajv-formats": "^3.0.1",
+ "content-type": "^1.0.5",
+ "cors": "^2.8.5",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.0",
+ "express": "^5.2.1",
+ "express-rate-limit": "^8.2.1",
+ "hono": "^4.11.4",
+ "jose": "^6.1.3",
+ "json-schema-typed": "^8.0.2",
+ "pkce-challenge": "^5.0.0",
+ "raw-body": "^3.0.0",
+ "zod": "^3.25 || ^4.0",
+ "zod-to-json-schema": "^3.25.1"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@cfworker/json-schema": "^4.1.1",
+ "zod": "^3.25 || ^4.0"
+ },
+ "peerDependenciesMeta": {
+ "@cfworker/json-schema": {
+ "optional": true
+ },
+ "zod": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/accepts": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-types": "^3.0.0",
+ "negotiator": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/ajv": {
+ "version": "8.20.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/ajv-formats": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "ajv": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/body-parser": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
+ "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "^3.1.2",
+ "content-type": "^2.0.0",
+ "debug": "^4.4.3",
+ "http-errors": "^2.0.1",
+ "iconv-lite": "^0.7.2",
+ "on-finished": "^2.4.1",
+ "qs": "^6.15.2",
+ "raw-body": "^3.0.2",
+ "type-is": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/body-parser/node_modules/content-type": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/bytes": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/content-disposition": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/content-type": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie-signature": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.6.0"
+ }
+ },
+ "node_modules/cors": {
+ "version": "2.8.6",
+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
+ "license": "MIT",
+ "dependencies": {
+ "object-assign": "^4",
+ "vary": "^1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/depd": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+ "license": "MIT"
+ },
+ "node_modules/encodeurl": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "license": "MIT"
+ },
+ "node_modules/etag": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/eventsource": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+ "license": "MIT",
+ "dependencies": {
+ "eventsource-parser": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/eventsource-parser": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/express": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
+ "license": "MIT",
+ "dependencies": {
+ "accepts": "^2.0.0",
+ "body-parser": "^2.2.1",
+ "content-disposition": "^1.0.0",
+ "content-type": "^1.0.5",
+ "cookie": "^0.7.1",
+ "cookie-signature": "^1.2.1",
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "finalhandler": "^2.1.0",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.0",
+ "merge-descriptors": "^2.0.0",
+ "mime-types": "^3.0.0",
+ "on-finished": "^2.4.1",
+ "once": "^1.4.0",
+ "parseurl": "^1.3.3",
+ "proxy-addr": "^2.0.7",
+ "qs": "^6.14.0",
+ "range-parser": "^1.2.1",
+ "router": "^2.2.0",
+ "send": "^1.1.0",
+ "serve-static": "^2.2.0",
+ "statuses": "^2.0.1",
+ "type-is": "^2.0.1",
+ "vary": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/express-rate-limit": {
+ "version": "8.7.0",
+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.0.tgz",
+ "integrity": "sha512-hOwV7WOxXfjRpAM1DSJWZDXx3GhplwD8IfwuwvogD8i1Qnkgosw/H45s4ZnFAUHDAhPjlY9hLBvJhKmGMyY26g==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "ip-address": "^10.2.0"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/express-rate-limit"
+ },
+ "peerDependencies": {
+ "express": ">= 4.11"
+ }
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "license": "MIT"
+ },
+ "node_modules/fast-uri": {
+ "version": "3.1.8",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
+ "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/finalhandler": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "on-finished": "^2.4.1",
+ "parseurl": "^1.3.3",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/forwarded": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/fresh": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/hono": {
+ "version": "4.13.10",
+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.10.tgz",
+ "integrity": "sha512-dQuLsa5oO+47QVMVMaaD9cIv8ctmVtK1iRvwWngkfloFJMeFeuoUFDswIqZGxmGX3hrRzREgEArjkK9OgsQEhA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.9.0"
+ }
+ },
+ "node_modules/http-errors": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
+ "license": "MIT",
+ "dependencies": {
+ "depd": "~2.0.0",
+ "inherits": "~2.0.4",
+ "setprototypeof": "~1.2.0",
+ "statuses": "~2.0.2",
+ "toidentifier": "~1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.7.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
+ "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
+ "node_modules/ip-address": {
+ "version": "10.7.2",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.2.tgz",
+ "integrity": "sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/ipaddr.js": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/is-promise": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+ "license": "MIT"
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "license": "ISC"
+ },
+ "node_modules/jose": {
+ "version": "6.2.12",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz",
+ "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
+ "node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
+ "node_modules/json-schema-typed": {
+ "version": "8.0.2",
+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",
+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/media-typer": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz",
+ "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/merge-descriptors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/negotiator": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz",
+ "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==",
+ "license": "MIT",
+ "dependencies": {
+ "content-type": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/negotiator/node_modules/content-type": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/object-inspect": {
+ "version": "1.13.4",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "license": "MIT",
+ "dependencies": {
+ "ee-first": "1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/path-to-regexp": {
+ "version": "8.4.2",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/pkce-challenge": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/proxy-addr": {
+ "version": "2.0.8",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
+ "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
+ "license": "MIT",
+ "dependencies": {
+ "forwarded": "0.2.0",
+ "ipaddr.js": "1.9.1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/qs": {
+ "version": "6.16.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
+ "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "es-define-property": "^1.0.1",
+ "side-channel": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/range-parser": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
+ "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/raw-body": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "~3.1.2",
+ "http-errors": "~2.0.1",
+ "iconv-lite": "~0.7.0",
+ "unpipe": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/router": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "is-promise": "^4.0.0",
+ "parseurl": "^1.3.3",
+ "path-to-regexp": "^8.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
+ "node_modules/send": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.1",
+ "mime-types": "^3.0.2",
+ "ms": "^2.1.3",
+ "on-finished": "^2.4.1",
+ "range-parser": "^1.2.1",
+ "statuses": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/serve-static": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
+ "license": "MIT",
+ "dependencies": {
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "parseurl": "^1.3.3",
+ "send": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/setprototypeof": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+ "license": "ISC"
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/side-channel": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.4",
+ "side-channel-list": "^1.0.1",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/statuses": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/toidentifier": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/type-is": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
+ "license": "MIT",
+ "dependencies": {
+ "content-type": "^2.0.0",
+ "media-typer": "^1.1.0",
+ "mime-types": "^3.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/type-is/node_modules/content-type": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/unpipe": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ },
+ "node_modules/zod": {
+ "version": "3.25.76",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
+ "node_modules/zod-to-json-schema": {
+ "version": "3.25.2",
+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
+ "license": "ISC",
+ "peerDependencies": {
+ "zod": "^3.25.28 || ^4"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..627477a
--- /dev/null
+++ b/package.json
@@ -0,0 +1,35 @@
+{
+ "name": "chums",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "description": "An Apple Watch and iPhone app for talking to the coding agents on your Mac (Claude Code and Codex), and its hub",
+ "scripts": {
+ "hub": "node hub/hub.mjs",
+ "test": "node tools/test-channel.mjs && CHUMS_TEST_NO_MODEL=1 node tools/test-hub.mjs && node tools/test-artifacts.mjs && node tools/test-runtimes.mjs"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.20.0",
+ "zod": "^3.25.0"
+ },
+ "peerDependencies": {
+ "@github/copilot-sdk": "^1.0.19"
+ },
+ "peerDependenciesMeta": {
+ "@github/copilot-sdk": {
+ "optional": true
+ }
+ },
+ "engines": {
+ "node": ">=20.11"
+ },
+ "license": "Apache-2.0",
+ "homepage": "https://chums.club",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/lcoutodemos/chums.git"
+ },
+ "bugs": {
+ "url": "https://github.com/lcoutodemos/chums/issues"
+ }
+}
diff --git a/tools/agent-cmd.mjs b/tools/agent-cmd.mjs
new file mode 100644
index 0000000..eab630d
--- /dev/null
+++ b/tools/agent-cmd.mjs
@@ -0,0 +1,45 @@
+// The command that starts one agent's Claude Code session (tools/agent-host.exp runs it): its folder on the first line,
+// then one argument per line. The agent's own folder gets a CLAUDE.md with its role. Exits 3 (and prints why) when
+// that thread is already running somewhere: one process per thread, always.
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { execFileSync } from 'node:child_process'
+import { standingFor } from '../hub/standing.mjs'
+
+const HOME = os.homedir(), ROOT = path.join(import.meta.dirname, '..')
+const id = process.argv[2]
+const a = JSON.parse(fs.readFileSync(path.join(HOME, '.chums/agents.json'), 'utf8')).find(x => x.id === id)
+if (!a) { console.error(`no agent ${id} in ~/.chums/agents.json`); process.exit(2) }
+// Codex, Copilot and other Agent Client Protocol agents run inside the hub (hub/runtimes.mjs), not in a terminal
+if (a.runtime && a.runtime !== 'claude') { console.error(`${id} runs on ${a.runtime}, inside the hub: no Claude Code session to start`); process.exit(2) }
+if (!a.sessionId || !a.cwd) { console.error(`${id} has no ${a.cwd ? 'sessionId' : 'cwd'} in ~/.chums/agents.json: restart the hub, which fills it in`); process.exit(2) }
+
+let running = ''
+try { running = execFileSync('/usr/bin/pgrep', ['-f', a.sessionId], { encoding: 'utf8' }).trim() } catch {}
+if (running) { console.error(`${id}'s thread is already running (pid ${running.split('\n').join(', ')})`); process.exit(3) }
+
+fs.mkdirSync(a.cwd, { recursive: true })
+// what stays fixed: that its soul comes with its owner's orders, and how to use its tools. Who it is lives in its soul
+// (~/.chums/souls/<id>.md), which the owner shapes from the watch; the hub sends it with the next order after any change.
+const standing = standingFor(a)
+if (a.cwd.startsWith(path.join(HOME, '.chums/agents'))) fs.writeFileSync(path.join(a.cwd, 'CLAUDE.md'), `# Agent ${a.id}\n\n${standing}\n`)
+// Claude Code keeps a folder's threads in ~/.claude/projects/<the folder, every other character a dash>
+const thread = path.join(HOME, '.claude/projects', a.cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${a.sessionId}.jsonl`)
+// how it asks before acting (default, acceptEdits, auto…), set from the watch and the iPhone; without one, the
+// defaultMode in ~/.claude/settings.json, which applies only to new sessions on its own, passed for a resumed one too
+let mode = a.permissionMode
+try { mode ??= JSON.parse(fs.readFileSync(path.join(HOME, '.claude/settings.json'), 'utf8')).permissions?.defaultMode } catch {}
+const args = [
+ '/usr/bin/env', `CHUMS_NAME=${a.id}`, `HOME=${HOME}`,
+ // ~/.local/bin: Claude Code's native installer; ~/.npm-global/bin: an npm prefix install (a LaunchAgent has no shell PATH)
+ `PATH=${path.dirname(process.execPath)}:${HOME}/.local/bin:${HOME}/.npm-global/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
+ path.join(ROOT, 'bin/chums-claude'), a.id,
+ fs.existsSync(thread) ? '--resume' : '--session-id', a.sessionId,
+ '--append-system-prompt', standing,
+ ...(a.addDirs ?? []).flatMap(d => ['--add-dir', d]),
+ ...(a.model ? ['--model', a.model] : []),
+ // a flag, so it holds when the session is resumed too
+ ...(typeof mode === 'string' && mode ? ['--permission-mode', mode] : []),
+]
+console.log([a.cwd, ...args].join('\n'))
diff --git a/tools/agent-host.exp b/tools/agent-host.exp
new file mode 100755
index 0000000..5809780
--- /dev/null
+++ b/tools/agent-host.exp
@@ -0,0 +1,37 @@
+#!/usr/bin/expect -f
+# One agent's Claude Code session, run with no terminal window (its LaunchAgent starts this; bin/chums-agents installs
+# them). It gives the session a 120 × 40 terminal of its own, answers the two start-up screens it knows (trusting the
+# agent's own folder, confirming the development channel) and nothing else, then waits until the session ends;
+# launchd starts it again. Notes go to ~/.chums/agents/<id>.host.log.
+set id [lindex $argv 0]
+set root [file dirname [file dirname [file normalize [info script]]]]
+file mkdir "$env(HOME)/.chums/agents"
+set logf [open "$env(HOME)/.chums/agents/$id.host.log" a]
+proc note {msg} { global logf; puts $logf "[clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] $msg"; flush $logf }
+
+# node: the one bin/chums-agents found (CHUMS_NODE in the LaunchAgent), else Homebrew's (Apple silicon, then Intel)
+set node [expr {[info exists env(CHUMS_NODE)] && $env(CHUMS_NODE) ne "" ? $env(CHUMS_NODE)
+ : [file executable /opt/homebrew/bin/node] ? "/opt/homebrew/bin/node" : "/usr/local/bin/node"}]
+if {[catch {exec $node "$root/tools/agent-cmd.mjs" $id} out]} { note "not started: $out"; sleep 30; exit 0 }
+set lines [split $out "\n"]
+cd [lindex $lines 0]
+log_user 0
+match_max 20000
+spawn -noecho {*}[lrange $lines 1 end]
+stty rows 40 columns 120 < $spawn_out(slave,name)
+note "started (pid [exp_pid])"
+
+# the start-up screens, only these and only in its first minute; words on screen are drawn with cursor moves between them
+set deadline [expr {[clock seconds] + 60}]
+set ready 0
+while {!$ready && [clock seconds] < $deadline} {
+ expect {
+ -re {trust\S{0,12}this\S{0,12}folder} { sleep 1.5; send "\r"; note "trusted its folder" }
+ -re {local\S{0,12}development} { sleep 1.5; send "\r"; note "confirmed the development channel"; set ready 1 }
+ timeout {}
+ eof { note "ended while starting"; exit 0 }
+ }
+}
+note [expr {$ready ? "running" : "running (no development-channel screen seen in its first minute)"}]
+expect -timeout -1 eof
+note "ended"
diff --git a/tools/agents.example.json b/tools/agents.example.json
new file mode 100644
index 0000000..bb53591
--- /dev/null
+++ b/tools/agents.example.json
@@ -0,0 +1,35 @@
+[
+ {
+ "id": "noodle",
+ "name": "Noodle",
+ "character": "noodle",
+ "runtime": "claude",
+ "cwd": "/Users/you/Developer/chums",
+ "addDirs": [
+ "/Users/you/Developer"
+ ],
+ "guide": ""
+ },
+ {
+ "id": "squint",
+ "name": "Squint",
+ "character": "squint",
+ "runtime": "claude",
+ "cwd": "/Users/you/.chums/agents/squint",
+ "addDirs": [
+ "/Users/you"
+ ],
+ "guide": "To see an app or a page, use chums_show with screenshot (and open: a URL to open it in Safari first). To read or click inside a page you're logged in to, run JavaScript in Safari with osascript (Safari's do JavaScript; it needs Develop › Allow JavaScript from Apple Events)."
+ },
+ {
+ "id": "ray",
+ "name": "Ray",
+ "character": "ray",
+ "runtime": "codex",
+ "cwd": "/Users/you/Developer",
+ "addDirs": [
+ "/Users/you"
+ ],
+ "model": "gpt-6-astra"
+ }
+]
diff --git a/tools/common.zsh b/tools/common.zsh
new file mode 100644
index 0000000..9430083
--- /dev/null
+++ b/tools/common.zsh
@@ -0,0 +1,67 @@
+# Shared by the bin/ scripts: where things are, and the per-machine settings that used to be hardcoded.
+# Each setting comes from an environment variable, else from ~/.chums/config.json, else a default:
+# CHUMS_BUNDLE config "bundleId" the app's bundle ID (the watch app is <it>.watchkitapp)
+# CHUMS_TEAM config "team" the Apple developer team to sign with (else tools/pick-team.py picks)
+# CHUMS_LABEL_PREFIX config "launchdPrefix" LaunchAgent labels: <prefix>.hub, <prefix>.tailscaled, <prefix>.agent.<id>
+# CHUMS_NODE config "node" the node binary LaunchAgents run (they don't get your shell's PATH)
+# Usage: source "${0:A:h:h}/tools/common.zsh"
+
+CHUMS_ROOT="${${(%):-%x}:A:h:h}"
+CHUMS_HOME=~/.chums
+CHUMS_CONFIG=$CHUMS_HOME/config.json
+
+# chums_cfg <key>: a value from ~/.chums/config.json, or nothing
+chums_cfg() {
+ [[ -f $CHUMS_CONFIG ]] || return 0
+ python3 -c 'import json,sys
+try: v = json.load(open(sys.argv[1])).get(sys.argv[2])
+except Exception: v = None
+print("" if v is None else v)' "$CHUMS_CONFIG" "$1"
+}
+
+: ${CHUMS_LABEL_PREFIX:=$(chums_cfg launchdPrefix)}
+: ${CHUMS_LABEL_PREFIX:=dev.chums}
+: ${CHUMS_NODE:=$(chums_cfg node)}
+: ${CHUMS_NODE:=$(command -v node)}
+
+# chums_die <message…>: print to stderr and stop
+chums_die() { print -u2 -- "chums: $*"; exit 1 }
+
+# chums_help "$@": with -h or --help, print the script's opening comment (what it does, its usage) and stop
+chums_help() {
+ [[ ${1:-} == (-h|--help) ]] || return 0
+ awk 'NR == 1 { next } /^#/ { sub(/^# ?/, ""); print; next } { exit }' "$ZSH_ARGZERO"
+ exit 0
+}
+
+# chums_need <command> <how to get it>: stop with a clear message when a command is missing
+chums_need() { command -v "$1" >/dev/null 2>&1 || chums_die "$1 is not installed. $2" }
+
+# chums_sim_udid [name]: the UDID of the watch simulator bin/chums-sim made ("Chums Watch"), or nothing
+chums_sim_udid() {
+ DEVELOPER_DIR=${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer} xcrun simctl list devices -j 2>/dev/null |
+ python3 -c 'import json,sys
+try: devices = json.load(sys.stdin)["devices"].values()
+except Exception: raise SystemExit
+for devs in devices:
+ for d in devs:
+ if d["name"] == sys.argv[1] and d["isAvailable"]: print(d["udid"]); raise SystemExit' "${1:-Chums Watch}"
+}
+
+# chums_sim_app: the watch app's bundle ID in the Simulator (what bin/chums-sim installs)
+chums_sim_app() { local b=${CHUMS_BUNDLE:-$(chums_cfg bundleId)}; echo "${b:-dev.chums}.watchkitapp" }
+
+# chums_need_config: stop unless the hub has written ~/.chums/config.json (it does on its first start)
+chums_need_config() {
+ [[ -f $CHUMS_CONFIG ]] || chums_die "no $CHUMS_CONFIG yet. Start the hub once (bin/chums-hub), then run this again."
+}
+
+# chums_reload <label> <plist>: stop a LaunchAgent and start it again from its plist. launchctl bootout returns before
+# the job is gone, and a bootstrap too soon fails ("Bootstrap failed: 5: Input/output error"), so wait, and retry.
+chums_reload() {
+ local d=gui/$(id -u) i
+ launchctl bootout $d/$1 2>/dev/null
+ for i in {1..20}; do launchctl print $d/$1 >/dev/null 2>&1 || break; sleep 0.25; done
+ for i in {1..4}; do launchctl bootstrap $d "$2" 2>/dev/null && return 0; sleep 1; done
+ launchctl bootstrap $d "$2"
+}
diff --git a/tools/demo-session.py b/tools/demo-session.py
new file mode 100644
index 0000000..dc89016
--- /dev/null
+++ b/tools/demo-session.py
@@ -0,0 +1,46 @@
+"""Start a real chums-claude session in a pty and keep it alive (for demos and simulator testing).
+Usage: python3 tools/demo-session.py <workdir> <name> [minutes] [extra claude args...]"""
+import json, os, pty, re, select, sys, time, urllib.request
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+WORK, NAME = sys.argv[1], sys.argv[2]
+MINUTES = float(sys.argv[3]) if len(sys.argv) > 3 else 20
+EXTRA = " ".join(sys.argv[4:])
+os.makedirs(WORK, exist_ok=True)
+cfg = json.load(open(os.path.expanduser("~/.chums/config.json")))
+
+def sessions():
+ req = urllib.request.Request(f"http://127.0.0.1:{cfg['port']}/v1/state?since=0",
+ headers={"authorization": f"Bearer {cfg['token']}"})
+ return json.load(urllib.request.urlopen(req, timeout=10))["sessions"]
+
+before = {s["id"] for s in sessions()}
+pid, fd = pty.fork()
+if pid == 0:
+ os.chdir(WORK)
+ os.environ.update(CHUMS_NO_RC="1", TERM="xterm-256color")
+ os.execvp("zsh", ["zsh", "-c", f"{ROOT}/bin/chums-claude {NAME} {EXTRA}"])
+
+screen = ""
+def pump(sec):
+ global screen
+ end = time.time() + sec
+ while time.time() < end:
+ if select.select([fd], [], [], 0.2)[0]:
+ try: screen = (screen + os.read(fd, 65536).decode(errors="ignore"))[-20000:]
+ except OSError: sys.exit(0)
+
+plain = lambda s: re.sub(r"\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07]*\x07", "", s).replace(" ", "").lower()
+done = set()
+for _ in range(60):
+ pump(1)
+ tail = plain(screen)[-1500:]
+ if "itrustthisfolder" in tail and "trust" not in done:
+ done.add("trust"); os.write(fd, b"\x1b[B"); pump(0.3); os.write(fd, b"\r"); screen = ""
+ elif "loadingdevelopmentchannels" in tail and "entertoconfirm" in tail and "dev" not in done:
+ done.add("dev"); os.write(fd, b"\r"); screen = ""
+ if any(s["name"] == NAME and s["id"] not in before for s in sessions()):
+ break
+print(f"session {NAME} ready", flush=True)
+pump(MINUTES * 60)
+os.write(fd, b"\x03"); pump(0.5); os.write(fd, b"\x03")
diff --git a/tools/doctor.py b/tools/doctor.py
new file mode 100644
index 0000000..00099d4
--- /dev/null
+++ b/tools/doctor.py
@@ -0,0 +1,593 @@
+"""Checks the whole Chums chain on this Mac and prints a pass/fail list, with the fix for each failure.
+
+Run it as bin/chums-doctor. It is read-only: it starts, stops, writes and installs nothing. What it does:
+ - runs version and sign-in checks (`claude auth status`, `codex login status`, `xcodebuild -version`, ...);
+ - reads ~/.chums/config.json and ~/.chums/agents.json;
+ - asks the hub for /v1/ping and /v1/state on 127.0.0.1, and the Funnel URL for /v1/ping over HTTPS;
+ - asks Chums' own tailscaled for its status, and Xcode (`xcrun devicectl list devices`) which devices it knows.
+The tokens in ~/.chums/config.json go only to your own hub and your own Funnel URL, and are never printed.
+Exit code: 0 when nothing failed, 1 otherwise. NO_COLOR=1 turns colours off.
+"""
+import ipaddress, json, os, platform, re, shutil, socket, subprocess, sys, tempfile, time
+import urllib.error, urllib.request
+
+if {'-h', '--help'} & set(sys.argv[1:]):
+ print(__doc__.strip()); sys.exit(0)
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+HOME = os.path.expanduser('~')
+CHUMS = os.path.join(HOME, '.chums')
+CONFIG = os.path.join(CHUMS, 'config.json')
+AGENTS = os.path.join(CHUMS, 'agents.json')
+TS_SOCK = os.path.join(CHUMS, 'tailscale', 'tailscaled.sock')
+DEV = os.environ.get('DEVELOPER_DIR') or '/Applications/Xcode.app/Contents/Developer'
+MODEL = os.environ.get('CHUMS_WHISPER_MODEL') or os.path.join(
+ HOME, 'Documents/huggingface/models/argmaxinc/whisperkit-coreml/openai_whisper-base')
+WHISPER_PORT = 50061
+KOKORO_PORT = 50062
+HUBCONFIG = os.path.join(ROOT, 'app/ChumsWatch/HubConfig.swift')
+# where installers put the CLIs, for when they aren't on this shell's PATH
+EXTRA_BIN = [os.path.join(HOME, '.local/bin'), os.path.join(HOME, '.npm-global/bin'), '/opt/homebrew/bin', '/usr/local/bin']
+
+COLOR = sys.stdout.isatty() and not os.environ.get('NO_COLOR')
+TAGS = {'PASS': '32', 'WARN': '33', 'FAIL': '31'}
+count = {'PASS': 0, 'WARN': 0, 'FAIL': 0}
+
+
+def report(kind, what, fix=None):
+ count[kind] += 1
+ tag = f'\033[{TAGS[kind]}m{kind}\033[0m' if COLOR else kind
+ print(f' {tag} {what}')
+ fixes = [fix] if isinstance(fix, str) else list(fix or [])
+ for i, line in enumerate(fixes):
+ print((' fix: ' if i == 0 else ' ') + line)
+
+
+def ok(what): report('PASS', what)
+def warn(what, fix=None): report('WARN', what, fix)
+def fail(what, fix=None): report('FAIL', what, fix)
+def note(what): print(f' -- {what}')
+
+
+def section(title):
+ print(f'\n{title}')
+
+
+def run(cmd, timeout=20, stdin='', env=None):
+ """(exit code, stdout, stderr); 127 when the command is missing, 124 on a timeout."""
+ # the usual install folders go on PATH too, as the hub gives them to the agents it runs (npm CLIs need node)
+ path = ':'.join([os.environ.get('PATH', '')] + EXTRA_BIN)
+ try:
+ p = subprocess.run(cmd, input=stdin, capture_output=True, text=True, timeout=timeout,
+ env=dict(os.environ, PATH=path, **(env or {})))
+ return p.returncode, p.stdout.strip(), p.stderr.strip()
+ except FileNotFoundError:
+ return 127, '', f'{cmd[0]}: not found'
+ except subprocess.TimeoutExpired:
+ return 124, '', f'{cmd[0]}: no answer in {timeout} s'
+
+
+def version(text):
+ m = re.search(r'(\d+)\.(\d+)(?:\.(\d+))?', text or '')
+ return tuple(int(x or 0) for x in m.groups()) if m else None
+
+
+def vstr(v): return '.'.join(map(str, v[:2] if len(v) > 2 and v[2] == 0 else v))
+
+
+def find(name, extra=()):
+ """(path, on PATH?) for a command, looking in the usual install folders too."""
+ p = shutil.which(name)
+ if p: return p, True
+ for d in list(extra) + EXTRA_BIN:
+ c = os.path.join(d, name)
+ if os.access(c, os.X_OK): return c, False
+ return None, False
+
+
+def read_json(path):
+ with open(path, encoding='utf-8') as f: return json.load(f)
+
+
+def http(url, token, timeout=4):
+ """(status, parsed JSON or None, error) for a GET to the hub on this Mac. No proxies."""
+ req = urllib.request.Request(url, headers={'Authorization': f'Bearer {token}'})
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ try:
+ with opener.open(req, timeout=timeout) as r:
+ body = r.read()
+ try: return r.status, json.loads(body), None
+ except ValueError: return r.status, None, None
+ except urllib.error.HTTPError as e:
+ return e.code, None, None
+ except (urllib.error.URLError, socket.timeout, ConnectionError, OSError) as e:
+ return None, None, str(getattr(e, 'reason', e))
+
+
+def port_open(port, host='localhost'): # whisperkit-cli serve listens on ::1
+ try:
+ with socket.create_connection((host, port), timeout=1): return True
+ except OSError: return False
+
+
+def launchd_loaded(label):
+ return run(['launchctl', 'print', f'gui/{os.getuid()}/{label}'], timeout=5)[0] == 0
+
+
+# ------------------------------------------------------------------------------------------------------------------
+cfg, agents, hub_up, team_kind = None, None, False, None
+label_prefix = os.environ.get('CHUMS_LABEL_PREFIX')
+
+print('Chums doctor: read-only checks of everything Chums needs. Nothing is changed.')
+print(f'checkout: {ROOT}')
+
+# ---------- the settings first: later checks depend on them ----------
+config_problem = None
+if os.path.isfile(CONFIG):
+ try: cfg = read_json(CONFIG)
+ except ValueError as e: config_problem = str(e)
+agents_problem = None
+if os.path.isfile(AGENTS):
+ try: agents = read_json(AGENTS)
+ except ValueError as e: agents_problem = str(e)
+label_prefix = label_prefix or (cfg or {}).get('launchdPrefix') or 'dev.chums'
+runtimes = [(a.get('runtime') or 'claude') for a in agents if isinstance(a, dict)] if isinstance(agents, list) else []
+need_claude = not runtimes or 'claude' in runtimes
+need_codex = 'codex' in runtimes
+
+# ---------- 1. this Mac ----------
+section('1. This Mac')
+mac = version(platform.mac_ver()[0])
+arm = run(['sysctl', '-n', 'hw.optional.arm64'], timeout=5)[1] == '1'
+if mac and mac >= (15, 6):
+ (ok if arm else warn)(f'macOS {vstr(mac)} on {"Apple silicon" if arm else "an Intel Mac"}'
+ + ('' if arm else ': Chums is made for Apple silicon Macs and is untested on Intel'))
+else:
+ fail(f'macOS {vstr(mac) if mac else "?"}: Xcode 26 needs macOS 15.6 or later', 'System Settings › General › Software Update')
+ok(f'python3 {platform.python_version()}')
+
+node = os.environ.get('CHUMS_NODE') or (cfg or {}).get('node') or find('node')[0]
+if node and os.access(node, os.X_OK):
+ nv = version(run([node, '-p', 'process.versions.node'], timeout=10)[1])
+ if nv and nv >= (20, 11): ok(f'Node.js {vstr(nv)} ({node})')
+ else: fail(f'Node.js {vstr(nv) if nv else "?"} is too old: Chums needs 20.11 or later', 'brew install node')
+else:
+ fail('Node.js is not installed (the hub and the channel run on it)', 'brew install node')
+
+if all(os.path.isdir(os.path.join(ROOT, 'node_modules', p)) for p in ('@modelcontextprotocol/sdk', 'zod')):
+ ok('npm packages installed')
+else:
+ fail('npm packages are not installed in this checkout', 'bin/chums-setup (it runs npm ci)')
+
+wk = find('whisperkit-cli')[0]
+if wk: ok(f'whisperkit-cli ({wk})')
+else: fail('whisperkit-cli is not installed (speech to text on the Mac)', 'brew install whisperkit-cli')
+if os.path.isfile(os.path.join(MODEL, 'config.json')) or os.path.isdir(os.path.join(MODEL, 'AudioEncoder.mlmodelc')):
+ ok('Whisper base model downloaded')
+else:
+ fail(f'Whisper model not found at {MODEL}',
+ ['bin/chums-setup downloads it (about 150 MB)', 'or set CHUMS_WHISPER_MODEL to the folder of a model you have'])
+
+ff = find('ffmpeg')[0]
+if ff: ok(f'ffmpeg ({ff})')
+else: fail('ffmpeg is not installed (the hub converts each clip with it before transcribing)', 'brew install ffmpeg')
+
+ts, ts_on_path = find('tailscale')
+tsd = find('tailscaled')[0]
+if ts and tsd:
+ tv = version(run([ts, 'version'], timeout=10)[1])
+ if tv and tv < (1, 52): fail(f'Tailscale {vstr(tv)} is too old: bin/chums-tunnel needs 1.52 or later', 'brew upgrade tailscale')
+ else: ok(f'Tailscale {vstr(tv) if tv else ""} (tailscale and tailscaled)')
+elif ts:
+ fail('tailscaled is missing: Chums runs its own tailscaled, which the App Store and standalone Tailscale apps '
+ "don't include", 'brew install tailscale')
+else:
+ fail('Tailscale is not installed (it puts the watch API on the internet)', 'brew install tailscale')
+
+if os.access('/usr/bin/expect', os.X_OK): ok('expect (runs background Claude Code agents)')
+else: warn('/usr/bin/expect is missing: only bin/chums-agents needs it')
+if not find('brew')[0]: note('Homebrew is not installed; the install commands below use it (https://brew.sh)')
+
+# ---------- 2. the agents' CLIs ----------
+section('2. Coding agents')
+claude, claude_on_path = find('claude', [os.path.dirname(os.environ['CHUMS_CLAUDE_BIN'])] if os.environ.get('CHUMS_CLAUDE_BIN') else [])
+if claude:
+ cv = run([claude, '--version'], timeout=20)[1].split('\n')[0].replace(' (Claude Code)', '')
+ # only when this version has `claude auth`: an older one would read "auth status" as a prompt
+ auth = None
+ if re.search(r'^\s+auth\b', run([claude, '--help'], timeout=20)[1], re.M):
+ try: auth = json.loads(run([claude, 'auth', 'status', '--json'], timeout=30)[1])
+ except ValueError: pass
+ where = '' if claude_on_path else f' (at {claude}, not on PATH)'
+ if auth is None:
+ warn(f'Claude Code {cv}{where}: could not check its sign-in (claude auth status needs a newer Claude Code)',
+ 'claude update')
+ elif auth.get('loggedIn'):
+ method = auth.get('authMethod') or 'signed in'
+ ok(f'Claude Code {cv}, signed in ({method}){where}')
+ if method != 'claude.ai':
+ note('Remote Control (the session also showing in the Claude app) needs a claude.ai login; '
+ 'with an API key, start sessions with CHUMS_NO_RC=1')
+ else:
+ (fail if need_claude else warn)(f'Claude Code {cv} is installed but not signed in{where}',
+ 'run claude, then /login (a Pro, Max, Team or Enterprise plan, or a Console API key)')
+ if not claude_on_path:
+ warn(f'claude is not on PATH: bin/chums-claude runs "claude" from PATH', f'add {os.path.dirname(claude)} to PATH in ~/.zshrc')
+elif need_claude:
+ fail('Claude Code is not installed' + (' (agents.json has Claude Code agents)' if runtimes else ''),
+ ['curl -fsSL https://claude.ai/install.sh | bash', 'then run claude and sign in'])
+else:
+ note('Claude Code is not installed: only Claude Code agents and changing a soul by voice need it')
+
+codex_cmds = [a['command'][0] for a in agents if isinstance(a, dict) and a.get('runtime') == 'codex'
+ and isinstance(a.get('command'), list) and a['command']] if isinstance(agents, list) else []
+codex = codex_cmds[0] if codex_cmds and os.access(codex_cmds[0], os.X_OK) else find('codex')[0]
+if codex:
+ cxv = version(run([codex, '--version'], timeout=20)[1])
+ # only when this version has `codex login status`: on an older one, `codex login` would start a sign-in
+ has_status = re.search(r'^\s+status\b', run([codex, 'login', '--help'], timeout=20)[1], re.M)
+ rc, out, err = run([codex, 'login', 'status'], timeout=20) if has_status else (1, '', 'no "codex login status" in this version')
+ signed = rc == 0 and 'not logged in' not in (out + err).lower()
+ label = f'Codex CLI {vstr(cxv)}' if cxv else f'Codex CLI ({codex}, its version unknown)'
+ if cxv and cxv < (0, 160):
+ warn(f'{label}: Chums was written against 0.160 (its app-server protocol changes between releases)',
+ 'npm install -g @openai/codex@latest (or brew upgrade --cask codex)')
+ said = ((out or err).splitlines() or ['signed in'])[0] # "Logged in using ChatGPT"
+ if signed: ok(f'{label}, {said[0].lower()}{said[1:]}')
+ else: (fail if need_codex else warn)(f'{label} is installed but not signed in', 'codex login')
+elif need_codex:
+ fail('Codex CLI is not installed (agents.json has Codex agents)', ['npm install -g @openai/codex (or brew install --cask codex)', 'then codex login'])
+else:
+ note('Codex CLI is not installed: only Codex agents ("runtime": "codex") need it')
+if not claude and not codex:
+ fail('No coding agent: Chums needs Claude Code, Codex, or both', 'docs/setup.md, "Pick your agent"')
+
+# ---------- 3. Chums' settings ----------
+section('3. Settings (~/.chums)')
+if config_problem:
+ fail(f'~/.chums/config.json is not valid JSON ({config_problem})',
+ ['fix the file by hand, or move it away and start the hub (it writes a new one with new tokens;',
+ 'then run bin/chums-install again so the watch app gets the new token)'])
+elif cfg is None:
+ fail('~/.chums/config.json does not exist yet', 'start the hub once: bin/chums-hub (it writes the file with two new tokens)')
+else:
+ mode = os.stat(CONFIG).st_mode & 0o777
+ if mode & 0o077: warn(f'~/.chums/config.json is readable by other users (mode {oct(mode)[2:]}); it holds the tokens', 'chmod 600 ~/.chums/config.json')
+ if cfg.get('token') and cfg.get('watchToken'): ok(f'~/.chums/config.json: ports {cfg.get("port", 7717)} and {cfg.get("publicPort", 7718)}, both tokens set (not shown)')
+ else: fail('~/.chums/config.json is missing a token', ['restart the hub: it adds the missing token', 'then bin/chums-install, so the watch app gets it'])
+ if cfg.get('publicURL'): ok(f'public URL {cfg["publicURL"]}')
+ else: fail('no public URL yet: the watch reaches the hub only through it (the Simulator does not need it)', 'bin/chums-tunnel')
+ if cfg.get('ownerName'): note(f'the agents call you {cfg["ownerName"]} (ownerName)')
+ else: note('ownerName is not set: the agents call you "the user" (add "ownerName": "Sam" to config.json)')
+
+# agents.json
+def looks():
+ try: src = open(os.path.join(ROOT, 'hub/hub.mjs'), encoding='utf-8').read()
+ except OSError: return set()
+ m = re.search(r"^const LOOKS = \[([^\]]*)\]", src, re.M)
+ return set(re.findall(r"'([a-z]+)'", m.group(1))) if m else set()
+
+LOOKS = looks()
+RUNTIMES = {'claude', 'codex', 'copilot', 'acp'}
+if agents_problem:
+ fail(f'~/.chums/agents.json is not valid JSON ({agents_problem})',
+ ['fix it (tools/agents.example.json shows the shape), then restart the hub',
+ 'or move it away: the hub writes one agent per character on its next start'])
+elif agents is None:
+ warn('~/.chums/agents.json does not exist yet', 'start the hub once: it writes one agent per character')
+elif not isinstance(agents, list):
+ fail('~/.chums/agents.json must be a list of agents ([ {...}, {...} ])', 'see tools/agents.example.json')
+else:
+ problems, notes, seen = [], [], set()
+ for i, a in enumerate(agents):
+ if not isinstance(a, dict): problems.append(f'entry {i + 1} is not an object'); continue
+ aid = a.get('id')
+ if not isinstance(aid, str) or not aid:
+ problems.append(f'entry {i + 1} has no "id"'); continue
+ if not re.fullmatch(r'[a-z0-9-]+', aid):
+ notes.append(f'{aid}: the watch opens a soul only for ids of lowercase letters, digits and dashes')
+ if aid in seen: problems.append(f'{aid}: the id is used twice')
+ seen.add(aid)
+ rt = a.get('runtime') or 'claude'
+ if rt not in RUNTIMES: problems.append(f'{aid}: unknown runtime {rt!r} (claude, codex; experimental: copilot, acp)')
+ if LOOKS and aid not in LOOKS: notes.append(f'{aid}: every agent is a character, and its id is the character\'s ({", ".join(sorted(LOOKS))}); the watch doesn\'t list this one')
+ cwd = a.get('cwd')
+ if not isinstance(cwd, str) or not os.path.isabs(os.path.expanduser(cwd)): problems.append(f'{aid}: "cwd" must be an absolute folder path')
+ elif not os.path.isdir(cwd) and not cwd.startswith(os.path.join(CHUMS, 'agents')):
+ notes.append(f'{aid}: its folder {cwd} does not exist')
+ for d in a.get('addDirs') or []:
+ if not os.path.isdir(d): notes.append(f'{aid}: addDirs folder {d} does not exist')
+ if rt == 'codex':
+ if a.get('approvalPolicy') not in (None, 'untrusted', 'on-request', 'on-failure', 'never'):
+ problems.append(f'{aid}: approvalPolicy {a["approvalPolicy"]!r} (untrusted, on-request, never)')
+ if a.get('sandbox') not in (None, 'read-only', 'workspace-write', 'danger-full-access'):
+ problems.append(f'{aid}: sandbox {a["sandbox"]!r} (read-only, workspace-write, danger-full-access)')
+ if rt == 'acp' and not a.get('command'): problems.append(f'{aid}: an acp agent needs "command"')
+ if rt == 'copilot' and not os.path.isdir(os.path.join(ROOT, 'node_modules/@github/copilot-sdk')):
+ problems.append(f'{aid}: runtime copilot needs the Copilot SDK (npm install --no-save @github/copilot-sdk)')
+ missing = sorted(LOOKS - seen) if LOOKS else []
+ if missing: notes.append(f'no agent yet for {", ".join(missing)}: the hub adds one for each character when it starts')
+ names = {'claude': 'Claude Code', 'codex': 'Codex', 'copilot': 'Copilot', 'acp': 'ACP'}
+ summary = ', '.join(f'{a.get("id")} ({names.get(a.get("runtime") or "claude", a.get("runtime"))})' for a in agents if isinstance(a, dict))
+ if problems: fail(f'~/.chums/agents.json: ' + '; '.join(problems), 'edit ~/.chums/agents.json (docs/other-agents.md lists the fields), then restart the hub')
+ else: ok(f'~/.chums/agents.json: {len(agents)} agent{"s" * (len(agents) != 1)}: {summary}')
+ for n in notes: warn(n)
+
+# ---------- 4. the hub ----------
+section('4. The hub')
+hub_label = f'{label_prefix}.hub'
+hub_launchd = os.path.isfile(os.path.join(HOME, 'Library/LaunchAgents', f'{hub_label}.plist'))
+start_fix = (f'launchctl kickstart -k gui/{os.getuid()}/{hub_label} (log: ~/.chums/hub.log)' if hub_launchd
+ else 'bin/chums-hub (or bin/chums-setup --launchd to run it at login)')
+if not (cfg and cfg.get('token')):
+ note('skipped: no config yet')
+else:
+ port, pport = cfg.get('port', 7717), cfg.get('publicPort', 7718)
+ status, body, err = http(f'http://127.0.0.1:{port}/v1/ping', cfg['token'])
+ if status == 200:
+ hub_up = True
+ ok(f'the hub answers on 127.0.0.1:{port}')
+ elif status == 401:
+ fail(f'something on 127.0.0.1:{port} refuses this config\'s token: a hub started with another config, or another program',
+ [f'lsof -nP -iTCP:{port} -sTCP:LISTEN shows what it is', 'stop it, then start the hub again'])
+ else:
+ fail(f'the hub is not running (nothing answers on 127.0.0.1:{port})', start_fix)
+ if hub_up:
+ s2, _, _ = http(f'http://127.0.0.1:{pport}/v1/ping', cfg.get('watchToken', ''))
+ if s2 == 200: ok(f'the watch side answers on 127.0.0.1:{pport} (what Funnel forwards to)')
+ else: fail(f'the watch side on 127.0.0.1:{pport} does not answer ({s2 or "no connection"})', ['restart the hub', start_fix])
+ if hub_launchd and launchd_loaded(hub_label): note(f'it runs as the LaunchAgent {hub_label}, log in ~/.chums/hub.log')
+ else: note('it runs in a terminal and stops when that terminal closes (bin/chums-setup --launchd runs it at login)')
+ if port_open(WHISPER_PORT): ok(f'speech to text (whisperkit-cli serve) listens on {WHISPER_PORT}')
+ else: fail(f'speech to text is not running (nothing on port {WHISPER_PORT}); the hub starts it',
+ ['the hub log says why: "whisper model missing" (bin/chums-setup) or "whisper exited"',
+ 'under launchd, whisperkit-cli must be in the PATH of the hub LaunchAgent: run bin/chums-setup --launchd again'])
+ # the agents' voices (Kokoro), unless config says otherwise
+ engine = (cfg.get('tts') or {}).get('engine') or ('kokoro' if os.access(os.path.join(CHUMS, 'kokoro/.venv/bin/python'), os.X_OK) else 'watch')
+ if engine == 'kokoro':
+ if port_open(KOKORO_PORT, '127.0.0.1'): ok(f"the agents' voices (Kokoro) answer on {KOKORO_PORT}")
+ else: warn(f"the agents' voices (Kokoro) are not running (nothing on port {KOKORO_PORT}): the watch reads replies with its own voice",
+ ['the hub starts Kokoro: its log says why if it stopped ("kokoro exited")', 'reinstall it: bin/chums-setup'])
+ elif engine == 'watch': note("the watch reads replies with its own voice (bin/chums-setup installs the agents' voices, Kokoro)")
+ else: note(f'replies are voiced with {engine} (config "tts")')
+ st, state, _ = http(f'http://127.0.0.1:{port}/v1/state?since=0', cfg['token'])
+ if st == 200 and state:
+ for a in state.get('agents', []):
+ rt = {'claude': 'Claude Code', 'codex': 'Codex'}.get(a.get('runtime', 'claude'), a.get('runtime'))
+ if a.get('status') != 'offline':
+ ok(f'agent {a.get("id")} ({a.get("name")}, {rt}) is {a.get("status")}')
+ elif rt == 'Claude Code':
+ warn(f'agent {a.get("id")} ({a.get("name")}, Claude Code) is not running: the watch shows it as "Not running on your Mac"',
+ [f'bin/chums-agents install (all) or bin/chums-agents start {a.get("id")}',
+ f'its log: ~/.chums/agents/{a.get("id")}.host.log'])
+ else:
+ warn(f'agent {a.get("id")} ({a.get("name")}, {rt}) is not running in the hub',
+ [f'its log: ~/.chums/agents/{a.get("id")}.host.log', 'restart the hub after fixing agents.json'])
+ ids = {a.get('id') for a in state.get('agents', [])}
+ for s in state.get('sessions', []):
+ if s.get('name') not in ids: note(f'session {s.get("name")} is connected (not in agents.json)')
+
+# permissions: the hub and the agents run through Chums.app, so every permission they need is Chums's (read-only here)
+chums_app = os.path.join(os.environ.get('CHUMS_MAC_APP') or os.path.join(HOME, 'Applications/Chums.app'), 'Contents/MacOS')
+la_dir = os.path.join(HOME, 'Library/LaunchAgents')
+plists = [os.path.join(la_dir, f) for f in sorted(os.listdir(la_dir)) if f.startswith((f'{label_prefix}.hub.', f'{label_prefix}.tailscaled.', f'{label_prefix}.agent.'))] if os.path.isdir(la_dir) else []
+if plists:
+ import plistlib
+ old = [os.path.basename(p) for p in plists
+ if (plistlib.load(open(p, 'rb')).get('ProgramArguments') or [''])[0] != os.path.join(chums_app, 'Chums')]
+ if old: warn(f'{", ".join(old)} still start{"s" * (len(old) == 1)} outside Chums.app: macOS asks for permissions as expect, caffeinate, node or tailscaled, again after each update',
+ 'bin/chums-setup --launchd and bin/chums-agents install (they restart the hub and the agents), then open Chums')
+ else: ok('the hub, tailscaled and the agents run as Chums (one app for every permission)')
+ if os.access(os.path.join(chums_app, 'Chums'), os.X_OK):
+ got = {w: run([os.path.join(chums_app, 'Chums'), '--check', w])[0] == 0 for w in ('screen', 'accessibility')}
+ names = {'screen': 'Screen Recording', 'accessibility': 'Accessibility'}
+ missing = [names[w] for w, g in got.items() if not g]
+ if missing: warn(f'Chums doesn\'t have {" or ".join(missing)} yet: an agent can stop on a dialog on this Mac',
+ 'open Chums (~/Applications) and click Allow All, once, at the Mac (bin/chums-permissions opens it)')
+ else: ok('Chums has Screen Recording and Accessibility (its window shows the rest)')
+
+# ---------- 5. Tailscale Funnel ----------
+section('5. Tailscale Funnel (the watch\'s way to the hub)')
+host = None
+if not (ts and tsd):
+ note('skipped: Tailscale is not installed')
+else:
+ rc, out, err = run([ts, f'--socket={TS_SOCK}', 'status', '--json'], timeout=10)
+ try: tstat = json.loads(out) if rc == 0 or out.startswith('{') else None
+ except ValueError: tstat = None
+ if not os.path.exists(TS_SOCK) or tstat is None:
+ fail("Chums' tailscaled is not running", ['bin/chums-tunnel starts it',
+ 'bin/chums-setup --launchd also runs it at login'])
+ else:
+ state_ = tstat.get('BackendState')
+ selfn = tstat.get('Self') or {}
+ host = (selfn.get('DNSName') or '').rstrip('.') or None
+ if state_ == 'Running':
+ ok(f'signed in to Tailscale as {host}')
+ elif state_ == 'NeedsLogin':
+ fail('tailscaled is not signed in to Tailscale', 'bin/chums-tunnel, then open the sign-in link it prints')
+ host = None
+ else:
+ fail(f'tailscaled is {state_}', 'bin/chums-tunnel')
+ host = None
+ caps = set((selfn.get('CapMap') or {}).keys()) | set(selfn.get('Capabilities') or [])
+ if host:
+ if 'https' in caps and 'funnel' in caps: ok('the tailnet allows HTTPS certificates and Funnel for this machine')
+ else: fail('the tailnet does not allow ' + ' and '.join(x for x, c in (('HTTPS certificates', 'https'), ('Funnel', 'funnel')) if c not in caps),
+ ['bin/chums-tunnel prints a link that turns both on; open it and approve',
+ 'or in the Tailscale admin console: DNS › HTTPS Certificates, and Access controls › the funnel node attribute'])
+ rc, out, _ = run([ts, f'--socket={TS_SOCK}', 'funnel', 'status', '--json'], timeout=10)
+ try: fs_ = json.loads(out) if out else {}
+ except ValueError: fs_ = {}
+ want = f'http://127.0.0.1:{(cfg or {}).get("publicPort", 7718)}'
+ proxy = (((fs_.get('Web') or {}).get(f'{host}:443') or {}).get('Handlers') or {}).get('/', {}).get('Proxy')
+ if (fs_.get('AllowFunnel') or {}).get(f'{host}:443') and proxy == want:
+ ok(f'Funnel is on: https://{host} goes to {want}')
+ elif proxy and proxy != want:
+ fail(f'Funnel forwards https://{host} to {proxy}, not to the hub\'s watch side ({want})', 'bin/chums-tunnel')
+ else:
+ fail('Funnel is off for this machine', 'bin/chums-tunnel')
+ if cfg and cfg.get('publicURL') and cfg['publicURL'].rstrip('/') != f'https://{host}':
+ fail(f'config.json has publicURL {cfg["publicURL"]}, but this machine is https://{host}',
+ ['bin/chums-tunnel (it stores the right URL)', 'then bin/chums-install (the URL is built into the watch app)'])
+
+# the public address, as the watch sees it: public DNS, then HTTPS through Funnel
+url = (cfg or {}).get('publicURL') or (f'https://{host}' if host else None)
+if url and cfg and cfg.get('watchToken'):
+ name = re.sub(r'^https?://', '', url).split('/')[0].split(':')[0]
+ ips = []
+ if shutil.which('dig'):
+ for server in ('1.1.1.1', '8.8.8.8'):
+ rc, out, _ = run(['dig', '+short', '+time=3', '+tries=1', 'A', name, f'@{server}'], timeout=10)
+ ips = [l for l in out.split('\n') if re.fullmatch(r'[\d.]+', l)]
+ if ips: break
+ if ips:
+ ok(f'{name} resolves in public DNS ({", ".join(ips[:2])})')
+ else:
+ fail(f'{name} does not resolve in public DNS yet',
+ ['a new Funnel name takes a while: Tailscale says up to 10 minutes; it has taken about 25',
+ 'run bin/chums-doctor again later; nothing else to do'])
+ code, body = None, ''
+ with tempfile.NamedTemporaryFile() as tmp:
+ t0 = time.time()
+ rc, out, err = run(['curl', '-sS', '--max-time', '15', '-o', tmp.name, '-w', '%{http_code} %{remote_ip}',
+ '-H', '@-', f'{url.rstrip("/")}/v1/ping'],
+ timeout=25, stdin=f'Authorization: Bearer {cfg["watchToken"]}\n')
+ took = time.time() - t0
+ parts = out.split()
+ code = parts[0] if parts else None
+ remote = parts[1] if len(parts) > 1 else ''
+ tailnet = False
+ try: tailnet = ipaddress.ip_address(remote) in ipaddress.ip_network('100.64.0.0/10') or remote.startswith('fd7a:115c:a1e0')
+ except ValueError: pass
+ if rc == 0 and code == '200':
+ if tailnet:
+ warn(f'{url}/v1/ping answers, but over your tailnet ({remote}), not through the internet',
+ 'check from a phone on cellular: open the URL + /v1/ping; {"error":"unauthorized"} means Funnel works')
+ else:
+ ok(f'{url}/v1/ping answers through Funnel from the internet with the watch token ({took:.1f} s)')
+ elif rc == 0 and code == '401':
+ fail(f'{url} reaches a hub that refuses this config\'s watch token',
+ ['the hub behind Funnel was started with another config: restart the hub', start_fix])
+ elif rc == 0 and code in ('502', '503', '504'):
+ fail(f'Funnel answers but the hub behind it does not (HTTP {code})', start_fix)
+ elif rc == 6:
+ fail(f'{url}: the name does not resolve from this Mac yet (see the DNS line above)',
+ 'if public DNS already resolves it, flush this Mac\'s cache: sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder')
+ elif rc != 127:
+ fail(f'{url}/v1/ping failed: {err or f"HTTP {code}"}',
+ ['tailscale --socket ~/.chums/tailscale/tailscaled.sock funnel status shows what Funnel serves',
+ 'the first HTTPS request to a new name waits while Tailscale gets its certificate; try again in a minute'])
+elif cfg:
+ note('skipped the internet check: no public URL yet')
+
+# ---------- 6. building the watch app ----------
+section('6. Building the watch app (Xcode, signing)')
+xcode_ok = False
+if os.path.isdir(DEV):
+ rc, out, _ = run(['xcodebuild', '-version'], timeout=30, env={'DEVELOPER_DIR': DEV})
+ xv = version(out)
+ if rc == 0 and xv and xv >= (26, 0):
+ xcode_ok = True
+ ok(f'{out.splitlines()[0]} ({DEV.split("/Contents")[0]})')
+ else:
+ fail(f'Xcode 26 or later is needed (found: {out.splitlines()[0] if out else "none"})', 'install Xcode from the App Store, or set DEVELOPER_DIR')
+else:
+ fail(f'Xcode not found at {DEV.split("/Contents")[0]}', ['install Xcode 26 from the App Store and open it once',
+ 'or set DEVELOPER_DIR to the Xcode you use (…/Xcode.app/Contents/Developer)'])
+if xcode_ok:
+ if run(['xcodebuild', '-license', 'check'], timeout=30, env={'DEVELOPER_DIR': DEV})[0] != 0:
+ fail("Xcode's license has not been accepted", 'open Xcode once, or: sudo xcodebuild -license accept')
+ if run(['xcodebuild', '-checkFirstLaunchStatus'], timeout=30, env={'DEVELOPER_DIR': DEV})[0] != 0:
+ fail("Xcode hasn't finished its first launch (it installs components then)", 'open Xcode once, or: sudo xcodebuild -runFirstLaunch')
+ sdk = version(run(['xcrun', '--sdk', 'watchos', '--show-sdk-version'], timeout=30, env={'DEVELOPER_DIR': DEV})[1])
+ if sdk and sdk >= (26, 0): ok(f'watchOS {vstr(sdk)} SDK')
+ else: fail('the watchOS SDK is missing from Xcode', 'Xcode › Settings › Components: get watchOS')
+ sel = run(['xcode-select', '-p'], timeout=5)[1]
+ if sel and not sel.startswith(DEV.split('/Contents')[0]):
+ note(f'xcode-select points at {sel}; Chums\' scripts use DEVELOPER_DIR={DEV}. To run xcrun devicectl yourself: '
+ f'sudo xcode-select -s {DEV.split("/Contents")[0]}')
+ rc, out, _ = run(['xcrun', 'simctl', 'list', 'runtimes', '-j'], timeout=30, env={'DEVELOPER_DIR': DEV})
+ try: sims = [r for r in json.loads(out)['runtimes'] if r.get('platform') == 'watchOS' and r.get('isAvailable')]
+ except (ValueError, KeyError): sims = []
+ if sims: ok(f'watchOS Simulator {sims[-1].get("version", "")} (for bin/chums-sim)')
+ else: note('no watchOS Simulator runtime: only bin/chums-sim needs it (xcodebuild -downloadPlatform watchOS, several GB)')
+if find('xcodegen')[0]: ok('xcodegen')
+else: fail('xcodegen is not installed (it makes the Xcode project)', 'brew install xcodegen')
+
+team = os.environ.get('CHUMS_TEAM') or (cfg or {}).get('team')
+if team:
+ source = 'CHUMS_TEAM' if os.environ.get('CHUMS_TEAM') else '"team" in config.json'
+ ok(f'signing team {team} (set by {source})')
+else:
+ rc, out, err = run([sys.executable, os.path.join(ROOT, 'tools/pick-team.py')], timeout=30)
+ team, team_kind = (out.strip() or None), ('free' if 'free' in err else 'paid')
+ if not team:
+ fail('Xcode has no Apple ID that can sign apps', ['Xcode › Settings › Apple Accounts › + › Apple ID, and sign in',
+ 'any Apple ID works: it gets a free Personal Team'])
+ elif team_kind == 'free':
+ warn(f'signing team {team} is a free Personal Team: installs expire after 7 days, 3 apps per device, 10 App IDs per 7 days',
+ 'run bin/chums-install again within 7 days, or join the Apple Developer Program ($99 a year, installs last a year)')
+ else:
+ ok(f'signing team {team} (a paid team in Xcode)')
+bundle = os.environ.get('CHUMS_BUNDLE') or (cfg or {}).get('bundleId')
+if bundle: note(f'bundle ID {bundle}: the watch app is {bundle}.watchkitapp')
+elif team: note(f'bundle ID dev.chums.{team.lower()} (from the team). To keep it if you change teams, add "bundleId" to ~/.chums/config.json')
+
+if os.path.isfile(HUBCONFIG):
+ src = open(HUBCONFIG, encoding='utf-8').read()
+ m_tok = re.search(r'static let token = "([^"]*)"', src)
+ m_hosts = re.search(r'static let hosts = (\[[^\]]*\])', src)
+ m_build = re.search(r'static let build = "([^"]*)"', src)
+ try: hosts = json.loads(m_hosts.group(1)) if m_hosts else []
+ except ValueError: hosts = []
+ built = f'built {m_build.group(1)}' if m_build else 'last build'
+ if cfg and m_tok and m_tok.group(1) != cfg.get('watchToken'):
+ fail(f'the watch app ({built}) has an older watch token than the hub (the watch shows "Hub refused the token")', 'bin/chums-install')
+ elif cfg and cfg.get('publicURL') and cfg['publicURL'] not in hosts:
+ fail(f'the watch app ({built}) has another hub address than {cfg["publicURL"]}', 'bin/chums-install')
+ elif cfg:
+ ok(f'the watch app ({built}) has the hub\'s current token and address')
+else:
+ note('the watch app has not been built from this checkout yet (bin/chums-install builds it)')
+
+# ---------- 7. the watch ----------
+section('7. The Apple Watch (as Xcode sees it)')
+if not xcode_ok:
+ note('skipped: Xcode is needed to see devices')
+else:
+ with tempfile.NamedTemporaryFile(suffix='.json') as tmp:
+ rc, out, err = run(['xcrun', 'devicectl', 'list', 'devices', '--json-output', tmp.name], timeout=60, env={'DEVELOPER_DIR': DEV})
+ try: devices = json.load(open(tmp.name))['result']['devices']
+ except (ValueError, KeyError, OSError): devices = None
+ if devices is None:
+ fail(f'xcrun devicectl could not list devices ({(err or out).splitlines()[-1] if (err or out) else rc})', 'open Xcode once and try again')
+ else:
+ def props(d):
+ hp, dp, cp = d.get('hardwareProperties', {}), d.get('deviceProperties', {}), d.get('connectionProperties', {})
+ return hp.get('platform'), dp.get('name', '?'), version(dp.get('osVersionNumber')), dp.get('developerModeStatus'), cp.get('pairingState')
+ watches = [d for d in devices if d.get('hardwareProperties', {}).get('platform') == 'watchOS']
+ phones = [d for d in devices if d.get('hardwareProperties', {}).get('deviceType') == 'iPhone']
+ for d in phones:
+ _, n, v, dm, pair = props(d)
+ note(f'iPhone {n} (iOS {vstr(v) if v else "?"}): {pair or "?"}, Developer Mode {dm or "?"}')
+ if not watches:
+ fail('Xcode does not know any Apple Watch yet',
+ ['connect the paired iPhone with a USB cable, unlock it and tap Trust',
+ 'keep the watch unlocked and near the iPhone, on the same Wi-Fi as the Mac',
+ 'open Xcode › Window › Devices and Simulators and wait for the watch (docs/setup.md, step 7)'])
+ for d in watches:
+ _, n, v, dm, pair = props(d)
+ what = f'Apple Watch {n} (watchOS {vstr(v) if v else "?"})'
+ if v and v < (26, 0): fail(f'{what}: Chums needs watchOS 26', 'on the iPhone: Watch app › General › Software Update')
+ elif pair != 'paired': fail(f'{what} is not paired with this Mac ({pair})', 'Xcode › Window › Devices and Simulators, with the iPhone on USB and the watch unlocked')
+ elif dm != 'enabled': fail(f'{what}: Developer Mode is {dm or "off"}',
+ ['on the watch: Settings › Privacy & Security › Developer Mode, then restart it and confirm',
+ 'switch missing? docs/setup.md, step 8'])
+ else: ok(f'{what}: paired with this Mac, Developer Mode on')
+
+# ---------- summary ----------
+print(f'\n{count["PASS"]} passed, {count["WARN"]} warning{"s" * (count["WARN"] != 1)}, {count["FAIL"]} failed.')
+if count['FAIL']:
+ print('Fix the first FAIL first: later checks often fail because of it. More in docs/troubleshooting.md.')
+sys.exit(1 if count['FAIL'] else 0)
diff --git a/tools/e2e-claude.py b/tools/e2e-claude.py
new file mode 100644
index 0000000..94c34e7
--- /dev/null
+++ b/tools/e2e-claude.py
@@ -0,0 +1,93 @@
+"""Real end-to-end: start chums-claude in a pty, accept startup prompts, send an order as the watch
+would, and wait for Claude to answer through chums_reply."""
+import json, os, pty, re, select, subprocess, sys, time, urllib.request
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+WORK = sys.argv[1]
+os.makedirs(WORK, exist_ok=True)
+cfg = json.load(open(os.path.expanduser("~/.chums/config.json")))
+HUB = f"http://127.0.0.1:{cfg['port']}"
+
+def hub(path, body=None):
+ req = urllib.request.Request(HUB + path, data=json.dumps(body).encode() if body else None,
+ headers={"authorization": f"Bearer {cfg['token']}", "content-type": "application/json"})
+ return json.load(urllib.request.urlopen(req, timeout=30))
+
+existing = {x["id"] for x in hub("/v1/state?since=0")["sessions"]}
+pid, fd = pty.fork()
+if pid == 0:
+ os.chdir(WORK)
+ os.environ.update(CHUMS_NO_RC="1", TERM="xterm-256color")
+ os.execvp("zsh", ["zsh", "-c", f"{ROOT}/bin/chums-claude e2e --permission-mode default"])
+
+screen = ""
+def pump(sec):
+ global screen
+ end = time.time() + sec
+ while time.time() < end:
+ r, _, _ = select.select([fd], [], [], 0.2)
+ if r:
+ try: screen += os.read(fd, 65536).decode(errors="ignore")
+ except OSError: return
+ screen = screen[-20000:]
+
+plain = lambda s: re.sub(r"\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07]*\x07", "", s)
+answered = set()
+DOWN = b"\x1b[B"
+for _ in range(40):
+ pump(1)
+ p = plain(screen).replace(" ", "").lower()
+ tail = p[-1500:]
+ if "itrustthisfolder" in tail and "trust" not in answered:
+ answered.add("trust"); os.write(fd, DOWN); pump(0.3); os.write(fd, b"\r"); screen = ""; pump(2)
+ continue
+ if ("developmentchannel" in tail or "dangerously" in tail) and "entertoconfirm" in tail and "dev" not in answered:
+ print("--- dev-channel prompt ---\n" + plain(screen)[-1200:])
+ answered.add("dev")
+ # pick the option that keeps the session running, not "Exit"
+ if re.search(r"❯\s*(\d\.)?\s*(no|exit|cancel)", plain(screen)[-1200:], re.I):
+ os.write(fd, DOWN); pump(0.3)
+ os.write(fd, b"\r"); screen = ""; pump(2)
+ continue
+ if any(s["name"] == "e2e" and s["id"] not in existing for s in hub("/v1/state?since=0")["sessions"]):
+ break
+state = hub("/v1/state?since=0")
+print("sessions:", [s["name"] for s in state["sessions"]], "| prompts answered:", sorted(answered))
+if not any(s["name"] == "e2e" for s in state["sessions"]):
+ print(plain(screen)[-3000:]); os.kill(pid, 9); sys.exit(1)
+
+t0 = time.time()
+old = {s["id"] for s in state["spoken"]}
+r = hub("/v1/say", {"text": "e2e, what is seven times six? Just answer through Chums."})
+print("echo:", r.get("echo"))
+reply = None
+while time.time() - t0 < 120 and not reply:
+ pump(1)
+ reply = next((s for s in hub("/v1/state?since=0")["spoken"] if s["session"] == "e2e" and s["id"] not in old), None)
+print(f"reply after {time.time()-t0:.1f}s:", reply and reply["text"])
+
+# Permission relay with a real prompt: a shell command needs approval; answer it "from the watch".
+target = os.path.join(WORK, "chums-proof.txt")
+if os.path.exists(target): os.remove(target)
+seen = {s["id"] for s in hub("/v1/state?since=0")["spoken"]}
+t1 = time.time()
+hub("/v1/say", {"text": "e2e, use the Bash tool to run: echo approved-from-watch > chums-proof.txt"})
+approval = None
+while time.time() - t1 < 90 and not approval:
+ pump(1)
+ ap = hub("/v1/state?since=0")["approvals"]
+ approval = ap[0] if ap else None
+print(f"approval card after {time.time()-t1:.1f}s:", approval and {k: approval[k] for k in ("tool", "description", "preview")})
+if approval:
+ v = hub("/v1/say", {"text": "yes"})
+ print("verdict:", v.get("echo"))
+ done = None
+ while time.time() - t1 < 150 and not done:
+ pump(1)
+ done = next((s for s in hub("/v1/state?since=0")["spoken"] if s["session"] == "e2e" and s["id"] not in seen), None)
+ print("file written:", os.path.exists(target) and open(target).read().strip(), "| reply:", done and done["text"])
+os.write(fd, b"\x03"); pump(0.5); os.write(fd, b"\x03"); pump(1)
+try: os.kill(pid, 9)
+except ProcessLookupError: pass
+if not reply:
+ print(plain(screen)[-3000:]); sys.exit(1)
diff --git a/tools/e2e-runtimes.mjs b/tools/e2e-runtimes.mjs
new file mode 100644
index 0000000..76a033c
--- /dev/null
+++ b/tools/e2e-runtimes.mjs
@@ -0,0 +1,208 @@
+// Real end to end, for the agents the hub runs itself: a private hub runs a real Codex or Copilot agent in a fresh
+// folder, and this plays the watch: a question, a command that needs approval (allowed), another one (denied), the
+// chums_reply tool. Codex also: a file edit, chums_show, an order while it works (steering), a Codex terminal on the
+// same thread (bin/chums-codex: the watch's orders show in it, and what's typed in it reaches the agent), another app's
+// app-server on the thread, its app-server dying, and the hub itself killed and started again. Its thread is archived
+// at the end (CHUMS_E2E_KEEP=1 keeps it).
+// It uses your Codex / Copilot logins and spends a few model calls (Codex: about 14 turns).
+// node tools/e2e-runtimes.mjs codex [model] codex app-server (default model gpt-6-astra)
+// node tools/e2e-runtimes.mjs copilot [model] the Copilot SDK (default model gpt-5-mini)
+// node tools/e2e-runtimes.mjs copilot-acp [model] `copilot --acp` (default model gpt-5-mini)
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { spawn } from 'node:child_process'
+import { startPrivateHub } from './test-hub-private.mjs'
+
+const [which = 'codex', model] = process.argv.slice(2)
+const work = fs.mkdtempSync(path.join(os.tmpdir(), `chums-e2e-${which}-`))
+const cwd = path.join(work, 'project')
+fs.mkdirSync(cwd)
+const agent = {
+ codex: { runtime: 'codex', model: model ?? 'gpt-6-astra', approvalPolicy: 'untrusted' }, // untrusted: every command asks
+ copilot: { runtime: 'copilot', model: model ?? 'gpt-5-mini' },
+ 'copilot-acp': { runtime: 'acp', command: ['copilot', '--acp', '--no-auto-update', '--model', model ?? 'gpt-5-mini'] },
+}[which]
+if (!agent) { console.error('codex, copilot or copilot-acp'); process.exit(2) }
+const ID = 'e2e'
+const logFile = path.join(work, 'hub.log')
+let { cfg, home, hub, stop } = await startPrivateHub({ agents: [{ id: ID, name: 'Tester', character: 'ray', cwd, ...agent }], logFile, env: { CHUMS_RUNTIME_DEBUG: '1' } })
+const H = `http://127.0.0.1:${cfg.port}`
+const call = async (p, body, again = true) => {
+ try { return await (await fetch(H + p, { method: body ? 'POST' : 'GET', headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/json' }, body: body && JSON.stringify(body) })).json() }
+ catch (e) { if (!again) throw e; await new Promise(r => setTimeout(r, 500)); return call(p, body, false) } // a kept-alive socket the hub closed
+}
+const state = () => call('/v1/state?since=0')
+const sleep = ms => new Promise(r => setTimeout(r, ms))
+let fails = 0; const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) fails++ }
+const t0 = Date.now(), at = () => `${((Date.now() - t0) / 1000).toFixed(1)}s`
+
+// every status the watch would have shown, in order
+const seen = []
+let watching = true
+;(async () => { while (watching) { const a = (await state().catch(() => null))?.agents?.find(x => x.id === ID); const st = a?.status; if (st && st !== seen.at(-1)) seen.push(st); await sleep(250) } })()
+const until = async (what, f, ms) => { const end = Date.now() + ms; for (;;) { const v = await f(); if (v) return v; if (Date.now() > end) { console.log(` (no ${what} after ${ms / 1000} s)`); return null } await sleep(300) } }
+const newLine = async (since, ms = 180_000) => until('spoken line', async () => (await state()).spoken.find(l => l.agent === ID && l.at > since && l.kind !== 'echo' && l.kind !== 'verdict'), ms)
+
+console.log(`${which}: ${JSON.stringify(agent)} in ${cwd}`)
+ok(await until('agent', async () => (await state()).agents.find(a => a.id === ID)?.status === 'idle', 120_000), `${at()} the agent is up (idle)`)
+
+let since = Date.now()
+await call('/v1/say', { agent: ID, text: 'What is seven times six? Just answer.' })
+const a1 = await newLine(since)
+ok(a1 && /42|forty.two/i.test(a1.text), `${at()} a question gets a spoken answer: "${a1?.text}"`)
+
+since = Date.now()
+await call('/v1/say', { agent: ID, text: 'Use the shell to run exactly this command: echo approved-from-watch > chums-proof.txt' })
+const card = await until('approval card', async () => (await state()).approvals.find(x => x.session === ID), 180_000)
+ok(card, `${at()} the command asks for approval on the watch: ${card?.tool} "${card?.summary}"`)
+if (card) await call('/v1/say', { agent: ID, text: 'yes', approval: card.requestId })
+const proof = path.join(cwd, 'chums-proof.txt')
+ok(await until('proof file', async () => fs.existsSync(proof), 120_000), `${at()} allowed from the watch, it ran: chums-proof.txt exists`)
+const a2 = await newLine(since)
+ok(a2, `${at()} and it said so: "${a2?.text}"`)
+
+since = Date.now()
+await call('/v1/say', { agent: ID, text: 'Use the shell to run exactly this command: rm chums-proof.txt' })
+const card2 = await until('second card', async () => (await state()).approvals.find(x => x.session === ID), 180_000)
+ok(card2, `${at()} a second command asks too: "${card2?.summary}"`)
+if (card2) await call('/v1/say', { agent: ID, text: 'no', approval: card2.requestId })
+// after a no, the agent may say so, or just end its turn (the watch has already said "Denied")
+const stopped = () => state().then(st => st.tools.some(t => t.session === ID && t.type === 'stop' && t.at > since))
+const a3 = await until('spoken line or the end of the turn', async () => (await state()).spoken.find(l => l.agent === ID && l.at > since && !['echo', 'verdict'].includes(l.kind)) ?? (await stopped() && { text: null }), 180_000)
+ok(fs.existsSync(proof), `${at()} denied from the watch, it didn't run: the file is still there`)
+ok(a3, `${at()} and its turn ended: ${a3?.text ? `it said "${a3.text}"` : 'it said nothing more'}`)
+
+// the Chums MCP server's own tool, asked for by name (the agents above may simply have answered in their final message)
+const spokenForIt = () => (fs.readFileSync(logFile, 'utf8').match(/spoken for e2e/g) ?? []).length
+await sleep(1500)
+const before = spokenForIt()
+since = Date.now()
+await call('/v1/say', { agent: ID, text: 'Call the chums_reply tool now with the text "Tool check passed." and status done.' })
+const a4 = await newLine(since)
+await sleep(1500)
+const toolSpoke = a4 && /tool check/i.test(a4.text) && spokenForIt() === before
+// Copilot CLI 1.0.32 over ACP doesn't start a session's stdio MCP servers, so there the hub speaks for it
+if (agent.runtime === 'acp' && !toolSpoke) console.log(`NOTE ${at()} no chums_reply tool over ACP with this agent; the hub said its final message: "${a4?.text}"`)
+else ok(toolSpoke, `${at()} chums_reply, the MCP tool, speaks on the watch: "${a4?.text}"`)
+
+const toolsSeen = (await state()).tools.filter(t => t.session === ID)
+if (agent.runtime === 'codex') {
+ const hostLog = () => fs.readFileSync(path.join(home, '.chums/agents', `${ID}.host.log`), 'utf8')
+ const status = async () => (await state()).agents.find(a => a.id === ID)?.status
+ // answers yes to every card for a while: the steps below are about something else
+ const allowAll = async (done, ms = 240_000) => until('the step', async () => {
+ const cards = (await state()).approvals.filter(x => x.session === ID)
+ for (const c of cards) await call('/v1/say', { agent: ID, text: 'yes', approval: c.requestId })
+ return cards.length ? null : done() // never done with a card still up
+ }, ms)
+
+ // a file edit with Codex's own patch tool is an edit event
+ since = Date.now()
+ await call('/v1/say', { agent: ID, text: 'Use your file editing tool, apply_patch, not the shell, to create notes.txt containing the word hello.' })
+ await allowAll(async () => fs.existsSync(path.join(cwd, 'notes.txt')) && (await state()).tools.some(t => t.session === ID && t.type === 'stop' && t.at > since))
+ const edits = (await state()).tools.filter(t => t.session === ID && t.at > since && t.type === 'edit')
+ ok(fs.existsSync(path.join(cwd, 'notes.txt')) && edits.some(t => /notes\.txt/.test(t.text)), `${at()} a file it writes is an edit event: ${edits.map(t => t.text).join(', ') || 'none'}`)
+
+ // chums_show: a picture on the watch
+ since = Date.now()
+ await call('/v1/say', { agent: ID, text: 'Write circle.svg, a 200 by 200 SVG with one red circle, then call the chums_show tool with file set to its absolute path and title Red circle.' })
+ const shown = await allowAll(async () => (await state()).spoken.find(l => l.agent === ID && l.at > since && l.artifact), 300_000)
+ let thumb = null
+ if (shown) { const r = await fetch(`${H}/v1/artifact/${shown.artifact.id}/thumb`, { headers: { authorization: `Bearer ${cfg.watchToken}` } }); const b = Buffer.from(await r.arrayBuffer()); thumb = r.ok && b[0] === 0xFF && b[1] === 0xD8 }
+ ok(shown && thumb, `${at()} chums_show puts a picture on the watch: "${shown?.artifact?.title}" ${shown?.artifact?.w}×${shown?.artifact?.h}, "${shown?.text}"`)
+
+ // an order said while it works joins the turn in progress (turn/steer): one turn, one stop, both answered
+ const stops = after => state().then(st => st.tools.filter(t => t.session === ID && t.type === 'stop' && t.at > after).length)
+ since = Date.now()
+ await call('/v1/say', { agent: ID, text: 'Run the shell command sleep 8, then tell me it finished.' })
+ await allowAll(async () => (await state()).tools.some(t => t.session === ID && t.at > since && /sleep 8/.test(t.text)), 120_000)
+ await sleep(1500)
+ const during = await status()
+ const since2 = Date.now()
+ await call('/v1/say', { agent: ID, text: 'Also, what is two plus three?' })
+ await allowAll(async () => (await state()).tools.some(t => t.session === ID && t.type === 'stop' && t.at > since2), 180_000)
+ const lines = (await state()).spoken.filter(l => l.agent === ID && l.at > since && !['echo', 'verdict'].includes(l.kind)).map(l => l.text)
+ const n = await stops(since)
+ const refused = hostLog().split('\n').filter(l => /steer refused|order waits/.test(l)).pop()
+ ok(during === 'working' && n === 1 && lines.some(l => /\b5\b|five/i.test(l)) && !refused,
+ `${at()} an order while it works joins that turn (status then: ${during}; ${n} turn${refused ? `; ${refused.slice(20)}` : ''}; said: ${lines.map(l => `"${l}"`).join(', ')})`)
+
+ // a Codex terminal on the agent's thread (bin/chums-codex): what the watch says shows in it as it happens, and what
+ // is typed in it goes to the same agent; the watch sees that turn's work and doesn't speak it
+ const steps = [{ wait: 7 }, { mark: 'A' }, { wait: 16 }, { mark: 'B' }, { type: 'What is nine plus ten? Just the number.' }, { key: 'enter' }, { wait: 25 }]
+ const T0 = Date.now()
+ const term = new Promise(resolve => {
+ const p = spawn('python3', [path.join(import.meta.dirname, 'pty-run.py'), JSON.stringify(steps), '/bin/zsh', path.join(import.meta.dirname, '../bin/chums-codex'), ID], { env: { ...process.env, HOME: home } })
+ let out = ''; p.stdout.on('data', d => { out += d }); p.on('close', () => resolve(out))
+ })
+ await sleep(8000)
+ since = Date.now()
+ await call('/v1/say', { agent: ID, text: 'What is the capital of France? One word.' })
+ const a7 = await newLine(since)
+ const [before = '', live = '', typed = ''] = (await term).split(/###[AB]###/)
+ const typedAt = T0 + 23_000
+ ok(/OpenAICodex/.test(before) && !/capitalofFrance/i.test(before) && /capitalofFrance/i.test(live) && /Paris/.test(live) && /Paris/.test(a7?.text ?? ''),
+ `${at()} chums-codex: a Codex terminal on the thread shows the watch's order and answer as they happen`)
+ ok(/nineplusten/i.test(typed) && /19/.test(typed), `${at()} what is typed in it goes to the agent, which answers there`)
+ const st5 = await state()
+ ok(st5.tools.some(t => t.session === ID && t.type === 'stop' && t.at > typedAt) && !st5.spoken.some(l => l.agent === ID && l.at > typedAt && !['echo', 'verdict'].includes(l.kind)),
+ `${at()} the watch sees that turn, and doesn't speak it`)
+ ok(await status() === 'idle', `${at()} quitting the terminal leaves the agent on the watch`)
+
+ // another app-server process on the thread (the desktop app's or the IDE extension's own): it can read the thread,
+ // not continue it while the hub runs it (one writer per thread)
+ const other = spawn('codex', ['app-server'], { stdio: ['pipe', 'pipe', 'ignore'], cwd })
+ const answers = new Map(); let n2 = 0
+ other.stdout.on('data', d => { for (const l of String(d).split('\n').filter(Boolean)) { try { const m = JSON.parse(l); if (m.id != null && !m.method) answers.get(m.id)?.(m) } catch {} } })
+ const ask2 = (method, params) => new Promise(r => { const i = ++n2; answers.set(i, r); other.stdin.write(JSON.stringify({ id: i, method, params }) + '\n'); setTimeout(() => r({ error: { message: 'no answer' } }), 60_000) })
+ await ask2('initialize', { clientInfo: { name: 'chums-e2e', title: null, version: '0' }, capabilities: null }); other.stdin.write('{"method":"initialized"}\n')
+ const thread = JSON.parse(fs.readFileSync(path.join(home, '.chums/agents', `${ID}.runtime.json`), 'utf8')).thread
+ const read = await ask2('thread/read', { threadId: thread, includeTurns: false }), resume = await ask2('thread/resume', { threadId: thread, excludeTurns: true })
+ other.kill()
+ ok(!read.error && /^Chums: /.test(read.result.thread.name ?? '') && /active writer/.test(resume.error?.message ?? ''),
+ `${at()} another Codex app (its own app-server) can read the thread ("${read.result?.thread?.name}") but not continue it while the hub runs it: ${resume.error?.message ?? 'it could!'}`)
+
+ // its app-server dies: the hub starts it again on the same thread, which remembers the conversation
+ const rt = JSON.parse(fs.readFileSync(path.join(home, '.chums/agents', `${ID}.runtime.json`), 'utf8'))
+ process.kill(rt.pid)
+ ok(await until('offline', async () => await status() === 'offline', 20_000), `${at()} its app-server killed, it goes offline`)
+ ok(await until('back', async () => await status() === 'idle', 60_000), `${at()} and comes back`)
+ const rt2 = JSON.parse(fs.readFileSync(path.join(home, '.chums/agents', `${ID}.runtime.json`), 'utf8'))
+ ok(rt2.thread === rt.thread && rt2.pid !== rt.pid, `${at()} on the same thread (${rt2.thread})`)
+ since = Date.now()
+ await call('/v1/say', { agent: ID, text: 'What number did you answer to my first question today?' })
+ const a5 = await newLine(since)
+ ok(a5 && /42|forty.two/i.test(a5.text), `${at()} and remembers it: "${a5?.text}"`)
+
+ // the hub itself is killed (as launchd might), leaving its app-server behind; the next hub stops that one and
+ // carries on the thread
+ hub.kill('SIGKILL')
+ await sleep(1000)
+ const alive = pid => { try { process.kill(pid, 0); return true } catch { return false } }
+ const orphan = rt2.pid, orphanWasAlive = alive(orphan)
+ ;({ cfg, home, hub, stop } = await startPrivateHub({ home, logFile, env: { CHUMS_RUNTIME_DEBUG: '1' } }))
+ ok(await until('back after the hub', async () => await status() === 'idle', 60_000), `${at()} a new hub on the same folder brings it back`)
+ const rt3 = JSON.parse(fs.readFileSync(path.join(home, '.chums/agents', `${ID}.runtime.json`), 'utf8'))
+ ok(orphanWasAlive && !alive(orphan) && rt3.thread === rt.thread, `${at()} the app-server the killed hub left (pid ${orphan}) is stopped, the thread is the same`)
+ since = Date.now()
+ await call('/v1/say', { agent: ID, text: 'What file did you create with apply_patch earlier? Just the name.' })
+ const a6 = await newLine(since)
+ ok(a6 && /notes/i.test(a6.text), `${at()} and remembers: "${a6?.text}"`)
+}
+
+await sleep(1000)
+watching = false
+ok(toolsSeen.some(t => t.type === 'bash' || t.type === 'test'), `tool calls were events: ${toolsSeen.map(t => `${t.text}${t.ok === false ? ' ✗' : ''}`).join(' | ')}`)
+ok(seen.includes('working') && seen.includes('waiting') && seen.at(-1) === 'idle', `statuses on the watch: ${seen.join(' → ')}`)
+const log = fs.readFileSync(logFile, 'utf8')
+const viaTool = (log.match(/reply <- e2e/g) ?? []).length, spokenFor = (log.match(/spoken for e2e/g) ?? []).length
+console.log(`replies: ${viaTool} spoken, ${viaTool - spokenFor} by chums_reply, ${spokenFor} from the final message`)
+console.log(`agent log: ${path.join(home, '.chums/agents', `${ID}.host.log`)}`)
+console.log(fs.readFileSync(path.join(home, '.chums/agents', `${ID}.host.log`), 'utf8').split('\n').slice(-12).join('\n'))
+console.log(fails ? `${fails} FAILED` : 'all passed', `(${at()})`)
+const sessionId = JSON.parse(fs.readFileSync(path.join(home, '.chums/agents.json'), 'utf8'))[0].sessionId
+stop()
+// a test's thread shouldn't stay in your Codex history (archived, not deleted: `codex unarchive <id>` brings it back)
+if (agent.runtime === 'codex' && sessionId && !process.env.CHUMS_E2E_KEEP) { await sleep(1500); spawn('codex', ['archive', sessionId], { stdio: 'ignore' }).on('close', c => { console.log(`archived its thread ${sessionId}${c ? ` (codex archive exited ${c})` : ''}`); process.exit(fails ? 1 : 0) }) }
+else process.exit(fails ? 1 : 0)
diff --git a/tools/e2e-watch.py b/tools/e2e-watch.py
new file mode 100644
index 0000000..53bd6d0
--- /dev/null
+++ b/tools/e2e-watch.py
@@ -0,0 +1,63 @@
+"""Live test for the watch: a real Claude Code session does real work (reads, edits, runs tests) while the
+watch app shows it. Answers the Bash approval "from the watch" after a pause so the card can be seen.
+usage: e2e-watch.py WORKDIR"""
+import json, os, pty, re, select, sys, time, urllib.request
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+WORK = sys.argv[1]
+cfg = json.load(open(os.path.expanduser("~/.chums/config.json")))
+HUB = f"http://127.0.0.1:{cfg['port']}"
+def hub(path, body=None):
+ req = urllib.request.Request(HUB + path, data=json.dumps(body).encode() if body else None,
+ headers={"authorization": f"Bearer {cfg['token']}", "content-type": "application/json"})
+ return json.load(urllib.request.urlopen(req, timeout=30))
+
+existing = {x["id"] for x in hub("/v1/state?since=0")["sessions"]}
+pid, fd = pty.fork()
+if pid == 0:
+ os.chdir(WORK); os.environ.update(CHUMS_NO_RC="1", TERM="xterm-256color")
+ os.execvp("zsh", ["zsh", "-c", f"{ROOT}/bin/chums-claude demo --permission-mode acceptEdits"])
+screen = ""
+def pump(sec):
+ global screen
+ end = time.time() + sec
+ while time.time() < end:
+ r, _, _ = select.select([fd], [], [], 0.2)
+ if r:
+ try: screen += os.read(fd, 65536).decode(errors="ignore")
+ except OSError: return
+ screen = screen[-20000:]
+plain = lambda s: re.sub(r"\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07]*\x07", "", s)
+answered = set()
+for _ in range(40):
+ pump(1)
+ tail = plain(screen).replace(" ", "").lower()[-1500:]
+ if "itrustthisfolder" in tail and "trust" not in answered:
+ answered.add("trust"); os.write(fd, b"\x1b[B"); pump(0.3); os.write(fd, b"\r"); screen = ""; pump(2); continue
+ if ("developmentchannel" in tail or "dangerously" in tail) and "entertoconfirm" in tail and "dev" not in answered:
+ answered.add("dev")
+ if re.search(r"❯\s*(\d\.)?\s*(no|exit|cancel)", plain(screen)[-1200:], re.I): os.write(fd, b"\x1b[B"); pump(0.3)
+ os.write(fd, b"\r"); screen = ""; pump(2); continue
+ if any(s["name"] == "demo" and s["id"] not in existing for s in hub("/v1/state?since=0")["sessions"]): break
+print("session up:", any(s["name"] == "demo" for s in hub("/v1/state?since=0")["sessions"]), flush=True)
+pump(3)
+seen = {s["id"] for s in hub("/v1/state?since=0")["spoken"]}
+t0 = time.time()
+r = hub("/v1/say", {"text": "demo, read math.js and test.js, add a square function to math.js with a test for it in test.js, then run npm test with the Bash tool and tell me the result through Chums."})
+print("order:", r.get("echo"), flush=True)
+reply, approved = None, 0
+while time.time() - t0 < 240 and not reply:
+ pump(1)
+ st = hub("/v1/state?since=0")
+ if st["approvals"]:
+ a = st["approvals"][0]
+ print(f"{time.time()-t0:5.1f}s approval: {a['tool']} {a['summary']}", flush=True)
+ pump(5) # leave the card on the watch for a moment
+ print(" ->", hub("/v1/say", {"text": "yes"}).get("echo"), flush=True); approved += 1
+ reply = next((s for s in st["spoken"] if s["session"] == "demo" and s["id"] not in seen and s["kind"] != "echo"), None)
+print(f"{time.time()-t0:5.1f}s reply:", reply and reply["text"], flush=True)
+print("tools seen:", [t["text"] + ("" if t["ok"] is None else (" ✓" if t["ok"] else " ✗")) for t in hub("/v1/state?since=0")["tools"] if t["session"] == "demo"], flush=True)
+pump(8)
+os.write(fd, b"\x03"); pump(0.5); os.write(fd, b"\x03"); pump(1)
+try: os.kill(pid, 9)
+except ProcessLookupError: pass
diff --git a/tools/fake-acp-agent.mjs b/tools/fake-acp-agent.mjs
new file mode 100644
index 0000000..c000ea3
--- /dev/null
+++ b/tools/fake-acp-agent.mjs
@@ -0,0 +1,95 @@
+// A stand-in Agent Client Protocol agent for tools/test-runtimes.mjs: the hub drives it as it would `copilot --acp`.
+// What it does depends on words in the prompt (tool, approve, reply, refuse, limit, crash); it notes every request in
+// $FAKE_LOG, one JSON line each, so the test can check what the hub sent.
+import fs from 'node:fs'
+import readline from 'node:readline'
+import { spawn } from 'node:child_process'
+
+const note = o => process.env.FAKE_LOG && fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify({ agent: 'acp', ...o }) + '\n')
+const send = m => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...m }) + '\n')
+let next = 0
+const waiting = new Map()
+const ask = (method, params) => new Promise(r => { const id = next++; waiting.set(id, r); send({ id, method, params }) })
+const update = (sessionId, u) => send({ method: 'session/update', params: { sessionId, update: u } })
+const say = (sessionId, text) => { for (const part of text.match(/.{1,12}/g)) update(sessionId, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: part } }) }
+let mcp = null // the Chums MCP server the hub gave the session
+
+// the session's MCP server, spoken to the way an agent would: initialize, then tools/call
+async function callTool(server, name, args) {
+ if (!mcp) {
+ const env = Object.fromEntries((server.env ?? []).map(e => [e.name, e.value]))
+ const p = spawn(server.command, server.args, { env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'inherit'] })
+ const pending = new Map(); let id = 0
+ readline.createInterface({ input: p.stdout }).on('line', l => { const m = JSON.parse(l); pending.get(m.id)?.(m); pending.delete(m.id) })
+ const rpc = (method, params) => new Promise(r => { const i = ++id; pending.set(i, r); p.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: i, method, params }) + '\n') })
+ await rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'fake-acp', version: '0' } })
+ p.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n')
+ const tools = await rpc('tools/list', {})
+ mcp = { rpc, tools: tools.result.tools }
+ note({ mcpTools: mcp.tools.map(t => ({ name: t.name, annotations: t.annotations })) })
+ }
+ return mcp.rpc('tools/call', { name, arguments: args })
+}
+
+const sessions = new Map()
+async function prompt(id, { sessionId, prompt: blocks }) {
+ const full = blocks.map(b => b.text ?? '').join('')
+ note({ method: 'session/prompt', text: full })
+ const text = full.split('\n').pop() // his words: the last line, after instructions and soul
+ const s = sessions.get(sessionId)
+ if (/crash/.test(text)) process.exit(1)
+ if (/limit/.test(text)) return send({ id, error: { code: -32000, message: 'Rate limit exceeded. Try again in a minute.' } })
+ if (/refuse/.test(text)) return send({ id, result: { stopReason: 'refusal' } })
+ update(sessionId, { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: 'Thinking.' } })
+ if (/tool/.test(text)) {
+ update(sessionId, { sessionUpdate: 'tool_call', toolCallId: 't1', title: 'Run the tests', kind: 'execute', status: 'pending', rawInput: { command: 'npm test' } })
+ update(sessionId, { sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'in_progress' })
+ update(sessionId, { sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed', rawOutput: { content: '12 passing\n<exited with exit code 0>' } })
+ update(sessionId, { sessionUpdate: 'tool_call', toolCallId: 't2', title: 'Read package.json', kind: 'read', status: 'completed', locations: [{ path: '/tmp/x/package.json' }] })
+ say(sessionId, 'Tests pass: all `12` of them, in **3 seconds**. Here are the details of every test that ran today.')
+ }
+ if (/approve/.test(text)) {
+ const tc = { toolCallId: 'p1', title: 'Delete the build folder', kind: 'execute', status: 'pending', rawInput: { command: 'rm -rf build' } }
+ update(sessionId, { sessionUpdate: 'tool_call', ...tc })
+ const r = await ask('session/request_permission', { sessionId, toolCall: tc, options: [
+ { optionId: 'yes-once', kind: 'allow_once', name: 'Allow once' }, { optionId: 'yes-always', kind: 'allow_always', name: 'Always allow' },
+ { optionId: 'no', kind: 'reject_once', name: 'Deny' }] })
+ note({ permission: r.result?.outcome })
+ const allowed = r.result?.outcome?.optionId === 'yes-once'
+ update(sessionId, { sessionUpdate: 'tool_call_update', toolCallId: 'p1', status: allowed ? 'completed' : 'failed', content: allowed ? [] : [{ type: 'content', content: { type: 'text', text: 'denied by the user' } }] })
+ say(sessionId, allowed ? 'Deleted the build folder.' : 'Okay, I left it.')
+ }
+ if (/reply/.test(text)) {
+ // the agent asks before an MCP tool call, as Copilot does; the hub allows its own tools without a card
+ const tc = { toolCallId: 'c1', title: 'chums-chums_reply', kind: 'other', status: 'pending', rawInput: { text: 'Replied through the tool.' } }
+ update(sessionId, { sessionUpdate: 'tool_call', ...tc })
+ const r = await ask('session/request_permission', { sessionId, toolCall: tc, options: [{ optionId: 'ok', kind: 'allow_once', name: 'Allow' }, { optionId: 'no', kind: 'reject_once', name: 'Deny' }] })
+ note({ chumsPermission: r.result?.outcome })
+ const out = await callTool(s.mcpServers.find(m => m.name === 'chums'), 'chums_reply', { text: 'Replied through the tool.', status: 'done' })
+ note({ chumsReply: out.result?.content?.[0]?.text })
+ update(sessionId, { sessionUpdate: 'tool_call_update', toolCallId: 'c1', status: 'completed' })
+ say(sessionId, 'This long final message is for the Mac only and should never be spoken on the watch at all.')
+ }
+ send({ id, result: { stopReason: 'end_turn' } })
+}
+
+readline.createInterface({ input: process.stdin }).on('line', l => {
+ const m = JSON.parse(l)
+ if (m.id !== undefined && !m.method) { waiting.get(m.id)?.(m); waiting.delete(m.id); return }
+ if (m.method !== 'session/prompt') note({ method: m.method, params: m.params })
+ switch (m.method) {
+ case 'initialize':
+ return send({ id: m.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true }, agentInfo: { name: 'fake-acp', version: '1' }, authMethods: [] } })
+ case 'session/new': {
+ const sessionId = `fake-${Date.now()}`
+ sessions.set(sessionId, m.params)
+ return send({ id: m.id, result: { sessionId } })
+ }
+ case 'session/load':
+ sessions.set(m.params.sessionId, m.params)
+ say(m.params.sessionId, 'An old answer, replayed while loading.') // never news: the hub must ignore it
+ return send({ id: m.id, result: {} })
+ case 'session/prompt': return prompt(m.id, m.params)
+ default: if (m.id !== undefined) send({ id: m.id, error: { code: -32601, message: 'no' } })
+ }
+})
diff --git a/tools/fake-codex.mjs b/tools/fake-codex.mjs
new file mode 100644
index 0000000..88ace09
--- /dev/null
+++ b/tools/fake-codex.mjs
@@ -0,0 +1,164 @@
+// A stand-in `codex app-server --listen unix://…` for tools/test-runtimes.mjs: a WebSocket on a Unix socket speaking
+// the app-server's JSON-RPC. What a turn does depends on words in it (tool, approve, edit, elsewhere, limit, compact,
+// reply, steer); every request is noted in $FAKE_LOG, one JSON line each.
+import fs from 'node:fs'
+import net from 'node:net'
+import crypto from 'node:crypto'
+import readline from 'node:readline'
+import { spawn } from 'node:child_process'
+
+const args = process.argv.slice(2)
+const sock = args[args.indexOf('--listen') + 1].replace(/^unix:\/\//, '')
+const config = args.flatMap((a, i) => a === '-c' ? [args[i + 1]] : [])
+const note = o => process.env.FAKE_LOG && fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify({ agent: 'codex', ...o }) + '\n')
+note({ started: args[0], config })
+
+// the MCP server the hub configured with -c mcp_servers.chums.* (TOML values: strings, arrays, an inline table)
+function chumsServer() {
+ const get = k => config.find(c => c.startsWith(`mcp_servers.chums.${k}=`))?.slice(`mcp_servers.chums.${k}=`.length)
+ const env = Object.fromEntries([...get('env').matchAll(/(\w+) = ("(?:[^"\\]|\\.)*")/g)].map(m => [m[1], JSON.parse(m[2])]))
+ return { command: JSON.parse(get('command')), args: JSON.parse(get('args')), env }
+}
+let mcp = null
+async function chumsReply(text) {
+ if (!mcp) {
+ const s = chumsServer()
+ const p = spawn(s.command, s.args, { env: { ...process.env, ...s.env }, stdio: ['pipe', 'pipe', 'inherit'] })
+ const pending = new Map(); let id = 0
+ readline.createInterface({ input: p.stdout }).on('line', l => { const m = JSON.parse(l); pending.get(m.id)?.(m); pending.delete(m.id) })
+ mcp = (method, params) => new Promise(r => { const i = ++id; pending.set(i, r); p.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: i, method, params }) + '\n') })
+ await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'fake-codex', version: '0' } })
+ p.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n')
+ }
+ return mcp('tools/call', { name: 'chums_reply', arguments: { text, status: 'done' } })
+}
+
+// ---- a WebSocket server, the few parts of it the hub's client uses ----
+function serve(conn, onMessage) {
+ let buf = Buffer.alloc(0), open = false
+ const out = text => {
+ const data = Buffer.from(text), n = data.length
+ const head = n < 126 ? Buffer.from([0x81, n]) : n < 65536 ? Buffer.from([0x81, 126, n >> 8, n & 255])
+ : Buffer.concat([Buffer.from([0x81, 127]), (() => { const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(n)); return b })()])
+ conn.write(Buffer.concat([head, data]))
+ }
+ conn.on('data', d => {
+ buf = Buffer.concat([buf, d])
+ if (!open) {
+ const end = buf.indexOf('\r\n\r\n'); if (end < 0) return
+ const key = buf.subarray(0, end).toString().match(/Sec-WebSocket-Key: (\S+)/i)[1]
+ const accept = crypto.createHash('sha1').update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64')
+ conn.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`)
+ buf = buf.subarray(end + 4); open = true
+ }
+ while (buf.length >= 2) {
+ let n = buf[1] & 127, off = 2
+ if (n === 126) { n = buf.readUInt16BE(2); off = 4 } else if (n === 127) { n = Number(buf.readBigUInt64BE(2)); off = 10 }
+ if (buf.length < off + 4 + n) return
+ const mask = buf.subarray(off, off + 4), data = Buffer.from(buf.subarray(off + 4, off + 4 + n))
+ for (let i = 0; i < n; i++) data[i] ^= mask[i & 3]
+ const op = buf[0] & 15
+ buf = buf.subarray(off + 4 + n)
+ if (op === 8) { conn.end(); return }
+ if (op === 1) onMessage(JSON.parse(data.toString()))
+ }
+ })
+ return m => out(JSON.stringify(m))
+}
+
+let thread = null, turnN = 0, active = null, steered = null
+const known = new Set(['thr-known'])
+const server = net.createServer(conn => {
+ let nextId = 0
+ const waiting = new Map()
+ const send = serve(conn, m => handle(m))
+ const notify = (method, params) => send({ method, params })
+ const ask = (method, params) => new Promise(r => { const id = nextId++; waiting.set(id, r); send({ id, method, params }) })
+ const item = (kind, it) => notify(`item/${kind}`, { item: it, threadId: thread.id, turnId: active, [kind === 'started' ? 'startedAtMs' : 'completedAtMs']: Date.now() })
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
+ const message = text => { const it = { type: 'agentMessage', id: `m${Math.random()}`, text, phase: 'final_answer' }; item('started', { ...it, text: '' }); item('completed', it) }
+ const done = (status = 'completed', error = null) => { notify('turn/completed', { threadId: thread.id, turn: { id: active, items: [], status, error } }); active = null }
+
+ async function turn(text) {
+ if (/limit/.test(text)) return done('failed', { message: 'You hit your usage limit.', codexErrorInfo: 'usageLimitExceeded' })
+ if (/tool/.test(text)) {
+ const cmd = { type: 'commandExecution', id: 'c1', command: "/bin/zsh -lc 'npm test'", cwd: '/tmp', status: 'inProgress', commandActions: [{ type: 'unknown', command: 'npm test' }], exitCode: null }
+ item('started', cmd); await sleep(50); item('completed', { ...cmd, status: 'completed', exitCode: 0 })
+ const rd = { type: 'commandExecution', id: 'c2', command: "/bin/zsh -lc 'cat package.json'", cwd: '/tmp', status: 'inProgress', commandActions: [{ type: 'read', command: 'cat package.json', name: 'package.json', path: '/tmp/x/package.json' }] }
+ item('started', rd); item('completed', { ...rd, status: 'completed', exitCode: 0 })
+ message('All tests pass. Twelve of them, in three seconds.')
+ }
+ if (/approve/.test(text)) {
+ const cmd = { type: 'commandExecution', id: 'c3', command: "/bin/zsh -lc 'rm -rf build'", status: 'inProgress', commandActions: [{ type: 'unknown', command: 'rm -rf build' }] }
+ item('started', cmd)
+ const r = await ask('item/commandExecution/requestApproval', { kind: 'command', threadId: thread.id, turnId: active, itemId: 'c3', command: cmd.command, commandActions: cmd.commandActions, reason: null })
+ note({ decision: r.result?.decision })
+ const ok = r.result?.decision === 'accept'
+ item('completed', { ...cmd, status: ok ? 'completed' : 'declined', exitCode: ok ? 0 : null })
+ message(ok ? 'Deleted it.' : 'Left it alone.')
+ }
+ if (/edit/.test(text)) {
+ const fc = { type: 'fileChange', id: 'f1', changes: [{ path: '/tmp/x/a.js', kind: { type: 'update', move_path: null }, diff: '' }], status: 'inProgress' }
+ item('started', fc)
+ const r = await ask('item/fileChange/requestApproval', { threadId: thread.id, turnId: active, itemId: 'f1', reason: null })
+ note({ fileDecision: r.result?.decision })
+ item('completed', { ...fc, status: r.result?.decision === 'accept' ? 'completed' : 'declined' })
+ message('Done with the edit.')
+ }
+ if (/elsewhere/.test(text)) {
+ // a Codex terminal on the same thread answers first: the hub hears serverRequest/resolved and drops its card
+ const id = nextId++
+ send({ id, method: 'item/commandExecution/requestApproval', params: { kind: 'command', threadId: thread.id, turnId: active, itemId: 'c4', command: 'make deploy', commandActions: [{ type: 'unknown', command: 'make deploy' }] } })
+ await sleep(Number(process.env.FAKE_ELSEWHERE_MS ?? 1500))
+ notify('serverRequest/resolved', { threadId: thread.id, requestId: id })
+ message('Deployed.')
+ }
+ if (/compact/.test(text)) {
+ item('started', { type: 'contextCompaction', id: 'k1' }); await sleep(50); item('completed', { type: 'contextCompaction', id: 'k1' })
+ message('Compacted and carried on.')
+ }
+ if (/reply/.test(text)) {
+ const r = await chumsReply('Codex replied by tool.')
+ note({ chumsReply: r.result?.content?.[0]?.text })
+ item('started', { type: 'mcpToolCall', id: 'x1', server: 'chums', tool: 'chums_reply', status: 'inProgress', arguments: {} })
+ item('completed', { type: 'mcpToolCall', id: 'x1', server: 'chums', tool: 'chums_reply', status: 'completed', arguments: {} })
+ message('A long final message that stays on the Mac, because the agent already spoke on the watch.')
+ }
+ if (/steer/.test(text)) {
+ await new Promise(r => { steered = r }) // waits for turn/steer
+ message('Steered.')
+ }
+ done()
+ }
+
+ async function handle(m) {
+ if (m.id !== undefined && !m.method) { waiting.get(m.id)?.(m); waiting.delete(m.id); return }
+ if (m.method !== 'initialized') note({ method: m.method, params: m.params })
+ const reply = result => send({ id: m.id, result })
+ switch (m.method) {
+ case 'initialize': return reply({ userAgent: 'fake-codex/0', codexHome: '/tmp', platformFamily: 'unix', platformOs: 'macos' })
+ case 'initialized': return
+ case 'thread/start':
+ thread = { id: `thr-${Date.now()}`, status: { type: 'idle' } }
+ return reply({ thread, model: m.params.model ?? 'fake' })
+ case 'thread/resume':
+ if (!known.has(m.params.threadId) && m.params.threadId !== thread?.id) return send({ id: m.id, error: { code: -32600, message: `no rollout found for thread id ${m.params.threadId}` } })
+ thread = { id: m.params.threadId, status: { type: 'idle' } }
+ return reply({ thread })
+ case 'turn/start': {
+ active = `turn-${++turnN}`
+ reply({ turn: { id: active, items: [], status: 'inProgress', error: null } })
+ notify('turn/started', { threadId: thread.id, turn: { id: active, items: [], status: 'inProgress' } })
+ return turn(m.params.input.map(i => i.text).join('').split('\n').pop()) // his words: the last line
+ }
+ case 'thread/name/set': return reply({})
+ case 'turn/steer':
+ if (m.params.expectedTurnId !== active) return send({ id: m.id, error: { code: -32600, message: 'no such turn' } })
+ reply({ turnId: active }); steered?.(); steered = null; return
+ default: return send({ id: m.id, error: { code: -32601, message: `no ${m.method}` } })
+ }
+ }
+})
+fs.rmSync(sock, { force: true })
+server.listen(sock)
+process.on('SIGTERM', () => { server.close(); process.exit(0) })
diff --git a/tools/gen-config.sh b/tools/gen-config.sh
new file mode 100755
index 0000000..22c4859
--- /dev/null
+++ b/tools/gen-config.sh
@@ -0,0 +1,30 @@
+#!/bin/zsh
+# Writes app/ChumsWatch/HubConfig.swift from ~/.chums/config.json: the hub's public address, the watch's token and a
+# build stamp. bin/chums-install runs it. The generated file is git-ignored (it holds the token).
+ROOT="${0:A:h:h}"
+[[ -f ~/.chums/config.json ]] || { echo "no ~/.chums/config.json yet: start the hub once (bin/chums-hub), it writes one" >&2; exit 1 }
+python3 - "$ROOT" <<'EOF'
+import json, os, subprocess, sys
+root = sys.argv[1]
+cfg = json.load(open(os.path.expanduser("~/.chums/config.json")))
+# The watch reaches the Mac only through its public https address (bin/chums-tunnel, cfg "publicURL"): watchOS doesn't
+# support apps reaching a home-network address, and probing one on other networks would hand the token to whoever has
+# that address. 127.0.0.1 is for the Simulator (the app drops it on a real watch).
+hosts = [h for h in (cfg.get('publicURL'), f"http://127.0.0.1:{cfg['port']}") if h]
+if not cfg.get('publicURL'): print("no publicURL yet: run bin/chums-tunnel first, or the watch can only reach the Simulator's hub")
+import datetime
+build = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
+out = os.path.join(root, "app/ChumsWatch/HubConfig.swift")
+# it holds the watch's token: readable by this user only
+with os.fdopen(os.open(out, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
+ os.fchmod(f.fileno(), 0o600)
+ f.write("// Generated by tools/gen-config.sh. Do not commit.\n")
+ f.write("enum HubConfig {\n")
+ f.write(f" static let hosts = {json.dumps(hosts)}\n")
+ f.write(f" static let token = {json.dumps(cfg['watchToken'])} // the watch's own token: the watch API only\n")
+ f.write(f" static let build = {json.dumps(build)}\n")
+ # the watch's frame rate and memory in the hub's log every 30 s: for working on the app, off unless asked for
+ f.write(f" static let diagnostics = {'true' if cfg.get('diagnostics') else 'false'}\n")
+ f.write("}\n")
+print("wrote", out, hosts)
+EOF
diff --git a/tools/heics.swift b/tools/heics.swift
new file mode 100644
index 0000000..bcc29fb
--- /dev/null
+++ b/tools/heics.swift
@@ -0,0 +1,20 @@
+import Foundation
+import ImageIO
+import UniformTypeIdentifiers
+import CoreGraphics
+// make a HEIC image sequence from PNG frames, then time decoding each frame
+let args = CommandLine.arguments, dir = args[1], clip = args[2], out = args[3], q = Double(args[4])!
+var urls: [URL] = []; var i = 0
+while FileManager.default.fileExists(atPath: "\(dir)/\(clip)_\(String(format: "%03d", i)).png") { urls.append(URL(fileURLWithPath: "\(dir)/\(clip)_\(String(format: "%03d", i)).png")); i += 1 }
+let type = (args.count > 5 ? args[5] : "public.heics") as CFString
+guard let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: out) as CFURL, type, urls.count, nil) else { print("no dest for", type); exit(1) }
+for u in urls {
+ let src = CGImageSourceCreateWithURL(u as CFURL, nil)!, im = CGImageSourceCreateImageAtIndex(src, 0, nil)!
+ CGImageDestinationAddImage(dest, im, [kCGImageDestinationLossyCompressionQuality: q] as CFDictionary)
+}
+print("finalize", CGImageDestinationFinalize(dest))
+let size = (try! FileManager.default.attributesOfItem(atPath: out)[.size] as! Int)
+let src = CGImageSourceCreateWithURL(URL(fileURLWithPath: out) as CFURL, nil)!
+let n = CGImageSourceGetCount(src), t0 = Date()
+for k in 0..<n { let im = CGImageSourceCreateImageAtIndex(src, k, [kCGImageSourceShouldCacheImmediately: true] as CFDictionary)!; _ = im.width }
+print("\(urls.count) frames -> \(size / 1024) KB (\(size / urls.count / 1024) KB/frame), \(n) decodable, \(String(format: "%.1f", Date().timeIntervalSince(t0) / Double(n) * 1000)) ms/frame on this Mac")
diff --git a/tools/kokoro-requirements.txt b/tools/kokoro-requirements.txt
new file mode 100644
index 0000000..1f3e372
--- /dev/null
+++ b/tools/kokoro-requirements.txt
@@ -0,0 +1,8 @@
+# The agents' voices (tools/kokoro-server.py): Kokoro on Apple Silicon through MLX. bin/chums-setup installs these
+# into ~/.chums/kokoro/.venv (Python 3.12, with uv). Versions tested together.
+mlx-audio==0.5.8
+mlx==0.32.3
+misaki[en]==0.9.4
+numpy==2.5.4
+# the English text processor's language model (installed here, not downloaded on first use)
+en_core_web_sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl
diff --git a/tools/kokoro-server.py b/tools/kokoro-server.py
new file mode 100644
index 0000000..c66255c
--- /dev/null
+++ b/tools/kokoro-server.py
@@ -0,0 +1,147 @@
+"""The agents' voices: Kokoro (82M, Apache-2.0) on the Mac's GPU through MLX, for the hub only (127.0.0.1).
+
+ ~/.chums/kokoro/.venv/bin/python tools/kokoro-server.py --port 50062 --voices bf_lily,am_santa,...
+
+It loads the model once and says a word in each voice it's given (so the first reply in a voice is as quick as any),
+then answers POST /speak {"text": "...", "voice": "bf_lily", "speed": 1.0} with the speech as AAC in an .m4a (what the
+watch plays), about 0.15 s for a one-sentence reply on an M-series Mac. GET /health says it's ready. One at a time:
+MLX runs on one GPU queue, and replies are short. bin/chums-setup installs it (tools/kokoro-requirements.txt).
+"""
+import argparse
+import ctypes
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import wave
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import numpy as np
+
+p = argparse.ArgumentParser()
+p.add_argument('--port', type=int, default=50062)
+p.add_argument('--voices', default='bf_lily')
+p.add_argument('--model', default='mlx-community/Kokoro-82M-bf16')
+p.add_argument('--once', action='store_true', help='download what it needs, say a sentence in each voice, and exit (bin/chums-setup)')
+a = p.parse_args()
+
+t0 = time.time()
+from mlx_audio.tts.utils import load_model # noqa: E402 (after argparse: --help stays fast)
+
+model = load_model(a.model)
+lock = threading.Lock()
+RATE = 24000
+
+
+_libc = ctypes.CDLL('/usr/lib/libSystem.dylib')
+
+
+def interactive():
+ """This thread runs at user-interactive priority: after a quiet while a render takes about half as long."""
+ _libc.pthread_set_qos_class_self_np(0x21, 0) # QOS_CLASS_USER_INTERACTIVE
+
+
+def speak(text, voice, speed=1.0):
+ """Float samples at 24 kHz. The voice's first letter is its language: a American English, b British."""
+ with lock:
+ parts = [np.array(r.audio) for r in model.generate(text=text, voice=voice, speed=speed, lang_code=voice[0])]
+ return np.concatenate(parts) if parts else np.zeros(0, dtype=np.float32)
+
+
+TARGET_RMS = 10 ** (-16 / 20) # -16 dBFS: a bit louder than Apple's own speech (-19.6), for the watch's small speaker
+LIMIT, CEIL = 0.62, 0.86 # above LIMIT, peaks are rounded off smoothly up to CEIL (-1.3 dBFS: AAC overshoots)
+
+
+def loud(x):
+ """Every voice as loud as the others, and louder than Kokoro makes them (-22 to -27 dBFS): gain to the target
+ level, then a soft limiter on the few peaks that would clip."""
+ rms = float(np.sqrt(np.mean(x ** 2))) if len(x) else 0.0
+ if rms < 1e-5:
+ return x
+ y = x * (TARGET_RMS / rms)
+ over = np.abs(y) > LIMIT
+ y[over] = np.sign(y[over]) * (LIMIT + (CEIL - LIMIT) * np.tanh((np.abs(y[over]) - LIMIT) / (CEIL - LIMIT)))
+ return y
+
+
+def m4a(samples):
+ """AAC in an .m4a, the way the watch plays it (about 20 KB for a sentence, encoded in about 30 ms)."""
+ pcm = (np.clip(loud(samples), -1, 1) * 32767).astype('<i2').tobytes()
+ with tempfile.TemporaryDirectory() as d:
+ wav, out = os.path.join(d, 's.wav'), os.path.join(d, 's.m4a')
+ with wave.open(wav, 'wb') as w:
+ w.setnchannels(1); w.setsampwidth(2); w.setframerate(RATE); w.writeframes(pcm)
+ subprocess.run(['/usr/bin/afconvert', '-f', 'm4af', '-d', 'aac', '-b', '32000', wav, out], check=True)
+ with open(out, 'rb') as f:
+ return f.read()
+
+
+ready = False
+# Kokoro's English voices (a American, b British): "--voices english" is all of them (bin/chums-setup downloads them
+# all, so any one can be picked on the watch while the hub runs offline)
+ENGLISH = ('af_heart af_bella af_nicole af_aoede af_kore af_sarah af_alloy af_nova af_sky af_jessica af_river am_fenrir '
+ 'am_michael am_puck am_echo am_eric am_liam am_onyx am_santa am_adam bf_emma bf_isabella bf_alice bf_lily '
+ 'bm_fable bm_george bm_lewis bm_daniel').split()
+voices = ENGLISH if a.voices == 'english' else [v for v in a.voices.split(',') if v]
+
+
+def warm():
+ global ready
+ interactive()
+ for v in voices:
+ try:
+ speak("I'm ready when you are. Tell me what you need.", v) # a full sentence: the first real one isn't slower
+ except Exception as e: # a voice that won't load is skipped, the others still work
+ print(f'kokoro: voice {v} failed to warm: {e}', file=sys.stderr, flush=True)
+ ready = True
+ print(f'kokoro: ready in {time.time() - t0:.1f} s with {", ".join(voices)}', file=sys.stderr, flush=True)
+
+
+class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def reply(self, code, body, kind='application/json'):
+ self.send_response(code)
+ self.send_header('content-type', kind)
+ self.send_header('content-length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ if self.path == '/health':
+ return self.reply(200 if ready else 503, json.dumps({'ready': ready, 'voices': voices}).encode())
+ self.reply(404, b'{}')
+
+ def do_POST(self):
+ interactive()
+ if self.path != '/speak':
+ return self.reply(404, b'{}')
+ try:
+ q = json.loads(self.rfile.read(int(self.headers.get('content-length', 0))) or b'{}')
+ text, voice = str(q.get('text', '')).strip(), str(q.get('voice') or voices[0])
+ if not text:
+ return self.reply(400, b'{"error":"no text"}')
+ t = time.time()
+ samples = speak(text, voice, float(q.get('speed', 1.0)))
+ gen = time.time() - t
+ body = m4a(samples)
+ self.send_response(200)
+ self.send_header('content-type', 'audio/mp4')
+ self.send_header('content-length', str(len(body)))
+ self.send_header('x-kokoro-ms', f'{gen * 1000:.0f}')
+ self.send_header('x-audio-seconds', f'{len(samples) / RATE:.2f}')
+ self.end_headers()
+ self.wfile.write(body)
+ except Exception as e:
+ self.reply(500, json.dumps({'error': str(e)}).encode())
+
+
+if a.once:
+ warm()
+ sys.exit(0)
+threading.Thread(target=warm, daemon=True).start()
+ThreadingHTTPServer(('127.0.0.1', a.port), Handler).serve_forever()
diff --git a/tools/mac-app/build.zsh b/tools/mac-app/build.zsh
new file mode 100755
index 0000000..1476c00
--- /dev/null
+++ b/tools/mac-app/build.zsh
@@ -0,0 +1,110 @@
+#!/bin/zsh
+# Builds ~/Applications/Chums.app (the Mac side's one identity for permissions, and the window that asks for them; see
+# main.swift) when it's missing or its source or signing identity changed, and prints the path of its executable.
+# tools/mac-app/build.zsh [--force]
+# tools/mac-app/build.zsh --expected-stamp what an up-to-date Chums.app's stamp is (builds nothing)
+# Signing: your Apple Development certificate for the configured team (the free Personal Team's works too) keeps the
+# same identity across rebuilds and the yearly certificate renewal, so permissions stay. With no certificate, ad hoc:
+# macOS ties permissions to that exact build, and a rebuild has to be allowed again (it says so).
+set -e
+HERE="${0:A:h}"
+source "$HERE/../common.zsh"
+APP=${CHUMS_MAC_APP:-$HOME/Applications/Chums.app}
+EXE="$APP/Contents/MacOS/Chums"
+BUNDLE=${CHUMS_BUNDLE:-$(chums_cfg bundleId)}; BUNDLE="${BUNDLE:-dev.chums}.mac"
+TEAM=${CHUMS_TEAM:-$(chums_cfg team)}
+# none set: the team bin/chums-install signs the apps with (else ad hoc, and macOS asks again after every rebuild)
+[[ -z $TEAM ]] && TEAM=$(python3 "$HERE/../pick-team.py" 2>/dev/null) || true
+ID=""
+if [[ -n $TEAM ]]; then
+ for h in $(security find-identity -v -p codesigning | awk '/Apple Development/{print $2}'); do
+ ou=$(security find-certificate -a -Z -p 2>/dev/null | awk -v h=$h 'BEGIN{p=0} /^SHA-1 hash:/{p=($3==h)} p' \
+ | openssl x509 -noout -subject 2>/dev/null | sed -n 's/.*OU *= *\([A-Z0-9]*\).*/\1/p')
+ [[ $ou == $TEAM ]] && { ID=$h; break }
+ done
+fi
+SRC=$(cat "$HERE/main.swift" "$HERE/build.zsh" | shasum | cut -c1-16)-$BUNDLE
+STAMP=$SRC-${ID:-adhoc}
+[[ $1 == --expected-stamp ]] && { print -- $STAMP; exit 0 }
+
+OLD=$(cat "$APP/Contents/Resources/stamp" 2>/dev/null || true)
+if [[ $1 != --force && -x $EXE && $OLD == $STAMP ]]; then
+ print -- $EXE; exit 0
+fi
+chums_need xcrun "Install Xcode or its command line tools: xcode-select --install"
+TMP=$(mktemp -d -t chums-app); trap 'rm -rf "${TMP:?}"' EXIT
+B="$TMP/Chums.app"; mkdir -p "$B/Contents/MacOS" "$B/Contents/Resources"
+for arch in arm64 x86_64; do
+ xcrun swiftc -O -target $arch-apple-macos13 -o "$TMP/Chums-$arch" "$HERE/main.swift"
+done
+lipo -create "$TMP/Chums-arm64" "$TMP/Chums-x86_64" -output "$B/Contents/MacOS/Chums"
+
+# the icon: Noodle (the public watch app's icon; in this repo the overlay has it, in the public one the app does)
+ICON=""
+for d in "$CHUMS_ROOT"/tools/public-overlay/app "$CHUMS_ROOT"/app; do
+ ICON=$(print -l "$d"/ChumsWatch/Assets.xcassets/AppIcon.appiconset/*.png(N) | head -1); [[ -n $ICON ]] && break
+done
+if [[ -n $ICON ]]; then
+ IS="$TMP/Chums.iconset"; mkdir -p "$IS"
+ for s in 16 32 128 256 512; do
+ sips -z $s $s "$ICON" --out "$IS/icon_${s}x${s}.png" >/dev/null
+ sips -z $((s*2)) $((s*2)) "$ICON" --out "$IS/icon_${s}x${s}@2x.png" >/dev/null
+ done
+ iconutil -c icns "$IS" -o "$B/Contents/Resources/Chums.icns"
+fi
+
+# a reason line for everything an agent may touch: with no reason, macOS can refuse without showing a dialog at all
+WHY="Your Chums agents do this on your Mac when you ask them to from the watch."
+keys=(NSAppleEventsUsageDescription NSDesktopFolderUsageDescription NSDocumentsFolderUsageDescription
+ NSDownloadsFolderUsageDescription NSRemovableVolumesUsageDescription NSNetworkVolumesUsageDescription
+ NSFileProviderDomainUsageDescription NSLocalNetworkUsageDescription NSContactsUsageDescription
+ NSCalendarsUsageDescription NSCalendarsFullAccessUsageDescription NSRemindersUsageDescription
+ NSRemindersFullAccessUsageDescription NSPhotoLibraryUsageDescription NSSystemAdministrationUsageDescription
+ NSBluetoothAlwaysUsageDescription NSMicrophoneUsageDescription NSCameraUsageDescription)
+reasons=""
+for k in $keys; do reasons+=" <key>$k</key><string>$WHY</string>"$'\n'; done
+cat > "$B/Contents/Info.plist" <<PL
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+ <key>CFBundleIdentifier</key><string>$BUNDLE</string>
+ <key>CFBundleName</key><string>Chums</string>
+ <key>CFBundleDisplayName</key><string>Chums</string>
+ <key>CFBundleExecutable</key><string>Chums</string>
+ <key>CFBundleIconFile</key><string>Chums</string>
+ <key>CFBundlePackageType</key><string>APPL</string>
+ <key>CFBundleShortVersionString</key><string>1.0</string>
+ <key>CFBundleVersion</key><string>1</string>
+ <key>LSMinimumSystemVersion</key><string>13.0</string>
+ <key>LSUIElement</key><true/>
+ <key>NSHighResolutionCapable</key><true/>
+$reasons</dict></plist>
+PL
+
+# the stamp says which identity actually signed it (a locked keychain falls back to ad hoc)
+sign() { print -- "$SRC-$1" > "$B/Contents/Resources/stamp"; codesign --force --timestamp=none -s "$2" "$B" >/dev/null 2>&1 }
+if [[ -n $ID ]] && sign $ID $ID; then NEW=$ID; else sign adhoc - || chums_die "codesign failed"; NEW=adhoc; fi
+
+# a new identity means macOS sees a new app: what was allowed has to be allowed again
+if [[ -n $OLD && ${OLD##*-} != $NEW ]]; then
+ print -u2 -- "chums: Chums.app is signed with a new identity ($([[ $NEW == adhoc ]] && print ad hoc || print your Apple Development certificate)): open Chums and click Allow All again."
+elif [[ -n $OLD && $NEW == adhoc && $OLD != "$SRC-adhoc" ]]; then
+ print -u2 -- "chums: Chums.app was rebuilt and is signed ad hoc: open Chums and click Allow All again."
+fi
+
+# swap in place: a LaunchAgent restarting meanwhile always finds an executable
+mkdir -p "${APP:h}"
+NEXT="${APP:h}/.Chums.app.new"; PREV="${APP:h}/.Chums.app.old"
+rm -rf "${NEXT:?}" "${PREV:?}"; ditto "$B" "$NEXT"
+[[ -d $APP ]] && mv "$APP" "$PREV"
+mv "$NEXT" "$APP"; rm -rf "${PREV:?}"
+# System Settings lists an app's permissions only if LaunchServices knows where the app is: tell it, every build
+/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f -R -trusted "$APP" 2>/dev/null || true
+# what runs through the old Chums starts again through the new one (macOS checks a running program against its file);
+# bin/chums-setup and bin/chums-agents reload theirs anyway and set CHUMS_NO_RESTART
+if [[ -n $OLD && -z $CHUMS_NO_RESTART ]]; then
+ for f in ~/Library/LaunchAgents/$CHUMS_LABEL_PREFIX.{hub,tailscaled}.plist(N) ~/Library/LaunchAgents/$CHUMS_LABEL_PREFIX.agent.*.plist(N); do
+ launchctl kickstart -k gui/$(id -u)/${${f:t}%.plist} 2>/dev/null && print -u2 -- "chums: restarted ${${f:t}%.plist} on the new Chums.app"
+ done
+fi
+print -- $EXE
diff --git a/tools/mac-app/main.swift b/tools/mac-app/main.swift
new file mode 100644
index 0000000..8c7e60e
--- /dev/null
+++ b/tools/mac-app/main.swift
@@ -0,0 +1,503 @@
+// Chums.app: the Mac side's one identity for permissions.
+//
+// Open it (double-click) a window that asks macOS for everything the agents need, once: Allow All
+// Chums <program> [args...] runs the program (the hub, an agent) as Chums: what it and everything it starts
+// ask for (files, screenshots, accessibility, controlling apps) belongs to Chums
+// Chums --check <what> [--ask] what's granted (bin/chums-permissions check, bin/chums-doctor); see check()
+//
+// macOS charges a permission to the "responsible" process. An app opened from Finder or started by launchd is
+// responsible for itself and what it starts; a program started from a terminal belongs to the terminal. So with
+// arguments, Chums first starts a copy of itself that disclaims its parent, and that copy runs the program. Both pass
+// SIGTERM, SIGINT, SIGHUP and SIGQUIT on and exit the way the program exited (launchd's KeepAlive and bootout work).
+import AppKit
+import ApplicationServices
+import CoreGraphics
+import Darwin
+import ScreenCaptureKit
+import SwiftUI
+
+// MARK: - running a program as Chums
+
+var childPID: pid_t = 0
+func passOn(_ sig: Int32) { if childPID > 0 { kill(childPID, sig) } }
+
+func spawn(_ argv: [String], disclaimingParent: Bool) -> Int32 {
+ var attr: posix_spawnattr_t?
+ posix_spawnattr_init(&attr)
+ defer { posix_spawnattr_destroy(&attr) }
+ var none = sigset_t()
+ posix_spawnattr_setsigmask(&attr, &none)
+ posix_spawnattr_setflags(&attr, Int16(POSIX_SPAWN_SETSIGMASK))
+ if disclaimingParent {
+ // responsibility_spawnattrs_setdisclaim: in libsystem since macOS 10.14, not in the public headers
+ typealias Disclaim = @convention(c) (UnsafeMutablePointer<posix_spawnattr_t?>, Int32) -> Int32
+ if let sym = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "responsibility_spawnattrs_setdisclaim") {
+ _ = unsafeBitCast(sym, to: Disclaim.self)(&attr, 1)
+ } else {
+ FileHandle.standardError.write("Chums: can't disclaim; permissions will go to the parent\n".data(using: .utf8)!)
+ }
+ }
+ var cargs: [UnsafeMutablePointer<CChar>?] = argv.map { strdup($0) } + [nil]
+ defer { cargs.forEach { free($0) } }
+ let err = posix_spawnp(&childPID, cargs[0], nil, &attr, &cargs, environ)
+ if err != 0 {
+ FileHandle.standardError.write("Chums: can't start \(argv[0]): \(String(cString: strerror(err)))\n".data(using: .utf8)!)
+ return 127
+ }
+ var status: Int32 = 0
+ while waitpid(childPID, &status, 0) < 0 && errno == EINTR {}
+ let sig = status & 0x7f
+ return sig == 0 ? (status >> 8) & 0xff : 128 + sig
+}
+
+// MARK: - what's granted
+
+let home = FileManager.default.homeDirectoryForCurrentUser
+let controlled: [(id: String, name: String)] = [
+ ("com.apple.finder", "Finder"), ("com.apple.systemevents", "System Events"), ("com.apple.Safari", "Safari"),
+ ("com.google.Chrome", "Google Chrome"), ("com.apple.mail", "Mail"), ("com.apple.iCal", "Calendar"),
+ ("com.apple.reminders", "Reminders"), ("com.apple.Notes", "Notes"), ("com.apple.MobileSMS", "Messages"),
+ ("com.apple.Music", "Music"), ("com.apple.Terminal", "Terminal"), ("com.apple.AddressBook", "Contacts"),
+ ("com.openai.sky.CUAService", "Codex Computer Use"),
+]
+/// an app with no window (System Events, Codex Computer Use): opening it to ask shows nothing, so Chums does
+func windowless(_ id: String) -> Bool {
+ guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: id), let info = Bundle(url: url)?.infoDictionary else { return false }
+ return (info["LSUIElement"] as? Bool) == true || (info["LSBackgroundOnly"] as? Bool) == true
+ || (info["LSUIElement"] as? String) == "1" || (info["LSBackgroundOnly"] as? String) == "1"
+}
+func installed(_ id: String) -> Bool { NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) != nil }
+
+func fullDiskAccess() -> Bool {
+ (try? FileManager.default.contentsOfDirectory(atPath: home.appendingPathComponent("Library/Safari").path)) != nil
+}
+func screenRecording() -> Bool { CGPreflightScreenCaptureAccess() }
+func accessibility(ask: Bool = false) -> Bool {
+ AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: ask] as CFDictionary)
+}
+/// granted, denied, not-asked or not-running (asking needs the app running)
+func automation(_ id: String, ask: Bool = false) -> String {
+ var target = AEAddressDesc()
+ let status: OSStatus = id.withCString { p in
+ _ = AECreateDesc(typeApplicationBundleID, p, strlen(p), &target)
+ defer { AEDisposeDesc(&target) }
+ return AEDeterminePermissionToAutomateTarget(&target, typeWildCard, typeWildCard, ask)
+ }
+ switch status {
+ case noErr: return "granted"
+ case OSStatus(errAEEventNotPermitted): return "denied"
+ case OSStatus(errAEEventWouldRequireUserConsent): return "not-asked"
+ case OSStatus(procNotFound): return "not-running"
+ default: return "unknown(\(status))"
+ }
+}
+/// reading the folder is what asks ("Chums would like to access files in your Desktop folder")
+func folder(_ name: String) -> Bool {
+ (try? FileManager.default.contentsOfDirectory(atPath: home.appendingPathComponent(name).path)) != nil
+}
+
+func check(_ args: [String]) -> Int32 {
+ let ask = args.contains("--ask")
+ let word: String
+ switch args.first {
+ case "fda": word = fullDiskAccess() ? "granted" : "denied"
+ case "screen": word = screenRecording() ? "granted" : "denied"
+ case "accessibility": word = accessibility(ask: ask) ? "granted" : "denied"
+ case "automation" where args.count > 1: word = automation(args[1], ask: ask)
+ case "apps":
+ // each installed app in the list: granted, denied, not-asked, or not-open (macOS can't tell until it is)
+ for app in controlled where installed(app.id) {
+ let st = automation(app.id)
+ print("\(st == "not-running" ? "not-open" : st)\t\(app.name)")
+ }
+ return 0
+ default:
+ print("usage: Chums --check fda | screen | accessibility [--ask] | automation <bundle id> [--ask] | apps")
+ return 64
+ }
+ print(word)
+ return word == "granted" ? 0 : 1
+}
+
+// MARK: - the window
+
+/// Finder and System Events are always asked (System Events starts with no window; with Accessibility it is how agents
+/// click and type anywhere). Any other listed app is asked too when it's open right now; nothing is opened just to
+/// ask, and an app that isn't open asks once, as Chums, the first time an agent uses it.
+let required = ["com.apple.finder", "com.apple.systemevents"]
+func appsToAsk() -> [(id: String, name: String)] {
+ controlled.filter { required.contains($0.id) || (installed($0.id) && windowless($0.id))
+ || !NSRunningApplication.runningApplications(withBundleIdentifier: $0.id).isEmpty }
+}
+
+enum Step { case folders, apps, accessibility, screen }
+
+/// Asks a fresh copy of Chums. A running process keeps the Screen Recording answer it started with (its connection to
+/// the window server), so the window would never see that switch flipped. The copy is Chums too: the answer is Chums's.
+func fresh(_ what: String) -> Bool {
+ let p = Process()
+ p.executableURL = Bundle.main.executableURL
+ p.arguments = ["--check", what]
+ p.standardOutput = FileHandle.nullDevice; p.standardError = FileHandle.nullDevice
+ guard (try? p.run()) != nil else { return false }
+ p.waitUntilExit()
+ return p.terminationStatus == 0
+}
+
+final class Permissions: ObservableObject {
+ // folders and apps that aren't open can't be read without asking: their last answer is remembered, and every
+ // Allow reads them again (a granted folder or app asks nothing; a refused one shows up as refused)
+ @Published var folders = UserDefaults.standard.bool(forKey: "folders")
+ @Published var allowedApps = Set(UserDefaults.standard.stringArray(forKey: "apps") ?? [])
+ @Published var refusedApps: [String: String] = [:] // bundle id: name
+ @Published var accessible = false
+ @Published var screen = false
+ @Published var disk = false
+ @Published var step: Step? // a step whose macOS dialogs are up
+ @Published var waiting: Step? // a System Settings switch it waits for
+ @Published var restarting = false
+ @Published var restartedOnce = false
+ private var timer: Timer?
+ private var skipped = false
+ private var refreshing = false
+
+ init() {
+ refresh()
+ timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] _ in self?.refresh() }
+ // Allow All restarts the agents at the end; if macOS quit Chums before that (Quit & Reopen), it does it now
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
+ if UserDefaults.standard.bool(forKey: "pendingRestart") && self.allDone {
+ UserDefaults.standard.set(false, forKey: "pendingRestart"); self.restartAgents()
+ }
+ }
+ }
+
+ var busy: Bool { step != nil || waiting != nil }
+ /// Full Disk Access covers Desktop, Documents and Downloads (and more)
+ var foldersDone: Bool { folders || disk }
+ var appsDone: Bool { required.allSatisfy(allowedApps.contains) && refusedApps.isEmpty }
+ var allDone: Bool { foldersDone && appsDone && accessible && screen }
+
+ /// the switches, read by fresh copies off the main thread; open apps read in place
+ func refresh() {
+ if refreshing || waiting != nil { return }
+ refreshing = true
+ let (ka, ks, kd) = (accessible, screen, disk)
+ DispatchQueue.global(qos: .utility).async {
+ let a = ka || fresh("accessibility"), sc = ks || fresh("screen"), d = kd || fresh("fda")
+ DispatchQueue.main.async {
+ if self.accessible != a { self.accessible = a }
+ if self.screen != sc { self.screen = sc }
+ if self.disk != d { self.disk = d }
+ if self.step != .apps { for app in appsToAsk() { self.note(app, automation(app.id)) } }
+ self.refreshing = false
+ }
+ }
+ }
+
+ /// keeps what macOS says about an app: granted, or refused (only the Automation pane undoes a refusal)
+ private func note(_ app: (id: String, name: String), _ state: String) {
+ if state == "granted" {
+ if !allowedApps.contains(app.id) { allowedApps.insert(app.id); save() }
+ if refusedApps[app.id] != nil { refusedApps[app.id] = nil }
+ } else if state == "denied" {
+ if allowedApps.contains(app.id) { allowedApps.remove(app.id); save() }
+ if refusedApps[app.id] == nil { refusedApps[app.id] = app.name }
+ } else if state == "not-asked" { // asked before, now not: its permissions were reset
+ if allowedApps.contains(app.id) { allowedApps.remove(app.id); save() }
+ if refusedApps[app.id] != nil { refusedApps[app.id] = nil }
+ }
+ }
+ private func save() { UserDefaults.standard.set(Array(allowedApps), forKey: "apps") }
+
+ /// Desktop, Documents, Downloads: reading each is what asks (once); it waits for the answer
+ func askFolders(then next: (() -> Void)? = nil) {
+ if disk { next?(); return }
+ step = .folders
+ DispatchQueue.global(qos: .userInitiated).async {
+ let ok = ["Desktop", "Documents", "Downloads"].map(folder).allSatisfy { $0 }
+ DispatchQueue.main.async {
+ self.folders = ok; UserDefaults.standard.set(ok, forKey: "folders"); self.step = nil
+ if !ok { self.openPane("Privacy_FilesAndFolders") }
+ next?()
+ }
+ }
+ }
+
+ /// "Chums wants access to control <app>": a dialog for each app not answered yet, each waiting for the answer
+ func askApps(then next: (() -> Void)? = nil) {
+ step = .apps
+ let list = appsToAsk()
+ DispatchQueue.global(qos: .userInitiated).async {
+ var results: [((id: String, name: String), String)] = []
+ for app in list {
+ var state = automation(app.id)
+ if state == "not-running", windowless(app.id),
+ let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: app.id) {
+ let cfg = NSWorkspace.OpenConfiguration(); cfg.activates = false
+ NSWorkspace.shared.openApplication(at: url, configuration: cfg)
+ for _ in 0..<20 where state == "not-running" { Thread.sleep(forTimeInterval: 0.25); state = automation(app.id) }
+ }
+ if state == "not-asked" { state = automation(app.id, ask: true) }
+ results.append((app, state))
+ }
+ DispatchQueue.main.async {
+ for (app, state) in results { self.note(app, state) }
+ self.step = nil
+ if !self.refusedApps.isEmpty { self.openPane("Privacy_Automation") }
+ next?()
+ }
+ }
+ }
+
+ /// macOS's own alert, which also puts Chums in the Accessibility list; then waits for the switch
+ func askAccessibility(then next: (() -> Void)? = nil) {
+ if fresh("accessibility") { accessible = true; next?(); return }
+ _ = accessibility(ask: true)
+ waitFor(.accessibility, until: { fresh("accessibility") }, then: next)
+ }
+
+ /// Asking isn't what puts an app in the Screen Recording list: trying to capture is. This does (macOS shows its
+ /// alert, and Chums is in the list), then waits for the switch.
+ func askScreen(then next: (() -> Void)? = nil) {
+ if fresh("screen") { screen = true; captureOnce(); next?(); return }
+ SCShareableContent.getExcludingDesktopWindows(false, onScreenWindowsOnly: true) { _, _ in }
+ waitFor(.screen, until: { fresh("screen") }) { if self.screen { self.captureOnce() }; next?() }
+ }
+
+ /// macOS 15 and later ask a second question ("Chums is requesting to bypass the system private window picker")
+ /// the first time a screenshot is actually taken, not when access is asked for. One screenshot here, the way the
+ /// agents take them, so that question comes now, while you're at the Mac. Once answered, it asks nothing.
+ func captureOnce() {
+ let file = FileManager.default.temporaryDirectory.appendingPathComponent("chums-first-capture.png")
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
+ p.arguments = ["-x", file.path]
+ p.terminationHandler = { _ in try? FileManager.default.removeItem(at: file) }
+ try? p.run()
+ }
+
+ /// every step in order; what's allowed already passes without a dialog. At the end the agents restart once, so
+ /// one that was refused something before starts again with everything.
+ func allowAll() {
+ UserDefaults.standard.set(true, forKey: "pendingRestart")
+ askFolders { self.askApps { self.askAccessibility { self.askScreen {
+ if self.allDone { UserDefaults.standard.set(false, forKey: "pendingRestart"); self.restartAgents() }
+ self.refresh()
+ } } } }
+ }
+
+ /// waits for a System Settings switch: checks by a fresh copy, off the main thread, until it's on (or Skip)
+ private func waitFor(_ s: Step, until granted: @escaping () -> Bool, then next: (() -> Void)?) {
+ waiting = s; skipped = false
+ func poll() {
+ DispatchQueue.global(qos: .userInitiated).async {
+ let on = granted()
+ DispatchQueue.main.async {
+ if on || self.skipped {
+ if s == .accessibility { self.accessible = on } else { self.screen = on }
+ self.waiting = nil; next?(); return
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: poll)
+ }
+ }
+ }
+ poll()
+ }
+
+ func skip() { skipped = true }
+ func openWaitingPane() { openPane(waiting == .screen ? "Privacy_ScreenCapture" : "Privacy_Accessibility") }
+ func showInFinder() { NSWorkspace.shared.activateFileViewerSelecting([Bundle.main.bundleURL]) }
+ func openFullDisk() { openPane("Privacy_AllFiles"); showInFinder() }
+ func openPane(_ pane: String) {
+ NSWorkspace.shared.open(URL(string: "x-apple.systempreferences:com.apple.preference.security?\(pane)")!)
+ }
+
+ /// starts the hub and the agents again (the watch's conversation is cut for a moment)
+ func restartAgents() {
+ let config = (try? JSONSerialization.jsonObject(with: Data(contentsOf: home.appendingPathComponent(".chums/config.json")))) as? [String: Any]
+ let prefix = (config?["launchdPrefix"] as? String) ?? "dev.chums"
+ let dir = home.appendingPathComponent("Library/LaunchAgents")
+ let labels = ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? [])
+ .filter { $0.hasPrefix("\(prefix).hub.") || $0.hasPrefix("\(prefix).agent.") }
+ .map { String($0.dropLast(".plist".count)) }
+ for label in labels {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/bin/launchctl")
+ p.arguments = ["kickstart", "-k", "gui/\(getuid())/\(label)"]
+ try? p.run()
+ }
+ restarting = true; restartedOnce = true
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) { self.restarting = false }
+ }
+}
+
+struct Row: View {
+ let symbol: String, title: String, detail: String
+ let done: Bool, busy: Bool, action: String, locked: Bool
+ let run: () -> Void
+ var body: some View {
+ HStack(spacing: 14) {
+ Image(systemName: symbol).font(.system(size: 20)).frame(width: 28).foregroundStyle(.secondary)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title).font(.body.weight(.medium))
+ Text(detail).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 12)
+ if done {
+ Label("Allowed", systemImage: "checkmark.circle.fill").foregroundStyle(.green)
+ } else if busy {
+ ProgressView().controlSize(.small)
+ } else {
+ Button(action, action: run).disabled(locked)
+ }
+ }
+ .padding(.horizontal, 16).padding(.vertical, 12)
+ }
+}
+
+struct PermissionsView: View {
+ @StateObject var p = Permissions()
+
+ var appsDetail: String {
+ if !p.refusedApps.isEmpty {
+ return "\(p.refusedApps.values.sorted().joined(separator: ", ")) refused. Switch Chums on for it in Settings › Automation."
+ }
+ let others = p.allowedApps.subtracting(required).count
+ if p.appsDone {
+ return "Finder, System Events\(others > 0 ? " and \(others) more" : ""). Other apps ask once, the first time an agent uses them."
+ }
+ return "Finder, System Events and the apps you have open. Other apps ask once, the first time an agent uses them."
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ HStack(spacing: 16) {
+ Image(nsImage: NSApp.applicationIconImage).resizable().frame(width: 64, height: 64)
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Chums").font(.title2.weight(.semibold))
+ Text("Allow these once. Then your agents don't stop on a dialog on this Mac when you ask from the watch.")
+ .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ VStack(spacing: 0) {
+ Row(symbol: "folder", title: "Your folders",
+ detail: p.disk && !p.folders ? "Desktop, Documents and Downloads: covered by Full Disk Access" : "Desktop, Documents and Downloads",
+ done: p.foldersDone, busy: p.step == .folders, action: "Allow", locked: p.busy, run: { p.askFolders() })
+ Divider()
+ Row(symbol: "macwindow.on.rectangle", title: "Apps", detail: appsDetail,
+ done: p.appsDone, busy: p.step == .apps, action: p.refusedApps.isEmpty ? "Allow" : "Open Settings", locked: p.busy,
+ run: { p.refusedApps.isEmpty ? p.askApps() : p.openPane("Privacy_Automation") })
+ Divider()
+ Row(symbol: "accessibility", title: "Accessibility", detail: "Clicking and typing in other apps",
+ done: p.accessible, busy: p.waiting == .accessibility, action: "Allow", locked: p.busy, run: { p.askAccessibility() })
+ Divider()
+ Row(symbol: "rectangle.dashed.badge.record", title: "Screen Recording", detail: "Screenshots when you ask for one",
+ done: p.screen, busy: p.waiting == .screen, action: "Allow", locked: p.busy, run: { p.askScreen() })
+ Divider()
+ Row(symbol: "externaldrive", title: "Full Disk Access (optional)", detail: "Also Mail, Messages and Safari data, iCloud Drive, other disks",
+ done: p.disk, busy: false, action: "Open Settings", locked: p.busy, run: p.openFullDisk)
+ }
+ .background(RoundedRectangle(cornerRadius: 10).fill(Color(nsColor: .controlBackgroundColor)))
+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color(nsColor: .separatorColor)))
+
+ if let w = p.waiting {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Now switch on Chums in System Settings › Privacy & Security › \(w == .screen ? "Screen & System Audio Recording" : "Accessibility").")
+ .font(.body.weight(.medium)).fixedSize(horizontal: false, vertical: true)
+ Text("This window sees the switch and goes on by itself."
+ + (w == .screen ? " If macOS offers Quit & Reopen, click Later. Then macOS asks once more, about bypassing the private window picker: click Allow." : "")
+ + " If Chums is already on there, switch it off and on again: Chums was signed again since. If it isn't in the list, click + and pick it: Show Chums in Finder points to it.")
+ .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(14)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.accentColor.opacity(0.12)))
+ } else {
+ Text(p.allDone
+ ? (p.restartedOnce ? "All set. The agents started again with these." : "All set. Agents started before this may be refused once: Restart Agents starts them again.")
+ : "Click Allow All, then answer each macOS dialog with Allow or OK.")
+ .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ HStack {
+ if p.waiting != nil {
+ Button("Skip", action: p.skip)
+ Button("Show Chums in Finder", action: p.showInFinder)
+ Spacer()
+ Button("Open System Settings", action: p.openWaitingPane).keyboardShortcut(.defaultAction)
+ } else {
+ Button(p.restarting ? "Restarting…" : "Restart Agents", action: p.restartAgents).disabled(p.restarting || p.busy)
+ Spacer()
+ if p.allDone {
+ Button("Done") { NSApp.terminate(nil) }.keyboardShortcut(.defaultAction)
+ } else {
+ Button("Allow All", action: p.allowAll).keyboardShortcut(.defaultAction).disabled(p.busy)
+ }
+ }
+ }
+ }
+ .padding(24)
+ .frame(width: 560)
+ }
+}
+
+final class AppDelegate: NSObject, NSApplicationDelegate {
+ var window: NSWindow!
+ func applicationDidFinishLaunching(_ note: Notification) {
+ let menu = NSMenu(), item = NSMenuItem()
+ item.submenu = NSMenu()
+ item.submenu?.addItem(withTitle: "Quit Chums", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
+ menu.addItem(item)
+ NSApp.mainMenu = menu
+ // a hosting controller sizes the window to the view, also when the waiting box appears
+ window = NSWindow(contentViewController: NSHostingController(rootView: PermissionsView()))
+ window.styleMask = [.titled, .closable]
+ window.title = "Chums"
+ window.center()
+ window.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ }
+ func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool { true }
+}
+
+// MARK: - main
+
+// A program to run starts with a path or a name; anything else that starts with "-" (macOS adds launch arguments when
+// it reopens an app, e.g. after Quit & Reopen) means the window.
+let given = Array(CommandLine.arguments.dropFirst())
+let args = given.first.map { $0 == "--check" || $0 == "--snapshot" || !$0.hasPrefix("-") } == true ? given : []
+// The window opened from Finder, `open` or a relaunch has launchd as its parent and is Chums's. Started from a
+// terminal it would be the terminal's, so it starts a copy of itself that disclaims the terminal.
+if args.isEmpty && getppid() != 1 && getenv("CHUMS_RESPONSIBLE") == nil {
+ setenv("CHUMS_RESPONSIBLE", "1", 1)
+ exit(spawn([Bundle.main.executablePath ?? CommandLine.arguments[0], "--window"], disclaimingParent: true))
+}
+if args.isEmpty { unsetenv("CHUMS_RESPONSIBLE") }
+if args.first == "--snapshot", args.count > 1 {
+ // the window as a picture, for the docs: Chums --snapshot out.png
+ _ = NSApplication.shared
+ let view = NSHostingView(rootView: PermissionsView().background(Color(nsColor: .windowBackgroundColor)))
+ view.frame = NSRect(origin: .zero, size: view.fittingSize)
+ view.layoutSubtreeIfNeeded()
+ RunLoop.main.run(until: Date().addingTimeInterval(0.5))
+ let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds)!
+ view.cacheDisplay(in: view.bounds, to: rep)
+ try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: args[1]))
+ exit(0)
+}
+if args.isEmpty {
+ let app = NSApplication.shared
+ let delegate = AppDelegate()
+ app.delegate = delegate
+ app.setActivationPolicy(.regular)
+ app.run()
+} else if getenv("CHUMS_RESPONSIBLE") == nil {
+ signal(SIGTERM, passOn); signal(SIGINT, passOn); signal(SIGHUP, passOn); signal(SIGQUIT, passOn)
+ // first a copy of this executable, responsible for itself, so what follows is Chums's even from a terminal
+ setenv("CHUMS_RESPONSIBLE", "1", 1)
+ exit(spawn([Bundle.main.executablePath ?? CommandLine.arguments[0]] + args, disclaimingParent: true))
+} else {
+ signal(SIGTERM, passOn); signal(SIGINT, passOn); signal(SIGHUP, passOn); signal(SIGQUIT, passOn)
+ unsetenv("CHUMS_RESPONSIBLE")
+ exit(args[0] == "--check" ? check(Array(args.dropFirst())) : spawn(args, disclaimingParent: false))
+}
diff --git a/tools/noodle-watch.sh b/tools/noodle-watch.sh
new file mode 100755
index 0000000..82429fb
--- /dev/null
+++ b/tools/noodle-watch.sh
@@ -0,0 +1,18 @@
+#!/bin/zsh
+# Noodle for the watch: each clip's rendered frames (design/noodle/renders/anim, from animate.py) become one HEIC image
+# sequence in app/ChumsWatch/Noodle/<clip>.heics (frames share data, so a 144-frame clip is ~120 KB), plus noodle.json
+# with each clip's frame count, role, state, events and per-frame anchors (hair, face, glass contact).
+# watchOS has no way to read frames out of a video (no AVAssetReader or video outputs), so the app decodes these with
+# ImageIO a frame at a time (Rig/StretchFrames.swift).
+set -e
+ROOT="${0:A:h:h}"; R="$ROOT/design/noodle/renders"; OUT="$ROOT/app/ChumsWatch/Noodle"; mkdir -p "$OUT"
+TOOL=$(mktemp -d)/heics
+swiftc -O -o "$TOOL" "$ROOT/tools/heics.swift"
+for c in $(python3 -c "import json;print(' '.join(json.load(open('$R/clips.json'))['clips']))"); do "$TOOL" "$R/anim" "$c" "$OUT/$c.heics" 0.65 >/dev/null; done
+python3 - "$R/clips.json" "$OUT/noodle.json" <<'PY'
+import json, sys
+m = json.load(open(sys.argv[1]))
+keep = {k: {kk: v[kk] for kk in ('n', 'loop', 'role', 'state', 'events', 'frames', 'scrub') if kk in v} for k, v in m['clips'].items()}
+json.dump({'fps': m.get('fps', 24), 'w': m.get('w', 396), 'h': m.get('h', 484), 'beat_chance': m.get('beat_chance', {}), 'clips': keep}, open(sys.argv[2], 'w'), separators=(',', ':'))
+PY
+du -sh "$OUT"
diff --git a/tools/page-shot.swift b/tools/page-shot.swift
new file mode 100644
index 0000000..320a902
--- /dev/null
+++ b/tools/page-shot.swift
@@ -0,0 +1,99 @@
+// page-shot: a web page (a URL or an HTML file) rendered by Safari's engine at phone width, the whole page top to bottom,
+// as a PNG. The hub uses it to show pages on the watch, which has no web engine of its own.
+// page-shot <url-or-file> <out.png> [width 390] [scale 2] [max width]
+// It loads the page as an iPhone would (its user agent and width), waits for it to settle (its animations ended), grows
+// the view to the page's full height (at most 9000 pt) and snapshots it. With a max width, a page wider than width (a
+// wide table) widens the view up to it, and the picture stays at most 1200 px wide. Prints "<w>x<h>", with " cut" when
+// the page was taller than 9000 pt. Exits 0 with the PNG written, 1 on a failure, 2 after 25 s.
+import AppKit
+import WebKit
+
+let args = CommandLine.arguments
+guard args.count >= 3 else { FileHandle.standardError.write("usage: page-shot <url-or-file> <out.png> [width] [scale] [max width]\n".data(using: .utf8)!); exit(1) }
+let target = args[1], out = URL(fileURLWithPath: args[2])
+let width = args.count > 3 ? Double(args[3]) ?? 390 : 390, scale = args.count > 4 ? Double(args[4]) ?? 2 : 2
+let maxWidth = args.count > 5 ? max(width, Double(args[5]) ?? width) : width
+let maxHeight = 9000.0
+var shown = width // the view's width: more for a page wider than width
+
+final class Shot: NSObject, WKNavigationDelegate {
+ let web: WKWebView, window: NSWindow
+ override init() {
+ let cfg = WKWebViewConfiguration()
+ // no scroll bar: with one (a Mac set to always show them) the page is laid out narrower while it's measured
+ // than when it's snapped, and its picture ends in blank space
+ cfg.userContentController.addUserScript(WKUserScript(source: """
+ const s = document.createElement('style'); s.textContent = '::-webkit-scrollbar { display: none }'; document.documentElement.appendChild(s)
+ """, injectionTime: .atDocumentStart, forMainFrameOnly: true))
+ // a page WebKit isn't showing (the screen locked or asleep) gets no animation frames: its frames come from a
+ // timer then, so an animation that goes by the clock (Chart.js, D3) still ends
+ cfg.userContentController.addUserScript(WKUserScript(source: """
+ const raf = window.requestAnimationFrame.bind(window), caf = window.cancelAnimationFrame.bind(window)
+ window.requestAnimationFrame = cb => document.visibilityState === 'visible' ? raf(cb) : -setTimeout(() => cb(performance.now()), 16)
+ window.cancelAnimationFrame = id => id < 0 ? clearTimeout(-id) : caf(id)
+ """, injectionTime: .atDocumentStart, forMainFrameOnly: false))
+ web = WKWebView(frame: NSRect(x: 0, y: 0, width: width, height: 844), configuration: cfg)
+ web.customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"
+ // WebKit only paints a view that's in a window, and runs a page's animations and timers only while the window
+ // is on screen: one in the corner, above the others, that can't be seen (0.4% opaque) or clicked
+ window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: 844), styleMask: .borderless, backing: .buffered, defer: false)
+ window.contentView = web
+ window.alphaValue = 0.004
+ window.ignoresMouseEvents = true
+ window.level = .floating
+ window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle] // on every Space, a full-screen app's too
+ window.orderFrontRegardless()
+ super.init()
+ web.navigationDelegate = self
+ }
+ func start() {
+ if target.hasPrefix("http://") || target.hasPrefix("https://"), let u = URL(string: target) { web.load(URLRequest(url: u)) }
+ else { let f = URL(fileURLWithPath: target); web.loadFileURL(f, allowingReadAccessTo: f.deletingLastPathComponent()) }
+ }
+ func webView(_ w: WKWebView, didFinish _: WKNavigation!) {
+ // fonts, images and the page's own scripts settle first
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { self.measure() }
+ }
+ func webView(_ w: WKWebView, didFail _: WKNavigation!, withError e: Error) { fail(e) }
+ func webView(_ w: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError e: Error) { fail(e) }
+ func fail(_ e: Error) { FileHandle.standardError.write("page-shot: \(e.localizedDescription)\n".data(using: .utf8)!); exit(1) }
+
+ func measure() {
+ // the end of any animation still running (a screen that's locked or asleep doesn't run them): a chart drawn in
+ let js = "document.getAnimations().forEach(a => { try { a.finish() } catch (e) {} }); [document.documentElement.scrollWidth, Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)]"
+ web.evaluateJavaScript(js) { v, _ in
+ let wh = (v as? [NSNumber])?.map(\.doubleValue) ?? []
+ // wider than the view: widen it (up to the max width), and measure again once the page has laid out anew
+ if wh.count == 2, wh[0] > shown + 1, shown < maxWidth {
+ shown = min(maxWidth, wh[0])
+ self.window.setContentSize(NSSize(width: shown, height: 844))
+ self.web.frame = NSRect(x: 0, y: 0, width: shown, height: 844)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self.measure() }
+ return
+ }
+ let full = wh.count == 2 ? wh[1] : 844, H = min(maxHeight, max(300, full))
+ self.window.setContentSize(NSSize(width: shown, height: H))
+ self.web.frame = NSRect(x: 0, y: 0, width: shown, height: H)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { self.snap(H, cut: full > maxHeight) }
+ }
+ }
+ func snap(_ H: Double, cut: Bool) {
+ let c = WKSnapshotConfiguration()
+ c.rect = CGRect(x: 0, y: 0, width: shown, height: H)
+ // in points; the image comes back at the screen's backing scale, so this gives width × scale pixels (a widened
+ // page: up to 1200)
+ c.snapshotWidth = NSNumber(value: min(shown * scale, max(width * scale, 1200)) / (NSScreen.main?.backingScaleFactor ?? 2))
+ web.takeSnapshot(with: c) { img, e in
+ guard let img, let tiff = img.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff),
+ let png = rep.representation(using: .png, properties: [:]) else { self.fail(e ?? NSError(domain: "page-shot", code: 1)); return }
+ do { try png.write(to: out); print("\(rep.pixelsWide)x\(rep.pixelsHigh)\(cut ? " cut" : "")"); exit(0) } catch { self.fail(error) }
+ }
+ }
+}
+
+let app = NSApplication.shared
+app.setActivationPolicy(.prohibited)
+let shot = Shot()
+shot.start()
+DispatchQueue.main.asyncAfter(deadline: .now() + 25) { FileHandle.standardError.write("page-shot: timed out\n".data(using: .utf8)!); exit(2) }
+app.run()
diff --git a/tools/pdf-shot.swift b/tools/pdf-shot.swift
new file mode 100644
index 0000000..9befd8c
--- /dev/null
+++ b/tools/pdf-shot.swift
@@ -0,0 +1,64 @@
+// pdf-shot: a PDF's pages as one picture, top to bottom, with a thin black gap between them. The hub uses it to show
+// PDFs on the watch, which has no PDF viewer of its own. PDFKit draws each page as Preview does, with its rotation,
+// annotations and form fields.
+// pdf-shot <in.pdf> <out.png>
+// Pages are drawn 1200 px wide; when they don't all fit in 10 M pixels at that width, narrower (down to 900 px) so
+// more of them do; past that, the pages that don't fit are left out. Prints "<w>x<h> <pages shown> <pages>". Exits 1
+// on a failure (a file that isn't a PDF, one locked with a password).
+import AppKit
+import PDFKit
+
+let args = CommandLine.arguments
+func fail(_ why: String) -> Never { FileHandle.standardError.write("pdf-shot: \(why)\n".data(using: .utf8)!); exit(1) }
+guard args.count >= 3 else { fail("usage: pdf-shot <in.pdf> <out.png>") }
+guard let doc = PDFDocument(url: URL(fileURLWithPath: args[1])) else { fail("not a PDF that can be opened") }
+if doc.isLocked && !doc.unlock(withPassword: "") { fail("the PDF is locked with a password") }
+let count = doc.pageCount
+guard count > 0 else { fail("the PDF has no pages") }
+
+let maxWidth = 1200.0, minWidth = 900.0, maxPixels = 10_000_000.0, gap = 16.0
+// each page as it's shown (its rotation applied), in points
+let sizes: [CGSize] = (0..<count).map { i in
+ let page = doc.page(at: i)!, b = page.bounds(for: .cropBox)
+ return page.rotation % 180 == 0 ? b.size : CGSize(width: b.height, height: b.width)
+}
+let ratios = sizes.map { Double($0.height / max($0.width, 1)) }
+// the widest width from 900 to 1200 px at which every page fits: W × (W × Σ ratios + gap × (pages − 1)) ≤ maxPixels
+let a = ratios.reduce(0, +), b = gap * Double(count - 1)
+let W = min(maxWidth, max(minWidth, ((-b + (b * b + 4 * a * maxPixels).squareRoot()) / (2 * a)).rounded(.down)))
+// the pages that fit at that width (at least the first, cut at the bottom if it alone is too tall)
+var heights: [Int] = [], total = 0
+for r in ratios {
+ let h = max(1, Int((W * r).rounded())), next = total + (heights.isEmpty ? 0 : Int(gap)) + h
+ if !heights.isEmpty && Double(next) * W > maxPixels { break }
+ heights.append(h); total = next
+}
+let width = Int(W), height = min(total, Int(maxPixels / W))
+
+guard let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
+else { fail("no memory for a \(width)x\(height) picture") }
+ctx.setFillColor(CGColor(gray: 0, alpha: 1))
+ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ctx.interpolationQuality = .high
+var top = 0
+for (i, h) in heights.enumerated() {
+ let page = doc.page(at: i)!
+ let y = height - top - h // Core Graphics counts from the bottom
+ let slot = CGRect(x: 0, y: y, width: width, height: h)
+ ctx.setFillColor(CGColor(gray: 1, alpha: 1))
+ ctx.fill(slot)
+ ctx.saveGState()
+ ctx.clip(to: slot)
+ ctx.translateBy(x: 0, y: CGFloat(y))
+ ctx.scaleBy(x: CGFloat(W) / sizes[i].width, y: CGFloat(h) / sizes[i].height)
+ page.draw(with: .cropBox, to: ctx) // in the box's space, its rotation applied
+ ctx.restoreGState()
+ top += h + Int(gap)
+}
+guard let image = ctx.makeImage(),
+ let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: args[2]) as CFURL, "public.png" as CFString, 1, nil)
+else { fail("can't write \(args[2])") }
+CGImageDestinationAddImage(dest, image, nil)
+guard CGImageDestinationFinalize(dest) else { fail("can't write \(args[2])") }
+print("\(width)x\(height) \(heights.count) \(count)")
diff --git a/tools/pick-team.py b/tools/pick-team.py
new file mode 100644
index 0000000..5a1fae5
--- /dev/null
+++ b/tools/pick-team.py
@@ -0,0 +1,47 @@
+#!/usr/bin/env python3
+"""Print the Apple developer team to sign Chums with.
+
+Order: $CHUMS_TEAM, then a paid team from Xcode's account cache, then the team (OU) of a valid Apple Development
+certificate in the keychain that isn't a free team's, then a free Personal Team (free provisioning: installs on your
+own devices expire after 7 days). Prints nothing if none is found; prints "free" on stderr when it picks a free team."""
+import os, plistlib, re, subprocess, sys
+
+if os.environ.get('CHUMS_TEAM'):
+ print(os.environ['CHUMS_TEAM']); sys.exit()
+
+try:
+ prefs = plistlib.loads(subprocess.run(['defaults', 'export', 'com.apple.dt.Xcode', '-'], capture_output=True).stdout)
+ # IDEProvisioningTeamByIdentifier is what each signed-in account can use now (empty while a team is suspended or
+ # being converted); IDEProvisioningTeams can still list teams an account has lost
+ live = prefs.get('IDEProvisioningTeamByIdentifier')
+ if live is not None:
+ teams = [t for ts in live.values() for t in ts if isinstance(t, dict)]
+ else:
+ teams = [t for ts in prefs.get('IDEProvisioningTeams', {}).values() for t in ts]
+ paid = [t for t in teams if not t.get('isFreeProvisioningTeam') and t.get('teamID')]
+ # prefer a team you run (Admin / Agent) over one where you're only a member
+ paid.sort(key=lambda t: 0 if str(t.get('teamMemberRole', '')).lower() in ('admin', 'agent', 'account holder') else 1)
+ if paid:
+ print(paid[0]['teamID']); sys.exit()
+ free = [t['teamID'] for t in teams if t.get('isFreeProvisioningTeam') and t.get('teamID')]
+except Exception:
+ free = []
+
+pems = subprocess.run(['security', 'find-certificate', '-a', '-c', 'Apple Development', '-p'], capture_output=True, text=True).stdout
+certs = re.findall(r'-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----', pems, re.S)
+best = None
+for pem in certs:
+ # a valid Apple Development certificate of a team that isn't a free Personal Team (e.g. a team that just became an
+ # organization, whose account Xcode's cache may not list yet)
+ if subprocess.run(['openssl', 'x509', '-noout', '-checkend', '0'], input=pem, capture_output=True, text=True).returncode != 0:
+ continue
+ out = subprocess.run(['openssl', 'x509', '-noout', '-subject'], input=pem, capture_output=True, text=True).stdout
+ ou = re.search(r'OU\s*=\s*([A-Z0-9]{10})', out)
+ if ou and ou.group(1) not in free:
+ best = ou.group(1)
+if best:
+ print(best); sys.exit()
+
+# no paid team and no valid certificate: a free Personal Team still signs for your own devices (7-day installs)
+if free:
+ print('free', file=sys.stderr); print(free[0])
diff --git a/tools/pix-compare.py b/tools/pix-compare.py
new file mode 100755
index 0000000..31c2674
--- /dev/null
+++ b/tools/pix-compare.py
@@ -0,0 +1,109 @@
+#!/usr/bin/env python3
+"""Compare the Pix port's frames (tools/pix-render.swift) with design/pix/reference, pixel for pixel.
+
+ python3 tools/pix-compare.py RENDERED_DIR [OUT_DIR] [--sheets all|diff|none]
+
+Per frame: max and mean absolute difference over RGB, the number of pixels that differ at all, and the number that differ
+by more than 8 (a visible step). Writes OUT_DIR/summary.txt, OUT_DIR/summary.json and, for every frame that differs,
+OUT_DIR/sheets/<name>.png: reference | port | difference ×8, with the differing pixels boxed. Also OUT_DIR/index.html.
+"""
+import json, os, sys
+import numpy as np
+from PIL import Image, ImageDraw
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+REF = os.path.join(ROOT, 'design', 'pix', 'reference')
+
+
+def load(path):
+ return np.asarray(Image.open(path).convert('RGBA')).astype(np.int16)
+
+
+def main():
+ args = [a for a in sys.argv[1:] if not a.startswith('--')]
+ opts = [a for a in sys.argv[1:] if a.startswith('--')]
+ rendered = args[0]
+ out = args[1] if len(args) > 1 else os.path.join(ROOT, 'app', 'build', 'pix-compare')
+ sheets = 'diff'
+ states = None
+ for o in opts:
+ if o.startswith('--sheets='): sheets = o.split('=', 1)[1]
+ if o.startswith('--states='): states = o.split('=', 1)[1].split(',')
+ os.makedirs(os.path.join(out, 'sheets'), exist_ok=True)
+ names = sorted(n[:-4] for n in os.listdir(REF) if n.endswith('.png'))
+ if states: names = [n for n in names if n.split('-')[2] in states]
+ rows = []
+ for name in names:
+ rp = os.path.join(rendered, name + '.png')
+ if not os.path.exists(rp):
+ rows.append(dict(name=name, missing=True)); continue
+ a, b = load(os.path.join(REF, name + '.png')), load(rp)
+ if a.shape != b.shape:
+ rows.append(dict(name=name, shape=[list(a.shape), list(b.shape)])); continue
+ d = np.abs(a[:, :, :3] - b[:, :, :3])
+ dm = d.max(axis=2)
+ differing = int((dm > 0).sum())
+ visible = int((dm > 8).sum())
+ row = dict(name=name, max=int(dm.max()), mean=float(d.mean()), differing=differing, visible=visible,
+ species=name.split('-')[1], state=name.split('-')[2], stateT=name.split('-')[3])
+ rows.append(row)
+ if sheets == 'all' or (sheets == 'diff' and differing):
+ sheet(a, b, dm, name, os.path.join(out, 'sheets', name + '.png'))
+ # summary
+ lines = []
+ lines.append(f'{"frame":34} {"max":>4} {"mean":>7} {"diff px":>8} {">8":>7}')
+ for r in rows:
+ if r.get('missing'): lines.append(f'{r["name"]:34} MISSING'); continue
+ if r.get('shape'): lines.append(f'{r["name"]:34} SHAPE {r["shape"]}'); continue
+ lines.append(f'{r["name"]:34} {r["max"]:4d} {r["mean"]:7.3f} {r["differing"]:8d} {r["visible"]:7d}')
+ ok = [r for r in rows if 'max' in r]
+ exact = sum(1 for r in ok if r['max'] == 0)
+ lines.append('')
+ lines.append(f'{exact} of {len(ok)} frames identical; {sum(1 for r in ok if r["max"] <= 2)} within 2; {sum(1 for r in ok if r["visible"] == 0)} with no pixel off by more than 8')
+ lines.append('')
+ lines.append('per state (both species, four stateT each): max | mean of means | pixels differing | pixels off by > 8')
+ for st in ['idle', 'listening', 'thinking', 'compacting', 'working', 'subagents', 'speaking', 'done', 'needs', 'waiting', 'blocked', 'dizzy', 'sleep']:
+ for sp in ['apple', 'banana']:
+ g = [r for r in ok if r['state'] == st and r['species'] == sp]
+ if not g: continue
+ lines.append(f' {st:11} {sp:7} max {max(r["max"] for r in g):3d} mean {np.mean([r["mean"] for r in g]):6.3f} differing {sum(r["differing"] for r in g):6d} >8 {sum(r["visible"] for r in g):6d}')
+ text = '\n'.join(lines)
+ print(text)
+ open(os.path.join(out, 'summary.txt'), 'w').write(text + '\n')
+ json.dump(rows, open(os.path.join(out, 'summary.json'), 'w'), indent=1)
+ # an index page
+ html = ['<meta charset=utf-8><title>Pix port vs reference</title><body style="background:#111;color:#ddd;font:13px ui-monospace,monospace;padding:16px">',
+ '<h2>Pix port vs design/pix/reference</h2><pre>', text, '</pre>']
+ for r in rows:
+ if r.get('differing'):
+ html.append(f'<h3 id="{r["name"]}">{r["name"]}: max {r["max"]}, mean {r["mean"]:.3f}, {r["differing"]} px differ, {r["visible"]} by more than 8</h3>'
+ f'<img src="sheets/{r["name"]}.png" style="max-width:100%;image-rendering:pixelated">')
+ open(os.path.join(out, 'index.html'), 'w').write('\n'.join(html))
+ print(f'\nwritten to {out}')
+
+
+def sheet(a, b, dm, name, path):
+ h, w = dm.shape
+ pad, lab = 8, 18
+ im = Image.new('RGB', (3 * w + 4 * pad, h + 2 * pad + lab), (24, 24, 28))
+ ref = Image.fromarray(a[:, :, :3].astype(np.uint8))
+ port = Image.fromarray(b[:, :, :3].astype(np.uint8))
+ diff = Image.fromarray(np.clip(np.abs(a[:, :, :3] - b[:, :, :3]) * 8, 0, 255).astype(np.uint8))
+ for i, (img, t) in enumerate([(ref, 'reference (Lab, Chrome)'), (port, 'port (Pix.swift)'), (diff, 'difference x8')]):
+ x = pad + i * (w + pad)
+ im.paste(img, (x, pad + lab))
+ dr = ImageDraw.Draw(im)
+ dr.text((pad, pad), f'{name} max {int(dm.max())} differing {int((dm > 0).sum())} px (>8: {int((dm > 8).sum())})', fill=(220, 220, 220))
+ for i, t in enumerate(['reference (Lab)', 'port (Pix.swift)', 'difference x8']):
+ dr.text((pad + i * (w + pad), pad + lab + h + 2), t, fill=(160, 160, 160))
+ # box the differing regions on the difference panel
+ ys, xs = np.where(dm > 0)
+ if len(ys):
+ x0, x1, y0, y1 = xs.min(), xs.max(), ys.min(), ys.max()
+ ox = pad + 2 * (w + pad)
+ dr.rectangle([ox + x0 - 2, pad + lab + y0 - 2, ox + x1 + 2, pad + lab + y1 + 2], outline=(255, 80, 80))
+ im.save(path)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/pix-compare.sh b/tools/pix-compare.sh
new file mode 100755
index 0000000..c9c3e67
--- /dev/null
+++ b/tools/pix-compare.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Build the Pix port on the Mac, render the 104 reference frames and compare them with design/pix/reference.
+# Output: app/build/pix-compare (summary.txt, index.html, sheets/*.png). Extra arguments go to pix-render (e.g. --time).
+set -e
+cd "$(dirname "$0")/.."
+export DEVELOPER_DIR=${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}
+OUT=app/build/pix-compare
+mkdir -p "$OUT/frames"
+xcrun swiftc -O -target "$(uname -m)-apple-macosx14.0" app/ChumsWatch/Rig/Pix.swift tools/pix-render.swift -o "$OUT/pix-render"
+"$OUT/pix-render" "$OUT/frames" "$@"
+python3 tools/pix-compare.py "$OUT/frames" "$OUT"
diff --git a/tools/pix-render.swift b/tools/pix-render.swift
new file mode 100644
index 0000000..8919b59
--- /dev/null
+++ b/tools/pix-render.swift
@@ -0,0 +1,97 @@
+import Foundation
+import CoreGraphics
+import ImageIO
+
+// Renders the Pix port (app/ChumsWatch/Rig/Pix.swift) on the Mac: the same 104 frames as design/pix/reference, at 3×
+// (594 × 726) on black, so tools/pix-compare.py can diff them pixel for pixel. Also times a frame at the watch's scale.
+//
+// tools/pix-compare.sh # build, render, compare (writes app/build/pix-compare)
+// pix-render OUTDIR # the 104 frames
+// pix-render OUTDIR --time # plus per-state render times
+// pix-render OUTDIR --float-bilinear --high-linear # resampling variants (see Pix.lowpBilinear / Pix.highIsCubic)
+
+@main
+struct Main {
+ static func main() {
+ let args = CommandLine.arguments
+ guard args.count >= 2 else { print("usage: pix-render OUTDIR [--time] [--float-bilinear] [--high-linear]"); exit(2) }
+ let out = URL(fileURLWithPath: args[1])
+ try? FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)
+ let env = ProcessInfo.processInfo.environment
+ func mode(_ v: String?) -> Pix.Bilinear? { v == "lowp" ? .lowp : v == "hw8" ? .hw8 : v == "float" ? .float : nil }
+ if let m = mode(env["PIX_HALVE"]) { Pix.halveMode = m }
+ if let m = mode(env["PIX_LAST"]) { Pix.lastMode = m }
+ if let v = env["PIX_HALVE_TIES"] { Pix.halveTiesUp = v == "up" }
+ if let v = env["PIX_LAST_TIES"] { Pix.lastTiesUp = v == "up" }
+ if let v = env["PIX_UNPREMUL_TIES"] { Pix.unpremulTiesUp = v == "up" }
+ if let b = env["PIX_SUBTEXEL"], let n = Int(b) { Pix.subtexelBits = n }
+ if env["PIX_HIGH"] == "cubic" { Pix.highIsCubic = true }
+ if env["PIX_HIGH"] == "linear" { Pix.highIsMip = false }
+ if let v = env["PIX_MIPBIAS"], let d = Double(v) { Pix.mipBias = d }
+ if env["PIX_MIPAXIS"] == "max" { Pix.mipAxisMax = true }
+
+ let stateTs: [(Double, String)] = [(0.3, "0_3"), (1, "1"), (2, "2"), (3.2, "3_2")]
+ var cases: [(String, Pix.Params)] = []
+ for species in Pix.Species.allCases {
+ for st in Pix.State.allCases {
+ for (T, name) in stateTs {
+ var p = Pix.Params()
+ p.species = species; p.state = st; p.stateT = T; p.t = 10 + T
+ p.cx = 99; p.cy = st == .needs ? 146 : st == .working ? 134 : 118; p.px = 7
+ p.voice = 0.6
+ p.text = "ALL 14 TESTS PASS. I ALSO FIXED A TYPO."
+ p.tools = ["READ", "EDIT", "BASH"]
+ p.subagents = 3
+ p.screen = CGRect(x: 0, y: 36, width: 198, height: 206)
+ p.room = 150
+ cases.append(("pix-\(species.rawValue)-\(st.rawValue)-\(name)", p))
+ }
+ }
+ }
+
+ let r = Pix.Raster(w: 594, h: 726)
+ let dump = env["PIX_DUMP"] // a directory: every atRes stage of every frame goes there as <frame>-<stage>.png
+ for (name, p) in cases {
+ r.fill(Pix.RGBA(0, 0, 0))
+ if let dump {
+ try? FileManager.default.createDirectory(atPath: dump, withIntermediateDirectories: true)
+ Pix.debugHook = { stage, ras in writePNG(ras, URL(fileURLWithPath: dump).appendingPathComponent("\(name)-\(stage).png")) }
+ }
+ Pix.draw(r, transform: Pix.Matrix(a: 3, b: 0, c: 0, d: 3, e: 0, f: 0), p)
+ Pix.debugHook = nil
+ writePNG(r, out.appendingPathComponent(name + ".png"))
+ }
+ print("rendered \(cases.count) frames to \(out.path)")
+
+ if args.contains("--time") {
+ // the 45 mm watch: 198 × 242 pt at 2× = 396 × 484 px
+ let w = Pix.Raster(w: 396, h: 484)
+ let m = Pix.Matrix(a: 2, b: 0, c: 0, d: 2, e: 0, f: 0)
+ print("\nrender time per frame at 396 × 484 (the watch's pixels), mean of 40 after warm-up:")
+ var worst = ("", 0.0), total = 0.0, n = 0
+ for species in Pix.Species.allCases {
+ print(" \(species.rawValue):")
+ for st in Pix.State.allCases {
+ var ms: [Double] = []
+ for (T, _) in stateTs {
+ let p = cases.first { $0.0 == "pix-\(species.rawValue)-\(st.rawValue)-\(T == 1 ? "1" : T == 2 ? "2" : T == 0.3 ? "0_3" : "3_2")" }!.1
+ for _ in 0..<3 { w.fill(Pix.RGBA(0, 0, 0)); Pix.draw(w, transform: m, p) }
+ let t0 = Date()
+ for _ in 0..<40 { w.fill(Pix.RGBA(0, 0, 0)); Pix.draw(w, transform: m, p) }
+ let dt = Date().timeIntervalSince(t0) / 40 * 1000
+ ms.append(dt); total += dt; n += 1
+ if dt > worst.1 { worst = ("\(species.rawValue) \(st.rawValue) T=\(T)", dt) }
+ }
+ print(String(format: " %-11@ %@ ms", st.rawValue as NSString, ms.map { String(format: "%.2f", $0) }.joined(separator: " / ") as NSString))
+ }
+ }
+ print(String(format: " mean %.2f ms, worst %.2f ms (%@)", total / Double(n), worst.1, worst.0 as NSString))
+ }
+ }
+
+ static func writePNG(_ r: Pix.Raster, _ url: URL) {
+ guard let img = r.image(), let dest = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil) else { print("cannot write \(url.path)"); return }
+ CGImageDestinationAddImage(dest, img, nil)
+ CGImageDestinationFinalize(dest)
+ }
+}
diff --git a/tools/pty-run.py b/tools/pty-run.py
new file mode 100644
index 0000000..ea0ccf0
--- /dev/null
+++ b/tools/pty-run.py
@@ -0,0 +1,51 @@
+"""Run a terminal program in a pseudo-terminal, act on it, and print what it drew, for tests of terminal UIs.
+
+ python3 tools/pty-run.py '<steps as JSON>' <command> [args...]
+
+Steps, in order: {"wait": seconds}, {"type": "text"} (typed a character at a time), {"key": "enter"}, {"mark": "name"}
+(writes ###name### into the output, so a test can tell what was drawn before and after). The terminal is 140 x 60.
+The output is the plain text drawn (escape sequences and all whitespace removed), with the marks; the program is
+killed at the end.
+"""
+import fcntl, json, os, pty, re, select, struct, sys, termios, time
+
+steps = json.loads(sys.argv[1])
+pid, fd = pty.fork()
+if pid == 0:
+ os.environ["TERM"] = "xterm-256color"
+ os.execvp(sys.argv[2], sys.argv[2:])
+fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 60, 140, 0, 0))
+out = []
+
+
+def pump(seconds):
+ end = time.time() + seconds
+ while time.time() < end:
+ r, _, _ = select.select([fd], [], [], 0.1)
+ if not r:
+ continue
+ try:
+ chunk = os.read(fd, 65536)
+ except OSError:
+ return
+ out.append(chunk)
+ if b"\x1b[6n" in chunk: # where's the cursor? (the UI waits for an answer)
+ os.write(fd, b"\x1b[1;1R")
+
+
+for step in steps:
+ if "wait" in step:
+ pump(step["wait"])
+ elif "type" in step:
+ for ch in step["type"]:
+ os.write(fd, ch.encode())
+ pump(0.03)
+ elif step.get("key") == "enter":
+ os.write(fd, b"\r")
+ pump(0.2)
+ elif "mark" in step:
+ out.append(f"###{step['mark']}###".encode())
+os.kill(pid, 9)
+text = b"".join(out).decode(errors="ignore")
+text = re.sub(r"\x1b\[[0-9;?<>=]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(\x07|\x1b\\)|\x1b[()][A-Z0-9]|\x1b[=>78]", "", text)
+print(re.sub(r"\s+", "", text))
diff --git a/tools/ql-shot.swift b/tools/ql-shot.swift
new file mode 100644
index 0000000..bc8375a
--- /dev/null
+++ b/tools/ql-shot.swift
@@ -0,0 +1,35 @@
+// ql-shot: Quick Look's picture of a file, as Finder draws it (a document's first page, a presentation's first slide,
+// a spreadsheet's first sheet, a 3D model), on white, up to 1600 px on its long side. The hub uses it for the files it
+// has no renderer of its own for (Word, Excel, PowerPoint, Pages, Keynote, Numbers, RTF, EPUB, USDZ…).
+// ql-shot <file> <out.png> [size 1600]
+// Prints "<w>x<h>". Exits 1 when Quick Look has no picture of the file (only its icon), at once; 2 after 20 s.
+// (Not qlmanage -t: it waits forever on a file it has no picture of, and draws RTF in dark mode, black on dark grey.)
+import AppKit
+import QuickLookThumbnailing
+
+let args = CommandLine.arguments
+func fail(_ why: String, _ code: Int32 = 1) -> Never { FileHandle.standardError.write("ql-shot: \(why)\n".data(using: .utf8)!); exit(code) }
+guard args.count >= 3 else { fail("usage: ql-shot <file> <out.png> [size]") }
+let file = URL(fileURLWithPath: args[1]), out = URL(fileURLWithPath: args[2])
+let side = args.count > 3 ? Double(args[3]) ?? 1600 : 1600
+
+let request = QLThumbnailGenerator.Request(fileAt: file, size: CGSize(width: side, height: side), scale: 1, representationTypes: .thumbnail)
+QLThumbnailGenerator.shared.generateBestRepresentation(for: request) { rep, _ in
+ guard let picture = rep?.cgImage else { fail("Quick Look has no picture of \(file.lastPathComponent)") }
+ // on white: a page or a model drawn on a clear background would turn black as a JPEG
+ let w = picture.width, h = picture.height
+ guard let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
+ else { fail("no memory for a \(w)x\(h) picture") }
+ ctx.setFillColor(CGColor(gray: 1, alpha: 1))
+ ctx.fill(CGRect(x: 0, y: 0, width: w, height: h))
+ ctx.draw(picture, in: CGRect(x: 0, y: 0, width: w, height: h))
+ guard let flat = ctx.makeImage(), let dest = CGImageDestinationCreateWithURL(out as CFURL, "public.png" as CFString, 1, nil)
+ else { fail("can't write \(out.path)") }
+ CGImageDestinationAddImage(dest, flat, nil)
+ guard CGImageDestinationFinalize(dest) else { fail("can't write \(out.path)") }
+ print("\(w)x\(h)")
+ exit(0)
+}
+DispatchQueue.main.asyncAfter(deadline: .now() + 20) { fail("timed out", 2) }
+RunLoop.main.run()
diff --git a/tools/readme-loops.sh b/tools/readme-loops.sh
new file mode 100755
index 0000000..7044f3e
--- /dev/null
+++ b/tools/readme-loops.sh
@@ -0,0 +1,55 @@
+#!/bin/zsh
+# Renders each character's loop for the README from the current code: 3.2 s of it idle on the watch's screen (the
+# faces and the clock at the top), at 20 frames a second, in the watch's case (docs/media/watch-case.png), as an
+# animated WebP 300 px wide in docs/media/characters/<id>.webp (GitHub plays it; its corners are transparent).
+#
+# usage: tools/readme-loops.sh [id ...] (default: every character)
+#
+# Run bin/chums-sim once first: it builds the watch app for the Simulator and makes the "Chums Watch" simulator. The
+# frames come from the app's offline renderer (app/ChumsWatch/OfflineRender.swift), not a screen recording, so they
+# are the same on every Mac. Needs ffmpeg and img2webp (brew install webp).
+set -euo pipefail
+ROOT="${0:A:h:h}"
+source "$ROOT/tools/common.zsh"
+chums_help "$@"
+: ${DEVELOPER_DIR:=/Applications/Xcode.app/Contents/Developer}; export DEVELOPER_DIR
+chums_need ffmpeg "Install it with: brew install ffmpeg"
+chums_need img2webp "Install it with: brew install webp"
+APP="$ROOT/app/build/sym/Debug-watchsimulator/ChumsWatch.app"
+[[ -d $APP ]] || chums_die "no watch app built for the Simulator yet: run bin/chums-sim once"
+BUNDLE=$(/usr/libexec/PlistBuddy -c "Print CFBundleIdentifier" "$APP/Info.plist")
+UDID=$(xcrun simctl list devices -j | python3 -c '
+import json, sys
+for devs in json.load(sys.stdin)["devices"].values():
+ for d in devs:
+ if d["name"] == "Chums Watch" and d["isAvailable"]: print(d["udid"]); raise SystemExit')
+[[ -n $UDID ]] || chums_die "no \"Chums Watch\" simulator: run bin/chums-sim once"
+xcrun simctl boot "$UDID" 2>/dev/null || true
+xcrun simctl install "$UDID" "$APP"
+
+ALL=(noodle stretch peeps squint ray tangle crunch nana)
+IDS=("$@"); (( ${#IDS} )) || IDS=($ALL)
+OUT="$ROOT/docs/media/characters"; mkdir -p "$OUT"
+DATA=$(xcrun simctl get_app_container "$UDID" "$BUNDLE" data)
+for id in $IDS; do
+ # the faces at the top left: this one, then the next two
+ i=${ALL[(i)$id]}; f2=${ALL[$(( i % ${#ALL} + 1 ))]}; f3=${ALL[$(( (i + 1) % ${#ALL} + 1 ))]}
+ spec=$(printf '{"name":"loop-%s","character":"%s","duration":3.2,"fps":20,"scale":3,"clock":"10:09","faces":["%s","%s","%s"],"events":[{"t":0,"state":"idle"}]}' \
+ $id $id $id $f2 $f3 | base64)
+ # one run at a time: the last one has quit, and this one has printed "done" (once more if it didn't)
+ for try in 1 2; do
+ xcrun simctl terminate "$UDID" "$BUNDLE" 2>/dev/null || true
+ out=$(xcrun simctl launch --console "$UDID" "$BUNDLE" -render "$spec" -quiet YES 2>&1 || true)
+ [[ $out == *"render: loop-$id done"* ]] && break
+ (( try == 2 )) && chums_die "the Simulator didn't render $id"
+ done
+ # the screen under the case: the case's band hides the screen's square corners
+ TMP=$(mktemp -d)
+ ffmpeg -v error -y -framerate 20 -pattern_type glob -i "$DATA/Documents/render/loop-$id/*.png" -i "$ROOT/docs/media/watch-case.png" \
+ -filter_complex "[0]scale=581:710:flags=lanczos,format=rgba,pad=815:907:100:99:color=black@0[s];[s][1]overlay=0:0,scale=300:-1:flags=lanczos" \
+ "$TMP/%04d.png"
+ img2webp -loop 0 -lossy -q 75 -m 6 -d 50 "$TMP"/*.png -o "$OUT/$id.webp" >/dev/null 2>&1
+ rm -rf "$TMP"
+ echo "$id: $(du -h "$OUT/$id.webp" | cut -f1)"
+done
+xcrun simctl shutdown "$UDID" 2>/dev/null || true # left running without a window, it plays the watch's taps as sounds
diff --git a/tools/test-artifacts.mjs b/tools/test-artifacts.mjs
new file mode 100644
index 0000000..10e29f6
--- /dev/null
+++ b/tools/test-artifacts.mjs
@@ -0,0 +1,159 @@
+// Artifacts: each kind of file a session shows (chums_show's file, through /channel/artifact) or you send from the
+// iPhone (/v1/upload) becomes a picture the watch fetches, and keeps what the iPhone opens (meta.view, /source, /view).
+// The files are made here, in the private hub's temporary home. node tools/test-artifacts.mjs
+import path from 'node:path'
+import fs from 'node:fs'
+import { spawnSync } from 'node:child_process'
+import { startPrivateHub } from './test-hub-private.mjs'
+import { markdown } from '../hub/render.mjs'
+
+let fails = 0; const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) fails++ }
+
+// ---------- Markdown, converted (no hub needed) ----------
+const md = markdown([
+ '# Title', '', 'Some **bold**, _em_ and `a <b> code`, a [link](https://example.com) and ![a chart](https://example.com/c.png).',
+ 'snake_case_stays <script>alert(1)</script><img src="https://example.com/x.png" alt="Logo"> <https://example.com/auto>', '',
+ '1. one', '2. two', ' - nested', '', '- [x] done', '', '> quoted', '', '| a | b |', '| - | -: |', '| 1 | 2 |', '',
+ '```', 'if (a < b) {}', '```', '', '---', '', 'Underlined', '==========',
+].join('\n'))
+ok(/<h1>Title<\/h1>/.test(md) && /<strong>bold<\/strong>/.test(md) && /<em>em<\/em>/.test(md) && /<code>a &lt;b&gt; code<\/code>/.test(md),
+ 'Markdown: a heading, emphasis and inline code (escaped)')
+ok(/<span class="link">link<\/span>/.test(md) && /Image: a chart/.test(md) && /Image: Logo/.test(md) && /https:\/\/example\.com\/auto/.test(md),
+ 'links and images become their text')
+ok(!/<(script|img|a)\b|\bhref=|\bsrc=/.test(md) && /snake_case_stays/.test(md), 'nothing in it loads or links; raw HTML is dropped, words with _ stay whole')
+ok(/<ol><li>one<\/li><li>two<ul><li>nested<\/li><\/ul><\/li><\/ol>/.test(md) && /☑/.test(md), 'lists, nested, and a task list')
+ok(/<blockquote><p>quoted<\/p><\/blockquote>/.test(md) && /<table><tr><th>a<\/th><th style="text-align:right">b<\/th><\/tr><tr><td>1<\/td>/.test(md),
+ 'a block quote and a table')
+ok(/<pre><code>if \(a &lt; b\) \{\}<\/code><\/pre>/.test(md) && /<hr>/.test(md) && /<h1>Underlined<\/h1>/.test(md), 'a code block, a rule, an underlined heading')
+
+// ---------- the files ----------
+const { cfg, home, stop } = await startPrivateHub()
+const H = `http://127.0.0.1:${cfg.port}`, P = `http://127.0.0.1:${cfg.publicPort}`
+const call = async (pathname, body) => {
+ const r = await fetch(H + pathname, { method: 'POST', headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/json' }, body: JSON.stringify(body) })
+ return { status: r.status, body: await r.json().catch(() => null) }
+}
+const get = (pathname, headers = {}, token = cfg.watchToken) => fetch(P + pathname, { headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...headers } })
+const sid = 'artifacts-' + Date.now()
+await call('/channel/register', { sessionId: sid, name: 'artifacts', cwd: '/tmp/artifacts' })
+
+const fx = path.join(home, 'files')
+fs.mkdirSync(fx)
+const at = f => path.join(fx, f)
+/// A PDF of `n` US Letter pages, each with its number in Helvetica and an orange band at the top.
+function makePDF(file, n) {
+ const objs = ['', '<< /Type /Catalog /Pages 2 0 R >>', '', '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>']
+ const pages = Array.from({ length: n }, (_, i) => 4 + i * 2)
+ objs[2] = `<< /Type /Pages /Kids [${pages.map(p => `${p} 0 R`).join(' ')}] /Count ${n} >>`
+ pages.forEach((p, i) => {
+ const s = `0.85 0.47 0.34 rg 0 672 612 120 re f 0 g BT /F1 64 Tf 72 500 Td (Page ${i + 1}) Tj ET`
+ objs[p] = `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${p + 1} 0 R >>`
+ objs[p + 1] = `<< /Length ${s.length} >>\nstream\n${s}\nendstream`
+ })
+ let out = '%PDF-1.4\n'
+ const offsets = objs.map((o, i) => { if (!i) return 0; const at = out.length; out += `${i} 0 obj\n${o}\nendobj\n`; return at })
+ const xref = out.length
+ out += `xref\n0 ${objs.length}\n0000000000 65535 f \n${offsets.slice(1).map(o => `${String(o).padStart(10, '0')} 00000 n \n`).join('')}`
+ fs.writeFileSync(file, out + `trailer\n<< /Size ${objs.length} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`)
+}
+makePDF(at('three.pdf'), 3)
+fs.writeFileSync(at('notes.md'), '# Notes\n\nA paragraph with **bold** text.\n\n- one\n- two\n\n```\ncode\n```\n')
+fs.writeFileSync(at('long.txt'), Array.from({ length: 500 }, (_, i) => `line ${i + 1}: ${'word '.repeat(i % 7)}`).join('\n') + '\n')
+fs.writeFileSync(at('people.csv'), 'id,name,"city, country"\n' + Array.from({ length: 300 }, (_, i) => `${i + 1},Person ${i + 1},"Lisbon, ""PT"""`).join('\n') + '\n')
+fs.writeFileSync(at('page.html'), '<!doctype html><meta name=viewport content="width=device-width"><body style="background:#123;color:#fff"><h1 id=h>Static</h1><script>h.textContent = "Ran"</script>')
+fs.writeFileSync(at('blob.bin'), Buffer.from(Array.from({ length: 4096 }, (_, i) => (i * 37) & 0xff)))
+fs.writeFileSync(at('data'), '{"a":1}\n') // no extension, but UTF-8 text
+spawnSync('/usr/bin/textutil', ['-convert', 'docx', at('long.txt'), '-output', at('letter.docx')])
+spawnSync('/usr/bin/textutil', ['-convert', 'rtf', at('notes.md'), '-output', at('notes.rtf')])
+const ffmpeg = ['/opt/homebrew/bin/ffmpeg', '/usr/local/bin/ffmpeg', ...(process.env.PATH ?? '').split(':').map(d => path.join(d, 'ffmpeg'))].find(f => fs.existsSync(f))
+if (ffmpeg) spawnSync(ffmpeg, ['-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=duration=2:size=320x240:rate=10', '-pix_fmt', 'yuv420p', '-y', at('clip.mov')])
+
+// each one, shown by a session: its kind, its picture, its title, and what the iPhone gets
+const cases = [
+ // file, kind, view.type, view.file, a check of the title, a check of the picture
+ ['three.pdf', 'pdf', 'pdf', 'source.pdf', t => t === 'three.pdf', a => a.w === 1200 && a.h > 2 * a.w * 792 / 612, 'all 3 pages, stacked'],
+ ['notes.md', 'doc', 'html', 'view.html', t => t === 'notes.md', a => a.w === 780, 'rendered at phone width'],
+ ['long.txt', 'text', 'text', 'view.html', t => /^long\.txt, first \d+ lines of 500$/.test(t), a => a.w === 780 && a.h > 4000, 'the first lines that fit'],
+ ['people.csv', 'table', 'html', 'view.html', t => t === 'people.csv, first 200 rows of 300', a => a.w >= 780 && a.h > 3000, 'a table of the first 200 rows'],
+ ['page.html', 'page', 'html', 'source.html', t => t === 'page.html', a => a.w === 780, 'rendered at phone width'],
+ ['letter.docx', 'doc', 'doc', 'source.docx', t => t === 'letter.docx', a => a.w > 500 && a.h > 500, "Quick Look's picture"],
+ ['notes.rtf', 'doc', 'doc', 'source.rtf', t => t === 'notes.rtf', a => a.w > 500, "Quick Look's picture, not its text"],
+ ['data', 'text', 'text', 'view.html', t => t === 'data', a => a.w === 780, 'UTF-8 text without an extension'],
+ ...(ffmpeg ? [['clip.mov', 'video', 'video', 'source.mov', t => t === 'clip.mov, a still at 0:01', a => a.w === 320 && a.h === 240, 'a still from a second in']] : []),
+]
+if (!ffmpeg) console.log('SKIP the video checks: no ffmpeg on this Mac (brew install ffmpeg)')
+const shown = {}
+for (const [file, kind, type, served, titleOK, pictureOK, what] of cases) {
+ const t0 = Date.now()
+ const r = await call('/channel/artifact', { sessionId: sid, file: at(file) })
+ const a = r.body ?? {}, ms = Date.now() - t0
+ const full = await get(`/v1/artifact/${a.id}/full`), jpeg = Buffer.from(await full.arrayBuffer())
+ const sane = a.w > 0 && a.h > 0 && a.w <= 1200 && a.w * a.h <= 10_000_000 && jpeg[0] === 0xFF && jpeg[1] === 0xD8
+ ok(r.status === 200 && a.kind === kind && titleOK(a.title) && sane && pictureOK(a),
+ `${file}: ${kind}, ${what} ("${a.title}", ${a.w}×${a.h}, ${ms} ms)${r.status !== 200 ? ` ${JSON.stringify(r.body)}` : ''}`)
+ const size = fs.statSync(at(file)).size
+ ok(a.view?.type === type && a.view.file === served && a.view.name === file && a.view.ext === path.extname(file).slice(1) && a.view.size === size && a.view.source === true,
+ `${file}: meta.view ${JSON.stringify(a.view)}`)
+ shown[file] = a
+}
+ok((await call('/channel/artifact', { sessionId: sid, file: at('blob.bin') })).status === 422, 'a file with no picture (binary, unknown to Quick Look) is refused with a reason')
+ok((await call('/channel/artifact', { sessionId: sid, file: at('nothing.pdf') })).status === 422, 'so is a file that isn\'t there')
+const again = Date.now(), second = await call('/channel/artifact', { sessionId: sid, file: at('three.pdf') })
+console.log(` (the PDF again, its helper compiled: ${Date.now() - again} ms)`)
+ok(second.body?.id !== shown['three.pdf'].id, 'each showing is its own artifact')
+
+// a PDF longer than one picture holds: the title says which pages it shows
+makePDF(at('long.pdf'), 14)
+const long = (await call('/channel/artifact', { sessionId: sid, file: at('long.pdf') })).body
+ok(/^long\.pdf, pages 1–\d of 14$/.test(long?.title ?? '') && long.w >= 900 && long.w * long.h <= 10_000_000, `a 14-page PDF: "${long?.title}" (${long?.w}×${long?.h})`)
+
+// what the state carries: the line, with the artifact's view
+const line = (await (await get('/v1/state?since=0')).json()).spoken.find(l => l.artifact?.id === shown['notes.md'].id)
+ok(line?.artifact?.view?.type === 'html' && line.artifact.view.file === 'view.html', "the conversation's line carries meta.view")
+
+// ---------- the routes ----------
+const pdf = shown['three.pdf'], pdfBytes = fs.readFileSync(at('three.pdf'))
+const src = await get(`/v1/artifact/${pdf.id}/source`), body = Buffer.from(await src.arrayBuffer())
+ok(src.status === 200 && src.headers.get('content-type') === 'application/pdf' && body.equals(pdfBytes) &&
+ /filename="three\.pdf"/.test(src.headers.get('content-disposition') ?? '') && src.headers.get('accept-ranges') === 'bytes',
+ '/source: the original, its type and file name')
+const part = await get(`/v1/artifact/${pdf.id}/source`, { range: 'bytes=10-19' }), partBytes = Buffer.from(await part.arrayBuffer())
+ok(part.status === 206 && part.headers.get('content-range') === `bytes 10-19/${pdfBytes.length}` && partBytes.equals(pdfBytes.subarray(10, 20)),
+ 'a range: 206 with those bytes')
+const tail = await get(`/v1/artifact/${pdf.id}/source`, { range: 'bytes=-7' })
+ok(tail.status === 206 && Buffer.from(await tail.arrayBuffer()).equals(pdfBytes.subarray(-7)), 'the last bytes: 206 with those')
+ok((await get(`/v1/artifact/${pdf.id}/source`, { range: `bytes=${pdfBytes.length}-` })).status === 416, 'a range past the end: 416')
+ok((await get(`/v1/artifact/${pdf.id}/view`)).headers.get('content-type') === 'application/pdf', '/view of a PDF: the PDF (no page of the hub\'s)')
+const view = await get(`/v1/artifact/${shown['notes.md'].id}/view`), html = await view.text()
+ok(view.status === 200 && view.headers.get('content-type') === 'text/html; charset=utf-8' && /default-src 'none'/.test(html) && /<h1>Notes<\/h1>/.test(html) &&
+ /sandbox/.test(view.headers.get('content-security-policy') ?? ''), "/view of Markdown: the hub's page, loading nothing, sandboxed")
+ok((await (await get(`/v1/artifact/${shown['notes.md'].id}/source`)).text()) === fs.readFileSync(at('notes.md'), 'utf8'), '/source of Markdown: the Markdown')
+const page = await get(`/v1/artifact/${shown['page.html'].id}/view`)
+ok(/sandbox allow-scripts/.test(page.headers.get('content-security-policy') ?? '') && (await page.text()).includes('h.textContent'), "/view of an agent's page: the page, its scripts allowed, in an origin of its own")
+const vid = shown['clip.mov']
+if (vid) {
+ const v = await get(`/v1/artifact/${vid.id}/source`, { range: 'bytes=0-1' })
+ ok(v.status === 206 && v.headers.get('content-type') === 'video/quicktime' && (await v.arrayBuffer()).byteLength === 2, 'a video: its type, and the two-byte range a player asks for first')
+}
+ok((await get(`/v1/artifact/${pdf.id}/source`, {}, null)).status === 401, 'not without a token')
+ok((await get(`/v1/artifact/${pdf.id}/source`, {}, cfg.token)).status === 401, 'not with the local token on the public door')
+ok((await get('/v1/artifact/0123456789ab/source')).status === 404 && (await get('/v1/artifact/0123456789ab/view')).status === 404, 'an id that isn\'t there: 404')
+for (const p of [`/v1/artifact/..%2F..%2Fconfig.json/source`, `/v1/artifact/${pdf.id}%2F..%2F..%2Fconfig.json/source`, `/v1/artifact/${pdf.id}/../../config.json`,
+ `/v1/artifact/${pdf.id}/meta.json`, `/v1/artifact/${pdf.id}/source.pdf`, `/v1/artifact/${pdf.id}0/source`]) {
+ const r = await get(p), text = await r.text()
+ ok(r.status === 404 && !text.includes(cfg.token) && !text.includes('%PDF'), `a path in the id is refused: ${p.replace(pdf.id, '<id>')} (${r.status})`)
+}
+
+// ---------- uploads from the iPhone: the same, with the name it was sent with ----------
+const put = (name, file) => fetch(`${P}/v1/upload?name=${encodeURIComponent(name)}`, { method: 'POST', headers: { authorization: `Bearer ${cfg.watchToken}` }, body: fs.readFileSync(file) })
+for (const [name, file, kind] of [['My notes.md', 'notes.md', 'doc'], ['scan.pdf', 'three.pdf', 'pdf'], ['report.docx', 'letter.docx', 'doc'],
+ ['log.txt', 'long.txt', 'text'], ['people.csv', 'people.csv', 'table'], ...(ffmpeg ? [['clip.mov', 'clip.mov', 'video']] : [])]) {
+ const t0 = Date.now(), up = await (await put(name, at(file))).json(), a = up.artifact
+ const back = a && Buffer.from(await (await get(`/v1/artifact/${a.id}/source`)).arrayBuffer())
+ ok(a?.kind === kind && a.view?.name === up.name && a.view.source && back?.equals(fs.readFileSync(at(file))) && fs.existsSync(path.join(home, '.chums/artifacts', a.id, 'full.jpg')),
+ `upload ${name}: ${a?.kind} "${a?.title}" ${a?.w}×${a?.h}, its original kept (${Date.now() - t0} ms)`)
+}
+const bin = await (await put('blob.bin', at('blob.bin'))).json()
+ok(bin.path && bin.artifact === null, 'an upload with no picture is just the file')
+
+console.log(fails ? `${fails} FAILED` : 'all passed'); stop(); process.exit(fails ? 1 : 0)
diff --git a/tools/test-channel.mjs b/tools/test-channel.mjs
new file mode 100644
index 0000000..8bc9059
--- /dev/null
+++ b/tools/test-channel.mjs
@@ -0,0 +1,91 @@
+// End-to-end check of hub + channel without Claude Code: this script plays Claude Code's side of the
+// MCP stdio connection and the watch's side of the hub API.
+import { spawn } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import readline from 'node:readline'
+
+import { startPrivateHub } from './test-hub-private.mjs'
+const { cfg, home, stop } = await startPrivateHub() // never the real hub: its sessions would get the test's orders
+const HUB = `http://127.0.0.1:${cfg.port}`
+const auth = { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/json' }
+const watch = (p, body) => fetch(HUB + p, { method: body ? 'POST' : 'GET', headers: auth, body: body && JSON.stringify(body) }).then(r => r.json())
+const sleep = ms => new Promise(r => setTimeout(r, ms))
+
+const ch = spawn('node', [path.join(import.meta.dirname, '../channel/chums-channel.mjs')], {
+ env: { ...process.env, HOME: home, CHUMS_NAME: 'chumstest' }, stdio: ['pipe', 'pipe', 'inherit'], cwd: os.tmpdir(),
+})
+const inbox = []
+readline.createInterface({ input: ch.stdout }).on('line', l => inbox.push(JSON.parse(l)))
+const send = m => ch.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...m }) + '\n')
+const waitFor = async (pred, ms = 5000) => {
+ const end = Date.now() + ms
+ while (Date.now() < end) { const i = inbox.findIndex(pred); if (i >= 0) return inbox.splice(i, 1)[0]; await sleep(50) }
+ throw new Error('timeout waiting for message')
+}
+const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) process.exitCode = 1 }
+
+send({ id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'fake-claude-code', version: '0' } } })
+const init = await waitFor(m => m.id === 1)
+ok(init.result.capabilities.experimental?.['claude/channel'] && init.result.capabilities.experimental?.['claude/channel/permission'], 'channel declares claude/channel + permission capabilities')
+send({ method: 'notifications/initialized' })
+
+await sleep(800)
+let st = await watch('/v1/state?since=0')
+ok(st.sessions.some(s => s.name === 'chumstest'), 'session registered with hub')
+
+// watch -> order -> channel notification into the session
+const r = await watch('/v1/say', { text: 'Tell chumstest to run the channel tests' })
+ok(r.kind === 'order' && r.target === 'chumstest', `routed order: ${r.echo}`)
+const note = await waitFor(m => m.method === 'notifications/claude/channel')
+ok(note.params.content.includes('channel tests'), `session received: "${note.params.content}"`)
+
+// Claude calls chums_reply -> spoken line on the watch
+send({ id: 2, method: 'tools/call', params: { name: 'chums_reply', arguments: { text: 'Channel tests passed.', status: 'done' } } })
+await waitFor(m => m.id === 2)
+st = await watch('/v1/state?since=0')
+ok(/^(chumstest: )?Channel tests passed\.$/.test(st.spoken.at(-1)?.text ?? ''), `watch hears: "${st.spoken.at(-1)?.text}"`)
+
+// a reply longer than 15 words is refused, so the session says it again, shorter; the watch hears nothing
+send({ id: 9, method: 'tools/call', params: { name: 'chums_reply', arguments: { text: 'I ran every one of the channel tests twice and all ten of them passed without any flaky failures at all.', status: 'done' } } })
+const long = await waitFor(m => m.id === 9)
+const st9 = await watch('/v1/state?since=0')
+ok(long.result?.isError && /Too long/.test(long.result.content[0].text) && !/flaky/.test(st9.spoken.at(-1)?.text ?? ''), 'a 21-word reply is refused and never reaches the watch')
+
+// from the iPhone: the order says so, and the reply can be a few sentences (the iPhone shows the text)
+await watch('/v1/say', { text: 'Tell chumstest what the label on this tube means', device: 'phone' })
+const phoneNote = await waitFor(m => m.method === 'notifications/claude/channel')
+ok(phoneNote.params.meta?.via === 'phone', `an order from the iPhone arrives via="${phoneNote.params.meta?.via}"`)
+const forty = 'It is a fluoride-free spearmint toothpaste. All-One is the maker\'s motto: one human family. The label also says seventy percent organic ingredients and that it helps freshen breath and whiten teeth without any harsh additives at all.'
+send({ id: 10, method: 'tools/call', params: { name: 'chums_reply', arguments: { text: forty, status: 'done' } } })
+const phoneReply = await waitFor(m => m.id === 10)
+const st10 = await watch('/v1/state?since=0')
+ok(!phoneReply.result?.isError && /fluoride-free/.test(st10.spoken.at(-1)?.text ?? ''), `a ${forty.split(' ').length}-word reply to the iPhone is shown`)
+await watch('/v1/say', { text: 'Tell chumstest to run them again' })
+const watchNote = await waitFor(m => m.method === 'notifications/claude/channel')
+send({ id: 11, method: 'tools/call', params: { name: 'chums_reply', arguments: { text: forty, status: 'done' } } })
+const watchReply = await waitFor(m => m.id === 11)
+ok(watchNote.params.meta?.via === 'watch' && watchReply.result?.isError, 'from the watch again: via="watch", and the same reply is too long for it')
+
+// Claude Code opens a permission prompt -> approval card on the watch -> "yes" -> verdict back
+send({ method: 'notifications/claude/channel/permission_request', params: { request_id: 'abcde', tool_name: 'Bash', description: 'Delete build folder', input_preview: '{"command":"rm -rf build"}' } })
+await sleep(300)
+st = await watch('/v1/state?since=0')
+ok(st.approvals[0]?.requestId === 'abcde' && st.approvals[0].preview.includes('rm -rf'), 'approval card shows tool + command')
+const v = await watch('/v1/say', { text: 'yes' })
+ok(v.kind === 'verdict', `spoken "yes" -> ${v.echo}`)
+const verdict = await waitFor(m => m.method === 'notifications/claude/channel/permission')
+ok(verdict.params.request_id === 'abcde' && verdict.params.behavior === 'allow', 'session received allow verdict')
+
+const f = await watch('/v1/say', { text: 'Tell the chalmtest session to open a pull request' })
+ok(f.kind === 'order' && f.target === 'chumstest', `misheard name still routes: ${f.echo}`)
+await waitFor(m => m.method === 'notifications/claude/channel')
+
+const s = await watch('/v1/say', { text: "what's running" })
+ok(s.kind === 'status', `status answer: ${s.echo}`)
+
+ch.stdin.end()
+await sleep(300)
+stop()
+process.exit()
diff --git a/tools/test-hub-private.mjs b/tools/test-hub-private.mjs
new file mode 100644
index 0000000..be2b2c8
--- /dev/null
+++ b/tools/test-hub-private.mjs
@@ -0,0 +1,44 @@
+// A private hub for the tests: its own HOME (so its own ~/.chums config and tokens), its own ports, no
+// speech-to-text, so tests never reach the real hub or a real Claude Code session in its routing table.
+// import { startPrivateHub } from './test-hub-private.mjs'; const { cfg, stop } = await startPrivateHub()
+// Options: agents (its ~/.chums/agents.json; else the hub writes its defaults), env (more environment for the hub and
+// the agents it runs), logFile (where the hub's log goes), home (a previous private hub's, to start a hub again on
+// it), and CHUMS_TEST_LOG=1 to see the hub's log. It returns hub (the process) and stop({ keepHome }).
+// Its bin/chums-agents is a stand-in that only writes what it was asked to <home>/chums-agents.log: a test that
+// restarts a Claude Code agent never touches a real LaunchAgent.
+import { spawn } from 'node:child_process'
+import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'
+
+export async function startPrivateHub({ agents, env = {}, logFile, home: again } = {}) {
+ const home = again ?? fs.mkdtempSync(path.join(os.tmpdir(), 'chums-test-'))
+ let cfg
+ if (again) cfg = JSON.parse(fs.readFileSync(path.join(home, '.chums/config.json'), 'utf8'))
+ else {
+ fs.mkdirSync(path.join(home, '.chums'))
+ cfg = { port: 17717 + Math.floor(Math.random() * 500) * 2, token: 'test-local-' + Date.now(), watchToken: 'test-watch-' + Date.now() }
+ cfg.publicPort = cfg.port + 1
+ fs.writeFileSync(path.join(home, '.chums/config.json'), JSON.stringify(cfg))
+ }
+ if (agents) fs.writeFileSync(path.join(home, '.chums/agents.json'), JSON.stringify(agents, null, 2))
+ const agentsBin = path.join(home, 'chums-agents')
+ fs.writeFileSync(agentsBin, '#!/bin/sh\necho "$*" >> "$0.log"\n', { mode: 0o755 })
+ let hub
+ // a port another test's hub already has (tests run side by side) stops this hub at once: it starts again on others
+ for (let attempt = 1; ; attempt++) {
+ hub = spawn('node', [path.join(import.meta.dirname, '../hub/hub.mjs')], {
+ env: { ...process.env, CHUMS_AGENTS_BIN: agentsBin, ...env, HOME: home, CHUMS_NO_WHISPER: '1' }, stdio: logFile ? ['ignore', fs.openSync(logFile, 'a'), fs.openSync(logFile, 'a')] : process.env.CHUMS_TEST_LOG ? 'inherit' : 'ignore',
+ })
+ let exited = false
+ hub.once('exit', () => { exited = true })
+ for (let i = 0; i < 50 && !exited; i++) {
+ try { if ((await fetch(`http://127.0.0.1:${cfg.port}/v1/ping`, { headers: { authorization: `Bearer ${cfg.token}` } })).ok) break } catch {}
+ await new Promise(r => setTimeout(r, 100))
+ }
+ if (!exited || again || attempt === 5) break
+ cfg.port = 17717 + Math.floor(Math.random() * 500) * 2; cfg.publicPort = cfg.port + 1
+ fs.writeFileSync(path.join(home, '.chums/config.json'), JSON.stringify(cfg))
+ }
+ process.on('exit', () => hub.kill()) // a test that dies doesn't leave its hub (and the agents it runs) behind
+ // (the hub may still be writing as it stops, e.g. its souls' first commit: the removal tries again)
+ return { cfg, home, hub, stop: ({ keepHome } = {}) => { hub.kill(); if (!keepHome) fs.rmSync(home, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) } }
+}
diff --git a/tools/test-hub.mjs b/tools/test-hub.mjs
new file mode 100644
index 0000000..891da91
--- /dev/null
+++ b/tools/test-hub.mjs
@@ -0,0 +1,248 @@
+import path from 'node:path'
+import fs from 'node:fs'
+import os from 'node:os'
+import net from 'node:net'
+import { spawnSync } from 'node:child_process'
+// Hub safety checks against the running hub: delivery acks, spoken-verdict binding, cleanup on bye, the public door.
+// node tools/test-hub.mjs
+import { startPrivateHub } from './test-hub-private.mjs'
+const { cfg, home, hub, stop } = await startPrivateHub() // never the real hub: its sessions would get the test's orders
+const H = `http://127.0.0.1:${cfg.port}`, P = `http://127.0.0.1:${cfg.publicPort}`
+const call = async (base, path, body, token = cfg.token) => {
+ const r = await fetch(base + path, { method: body ? 'POST' : 'GET', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: body && JSON.stringify(body) })
+ return { status: r.status, body: await r.json().catch(() => null) }
+}
+let fails = 0; const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) fails++ }
+const sid = 'acktest-' + Date.now()
+await call(H, '/channel/register', { sessionId: sid, name: 'acktest', cwd: '/tmp/acktest' })
+await call(H, '/v1/say', { text: 'tell acktest to run the thing' })
+const a = (await call(H, `/channel/next?sessionId=${sid}`)).body.items
+ok(a.length === 1 && a[0].id, 'order delivered with an id')
+const b = (await call(H, `/channel/next?sessionId=${sid}`)).body.items
+ok(b.length === 1 && b[0].id === a[0].id, 'unacknowledged order delivered again (lost response)')
+await call(H, '/v1/say', { text: 'tell acktest to run another thing' })
+const c = (await call(H, `/channel/next?sessionId=${sid}&ack=${a[0].id}`)).body.items
+ok(c.length === 1 && c[0].id !== a[0].id, 'acknowledged order gone, the next one arrives')
+// spoken verdicts: two requests pending
+await call(H, '/channel/permission', { sessionId: sid, request_id: 'r1', tool_name: 'Bash', description: 'first', input_preview: 'ls' })
+await call(H, '/channel/permission', { sessionId: sid, request_id: 'r2', tool_name: 'Bash', description: 'second', input_preview: 'pwd' })
+ok((await call(H, '/v1/say', { text: 'yes' })).body.kind === 'ask', 'bare "yes" with two pending and no card asks which')
+ok((await call(H, '/v1/say', { text: "yes, but don't run it" })).body.kind !== 'verdict', '"yes, but don\'t run it" is not a yes')
+const v = (await call(H, '/v1/say', { text: 'Yes.', approval: 'r1' })).body
+ok(v.kind === 'verdict' && /Allowed/.test(v.echo), '"Yes." with the shown card allows that card')
+const st = (await call(H, '/v1/state?since=0')).body
+ok(st.approvals.length === 1 && st.approvals[0].requestId === 'r2', 'only the shown request was answered')
+const d = (await call(H, `/channel/next?sessionId=${sid}&ack=${c[0].id}`)).body.items
+ok(d.some(it => it.type === 'verdict' && it.requestId === 'r1' && it.behavior === 'allow'), 'the verdict reaches the session')
+// subagents: the hook events count them; a stop clears them
+const who = (await call(H, '/v1/state?since=0')).body.sessions.find(x => x.id === sid)
+const hook = (event, agent) => call(H, '/hook', { name: who.name, cwd: who.cwd ?? '', event, agent })
+await hook('SubagentStart', 'ag1'); await hook('SubagentStart', 'ag2')
+ok((await call(H, '/v1/state?since=0')).body.sessions.find(x => x.id === sid).subagents === 2, 'two subagents started: the watch sees 2')
+await hook('SubagentStop', 'ag1')
+ok((await call(H, '/v1/state?since=0')).body.sessions.find(x => x.id === sid).subagents === 1, 'one stopped: the watch sees 1')
+await hook('Stop')
+ok((await call(H, '/v1/state?since=0')).body.sessions.find(x => x.id === sid).subagents === 0, 'the turn stopped: no subagents')
+// artifacts: a page, an HTML file and an image become pictures the watch can fetch, each said as a line
+const page = await call(H, '/channel/artifact', { sessionId: sid, url: 'https://example.com', text: 'Here it is.' })
+ok(page.status === 200 && page.body.kind === 'page' && page.body.w === 780 && page.body.h > 400, `a public page renders at phone width (${page.body.w}×${page.body.h})`)
+ok(page.body.view?.type === 'url' && page.body.view.url === 'https://example.com' && page.body.view.name === 'example.com', 'the iPhone is given its URL')
+const html = path.join(os.tmpdir(), `artifact-test-${Date.now()}.html`)
+fs.writeFileSync(html, '<!doctype html><meta name=viewport content="width=device-width"><body style="margin:0;background:#D97757;height:1600px"><h1>Hi</h1>')
+const doc = await call(H, '/channel/artifact', { sessionId: sid, file: html, title: 'Test page' })
+ok(doc.status === 200 && doc.body.title === 'Test page' && doc.body.h >= 3000, `an HTML file renders whole, top to bottom (${doc.body.h} px)`)
+const img = await call(H, '/channel/artifact', { sessionId: sid, file: path.join(import.meta.dirname, '../design/pix/reference', fs.readdirSync(path.join(import.meta.dirname, '../design/pix/reference')).find(f => f.endsWith('.png'))) })
+ok(img.status === 200 && img.body.kind === 'image', `an image is shown as it is ${img.status !== 200 ? JSON.stringify(img.body) : ''}`)
+ok(img.body.view?.type === 'image' && img.body.view.file === 'source.png' && img.body.view.source, 'and the iPhone gets the image itself')
+// (tools/test-artifacts.mjs shows every other kind)
+const blob = path.join(home, 'blob.bin')
+fs.writeFileSync(blob, Buffer.from(Array.from({ length: 4096 }, (_, i) => (i * 37) & 0xff)))
+ok((await call(H, '/channel/artifact', { sessionId: sid, file: blob })).status === 422, 'a file there is no picture of is refused with a reason')
+const line = (await call(H, '/v1/state?since=0')).body.spoken.find(l => l.artifact?.id === page.body.id)
+ok(line && line.kind === 'artifact' && line.text === 'Here it is.', 'the artifact is a line in the conversation, with its text')
+for (const which of ['thumb', 'full']) {
+ const r = await fetch(`${P}/v1/artifact/${page.body.id}/${which}`, { headers: { authorization: `Bearer ${cfg.watchToken}` } })
+ const b = Buffer.from(await r.arrayBuffer())
+ ok(r.status === 200 && r.headers.get('content-type') === 'image/jpeg' && b[0] === 0xFF && b[1] === 0xD8, `the watch fetches its ${which} through the public door (${b.length} bytes)`)
+}
+ok((await fetch(`${P}/v1/artifact/${page.body.id}/full`)).status === 401, 'not without the watch token')
+// agents: an order sent to an agent reaches its session only; one that isn't running says so; lines carry the agent
+// the default agents, in order: code, the Mac, design (their ids differ between the internal and the public tree)
+// every character is its own agent; the seed souls give Squint the Mac and Peeps design
+const MAC = 'squint', DESIGN = 'peeps'
+const nid = MAC + '-' + Date.now()
+await call(H, '/channel/register', { sessionId: nid, name: MAC, cwd: '/tmp/' + MAC })
+const toNoodle = (await call(H, '/v1/say', { text: 'check my calendar', agent: MAC })).body
+ok(toNoodle.kind === 'order' && toNoodle.target === MAC && !toNoodle.echo.toLowerCase().includes(MAC + ':'), 'an order to Noodle goes to Noodle, echoed without a name')
+const nItems = (await call(H, `/channel/next?sessionId=${nid}`)).body.items
+ok(nItems.some(it => it.type === 'order' && it.text.endsWith('check my calendar')), "Noodle's session gets it (after its soul, the first time)")
+const notRunning = (await call(H, '/v1/say', { text: 'draw me an icon', agent: DESIGN })).body.echo ?? ''
+ok(/^\w+ isn't running\.$/.test(notRunning), `an agent that isn't running says so (${notRunning})`)
+await call(H, '/channel/reply', { sessionId: nid, text: 'Two meetings today.', status: 'done' })
+const st2 = (await call(H, '/v1/state?since=0')).body
+ok(st2.spoken.some(l => l.text === 'Two meetings today.' && l.agent === MAC), "Noodle's reply is tagged as Noodle's")
+ok(st2.spoken.some(l => l.kind === 'echo' && l.agent === MAC), 'so is the echo of what you told it')
+const ag = Object.fromEntries(st2.agents.map(a => [a.id, a]))
+ok(ag[MAC]?.status === 'idle' && ag[DESIGN]?.status === 'offline', `the agents list says who's running (${st2.agents.map(a => a.id + ':' + a.status).join(', ')})`)
+ok(st2.agents.length >= 8 && st2.agents.every(a => a.character === a.id && a.runtime === 'claude'), `one agent per character, each on Claude Code by default (${st2.agents.length})`)
+ok(Array.isArray(st2.runtimes) && st2.runtimes.includes('claude'), `the state says what an agent can switch to (${st2.runtimes})`)
+ok((await call(H, `/v1/agents/${MAC}/runtime`, { runtime: 'gemini' })).status === 400, 'an unknown runtime is refused')
+// its permission mode, from the watch or the iPhone: kept in agents.json, and its session restarts in it (the private
+// hub's bin/chums-agents is a stand-in that notes what it's asked)
+const perms = (await call(H, '/v1/permissions')).body
+ok(perms.claude.modes.map(m => m.id).join() === 'default,acceptEdits,auto' && perms.codex.modes.map(m => m.id).join() === 'untrusted,on-request,never' &&
+ [...perms.claude.modes, ...perms.codex.modes].every(m => Object.keys(m).join() === 'id,name,about' && m.name && m.about), "each runtime's modes, each with a name and what it does")
+ok(perms.claude.default === 'Asks first' && perms.codex.default === 'Asks when it needs to', `and what each runs in without one (${perms.claude.default}; ${perms.codex.default})`)
+fs.mkdirSync(path.join(home, '.claude'))
+fs.writeFileSync(path.join(home, '.claude/settings.json'), JSON.stringify({ permissions: { defaultMode: 'auto' } }))
+ok((await call(H, '/v1/permissions')).body.claude.default === 'Decides on its own', "Claude Code's is its settings' defaultMode, read when asked")
+const entry = () => JSON.parse(fs.readFileSync(path.join(home, '.chums/agents.json'), 'utf8')).find(a => a.id === MAC)
+const restarts = () => (fs.existsSync(path.join(home, 'chums-agents.log')) ? fs.readFileSync(path.join(home, 'chums-agents.log'), 'utf8') : '').split('\n').filter(l => l === `restart ${MAC}`).length
+const permissionOf = async () => (await call(H, '/v1/state')).body.agents.find(a => a.id === MAC).permission
+ok((await call(H, `/v1/agents/${MAC}/permission`, { mode: 'acceptEdits' })).body?.mode === 'acceptEdits' && entry().permissionMode === 'acceptEdits' && await permissionOf() === 'acceptEdits',
+ 'a Claude Code agent gets a permission mode: kept in agents.json as permissionMode, and the apps are told')
+ok(restarts() === 1, 'its session restarts in it (bin/chums-agents restart)')
+ok((await call(H, `/v1/agents/${MAC}/permission`, { mode: 'acceptEdits' })).status === 200 && restarts() === 1, 'the same mode again restarts nothing')
+const wrong = await call(H, `/v1/agents/${MAC}/permission`, { mode: 'never' })
+ok(wrong.status === 400 && entry().permissionMode === 'acceptEdits', `a mode its runtime doesn't have is refused (${wrong.body?.error})`)
+ok((await call(H, `/v1/agents/${MAC}/permission`, { mode: null })).body?.mode === null && !('permissionMode' in entry()) && await permissionOf() === null && restarts() === 2,
+ "no mode: permissionMode is gone, and it restarts on Claude Code's own setting")
+// a step auto mode refused: one line in the agent's conversation, and a burst of them is one line a minute
+const refuse = command => call(H, '/hook', { name: MAC, cwd: '/tmp/' + MAC, event: 'PermissionDenied', tool: 'Bash', input: { command } })
+await refuse('security find-generic-password -s github -w')
+await refuse('security find-generic-password -s npm -w')
+const st3 = (await call(H, '/v1/state')).body, refusals = st3.spoken.filter(l => l.kind === 'refused')
+ok(refusals.length === 1 && refusals[0].agent === MAC && refusals[0].text === 'Auto mode refused: Bash security find-generic-password…',
+ `a refusal is a line in its agent's conversation ("${refusals[0]?.text}"), and a second within a minute adds none`)
+ok(st3.reactions.filter(r => r.kind === 'denied' && r.session === MAC).length === 2, 'each still makes the character react')
+// souls: a change said by voice is proposed (nothing saved), saved against the version seen, sent with the next order
+// (once), and undone
+const card0 = (await call(H, `/v1/agents/${MAC}/soul`)).body
+ok(card0.name === 'Squint' && /Mac/.test(card0.owns), `Squint starts from its seed soul (${card0.name}: ${card0.owns})`)
+// the soul editor is a real model call (the claude CLI, signed in); CHUMS_TEST_NO_MODEL=1 skips it (CI)
+if (process.env.CHUMS_TEST_NO_MODEL) console.log('SKIP the soul editor checks (CHUMS_TEST_NO_MODEL)')
+else {
+const prop = (await call(H, '/v1/say', { soul: MAC, text: 'You also look after my calendar, and talk more casually.' })).body
+ok(prop.kind === 'soul' && prop.proposal && /calendar/i.test(prop.soul?.owns ?? '') && prop.summary, `a spoken change comes back as a proposal: "${prop.summary}"`)
+ok(!/calendar/i.test((await call(H, `/v1/agents/${MAC}/soul`)).body.owns), 'nothing is saved before Save')
+const saved = (await call(H, `/v1/agents/${MAC}/soul/save`, { proposal: prop.proposal })).body
+ok(/calendar/i.test(saved.owns) && saved.canUndo, 'Save keeps it')
+ok((await call(H, `/v1/agents/${MAC}/soul/save`, { proposal: prop.proposal })).status === 409, "the same change can't be saved twice")
+await call(H, '/v1/say', { text: 'what is on my calendar today', agent: MAC })
+const o1 = (await call(H, `/channel/next?sessionId=${nid}`)).body.items.filter(it => it.type === 'order').pop()
+ok(/^\[Your soul/.test(o1?.text ?? '') && /calendar/i.test(o1.text) && /what is on my calendar today$/.test(o1.text), "Noodle's next order carries its new soul, then the order")
+await call(H, '/v1/say', { text: 'and tomorrow', agent: MAC })
+const o2 = (await call(H, `/channel/next?sessionId=${nid}&ack=${o1.id}`)).body.items.filter(it => it.type === 'order').pop()
+ok(o2?.text === 'and tomorrow', 'the one after that is just the order')
+const undone = (await call(H, `/v1/agents/${MAC}/soul/undo`, {})).body
+ok(!/calendar/i.test(undone.owns ?? 'calendar') && undone.name === card0.name, 'Undo puts the last version back')
+const stale = (await call(H, '/v1/say', { soul: MAC, text: 'Call yourself Mochi.' })).body
+await call(H, `/v1/agents/${MAC}/soul/undo`, {})
+ok((await call(H, `/v1/agents/${MAC}/soul/save`, { proposal: stale.proposal })).status === 409, 'a change proposed against an older version is refused')
+const vague = (await call(H, '/v1/say', { soul: DESIGN, text: 'blue' })).body
+ok(vague.kind === 'soul' && (vague.clarify || vague.proposal), `something unclear gets a question back (${vague.clarify ?? vague.summary})`)
+}
+// a soul's parts, set one at a time from the iPhone: written as given, too long refused, Undo puts the last back
+const set1 = (await call(H, `/v1/agents/${MAC}/soul/set`, { field: 'voice', value: 'Short and dry.' })).body
+ok(set1.voice === 'Short and dry.', 'a part of a soul is set as written')
+ok((await call(H, `/v1/agents/${MAC}/soul/set`, { field: 'owns', value: 'x'.repeat(400) })).status === 400, 'a part longer than its limit is refused')
+ok((await call(H, `/v1/agents/${MAC}/soul/set`, { field: 'secret', value: 'x' })).status === 400, 'only the soul\'s parts can be set')
+ok((await call(H, `/v1/agents/${MAC}/soul/undo`, {})).body.voice !== 'Short and dry.', 'Undo takes the set back')
+// each agent keeps its own lines: a busy one doesn't push a quiet one's conversation out
+await call(H, '/v1/say', { text: 'a line for the quiet one', agent: DESIGN })
+for (let i = 0; i < 25; i++) await call(H, '/v1/say', { text: `busy line ${i}`, agent: MAC })
+const lines = (await call(H, '/v1/state')).body.spoken
+ok(lines.some(l => l.agent === DESIGN) && lines.filter(l => l.agent === MAC).length <= 20,
+ `25 lines to one agent leave another's in place, and the apps get 20 of each at most (${lines.filter(l => l.agent === MAC).length})`)
+// a message is a message: what /v1/say takes is cut at 4000 characters
+await call(H, '/v1/say', { text: 'x '.repeat(5000), agent: MAC })
+const huge = (await call(H, `/channel/next?sessionId=${nid}`)).body.items.filter(it => it.type === 'order').pop()
+ok(huge && huge.text.length < 4000 + 2000, `a 10,000-character message reaches the agent cut to 4000 (${huge?.text.length} with its soul)`)
+// the widgets' agent: the one last talked to, or the one the iPhone shows
+ok((await call(H, '/v1/state')).body.focus === MAC, 'talking to an agent makes it the one the widgets show')
+ok((await call(H, '/v1/focus', { agent: DESIGN })).body.focus === DESIGN && (await call(H, '/v1/state')).body.focus === DESIGN,
+ 'the agent the iPhone shows is the one the widgets show')
+ok((await call(H, '/v1/focus', { agent: 'nobody' })).status === 404, 'only an agent can be shown')
+// uploads: a picture from the iPhone lands in the uploads folder, an order names its path (and only uploads), and the
+// echo of what you said shows it
+const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
+const put = (token, name) => fetch(`${P}/v1/upload?name=${encodeURIComponent(name)}`, { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'image/png' }, body: png })
+const up = await (await put(cfg.watchToken, '../../etc/my photo.png')).json()
+ok(up.path && path.basename(path.dirname(up.path)) === 'uploads' && !up.name.includes('/') && up.artifact?.kind === 'image',
+ `an upload lands in the uploads folder, its name made safe, shown as a picture (${up.name})`)
+await call(H, '/v1/say', { text: 'what is this', agent: MAC, files: [up.path, '/etc/hosts'] })
+const order = (await call(H, `/channel/next?sessionId=${nid}`)).body.items.filter(it => it.type === 'order' && it.text.includes('what is this')).pop()
+ok(order?.text.includes(up.path) && !order.text.includes('/etc/hosts'), 'the order names the upload, and only uploads')
+const updir = path.dirname(up.path)
+await call(H, '/v1/say', { text: 'look closer', agent: MAC, files: [path.join(updir, '..', 'config.json'), updir, path.join(updir, '..', 'uploads', path.basename(up.path))] })
+const order3 = (await call(H, `/channel/next?sessionId=${nid}&ack=${order.id}`)).body.items.filter(it => it.type === 'order' && it.text.includes('look closer')).pop()
+ok(order3 && !order3.text.includes('config.json') && order3.text.endsWith(`Attached (files on this Mac; read them): ${up.path}`),
+ 'an order can\'t name a file outside the uploads folder, or the folder; a path through .. is given resolved')
+ok((await call(H, '/v1/state?since=0')).body.spoken.some(l => l.kind === 'echo' && l.agent === MAC && l.artifact?.id === up.artifact.id),
+ 'the echo of what you said shows the picture')
+ok((await put(cfg.token, 'x.png')).status === 401, 'uploads need the watch token on the public door')
+await call(H, '/channel/bye', { sessionId: nid })
+await call(H, '/channel/bye', { sessionId: sid })
+ok(!(await call(H, '/v1/state?since=0')).body.approvals.some(a => a.requestId === 'r2'), 'approvals of a session that said bye are gone')
+// the public door
+ok((await call(P, '/v1/ping', null, cfg.watchToken)).status === 200, 'public door: watch token works')
+ok((await call(P, '/channel/next?sessionId=x', null, cfg.watchToken)).status === 404, 'public door: session endpoints don\'t exist')
+ok((await call(P, '/v1/ping', null, cfg.token)).status === 401, 'public door: the local token is refused')
+// what anyone on the internet can send through Funnel, without a token: bytes as they come, never a crash
+let exited = false
+hub.on('exit', () => { exited = true })
+const raw = (port, ...parts) => new Promise(resolve => {
+ const s = net.connect(port, '127.0.0.1', () => s.write(Buffer.concat(parts.map(x => Buffer.isBuffer(x) ? x : Buffer.from(x)))))
+ let got = ''; s.on('data', d => { got += d }); s.on('close', () => resolve(got)); s.on('error', () => resolve(got))
+ setTimeout(() => s.destroy(), 5000)
+})
+const status = reply => Number(reply.match(/^HTTP\/1\.1 (\d+)/)?.[1] ?? 0)
+const odd = Buffer.concat([Buffer.from('a'.repeat(cfg.watchToken.length - 1)), Buffer.from([0xe9])]) // right length, one byte not ASCII
+ok(status(await raw(cfg.publicPort, 'GET /v1/ping HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer ', odd, '\r\nConnection: close\r\n\r\n')) === 401,
+ 'public door: a token with a byte that isn\'t ASCII is refused')
+ok([400, 404].includes(status(await raw(cfg.publicPort, 'GET // HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n'))), 'public door: a URL that doesn\'t parse is refused')
+ok(status(await raw(cfg.port, 'GET // HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n')) === 400, 'local door: the same')
+ok((await call(P, '/v1/../channel/next?sessionId=x', null, cfg.watchToken)).status === 404, 'public door: /v1/.. doesn\'t reach the session endpoints')
+ok((await call(P, '/hook', { event: 'Stop' }, cfg.watchToken)).status === 404, 'public door: the hooks\' endpoint doesn\'t exist')
+await new Promise(r => setTimeout(r, 300))
+ok(!exited && (await call(P, '/v1/ping', null, cfg.watchToken)).status === 200, 'the hub is still up after all of them')
+// limits on what the watch token can send
+const big = await raw(cfg.publicPort, `POST /v1/upload?name=big.bin HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer ${cfg.watchToken}\r\nContent-Length: ${25 * 1024 * 1024 + 1}\r\n\r\n`, 'x')
+ok(status(big) === 413, 'an upload over 25 MB is refused with 413, before it is read')
+const notJSON = await fetch(`${P}/v1/say`, { method: 'POST', headers: { authorization: `Bearer ${cfg.watchToken}` }, body: '{not json' })
+ok(notJSON.status === 400, 'a body that isn\'t JSON is a 400')
+// the apps' event log: one line per event, a new file past 10 MB, nothing of it in the hub's own log
+const events = path.join(home, '.chums/watch-events.log')
+await call(P, '/v1/event', { text: 'launch\nfake line' }, cfg.watchToken)
+ok(/ launch fake line\n$/.test(fs.readFileSync(events, 'utf8')), 'an event with a line break is written as one line')
+fs.appendFileSync(events, 'x'.repeat(10e6 + 1))
+await call(P, '/v1/event', { text: 'after' }, cfg.watchToken)
+ok(fs.existsSync(events + '.1') && fs.statSync(events).size < 100, 'past 10 MB the event log starts a new file')
+// a second hub on the same ports says so and stops, and the first one keeps running
+const second = spawnSync('node', [path.join(import.meta.dirname, '../hub/hub.mjs')], { env: { ...process.env, HOME: home, CHUMS_NO_WHISPER: '1' }, encoding: 'utf8', timeout: 10_000 })
+ok(second.status === 1 && /is in use/.test(second.stderr) && (await call(H, '/v1/ping')).status === 200, 'a second hub on the same ports stops with a message; the first is still up')
+// an agent written by hand without a folder or a session ID gets them (a Claude Code agent can't start without either)
+const byHand = await startPrivateHub({ agents: [{ id: 'noodle', name: 'Noodle' }, { id: 'ray', runtime: 'codex', cwd: '/tmp/ray', command: ['/nonexistent/codex'] }] })
+const written = JSON.parse(fs.readFileSync(path.join(byHand.home, '.chums/agents.json'), 'utf8'))
+const nd = written.find(a => a.id === 'noodle'), rd = written.find(a => a.id === 'ray')
+ok(/^[0-9a-f-]{36}$/.test(nd?.sessionId ?? '') && nd.cwd === path.join(byHand.home, '.chums/agents/noodle') && !rd?.sessionId && rd?.cwd === '/tmp/ray',
+ 'an agent written by hand gets a folder, and a Claude Code one a session ID (a Codex one gets its thread from Codex)')
+byHand.stop()
+// a soul change said on a Mac without Claude Code (the editor is claude -p) is an error on the watch, not a stopped hub
+const noClaude = await startPrivateHub({ env: { CHUMS_CLAUDE_BIN: '/nonexistent/claude' } })
+const said = await fetch(`http://127.0.0.1:${noClaude.cfg.publicPort}/v1/say`, { method: 'POST', headers: { authorization: `Bearer ${noClaude.cfg.watchToken}`, 'content-type': 'application/json' }, body: JSON.stringify({ soul: MAC, text: 'talk more casually' }) }).then(r => r.json())
+const alive = await fetch(`http://127.0.0.1:${noClaude.cfg.port}/v1/ping`, { headers: { authorization: `Bearer ${noClaude.cfg.token}` } }).then(r => r.status, () => 0)
+ok(said.kind === 'soul' && /Claude Code/.test(said.error ?? '') && alive === 200, `without Claude Code a soul change says why (${said.error}) and the hub stays up`)
+noClaude.stop()
+// a settings file that doesn't parse stops the hub, untouched, with a message that doesn't quote it (it holds the tokens)
+for (const [file, text] of [['config.json', '{"token": "secret-token-1", "port": 1'], ['agents.json', '[{"id": "noodle", "sessionId": "keep-me"']]) {
+ const h2 = fs.mkdtempSync(path.join(os.tmpdir(), 'chums-test-'))
+ fs.mkdirSync(path.join(h2, '.chums'))
+ if (file === 'agents.json') fs.writeFileSync(path.join(h2, '.chums/config.json'), JSON.stringify({ port: cfg.port + 2, publicPort: cfg.port + 3, token: 'a', watchToken: 'b' }))
+ fs.writeFileSync(path.join(h2, '.chums', file), text)
+ const r = spawnSync('node', [path.join(import.meta.dirname, '../hub/hub.mjs')], { env: { ...process.env, HOME: h2, CHUMS_NO_WHISPER: '1' }, encoding: 'utf8', timeout: 10_000 })
+ ok(r.status === 1 && fs.readFileSync(path.join(h2, '.chums', file), 'utf8') === text && r.stderr.includes(file) && !r.stderr.includes('secret-token') && !r.stderr.includes('keep-me'),
+ `a ${file} that isn't valid JSON stops the hub and is left as it was`)
+ fs.rmSync(h2, { recursive: true, force: true })
+}
+console.log(fails ? `${fails} FAILED` : 'all passed'); stop(); process.exit(fails ? 1 : 0)
diff --git a/tools/test-runtimes.mjs b/tools/test-runtimes.mjs
new file mode 100644
index 0000000..db8b7f7
--- /dev/null
+++ b/tools/test-runtimes.mjs
@@ -0,0 +1,204 @@
+// Agents the hub runs itself (hub/runtimes.mjs), against stand-ins: an Agent Client Protocol agent
+// (tools/fake-acp-agent.mjs, as `copilot --acp` would be) and a Codex app-server (tools/fake-codex.mjs). The watch's
+// side is the hub's API, as in tools/test-hub.mjs. No real Codex or Copilot: tools/e2e-runtimes.mjs runs those.
+// node tools/test-runtimes.mjs
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { startPrivateHub } from './test-hub-private.mjs'
+import { spokenLine } from '../hub/runtimes.mjs'
+
+const work = fs.mkdtempSync(path.join(os.tmpdir(), 'chums-rt-'))
+const LOG = path.join(work, 'fake.log')
+const agents = [
+ { id: 'acpy', name: 'Acpy', character: 'ray', runtime: 'acp', command: [process.execPath, path.join(import.meta.dirname, 'fake-acp-agent.mjs')], cwd: path.join(work, 'acpy') },
+ { id: 'codey', name: 'Codey', character: 'squint', runtime: 'codex', command: [process.execPath, path.join(import.meta.dirname, 'fake-codex.mjs')], cwd: path.join(work, 'codey'), model: 'gpt-6-astra' },
+]
+const { cfg, home, stop } = await startPrivateHub({ agents, env: { FAKE_LOG: LOG } })
+const H = `http://127.0.0.1:${cfg.port}`
+const call = async (p, body) => {
+ const r = await fetch(H + p, { method: body ? 'POST' : 'GET', headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/json' }, body: body && JSON.stringify(body) })
+ return { status: r.status, body: await r.json().catch(() => null) }
+}
+const state = async () => (await call('/v1/state?since=0')).body
+const sleep = ms => new Promise(r => setTimeout(r, ms))
+const until = async (what, f, ms = 8000) => {
+ const end = Date.now() + ms
+ for (;;) { const v = await f(); if (v) return v; if (Date.now() > end) { console.log(' (timed out waiting for', what + ')'); return null } await sleep(100) }
+}
+const noted = () => fs.existsSync(LOG) ? fs.readFileSync(LOG, 'utf8').trim().split('\n').map(l => JSON.parse(l)) : []
+let fails = 0; const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) fails++ }
+const agentOf = async id => (await state()).agents.find(a => a.id === id)
+const spokenBy = async (id, text) => until(`"${text}"`, async () => (await state()).spoken.find(l => l.agent === id && (text instanceof RegExp ? text.test(l.text) : l.text === text)))
+const cardFor = async id => until(`a card for ${id}`, async () => (await state()).approvals.find(a => a.session === id))
+const say = (agent, text) => call('/v1/say', { text, agent })
+
+// ---------- the spoken line a hub-run agent's answer becomes ----------
+ok(spokenLine('Tests pass: all `12` of them, in **3 seconds**. More here.') === 'Tests pass: all 12 of them, in 3 seconds.', 'an answer is said as its first sentence, without markdown')
+ok(spokenLine('Saved it to /Users/x/Developer/app/notes.md for you.') === 'Saved it to notes.md for you.', 'paths are said as file names')
+ok(spokenLine('See https://example.com/a/b for it.') === 'See a link for it.', 'links are "a link"')
+ok(spokenLine('one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen').split(' ').length === 15, 'and it is 15 words at most')
+
+// ---------- an Agent Client Protocol agent ----------
+ok(await until('acpy up', async () => (await agentOf('acpy'))?.status === 'idle'), 'the ACP agent starts with the hub and shows as idle')
+ok((await agentOf('acpy')).runtime === 'acp', 'the watch is told which runtime it is')
+const savedAcp = JSON.parse(fs.readFileSync(path.join(home, '.chums/agents.json'), 'utf8')).find(a => a.id === 'acpy').sessionId
+ok(/^fake-/.test(savedAcp ?? ''), `its session id is kept in agents.json (${savedAcp})`)
+const mcp = noted().find(n => n.agent === 'acp' && n.method === 'session/new')?.params.mcpServers?.[0]
+ok(mcp?.name === 'chums' && mcp.args[0].endsWith('channel/chums-channel.mjs') && mcp.env.some(e => e.name === 'CHUMS_SESSION'), 'its session gets the Chums MCP server, bound to its hub session')
+
+const o1 = (await say('acpy', 'run the tool please')).body
+ok(o1.kind === 'order' && o1.target === 'acpy', `an order to it is routed like any other (${o1.echo})`)
+const said1 = await spokenBy('acpy', 'Tests pass: all 12 of them, in 3 seconds.')
+ok(said1?.kind === 'done', "a turn that didn't call chums_reply is answered with its last message's first sentence")
+const p1 = noted().find(n => n.agent === 'acp' && n.method === 'session/prompt')?.text ?? ''
+ok(/^\[Standing instructions from Chums/.test(p1) && /chums_reply/.test(p1) && /\[From the watch\] \[Your soul/.test(p1) && /run the tool please$/.test(p1),
+ 'the first prompt carries the standing instructions, then the watch mark, its soul and the order')
+const st1 = await state()
+const t1 = st1.tools.filter(t => t.session === 'acpy')
+ok(t1.some(t => t.type === 'test' && /npm test/.test(t.text) && t.ok === true) && t1.some(t => t.type === 'read' && t.text === 'Read package.json'),
+ `its tool calls are events on the watch (${t1.map(t => `${t.text}:${t.ok}`).join(', ')})`)
+ok(t1.some(t => t.type === 'stop') && (await agentOf('acpy')).status === 'idle', 'the end of the turn is a stop, and it is idle again')
+ok(!st1.spoken.some(l => /replayed/.test(l.text)), 'nothing it replays is news')
+
+await say('acpy', 'approve the cleanup')
+const c1 = await cardFor('acpy')
+ok(c1?.summary === 'rm -rf build' && c1.tool === 'Bash', `its permission request is an approval card (${c1?.summary})`)
+ok((await agentOf('acpy')).status === 'waiting' && (await agentOf('acpy')).needs, 'and it waits for him')
+ok((await say('acpy', 'yes')).body.kind === 'verdict', 'a spoken yes answers it')
+ok(await spokenBy('acpy', 'Deleted the build folder.'), 'the agent carries on')
+ok(noted().filter(n => n.permission).pop()?.permission?.optionId === 'yes-once', 'yes is "allow once", never "always"')
+await say('acpy', 'approve another one')
+await until('the second card', async () => (await state()).approvals.length === 1)
+await say('acpy', 'no')
+ok(await spokenBy('acpy', 'Okay, I left it.'), 'a spoken no denies it')
+ok(noted().filter(n => n.permission).pop()?.permission?.optionId === 'no', 'no is "reject once"')
+
+await say('acpy', 'reply by the tool')
+ok(await spokenBy('acpy', 'Replied through the tool.'), 'chums_reply from its MCP server speaks on the watch')
+const chumsAsk = noted().find(n => n.chumsPermission)?.chumsPermission
+ok(chumsAsk?.optionId === 'ok' && !(await state()).approvals.length, "Chums' own tools are allowed without a card")
+await sleep(300)
+ok(!(await state()).spoken.some(l => /long final message/.test(l.text)), "once it spoke, its final message isn't said too")
+const tools = noted().find(n => n.mcpTools)?.mcpTools ?? []
+ok(tools.length === 2 && tools.every(t => t.annotations?.readOnlyHint === true), 'the MCP server offers chums_reply and chums_show, marked read-only')
+
+await say('acpy', 'refuse this')
+ok(await until('blocked', async () => (await agentOf('acpy')).status === 'blocked'), 'a refusal leaves it blocked')
+await say('acpy', 'limit please')
+ok(await until('limited', async () => (await agentOf('acpy')).status === 'limited'), 'a rate limit leaves it limited')
+
+await say('acpy', 'crash now')
+ok(await until('offline', async () => (await agentOf('acpy')).status === 'offline'), 'when its process dies it goes offline')
+ok(await until('back', async () => (await agentOf('acpy')).status === 'idle', 15000), 'and the hub starts it again')
+ok(noted().filter(n => n.agent === 'acp' && n.method === 'session/load').pop()?.params.sessionId === savedAcp, 'carrying on the same session (session/load)')
+
+// ---------- a Codex app-server ----------
+ok(await until('codey up', async () => (await agentOf('codey'))?.status === 'idle'), 'the Codex agent starts with the hub and shows as idle')
+const started = noted().find(n => n.agent === 'codex' && n.started)
+ok(started?.started === 'app-server' && started.config.some(c => c.startsWith('mcp_servers.chums.command=')) && started.config.some(c => /CHUMS_SESSION = "/.test(c)),
+ 'it runs `codex app-server` with the Chums MCP server configured')
+const ts = noted().find(n => n.agent === 'codex' && n.method === 'thread/start')?.params
+ok(ts?.model === 'gpt-6-astra' && ts.approvalPolicy === 'on-request' && ts.sandbox === 'workspace-write' && /chums_reply/.test(ts.developerInstructions) && /id: codey/.test(ts.developerInstructions),
+ 'its thread gets the model, on-request approvals in the workspace sandbox, and the standing instructions as developer instructions')
+const savedThread = JSON.parse(fs.readFileSync(path.join(home, '.chums/agents.json'), 'utf8')).find(a => a.id === 'codey').sessionId
+ok(/^thr-/.test(savedThread ?? ''), `its thread id is kept in agents.json (${savedThread})`)
+ok(noted().some(n => n.method === 'thread/name/set' && n.params.name === 'Chums: Codey' && n.params.threadId === savedThread), 'its thread is named after the agent, for Codex\'s own lists')
+const rt = JSON.parse(fs.readFileSync(path.join(home, '.chums/agents/codey.runtime.json'), 'utf8'))
+ok(rt.thread === savedThread && rt.socket.endsWith(`${cfg.port}-codey.sock`), 'and bin/chums-agents open can find its thread and socket')
+
+await say('codey', 'run the tool')
+ok(await spokenBy('codey', 'All tests pass.'), 'its final answer is said when it didn\'t call chums_reply')
+const t2 = (await state()).tools.filter(t => t.session === 'codey')
+ok(t2.some(t => t.text === 'Bash npm test' && t.type === 'test' && t.ok) && t2.some(t => t.text === 'Read package.json'),
+ `its commands are events, read as what they do (${t2.map(t => t.text).join(', ')})`)
+ok(/^\[From the watch\] \[Your soul/.test(noted().find(n => n.method === 'turn/start')?.params.input[0].text ?? ''), 'its turn carries the watch mark and its soul')
+
+await say('codey', 'approve this')
+const c2 = await cardFor('codey')
+ok(c2?.summary === 'rm -rf build', `a command approval is a card (${c2?.summary})`)
+await say('codey', 'yes')
+ok(await spokenBy('codey', 'Deleted it.'), 'yes lets it run')
+ok(noted().filter(n => n.decision).pop()?.decision === 'accept', 'as "accept"')
+await say('codey', 'edit with approval')
+const c3 = await cardFor('codey')
+ok(c3?.summary === 'edit a.js', `a file change approval is a card (${c3?.summary})`)
+await say('codey', 'no')
+ok(await spokenBy('codey', 'Done with the edit.') && noted().filter(n => n.fileDecision).pop()?.fileDecision === 'decline', 'no declines it')
+
+await say('codey', 'answered elsewhere')
+ok(await cardFor('codey'), 'a card appears')
+ok(await until('the card gone', async () => !(await state()).approvals.length), 'and goes when a Codex terminal on the thread answers first')
+ok(await spokenBy('codey', 'Deployed.'), 'the turn carries on')
+
+await say('codey', 'reply via the tool')
+ok(await spokenBy('codey', 'Codex replied by tool.'), "chums_reply from Codex's MCP server speaks on the watch")
+await sleep(300)
+ok(!(await state()).spoken.some(l => /stays on the Mac/.test(l.text)), 'and its final message is not said too')
+ok(!(await state()).tools.some(t => /chums/.test(t.text)), "Chums' own tool calls aren't events")
+
+await say('codey', 'compact then go on')
+ok(await spokenBy('codey', 'Compacted and carried on.'), 'it compacts and carries on')
+
+await say('codey', 'steer a long one')
+await until('working', async () => (await agentOf('codey')).status === 'working')
+await sleep(200)
+await say('codey', 'and one more thing')
+ok(await spokenBy('codey', 'Steered.'), 'an order while it works joins the turn (turn/steer)')
+ok(noted().some(n => n.method === 'turn/steer' && /and one more thing$/.test(n.params.input[0].text)), 'with what he said')
+
+await say('codey', 'hit the limit')
+ok(await until('limited', async () => (await agentOf('codey')).status === 'limited'), 'a usage limit leaves it limited')
+
+// ---------- its model, chosen on its card on the iPhone ----------
+fs.mkdirSync(path.join(home, '.codex'), { recursive: true })
+fs.writeFileSync(path.join(home, '.codex/models_cache.json'), JSON.stringify({ models: [
+ { slug: 'gpt-6-luna', display_name: 'GPT-6-Luna', description: 'Fast.', visibility: 'list', priority: 4 },
+ { slug: 'gpt-6-astra', display_name: 'GPT-6-Astra', description: 'Frontier.', visibility: 'list', priority: 2 },
+ { slug: 'gpt-hidden', display_name: 'Hidden', visibility: 'hide', priority: 1 },
+] }))
+fs.writeFileSync(path.join(home, '.codex/config.toml'), 'model = "gpt-6-astra"\n[profiles.x]\nmodel = "other"\n')
+const models = (await call('/v1/models')).body
+ok(models.codex.models.map(m => m.id).join() === 'gpt-6-astra,gpt-6-luna' && models.codex.default === 'GPT-6-Astra',
+ `Codex offers the models its cache lists for the account, in its order, and says what it uses by default (${models.codex.default})`)
+ok(models.claude.models.map(m => m.id).join() === 'fable,opus,sonnet,haiku', 'Claude Code offers its aliases')
+ok((await call('/v1/agents/codey/model', { model: 'gpt-hidden' })).status === 400, "a model Codex doesn't list is refused")
+const resumes = () => noted().filter(n => n.agent === 'codex' && n.method === 'thread/resume')
+const before = resumes().length
+ok((await call('/v1/agents/codey/model', { model: 'gpt-6-luna' })).body?.model === 'gpt-6-luna', 'an agent gets another model')
+ok(await until('restarted on it', async () => resumes().length > before && resumes().pop().params.model === 'gpt-6-luna'),
+ 'it restarts on it, on the same thread')
+ok(JSON.parse(fs.readFileSync(path.join(home, '.chums/agents.json'), 'utf8')).find(a => a.id === 'codey').model === 'gpt-6-luna' && (await agentOf('codey')).model === 'gpt-6-luna',
+ 'kept in agents.json, and the iPhone is told')
+await call('/v1/agents/codey/model', { model: null })
+ok(await until('back on the default', async () => resumes().pop()?.params.model === null && (await agentOf('codey')).model === null),
+ "no model: Codex's own setting again")
+
+// ---------- its permission mode, chosen on the watch or the iPhone ----------
+ok((await call('/v1/permissions')).body.codex.default === 'Asks when it needs to', "without a mode of its own it asks when it needs to (on-request)")
+ok((await call('/v1/agents/codey/permission', { mode: 'auto' })).status === 400, "a mode Codex doesn't have is refused")
+let n = resumes().length
+ok((await call('/v1/agents/codey/permission', { mode: 'untrusted' })).body?.mode === 'untrusted', 'an agent gets another approval policy')
+ok(await until('restarted in it', async () => resumes().length > n && resumes().pop().params.approvalPolicy === 'untrusted'),
+ 'it restarts in it, on the same thread')
+ok(JSON.parse(fs.readFileSync(path.join(home, '.chums/agents.json'), 'utf8')).find(a => a.id === 'codey').approvalPolicy === 'untrusted' && (await agentOf('codey')).permission === 'untrusted',
+ 'kept in agents.json as approvalPolicy, and the apps are told')
+n = resumes().length
+await call('/v1/agents/codey/permission', { mode: null })
+ok(await until('back on the default', async () => resumes().length > n && resumes().pop().params.approvalPolicy === 'on-request' && (await agentOf('codey')).permission === null),
+ 'no mode: on-request again')
+fs.writeFileSync(path.join(home, '.codex/config.toml'), 'model = "gpt-6-astra"\napproval_policy = "never"\n')
+ok((await call('/v1/permissions')).body.codex.default === 'Never asks', "with approval_policy in Codex's config.toml, that is its default")
+n = resumes().length
+await call('/v1/agents/codey/model', { model: 'gpt-6-luna' })
+ok(await until('restarted', async () => resumes().length > n && resumes().pop().params.approvalPolicy === 'never'), 'and what it runs in')
+
+// ---------- and the Claude Code path is untouched: a channel session still registers and gets orders ----------
+await call('/channel/register', { sessionId: 'cc-1', name: 'demo', cwd: '/tmp/demo' })
+await say(null, 'tell demo to say hi')
+const items = (await call('/channel/next?sessionId=cc-1')).body.items
+ok(items.some(i => i.type === 'order' && /say hi$/.test(i.text)), 'a Claude Code session still gets its orders through the channel')
+
+console.log(fails ? `${fails} FAILED` : 'all passed')
+stop(); fs.rmSync(work, { recursive: true, force: true })
+process.exit(fails ? 1 : 0)
diff --git a/tools/watch_devmode.py b/tools/watch_devmode.py
new file mode 100644
index 0000000..0488c30
--- /dev/null
+++ b/tools/watch_devmode.py
@@ -0,0 +1,80 @@
+"""Reveal (and optionally enable) Developer Mode on an Apple Watch reached through its paired iPhone.
+
+Route: Mac --usbmux--> iPhone --companion_proxy port forward--> watch lockdownd (62078).
+Usage: CHUMS_PHONE_UDID=… CHUMS_WATCH_UDID=… python3 watch_devmode.py [status|reveal|enable]
+Needs: pip install pymobiledevice3
+"""
+import asyncio
+import os
+import sys
+
+from pymobiledevice3 import usbmux
+from pymobiledevice3.lockdown import UsbmuxLockdownClient, create_using_usbmux
+from pymobiledevice3.service_connection import ServiceConnection
+from pymobiledevice3.services.amfi import AmfiService
+
+# The iPhone's and the watch's UDIDs (find them with: xcrun xctrace list devices). Set both, e.g.
+# CHUMS_PHONE_UDID=00008XXX-... CHUMS_WATCH_UDID=00008XXX-... python3 tools/watch_devmode.py reveal
+PHONE = os.environ.get("CHUMS_PHONE_UDID", "")
+WATCH = os.environ.get("CHUMS_WATCH_UDID", "")
+if not (PHONE and WATCH):
+ sys.exit("Set CHUMS_PHONE_UDID and CHUMS_WATCH_UDID (from: xcrun xctrace list devices). The iPhone must be on USB.")
+LOCKDOWN_PORT = 62078
+
+_keepalive = [] # companion_proxy connections must stay open for their forwards to live
+
+
+async def forward(phone, gizmo_port: int) -> ServiceConnection:
+ svc = await phone.start_lockdown_service("com.apple.companion_proxy")
+ resp = await svc.send_recv_plist({
+ "Command": "StartForwardingServicePort",
+ "GizmoRemotePortNumber": gizmo_port,
+ "IsServiceLowPriority": False,
+ "PreferWifi": False,
+ })
+ local = resp.get("CompanionProxyServicePort")
+ if local is None:
+ raise RuntimeError(f"forward of watch port {gizmo_port} failed: {resp}")
+ _keepalive.append(svc)
+ return await ServiceConnection.create_using_usbmux(PHONE, local)
+
+
+def watch_client_class(phone):
+ class WatchLockdown(UsbmuxLockdownClient):
+ async def create_service_connection(self, port: int) -> ServiceConnection:
+ return await forward(phone, port)
+
+ return WatchLockdown
+
+
+async def main(action: str) -> None:
+ phone = await create_using_usbmux(PHONE, connection_type="USB")
+ print("phone:", phone.all_values.get("DeviceName"), phone.all_values.get("ProductVersion"))
+
+ async with await usbmux.create_mux() as mux:
+ pair_record = await mux.get_pair_record(WATCH)
+ system_buid = await mux.get_buid()
+
+ conn = await forward(phone, LOCKDOWN_PORT)
+ cls = watch_client_class(phone)
+ watch = await cls.create(conn, identifier=WATCH, pair_record=pair_record, system_buid=system_buid,
+ autopair=True, pair_timeout=90)
+ v = watch.all_values
+ print("watch:", v.get("DeviceName"), v.get("ProductType"), "watchOS", v.get("ProductVersion"))
+ status = await watch.get_value("com.apple.security.mac.amfi", "DeveloperModeStatus")
+ print("DeveloperModeStatus:", status)
+
+ amfi = AmfiService(watch)
+ if action == "reveal":
+ await amfi.reveal_developer_mode_option_in_ui()
+ print("reveal: OK - Developer Mode toggle should now show in Settings > Privacy & Security")
+ elif action == "accept":
+ await amfi.enable_developer_mode_post_restart()
+ print("accept: OK")
+ elif action == "enable":
+ await amfi.enable_developer_mode(enable_post_restart=False)
+ print("enable: sent - watch will restart and ask to confirm")
+
+
+if __name__ == "__main__":
+ asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else "status"))