Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Train D1: Open Bot Avatar bodies, our shapes on its engine, and custom body colours (#7131)
Milind Sonid6660e2d7978
diff --git a/.oxlintrc.json b/.oxlintrc.jsonindex e60f86a17e..14d47acf9e 100644--- a/.oxlintrc.json+++ b/.oxlintrc.json@@ -18,6 +18,7 @@"electron/vendor/**","release/**","third_party/**",+ "packages/phone-protocol/src/open-bot-avatar/**","electron/resources/**"],"overrides": [diff --git a/NOTICE b/NOTICEindex 9102af1f56..c84dc5df62 100644--- a/NOTICE+++ b/NOTICE@@ -129,3 +129,9 @@ Teams' display-name rule. Copyright 2025-2026 Vexa.ai Inc. and the Vexacontributors, used under the Apache License, Version 2.0(third_party/vexa/LICENSE). The adapted parts were rewritten in our own code;no Vexa file is included unmodified.++The object avatars bots can wear include the engine and avatar definitions of+Open Bot Avatar 0.3.0, with the changes its vendored README lists,+https://github.com/DominikScholz/open-bot-avatar, Copyright (c) 2026 Dominik+Scholz, used under the MIT License+(packages/phone-protocol/src/open-bot-avatar/LICENSE).diff --git a/README.md b/README.mdindex dcc633b98d..32db064d05 100644--- a/README.md+++ b/README.md@@ -274,6 +274,7 @@ expressions · screenshots of the bot's work folded into the transcript.| **Cua Driver** | Native computer use on your own machine || **ElevenLabs · Fish Audio** | Hosted voices for bots that talk back || **GitHub Sponsors** | One-time and monthly project support |+| **Open Bot Avatar** ([github.com/DominikScholz/open-bot-avatar](https://github.com/DominikScholz/open-bot-avatar)) | The avatar engine and many of the bot avatars, by Dominik Scholz |## How it works@@ -551,6 +552,11 @@ Packaged Cua Driver components retain their upstream MIT, SIL OFL 1.1, MPL-2.0,the corresponding notices, license texts, source locations, and SBOM are in[`third_party/cua-driver/`](third_party/cua-driver/) and ship beside the native runtime.+The bot avatar engine and avatar designs come from+[Open Bot Avatar](https://github.com/DominikScholz/open-bot-avatar), Copyright (c) 2026 Dominik Scholz,+used under the MIT License; its license and our changes are in+[`packages/phone-protocol/src/open-bot-avatar/`](packages/phone-protocol/src/open-bot-avatar/).+OpenMausBot is an independent, open-source project inspired by Grok Bot. It isnot affiliated with, endorsed by, or associated with xAI; "Grok" is a trademarkof its respective owner.diff --git a/electron/places-together.d.mts b/electron/places-together.d.mtsindex dea83c7c27..962e2e95d0 100644--- a/electron/places-together.d.mts+++ b/electron/places-together.d.mts@@ -15,6 +15,7 @@ export interface PlaceBotRow {color?: string;mascotBody?: string;mascotFaceColor?: string;+ mascotBodyColor?: string;chief?: true;waiting?: true;working?: true;diff --git a/electron/places-together.mjs b/electron/places-together.mjsindex 32fd02fb9a..b0c79ba8be 100644--- a/electron/places-together.mjs+++ b/electron/places-together.mjs@@ -54,9 +54,9 @@ export function botRow(bot, home) {if (!record(bot) || !ID.test(String(bot.id)) || !ID.test(String(bot.threadId)) || bot.hidden || bot.sidebarHidden || bot.movedTo) return null;const name = text(bot.name, 80);if (!name) return null;- const title = text(bot.title, 80), color = look(bot.color), body = look(bot.mascotBody), face = look(bot.mascotFaceColor);+ const title = text(bot.title, 80), color = look(bot.color), body = look(bot.mascotBody), face = look(bot.mascotFaceColor), tint = look(bot.mascotBodyColor);return { home, id: bot.id, threadId: bot.threadId, name, ...(title ? { title } : {}), ...(color ? { color } : {}),- ...(body ? { mascotBody: body } : {}), ...(face ? { mascotFaceColor: face } : {}), ...(bot.chiefOfStaff === true ? { chief: true } : {}), ...rowState(bot) };+ ...(body ? { mascotBody: body } : {}), ...(face ? { mascotFaceColor: face } : {}), ...(tint ? { mascotBodyColor: tint } : {}), ...(bot.chiefOfStaff === true ? { chief: true } : {}), ...rowState(bot) };}/** The AIs a place's `GET /api/instances` answer says are ready to use: installed and signed in, never one that onlydiff --git a/packages/phone-protocol/src/bot-avatar.ts b/packages/phone-protocol/src/bot-avatar.tsindex e359281c73..adcb38e400 100644--- a/packages/phone-protocol/src/bot-avatar.ts+++ b/packages/phone-protocol/src/bot-avatar.ts@@ -4,6 +4,12 @@ export const MASCOT_FACE_COLORS = ["white", "black"] as const;export const mascotFaceColorSchema = z.enum(MASCOT_FACE_COLORS);export type MascotFaceColor = z.infer<typeof mascotFaceColorSchema>;+/** A custom avatar body tint, stored as lowercase `#rrggbb`. */+export const mascotBodyColorSchema = z+ .string()+ .regex(/^#[0-9a-f]{6}$/i, "must be a #rrggbb hex colour")+ .transform((value) => value.toLowerCase());+export function mascotFaceInk(value: unknown): string | undefined {const color = mascotFaceColorSchema.safeParse(value).data;return color === "white" ? "#ffffff" : color === "black" ? "#000000" : undefined;diff --git a/packages/phone-protocol/src/bot-body.ts b/packages/phone-protocol/src/bot-body.tsindex 5d3e076a79..9e967614e4 100644--- a/packages/phone-protocol/src/bot-body.ts+++ b/packages/phone-protocol/src/bot-body.ts@@ -1,15 +1,19 @@-/** Every body a bot can wear: the gradient catalog plus the festival bodies. */+/** Every body a bot can wear: the gradient catalog, the festival bodies and the object avatars. */import { z } from "zod";import { DEFAULT_MASCOT_BODY, MASCOT_BODY_IDS } from "./mascot-bodies.ts";import { CARVED_BODY_IDS, DIWALI_BODY_IDS, HALLOWEEN_BODY_IDS, type CarvedBodyId } from "./carved-bodies.ts";+import { OBJECT_BODY_IDS, type ObjectBodyId } from "./object-bodies.ts";import type { MausColor } from "./wire.ts";-export const BOT_BODY_IDS = [...MASCOT_BODY_IDS, ...CARVED_BODY_IDS] as const;+export const BOT_BODY_IDS = [...MASCOT_BODY_IDS, ...CARVED_BODY_IDS, ...OBJECT_BODY_IDS] as const;export type BotBodyId = (typeof BOT_BODY_IDS)[number];+/** The bodies a look picker always offers, in its order: the shapes, then the objects. */+export const EVERYDAY_BODY_IDS = [...MASCOT_BODY_IDS, ...OBJECT_BODY_IDS] as const;+export const botBodySchema = z.enum(BOT_BODY_IDS);/** Runtime-safe read of an untrusted persisted or streamed body id. */@@ -21,6 +25,10 @@ export function isCarvedBody(value: unknown): value is CarvedBodyId {return (CARVED_BODY_IDS as readonly unknown[]).includes(value);}+export function isObjectBody(value: unknown): value is ObjectBodyId {+ return (OBJECT_BODY_IDS as readonly unknown[]).includes(value);+}+export type CostumeColor = Exclude<MausColor, "silver" | "chrome">;/** A festival skin's own bodies, and the costume each bot colour wears while "Dress my bots up" is on with it. */diff --git a/packages/phone-protocol/src/mascot-bodies.ts b/packages/phone-protocol/src/mascot-bodies.tsindex 8c11bf2c4b..2a4a4c4485 100644--- a/packages/phone-protocol/src/mascot-bodies.ts+++ b/packages/phone-protocol/src/mascot-bodies.ts@@ -5,10 +5,8 @@* `scripts/gen-mascot-bodies.ts`, which solves each face placement against the real* expression geometry and verifies that nothing clips.*- * Every body carries the same face at the same size: the generator clamps the whole- * catalog to the smallest face any one body can hold, so the mascot reads as one- * character in different bodies rather than ten different mascots. Roomier bodies simply- * end up with more margin around the face.+ * The cursor keeps the face it shipped with. Every other body wears the largest face it+ * holds with room to spare, never smaller than the cursor's, so the face leads the shape.** The fields match `CursorSilhouette` exactly, so a body can be handed to the renderer* with no adapter in between.@@ -55,7 +53,7 @@ export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {fit: "translate(-0.7217 2.9555) scale(1.134706)",body: "<path fill=\"{{GRADIENT}}\" d=\"M198.91052 113.12915C198.30169 121.88191 196.37668 130.37605 193.1355 138.61157C189.89431 146.84709 185.49332 154.4026 179.93252 161.27809C174.37172 168.15358 167.99976 174.1053 160.81663 179.13325C153.6335 184.1612 145.98678 188.22176 137.87645 191.31491C129.76613 194.40806 121.42581 196.55178 112.85548 197.74609C104.28516 198.94039 95.66469 199.12755 86.99407 198.30758C78.32344 197.4876 69.86713 195.54477 61.62513 192.47909C53.38313 189.41341 45.74309 185.20915 38.70501 179.86633C31.66693 174.52351 25.60941 168.25632 20.53243 161.06476C15.45546 153.87319 11.54067 146.15559 8.78808 137.91195C6.03549 129.66831 4.37316 121.28874 3.80109 112.77325C3.22902 104.25775 3.5616 95.83136 4.79882 87.49409C6.03604 79.15682 8.08364 70.99969 10.94163 63.0227C13.79962 55.04571 17.53174 47.38891 22.13799 40.0523C26.74425 32.71568 32.30193 26.0276 38.81103 19.98806C45.32014 13.94852 52.65266 9.00619 60.80862 5.16109C68.96458 1.31599 77.53546 -1.10241 86.52128 -2.09412C95.50709 -3.08583 104.37427 -2.64309 113.12282 -0.76589C121.87137 1.11131 130.09712 4.12751 137.80007 8.28271C145.50302 12.43791 152.53652 17.35515 158.90058 23.03443C165.26463 28.7137 170.969 34.91856 176.01368 41.649C181.05836 48.37944 185.3953 55.56843 189.02451 63.21597C192.65372 70.86352 195.3609 78.90607 197.14605 87.34364C198.93119 95.78121 199.51935 104.37638 198.91052 113.12915Z\"/>",clip: "<path d=\"M198.91052 113.12915C198.30169 121.88191 196.37668 130.37605 193.1355 138.61157C189.89431 146.84709 185.49332 154.4026 179.93252 161.27809C174.37172 168.15358 167.99976 174.1053 160.81663 179.13325C153.6335 184.1612 145.98678 188.22176 137.87645 191.31491C129.76613 194.40806 121.42581 196.55178 112.85548 197.74609C104.28516 198.94039 95.66469 199.12755 86.99407 198.30758C78.32344 197.4876 69.86713 195.54477 61.62513 192.47909C53.38313 189.41341 45.74309 185.20915 38.70501 179.86633C31.66693 174.52351 25.60941 168.25632 20.53243 161.06476C15.45546 153.87319 11.54067 146.15559 8.78808 137.91195C6.03549 129.66831 4.37316 121.28874 3.80109 112.77325C3.22902 104.25775 3.5616 95.83136 4.79882 87.49409C6.03604 79.15682 8.08364 70.99969 10.94163 63.0227C13.79962 55.04571 17.53174 47.38891 22.13799 40.0523C26.74425 32.71568 32.30193 26.0276 38.81103 19.98806C45.32014 13.94852 52.65266 9.00619 60.80862 5.16109C68.96458 1.31599 77.53546 -1.10241 86.52128 -2.09412C95.50709 -3.08583 104.37427 -2.64309 113.12282 -0.76589C121.87137 1.11131 130.09712 4.12751 137.80007 8.28271C145.50302 12.43791 152.53652 17.35515 158.90058 23.03443C165.26463 28.7137 170.969 34.91856 176.01368 41.649C181.05836 48.37944 185.3953 55.56843 189.02451 63.21597C192.65372 70.86352 195.3609 78.90607 197.14605 87.34364C198.93119 95.78121 199.51935 104.37638 198.91052 113.12915Z\"/>",- anchor: { x: 111.22, y: 116.58, scale: 0.791 },+ anchor: { x: 112.08, y: 117.43, scale: 1.216 },},circle: {id: "circle",@@ -63,7 +61,7 @@ export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {fit: "translate(0 0) scale(1.142705)",body: "<path fill=\"{{GRADIENT}}\" d=\"M200 100C200 155.22847 155.22847 200 100 200C44.77153 200 0 155.22847 0 100C0 44.77153 44.77153 0 100 0C155.22847 0 200 44.77153 200 100Z\"/>",clip: "<path d=\"M200 100C200 155.22847 155.22847 200 100 200C44.77153 200 0 155.22847 0 100C0 44.77153 44.77153 0 100 0C155.22847 0 200 44.77153 200 100Z\"/>",- anchor: { x: 113.82, y: 110.27, scale: 0.791 },+ anchor: { x: 113.82, y: 112.05, scale: 1.26 },},squircle: {id: "squircle",@@ -71,7 +69,7 @@ export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {fit: "translate(0 0) scale(1.142705)",body: "<path fill=\"{{GRADIENT}}\" d=\"M50 0C83.33333 0 116.66667 0 150 0C177.61424 0 200 22.38576 200 50C200 83.33333 200 116.66667 200 150C200 177.61424 177.61424 200 150 200C116.66667 200 83.33333 200 50 200C22.38576 200 0 177.61424 0 150C0 116.66667 0 83.33333 0 50C0 22.38576 22.38576 0 50 0Z\"/>",clip: "<path d=\"M50 0C83.33333 0 116.66667 0 150 0C177.61424 0 200 22.38576 200 50C200 83.33333 200 116.66667 200 150C200 177.61424 177.61424 200 150 200C116.66667 200 83.33333 200 50 200C22.38576 200 0 177.61424 0 150C0 116.66667 0 83.33333 0 50C0 22.38576 22.38576 0 50 0Z\"/>",- anchor: { x: 111.78, y: 111.79, scale: 0.791 },+ anchor: { x: 111.79, y: 109.75, scale: 1.332 },},capsule: {id: "capsule",@@ -79,7 +77,7 @@ export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {fit: "translate(0 0) scale(1.142705)",body: "<path fill=\"{{GRADIENT}}\" d=\"M100 0C141.42136 0 175 33.57864 175 75C175 91.66667 175 108.33333 175 125C175 166.42136 141.42136 200 100 200C58.57864 200 25 166.42136 25 125C25 108.33333 25 91.66667 25 75C25 33.57864 58.57864 0 100 0Z\"/>",clip: "<path d=\"M100 0C141.42136 0 175 33.57864 175 75C175 91.66667 175 108.33333 175 125C175 166.42136 141.42136 200 100 200C58.57864 200 25 166.42136 25 125C25 108.33333 25 91.66667 25 75C25 33.57864 58.57864 0 100 0Z\"/>",- anchor: { x: 113.82, y: 131.68, scale: 0.791 },+ anchor: { x: 113.82, y: 131.68, scale: 0.979 },},drop: {id: "drop",@@ -87,7 +85,7 @@ export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {fit: "translate(-3.5341 -3.5341) scale(1.178046)",body: "<path fill=\"{{GRADIENT}}\" d=\"M100 3C160.84 78.2235 178 103.298 178 119C178 162.07821 143.07821 197 100 197C56.92179 197 22 162.07821 22 119C22 103.298 39.16 78.2235 100 3Z\"/>",clip: "<path d=\"M100 3C160.84 78.2235 178 103.298 178 119C178 162.07821 143.07821 197 100 197C56.92179 197 22 162.07821 22 119C22 103.298 39.16 78.2235 100 3Z\"/>",- anchor: { x: 112.47, y: 138.8, scale: 0.791 },+ anchor: { x: 113.15, y: 138.12, scale: 0.964 },},shield: {id: "shield",@@ -95,7 +93,7 @@ export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {fit: "translate(-12.1611 -24.3222) scale(1.264316)",body: "<path fill=\"{{GRADIENT}}\" d=\"M57.25 38.475C85.75 12.825 114.25 12.825 142.75 38.475C153.89667 76.64167 165.04333 114.80833 176.19 152.975C188.73 184.325 179.325 200 147.975 200C115.99167 200 84.00833 200 52.025 200C20.675 200 11.27 184.325 23.81 152.975C34.95667 114.80833 46.10333 76.64167 57.25 38.475Z\"/>",clip: "<path d=\"M57.25 38.475C85.75 12.825 114.25 12.825 142.75 38.475C153.89667 76.64167 165.04333 114.80833 176.19 152.975C188.73 184.325 179.325 200 147.975 200C115.99167 200 84.00833 200 52.025 200C20.675 200 11.27 184.325 23.81 152.975C34.95667 114.80833 46.10333 76.64167 57.25 38.475Z\"/>",- anchor: { x: 112.38, y: 170.61, scale: 0.791 },+ anchor: { x: 113.11, y: 156.97, scale: 0.964 },},hexagon: {id: "hexagon",@@ -103,7 +101,7 @@ export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {fit: "translate(-4.1077 -4.1077) scale(1.183782)",body: "<path fill=\"{{GRADIENT}}\" d=\"M94.90777 4.94C98.30259 2.98 101.69741 2.98 105.09223 4.94C129.98757 19.31333 154.88292 33.68667 179.77826 48.06C183.17308 50.02 184.87049 52.96 184.87049 56.88C184.87049 85.62667 184.87049 114.37333 184.87049 143.12C184.87049 147.04 183.17308 149.98 179.77826 151.94C154.88292 166.31333 129.98757 180.68667 105.09223 195.06C101.69741 197.02 98.30259 197.02 94.90777 195.06C70.01243 180.68667 45.11708 166.31333 20.22174 151.94C16.82692 149.98 15.12951 147.04 15.12951 143.12C15.12951 114.37333 15.12951 85.62667 15.12951 56.88C15.12951 52.96 16.82692 50.02 20.22174 48.06C45.11708 33.68667 70.01243 19.31333 94.90777 4.94Z\"/>",clip: "<path d=\"M94.90777 4.94C98.30259 2.98 101.69741 2.98 105.09223 4.94C129.98757 19.31333 154.88292 33.68667 179.77826 48.06C183.17308 50.02 184.87049 52.96 184.87049 56.88C184.87049 85.62667 184.87049 114.37333 184.87049 143.12C184.87049 147.04 183.17308 149.98 179.77826 151.94C154.88292 166.31333 129.98757 180.68667 105.09223 195.06C101.69741 197.02 98.30259 197.02 94.90777 195.06C70.01243 180.68667 45.11708 166.31333 20.22174 151.94C16.82692 149.98 15.12951 147.04 15.12951 143.12C15.12951 114.37333 15.12951 85.62667 15.12951 56.88C15.12951 52.96 16.82692 50.02 20.22174 48.06C45.11708 33.68667 70.01243 19.31333 94.90777 4.94Z\"/>",- anchor: { x: 112.26, y: 110.7, scale: 0.791 },+ anchor: { x: 112.26, y: 110.7, scale: 1.132 },},diamond: {id: "diamond",@@ -111,15 +109,15 @@ export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {fit: "translate(-5.9383 -5.9383) scale(1.202088)",body: "<path fill=\"{{GRADIENT}}\" d=\"M94.12 7.88C98.04 3.96 101.96 3.96 105.88 7.88C134.62667 36.62667 163.37333 65.37333 192.12 94.12C196.04 98.04 196.04 101.96 192.12 105.88C163.37333 134.62667 134.62667 163.37333 105.88 192.12C101.96 196.04 98.04 196.04 94.12 192.12C65.37333 163.37333 36.62667 134.62667 7.88 105.88C3.96 101.96 3.96 98.04 7.88 94.12C36.62667 65.37333 65.37333 36.62667 94.12 7.88Z\"/>",clip: "<path d=\"M94.12 7.88C98.04 3.96 101.96 3.96 105.88 7.88C134.62667 36.62667 163.37333 65.37333 192.12 94.12C196.04 98.04 196.04 101.96 192.12 105.88C163.37333 134.62667 134.62667 163.37333 105.88 192.12C101.96 196.04 98.04 196.04 94.12 192.12C65.37333 163.37333 36.62667 134.62667 7.88 105.88C3.96 101.96 3.96 98.04 7.88 94.12C36.62667 65.37333 65.37333 36.62667 94.12 7.88Z\"/>",- anchor: { x: 112.53, y: 109.95, scale: 0.791 },+ anchor: { x: 112.53, y: 110.59, scale: 0.929 },},star: {id: "star",name: "Star",fit: "translate(-8.3327 3.1407) scale(1.226032)",- body: "<path fill=\"{{GRADIENT}}\" d=\"M100 2C110.56054 20.13133 121.12108 38.26266 131.68163 56.39398C152.18893 60.83477 172.69623 65.27555 193.20354 69.71633C179.22301 85.3629 165.24248 101.00946 151.26195 116.65602C153.37562 137.5319 155.48929 158.40778 157.60295 179.28367C138.40197 170.82244 119.20098 162.36122 100 153.9C80.79902 162.36122 61.59803 170.82244 42.39705 179.28367C44.51071 158.40778 46.62438 137.5319 48.73805 116.65602C34.75752 101.00946 20.77699 85.3629 6.79646 69.71633C27.30377 65.27555 47.81107 60.83477 68.31837 56.39398C78.87892 38.26266 89.43946 20.13133 100 2Z\"/>",- clip: "<path d=\"M100 2C110.56054 20.13133 121.12108 38.26266 131.68163 56.39398C152.18893 60.83477 172.69623 65.27555 193.20354 69.71633C179.22301 85.3629 165.24248 101.00946 151.26195 116.65602C153.37562 137.5319 155.48929 158.40778 157.60295 179.28367C138.40197 170.82244 119.20098 162.36122 100 153.9C80.79902 162.36122 61.59803 170.82244 42.39705 179.28367C44.51071 158.40778 46.62438 137.5319 48.73805 116.65602C34.75752 101.00946 20.77699 85.3629 6.79646 69.71633C27.30377 65.27555 47.81107 60.83477 68.31837 56.39398C78.87892 38.26266 89.43946 20.13133 100 2Z\"/>",- anchor: { x: 113.82, y: 125.43, scale: 0.791 },+ body: "<path fill=\"{{GRADIENT}}\" d=\"M100 2C111.90461 18.28138 123.80922 34.56275 135.71383 50.84413C154.87707 57.13486 174.0403 63.4256 193.20354 69.71633C181.39776 86.06951 169.59198 102.42269 157.78619 118.77587C157.72511 138.94514 157.66403 159.1144 157.60295 179.28367C138.40197 173.10911 119.20098 166.93456 100 160.76C80.79902 166.93456 61.59803 173.10911 42.39705 179.28367C42.33597 159.1144 42.27489 138.94514 42.21381 118.77587C30.40802 102.42269 18.60224 86.06951 6.79646 69.71633C25.9597 63.4256 45.12293 57.13486 64.28617 50.84413C76.19078 34.56275 88.09539 18.28138 100 2Z\"/>",+ clip: "<path d=\"M100 2C111.90461 18.28138 123.80922 34.56275 135.71383 50.84413C154.87707 57.13486 174.0403 63.4256 193.20354 69.71633C181.39776 86.06951 169.59198 102.42269 157.78619 118.77587C157.72511 138.94514 157.66403 159.1144 157.60295 179.28367C138.40197 173.10911 119.20098 166.93456 100 160.76C80.79902 166.93456 61.59803 173.10911 42.39705 179.28367C42.33597 159.1144 42.27489 138.94514 42.21381 118.77587C30.40802 102.42269 18.60224 86.06951 6.79646 69.71633C25.9597 63.4256 45.12293 57.13486 64.28617 50.84413C76.19078 34.56275 88.09539 18.28138 100 2Z\"/>",+ anchor: { x: 113.82, y: 125.43, scale: 0.845 },},};diff --git a/packages/phone-protocol/src/object-bodies.ts b/packages/phone-protocol/src/object-bodies.tsnew file mode 100644index 0000000000..e987b0c5dc--- /dev/null+++ b/packages/phone-protocol/src/object-bodies.ts@@ -0,0 +1,162 @@+/**+ * Open Bot Avatar's avatars, worn as bodies: its seven starters, then its gallery. MIT, Copyright (c) 2026+ * Dominik Scholz. Ids carry "obj-" so they never meet a shape or festival body's.+ */++import type { MascotBodyId } from "./mascot-bodies.ts";+import { examples } from "./open-bot-avatar/examples.ts";+import type { AvatarDefinition } from "./open-bot-avatar/types.ts";++/** In the order the look pickers show them. */+export const OBJECT_BODY_IDS = [+ "obj-controller", "obj-barbell", "obj-mug", "obj-lightbulb", "obj-chat", "obj-sprout",+ "obj-watering-can", "obj-book", "obj-brain", "obj-bull", "obj-bunny", "obj-camera",+ "obj-cat", "obj-cloud", "obj-egg", "obj-ghost", "obj-magnifier", "obj-paint-brush",+ "obj-palette", "obj-rocket", "obj-witch-hat",+] as const;++export type ObjectBodyId = (typeof OBJECT_BODY_IDS)[number];++const GALLERY: AvatarDefinition[] = [+ {+ version: 1,+ id: "book",+ name: "Book",+ body: { path: "M12 32C12 29 14 27 17 26C30 21.5 42 23 50 31C58 23 70 21.5 83 26C86 27 88 29 88 32V64H89C90.7 64 92 65.3 92 67V75C92 77 90.5 78 88.5 77.5C76 75 60 76 50 84C40 76 24 75 11.5 77.5C9.5 78 8 77 8 75V67C8 65.3 9.3 64 11 64H12Z" },+ eyes: { x: 50, y: 51, spacing: 18, scale: 1.1 },+ },+ {+ version: 1,+ id: "brain",+ name: "Brain",+ body: { path: "M14 50C10 42 14 32 22 30C24 21 34 17 41 21C46 15 56 15 61 20C68 16 78 20 79 28C87 30 91 39 88 47C92 54 89 64 81 66C80 71 76 74 71 73C67 75 64 74 62 72C61 74 61 76 61.5 78C62 81 59 82.5 57 81.5C55.5 80.5 55 78 54 76C53 74 50 72.5 47 72.5C42 74 38 72 36 70C30 73 20 71 18 64C12 62 10 56 14 50Z" },+ eyes: { x: 50, y: 45, spacing: 17, scale: 1.15 },+ },+ {+ version: 1,+ id: "bull",+ name: "Bull",+ body: { path: "M40 28L60 28C70 28 76 36 76 48L76 62C76 74 66 84 50 84C34 84 24 74 24 62L24 48C24 36 30 28 40 28ZM32 40C22 38 15 32 15 24C15 18 18 13 22 10C25 8 28 10 27 13C25 18 24 22 28 26C31 29 36 30 42 30ZM58 30C64 30 69 29 72 26C76 22 75 18 73 13C72 10 75 8 78 10C82 13 85 18 85 24C85 32 78 38 68 40ZM29 55C23 56 17 55 12 52C9 50 8 47 10 45C14 41 22 40 28 42ZM72 42C78 40 86 41 90 45C92 47 91 50 88 52C83 55 77 56 71 55Z" },+ eyes: { x: 50, y: 52, spacing: 17, scale: 1.15 },+ },+ {+ version: 1,+ id: "bunny",+ name: "Bunny",+ body: { path: "M50 40C68 40 80 50 80 64C80 78 68 86 50 86C32 86 20 78 20 64C20 50 32 40 50 40ZM30 46C26 36 24 24 26 16C28 10 34 10 37 15C40 22 42 34 42 44ZM58 44C58 34 61 22 66 15C69 10 76 11 76 17C76 25 74 36 70 46Z" },+ eyes: { x: 50, y: 62, spacing: 17, scale: 1.15 },+ },+ {+ version: 1,+ id: "camera",+ name: "Camera",+ body: { path: "M17 34H20V31C20 29 21 28 23 28H27C29 28 30 29 30 31V34H36L40 23C41 21 42 20 44 20H56C58 20 59 21 60 23L64 34H83C87.5 34 91 37.5 91 42V72C91 76.5 87.5 80 83 80H17C12.5 80 9 76.5 9 72V42C9 37.5 12.5 34 17 34Z" },+ eyes: { x: 50, y: 54, spacing: 17, scale: 1.1 },+ },+ {+ version: 1,+ id: "cat",+ name: "Cat",+ body: { path: "M50 23C68 23 82 30 82 45C82 58 68 65 50 65C32 65 18 58 18 45C18 30 32 23 50 23ZM24 42C21 32 20 22 22 15C23 11 26 10 29 12C34 16 39 21 44 28L36 42ZM64 42L56 28C61 21 66 16 71 12C74 10 77 11 78 15C80 22 79 32 76 42ZM38 56L62 56C70 56 74 66 74 76C74 83 70 86 63 86L37 86C30 86 26 83 26 76C26 66 30 56 38 56ZM70 72C77 74 81 70 80 64C79 60 81 57 84 58C87 59 88.5 63 88 68C87 77 80 83 70 81Z" },+ eyes: { x: 50, y: 43, spacing: 17, scale: 1.1 },+ },+ {+ version: 1,+ id: "cloud",+ name: "Cloud",+ body: { path: "M24 76C14 76 9 69 9 61C9 52 15 46 23 45.5C25 33 36 24 49 24C61 24 70 31 73 41C83 41 91 49 91 59C91 69 83 76 74 76Z" },+ eyes: { x: 50, y: 54, spacing: 17, scale: 1.15 },+ },+ {+ version: 1,+ id: "egg",+ name: "Egg",+ body: { path: "M50 10C66 10 82 34 82 58C82 76 68 88 50 88C32 88 18 76 18 58C18 34 34 10 50 10Z" },+ eyes: { x: 50, y: 54, spacing: 17, scale: 1.2 },+ },+ {+ version: 1,+ id: "ghost",+ name: "Ghost",+ body: { path: "M24 50C24 28 35 12 50 12C65 12 76 28 76 50L77 80C77 85 73 88 68 88C63 88 61 84 59 81C57 84 54 88 50 88C46 88 43 84 41 81C39 84 37 88 32 88C27 88 23 85 23 80Z" },+ eyes: { x: 50, y: 42, spacing: 16, scale: 1.15 },+ },+ {+ version: 1,+ id: "magnifier",+ name: "Magnifier",+ body: { path: "M41 12A29 29 0 0 1 64.44 58.08L68.50 62.13A8 8 0 0 1 75.65 64.33L87.67 76.36A8 8 0 0 1 76.36 87.67L64.33 75.65A8 8 0 0 1 62.13 68.50L58.08 64.44A29 29 0 1 1 41 12Z" },+ eyes: { x: 41, y: 40, spacing: 17, scale: 1.15 },+ },+ {+ version: 1,+ id: "paint-brush",+ name: "Paint Brush",+ body: { path: "M77.2 8.5C80.3 8.7 82.3 10.2 83.4 13.1C84 14.5 83.3 16.2 82.3 17.6L65.9 40.8L56.2 33.7L73.2 11C74.2 9.6 75.6 8.5 77.2 8.5ZM55.4 26.8L72.8 39.4C74.2 40.4 74.5 42.2 73.5 43.6L66.6 53C65.6 54.4 63.8 54.7 62.4 53.7L45.1 41C43.7 40 43.4 38.2 44.4 36.8L51.2 27.4C52.2 26 54 25.8 55.4 26.8ZM48.4 38.7L63.7 49.8C67.9 57.1 66.8 65.9 61.8 72.9C54.7 82.6 41.2 86.6 25.2 85.1C22.2 85 20 82.9 21 79.9C24.6 71.4 21.1 57.1 28.2 47.4C33.3 40.4 40.8 37.4 48.4 38.7Z" },+ eyes: { x: 44, y: 59, spacing: 16, scale: 1.05 },+ },+ {+ version: 1,+ id: "palette",+ name: "Palette",+ body: { path: "M46 18C70 16 90 28 90 48C90 68 74 84 52 84C42 84 36 80 34 74C32 68 36 64 32 60C28 56 22 62 16 58C10 54 10 46 12 40C16 26 30 19 46 18ZM21 44A5 5 0 1 0 31 44A5 5 0 1 0 21 44Z" },+ eyes: { x: 58, y: 46, spacing: 17, scale: 1.15 },+ },+ {+ version: 1,+ id: "rocket",+ name: "Rocket",+ body: { path: "M46 10C48 8.5 52 8.5 54 10C64 17 71 29 71 44V72H29V44C29 29 36 17 46 10ZM29 56H71C80 61 86 70 86 80C86 84 83 86 79 85L72 83H28L21 85C17 86 14 84 14 80C14 70 20 61 29 56ZM42 80H58C59 86 55 90 50 92C45 90 41 86 42 80Z" },+ eyes: { x: 50, y: 46, spacing: 15, scale: 1.05 },+ },+ {+ version: 1,+ id: "shield",+ name: "Shield",+ body: { path: "M50 14C60 18 72 18 82 16Q86 16 86 20L86 46C86 64 72 78 54 86.5Q50 88.5 46 86.5C28 78 14 64 14 46L14 20Q14 16 18 16C28 18 40 18 50 14Z" },+ eyes: { x: 50, y: 42, spacing: 17, scale: 1.15 },+ },+ {+ version: 1,+ id: "star",+ name: "Star",+ body: { path: "M53.7 17.95L62 31.2Q64.1 34.6 68 35.6L83.1 39.3Q89.9 41 85.4 46.4L75.4 58.3Q72.8 61.4 73.1 65.4L74.2 81Q74.7 88 68.2 85.4L53.7 79.5Q50 78 46.3 79.5L31.8 85.4Q25.3 88 25.8 81L26.9 65.4Q27.2 61.4 24.6 58.3L14.6 46.4Q10.1 41 16.9 39.3L32 35.6Q35.9 34.6 38 31.2L46.3 17.95Q50 12 53.7 17.95Z" },+ eyes: { x: 50, y: 52, spacing: 16, scale: 1.1 },+ },+ {+ version: 1,+ id: "witch-hat",+ name: "Witch Hat",+ body: { path: "M50 72C72 72 92 75 92 80C92 85 72 87 50 87C28 87 8 85 8 80C8 75 28 72 50 72ZM37 30L63 30Q68 30 68.8 35L77.5 76Q78 80 74 80L26 80Q22 80 22.5 76L31.2 35Q32 30 37 30ZM30.56 38C33 26.5 40 18 52 14C62 10.5 72 9 81 11A3.2 3.2 0 0 1 81 17.4C74 18 69.5 24.5 68.1 31.5L69.44 38Z" },+ eyes: { x: 50, y: 54, spacing: 15, scale: 1.05 },+ },+];++const SHIELD = GALLERY.find((one) => one.id === "shield") as AvatarDefinition;+const STAR = GALLERY.find((one) => one.id === "star") as AvatarDefinition;++export const OBJECT_BODIES = Object.fromEntries(+ [...examples, ...GALLERY].filter((one) => one !== SHIELD && one !== STAR).map((definition) => [`obj-${definition.id}`, definition]),+) as Record<ObjectBodyId, AvatarDefinition>;++const shape = (id: string, name: string, path: string, eyes: AvatarDefinition["eyes"]): AvatarDefinition => ({ version: 1, id, name, body: { path }, eyes });++/** Our shapes, drawn for the same engine; Shield and Star are Open Bot Avatar's own. The cursor keeps its own renderer. */+export const SHAPE_BODIES: Record<Exclude<MascotBodyId, "cursor">, AvatarDefinition> = {+ blob: shape("blob", "Blob", "M48 10C64 8 78 16 85 30C92 44 90 62 80 75C70 88 52 93 36 87C20 81 9 66 10 49C11 30 30 12 48 10Z", { x: 50, y: 48, spacing: 18, scale: 1.15 }),+ circle: shape("circle", "Circle", "M50 10A40 40 0 1 1 50 90A40 40 0 1 1 50 10Z", { x: 50, y: 48, spacing: 18, scale: 1.15 }),+ squircle: shape("squircle", "Squircle", "M50 12C78 12 88 22 88 50C88 78 78 88 50 88C22 88 12 78 12 50C12 22 22 12 50 12Z", { x: 50, y: 48, spacing: 18, scale: 1.15 }),+ capsule: shape("capsule", "Capsule", "M50 8C66 8 78 20 78 36V64C78 80 66 92 50 92C34 92 22 80 22 64V36C22 20 34 8 50 8Z", { x: 50, y: 46, spacing: 16, scale: 1.1 }),+ drop: shape("drop", "Drop", "M46.5 12Q50 7 53.5 12C64 27 80 45 80 62C80 79 66 91 50 91C34 91 20 79 20 62C20 45 36 27 46.5 12Z", { x: 50, y: 60, spacing: 16, scale: 1.1 }),+ shield: { ...SHIELD, id: "shield" },+ hexagon: shape("hexagon", "Hexagon", "M40.47 13.5Q50 8 59.53 13.5L76.85 23.5Q86.37 29 86.37 40L86.37 60Q86.37 71 76.85 76.5L59.53 86.5Q50 92 40.47 86.5L23.15 76.5Q13.63 71 13.63 60L13.63 40Q13.63 29 23.15 23.5Z", { x: 50, y: 47, spacing: 18, scale: 1.15 }),+ diamond: shape("diamond", "Diamond", "M40.1 16.9Q50 7 59.9 16.9L83.1 40.1Q93 50 83.1 59.9L59.9 83.1Q50 93 40.1 83.1L16.9 59.9Q7 50 16.9 40.1Z", { x: 50, y: 47, spacing: 16, scale: 1.1 }),+ star: { ...STAR, id: "star" },+};++/** The engine definition a body is drawn from, or undefined for the cursor and the festival bodies. */+export function engineBody(id: unknown): AvatarDefinition | undefined {+ if (typeof id !== "string") return undefined;+ for (const table of [OBJECT_BODIES, SHAPE_BODIES] as Record<string, AvatarDefinition>[]) if (Object.hasOwn(table, id)) return table[id];+ return undefined;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/LICENSE b/packages/phone-protocol/src/open-bot-avatar/LICENSEnew file mode 100644index 0000000000..4ef1195fa7--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Dominik Scholz++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/phone-protocol/src/open-bot-avatar/README.md b/packages/phone-protocol/src/open-bot-avatar/README.mdnew file mode 100644index 0000000000..146c3ba320--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/README.md@@ -0,0 +1,30 @@+# open-bot-avatar++Vendored sources of [Open Bot Avatar](https://github.com/DominikScholz/open-bot-avatar)+(MIT, see `LICENSE`) at commit `5e64c081971eb296f562544641bad37d40fb36b6`, which npm publishes as+`open-bot-avatar` 0.3.0:++- `*.ts` ← `packages/core/src/*.ts`, the engine: validation, volume, motion and SVG rendering, with no DOM.+ Upstream's `index.ts` (a re-export barrel) and `seams.ts` (nothing imports it) are left out; import each+ module directly.+- `dom/` ← `packages/core/src/dom/`, the browser mount. Only the desktop app uses it; the protocol's own+ type check and the phone copy (`scripts/sync-phone-protocol.mjs`) leave it out.++## Our changes++`render.ts` carries our only code changes, each marked `MausBot:`:++- A smile under the eyes (`mouthMark`), drawn with the eyes in the canvas and SVG renderers. The CSS-3D+ `renderAvatarScene` path has no mouth; `mountAvatar` only falls back to it where canvas is missing+ (never in the desktop app).+- The ribbons of `working` and `done` take our six rainbow comet palettes (`COMET_COLORS`) instead of+ shades of the body colour.++Comments in `motion.ts` and `effects.ts` that pointed at an upstream pull request and a third-party demo+now say "a reference animation"; the numbers are unchanged.++`../object-bodies.ts` holds the starters from `examples.ts` and the definitions in the upstream `gallery/*.json`,+each worn under an `obj-` id.++To refresh, copy `packages/core/src` from a newer commit over these files, reapply the changes above, update the commit above and the+gallery definitions, then run the protocol, mascot and sync-phone-protocol tests.diff --git a/packages/phone-protocol/src/open-bot-avatar/animator.ts b/packages/phone-protocol/src/open-bot-avatar/animator.tsnew file mode 100644index 0000000000..af9288e1d6--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/animator.ts@@ -0,0 +1,89 @@+/**+ * The per-avatar state a live renderer keeps between frames, independent of+ * any platform: the eased look toward a target (follow.ts) and the eased+ * change between states and moods (mood.ts). Feed it once per frame; it+ * returns the `gaze`, `motionBlend` and `stateAge` render options for that+ * frame and whether it is still easing.+ */+import { REST, followGaze, followStep, type FollowState } from './follow.ts';+import { DONE_TURN_S, resolveLook } from './motion.ts';+import { moodProgress, settleMood, type MoodState } from './mood.ts';+import type { AvatarMood, AvatarMotion, AvatarMotionBlend, AvatarState } from './types.ts';++export interface AnimatorInput {+ /** Wall clock, ms (e.g. performance.now()). Easing runs on it even when the animation clock stops. */+ now: number;+ state?: AvatarState;+ mood?: AvatarMood;+ /** @deprecated Use `state` and `mood`; they win when given. */+ motion?: AvatarMotion;+ /** Look target, -1..1 per axis (x right, y down), e.g. from pointerGaze; null eases back to rest. */+ target: { x: number; y: number } | null;+ /** Keep the current look as it is (e.g. while the user drags the view). */+ hold?: boolean;+ /** Snap instead of easing. */+ reducedMotion: boolean;+}++export interface AnimatorStep {+ gaze?: { x: number; y: number; weight: number };+ motionBlend?: AvatarMotionBlend;+ /** Seconds since the state began (a change of mood alone does not restart it). */+ stateAge: number;+ /** True while the look or a change of state or mood is still easing. */+ moving: boolean;+}++export interface Animator {+ step(input: AnimatorInput): AnimatorStep;+ /** Back to rest with no history, e.g. when the avatar is remounted. */+ reset(): void;+}++export function createAnimator(): Animator {+ let follow: FollowState = REST;+ let last: number | null = null;+ // What is on screen, when its change began and when its state began.+ let shown: { state: AvatarState; mood: AvatarMood; blend?: AvatarMotionBlend; since: number; began: number } | null = null;++ return {+ step({ now, target, hold = false, reducedMotion, ...given }) {+ const dt = last === null ? 0 : (now - last) / 1000;+ last = now;+ let moving = false;+ if (!hold) ({ state: follow, moving } = followStep(follow, target, dt, reducedMotion));++ // A new state or mood eases in from the pose on screen (a change under way included); reduced motion switches at once.+ const { state, mood } = resolveLook(given);+ if (shown && (state !== shown.state || mood !== shown.mood)) {+ const before: MoodState = {+ state: shown.state,+ mood: shown.mood,+ age: (now - shown.began) / 1000,+ blend: shown.blend && { from: shown.blend.from, t: moodProgress(now - shown.since) },+ };+ shown = {+ state,+ mood,+ blend: reducedMotion ? undefined : { from: settleMood(before), t: 0 },+ since: now,+ began: state === shown.state ? shown.began : now,+ };+ }+ // An avatar that mounts done starts it at rest, as if it had just finished celebrating; any+ // other state starts afresh (a working bot's first sweep comes a second or two in).+ shown ??= { state, mood, since: now, began: now - (state === 'done' ? DONE_TURN_S * 1000 : 0) };+ const t = reducedMotion ? 1 : moodProgress(now - shown.since);+ let motionBlend: AvatarMotionBlend | undefined;+ if (shown.blend && t < 1) motionBlend = { from: shown.blend.from, t };+ else shown.blend = undefined;++ return { gaze: followGaze(follow), motionBlend, stateAge: (now - shown.began) / 1000, moving: moving || motionBlend !== undefined };+ },+ reset() {+ follow = REST;+ last = null;+ shown = null;+ },+ };+}diff --git a/packages/phone-protocol/src/open-bot-avatar/color.ts b/packages/phone-protocol/src/open-bot-avatar/color.tsnew file mode 100644index 0000000000..9da03dc45a--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/color.ts@@ -0,0 +1,105 @@+/** Minimal hex color handling for the renderer. Only #rgb / #rrggbb are accepted. */++export type Rgb = [number, number, number];++export function parseHex(input: unknown): Rgb | null {+ if (typeof input !== 'string') return null;+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(input.trim());+ if (!m) return null;+ let h = m[1];+ if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];+ return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];+}++export function toHex([r, g, b]: Rgb): string {+ const c = (v: number) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, '0');+ return `#${c(r)}${c(g)}${c(b)}`;+}++export function mix(a: Rgb, b: Rgb, t: number): Rgb {+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+}++/**+ * Darken while keeping the hue rich: blend toward a deeper, slightly+ * saturated version of the color rather than toward gray-black.+ */+export function shade(c: Rgb, t: number): Rgb {+ const max = Math.max(...c);+ const deep: Rgb = [c[0] * 0.35 - (max - c[0]) * 0.1, c[1] * 0.35 - (max - c[1]) * 0.1, c[2] * 0.35 - (max - c[2]) * 0.1];+ return mix(c, deep, t);+}++export function tint(c: Rgb, t: number): Rgb {+ return mix(c, [255, 255, 255], t);+}++/** WCAG relative luminance. */+export function luminance([r, g, b]: Rgb): number {+ const ch = (v: number) => {+ const s = v / 255;+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b);+}++export function contrast(a: Rgb, b: Rgb): number {+ const la = luminance(a), lb = luminance(b);+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);+}++export const DARK_INK: Rgb = [20, 22, 34];+export const LIGHT_INK: Rgb = [250, 250, 255];++/** Pick the eye ink with the best contrast against the body color. */+export function autoEyeColor(body: Rgb): Rgb {+ return contrast(body, DARK_INK) >= contrast(body, LIGHT_INK) ? DARK_INK : LIGHT_INK;+}++// OKLCH, for colors that look equally bright whatever their hue.++const toLinear = (v: number) => {+ const s = v / 255;+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;+};+const fromLinear = (v: number) => 255 * (v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055);++/** A color as OKLCH: lightness 0..1, chroma, hue in degrees. */+export function toOklch(c: Rgb): [number, number, number] {+ const [r, g, b] = c.map(toLinear);+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);+ const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;+ const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;+ const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;+ const h = (Math.atan2(B, A) * 180) / Math.PI;+ return [L, Math.hypot(A, B), h < 0 ? h + 360 : h];+}++function oklchLinear(L: number, C: number, h: number): [number, number, number] {+ const a = C * Math.cos((h * Math.PI) / 180), b = C * Math.sin((h * Math.PI) / 180);+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;+ return [+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,+ ];+}++/** An OKLCH color in sRGB, its chroma lowered as far as it takes to fit (lightness and hue are kept). */+export function oklch(L: number, C: number, h: number): Rgb {+ const fits = (c: number) => oklchLinear(L, c, h).every((v) => v >= -1e-4 && v <= 1 + 1e-4);+ let lo = 0, hi = C;+ if (!fits(hi)) {+ for (let i = 0; i < 20; i++) {+ const mid = (lo + hi) / 2;+ if (fits(mid)) lo = mid;+ else hi = mid;+ }+ hi = lo;+ }+ return oklchLinear(L, hi, h).map(fromLinear) as Rgb;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/contour.ts b/packages/phone-protocol/src/open-bot-avatar/contour.tsnew file mode 100644index 0000000000..22582bf650--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/contour.ts@@ -0,0 +1,193 @@+/**+ * Iso-contours of a sampled scalar field (marching squares), assembled into+ * closed loops and simplified. Used once per definition to turn a part's+ * depth field into plain cross-section paths, so slices need no SVG masks.+ */+import type { Point } from './path.ts';++export interface Field {+ /** Row-major samples, nx * ny. The outermost ring should be below every level. */+ values: Float64Array;+ nx: number;+ ny: number;+ x0: number;+ y0: number;+ step: number;+}++/** Closed loops where the field crosses `level` (inside = value ≥ level). */+export function contourLoops(field: Field, level: number): Point[][] {+ const { values, nx, ny, x0, y0, step } = field;+ const at = (i: number, j: number) => values[j * nx + i] - level;+ // Edge keys: horizontal edge (i,j)-(i+1,j) = 2*(j*nx+i), vertical (i,j)-(i,j+1) = 2*(j*nx+i)+1.+ const points = new Map<number, Point>();+ const links = new Map<number, number[]>();+ const point = (key: number): void => {+ if (points.has(key)) return;+ const idx = key >> 1, i = idx % nx, j = (idx - i) / nx;+ const a = at(i, j);+ if (key & 1) {+ const b = at(i, j + 1), t = a / (a - b);+ points.set(key, [x0 + i * step, y0 + (j + t) * step]);+ } else {+ const b = at(i + 1, j), t = a / (a - b);+ points.set(key, [x0 + (i + t) * step, y0 + j * step]);+ }+ };+ const link = (p: number, q: number) => {+ point(p); point(q);+ (links.get(p) ?? links.set(p, []).get(p)!).push(q);+ (links.get(q) ?? links.set(q, []).get(q)!).push(p);+ };++ for (let j = 0; j < ny - 1; j++) {+ for (let i = 0; i < nx - 1; i++) {+ const tl = at(i, j) >= 0, tr = at(i + 1, j) >= 0, br = at(i + 1, j + 1) >= 0, bl = at(i, j + 1) >= 0;+ const code = (tl ? 8 : 0) | (tr ? 4 : 0) | (br ? 2 : 0) | (bl ? 1 : 0);+ if (code === 0 || code === 15) continue;+ const top = 2 * (j * nx + i), bottom = 2 * ((j + 1) * nx + i);+ const left = 2 * (j * nx + i) + 1, right = 2 * (j * nx + i + 1) + 1;+ if (code === 10 || code === 5) {+ const center = (at(i, j) + at(i + 1, j) + at(i + 1, j + 1) + at(i, j + 1)) / 4 >= 0;+ // Diagonal corners: the center decides whether they connect through the cell.+ if ((code === 10) === center) { link(top, right); link(bottom, left); }+ else { link(left, top); link(right, bottom); }+ continue;+ }+ const crossed: number[] = [];+ if (tl !== tr) crossed.push(top);+ if (tr !== br) crossed.push(right);+ if (br !== bl) crossed.push(bottom);+ if (bl !== tl) crossed.push(left);+ link(crossed[0], crossed[1]);+ }+ }++ const loops: Point[][] = [];+ const seen = new Set<number>();+ for (const start of links.keys()) {+ if (seen.has(start)) continue;+ const loop: Point[] = [];+ let prev = -1, cur = start;+ while (!seen.has(cur)) {+ seen.add(cur);+ loop.push(points.get(cur)!);+ const next = links.get(cur)!.find((n) => n !== prev && !seen.has(n));+ if (next === undefined) break;+ prev = cur; cur = next;+ }+ if (loop.length >= 3) loops.push(loop);+ }+ return loops;+}++function perpendicular(p: Point, a: Point, b: Point): number {+ const dx = b[0] - a[0], dy = b[1] - a[1];+ const len = Math.hypot(dx, dy);+ if (len === 0) return Math.hypot(p[0] - a[0], p[1] - a[1]);+ return Math.abs(dx * (a[1] - p[1]) - dy * (a[0] - p[0])) / len;+}++/** Ramer-Douglas-Peucker on a closed loop. */+export function simplifyLoop(loop: Point[], tolerance: number): Point[] {+ if (loop.length <= 8) return loop;+ // Split at the point farthest from the first so the closed loop becomes two open chains.+ let far = 0, best = -1;+ for (let k = 1; k < loop.length; k++) {+ const d = Math.hypot(loop[k][0] - loop[0][0], loop[k][1] - loop[0][1]);+ if (d > best) { best = d; far = k; }+ }+ const keep = new Uint8Array(loop.length);+ keep[0] = keep[far] = 1;+ const stack: [number, number][] = [[0, far], [far, loop.length]];+ while (stack.length) {+ const [s, e] = stack.pop()!;+ const end = loop[e % loop.length];+ let idx = -1, max = tolerance;+ for (let k = s + 1; k < e; k++) {+ const d = perpendicular(loop[k], loop[s], end);+ if (d > max) { max = d; idx = k; }+ }+ if (idx >= 0) { keep[idx] = 1; stack.push([s, idx], [idx, e]); }+ }+ return loop.filter((_, k) => keep[k]);+}++/** Path numbers are hundredths; vertices snap to even ones so edge midpoints land exactly on the grid. */+const UNIT = 100;++/** A grid value as a path number, as short as SVG allows: no leading zero, no `-0`. */+const num = (k: number) => {+ const a = Math.abs(k), whole = Math.floor(a / UNIT), frac = a % UNIT;+ const f = frac === 0 ? '' : frac % 10 === 0 ? `.${frac / 10}` : frac < 10 ? `.0${frac}` : `.${frac}`;+ return (k < 0 ? '-' : '') + (whole || !f ? whole : '') + f;+};++/** Turns sharper than this (radians) stay corners; gentler ones are drawn as curves. */+const CORNER = 0.6;++/**+ * A gentle turn between long edges is a corner of the outline too, not a facet of a traced curve:+ * it stays sharp once its curve would leave the traced loop by more than this (viewBox units).+ */+const SAG = 0.1;++/**+ * Compact closed path from loops (draw with fill-rule evenodd). Traced loops are polylines, so+ * gentle turns are drawn as quadratics between edge midpoints, which hides their facets at large+ * sizes; real corners stay sharp. Relative commands, smooth t segments and implicit repeats keep+ * the string short.+ */+export function loopsToPath(loops: Point[][]): string {+ let d = '', cmd = '', last = '';+ const emit = (c: string, ...ks: number[]) => {+ if (c !== cmd) { d += c; cmd = c; last = ''; }+ for (const k of ks) {+ const t = num(k);+ // A separator is only needed where the next number could be read as part of the last one.+ if (last && t[0] !== '-' && !(t[0] === '.' && last.includes('.'))) d += ' ';+ d += t;+ last = t;+ }+ };+ for (const loop of loops) {+ const n = loop.length;+ const v = loop.map(([x, y]) => [2 * Math.round(x * UNIT / 2), 2 * Math.round(y * UNIT / 2)]);+ const corner = loop.map((p, k) => {+ const a = loop[(k + n - 1) % n], b = loop[(k + 1) % n];+ const cross = (p[0] - a[0]) * (b[1] - p[1]) - (p[1] - a[1]) * (b[0] - p[0]);+ // The curve passes a quarter of p's height over the chord a-b away from p.+ return Math.abs(Math.atan2(cross, (p[0] - a[0]) * (b[0] - p[0]) + (p[1] - a[1]) * (b[1] - p[1]))) > CORNER+ || Math.abs(cross) > 4 * SAG * Math.hypot(b[0] - a[0], b[1] - a[1]);+ });+ const mid = (k: number) => [(v[k % n][0] + v[(k + 1) % n][0]) / 2, (v[k % n][1] + v[(k + 1) % n][1]) / 2];+ let [cx, cy] = mid(0);+ emit('M', cx, cy);+ let smooth = false;+ for (let k = 1; k <= n; k++) {+ const [px, py] = v[k % n];+ if (corner[k % n]) {+ // A midpoint between two corners lies on their straight edge, so it is only kept to start a curve.+ emit('l', px - cx, py - cy);+ cx = px; cy = py;+ if (k < n && !corner[(k + 1) % n]) {+ const [mx, my] = mid(k);+ emit('l', mx - cx, my - cy);+ cx = mx; cy = my;+ }+ smooth = false;+ } else {+ const [mx, my] = mid(k);+ // After a curve, the reflected control point is exactly this vertex (it mirrors the last one+ // across their shared midpoint), so t needs only the end point.+ if (smooth) emit('t', mx - cx, my - cy);+ else emit('q', px - cx, py - cy, mx - cx, my - cy);+ cx = mx; cy = my;+ smooth = true;+ }+ }+ d += 'Z';+ cmd = 'Z'; last = '';+ }+ return d;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/clock.ts b/packages/phone-protocol/src/open-bot-avatar/dom/clock.tsnew file mode 100644index 0000000000..6129e6a523--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/clock.ts@@ -0,0 +1,78 @@+/**+ * One shared animation loop for every live avatar on the page.+ *+ * Subscribers measure first and draw second, so layout reads never interleave+ * with DOM writes. The loop sleeps once no subscriber needs frames (every+ * avatar is still, or under reduced motion with its easing settled).+ * Subscribers that ask to wait are skipped until their time comes.+ */++export interface Pointer {+ x: number;+ y: number;+}++export interface FrameSubscriber {+ measure?: () => void;+ /**+ * `time` is the animation clock in seconds, `pointer` the last pointer+ * position in viewport pixels (null when there is none). Return true for+ * the next frame, a number of seconds to skip (neither measured nor drawn+ * until then), or false once no more frames are needed.+ */+ draw: (time: number, pointer: Pointer | null) => boolean | number;+}++const subscribers = new Set<FrameSubscriber>();+let frame = 0;+/** Animation time before which a subscriber that asked to wait is skipped (neither measured nor drawn). */+const due = new WeakMap<FrameSubscriber, number>();+let pointer: Pointer | null = null;+const startedAt = typeof performance !== 'undefined' ? performance.now() : 0;++function tick(now: number) {+ frame = 0;+ const time = (now - startedAt) / 1000;+ let busy = false;+ const ready: FrameSubscriber[] = [];+ for (const s of subscribers) {+ const at = due.get(s);+ if (at !== undefined && at > time) busy = true;+ else ready.push(s);+ }+ for (const s of ready) s.measure?.();+ for (const s of ready) {+ const next = s.draw(time, pointer);+ if (typeof next === 'number') due.set(s, time + next);+ else due.delete(s);+ busy = next !== false || busy;+ }+ if (busy) wake();+}++function wake() {+ if (!frame && subscribers.size > 0 && typeof requestAnimationFrame !== 'undefined') frame = requestAnimationFrame(tick);+}++export function subscribeFrames(subscriber: FrameSubscriber): () => void {+ subscribers.add(subscriber);+ wake();+ return () => {+ subscribers.delete(subscriber);+ if (subscribers.size === 0) {+ if (frame) cancelAnimationFrame(frame);+ frame = 0;+ }+ };+}++/** Set the pointer every following avatar looks toward (viewport pixels), or null when there is none. */+export function setPointer(next: Pointer | null) {+ pointer = next;+ wake();+}++/** Request a frame after a non-animated change (color, depth, definition). */+export function requestFrame() {+ wake();+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/index.ts b/packages/phone-protocol/src/open-bot-avatar/dom/index.tsnew file mode 100644index 0000000000..ebfdcc53a1--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/index.ts@@ -0,0 +1,6 @@+export { mountAvatar } from './mount.ts';+export type { AvatarOptions, MountedAvatar } from './mount.ts';+export { requestFrame, setPointer, subscribeFrames } from './clock.ts';+export type { FrameSubscriber, Pointer } from './clock.ts';+export { trackPointer } from './pointer.ts';+export { prefersReducedMotion } from './reduced.ts';diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/mount.ts b/packages/phone-protocol/src/open-bot-avatar/dom/mount.tsnew file mode 100644index 0000000000..e5445da619--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/mount.ts@@ -0,0 +1,346 @@+/**+ * A live avatar in any DOM element, without a framework.+ *+ * const avatar = mountAvatar(el, { definition, color: '#1f7cf2', followPointer: true });+ * avatar.update({ state: 'working', mood: 'happy' });+ * avatar.destroy();+ *+ * Live avatars paint each frame to one canvas (see paint.ts): one compositor+ * layer and a small bitmap per avatar. `renderer: 'scene'` mounts a CSS 3D scene+ * instead, where every cross-section is its own small SVG and each frame only+ * writes a few CSS transforms; it costs a compositor layer per visible slice,+ * and is also the fallback where canvas is unavailable. `still` avatars are a+ * single static SVG and never animate. Every avatar on the page shares one+ * animation loop.+ */+import { createAnimator } from '../animator.ts';+import { pointerGaze } from '../follow.ts';+import { resolveLook } from '../motion.ts';+import { DEFAULT_COLOR, DEFAULT_EYE_COLOR, liveFrame, renderAvatarScene, renderAvatarSvg, sceneFrame, type SceneFrame } from '../render.ts';+import type { AvatarDefinition, AvatarMood, AvatarState, RenderOptions } from '../types.ts';+import { requestFrame, subscribeFrames } from './clock.ts';+import { canvasSupported, mountCanvas, paintCanvas, type CanvasSurface } from './paint.ts';+import { trackPointer } from './pointer.ts';+import { prefersReducedMotion } from './reduced.ts';++export interface AvatarOptions {+ definition: AvatarDefinition;+ /** Body color: #rgb or #rrggbb, or any CSS color (e.g. var(--brand)). */+ color?: string;+ /** Eye color: #rgb or #rrggbb, or any CSS color. Defaults to a near-black ink. */+ eyeColor?: string;+ /** Volume amount 0..14 (6 = natural depth, 0 = flat). */+ depth?: number;+ /** What the bot is doing (default `idle`). Changes ease from what is on screen. */+ state?: AvatarState;+ /**+ * How the bot feels (default `neutral`): it shapes the eyes on top of any state. `idle` and+ * `thinking` are still accepted here from before `state` existed and mean those states.+ */+ mood?: AvatarMood | 'idle' | 'thinking';+ /** Eyes look and the body turns toward the mouse, pen or finger anywhere on the page. */+ followPointer?: boolean;+ /** Fixed look direction (-1..1 per axis, x right, y down). Wins over the pointer. */+ lookAt?: { x: number; y: number } | null;+ /** Keep the current look as it is (e.g. while the user drags the view). */+ holdGaze?: boolean;+ /** Extra view rotation in radians on top of the resting view (e.g. drag-to-turn). */+ view?: { yaw: number; pitch: number };+ /** true or false to force; 'system' (default) follows prefers-reduced-motion. */+ reducedMotion?: boolean | 'system';+ /** Render one static SVG and never animate (thumbnails, lists). */+ still?: boolean;+ /**+ * How a live avatar draws. 'canvas' (default) paints each frame to one canvas: one compositor layer+ * per avatar. 'scene' is a CSS 3D scene with a compositor layer per visible slice: more CPU and+ * layers, but less video memory for a single avatar several hundred pixels wide.+ */+ renderer?: 'canvas' | 'scene';+ /** Accessible name; defaults to the definition's name. "" marks the avatar decorative. */+ label?: string;+}++export interface MountedAvatar {+ /** Change any options; only what changed is redrawn. */+ update(options: Partial<AvatarOptions>): void;+ destroy(): void;+}++/** Handles into a mounted scene, and the last values written, so frames only touch what changed. */+interface Scene {+ key: string;+ geometry: string;+ motion: HTMLElement;+ view: HTMLElement;+ stacks: Record<'z' | 'x', HTMLElement>;+ slices: Record<'z' | 'x', HTMLElement[]>;+ eyes: { root: HTMLElement; pill: HTMLElement; arc: HTMLElement; morph: HTMLElement; path: SVGPathElement }[];+ fx: Record<'back' | 'front', HTMLElement>;+ last: Record<string, string>;+}++function mountScene(el: HTMLElement, definition: AvatarDefinition, depth: number | undefined): Scene {+ el.innerHTML = renderAvatarScene(definition, { depth });+ const q = (s: string) => el.querySelector(s) as HTMLElement;+ const stacks = { z: q('[data-stack="z"]'), x: q('[data-stack="x"]') };+ return {+ key: q('[data-avatar-scene]').dataset.avatarScene ?? '',+ geometry: geometryKey(definition),+ motion: q('[data-motion]'),+ view: q('[data-view]'),+ stacks,+ slices: { z: [...stacks.z.children] as HTMLElement[], x: [...stacks.x.children] as HTMLElement[] },+ eyes: [0, 1].map((i) => {+ const root = q(`[data-eye="${i}"]`);+ const morph = root.querySelector('[data-morph]') as HTMLElement;+ return { root, pill: root.querySelector('i') as HTMLElement, arc: root.querySelector('svg') as unknown as HTMLElement, morph, path: morph.querySelector('path') as SVGPathElement };+ }),+ fx: { back: q('[data-fx="back"]'), front: q('[data-fx="front"]') },+ last: {},+ };+}++/** Write a style property only when its value changed since the last frame. */+function put(m: Scene, key: string, el: HTMLElement, prop: 'transform' | 'visibility' | 'display', value: string) {+ if (m.last[key] === value) return;+ m.last[key] = value;+ el.style[prop] = value;+}++function apply(m: Scene, frame: SceneFrame) {+ put(m, 'motion', m.motion, 'transform', frame.motion);+ put(m, 'view', m.view, 'transform', frame.view);+ // A body that has given way to a mark holds no layers.+ put(m, 'body', m.view, 'display', frame.body > 0 ? 'block' : 'none');+ for (const side of ['back', 'front'] as const) {+ if (m.last[side] === frame[side]) continue;+ m.last[side] = frame[side];+ m.fx[side].innerHTML = frame[side];+ }+ // display:none, not visibility: hidden slices would still each hold a 3D layer.+ put(m, 'z', m.stacks.z, 'display', frame.stack === 'z' ? 'block' : 'none');+ put(m, 'x', m.stacks.x, 'display', frame.stack === 'x' ? 'block' : 'none');+ const slices = m.slices[frame.stack];+ frame.slices.forEach((shown, i) => slices[i] && put(m, `${frame.stack}${i}`, slices[i], 'display', shown ? 'block' : 'none'));+ frame.eyes.forEach((eye, i) => {+ const e = m.eyes[i];+ put(m, `e${i}`, e.root, 'transform', eye.transform);+ put(m, `v${i}`, e.root, 'visibility', eye.visible ? 'visible' : 'hidden');+ put(m, `p${i}`, e.pill, 'transform', eye.pill);+ put(m, `ph${i}`, e.pill, 'display', eye.happy || eye.d ? 'none' : 'block');+ put(m, `a${i}`, e.arc, 'display', eye.happy && !eye.d ? 'block' : 'none');+ put(m, `m${i}`, e.morph, 'display', eye.d ? 'block' : 'none');+ if (eye.d && m.last[`d${i}`] !== eye.d) {+ m.last[`d${i}`] = eye.d;+ e.path.setAttribute('d', eye.d);+ }+ });+}++const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;+const isHex = (c: string | undefined) => c === undefined || HEX.test(c);++const keys = new WeakMap<object, string>();+/** Everything in a definition the static scene markup depends on. */+function geometryKey(definition: AvatarDefinition): string {+ let key = keys.get(definition);+ if (key === undefined) {+ key = JSON.stringify([definition?.id, definition?.name, definition?.body?.path, definition?.eyes]);+ keys.set(definition, key);+ }+ return key;+}++/** Midpoint between the eyes as a fraction of the (square, 100-unit) box: the look starts there. */+function eyesOrigin(definition: AvatarDefinition): { x: number; y: number } {+ const { x, y } = definition.eyes ?? {};+ const at = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(1, Math.max(0, v / 100)) : 0.5);+ return { x: at(x), y: at(y) };+}++/** Avatars smaller than this (CSS px) redraw at SMALL_FPS: the difference doesn't show, and pages often hold many. */+const SMALL_SIZE = 128;+const SMALL_FPS = 30;+/** How far outside the viewport (CSS px) avatars keep animating, so they are already moving as they scroll in. */+const VIEW_MARGIN = 100;+/** Slack so a 60 Hz display reliably draws every other frame rather than drifting between 1 and 3. */+const FRAME_SLACK = 0.004;++export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedAvatar {+ let opts: AvatarOptions = { ...initial };+ const animator = createAnimator();+ let rect: DOMRect | null = null;+ let scene: Scene | null = null;+ let surface: CanvasSurface | null = null;+ let lastStill = '';+ let failed = false;+ let dirty = true;+ let releasePointer: (() => void) | null = null;+ let size = host.clientWidth;+ const resize = typeof ResizeObserver === 'undefined'+ ? null+ : new ResizeObserver(([entry]) => {+ const next = entry.contentRect.width;+ if (next === size) return;+ size = next;+ requestFrame();+ });+ resize?.observe(host);++ /** Whether the host is in or near the viewport. Offscreen, a live avatar only redraws after a change. */+ let visible = true;+ const intersect = typeof IntersectionObserver === 'undefined'+ ? null+ : new IntersectionObserver(+ (entries) => {+ const next = entries[entries.length - 1].isIntersecting;+ if (next === visible) return;+ visible = next;+ if (visible) requestFrame();+ },+ { rootMargin: `${VIEW_MARGIN}px` },+ );+ intersect?.observe(host);++ if (getComputedStyle(host).position === 'static') host.style.position = 'relative';++ const syncHost = () => {+ host.style.color = opts.color ?? DEFAULT_COLOR;+ host.style.setProperty('--avatar-ink', opts.eyeColor ?? DEFAULT_EYE_COLOR);+ const decorative = opts.label === '';+ if (decorative) {+ host.removeAttribute('role');+ host.removeAttribute('aria-label');+ host.setAttribute('aria-hidden', 'true');+ } else {+ host.setAttribute('role', 'img');+ host.setAttribute('aria-label', opts.label ?? opts.definition?.name ?? 'Avatar');+ host.removeAttribute('aria-hidden');+ }+ const wantsPointer = !!opts.followPointer && !opts.still;+ if (wantsPointer && !releasePointer) releasePointer = trackPointer();+ else if (!wantsPointer && releasePointer) {+ releasePointer();+ releasePointer = null;+ }+ };++ const clear = () => {+ host.textContent = '';+ scene = null;+ surface = null;+ lastStill = '';+ };++ const draw = (time: number, pointer: { x: number; y: number } | null): boolean => {+ const p = opts;+ const reducedMotion = p.reducedMotion === 'system' || p.reducedMotion === undefined ? prefersReducedMotion() : p.reducedMotion;+ const now = performance.now();+ // `mood: 'idle' | 'thinking'` are the states they were before `state` existed.+ const look = resolveLook({ state: p.state, mood: p.mood, motion: p.mood });+ try {+ if (p.still) {+ if (scene || surface) clear();+ const svg = renderAvatarSvg(p.definition, {+ color: p.color,+ eyeColor: p.eyeColor,+ depth: p.depth,+ state: look.state,+ mood: look.mood,+ view: p.view,+ gaze: p.lookAt ?? undefined,+ reducedMotion: true,+ });+ // The engine derives SVG ids from geometry, so repeated avatars can share them safely.+ if (svg !== lastStill) {+ host.innerHTML = svg;+ lastStill = svg;+ }+ failed = false;+ return false;+ }+ if (lastStill) clear();++ const target = p.lookAt+ ? p.lookAt+ : p.followPointer && pointer && rect && rect.width > 0+ ? pointerGaze(pointer, rect, eyesOrigin(p.definition))+ : null;+ const step = animator.step({ now, state: look.state, mood: look.mood, target, hold: p.holdGaze, reducedMotion });+ const options: RenderOptions = {+ depth: p.depth,+ state: look.state,+ mood: look.mood,+ stateAge: step.stateAge,+ motionBlend: step.motionBlend,+ size: size || undefined,+ time,+ gaze: step.gaze,+ view: p.view,+ reducedMotion,+ };+ if (p.renderer !== 'scene' && canvasSupported()) {+ if (scene) clear();+ const flat = liveFrame(p.definition, { ...options, color: p.color, eyeColor: p.eyeColor });+ const key = `${geometryKey(p.definition)}|${p.depth}`;+ if (!surface || surface.key !== key || !host.contains(surface.canvas)) surface = mountCanvas(host, key, p.definition, p.depth);+ // Any CSS color works, as in the scene: one that is not hex is read back every frame from the+ // host's computed `color` and --avatar-ink (which syncHost sets), so themes apply live.+ const css = isHex(p.color) && isHex(p.eyeColor) ? null : getComputedStyle(host);+ const fill = css && !isHex(p.color) ? css.color || flat.color : flat.color;+ const ink = css && !isHex(p.eyeColor) ? css.getPropertyValue('--avatar-ink').trim() || flat.ink : flat.ink;+ paintCanvas(surface, flat, size, fill, ink);+ failed = false;+ return !reducedMotion || step.moving;+ }+ if (surface) clear();+ const frame = sceneFrame(p.definition, { ...options, color: p.color });+ if (!scene || scene.key !== frame.scene || scene.geometry !== geometryKey(p.definition) || !host.contains(scene.view)) {+ scene = mountScene(host, p.definition, p.depth);+ }+ apply(scene, frame);+ failed = false;+ return !reducedMotion || step.moving;+ } catch (error) {+ if (!failed) {+ clear();+ console.error('open-bot-avatar: render failed', error);+ failed = true;+ }+ return false;+ }+ };++ syncHost();+ const unsubscribe = subscribeFrames({+ measure: () => {+ rect = visible && opts.followPointer && !opts.still && !opts.holdGaze && !opts.lookAt ? host.getBoundingClientRect() : null;+ },+ draw: (time, pointer) => {+ // Stills, and live avatars out of view, only redraw after a change; live avatars in view every+ // frame they ask for. A change still draws offscreen, so the content is current when printed.+ if ((opts.still || !visible) && !dirty) return false;+ dirty = false;+ const more = draw(time, pointer);+ if (!visible) return false;+ return more && size > 0 && size < SMALL_SIZE ? 1 / SMALL_FPS - FRAME_SLACK : more;+ },+ });++ return {+ update(next) {+ opts = { ...opts, ...next };+ syncHost();+ dirty = true;+ requestFrame();+ },+ destroy() {+ unsubscribe();+ resize?.disconnect();+ intersect?.disconnect();+ releasePointer?.();+ releasePointer = null;+ clear();+ },+ };+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/paint.ts b/packages/phone-protocol/src/open-bot-avatar/dom/paint.tsnew file mode 100644index 0000000000..fea4f035bc--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/paint.ts@@ -0,0 +1,227 @@+/**+ * The canvas renderer, the default for live avatars: paints flat avatar frames+ * to one canvas, so an avatar costs one compositor layer and one small bitmap+ * however many slices it shows. Equal geometry shares its parsed paths.+ *+ * The bitmap covers what the frames actually paint, plus slack, and only grows+ * while the avatar's size and the pixel ratio stay the same. A GPU canvas that+ * animates antialiased paths holds several times its bitmap in video memory,+ * so covering every possible view up front (avatarExtent, kept as the upper+ * bound) would cost about three times as much.+ *+ * The canvas sits in a wrapper at the host's content box, as the scene does,+ * overhangs it by the avatar's reach and ignores the pointer.+ */+import { avatarExtent } from '../render.ts';+import type { AvatarFrame, EyeMark, FramePath, Matrix } from '../render.ts';+import type { AvatarDefinition } from '../types.ts';++/** A square in viewBox units. */+export interface Square {+ x: number;+ y: number;+ size: number;+}++/** An axis-aligned box in viewBox units; empty when x0 > x1. */+export interface Bounds {+ x0: number;+ y0: number;+ x1: number;+ y1: number;+}++/** Slack around a frame's bounds when the bitmap is laid out, viewBox units: idle motion and gaze stay inside it. */+export const FIT_SLACK = 8;+/** Margin a frame keeps from the bitmap's edge for antialiasing, viewBox units. */+export const FIT_PAD = 1;++/**+ * The square to lay the bitmap out over: `prev` while it still holds `b`, else `prev` grown to+ * hold `b` with slack. Never larger than `cap` unless `b` itself leaves `cap`.+ */+export function fitSquare(prev: Square | null, b: Bounds, cap: Square): Square {+ if (!(b.x0 <= b.x1 && b.y0 <= b.y1)) return prev ?? cap;+ if (+ prev &&+ b.x0 - FIT_PAD >= prev.x &&+ b.y0 - FIT_PAD >= prev.y &&+ b.x1 + FIT_PAD <= prev.x + prev.size &&+ b.y1 + FIT_PAD <= prev.y + prev.size+ ) {+ return prev;+ }+ let x0 = b.x0 - FIT_SLACK, y0 = b.y0 - FIT_SLACK, x1 = b.x1 + FIT_SLACK, y1 = b.y1 + FIT_SLACK;+ if (prev) {+ x0 = Math.min(x0, prev.x);+ y0 = Math.min(y0, prev.y);+ x1 = Math.max(x1, prev.x + prev.size);+ y1 = Math.max(y1, prev.y + prev.size);+ }+ const size = Math.max(x1 - x0, y1 - y0);+ const inCap = b.x0 >= cap.x && b.y0 >= cap.y && b.x1 <= cap.x + cap.size && b.y1 <= cap.y + cap.size;+ if (size >= cap.size && inCap) return cap;+ return { x: (x0 + x1 - size) / 2, y: (y0 + y1 - size) / 2, size };+}++interface Section {+ path: Path2D;+ rule: CanvasFillRule;+}++const MAX_SECTIONS = 4096;+const sections = new Map<string, Section>();++let supported: boolean | undefined;+/** Whether this environment can paint avatars: a 2D canvas and Path2D (jsdom has neither). */+export function canvasSupported(): boolean {+ if (supported === undefined) {+ // Path2D first: asking jsdom for a context logs a "not implemented" error.+ supported = typeof Path2D !== 'undefined' && typeof document !== 'undefined' && !!document.createElement('canvas').getContext('2d');+ }+ return supported;+}++/**+ * Each shape's matrix with the frame's root motion applied, and the bounds of everything the frame+ * paints, in viewBox units. Pure.+ */+export function framePlacement(frame: AvatarFrame): { matrices: Matrix[]; bounds: Bounds } {+ const boxes = new Map(frame.paths.map((p) => [p.id, p.box]));+ const [ra, rb, rc, rd, re, rf] = frame.root;+ const bounds: Bounds = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };+ const add = (m: Matrix, x: number, y: number) => {+ const X = m[0] * x + m[2] * y + m[4], Y = m[1] * x + m[3] * y + m[5];+ if (X < bounds.x0) bounds.x0 = X;+ if (X > bounds.x1) bounds.x1 = X;+ if (Y < bounds.y0) bounds.y0 = Y;+ if (Y > bounds.y1) bounds.y1 = Y;+ };+ const matrices = frame.shapes.map((shape) => {+ const [a, b, c, d, e, f] = shape.matrix;+ const m: Matrix = [ra * a + rc * b, rb * a + rd * b, ra * c + rc * d, rb * c + rd * d, ra * e + rc * f + re, rb * e + rd * f + rf];+ const box = shape.kind === 'slice' ? boxes.get(shape.path) : shape.kind === 'eye' ? eyeBox(shape.mark) : shape.box;+ if (box) {+ add(m, box.x, box.y);+ add(m, box.x + box.w, box.y);+ add(m, box.x, box.y + box.h);+ add(m, box.x + box.w, box.y + box.h);+ }+ return m;+ });+ return { matrices, bounds };+}++function eyeBox(mark: EyeMark): FramePath['box'] {+ if (mark.shape === 'pill') return { x: mark.x, y: mark.y, w: mark.width, h: mark.height };+ // Quadratics lie within their points' hull; an arc's stroke reaches half its width past it.+ const reach = mark.shape === 'arc' ? mark.strokeWidth : 0;+ const n = (mark.d.match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number);+ const xs = n.filter((_, i) => i % 2 === 0), ys = n.filter((_, i) => i % 2 === 1);+ const x = Math.min(...xs) - reach, y = Math.min(...ys) - reach;+ return { x, y, w: Math.max(...xs) + reach - x, h: Math.max(...ys) + reach - y };+}++function eye(ctx: CanvasRenderingContext2D, mark: EyeMark) {+ if (mark.shape === 'path') {+ ctx.fill(new Path2D(mark.d));+ return;+ }+ if (mark.shape === 'arc') {+ ctx.lineWidth = mark.strokeWidth;+ ctx.stroke(new Path2D(mark.d));+ return;+ }+ const { x, y, width: w, height: h, radius: r } = mark;+ ctx.beginPath();+ if (typeof ctx.roundRect === 'function') ctx.roundRect(x, y, w, h, r);+ else {+ // Safari before 16 and Firefox before 112.+ ctx.moveTo(x + r, y);+ ctx.arcTo(x + w, y, x + w, y + h, r);+ ctx.arcTo(x + w, y + h, x, y + h, r);+ ctx.arcTo(x, y + h, x, y, r);+ ctx.arcTo(x, y, x + w, y, r);+ ctx.closePath();+ }+ ctx.fill();+}++/** A mounted canvas and the square and size its bitmap was last laid out at. */+export interface CanvasSurface {+ key: string;+ canvas: HTMLCanvasElement;+ ctx: CanvasRenderingContext2D | null;+ cap: Square;+ fit: Square | null;+ layout: string;+ left: number;+ top: number;+}++export function mountCanvas(el: HTMLElement, key: string, definition: AvatarDefinition, depth: number | undefined): CanvasSurface {+ const cap = avatarExtent(definition, depth);+ const wrap = document.createElement('div');+ // In flow at the content box, like the scene's root, so the host's padding and border place it.+ wrap.style.cssText = 'position:relative;width:100%;height:100%;pointer-events:none';+ const canvas = document.createElement('canvas');+ canvas.setAttribute('aria-hidden', 'true');+ canvas.style.cssText = 'position:absolute';+ wrap.append(canvas);+ el.replaceChildren(wrap);+ return { key, canvas, ctx: canvas.getContext('2d'), cap, fit: null, layout: '', left: 0, top: 0 };+}++/** Paint one frame `size` CSS pixels wide. `fill` and `ink` override the frame's colors with any canvas color. */+export function paintCanvas(surface: CanvasSurface, frame: AvatarFrame, size: number, fill = frame.color, ink = frame.ink) {+ const { canvas, ctx } = surface;+ if (!ctx || size <= 0) return;+ const dpr = window.devicePixelRatio || 1;+ const scale = (size / 100) * dpr;+ const layout = `${size}|${dpr}`;+ if (sections.size > MAX_SECTIONS) sections.clear();+ for (const { id, d, evenOdd } of frame.paths) {+ if (!sections.has(id)) sections.set(id, { path: new Path2D(d), rule: evenOdd ? 'evenodd' : 'nonzero' });+ }+ const { matrices, bounds } = framePlacement(frame);+ const fit = fitSquare(surface.layout === layout ? surface.fit : null, bounds, surface.cap);+ if (surface.layout === layout && fit === surface.fit) {+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ } else {+ // Whole device pixels, so the bitmap is never resampled. Setting the width also clears it.+ surface.layout = layout;+ surface.fit = fit;+ surface.left = Math.floor(fit.x * scale);+ surface.top = Math.floor(fit.y * scale);+ const bitmap = Math.ceil(fit.size * scale) + 1;+ canvas.width = canvas.height = bitmap;+ canvas.style.left = `${surface.left / dpr}px`;+ canvas.style.top = `${surface.top / dpr}px`;+ canvas.style.width = canvas.style.height = `${bitmap / dpr}px`;+ }++ ctx.lineCap = 'round';+ ctx.strokeStyle = ink;+ ctx.fillStyle = fill;+ // Shapes run in the thousands per second across a page: one setTransform each beats save/restore.+ for (let i = 0; i < frame.shapes.length; i++) {+ const shape = frame.shapes[i], m = matrices[i];+ ctx.setTransform(scale * m[0], scale * m[1], scale * m[2], scale * m[3], scale * m[4] - surface.left, scale * m[5] - surface.top);+ if (shape.kind === 'slice') {+ const section = sections.get(shape.path) as Section;+ ctx.fill(section.path, section.rule);+ } else if (shape.kind === 'eye') {+ ctx.fillStyle = ink;+ eye(ctx, shape.mark);+ ctx.fillStyle = fill;+ } else {+ const g = shape.gradient;+ const paint = ctx.createLinearGradient(g.x1, g.y1, g.x2, g.y2);+ g.stops.forEach((c, i) => paint.addColorStop(i / (g.stops.length - 1), c));+ ctx.fillStyle = paint;+ ctx.fill(new Path2D(shape.d));+ ctx.fillStyle = fill;+ }+ }+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/pointer.ts b/packages/phone-protocol/src/open-bot-avatar/dom/pointer.tsnew file mode 100644index 0000000000..1212e8052e--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/pointer.ts@@ -0,0 +1,51 @@+/**+ * Window-wide pointer tracking for avatars that follow the cursor. Listeners+ * are installed while at least one avatar asks for them and removed after the+ * last one lets go.+ */+import { setPointer } from './clock.ts';++let users = 0;+let detach: (() => void) | null = null;++function attach(): () => void {+ const move = (e: PointerEvent) => setPointer({ x: e.clientX, y: e.clientY });+ const leave = () => setPointer(null);+ // Leaving the window shows up as an `out` with no related target.+ const out = (e: PointerEvent) => !e.relatedTarget && leave();+ // A lifted finger or pen has no position any more.+ const lift = (e: PointerEvent) => e.pointerType !== 'mouse' && leave();+ const hidden = () => document.hidden && leave();+ window.addEventListener('pointermove', move, { passive: true });+ window.addEventListener('pointerdown', move, { passive: true });+ window.addEventListener('pointerout', out);+ window.addEventListener('pointerup', lift);+ window.addEventListener('pointercancel', lift);+ window.addEventListener('blur', leave);+ document.addEventListener('visibilitychange', hidden);+ return () => {+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerdown', move);+ window.removeEventListener('pointerout', out);+ window.removeEventListener('pointerup', lift);+ window.removeEventListener('pointercancel', lift);+ window.removeEventListener('blur', leave);+ document.removeEventListener('visibilitychange', hidden);+ setPointer(null);+ };+}++/** Start tracking the pointer; call the returned function to stop. Safe to call many times. */+export function trackPointer(): () => void {+ if (typeof window === 'undefined') return () => {};+ if (users++ === 0) detach = attach();+ let released = false;+ return () => {+ if (released) return;+ released = true;+ if (--users === 0) {+ detach?.();+ detach = null;+ }+ };+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/reduced.ts b/packages/phone-protocol/src/open-bot-avatar/dom/reduced.tsnew file mode 100644index 0000000000..8e4984d6a3--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/reduced.ts@@ -0,0 +1,18 @@+/** The system's prefers-reduced-motion setting, watched once for the whole page. */+import { requestFrame } from './clock.ts';++const QUERY = '(prefers-reduced-motion: reduce)';+let mql: MediaQueryList | null | undefined;++function media(): MediaQueryList | null {+ if (mql === undefined) {+ mql = typeof matchMedia === 'undefined' ? null : matchMedia(QUERY);+ // Live avatars pick up a change on their next frame; wake the loop so they get one.+ mql?.addEventListener('change', requestFrame);+ }+ return mql;+}++export function prefersReducedMotion(): boolean {+ return media()?.matches ?? false;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/effects.ts b/packages/phone-protocol/src/open-bot-avatar/effects.tsnew file mode 100644index 0000000000..62005cb68d--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/effects.ts@@ -0,0 +1,405 @@+/**+ * What a state draws besides the body: the ribbons that circle a working bot, and the marks a+ * thinking or blocked bot turns into (three dots, an exclamation mark). Pure geometry in viewBox+ * units, from the body's bounds, a seed and the animation clock.+ */+import { noise } from './motion.ts';+import type { Bounds, Point } from './path.ts';++const TAU = Math.PI * 2;+const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));+const smooth = (u: number) => { const x = clamp(u, 0, 1); return x * x * (3 - 2 * x); };+const f = (n: number) => {+ const r = Math.round(n * 100) / 100;+ return (Object.is(r, -0) ? 0 : r).toString();+};++export interface Box { x: number; y: number; w: number; h: number }++// ---------------------------------------------------------------------------+// Ribbons++/** One piece of a ribbon: the part of it in front of the body, or the part behind. */+export interface RibbonPiece {+ d: string;+ front: boolean;+ box: Box;+ /**+ * Which ribbon the piece belongs to. In a celebration, 0..8: hoop `ribbon / LANES`, lane+ * `ribbon % LANES` (from the inner ring out). A working turn has one hoop with three to five+ * ribbons, numbered 0..4 from the inner ring out.+ */+ ribbon: number;+ /**+ * The stretch of its ribbon the piece covers, 0 (tail) to 1 (head), and the centre of the+ * ribbon at either end of that stretch, for a gradient along it. A ribbon comes in a few+ * stretches, each a little past the next where they meet so no seam shows.+ */+ along: [number, number];+ from: [number, number];+ to: [number, number];+}++/**+ * The ribbons ride hoops round the body's centre, laid out as measured from a reference+ * animation, at one size for every avatar. Lengths are in design units: the reference's+ * 228.541-unit space, which its bot fills; here that space is a body of the typical size,+ * BODY units across, so one design unit is BODY / DESIGN avatar units whatever the avatar.+ *+ * A hoop is a ring of radius RING tipped HOOP_TILT out of the screen, so it shows as a flat ellipse, and+ * rolled in the picture. Its near side is the top: a ribbon crosses in front of the body along+ * the top and behind it along the bottom. A working bot uses one hoop, rolled HOOP_ROLL; a+ * celebration three, each a third of a half turn further round, so they cross into a cage.+ *+ * Each hoop carries LANES ribbons on rings LADDER units apart in all, outward from its ring.+ * A ribbon starts at the top of its hoop and goes round with the body's turn (`sweep`), each at+ * its own share of it (FOLLOW) plus a drift of its own (DRIFT), so the ribbons on one hoop part+ * as they go; its ring widens as it goes (WIDEN), and its tail trails up to ARC behind its head.+ */+const DESIGN = 228.541;+/** The typical body across its larger side (the median of the starters and gallery). */+const BODY = 80;+const UNIT = BODY / DESIGN;+/**+ * A hoop's inner ring stands this far outside the body along the hoop's own direction: the hoop's+ * sides, where its ribbons pass behind the body, lie just off the outline (the inner ribbon's+ * edge included), whatever the shape. RING is the typical body's (half its widest row, 38.8,+ * the median of the starters and gallery, × 116/114.27), for callers that give no outline.+ */+const RIM_MARGIN = 2;+const RING = 38.8 * (116 / 114.2705);++/**+ * How far `outlines` (the body in each pose it takes) reach from (cx, cy): `at` along a direction+ * (radians), either way, worked out exactly each time it is asked (a hoop asks once a frame, along+ * its own roll); `max` the farthest over all directions, from RIM_STEPS samples over a half turn.+ */+const RIM_STEPS = 180;++/** How far `outlines` reach from (cx, cy) along a direction (radians), either way, exactly. */+function reachAlong(outlines: Point[][][], cx: number, cy: number, a: number): number {+ const ux = Math.cos(a), uy = Math.sin(a);+ let far = 0;+ for (const poly of outlines.flat()) {+ for (let i = 0; i < poly.length; i++) {+ const [x1, y1] = poly[i], [x2, y2] = poly[(i + 1) % poly.length];+ const ex = x2 - x1, ey = y2 - y1, den = ux * ey - uy * ex;+ if (Math.abs(den) < 1e-12) continue;+ // Where the line through the centre crosses this edge: t along the line, s along the edge.+ const t = ((x1 - cx) * ey - (y1 - cy) * ex) / den, s = ((x1 - cx) * uy - (y1 - cy) * ux) / den;+ if (s >= 0 && s <= 1) far = Math.max(far, Math.abs(t));+ }+ }+ return far;+}++/** How each hoop is rolled in the picture, for an avatar's seed: hoop 0 is a working turn's. */+function hoopRolls(seed: number): number[] {+ return Array.from({ length: HOOPS }, (_, i) => HOOP_ROLL + (i * Math.PI) / HOOPS + (noise(seed, 450 + i) - 0.5) * HOOP_JITTER);+}++/** Where a body's hoops are centred, and how far the body reaches from there (see rimOf). */+export interface Rim {+ cx: number;+ cy: number;+ at: (angle: number) => number;+ max: number;+}+export function rimOf(outlines: Point[][][], cx: number, cy: number): Rim {+ const at = (angle: number) => reachAlong(outlines, cx, cy, angle);+ const steps = Array.from({ length: RIM_STEPS }, (_, k) => at((k * Math.PI) / RIM_STEPS));+ // A spike between two samples can reach a little further than either: allow for a degree's sweep.+ return { cx, cy, at, max: Math.max(...steps) * 1.02 };+}+const HOOP_TILT = 0.386;+const HOOP_ROLL = 0.157;+/** A hoop's roll jitter (full range, radians). */+const HOOP_JITTER = 0.24;+/**+ * A hoop's tilt jitter. The ribbons on one hoop share its roll and tilt exactly: they overlap+ * side by side, and only on one plane do they all pass behind the body along the same line, so+ * which of them lies on top never flips where they do.+ */+const HOOP_TILT_JITTER = 0.08;+const LADDER = 38;+const ARC: [number, number] = [2.2, 3.4];+const FOLLOW: [number, number] = [0.74, 0.94];+/** Radians per second a ribbon drifts on by itself, and design units per second its ring widens. */+const DRIFT: [number, number] = [0.5, 1.1];+const WIDEN = 2.5;+/** How far behind the turn a ribbon starts, at most (radians). */+const START = 0.18;+/**+ * A ribbon's width: a size per ribbon (design units; wider when there are only three, narrower+ * among nine), times BRUSH. It narrows to FAR of that while its head is behind the body, is never+ * wider than a third of its own length on screen, and runs from half that width at its tail to+ * the full width at its head, round at both ends. It grows in over GROW_S and thins as it draws back in.+ */+const SIZE_FEW: [number, number] = [8, 10.5];+const SIZE_FOUR: [number, number] = [6.6, 8.6];+const SIZE_MANY: [number, number] = [5.6, 7.4];+/** A working turn lets out three to five ribbons on its one hoop (per avatar); a celebration three on each. */+const WORK_LANES: [number, number] = [3, 5];+const sizeFor = (count: number) => (count <= 3 ? SIZE_FEW : count === 4 ? SIZE_FOUR : SIZE_MANY);+const BRUSH = 1.7 * 1.98;+const FAR = 0.72;+const GROW_S = 0.34;+/** The ribbons on a turn are let out one after another, this long apart (seconds). */+const STAGGER: [number, number] = [0.055, 0.105];+/**+ * How fast the sweep goes on average (radians per second), working and celebrating: the drift+ * and widening are timed against it, so a ribbon is placed from the sweep alone.+ */+const SWEEP_RATE: [number, number] = [6.3, 15];+/** The longest a sweep lasts, seconds: the widening is bounded by it. */+const SWEEP_LONGEST = 4;+export const LANES = 3;+export const HOOPS = 3;+const SAMPLES = 24;+/** A ribbon is cut into stretches this many samples long, each with a gradient of its own, so its colour follows its length even where it curves round. */+const STRETCH = 6;+/** How far either side of a layer change a ribbon is sampled, radians: the piece behind runs this far on under the piece in front. */+const SLIVER = 0.02;+/** Points on each round end of a ribbon. */+const CAP = 7;++const mix = (range: [number, number], u: number) => range[0] + (range[1] - range[0]) * u;++/**+ * The radius of the farthest ring a ribbon can ride round a body whose outline reaches `rimMax`+ * from its centre at most, the widest a ribbon gets, and how far a ribbon reaches out from its+ * ring (half that). Widths are the same for every avatar; the rings follow its outline.+ */+export function ribbonReach(rimMax?: number): { radius: number; width: number; band: number } {+ const width = SIZE_FEW[1] * BRUSH * UNIT;+ const ring = rimMax === undefined ? RING : rimMax + RIM_MARGIN;+ return { radius: ring + (LADDER + WIDEN * SWEEP_LONGEST) * UNIT, width, band: width / 2 };+}++/**+ * The ribbons at one moment, as filled outlines: round at both ends, a little narrower at the+ * tail than at the head and narrower behind the body, and split where a ribbon passes from+ * behind the body to in front of it. `presence` 0..1 draws them out and back in. `cage` picks+ * the layout: a working turn's 3 to 5 ribbons on one hoop (below 0.5), or a celebration's three+ * on each of three hoops. `sweep` (radians, signed) is how far the body's turn has carried+ * them; between turns they are not drawn. Each ribbon narrows where its hoop curves tighter than+ * half its width, so its outline never folds over itself. `rim` gives the hoops' centre (the+ * middle of the body's mass) and how far the body reaches from it along a direction: a working+ * turn's hoop stands just outside the body along its own direction; a celebration's three share+ * one radius, the largest any of them needs, so the cage stays round. Either way the ribbons pass+ * behind the body only off its outline.+ */+export function ribbonPieces(+ b: Bounds, presence: number, seed: number, _time: number, sweep = 0, cage = 0, rim?: Rim,+): RibbonPiece[] {+ const k = clamp(presence, 0, 1), more = cage >= 0.5 ? 1 : 0;+ if (k <= 0.01) return [];+ const cx = rim ? rim.cx : (b.minX + b.maxX) / 2, cy = rim ? rim.cy : (b.minY + b.maxY) / 2;+ const rolls = hoopRolls(seed), rollOf = (i: number) => rolls[i];+ const cageRing = rim ? Math.max(...[0, 1, 2].map((i) => rim.at(rollOf(i)))) + RIM_MARGIN : RING;+ const unit = UNIT;+ const dir = sweep < 0 ? -1 : 1;+ // How long the sweep has been going, from how far it has got.+ const since = Math.abs(sweep) / mix(SWEEP_RATE, more);+ const pieces: RibbonPiece[] = [];+ for (let i = 0; i < (more ? HOOPS : 1); i++) {+ const hoopRoll = rollOf(i);+ const hoopTilt = HOOP_TILT + (noise(seed, 460 + i) - 0.5) * HOOP_TILT_JITTER;+ const ring = more ? cageRing : rim ? rim.at(hoopRoll) + RIM_MARGIN : RING;+ const lanes = i || more > 0 ? LANES : Math.round(mix(WORK_LANES, noise(seed, 47)));+ for (let l = 0; l < lanes; l++) {+ const n = (m: number) => noise(seed, 500 + (i * LANES + l) * 11 + m);+ // Let out in turn, lane by lane across the hoops: how long ago this one was, and how far+ // the turn had got by then.+ const order = more > 0 ? l * HOOPS + i : l;+ const at = order * mix(STAGGER, n(7));+ const life = since - at;+ if (life <= 0) continue;+ const before = since > 0 ? Math.abs(sweep) * (at / since) : 0;+ const roll = hoopRoll;+ const tilt = hoopTilt;+ const flat = Math.sin(tilt), depth = Math.cos(tilt);+ const cr = Math.cos(roll), sr = Math.sin(roll);+ const r = ring + (l * LADDER * unit) / (lanes - 1) + mix([0, WIDEN], n(2)) * unit * life;+ // The orbit angle (0 = the top of the hoop) of the head: it starts where the turn was when+ // it was let out, a little behind, and goes its own share of the rest. Its tail trails it by+ // as far as it has gone, up to its arc; drawing back in shortens and thins it.+ const travel = (Math.abs(sweep) - before) * mix(FOLLOW, n(3)) + mix(DRIFT, n(4)) * life;+ const head = dir * (before + travel - START * n(5));+ const ret = 1 - clamp(k * 1.25, 0, 1);+ const length = Math.min(mix(ARC, n(6)), travel) * (1 - ret * ret * (3 - 2 * ret));+ if (length <= 0.02) continue;+ const size = mix(sizeFor(lanes), n(8)) * (1 - more) + mix(SIZE_MANY, n(8)) * more;+ const nearHead = clamp(Math.cos(head) * depth, 0, 1);+ let full = size * BRUSH * unit * (FAR + (1 - FAR) * nearHead) * smooth(life / GROW_S) * (1 - 0.72 * ret * ret);+ // A point of the ribbon is in front of the body on the near half of its hoop (depth above 0).+ const lamAt = (u: number) => head - dir * length * (1 - u);+ const point = (lam: number): [number, number] => {+ const a = Math.sin(lam), y = -Math.cos(lam) * flat;+ return [cx + r * (a * cr - y * sr), cy + r * (a * sr + y * cr)];+ };+ // Where along the ribbon (0 tail .. 1 head) to sample it: evenly, plus exactly where it+ // passes from one layer to the other (the hoop's sides, where its depth is 0) and a sliver+ // either side, so every ribbon on a hoop changes layer along the same line.+ const along = (lam: number) => 1 - (head - lam) / (dir * length);+ const sliver = SLIVER / length;+ const ss: number[] = [];+ for (let j = 0; j <= SAMPLES; j++) ss.push(j / SAMPLES);+ const lo = Math.min(head, head - dir * length), hi = Math.max(head, head - dir * length);+ for (let side = Math.ceil((lo - Math.PI / 2) / Math.PI); Math.PI / 2 + side * Math.PI < hi; side++) {+ const u = along(Math.PI / 2 + side * Math.PI);+ for (const d of [-sliver, 0, sliver]) if (u + d > 0 && u + d < 1) ss.push(u + d);+ }+ ss.sort((x, y) => x - y);+ // A sample exactly on a side belongs with the stretch after it.+ const near = ss.map((u) => Math.cos(lamAt(u) + dir * 1e-6) > 0);+ // Centre, half width, unit normal (on screen) at each sample, tail to head.+ const mid: [number, number][] = [], halfs: number[] = [], norm: [number, number][] = [], bend: number[] = [];+ for (const u of ss) {+ const lam = lamAt(u);+ // On the hoop before its roll: the ellipse's normal.+ const nx = Math.sin(lam) * flat, ny = -Math.cos(lam);+ const nl = Math.hypot(nx, ny) || 1;+ const ux = nx / nl, uy = ny / nl;+ mid.push(point(lam));+ norm.push([ux * cr - uy * sr, ux * sr + uy * cr]);+ halfs.push(0.5 + 0.5 * u);+ // How tightly the hoop curves here, as a radius: a ribbon wider than it would fold.+ const c = Math.cos(lam), sn = Math.sin(lam);+ bend.push((r * (c * c + flat * flat * sn * sn) ** 1.5) / flat);+ }+ const last = ss.length - 1;+ // Never wider than a third of its own length on screen.+ let onScreen = 0;+ for (let j = 1; j <= last; j++) onScreen += Math.hypot(mid[j][0] - mid[j - 1][0], mid[j][1] - mid[j - 1][1]);+ full = Math.min(full, 0.34 * onScreen);+ for (let j = 0; j <= last; j++) halfs[j] = Math.min(halfs[j] * (full / 2), 0.9 * bend[j]);+ const side = (j: number, sign: number): [number, number] => [mid[j][0] + sign * norm[j][0] * halfs[j], mid[j][1] + sign * norm[j][1] * halfs[j]];+ // A half circle round an end, from one edge to the other through the point ahead of it (or behind).+ const cap = (j: number, ahead: boolean): [number, number][] => {+ const o = ahead ? mid[j - 1] : mid[j + 1];+ let tx = ahead ? mid[j][0] - o[0] : o[0] - mid[j][0], ty = ahead ? mid[j][1] - o[1] : o[1] - mid[j][1];+ const tl = Math.hypot(tx, ty) || 1;+ tx /= tl; ty /= tl;+ const [nx, ny] = norm[j], h = halfs[j], out: [number, number][] = [];+ for (let c = 1; c < CAP; c++) {+ const t = (Math.PI * c) / CAP;+ // Ahead: from the + edge forward round to the - edge; behind: from the - edge back to the +.+ const e = ahead ? Math.cos(t) : -Math.cos(t), g = ahead ? Math.sin(t) : -Math.sin(t);+ out.push([mid[j][0] + (nx * e + tx * g) * h, mid[j][1] + (ny * e + ty * g) * h]);+ }+ return out;+ };+ // Runs of samples on one side, and at most a stretch long, each become a piece. Pieces overlap+ // by a sample where they meet, the one drawn first running on under the other, so no seam+ // shows: within a side the earlier piece runs on under the later; between sides the piece+ // behind the body (drawn before every piece in front) runs a sliver on under the piece in front.+ let from = 0;+ for (let j = 1; j <= last; j++) {+ const turns = j < last && near[j] !== near[from];+ if (j < last && !turns && j - from < STRETCH) continue;+ const to = j;+ const behind = !near[from];+ const end = to < last && (!turns || behind) ? to + 1 : to;+ const start = from > 0 && behind && near[from - 1] ? from - 1 : from;+ const pts: [number, number][] = [];+ for (let q = start; q <= end; q++) pts.push(side(q, 1));+ if (end === last) pts.push(...cap(last, true));+ for (let q = end; q >= start; q--) pts.push(side(q, -1));+ if (start === 0) pts.push(...cap(0, false));+ const xs = pts.map((p) => p[0]), ys = pts.map((p) => p[1]);+ const x = Math.min(...xs), y = Math.min(...ys);+ pieces.push({+ d: `M${pts.map((p) => `${f(p[0])} ${f(p[1])}`).join('L')}Z`,+ front: near[from],+ box: { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y },+ ribbon: i * LANES + l,+ along: [ss[from], ss[to]],+ from: mid[from],+ to: mid[to],+ });+ from = j;+ }+ }+ }+ return pieces;+}++// ---------------------------------------------------------------------------+// Marks++/** One part of a mark: a fixed outline about its own centre, and where that centre is this frame. */+export interface MarkPart {+ /** Stable name of the outline, e.g. "dot". */+ shape: string;+ d: string;+ box: Box;+ /** Centre, viewBox units, then a rotation about the mark's centre (radians) and a scale about the part's own. */+ x: number;+ y: number;+ turn: number;+ scale: number;+}++const circle = (r: number) => `M${f(r)} 0A${f(r)} ${f(r)} 0 1 1 ${f(-r)} 0A${f(r)} ${f(r)} 0 1 1 ${f(r)} 0Z`;+const capsule = (w: number, h: number) => {+ const r = w / 2, y = h / 2 - r;+ return `M${f(-r)} ${f(-y)}A${f(r)} ${f(r)} 0 0 1 ${f(r)} ${f(-y)}L${f(r)} ${f(y)}A${f(r)} ${f(r)} 0 0 1 ${f(-r)} ${f(y)}Z`;+};++/** The unit every mark is sized in: a share of the body's smaller side, within limits that read at any size. */+function markUnit(b: Bounds): number {+ return clamp(Math.min(b.maxX - b.minX, b.maxY - b.minY), 34, 78);+}++/**+ * The parts of the marks at one moment. `bang` and `dots` 0..1 are how far the body has given+ * way to each (see Pose): a mark grows in as the body goes, from the body's centre.+ * The dots take turns hopping; the exclamation mark jumps and shakes every couple of seconds.+ */+export function markParts(b: Bounds, bang: number, dots: number, seed: number, time: number, still: boolean): MarkPart[] {+ const cx = (b.minX + b.maxX) / 2, cy = (b.minY + b.maxY) / 2;+ const u = markUnit(b);+ const t = still ? 0 : time + noise(seed, 9) * 10;+ const parts: MarkPart[] = [];+ // A mark starts to grow just before the body is gone, so something is always on screen.+ const grown = (weight: number) => smooth((clamp(weight, 0, 1) - 0.45) / 0.55);++ const gb = grown(bang);+ if (gb > 0) {+ const barW = 0.21 * u, barH = 0.5 * u, dot = 0.115 * u, gap = 0.1 * u;+ const total = barH + gap + 2 * dot;+ // One alarm every 2.6 s: a jump, with a shake that dies away as it lands.+ const p = still ? 1 : ((t % 2.6) + 2.6) % 2.6 / 2.6;+ const alarm = p < 0.3 ? p / 0.3 : 1;+ const jump = still ? 0 : Math.sin(Math.PI * alarm);+ const turn = still ? 0 : 0.2 * Math.sin(TAU * 3 * alarm) * (1 - alarm);+ const lift = -0.09 * u * jump;+ const barY = -total / 2 + barH / 2, dotY = total / 2 - dot;+ // The dot lags the bar on the way up, so the mark stretches as it jumps.+ parts.push(+ { shape: 'bar', d: capsule(barW, barH), box: { x: -barW / 2, y: -barH / 2, w: barW, h: barH }, x: cx, y: cy + (barY + lift) * gb, turn, scale: gb },+ { shape: 'dot', d: circle(dot), box: { x: -dot, y: -dot, w: 2 * dot, h: 2 * dot }, x: cx, y: cy + (dotY + lift * 0.45) * gb, turn, scale: gb },+ );+ }++ const gd = grown(dots);+ if (gd > 0) {+ const r = 0.1 * u, step = 0.31 * u;+ for (let i = 0; i < 3; i++) {+ // Each dot hops in turn, a beat after the one before it.+ const p = still ? 0 : (((t - i * 0.17) % 1.25) + 1.25) % 1.25 / 1.25;+ const hop = p < 0.4 ? Math.sin(Math.PI * (p / 0.4)) : 0;+ parts.push({+ shape: 'dot3', d: circle(r), box: { x: -r, y: -r, w: 2 * r, h: 2 * r },+ x: cx + (i - 1) * step * gd, y: cy - 0.16 * u * hop * gd, turn: 0, scale: gd * (1 + 0.12 * hop),+ });+ }+ }+ return parts;+}++/** How much of its size the body keeps while it gives way to a mark: gone a little past half way. */+export function bodyScale(bang: number, dots: number): number {+ return 1 - smooth(clamp(bang + dots, 0, 1) / 0.55);+}diff --git a/packages/phone-protocol/src/open-bot-avatar/examples.ts b/packages/phone-protocol/src/open-bot-avatar/examples.tsnew file mode 100644index 0000000000..efdea07199--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/examples.ts@@ -0,0 +1,112 @@+import type { AvatarDefinition } from './types.ts';++/**+ * Starter avatars, produced with the generate-avatar design prompt. The+ * face-bearing part is always the dominant mass, so the enlarged runtime eyes+ * keep visible room (see faceRoom in volume.ts), and accessories stay small by+ * their outer extent, hollow loops included. Outlines wind clockwise;+ * holes (handles, loops) wind counter-clockwise so the nonzero fill rule cuts+ * them. Tests keep these equal to the skill's example run and the examples in+ * skills/generate-avatar/references/system-prompt.md.+ */+export const examples: AvatarDefinition[] = [+ // Front view: one squat body; the face sits on the wide center above the grips.+ {+ version: 1,+ id: 'controller',+ name: 'Controller',+ body: {+ path:+ 'M28 22C38 20 44 23 50 23C56 23 62 20 72 22C84 24 90 34 91 48C92 62 91 76 82 80C75 83 69 78 66 72C63 67 58 66 50 66C42 66 37 67 34 72C31 78 25 83 18 80C9 76 8 62 9 48C10 34 16 24 28 22Z',+ },+ eyes: { x: 50, y: 42, spacing: 16, scale: 1.05 },+ },+ // Side view, mirror-symmetric about y 50 so it turns as a bar with round plates: two weight tiers a side and a soft bar end.+ {+ version: 1,+ id: 'barbell',+ name: 'Barbell',+ body: {+ path:+ 'M12 41H12A4 4 0 0 1 16 45V55A4 4 0 0 1 12 59H12A4 4 0 0 1 8 55V45A4 4 0 0 1 12 41Z' ++ 'M18 29H18A4 4 0 0 1 22 33V67A4 4 0 0 1 18 71H18A4 4 0 0 1 14 67V33A4 4 0 0 1 18 29Z' ++ 'M26 17H26A5 5 0 0 1 31 22V78A5 5 0 0 1 26 83H26A5 5 0 0 1 21 78V22A5 5 0 0 1 26 17Z' ++ 'M38 33H62A10 10 0 0 1 72 43V57A10 10 0 0 1 62 67H38A10 10 0 0 1 28 57V43A10 10 0 0 1 38 33Z' ++ 'M74 17H74A5 5 0 0 1 79 22V78A5 5 0 0 1 74 83H74A5 5 0 0 1 69 78V22A5 5 0 0 1 74 17Z' ++ 'M82 29H82A4 4 0 0 1 86 33V67A4 4 0 0 1 82 71H82A4 4 0 0 1 78 67V33A4 4 0 0 1 82 29Z' ++ 'M88 41H88A4 4 0 0 1 92 45V55A4 4 0 0 1 88 59H88A4 4 0 0 1 84 55V45A4 4 0 0 1 88 41Z',+ },+ eyes: { x: 50, y: 50, spacing: 15, scale: 1.05 },+ },+ // Side view: the cup carries the face and dominates; a compact handle loop stays a see-through cut-out.+ {+ version: 1,+ id: 'mug',+ name: 'Mug',+ body: {+ path:+ 'M22 20H62C67 20 70 23 70 28V72C70 80 64 86 56 86H28C20 86 14 80 14 72V28C14 23 17 20 22 20Z' ++ 'M68 36C80 34 87 42 87 53C87 64 80 72 68 70Z' ++ 'M69 45L69 61C75.5 62 79 58.5 79 53C79 47.5 76 44 69 45Z',+ },+ eyes: { x: 42, y: 49, spacing: 16, scale: 1.15 },+ },+ // Front view: a big round globe for the face; its neck runs flush into a straight base (one smooth outline), then a clear step down to the contact cap.+ {+ version: 1,+ id: 'lightbulb',+ name: 'Lightbulb',+ body: {+ path:+ 'M36 72V66C36 60 18 55 18 40A32 32 0 0 1 82 40C82 55 64 60 64 66V72Z' ++ 'M36 68H64V77A4 4 0 0 1 60 81H40A4 4 0 0 1 36 77Z' ++ 'M43 78H57V84A4 4 0 0 1 53 88H47A4 4 0 0 1 43 84Z',+ },+ eyes: { x: 50, y: 40, spacing: 17, scale: 1.2 },+ },+ // A wide speech bubble with a small tail.+ {+ version: 1,+ id: 'chat',+ name: 'Chat',+ body: {+ path:+ 'M28 14H72C82 14 90 22 90 32V54C90 64 82 72 72 72H42L25 86C23.5 87.3 21.5 86 22.3 84L27 71.5C17 70 10 63 10 54V32C10 22 18 14 28 14Z',+ },+ eyes: { x: 50, y: 42, spacing: 18, scale: 1.25 },+ },+ // Side view: a big pot (rim + tapered body) hosts the face; a stem with a small bud and two curving leaf blades that taper to soft tips.+ {+ version: 1,+ id: 'sprout',+ name: 'Sprout',+ body: {+ path:+ 'M49.5 19H50.5A3 3 0 0 1 53.5 22V46H46.5V22A3 3 0 0 1 49.5 19Z' ++ 'M49 38C36 41 22.5 36 17.6 23.4A1.4 1.4 0 0 1 18.4 21.6C29 17.5 41.5 21.5 49 34Z' ++ 'M51 30C57 14.5 72 8.5 82.6 11.8A1.4 1.4 0 0 1 83.5 13.4C80.5 27.5 66 35.5 51 34Z' ++ 'M24 44H76A4 4 0 0 1 80 48V54A4 4 0 0 1 76 58H24A4 4 0 0 1 20 54V48A4 4 0 0 1 24 44Z' ++ 'M24 56H76L71 84C70.4 87.5 68 90 64.5 90H35.5C32 90 29.6 87.5 29 84Z',+ },+ eyes: { x: 50, y: 71, spacing: 16, scale: 1.05 },+ },+ // Side view: a big can body hosts the face; a small rear handle loop, joined to the body at both ends, and a short spout name it.+ {+ version: 1,+ id: 'watering-can',+ name: 'Watering Can',+ body: {+ path:+ 'M32 38H62C68 38 71 41 72 47L74 76C74.5 82 70 86 64 86H30C24 86 19.5 82 20 76L22 47C23 41 26 38 32 38Z' ++ 'M23 63C14 63 8.5 57 8.5 48C8.5 37 13 30.5 19 30.5C25 30.5 28.5 34 30 39.5L26 52Z' ++ 'M23.5 42C22 38 20 36 17.5 36C15 36 14 41 14 48C14 54 16 57.5 22 58L23.5 47Z' ++ 'M69 66C75 61 78 55 80 46.5L88 49.5C85 62 80 73 72 81Z' ++ 'M78.7 43A7 4.5 25 0 1 91.3 49A7 4.5 25 0 1 78.7 43Z',+ },+ eyes: { x: 47, y: 61, spacing: 16, scale: 1.15 },+ },+];++export function getExample(id: string): AvatarDefinition | undefined {+ return examples.find((e) => e.id === id);+}diff --git a/packages/phone-protocol/src/open-bot-avatar/eyes.ts b/packages/phone-protocol/src/open-bot-avatar/eyes.tsnew file mode 100644index 0000000000..0007f207ab--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/eyes.ts@@ -0,0 +1,157 @@+/**+ * The outline of one eye for any look. The plain pill, the happy arc and the flat slit of a+ * waiting bot are each walked as a closed outline from the top centre, clockwise, at even steps;+ * mixing them point by point gives every shape in between, so a change of state or mood morphs+ * the eyes instead of swapping them. The slit lies inside the room validation keeps for the arc.+ */+import type { EyeLook } from './motion.ts';+import type { Point } from './path.ts';+import { HAPPY_ARC } from './validate.ts';++/** Where one eye is drawn this frame, in its face plane (viewBox units). */+export interface EyeSpot {+ /** Centre, gaze included. */+ x: number;+ y: number;+ /** Neutral size. */+ w: number;+ h: number;+ /** Height of the pill after blink and squint, and how far that moves it down. */+ open: number;+ shift: number;+}++/** Points per outline. */+const STEPS = 40;+/** The slit: as long as the happy arc is wide, this thick (both as shares of the eye's width), tipped this far. */+const SLIT = { length: 1.9, thick: 0.5, tip: 0.2 } as const;++const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));++/** `count` points at even steps along a closed polyline, the first one at its first point. */+function resample(pts: Point[], count: number): Point[] {+ const n = pts.length;+ const at: number[] = [0];+ for (let i = 0; i < n; i++) {+ const a = pts[i], b = pts[(i + 1) % n];+ at.push(at[i] + Math.hypot(b[0] - a[0], b[1] - a[1]));+ }+ const total = at[n];+ const out: Point[] = [];+ let i = 0;+ for (let k = 0; k < count; k++) {+ const s = (k / count) * total;+ while (i < n - 1 && at[i + 1] < s) i++;+ const a = pts[i], b = pts[(i + 1) % n];+ const u = at[i + 1] > at[i] ? (s - at[i]) / (at[i + 1] - at[i]) : 0;+ out.push([a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u]);+ }+ return out;+}++/** An arc of a circle as points, from angle `from` to `to` (radians, y down), ends included. */+function sweep(cx: number, cy: number, r: number, from: number, to: number, steps: number): Point[] {+ const pts: Point[] = [];+ for (let i = 0; i <= steps; i++) {+ const a = from + ((to - from) * i) / steps;+ pts.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r]);+ }+ return pts;+}++/** The pill: a stadium `w` wide and `h` tall about (cx, cy), from the top centre, clockwise. */+function pill(cx: number, cy: number, w: number, h: number): Point[] {+ const r = Math.min(w, h) / 2;+ const fx = w / 2 - r, fy = h / 2 - r;+ const q = Math.PI / 2;+ return [+ [cx, cy - h / 2] as Point,+ ...sweep(cx + fx, cy - fy, r, -q, 0, 6),+ ...sweep(cx + fx, cy + fy, r, 0, q, 6),+ ...sweep(cx - fx, cy + fy, r, q, 2 * q, 6),+ ...sweep(cx - fx, cy - fy, r, 2 * q, 3 * q, 6),+ ];+}++/** The happy arc as an outline: its stroke's two edges and round ends, from the top centre, clockwise. */+function arc(e: EyeSpot): Point[] {+ const hw = e.w * HAPPY_ARC.halfWidth, base = e.y + e.h * HAPPY_ARC.base, peak = e.y - e.h * HAPPY_ARC.peak;+ const r = (e.w * HAPPY_ARC.stroke) / 2;+ // The centre line and its upward normal at s (0 = left end, 1 = right end).+ const at = (s: number): { p: Point; n: Point } => {+ const m = 1 - s;+ const x = e.x + hw * (2 * s - 1), y = (m * m + s * s) * base + 2 * m * s * peak;+ const tx = 2 * hw, ty = 2 * (2 * s - 1) * (base - peak);+ const len = Math.hypot(tx, ty);+ return { p: [x, y], n: [ty / len, -tx / len] };+ };+ const edge = (from: number, to: number, side: 1 | -1): Point[] => {+ const pts: Point[] = [];+ for (let i = 0; i <= 8; i++) {+ const { p, n } = at(from + ((to - from) * i) / 8);+ pts.push([p[0] + n[0] * r * side, p[1] + n[1] * r * side]);+ }+ return pts;+ };+ const end = (s: 0 | 1): Point[] => {+ const { p, n } = at(s);+ const up = Math.atan2(n[1], n[0]);+ // Round the end from the upper edge to the lower one, the long way round its tip.+ return s === 1 ? sweep(p[0], p[1], r, up, up + Math.PI, 8) : sweep(p[0], p[1], r, up + Math.PI, up + 2 * Math.PI, 8);+ };+ return [...edge(0.5, 1, 1), ...end(1), ...edge(1, 0, -1), ...end(0), ...edge(0, 0.5, 1)];+}++/** The slit: a thin capsule lying almost flat, both eyes tipped the same way; a blink thins it. */+function slit(e: EyeSpot): Point[] {+ const length = e.w * SLIT.length, thick = e.w * SLIT.thick * clamp(e.open / e.h, 0.3, 1);+ const cos = Math.cos(SLIT.tip), sin = Math.sin(SLIT.tip);+ return pill(0, 0, length, thick).map(([x, y]) => [e.x + x * cos - y * sin, e.y + x * sin + y * cos]);+}++/** Whether a look is exactly the plain pill or exactly the happy arc: those are drawn as before. */+export function plainLook(look: EyeLook): 'pill' | 'arc' | null {+ if (look.arc >= 1) return 'arc';+ return look.arc <= 0 && look.slit <= 0 ? 'pill' : null;+}++/** The outline of one eye, closed, clockwise from the top: the pill, the arc and the slit mixed by the look. */+export function eyeOutline(look: EyeLook, e: EyeSpot): Point[] {+ const a = clamp(look.arc, 0, 1), s = clamp(look.slit, 0, 1 - a);+ const shapes: [number, Point[]][] = [[1 - a - s, pill(e.x, e.y + e.shift, e.w, e.open)], [a, arc(e)], [s, slit(e)]];+ const out: Point[] = Array.from({ length: STEPS }, () => [0, 0]);+ for (const [weight, shape] of shapes) {+ if (weight <= 0) continue;+ resample(shape, STEPS).forEach(([x, y], i) => {+ out[i][0] += x * weight;+ out[i][1] += y * weight;+ });+ }+ return out;+}++const f = (n: number) => {+ const r = Math.round(n * 100) / 100;+ return (Object.is(r, -0) ? 0 : r).toString();+};++/** A smooth closed path through an outline: a quadratic per point, joined at the midpoints. Absolute M, Q and Z only. */+export function outlinePath(pts: Point[]): string {+ const n = pts.length;+ const mid = (i: number): Point => {+ const a = pts[i % n], b = pts[(i + 1) % n];+ return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];+ };+ const start = mid(n - 1);+ let d = `M${f(start[0])} ${f(start[1])}`;+ for (let i = 0; i < n; i++) {+ const m = mid(i);+ d += `Q${f(pts[i][0])} ${f(pts[i][1])} ${f(m[0])} ${f(m[1])}`;+ }+ return `${d}Z`;+}++/** The path of one eye for a look that is neither the plain pill nor the plain arc. */+export function eyePath(look: EyeLook, e: EyeSpot): string {+ return outlinePath(eyeOutline(look, e));+}diff --git a/packages/phone-protocol/src/open-bot-avatar/follow.ts b/packages/phone-protocol/src/open-bot-avatar/follow.tsnew file mode 100644index 0000000000..50be75e641--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/follow.ts@@ -0,0 +1,81 @@+/**+ * Cursor following, as pure functions the frame loop steps once per frame.+ *+ * The pointer is mapped to a look direction from the avatar's eyes (not its+ * box center, so a pointer level with the eyes reads as level): radial+ * (diagonals are no stronger than straight lines) and soft, so it uses most of+ * the (small) range across the stage around the avatar and saturates gently+ * beyond it. `attention` fades the whole response in and out, so the eyes and+ * the body's turn hand over to idle motion without a jump.+ */++export interface FollowState {+ x: number;+ y: number;+ /** 0 = at rest (idle wander, resting turn), 1 = fully following the pointer. */+ attention: number;+}++export const REST: FollowState = { x: 0, y: 0, attention: 0 };++/** Time constant of the look easing, seconds: quick enough to track a moving pointer. */+const TAU = 0.12;+/**+ * Attention fades in and out more slowly, so taking up a target, losing it+ * (pointer leaves, follow toggled off) or settling back into the resting turn+ * is an unhurried turn rather than a snap.+ */+const ATTEND_TAU = 0.3;+/** Pointer distance, in avatar sizes, at which the look is at tanh(1) ≈ 76% of full. */+const REACH = 1;+/** Small avatars still get a usable reach, CSS px. */+const MIN_SIZE = 160;++/**+ * Look direction (-1..1, x right, y down) toward a viewport point, from the+ * avatar's bounding box. `origin` is where the look starts, as a fraction of+ * the box (the eyes; default the center).+ */+export function pointerGaze(+ pointer: { x: number; y: number },+ box: { left: number; top: number; width: number; height: number },+ origin: { x: number; y: number } = { x: 0.5, y: 0.5 },+) {+ const reach = Math.max(box.width, box.height, MIN_SIZE) * REACH;+ const dx = (pointer.x - (box.left + box.width * origin.x)) / reach;+ const dy = (pointer.y - (box.top + box.height * origin.y)) / reach;+ const m = Math.hypot(dx, dy);+ if (!Number.isFinite(m) || m < 1e-9) return { x: 0, y: 0 };+ const k = Math.tanh(m) / m;+ return { x: dx * k, y: dy * k };+}++/**+ * One easing step toward `target` (null = not following: back to rest).+ * Frame-rate independent; reduced motion snaps. Returns the next state and+ * whether it still needs frames.+ */+export function followStep(state: FollowState, target: { x: number; y: number } | null, dt: number, reduced: boolean): { state: FollowState; moving: boolean } {+ const goal: FollowState = target ? { x: target.x, y: target.y, attention: 1 } : REST;+ const step = Math.max(0, Math.min(dt, 0.1));+ const ease = (tau: number) => (reduced ? 1 : 1 - Math.exp(-step / tau));+ // Losing the target relaxes the look at the unhurried attention rate, as one movement.+ const k = ease(target ? TAU : ATTEND_TAU);+ const next: FollowState = {+ x: state.x + (goal.x - state.x) * k,+ y: state.y + (goal.y - state.y) * k,+ attention: state.attention + (goal.attention - state.attention) * ease(ATTEND_TAU),+ };+ const moving = Math.abs(goal.x - next.x) > 0.002 || Math.abs(goal.y - next.y) > 0.002 || Math.abs(goal.attention - next.attention) > 0.002;+ return { state: moving ? next : goal, moving };+}++/**+ * The pose's look target for a follow state, nothing at all once at rest.+ * Attention eased through a smoothstep is the weight, so the turn starts and+ * ends gently rather than at full speed.+ */+export function followGaze(state: FollowState): { x: number; y: number; weight: number } | undefined {+ const a = Math.min(1, Math.max(0, state.attention));+ return a > 0 ? { x: state.x, y: state.y, weight: a * a * (3 - 2 * a) } : undefined;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/mood.ts b/packages/phone-protocol/src/open-bot-avatar/mood.tsnew file mode 100644index 0000000000..151e5cce6f--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/mood.ts@@ -0,0 +1,45 @@+/**+ * Changes of state and mood as pure functions a frame loop steps: the pose+ * eases from what is on screen into the new state and mood (see blendPoses in+ * motion.ts), and a change during a change continues from where it is.+ */+import type { AvatarMood, AvatarMotion, AvatarMotionBlend, AvatarState } from './types.ts';++/** Length of a mood change, ms. */+export const MOOD_MS = 420;++const smooth = (t: number) => {+ const x = Math.min(1, Math.max(0, t));+ return x * x * (3 - 2 * x);+};++/** Eased progress of a mood change from elapsed time (smoothstep, clamped). */+export function moodProgress(elapsedMs: number): number {+ return smooth(elapsedMs / MOOD_MS);+}++/** A state and mood on screen, possibly still easing in over what came before. */+export interface MoodState {+ state?: AvatarState;+ mood?: AvatarMood;+ /** @deprecated Use `state` and `mood`. */+ motion?: AvatarMotion;+ /** Seconds the state had been showing when the next change began. */+ age?: number;+ blend?: AvatarMotionBlend;+}++/**+ * What a new mood change eases in from: the mood on screen with any change+ * still under way frozen at its progress, so the pose continues from exactly+ * where it is. Older changes whose share has all but faded (or beyond a few+ * levels) are dropped, so rapid clicking never grows the chain.+ */+export function settleMood(state: MoodState, share = 1, depth = 0): MoodState {+ const b = state.blend;+ if (!b) return state;+ const { blend: _, ...settled } = state;+ const rest = share * (1 - b.t);+ if (rest < 0.02 || depth >= 3) return settled;+ return { ...settled, blend: { from: typeof b.from === 'string' ? b.from : settleMood(b.from, rest, depth + 1), t: b.t } };+}diff --git a/packages/phone-protocol/src/open-bot-avatar/motion.ts b/packages/phone-protocol/src/open-bot-avatar/motion.tsnew file mode 100644index 0000000000..95050894f9--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/motion.ts@@ -0,0 +1,431 @@+/**+ * Deterministic pose model. A pose is a pure function of (seed, time, state,+ * mood, gaze, reducedMotion): no wall clock, no Math.random, so any frame can+ * be reproduced exactly (tests, SSR, scrubbing).+ */+import type { AvatarMood, AvatarMotion, AvatarMotionBlend, AvatarState } from './types.ts';++/**+ * How the eyes are drawn, as numbers that blend: any two looks mix into a shape in between, so+ * the eyes morph from one to the other (see eyes.ts).+ */+export interface EyeLook {+ /** 0 = the plain pill, 1 = the happy arc. */+ arc: number;+ /** 0 = the plain pill, 1 = the flat slit of a waiting bot. Never more than `1 - arc`. */+ slit: number;+}++export interface Pose {+ /** View rotation in radians: yaw turns about the vertical axis, pitch about the horizontal. */+ yaw: number;+ pitch: number;+ /** In-plane rotation, degrees. */+ roll: number;+ /** Vertical offset (negative = up), viewBox units. */+ lift: number;+ /** Squash and stretch about the base of the body. */+ sx: number;+ sy: number;+ /** Eye look direction, -1..1 per axis. */+ gazeX: number;+ gazeY: number;+ /** 0 = open, 1 = fully closed. */+ blink: number;+ /** Extra lid narrowing per eye, 0..1. */+ squintL: number;+ squintR: number;+ eyes: EyeLook;+ /** Presence of the ribbons that circle the body: 0..1 draws them out and back in. */+ ribbons: number;+ /** Which layout the ribbons take: 0 a working turn's one hoop, 1 a celebration's cage of three. */+ cage: number;+ /**+ * How far the body's turn has carried the ribbons round, radians, signed and not wrapped: each+ * ribbon goes its own share of it, so a whole turn more does not put them back where they were.+ */+ sweep: number;+ /** How far the body has given way to a mark, 0..1 each: the exclamation mark and the three dots. */+ bang: number;+ dots: number;+}++/** Every state and mood, in the order hosts list them. */+export const STATES: readonly AvatarState[] = ['idle', 'thinking', 'working', 'waiting', 'blocked', 'done'];+export const MOODS: readonly AvatarMood[] = ['neutral', 'happy'];++export function isState(value: unknown): value is AvatarState {+ return STATES.includes(value as AvatarState);+}++export function isMood(value: unknown): value is AvatarMood {+ return MOODS.includes(value as AvatarMood);+}++/**+ * The state and mood to show. `motion` is the single option that came before them: `thinking`+ * is a state, `happy` a mood. An explicit `state` or `mood` wins over it.+ */+export function resolveLook(given: { state?: unknown; mood?: unknown; motion?: unknown }): { state: AvatarState; mood: AvatarMood } {+ return {+ state: isState(given.state) ? given.state : given.motion === 'thinking' ? 'thinking' : 'idle',+ mood: isMood(given.mood) ? given.mood : given.motion === 'happy' ? 'happy' : 'neutral',+ };+}++/** Resting view: turned a little and seen a little from above, so the volume reads without dominating. */+export const BASE_YAW = -0.3;+export const BASE_PITCH = 0.2;+/**+ * Following a look target: the body turns toward it by up to these angles+ * (radians, at full deflection) and the eyes use this share of their small+ * range, so the whole character looks rather than the eyes sliding alone.+ */+export const LOOK_YAW = 0.32;+export const LOOK_PITCH = 0.18;+export const LOOK_EYES = 0.7;++const TAU = Math.PI * 2;++export function hashString(s: string): number {+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}++/** Stateless hash noise in [0, 1). */+export function noise(seed: number, n: number): number {+ let h = (seed ^ Math.imul(n | 0, 0x9e3779b1)) >>> 0;+ h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);+ h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);+ h ^= h >>> 16;+ return (h >>> 0) / 4294967296;+}++const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));+const smooth = (u: number) => { const x = clamp(u, 0, 1); return x * x * (3 - 2 * x); };+const mix = (a: number, b: number, k: number) => a + (b - a) * k;++/** Blink closure 0..1: one blink per ~4.2 s slot at a seeded offset, sometimes a double blink. */+export function blinkAt(seed: number, t: number): number {+ const SLOT = 4.2, DUR = 0.19;+ const slot = Math.floor(t / SLOT);+ let closure = 0;+ for (const s of [slot - 1, slot]) {+ const start = s * SLOT + 0.5 + noise(seed, s * 2) * 2.9;+ const starts = noise(seed, s * 2 + 1) > 0.8 ? [start, start + 0.34] : [start];+ for (const b of starts) {+ const u = (t - b) / DUR;+ if (u > 0 && u < 1) closure = Math.max(closure, Math.sin(Math.PI * u));+ }+ }+ return closure;+}++/** Idle eye wander: short holds between quick saccades, centered more often than not. */+export function wanderAt(seed: number, t: number): [number, number] {+ const SLOT = 1.9;+ const s = Math.floor(t / SLOT);+ const target = (k: number): [number, number] => {+ if (noise(seed, 1000 + k * 3) < 0.4) return [0, 0];+ return [(noise(seed, 1001 + k * 3) * 2 - 1) * 0.6, (noise(seed, 1002 + k * 3) * 2 - 1) * 0.35];+ };+ const a = target(s - 1), b = target(s);+ const e = smooth((t - s * SLOT) / 0.16);+ return [a[0] + (b[0] - a[0]) * e, a[1] + (b[1] - a[1]) * e];+}++/** Working: the eyes dart from one thing to the next, mostly down at the work. */+function dartAt(seed: number, t: number): [number, number] {+ const SLOT = 0.62;+ const s = Math.floor(t / SLOT);+ const target = (k: number): [number, number] => [(noise(seed, 2001 + k * 3) * 2 - 1) * 0.8, 0.1 + noise(seed, 2002 + k * 3) * 0.5];+ const a = target(s - 1), b = target(s);+ const e = smooth((t - s * SLOT) / 0.12);+ return [mix(a[0], b[0], e), mix(a[1], b[1], e)];+}++export interface PoseInput {+ seed: number;+ time: number;+ state?: AvatarState;+ mood?: AvatarMood;+ /** @deprecated Use `state` and `mood`; they win when given. */+ motion?: AvatarMotion;+ /** Seconds since `state` began: `done` celebrates from then on. Without it the state is at rest. */+ stateAge?: number;+ /** Look target, -1..1 per axis (x right, y down); `weight` 0..1 fades it in over the idle pose (default 1). */+ gaze?: { x: number; y: number; weight?: number };+ reducedMotion: boolean;+ /** Extra view rotation in radians (e.g. from drag-to-turn), added to the resting view. */+ view?: { yaw: number; pitch: number };+ /** Easing in from what was shown before (see blendPoses). */+ blend?: AvatarMotionBlend;+}++/**+ * Pose part way from `a` to `b`, both taken at the same moment so either side's motion keeps+ * running. Everything is a number, the eyes' look included, so eyes morph from one shape to the+ * next and a body gives way to a mark (and back) part by part.+ */+export function blendPoses(a: Pose, b: Pose, t: number): Pose {+ const k = clamp(t, 0, 1);+ const m = (x: number, y: number) => mix(x, y, k);+ // The ribbons stay where the side that shows them has carried them: mixing a celebration's many+ // turns with a pose that has none would wind them back round while they fade.+ const sweep = a.ribbons > 0 && b.ribbons > 0 ? m(a.sweep, b.sweep) : a.ribbons > 0 ? a.sweep : b.sweep;+ // Likewise their layout: a celebration fading out keeps its cage.+ const cage = a.ribbons > 0 && b.ribbons > 0 ? m(a.cage, b.cage) : a.ribbons > 0 ? a.cage : b.cage;+ return {+ yaw: m(a.yaw, b.yaw), pitch: m(a.pitch, b.pitch), roll: m(a.roll, b.roll), lift: m(a.lift, b.lift),+ sx: m(a.sx, b.sx), sy: m(a.sy, b.sy), gazeX: m(a.gazeX, b.gazeX), gazeY: m(a.gazeY, b.gazeY),+ blink: m(a.blink, b.blink), squintL: m(a.squintL, b.squintL), squintR: m(a.squintR, b.squintR),+ eyes: { arc: m(a.eyes.arc, b.eyes.arc), slit: m(a.eyes.slit, b.eyes.slit) },+ ribbons: m(a.ribbons, b.ribbons), cage, sweep, bang: m(a.bang, b.bang), dots: m(a.dots, b.dots),+ };+}++export function computePose(input: PoseInput): Pose {+ const pose = statePose(input);+ const blend = input.blend;+ if (!blend || !(blend.t < 1)) return pose;+ const from = typeof blend.from === 'string' ? { motion: blend.from } : blend.from;+ // A change of mood alone keeps the state's clock running on both sides, so a turn under way+ // stays one turn; a state that was left is held at the age it had.+ const stateAge = resolveLook(from).state === resolveLook(input).state ? input.stateAge : from.age;+ const before = computePose({ ...input, state: from.state, mood: from.mood, motion: from.motion, stateAge, blend: from.blend });+ return blendPoses(before, pose, Number.isFinite(blend.t) ? blend.t : 1);+}++/**+ * Done celebrates in cycles, timed from a reference animation: the ribbons go round+ * DONE_SWEEPS times while the body turns DONE_SWEEPS / 3 times (see celebration), then they draw+ * back in and the bot rests. DONE_TURN_S covers the turn and the drawing in. A cycle lasts+ * DONE_CYCLE_S or up to a seventh longer, differently for each avatar, so several done bots on a+ * page drift apart instead of turning together.+ */+export const DONE_TURN_S = 3.87;+export const DONE_CYCLE_S = 6.2;+const DONE_SWEEPS = 9;+/**+ * How long the ribbons take to draw back in, seconds: they start once the turn has slowed below+ * about 0.9 rad/s, 3.37 s in, and are gone at DONE_TURN_S.+ */+const DONE_DRAW_IN_S = 0.5;++/**+ * A working bot gets on with it and every so often throws itself into the work: a band of+ * ribbons sweeps once round it, easing in like a spring settling, then draws back in. The first comes WORK_FIRST_S+ * (plus up to WORK_FIRST_JITTER_S) after the state begins, then one every WORK_GAP_S, each up to+ * WORK_JITTER_S late, so several working bots do not turn together. A turn takes WORK_TURN_S.+ */+const WORK_FIRST_S = 1.2;+const WORK_FIRST_JITTER_S = 1.2;+const WORK_GAP_S = 7.5;+const WORK_JITTER_S = 1.5;+const WORK_TURN_S = 1.5;+/** How quickly a working turn eases in to its full circle, per second: a critically damped spring's rate. */+const WORK_EASE = 6.2;++/**+ * Where a working bot is in its turns `age` seconds into the state: how far into the current+ * turn (seconds), or null between turns.+ */+function workTurn(seed: number, age: number): number | null {+ const first = WORK_FIRST_S + WORK_FIRST_JITTER_S * noise(seed, 41);+ if (age < first) return null;+ const n = Math.floor((age - first) / WORK_GAP_S);+ // A turn may start up to WORK_JITTER_S late, so the one before may still be running.+ for (const k of [n, n - 1]) {+ if (k < 0) continue;+ const start = first + k * WORK_GAP_S + (k ? WORK_JITTER_S * noise(seed, 60 + k) : 0);+ if (age >= start && age < start + WORK_TURN_S) return age - start;+ }+ return null;+}++/** An angle as the nearest way round to it, -π..π, so a blend never unwinds whole turns. */+const near = (angle: number) => angle - TAU * Math.round(angle / TAU);++/**+ * How far a celebration's ribbons have gone round `t` seconds in, radians, on the reference curve: half+ * a radian of wind-up the other way over 0.24 s, a speed-up to a steady run, then from 2.54 s a+ * slow-down that lands, at 3.79 s, on DONE_SWEEPS whole turns.+ */+const CELEBRATION_END_S = 3.79;+const CELEBRATION_SPEED = (DONE_SWEEPS * TAU + 0.5) / 2.4625;+function celebration(t: number): number {+ const v = CELEBRATION_SPEED;+ if (t <= 0) return 0;+ if (t < 0.24) return -0.25 * (1 - Math.cos((Math.PI * t) / 0.24));+ if (t < 0.54) return -0.5 + (v * (t - 0.24) ** 2) / 0.6;+ if (t < 2.54) return -0.5 + v * (t - 0.39);+ if (t < CELEBRATION_END_S) return -0.5 + v * 2.15 + (1.25 * v * (1 - (1 - (t - 2.54) / 1.25) ** 4)) / 4;+ return DONE_SWEEPS * TAU;+}++function statePose(input: PoseInput): Pose {+ const { seed, time, gaze, reducedMotion, view } = input;+ const { state, mood } = resolveLook(input);+ // Per-avatar phase offset so several avatars on a page do not move in lockstep.+ const t = reducedMotion ? 0 : time + noise(seed, 7) * 10;+ const live = reducedMotion ? 0 : 1;+ const wave = (period: number, phase = 0) => (reducedMotion ? 0 : Math.sin((TAU * t) / period + phase));+ const given = gaze && Number.isFinite(gaze.x) && Number.isFinite(gaze.y)+ ? [clamp(gaze.x, -1, 1), clamp(gaze.y, -1, 1)] as [number, number]+ : null;+ const weight = given ? (Number.isFinite(gaze?.weight) ? clamp(gaze?.weight as number, 0, 1) : 1) : 0;+ // While it attends to a target the body holds its aim: idle sway of the turn settles to a trace.+ const sway = 1 - 0.7 * weight;++ const pose: Pose = {+ yaw: BASE_YAW, pitch: BASE_PITCH, roll: 0, lift: 0, sx: 1, sy: 1,+ gazeX: 0, gazeY: 0, blink: 0, squintL: 0, squintR: 0,+ eyes: { arc: mood === 'happy' ? 1 : 0, slit: 0 }, ribbons: 0, cage: 0, sweep: 0, bang: 0, dots: 0,+ };+ /** The calm pose of a bot with nothing to do: it breathes, sways, blinks and looks around. */+ const rest = (pace: number) => {+ pose.yaw += 0.07 * sway * wave(6.1 * pace);+ pose.pitch += 0.04 * sway * wave(4.7 * pace, 1);+ pose.roll = 1.6 * wave(5.3 * pace, 2);+ pose.lift = reducedMotion ? 0 : -0.45 * (1 - Math.cos((TAU * t) / (3.4 * pace)));+ const breath = wave(3.4 * pace, -Math.PI / 2);+ pose.sy = 1 + 0.012 * breath;+ pose.sx = 1 - 0.008 * breath;+ if (!reducedMotion) {+ pose.blink = blinkAt(seed, t);+ [pose.gazeX, pose.gazeY] = wanderAt(seed, t);+ }+ };++ if (state === 'idle' && mood === 'happy') {+ // With nothing to do, a happy bot hops.+ const period = 0.92;+ const p = reducedMotion ? 0.5 : ((t % period) + period) % period / period;+ const air = 4 * p * (1 - p);+ const land = reducedMotion ? 0 : clamp(1 - Math.min(p, 1 - p) / 0.12, 0, 1);+ pose.lift = reducedMotion ? 0 : -3.2 * air;+ pose.sy = 1 - 0.09 * land + 0.03 * air * live;+ pose.sx = 1 + 0.07 * land - 0.015 * air * live;+ pose.roll = 4.5 * wave(period * 2);+ pose.yaw += 0.1 * wave(period * 2, 0.6);+ } else if (state === 'thinking') {+ // Looks up and away while it gives way to the three dots.+ pose.yaw += 0.12 + 0.05 * sway * wave(7.3);+ pose.pitch += 0.08;+ pose.roll = -5 + 1.4 * wave(4.1);+ pose.lift = -0.5 * (1 - Math.cos((TAU * t) / 5.2)) * live;+ pose.gazeX = 0.55 + 0.3 * wave(5.6);+ pose.gazeY = -0.8;+ pose.squintL = 0.22;+ pose.squintR = 0.32 + 0.1 * wave(3.1);+ if (!reducedMotion) pose.blink = blinkAt(seed, t * 0.7);+ pose.dots = 1;+ } else if (state === 'working') {+ // Bent over the work and busy: a quick steady bob and eyes darting across it, and every so+ // often a turn with a band of ribbons sweeping round it.+ const beat = wave(0.7);+ pose.yaw += 0.08 * sway * wave(2.3, 0.4);+ pose.pitch -= 0.05;+ pose.roll = 3 + 0.6 * beat;+ pose.lift = -0.3 * (0.5 + 0.5 * beat) * live;+ pose.sy = 0.99 - 0.008 * beat;+ pose.sx = 1.005 + 0.005 * beat;+ pose.squintL = 0.25;+ pose.squintR = 0.25;+ if (reducedMotion) {+ pose.gazeX = 0.15;+ pose.gazeY = 0.3;+ } else {+ [pose.gazeX, pose.gazeY] = dartAt(seed, t);+ pose.blink = blinkAt(seed, t * 1.3);+ }+ // Counted from when the state began; without an age, from the clock.+ const age = Number.isFinite(input.stateAge) ? Math.max(0, input.stateAge as number) : Math.max(0, time);+ const into = reducedMotion ? null : workTurn(seed, age);+ if (into !== null) {+ // A full circle that eases in like a spring settling. The band rides it round, out at the+ // start and back in at the end; the body keeps facing the work, leaning into the sweep, and+ // the eyes follow the band across.+ const e = WORK_EASE * into;+ const turn = TAU * (1 - (1 + e) * Math.exp(-e));+ const swell = Math.sin(turn / 2);+ pose.ribbons = clamp(into / 0.16, 0, 1) * clamp((WORK_TURN_S - into) / 0.5, 0, 1);+ pose.sweep = turn;+ pose.yaw += 0.22 * swell;+ pose.roll += 3 * swell;+ pose.lift -= 1.2 * swell;+ pose.gazeX = clamp(pose.gazeX * (1 - swell) - 0.85 * Math.sin(turn), -1, 1);+ pose.gazeY = pose.gazeY * (1 - swell) - 0.3 * swell;+ }+ } else if (state === 'waiting') {+ // Leans to one side, eyes flattened to slits, glancing off at whatever it is waiting on.+ // Now and then it sighs. A happy bot keeps its arcs.+ const p = reducedMotion ? 0 : ((t % 6.5) + 6.5) % 6.5 / 6.5;+ // One breath in and out over the first third of the cycle.+ const sigh = Math.sin(TAU * clamp(p / 0.33, 0, 1));+ pose.yaw += 0.04 * sway * wave(7.4);+ pose.pitch += 0.02 + 0.03 * sigh;+ pose.roll = 7 + 1.2 * wave(6.4, 2);+ pose.lift = -0.3 * (1 - Math.cos((TAU * t) / 6.5)) * live;+ pose.sy = 1 + 0.025 * sigh;+ pose.sx = 1 - 0.012 * sigh;+ pose.gazeX = 0.5 + 0.15 * wave(8.2);+ pose.gazeY = 0.1;+ pose.eyes.slit = 1 - pose.eyes.arc;+ if (!reducedMotion) pose.blink = blinkAt(seed, t * 0.6);+ } else if (state === 'blocked') {+ // Stops still while it gives way to the exclamation mark.+ pose.sy = 1.02;+ pose.sx = 0.99;+ pose.bang = 1;+ } else if (state === 'done') {+ // Celebrates: a few turns with ribbons flying round it, then a rest, content and a little+ // slower than idle, and after a while again, the other way round.+ rest(1.25);+ // Counted from when the state began. Without an age it is at rest.+ const age = !reducedMotion && Number.isFinite(input.stateAge) ? Math.max(0, input.stateAge as number) : DONE_TURN_S;+ const length = DONE_CYCLE_S * (1 + 0.15 * noise(seed, 31));+ const cycle = Math.floor(age / length), since = age - cycle * length;+ if (since < DONE_TURN_S) {+ const swell = Math.sin((Math.PI * since) / DONE_TURN_S);+ const way = cycle % 2 ? -1 : 1;+ const sweep = celebration(since) * way;+ // The body turns a third as often as the ribbons go round.+ pose.yaw += near(sweep / 3);+ pose.lift -= 2.2 * swell;+ pose.sy += 0.04 * swell;+ // All the ribbons out at full strength while the turn is quick, drawn back in as it settles.+ pose.ribbons = clamp(since / 0.1, 0, 1) * clamp((DONE_TURN_S - since) / DONE_DRAW_IN_S, 0, 1);+ pose.cage = 1;+ // The ribbons only set off once the turn goes forward: the wind-up does not carry them.+ pose.sweep = way * Math.max(0, celebration(since));+ }+ } else {+ rest(1);+ }++ if (given && weight > 0) {+ // A look target wins over idle wander. The body turns to face it: the resting+ // three-quarter turn gives way (so a target on either side turns the front that+ // way) and the eyes add a modest share on top. Reduced motion keeps the body+ // still, so the eyes alone use their full (still small) range. Happy arcs stay put.+ const share = reducedMotion ? 1 : LOOK_EYES;+ const follow = weight * (1 - pose.eyes.arc);+ pose.gazeX = mix(pose.gazeX, given[0] * share, follow);+ pose.gazeY = mix(pose.gazeY, given[1] * share, follow);+ if (!reducedMotion) {+ // Positive yaw turns the front to the right, positive pitch tips it up.+ pose.yaw += weight * (given[0] * LOOK_YAW - BASE_YAW);+ pose.pitch += weight * (-given[1] * LOOK_PITCH - BASE_PITCH / 2);+ }+ }+ if (view && Number.isFinite(view.yaw) && Number.isFinite(view.pitch)) {+ pose.yaw += view.yaw;+ pose.pitch += view.pitch;+ }+ return pose;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/path.ts b/packages/phone-protocol/src/open-bot-avatar/path.tsnew file mode 100644index 0000000000..97f7070121--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/path.ts@@ -0,0 +1,330 @@+/**+ * Restricted SVG path geometry: parser, normalizer and flattener.+ *+ * Accepts the path command set M L H V C S Q T A Z (absolute and relative)+ * and nothing else. The parsed result is re-serialized from numbers, so the+ * renderer never echoes model-written text into markup.+ */++export type Segment =+ | { c: 'M'; x: number; y: number }+ | { c: 'L'; x: number; y: number }+ | { c: 'C'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }+ | { c: 'Q'; x1: number; y1: number; x: number; y: number }+ | { c: 'A'; rx: number; ry: number; rot: number; large: 0 | 1; sweep: 0 | 1; x: number; y: number }+ | { c: 'Z' };++export type Point = [number, number];++export const PATH_LIMITS = {+ maxChars: 6000,+ maxSegments: 400,+ maxSubpaths: 16,+ coordMin: -20,+ coordMax: 120,+} as const;++const ARG_COUNT: Record<string, number> = { M: 2, L: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, T: 2, A: 7, Z: 0 };++export class PathError extends Error {}++function tokenize(d: string): (string | number)[] {+ if (/[^MmLlHhVvCcSsQqTtAaZz0-9.,eE+\-\s]/.test(d)) {+ const bad = d.match(/[^MmLlHhVvCcSsQqTtAaZz0-9.,eE+\-\s]/)![0];+ throw new PathError(`unsupported character ${JSON.stringify(bad)} (allowed commands: M L H V C S Q T A Z)`);+ }+ const tokens: (string | number)[] = [];+ const re = /([MmLlHhVvCcSsQqTtAaZz])|([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)|([\s,]+)/y;+ let i = 0;+ while (i < d.length) {+ re.lastIndex = i;+ const m = re.exec(d);+ if (!m) throw new PathError(`cannot parse path near ${JSON.stringify(d.slice(i, i + 12))}`);+ if (m[1]) tokens.push(m[1]);+ else if (m[2]) tokens.push(Number(m[2]));+ i = re.lastIndex;+ }+ return tokens;+}++/** Parse and convert to absolute M/L/C/Q/A/Z segments. Throws PathError. */+export function parsePath(d: string): Segment[] {+ if (typeof d !== 'string' || d.trim() === '') throw new PathError('path is empty');+ if (d.length > PATH_LIMITS.maxChars) throw new PathError(`path longer than ${PATH_LIMITS.maxChars} characters`);+ const tokens = tokenize(d);+ const out: Segment[] = [];+ let i = 0;+ let cx = 0, cy = 0, sx = 0, sy = 0;+ let prevC: [number, number] | null = null;+ let prevQ: [number, number] | null = null;+ let cmd = '';+ let subpaths = 0;+ let open = false;++ while (i < tokens.length) {+ const t = tokens[i];+ if (typeof t === 'string') {+ cmd = t;+ i++;+ if (cmd === 'Z' || cmd === 'z') {+ if (!open) throw new PathError('Z without an open subpath');+ out.push({ c: 'Z' });+ cx = sx; cy = sy; prevC = prevQ = null; open = false;+ continue;+ }+ } else if (!cmd) {+ throw new PathError('path must start with M');+ } else if (cmd === 'Z' || cmd === 'z') {+ throw new PathError('numbers after Z');+ }+ const up = cmd.toUpperCase();+ const rel = cmd !== up;+ if (out.length === 0 && up !== 'M') throw new PathError('path must start with M');+ const n = ARG_COUNT[up];+ const args: number[] = [];+ for (let k = 0; k < n; k++) {+ const v = tokens[i + k];+ if (typeof v !== 'number') throw new PathError(`command ${cmd} expects ${n} numbers`);+ if (!Number.isFinite(v)) throw new PathError('non-finite number');+ args.push(v);+ }+ i += n;+ const ox = rel ? cx : 0, oy = rel ? cy : 0;+ let nextC: [number, number] | null = null;+ let nextQ: [number, number] | null = null;+ switch (up) {+ case 'M': {+ if (open) out.push({ c: 'Z' }); // implicit close keeps fill semantics explicit+ cx = args[0] + ox; cy = args[1] + oy; sx = cx; sy = cy;+ out.push({ c: 'M', x: cx, y: cy });+ subpaths++; open = true;+ cmd = rel ? 'l' : 'L'; // subsequent pairs are implicit lineto+ break;+ }+ case 'L': cx = args[0] + ox; cy = args[1] + oy; out.push({ c: 'L', x: cx, y: cy }); break;+ case 'H': cx = args[0] + ox; out.push({ c: 'L', x: cx, y: cy }); break;+ case 'V': cy = args[0] + oy; out.push({ c: 'L', x: cx, y: cy }); break;+ case 'C': {+ const s: Segment = { c: 'C', x1: args[0] + ox, y1: args[1] + oy, x2: args[2] + ox, y2: args[3] + oy, x: args[4] + ox, y: args[5] + oy };+ out.push(s); nextC = [s.x2, s.y2]; cx = s.x; cy = s.y; break;+ }+ case 'S': {+ const x1: number = prevC ? 2 * cx - prevC[0] : cx, y1: number = prevC ? 2 * cy - prevC[1] : cy;+ const s: Segment = { c: 'C', x1, y1, x2: args[0] + ox, y2: args[1] + oy, x: args[2] + ox, y: args[3] + oy };+ out.push(s); nextC = [s.x2, s.y2]; cx = s.x; cy = s.y; break;+ }+ case 'Q': {+ const s: Segment = { c: 'Q', x1: args[0] + ox, y1: args[1] + oy, x: args[2] + ox, y: args[3] + oy };+ out.push(s); nextQ = [s.x1, s.y1]; cx = s.x; cy = s.y; break;+ }+ case 'T': {+ const x1: number = prevQ ? 2 * cx - prevQ[0] : cx, y1: number = prevQ ? 2 * cy - prevQ[1] : cy;+ const s: Segment = { c: 'Q', x1, y1, x: args[0] + ox, y: args[1] + oy };+ out.push(s); nextQ = [x1, y1]; cx = s.x; cy = s.y; break;+ }+ case 'A': {+ const [rx, ry, rot, la, sw] = args;+ if (rx < 0 || ry < 0) throw new PathError('arc radii must be non-negative');+ if ((la !== 0 && la !== 1) || (sw !== 0 && sw !== 1)) throw new PathError('arc flags must be 0 or 1, written as separate numbers');+ cx = args[5] + ox; cy = args[6] + oy;+ out.push({ c: 'A', rx, ry, rot, large: la as 0 | 1, sweep: sw as 0 | 1, x: cx, y: cy });+ break;+ }+ default:+ throw new PathError(`unsupported command ${cmd}`);+ }+ prevC = nextC; prevQ = nextQ;+ if (out.length > PATH_LIMITS.maxSegments) throw new PathError(`more than ${PATH_LIMITS.maxSegments} segments`);+ }+ if (open) out.push({ c: 'Z' });+ if (subpaths > PATH_LIMITS.maxSubpaths) throw new PathError(`more than ${PATH_LIMITS.maxSubpaths} subpaths`);+ for (const s of out) {+ for (const [k, v] of Object.entries(s)) {+ if (k === 'c' || typeof v !== 'number') continue;+ if (k === 'rot' || k === 'large' || k === 'sweep') continue;+ if (v < PATH_LIMITS.coordMin || v > PATH_LIMITS.coordMax) throw new PathError(`coordinate ${v} far outside the 0..100 viewBox`);+ }+ }+ return out;+}+++function fmt(n: number): string {+ const r = Math.round(n * 100) / 100;+ return (Object.is(r, -0) ? 0 : r).toString();+}++/** Compact absolute serialization built only from parsed numbers. */+export function serializePath(segs: Segment[]): string {+ const parts: string[] = [];+ for (const s of segs) {+ switch (s.c) {+ case 'M': parts.push(`M${fmt(s.x)} ${fmt(s.y)}`); break;+ case 'L': parts.push(`L${fmt(s.x)} ${fmt(s.y)}`); break;+ case 'C': parts.push(`C${fmt(s.x1)} ${fmt(s.y1)} ${fmt(s.x2)} ${fmt(s.y2)} ${fmt(s.x)} ${fmt(s.y)}`); break;+ case 'Q': parts.push(`Q${fmt(s.x1)} ${fmt(s.y1)} ${fmt(s.x)} ${fmt(s.y)}`); break;+ case 'A': parts.push(`A${fmt(s.rx)} ${fmt(s.ry)} ${fmt(s.rot)} ${s.large} ${s.sweep} ${fmt(s.x)} ${fmt(s.y)}`); break;+ case 'Z': parts.push('Z'); break;+ }+ }+ return parts.join('');+}++/** Endpoint arc → sampled points (SVG implementation notes, F.6.5). */+function sampleArc(x0: number, y0: number, s: Extract<Segment, { c: 'A' }>, out: Point[]): void {+ let { rx, ry } = s;+ const { x, y } = s;+ if (rx === 0 || ry === 0 || (x0 === x && y0 === y)) { out.push([x, y]); return; }+ const phi = (s.rot * Math.PI) / 180;+ const cos = Math.cos(phi), sin = Math.sin(phi);+ const dx = (x0 - x) / 2, dy = (y0 - y) / 2;+ const x1p = cos * dx + sin * dy, y1p = -sin * dx + cos * dy;+ rx = Math.abs(rx); ry = Math.abs(ry);+ const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);+ if (lambda > 1) { const k = Math.sqrt(lambda); rx *= k; ry *= k; }+ const num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;+ const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;+ let coef = Math.sqrt(Math.max(0, num / den));+ if (s.large === s.sweep) coef = -coef;+ const cxp = (coef * rx * y1p) / ry, cyp = (-coef * ry * x1p) / rx;+ const cx = cos * cxp - sin * cyp + (x0 + x) / 2;+ const cy = sin * cxp + cos * cyp + (y0 + y) / 2;+ const ang = (ux: number, uy: number, vx: number, vy: number) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);+ const t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);+ let dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);+ if (!s.sweep && dt > 0) dt -= 2 * Math.PI;+ if (s.sweep && dt < 0) dt += 2 * Math.PI;+ // Chords within FLATNESS of the arc: a chord over angle θ sags r(1 - cos(θ/2)).+ const step = 2 * Math.acos(Math.max(-1, 1 - FLATNESS / Math.max(rx, ry)));+ const steps = Math.min(256, Math.max(4, Math.ceil(Math.abs(dt) / step)));+ for (let k = 1; k <= steps; k++) {+ const t = t1 + (dt * k) / steps;+ const ex = rx * Math.cos(t), ey = ry * Math.sin(t);+ out.push([cos * ex - sin * ey + cx, sin * ex + cos * ey + cy]);+ }+}++/**+ * Largest gap, viewBox units, between a curve and the polygon that stands for it. Volume slices+ * follow that polygon while the flat core draws the real curve, so coarser chords show as facets+ * and teeth along the rim of large avatars.+ */+export const FLATNESS = 0.02;++/** Flatten into closed polygons, one per subpath. */+export function flattenPath(segs: Segment[]): Point[][] {+ const polys: Point[][] = [];+ let cur: Point[] = [];+ let px = 0, py = 0;+ for (const s of segs) {+ switch (s.c) {+ case 'M':+ if (cur.length) polys.push(cur);+ cur = [[s.x, s.y]]; px = s.x; py = s.y; break;+ case 'L': cur.push([s.x, s.y]); px = s.x; py = s.y; break;+ case 'C': {+ // Wang's bound: this many chords keep within FLATNESS of the curve.+ const m = Math.max(Math.hypot(px - 2 * s.x1 + s.x2, py - 2 * s.y1 + s.y2), Math.hypot(s.x1 - 2 * s.x2 + s.x, s.y1 - 2 * s.y2 + s.y));+ const n = Math.min(128, Math.max(2, Math.ceil(Math.sqrt((0.75 * m) / FLATNESS))));+ for (let k = 1; k <= n; k++) {+ const t = k / n, u = 1 - t;+ cur.push([+ u * u * u * px + 3 * u * u * t * s.x1 + 3 * u * t * t * s.x2 + t * t * t * s.x,+ u * u * u * py + 3 * u * u * t * s.y1 + 3 * u * t * t * s.y2 + t * t * t * s.y,+ ]);+ }+ px = s.x; py = s.y; break;+ }+ case 'Q': {+ const n = Math.min(128, Math.max(2, Math.ceil(Math.sqrt((0.25 * Math.hypot(px - 2 * s.x1 + s.x, py - 2 * s.y1 + s.y)) / FLATNESS))));+ for (let k = 1; k <= n; k++) {+ const t = k / n, u = 1 - t;+ cur.push([u * u * px + 2 * u * t * s.x1 + t * t * s.x, u * u * py + 2 * u * t * s.y1 + t * t * s.y]);+ }+ px = s.x; py = s.y; break;+ }+ case 'A': sampleArc(px, py, s, cur); px = s.x; py = s.y; break;+ case 'Z':+ if (cur.length) { polys.push(cur); px = cur[0][0]; py = cur[0][1]; }+ cur = []; break;+ }+ }+ if (cur.length) polys.push(cur);+ return polys.filter((p) => p.length >= 3);+}++/** Nonzero winding number of a point against all subpaths (SVG default fill rule). */+export function winding(polys: Point[][], x: number, y: number): number {+ let w = 0;+ for (const poly of polys) {+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {+ const [xi, yi] = poly[i];+ const [xj, yj] = poly[j];+ if (yj <= y) {+ if (yi > y && (xi - xj) * (y - yj) - (x - xj) * (yi - yj) > 0) w++;+ } else if (yi <= y && (xi - xj) * (y - yj) - (x - xj) * (yi - yj) < 0) w--;+ }+ }+ return w;+}++export function isInside(polys: Point[][], x: number, y: number): boolean {+ return winding(polys, x, y) !== 0;+}++/**+ * Nonzero inside flags for many points on one row (xs ascending), from a+ * single pass over the edges instead of one winding test per point.+ */+export function insideRow(polys: Point[][], y: number, xs: number[], out: Uint8Array): void {+ const hits: [number, number][] = [];+ for (const poly of polys) {+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {+ const [xj, yj] = poly[j], [xi, yi] = poly[i];+ if (yj <= y && yi > y) hits.push([xj + ((y - yj) * (xi - xj)) / (yi - yj), 1]);+ else if (yi <= y && yj > y) hits.push([xj + ((y - yj) * (xi - xj)) / (yi - yj), -1]);+ }+ }+ hits.sort((a, b) => a[0] - b[0]);+ let w = 0, h = 0;+ for (let k = 0; k < xs.length; k++) {+ while (h < hits.length && hits[h][0] < xs[k]) w += hits[h++][1];+ out[k] = w !== 0 ? 1 : 0;+ }+}++export interface Bounds { minX: number; minY: number; maxX: number; maxY: number }++export function bounds(polys: Point[][]): Bounds {+ const b = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };+ for (const p of polys) for (const [x, y] of p) {+ if (x < b.minX) b.minX = x;+ if (y < b.minY) b.minY = y;+ if (x > b.maxX) b.maxX = x;+ if (y > b.maxY) b.maxY = y;+ }+ return b;+}++/** Filled area estimated on a 1-unit sample grid (nonzero rule). */+export function filledArea(polys: Point[][], b: Bounds = bounds(polys)): number {+ let n = 0;+ const xs: number[] = [];+ for (let x = Math.floor(b.minX) + 0.5; x < b.maxX; x += 1) xs.push(x);+ const row = new Uint8Array(xs.length);+ for (let y = Math.floor(b.minY) + 0.5; y < b.maxY; y += 1) {+ insideRow(polys, y, xs, row);+ for (const v of row) n += v;+ }+ return n;+}++/** Split normalized segments into one segment list per subpath. */+export function splitSubpaths(segs: Segment[]): Segment[][] {+ const out: Segment[][] = [];+ for (const s of segs) {+ if (s.c === 'M') out.push([]);+ out[out.length - 1]?.push(s);+ }+ return out;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/render.ts b/packages/phone-protocol/src/open-bot-avatar/render.tsnew file mode 100644index 0000000000..df09066be7--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/render.ts@@ -0,0 +1,796 @@+/**+ * Renderers for a validated silhouette + eye placement with implied volume+ * (see volume.ts). One flat body color, two plain dark eyes; no gradients,+ * gloss, rim light or shadows. Output is built only from numbers and the+ * renderer's own markup.+ *+ * - avatarFrame: one frame flattened to plain data (paths, matrices, eyes),+ * for any vector renderer.+ * - renderAvatarSvg: a standalone still, serialized from avatarFrame. Cross-sections of the stack that+ * faces the viewer are projected orthographically and painted back to front.+ * - renderAvatarScene + sceneFrame: a CSS 3D scene. Every cross-section is its+ * own small SVG placed once with a 3D transform; animating, turning and+ * recoloring only change a few CSS transforms, and the browser's compositor+ * does projection and occlusion. Each visible slice costs a compositor layer,+ * so mountAvatar paints live avatars to one canvas by default and only uses+ * the scene with `renderer: 'scene'`.+ *+ * A state can draw more than the body (see effects.ts): ribbons behind and in front of it, and+ * the marks a thinking or blocked bot turns into. Those stay where they are while the body hops+ * and rolls.+ */+import { mix, parseHex, toHex } from './color.ts';+import type { Rgb } from './color.ts';+import { bodyScale, markParts, ribbonPieces, ribbonReach, rimOf } from './effects.ts';+import type { Rim } from './effects.ts';+import type { Box } from './effects.ts';+import { eyePath, plainLook } from './eyes.ts';+import type { EyeSpot } from './eyes.ts';+import { computePose, hashString, noise } from './motion.ts';+import type { EyeLook, Pose } from './motion.ts';+import type { Bounds, Point } from './path.ts';+import { EYE_H, EYE_W, GAZE_X, GAZE_Y, HAPPY_ARC, analyzeBody, eyeCenters, gazeRange, validateAvatar } from './validate.ts';+import type { GazeRange } from './validate.ts';+import { buildVolume } from './volume.ts';+import type { Volume, VolumeSlice } from './volume.ts';+import type { AvatarDefinition, RenderOptions } from './types.ts';++export const DEFAULT_COLOR = '#ff6a1a';+export const DEFAULT_EYE_COLOR = '#151515';+/** `depth` option value that maps to the natural inferred volume. */+export const DEFAULT_DEPTH = 6;+const MAX_DEPTH = 14;+/**+ * Eyes sit this far above the surface so they never touch the body planes. iOS WebKit treats planes+ * closer than about a pixel as one and may draw the body over an eye (0.3 did: a band of the+ * barbell's bar through one eye), so the gap is a few pixels at the stage's size. Turned, an eye+ * drifts lift × sin(angle) from its spot: under half a unit at rest, about one at 45°.+ */+const EYE_LIFT = 1.5;++interface Prepared {+ def: AvatarDefinition;+ vol: Volume;+ range: GazeRange;+ seed: number;+ /** Prefix for SVG ids; equal geometry and depth always give equal ids, so repeats on a page are safe. */+ id: string;+ /** Stable SVG id per distinct cross-section path, assigned once. */+ ids: Map<string, string>;+ /** Slices kept at a rendered size, per stack, keyed by stack and rounded size. */+ detail: Map<string, boolean[]>;+ /** Where the ribbons' hoops are centred and how far the body reaches from there (see ribbonRims). */+ rims: () => { work: Rim; cage: Rim };+}++const cache = new Map<string, Prepared>();++const f = (n: number) => {+ const r = Math.round(n * 100) / 100;+ return (Object.is(r, -0) ? 0 : r).toString();+};+const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));++function depthOption(options: RenderOptions): number {+ const d = clamp(Number.isFinite(options.depth) ? (options.depth as number) : DEFAULT_DEPTH, 0, MAX_DEPTH);+ return Math.round(d * 2) / 2;+}++const lazy = <T>(make: () => T): (() => T) => {+ let value: T | undefined;+ return () => (value ??= make());+};++/**+ * How far the body reaches from the middle of its box, for a working turn's hoop and for a+ * celebration's cage. The hoops' centre hops and stretches with the body (see ribbonsFollow) but+ * does not lean or sway with it, so each is measured over the leans its state takes, the body+ * stretched about the centre: a working bot leans 2.4° to 6.6° and squashes to 98%; a celebrating+ * one sways ±1.7° and stretches up to 5.5%. The hoops stand just outside that, so the body never+ * moves through a point where a ribbon passes behind it.+ */+export function ribbonRims(polys: Point[][], b: Bounds): { work: Rim; cage: Rim } {+ const [cx, cy] = pivotOf(b);+ const bx = (b.minX + b.maxX) / 2, by = b.maxY;+ /** The body leaned by each of `rolls` (degrees, about its base) and stretched by each of `sys` about the centre. */+ const posed = (rolls: number[], sys: number[]) => {+ const out: Point[][][] = [];+ for (const roll of rolls) {+ const r = (roll * Math.PI) / 180, c = Math.cos(r), sn = Math.sin(r);+ for (const k of sys) {+ out.push(polys.map((poly) => poly.map(([x, y]): Point => {+ const lx = bx + c * (x - bx) - sn * (y - by), ly = by + sn * (x - bx) + c * (y - by);+ return [cx + 1.01 * (lx - cx), cy + k * (ly - cy)];+ })));+ }+ }+ return out;+ };+ return { work: rimOf(posed([2.4, 4.5, 6.6], [0.98, 1]), cx, cy), cage: rimOf(posed([-1.7, 0, 1.7], [0.99, 1.055]), cx, cy) };+}++/**+ * The rim moved to where the hoops' centre is in this pose: it hops and stretches with the body+ * (the root motion's lift and scale about the base) but does not lean or sway with it.+ */+export function ribbonsFollow(rim: Rim, pose: Pick<Pose, 'lift' | 'sx' | 'sy'>, b: Bounds): Rim {+ const bx = (b.minX + b.maxX) / 2, by = b.maxY;+ return { ...rim, cx: bx + pose.sx * (rim.cx - bx), cy: by + pose.sy * (rim.cy - by) + pose.lift };+}++function prepare(definition: AvatarDefinition, depth: number): Prepared {+ const key = JSON.stringify([definition?.id, definition?.name, definition?.body?.path, definition?.eyes, depth]);+ const hit = cache.get(key);+ if (hit) return hit;+ const res = validateAvatar(definition);+ if (!res.ok) throw new Error(`Invalid avatar definition: ${res.errors.join('; ')}`);+ const def = res.value;+ const body = analyzeBody(def.body.path);+ const vol = buildVolume(def, depth / DEFAULT_DEPTH, body);+ const id = `oba-${hashString(`${def.id}|${def.body.path}|${depth}`).toString(36)}`;+ const ids = new Map<string, string>();+ for (const part of vol.parts) for (const s of [...part.zSlices, ...part.xSlices]) if (!ids.has(s.d)) ids.set(s.d, `${id}-${ids.size}`);+ const prepared: Prepared = {+ def,+ vol,+ range: gazeRange(body.polys, { ...def.eyes, scale: vol.eyeScale }),+ seed: hashString(def.id),+ id,+ ids,+ detail: new Map(),+ rims: lazy(() => ribbonRims(body.polys, vol.bounds)),+ };+ if (cache.size >= 64) cache.delete(cache.keys().next().value as string);+ cache.set(key, prepared);+ return prepared;+}++/** The validated definition and its cached volume, exactly as the renderers use them. Throws if invalid. */+export function preparedVolume(definition: AvatarDefinition, depth?: number): { def: AvatarDefinition; vol: Volume } {+ const p = prepare(definition, depthOption({ depth }));+ return { def: p.def, vol: p.vol };+}++function poseOf(p: Prepared, options: RenderOptions): Pose {+ return computePose({+ seed: p.seed,+ time: Number.isFinite(options.time) ? (options.time as number) : 0,+ state: options.state,+ mood: options.mood,+ motion: options.motion,+ stateAge: options.stateAge,+ gaze: options.gaze,+ reducedMotion: options.reducedMotion === true,+ view: options.view,+ blend: options.motionBlend,+ });+}++function esc(s: string): string {+ return s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);+}++// ---------------------------------------------------------------------------+// View math++type M = Matrix;+const mul = (m: M, n: M): M => [+ m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1],+ m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],+ m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5],+];+const translate = (x: number, y: number): M => [1, 0, 0, 1, x, y];+const about = (x: number, y: number, m: M): M => mul(translate(x, y), mul(m, translate(-x, -y)));+const invert = ([a, b, c, d, e, g]: M): M => {+ const det = a * d - b * c;+ return [d / det, -b / det, -c / det, a / det, (c * g - d * e) / det, (b * e - a * g) / det];+};+const mat = (m: M) => `matrix(${m.map((v, i) => (i < 4 ? (Math.round(v * 10000) / 10000).toString() : f(v))).join(' ')})`;++export interface ViewBasis {+ cY: number;+ sY: number;+ cP: number;+ sP: number;+ /** cos(yaw)·cos(pitch): > 0 when the front faces the viewer. */+ facing: number;+}++export function viewBasis(yaw: number, pitch: number): ViewBasis {+ const cY = Math.cos(yaw), cP = Math.cos(pitch);+ return { cY, sY: Math.sin(yaw), cP, sP: Math.sin(pitch), facing: cY * cP };+}++/** Minimum facing (toward-viewer component of the surface normal) for an eye to be drawn. */+const EYE_FACING = 0.22;++/** Toward-viewer component of a model-space direction under this view (1 = straight at the viewer). */+export function facingOf(v: ViewBasis, [x, y, z]: [number, number, number]): number {+ return v.sP * y + v.cP * (-v.sY * x + v.cY * z);+}++/** Whether eye `i` is drawn: every surface normal under it must face the viewer. */+function eyeVisible(vol: Volume, v: ViewBasis, i: number): boolean {+ return vol.eyeNormals[i].every((n) => facingOf(v, n) > EYE_FACING);+}++/** Which slice stack faces the viewer more: front-facing z-planes or side-facing x-planes. */+export function activeStack(v: ViewBasis): 'z' | 'x' {+ return Math.abs(v.cY) >= Math.abs(v.sY) ? 'z' : 'x';+}++/**+ * Orthographic projection of the plane at depth z, pivoting on `pivot` at z = 0.+ * Yaw turns about the vertical axis, then pitch tips about the horizontal axis.+ */+export function planeMatrix(v: ViewBasis, z: number, pivot: Point): M {+ const [cx, cy] = pivot;+ return [+ v.cY, v.sY * v.sP, 0, v.cP,+ cx - v.cY * cx + v.sY * z,+ cy - v.cP * cy - v.sY * v.sP * cx - v.cY * v.sP * z,+ ];+}++/** Projection of the side plane x = x0, whose local coordinates are (u = -z, y). */+export function sidePlaneMatrix(v: ViewBasis, x0: number, pivot: Point): M {+ const [cx, cy] = pivot;+ return [-v.sY, v.cY * v.sP, 0, v.cP, cx + v.cY * (x0 - cx), cy - v.cP * cy + v.sY * v.sP * (x0 - cx)];+}++/** Project a 3D point: screen x, screen y and depth toward the viewer. */+export function projectPoint(v: ViewBasis, [x, y, z]: [number, number, number], pivot: Point): [number, number, number] {+ const m = planeMatrix(v, z, pivot);+ const X = x - pivot[0], Y = y - pivot[1];+ return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5], v.sP * Y + v.cP * (-v.sY * X + v.cY * z)];+}++function rootMatrix(pose: Pose, b: Bounds): M {+ const bx = (b.minX + b.maxX) / 2, by = b.maxY;+ const r = (pose.roll * Math.PI) / 180;+ const rot: M = [Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0];+ return mul(translate(0, pose.lift), about(bx, by, mul(rot, [pose.sx, 0, 0, pose.sy, 0, 0])));+}++const pivotOf = (b: Bounds): Point => [(b.minX + b.maxX) / 2, (b.minY + b.maxY) / 2];++/** The hop and the share of a point's distance from the base that roll and squash can move it. */+const POSE_LIFT = 4;+const POSE_SWAY = 0.2;++/**+ * A square of viewBox units that holds the avatar at every view and pose. Throws if invalid. The+ * canvas renderer uses it only as an upper bound: it sizes each bitmap to what is actually painted.+ */+export function avatarExtent(definition: AvatarDefinition, depth?: number): { x: number; y: number; size: number } {+ const p = prepare(definition, depthOption({ depth }));+ const { vol } = p;+ const b = vol.bounds;+ const [cx, cy] = pivotOf(b);+ const radius = Math.hypot(b.maxX - b.minX, b.maxY - b.minY, Math.max(...vol.parts.map((part) => part.depth)) + 2 * EYE_LIFT) / 2;+ // Ribbons reach their hoop plus their band from the middle of the body's box, and keep the+ // canvas's antialiasing margin (FIT_PAD) inside.+ const { work, cage } = p.rims();+ // The hoops' centre also hops and stretches with the body: as far as the body's own pose moves it.+ const reach = (rim: Rim) => {+ const r = ribbonReach(rim.max);+ return Math.hypot(rim.cx - cx, rim.cy - cy) + POSE_LIFT + POSE_SWAY * Math.abs(b.maxY - rim.cy) + r.radius + r.band + 1.2;+ };+ const half = Math.max(radius + POSE_LIFT + POSE_SWAY * (radius + b.maxY - cy), reach(work), reach(cage));+ return { x: cx - half, y: cy - half, size: 2 * half };+}++/**+ * Every cross-section a view draws, with its projection: the stack facing the+ * viewer, minus z-slices hidden behind the core (they add nothing to the+ * silhouette or the paint). Their union is the silhouette on screen.+ */+function drawnSlices(p: Prepared, v: ViewBasis, size: number | undefined, visit: (s: VolumeSlice, m: M, part: number, index: number) => void) {+ const { vol } = p;+ const stack = activeStack(v);+ const pivot = pivotOf(vol.bounds);+ const drawn = sliceCull(v);+ const kept = sliceDetail(p, stack, size);+ let k = 0;+ vol.parts.forEach((part, i) => {+ (stack === 'z' ? part.zSlices : part.xSlices).forEach((s, j) => {+ if (!kept[k++] || !drawn(s)) return;+ visit(s, stack === 'z' ? planeMatrix(v, s.at, pivot) : sidePlaneMatrix(v, s.at, pivot), i, j);+ });+ });+}++/** Whether a slice of the active stack shows: z-slices hidden behind the core are skipped. */+function sliceCull(v: ViewBasis): (s: VolumeSlice) => boolean {+ // Screen shift per unit of depth, and the smallest on-screen size of an in-plane inset.+ const sweep = Math.hypot(v.sY, v.cY * v.sP);+ const inset = Math.min(Math.abs(v.cY), Math.abs(v.cP));+ return (s) => s.axis !== 'z' || s.inset <= 0 || Math.abs(s.at) * sweep > s.inset * inset;+}++// ---------------------------------------------------------------------------+// Eyes (shared by both renderers, in face-plane coordinates)++interface EyeState {+ /** Neutral center and size. */+ x: number;+ y: number;+ w: number;+ h: number;+ /** Gaze offset. */+ dx: number;+ dy: number;+ /** Drawn pill height after blink/squint, and its downward shift (lids close toward a point below center). */+ open: number;+ shift: number;+ look: EyeLook;+ /** The plain pill or the plain happy arc, drawn as such; null for every other look (a path). */+ plain: 'pill' | 'arc' | null;+}++function eyeStates(p: Prepared, pose: Pose): [EyeState, EyeState] {+ const s = p.vol.eyeScale;+ const w = EYE_W * s, h = EYE_H * s;+ const r = p.range;+ const dx = pose.gazeX * (pose.gazeX >= 0 ? r.right : r.left) * GAZE_X * s;+ const dy = pose.gazeY * (pose.gazeY >= 0 ? r.down : r.up) * GAZE_Y * s;+ const centers = eyeCenters(p.def.eyes);+ const plain = plainLook(pose.eyes);+ return ([0, 1] as const).map((i) => {+ const squint = i === 0 ? pose.squintL : pose.squintR;+ const open = Math.max(h * Math.max(0.09, (1 - pose.blink) * (1 - squint * 0.4)), w * 0.55);+ return { x: centers[i][0], y: centers[i][1], w, h, dx, dy, open, shift: (h - open) * 0.18, look: pose.eyes, plain };+ }) as [EyeState, EyeState];+}++/** Where an eye is drawn: with its gaze offset, or without it where a transform applies the gaze. */+function eyeSpot(e: EyeState, gaze: boolean): EyeSpot {+ return { x: e.x + (gaze ? e.dx : 0), y: e.y + (gaze ? e.dy : 0), w: e.w, h: e.h, open: e.open, shift: e.shift };+}++function happyArc(e: EyeState): string {+ const ex = e.x + e.dx, ey = e.y + e.dy;+ const hw = e.w * HAPPY_ARC.halfWidth, base = ey + e.h * HAPPY_ARC.base;+ return `M${f(ex - hw)} ${f(base)}Q${f(ex)} ${f(ey - e.h * HAPPY_ARC.peak)} ${f(ex + hw)} ${f(base)}`;+}++function eyeMark(e: EyeState): EyeMark {+ if (e.plain === 'arc') return { shape: 'arc', d: happyArc(e), strokeWidth: e.w * HAPPY_ARC.stroke };+ if (e.plain === null) return { shape: 'path', d: eyePath(e.look, eyeSpot(e, true)) };+ const cx = e.x + e.dx, cy = e.y + e.dy + e.shift;+ return { shape: 'pill', x: cx - e.w / 2, y: cy - e.open / 2, width: e.w, height: e.open, radius: Math.min(e.w, e.open) / 2 };+}++/**+ * MausBot: a smile under the eyes, stroked like the happy arc. It follows the gaze with the eyes,+ * deepens as the eyes turn happy and flattens as they turn to a waiting slit.+ */+function mouthMark(eyes: [EyeState, EyeState]): EyeMark {+ const [a, b] = eyes;+ const x = (a.x + b.x) / 2 + a.dx, y = a.y + a.h * 0.62 + a.dy;+ const hw = Math.max((b.x - a.x) * 0.3, a.w * 0.7);+ const happy = clamp(a.look.arc, 0, 1), flat = clamp(a.look.slit, 0, 1);+ const depth = hw * (0.42 + 0.38 * happy) * (1 - 0.8 * flat);+ return { shape: 'arc', d: `M${f(x - hw)} ${f(y)}Q${f(x)} ${f(y + 2 * depth)} ${f(x + hw)} ${f(y)}`, strokeWidth: a.w * 0.55 };+}++function colors(options: RenderOptions): { color: string; ink: string } {+ return {+ color: toHex(parseHex(options.color) ?? (parseHex(DEFAULT_COLOR) as Rgb)),+ ink: toHex(parseHex(options.eyeColor) ?? (parseHex(DEFAULT_EYE_COLOR) as Rgb)),+ };+}++// ---------------------------------------------------------------------------+// Flat frames: the whole projected avatar as plain data++/** 2D affine matrix in SVG order (a b c d e f). */+export type Matrix = [number, number, number, number, number, number];++/**+ * How one eye is drawn, in its face plane's coordinates (viewBox units): the plain pill, the+ * plain happy arc (stroked, round caps), or for every other look a filled outline (a waiting+ * bot's slits, and every shape on the way from one look to the next).+ */+export type EyeMark =+ | { shape: 'pill'; x: number; y: number; width: number; height: number; radius: number }+ | { shape: 'arc'; d: string; strokeWidth: number }+ | { shape: 'path'; d: string };++export type FrameShape =+ | {+ kind: 'slice';+ /** Stable across frames for the same cross-section: use it as a key in retained renderers. */+ key: string;+ /** Id of an entry in AvatarFrame.paths. */+ path: string;+ matrix: Matrix;+ }+ | { kind: 'eye'; key: 'eye-0' | 'eye-1' | 'mouth'; matrix: Matrix; mark: EyeMark }+ | {+ /**+ * A piece of a ribbon: fill `d` in `fill`. Each ribbon has a hue of its own, set apart from+ * the body's; a piece `front` of the body is lighter than one behind it.+ */+ kind: 'ribbon';+ key: string;+ d: string;+ box: { x: number; y: number; w: number; h: number };+ matrix: Matrix;+ front: boolean;+ /** The ribbon's colour where it is plainest (the middle of its gradient). */+ fill: string;+ /**+ * A linear gradient along the whole ribbon, in the same coordinates as `d`: from its tail+ * (x1, y1) to its head (x2, y2), the stops evenly spaced. Every piece of a ribbon shares it.+ */+ gradient: { x1: number; y1: number; x2: number; y2: number; stops: string[] };+ };++/** One cross-section outline, shared by every shape that draws it. */+export interface FramePath {+ id: string;+ d: string;+ evenOdd: boolean;+ box: { x: number; y: number; w: number; h: number };+}++/**+ * One frame of the avatar flattened onto the screen: every cross-section the+ * view draws with its projection, and the visible eyes, sorted back to front,+ * between the ribbons behind the body and those in front of it. The marks of+ * `thinking` and `blocked` are listed as slices too, in place of the body.+ * Painting them in order (body paths in `color`, eyes in `ink`) inside the+ * `root` transform and a 0 0 100 100 viewBox gives the avatar exactly as+ * renderAvatarSvg draws it. Plain numbers and path strings, so any vector+ * renderer (SVG, canvas, Skia, react-native-svg) can draw it.+ */+export interface AvatarFrame {+ name: string;+ color: string;+ ink: string;+ /**+ * Distinct cross-section paths this frame uses; ids are stable for equal geometry and depth.+ * `box` bounds `d` in its own coordinates, before a shape's matrix.+ */+ paths: FramePath[];+ /** 2D motion (hop, roll, squash) about the base of the body, applied to every shape. */+ root: Matrix;+ /** Back to front. */+ shapes: FrameShape[];+}++/** Compute one flat frame of a definition. Throws if the definition is invalid. */+export function avatarFrame(definition: AvatarDefinition, options: RenderOptions = {}): AvatarFrame {+ return flatFrame(definition, options, undefined);+}++/**+ * avatarFrame for a live avatar drawn `options.size` CSS pixels wide: like the scene, it skips+ * cross-sections that would sit less than a pixel apart. Internal to the live renderers, so+ * `size` never changes what avatarFrame returns to custom renderers.+ */+export function liveFrame(definition: AvatarDefinition, options: RenderOptions = {}): AvatarFrame {+ return flatFrame(definition, options, options.size);+}++/** The colour `t` (0..1) of the way along a colour run, in sRGB between its stops. */+function runAt(run: Rgb[], t: number): string {+ const x = clamp(t, 0, 1) * (run.length - 1), n = Math.min(Math.floor(x), run.length - 2);+ return toHex(mix(run[n], run[n + 1], x - n));+}++/** MausBot: every ribbon takes one of our comet palettes (three neighbouring hues head to tail), whatever the body's colour. */+const COMET_COLORS: Rgb[][] = [+ ['#A855F7', '#6366F1', '#38BDF8'], ['#22D3EE', '#34D399', '#A3E635'], ['#FB923C', '#F43F5E', '#D946EF'],+ ['#818CF8', '#C084FC', '#F472B6'], ['#FACC15', '#FB923C', '#EC4899'], ['#34D399', '#22D3EE', '#60A5FA'],+].map((run) => run.map((hex) => parseHex(hex) as Rgb));++function cometPalette(seed: number): Rgb[][] {+ const turn = Math.floor(noise(seed, 500) * COMET_COLORS.length);+ return Array.from({ length: 9 }, (_, i) => COMET_COLORS[(i + turn) % COMET_COLORS.length]);+}++/** What a frame draws besides the body, in viewBox units outside the body's own motion. */+interface Effects {+ /** How much of its size the body keeps while it gives way to a mark (0 = gone). */+ body: number;+ ribbons: { d: string; box: Box; front: boolean; fill: string; gradient: RibbonGradient }[];+ marks: { id: string; d: string; box: Box; matrix: M }[];+}++function effectsOf(p: Prepared, pose: Pose, options: RenderOptions): Effects {+ const b = p.vol.bounds;+ const time = Number.isFinite(options.time) ? (options.time as number) : 0;+ const still = options.reducedMotion === true;+ const [cx, cy] = pivotOf(b);+ return {+ body: bodyScale(pose.bang, pose.dots),+ ribbons: still ? [] : ribbonPieces(b, pose.ribbons, p.seed, time, pose.sweep, pose.cage, ribbonsFollow(pose.cage >= 0.5 ? p.rims().cage : p.rims().work, pose, b)).map((r) => {+ const hue = cometPalette(p.seed)[r.ribbon % 9];+ // The piece's stretch of its ribbon's colour run, front and back alike.+ const [s0, s1] = r.along;+ const stops = [s0, (s0 + s1) / 2, s1].map((t) => runAt(hue, t));+ // A gradient needs some length; a piece too short to have one takes its middle colour.+ const long = Math.hypot(r.to[0] - r.from[0], r.to[1] - r.from[1]) > 0.01;+ return {+ d: r.d, box: r.box, front: r.front, fill: stops[1],+ gradient: long ? { x1: r.from[0], y1: r.from[1], x2: r.to[0], y2: r.to[1], stops } : { x1: r.from[0], y1: r.from[1], x2: r.from[0] + 0.01, y2: r.from[1], stops: [stops[1], stops[1], stops[1]] },+ };+ }),+ marks: markParts(b, pose.bang, pose.dots, p.seed, time, still).map((part) => {+ const turn: M = [Math.cos(part.turn), Math.sin(part.turn), -Math.sin(part.turn), Math.cos(part.turn), 0, 0];+ return {+ id: `${p.id}-${part.shape}`,+ d: part.d,+ box: part.box,+ matrix: mul(about(cx, cy, turn), mul(translate(part.x, part.y), [part.scale, 0, 0, part.scale, 0, 0])),+ };+ }),+ };+}++function flatFrame(definition: AvatarDefinition, options: RenderOptions, size: number | undefined): AvatarFrame {+ const p = prepare(definition, depthOption(options));+ const { vol } = p;+ const b = vol.bounds;+ const { color, ink } = colors(options);+ const pose = poseOf(p, options);+ const pivot = pivotOf(b);+ const v = viewBasis(pose.yaw, pose.pitch);+ const stack = activeStack(v);+ const eyesMid: Point = [p.def.eyes.x, p.def.eyes.y];+ const fx = effectsOf(p, pose, options);+ const root = rootMatrix(pose, b);+ // The body shrinks toward its center as it gives way to a mark.+ const shrink = (m: M): M => (fx.body < 1 ? mul(about(pivot[0], pivot[1], [fx.body, 0, 0, fx.body, 0, 0]), m) : m);++ // Only the cross-sections this view draws are listed; ids are stable across frames.+ const paths = new Map<string, FramePath>();+ const items: { depth: number; shape: FrameShape }[] = [];+ if (fx.body > 0) {+ drawnSlices(p, v, size, (s, m, i, j) => {+ let path = paths.get(s.d);+ if (!path) {+ path = { id: p.ids.get(s.d) as string, d: s.d, evenOdd: s.evenOdd, box: { ...s.box } };+ paths.set(s.d, path);+ }+ // Depth keys are taken under the eyes for the eye part, so only depth decides eye-vs-body order there.+ const [rx, ry] = i === vol.eyePart ? eyesMid : vol.parts[i].center;+ const depth = stack === 'z' ? projectPoint(v, [rx, ry, s.at], pivot)[2] : projectPoint(v, [s.at, ry, 0], pivot)[2];+ items.push({ depth, shape: { kind: 'slice', key: `${i}${stack}${j}`, path: path.id, matrix: shrink(m) } });+ });+ // Painted on the surface; each eye goes once the surface under it turns away.+ const eyes = eyeStates(p, pose);+ if (eyeVisible(vol, v, 0) && eyeVisible(vol, v, 1)) {+ const z = (vol.eyeZ[0] + vol.eyeZ[1]) / 2 + EYE_LIFT;+ items.push({+ depth: projectPoint(v, [eyesMid[0], eyesMid[1], z], pivot)[2] + 1e-6,+ shape: { kind: 'eye', key: 'mouth', matrix: shrink(planeMatrix(v, z, pivot)), mark: mouthMark(eyes) },+ });+ }+ eyes.forEach((e, idx) => {+ if (eyeVisible(vol, v, idx)) {+ const z = vol.eyeZ[idx] + EYE_LIFT;+ items.push({+ depth: projectPoint(v, [eyesMid[0], eyesMid[1], z], pivot)[2] + 1e-6,+ shape: { kind: 'eye', key: idx === 0 ? 'eye-0' : 'eye-1', matrix: shrink(planeMatrix(v, z, pivot)), mark: eyeMark(e) },+ });+ }+ });+ items.sort((a, c) => a.depth - c.depth);+ }++ // Ribbons and marks stay put while the body moves: their matrices undo the root's motion.+ const fixed = fx.ribbons.length || fx.marks.length ? invert(root) : null;+ const ribbon = (front: boolean): FrameShape[] =>+ fx.ribbons.flatMap((r, i) =>+ r.front === front ? [{ kind: 'ribbon' as const, key: `ribbon-${i}`, d: r.d, box: r.box, matrix: fixed as M, front, fill: r.fill, gradient: r.gradient }] : [],+ );+ const marks = fx.marks.map((mark, i): FrameShape => {+ if (!paths.has(mark.id)) paths.set(mark.id, { id: mark.id, d: mark.d, evenOdd: false, box: mark.box });+ return { kind: 'slice', key: `mark-${i}`, path: mark.id, matrix: mul(fixed as M, mark.matrix) };+ });+ return {+ name: p.def.name, color, ink, paths: [...paths.values()], root,+ shapes: [...ribbon(false), ...items.map((it) => it.shape), ...ribbon(true), ...marks],+ };+}++// ---------------------------------------------------------------------------+// Standalone SVG still++function eyeSvg(mark: EyeMark, ink: string): string {+ if (mark.shape === 'path') return `<path d="${mark.d}" fill="${ink}"/>`;+ if (mark.shape === 'arc') {+ return `<path d="${mark.d}" fill="none" stroke="${ink}" stroke-width="${f(mark.strokeWidth)}" stroke-linecap="round"/>`;+ }+ return `<rect x="${f(mark.x)}" y="${f(mark.y)}" width="${f(mark.width)}" height="${f(mark.height)}" rx="${f(mark.radius)}" fill="${ink}"/>`;+}++type RibbonGradient = { x1: number; y1: number; x2: number; y2: number; stops: string[] };++/**+ * A ribbon piece with its gradient alongside it. The id is taken from the gradient itself, so+ * repeats on a page (the same avatar at the same moment) share one harmlessly.+ */+function ribbonSvg(d: string, g: RibbonGradient): string {+ const id = `oba-g${hashString(`${f(g.x1)},${f(g.y1)},${f(g.x2)},${f(g.y2)},${g.stops.join()}`).toString(36)}`;+ const stops = g.stops.map((c, i) => `<stop offset="${f(i / (g.stops.length - 1))}" stop-color="${c}"/>`).join('');+ return (+ `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${f(g.x1)}" y1="${f(g.y1)}" x2="${f(g.x2)}" y2="${f(g.y2)}">${stops}</linearGradient>` ++ `<path d="${d}" fill="url(#${id})"/>`+ );+}++/** Render a definition to a standalone SVG string. Throws if the definition is invalid. */+export function renderAvatarSvg(definition: AvatarDefinition, options: RenderOptions = {}): string {+ const frame = avatarFrame(definition, options);+ const defsMarkup = frame.paths.map((d) => `<path id="${d.id}" d="${d.d}"${d.evenOdd ? ' fill-rule="evenodd"' : ''}/>`).join('');+ const body = frame.shapes+ .map((s) =>+ s.kind === 'slice' ? `<use href="#${s.path}" transform="${mat(s.matrix)}"/>`+ : s.kind === 'eye' ? `<g transform="${mat(s.matrix)}">${eyeSvg(s.mark, frame.ink)}</g>`+ : `<g transform="${mat(s.matrix)}">${ribbonSvg(s.d, s.gradient)}</g>`,+ )+ .join('');+ const size = Number.isFinite(options.size) && (options.size as number) > 0 ? f(clamp(options.size as number, 8, 4096)) : null;+ const dims = size ? ` width="${size}" height="${size}"` : '';+ const label = esc(frame.name);++ return (+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"${dims} role="img" aria-label="${label}" overflow="visible">` ++ `<title>${label}</title>` ++ `<defs>${defsMarkup}</defs>` ++ `<g transform="${mat(frame.root)}" fill="${frame.color}">` ++ body ++ `</g></svg>`+ );+}++// ---------------------------------------------------------------------------+// Live CSS 3D scene++/** 1 viewBox unit = 1% of the scene's (square) container width. */+const u = (n: number) => `${f(n)}cqw`;+const FILL = 'position:absolute;left:0;top:0;width:100%;height:100%;';++function sliceMarkup(s: VolumeSlice): string {+ const pad = 0.3;+ const x = s.box.x - pad, y = s.box.y - pad, w = s.box.w + 2 * pad, h = s.box.h + 2 * pad;+ const rule = s.evenOdd ? ' fill-rule="evenodd"' : '';+ const place = s.axis === 'z'+ ? `left:${u(x)};top:${u(y)};transform:translateZ(${u(s.at)})`+ : // The side plane's u = 0 line sits at x = s.at; turning it 90° about that line maps u to -z.+ `left:${u(s.at + x)};top:${u(y)};transform-origin:${u(-x)} 50%;transform:rotateY(90deg)`;+ return (+ `<svg viewBox="${f(x)} ${f(y)} ${f(w)} ${f(h)}" style="position:absolute;width:${u(w)};height:${u(h)};overflow:visible;${place}" aria-hidden="true">` ++ `<path d="${s.d}"${rule} fill="currentColor"/></svg>`+ );+}++const overlay = (side: 'back' | 'front') =>+ `<svg data-fx="${side}" viewBox="0 0 100 100" style="${FILL}overflow:visible;pointer-events:none" fill="currentColor" aria-hidden="true"></svg>`;++/**+ * Static markup of the live scene for a definition and depth. Mount it once,+ * then apply `sceneFrame` every frame. Body color comes from CSS `color` on+ * an ancestor, eye ink from `--avatar-ink`.+ */+export function renderAvatarScene(definition: AvatarDefinition, options: Pick<RenderOptions, 'depth'> = {}): string {+ const p = prepare(definition, depthOption(options));+ const { vol } = p;+ const b = vol.bounds;+ const [cx, cy] = pivotOf(b);+ const ink = `var(--avatar-ink,${DEFAULT_EYE_COLOR})`;+ const stack = (axis: 'z' | 'x') =>+ `<div data-stack="${axis}" style="${FILL}transform-style:preserve-3d">` ++ vol.parts.map((part) => (axis === 'z' ? part.zSlices : part.xSlices).map(sliceMarkup).join('')).join('') ++ `</div>`;+ const eyes = eyeStates(p, poseOf(p, { reducedMotion: true })).map((e, i) => {+ const box = `left:${u(e.x - e.w / 2)};top:${u(e.y - e.h / 2)};width:${u(e.w)};height:${u(e.h)}`;+ return (+ `<div data-eye="${i}" style="position:absolute;${box};backface-visibility:hidden;transform:translateZ(${u(vol.eyeZ[i] + EYE_LIFT)})">` ++ `<i style="position:absolute;inset:0;border-radius:999px;background:${ink}"></i>` ++ `<svg viewBox="${f(e.x - e.w / 2)} ${f(e.y - e.h / 2)} ${f(e.w)} ${f(e.h)}" style="${FILL}overflow:visible;display:none" aria-hidden="true">` ++ `<path d="${happyArc(e)}" fill="none" stroke="${ink}" stroke-width="${f(e.w * HAPPY_ARC.stroke)}" stroke-linecap="round"/></svg>` ++ // Every look between the pill and the arc: its outline is written each frame it changes.+ `<svg data-morph viewBox="${f(e.x - e.w / 2)} ${f(e.y - e.h / 2)} ${f(e.w)} ${f(e.h)}" style="${FILL}overflow:visible;display:none" aria-hidden="true">` ++ `<path fill="${ink}"/></svg>` ++ `</div>`+ );+ });+ return (+ `<div data-avatar-scene="${p.id}" style="position:relative;width:100%;height:100%;container-type:size">` ++ // Ribbons behind the body; they and the marks are written each frame they show.+ overlay('back') ++ // will-change pins the slices' raster scale: without it every hop and squash re-rasterizes each slice.+ `<div data-motion style="${FILL}will-change:transform;transform-origin:${u((b.minX + b.maxX) / 2)} ${u(b.maxY)}">` ++ `<div data-view style="${FILL}transform-style:preserve-3d;transform-origin:${u(cx)} ${u(cy)}">` ++ stack('z') + stack('x') + eyes.join('') ++ `</div></div>` ++ overlay('front') ++ `</div>`+ );+}++export interface SceneFrame {+ /** Identifies the static markup this frame belongs to. */+ scene: string;+ /** 2D motion (hop, roll, squash) about the base of the body. */+ motion: string;+ /** 3D view rotation about the body center, scaled down while the body gives way to a mark. */+ view: string;+ /** How much of its size the body keeps, 0..1; at 0 the view needs no layers. */+ body: number;+ /** Markup for the scene's two overlays (`data-fx`): ribbons behind the body; ribbons and marks in front. */+ back: string;+ front: string;+ stack: 'z' | 'x';+ /** Per slice of the active stack, in markup order: whether it shows. Hidden ones need no layer. */+ slices: boolean[];+ /** `d` is set while the eye is between the pill and the arc: it then shows the `data-morph` path alone. */+ eyes: { visible: boolean; happy: boolean; transform: string; pill: string; d: string }[];+}++const r4 = (n: number) => Math.round(n * 10000) / 10000;++/** Closest on-screen spacing, CSS px, between cross-sections a small live avatar keeps. */+const SLICE_GAP_PX = 0.75;++/**+ * Per slice of a stack, in markup order: whether it is kept at this rendered size. Within each part,+ * slices closer than SLICE_GAP_PX to the last kept one are dropped; the outermost always stay, and+ * so does the core, which sliceCull relies on to cover the inset slices it hides.+ */+function sliceDetail(p: Prepared, stack: 'z' | 'x', size: number | undefined): boolean[] {+ const px = Number.isFinite(size) && (size as number) > 0 ? Math.round(size as number) : 0;+ const key = `${stack}${px}`;+ let keep = p.detail.get(key);+ if (keep) return keep;+ const gap = px ? (SLICE_GAP_PX * 100) / px : 0;+ keep = p.vol.parts.flatMap((part) => {+ const slices = stack === 'z' ? part.zSlices : part.xSlices;+ let last = -Infinity;+ return slices.map((s, j) => {+ const core = s.axis === 'z' && s.at === 0 && s.inset === 0;+ const kept = core || j === 0 || j === slices.length - 1 || s.at - last >= gap;+ if (kept) last = s.at;+ return kept;+ });+ });+ if (p.detail.size >= 32) p.detail.clear();+ p.detail.set(key, keep);+ return keep;+}++/** Per-frame CSS for a mounted scene. Pure and cheap: no geometry is rebuilt. */+export function sceneFrame(definition: AvatarDefinition, options: RenderOptions = {}): SceneFrame {+ const p = prepare(definition, depthOption(options));+ const pose = poseOf(p, options);+ const v = viewBasis(pose.yaw, pose.pitch);+ const states = eyeStates(p, pose);+ const stack = activeStack(v);+ const drawn = sliceCull(v);+ const kept = sliceDetail(p, stack, options.size);+ const fx = effectsOf(p, pose, options);+ const piece = (front: boolean) => fx.ribbons.filter((r) => r.front === front).map((r) => ribbonSvg(r.d, r.gradient)).join('');+ let k = 0;+ return {+ scene: p.id,+ motion: `translate(0,${u(pose.lift)}) rotate(${f(pose.roll)}deg) scale(${r4(pose.sx)},${r4(pose.sy)})`,+ view: (fx.body < 1 ? `scale(${r4(fx.body)}) ` : '') + `rotateX(${r4(pose.pitch)}rad) rotateY(${r4(pose.yaw)}rad)`,+ body: fx.body,+ back: piece(false),+ front: piece(true) + fx.marks.map((mark) => `<path d="${mark.d}" transform="${mat(mark.matrix)}"/>`).join(''),+ stack,+ slices: p.vol.parts.flatMap((part) => (stack === 'z' ? part.zSlices : part.xSlices).map((s) => kept[k++] && drawn(s))),+ eyes: states.map((e, i) => ({+ visible: eyeVisible(p.vol, v, i),+ happy: e.plain === 'arc',+ transform: `translateZ(${u(p.vol.eyeZ[i] + EYE_LIFT)}) translate(${u(e.dx)},${u(e.dy)})`,+ pill: `translateY(${u(e.shift)}) scaleY(${r4(e.open / e.h)})`,+ d: e.plain === null ? eyePath(e.look, eyeSpot(e, false)) : '',+ })),+ };+}diff --git a/packages/phone-protocol/src/open-bot-avatar/types.ts b/packages/phone-protocol/src/open-bot-avatar/types.tsnew file mode 100644index 0000000000..840aed1dd2--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/types.ts@@ -0,0 +1,112 @@+/**+ * Avatar definition contract v1 (see docs/avatar-contract.md).+ *+ * A definition is geometry only: one monochrome silhouette path in a fixed+ * 0 0 100 100 viewBox plus a placement for the eye pair. Everything else+ * (color, implied volume, view, gaze, blinking, motion) is owned by the+ * runtime renderer.+ */++export interface AvatarEyes {+ /** Center of the eye pair, viewBox units. */+ x: number;+ y: number;+ /** Center-to-center distance between the two eyes, viewBox units. */+ spacing: number;+ /** 1 = each neutral eye is ~4 units wide and ~11 units tall. */+ scale: number;+}++export interface AvatarDefinition {+ version: 1;+ /** Lowercase slug, e.g. "controller". */+ id: string;+ /** Human-readable display name. */+ name: string;+ /** One filled path, nonzero fill rule; holes wind opposite to their outline. */+ body: { path: string };+ eyes: AvatarEyes;+}++/**+ * What the bot is doing. `thinking` and `blocked` replace the body with a mark (three dots, an+ * exclamation mark); `working` sweeps a band of ribbons round the body every few seconds; `done`+ * celebrates: it turns a few times with ribbons flying, rests, and after a while does it again.+ */+export type AvatarState = 'idle' | 'thinking' | 'working' | 'waiting' | 'blocked' | 'done';++/** How the bot feels. It shapes the eyes on top of any state; in `idle` a happy bot also hops. */+export type AvatarMood = 'neutral' | 'happy';++/**+ * The single option that came before `state` and `mood`, still accepted: `idle` and `thinking`+ * are states, `happy` is the idle state in a happy mood.+ * @deprecated Use `state` and `mood`.+ */+export type AvatarMotion = 'idle' | 'thinking' | 'happy';++/**+ * A change easing in over what was shown before it: a plain legacy motion, or a state and mood+ * that were themselves still easing in (their progress frozen where it was). `t` 0..1.+ */+export interface AvatarMotionBlend {+ from:+ | AvatarMotion+ | {+ state?: AvatarState;+ mood?: AvatarMood;+ /** @deprecated Use `state` and `mood`. */+ motion?: AvatarMotion;+ /** Seconds that state had been showing when the change began (see RenderOptions.stateAge). */+ age?: number;+ blend?: AvatarMotionBlend;+ };+ t: number;+}++export interface RenderOptions {+ /** Body color as #rgb or #rrggbb. Invalid values fall back to the default. */+ color?: string;+ /** Eye color as #rgb or #rrggbb. Defaults to a plain near-black ink. */+ eyeColor?: string;+ /**+ * Rendered width/height in CSS pixels. Omit for a fluid SVG. In sceneFrame it lets small+ * live avatars skip cross-sections that would sit less than a pixel apart.+ */+ size?: number;+ /** Volume amount 0..14 (default 6 = natural depth; 0 = flat). Scales every part's inferred depth. */+ depth?: number;+ /** Extra view rotation in radians on top of the resting view (drag-to-turn). yaw turns left/right, pitch tips. */+ view?: { yaw: number; pitch: number };+ /** Animation clock in seconds. Same inputs always produce the same SVG. */+ time?: number;+ /**+ * Look target, each axis normalized -1..1 (x right, y down). Overrides idle eye+ * wander and turns the body toward it; `weight` (0..1, default 1) blends it in+ * over the idle pose so following can start and stop without a jump.+ */+ gaze?: { x: number; y: number; weight?: number };+ /** What the bot is doing (default `idle`). */+ state?: AvatarState;+ /** How the bot feels (default `neutral`). */+ mood?: AvatarMood;+ /** @deprecated Use `state` and `mood`; they win when given. */+ motion?: AvatarMotion;+ /**+ * Seconds since `state` began. `done` celebrates from the moment it begins, so hosts that+ * animate pass this (createAnimator returns it); without it the state is drawn at rest.+ */+ stateAge?: number;+ /**+ * Ease into `state` and `mood` from what was shown before: the pose blends between the two+ * and the eyes morph from one shape to the other. Hosts leave it out once `t` reaches 1 (and+ * under reduced motion).+ */+ motionBlend?: AvatarMotionBlend;+ /** Freeze body motion, blinking, ribbons and marks at a calm pose; gaze still applies. */+ reducedMotion?: boolean;+}++export type ValidationResult =+ | { ok: true; value: AvatarDefinition }+ | { ok: false; errors: string[] };diff --git a/packages/phone-protocol/src/open-bot-avatar/validate.ts b/packages/phone-protocol/src/open-bot-avatar/validate.tsnew file mode 100644index 0000000000..fa79574e06--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/validate.ts@@ -0,0 +1,282 @@+import { bounds, filledArea, flattenPath, insideRow, isInside, parsePath, PathError, serializePath, splitSubpaths } from './path.ts';+import type { Bounds, Point } from './path.ts';+import type { AvatarEyes, ValidationResult } from './types.ts';++/** Neutral eye size at scale 1, viewBox units. */+export const EYE_W = 4;+export const EYE_H = 11;+/** Hard limits; the contract's soft target for the body is 8..92. */+export const BODY_MIN = 6;+export const BODY_MAX = 94;+const EYE_MARGIN = 1.2;+/**+ * Max gaze travel of the eyes inside the face at scale 1. Deliberately small:+ * a subtle shift reads as looking around, and the enlarged eyes stay well+ * inside the face instead of sliding toward its edge.+ */+export const GAZE_X = 1.5;+export const GAZE_Y = 1.1;+/**+ * Happy-eye arc, as fractions of the drawn eye size (w = width, h = height):+ * a quadratic from (x ∓ halfWidth·w, y + base·h) through the control point+ * (x, y − peak·h), stroked `stroke`·w wide with round caps.+ */+export const HAPPY_ARC = { halfWidth: 0.72, base: 0.1, peak: 0.42, stroke: 0.6 } as const;+/** Gap the renderer keeps between every drawn eye shape and the outline while the eyes look around. */+export const EYE_CLEARANCE = 1.5;++const TOP_KEYS = ['version', 'id', 'name', 'body', 'eyes'];+const EYE_KEYS = ['x', 'y', 'spacing', 'scale'];++export interface BodyHole {+ /** The hole's own subpath, serialized. */+ d: string;+ /** Approximate cut-out area, units². */+ area: number;+}++export interface BodySubpath {+ /** The subpath, serialized. */+ d: string;+ /** Its own flattened polygon(s). */+ polys: Point[][];+ /** True when the subpath cuts a hole rather than adding fill. */+ hole: boolean;+ /** A point inside the subpath's own fill (for holes: inside the cut-out). */+ probe: Point | null;+}++export interface BodyAnalysis {+ polys: Point[][];+ bounds: Bounds;+ area: number;+ holes: BodyHole[];+ subpaths: BodySubpath[];+}++/** Holes up to this area count as small details (buttons, sockets). The renderer cuts every hole through. */+export const RECESS_MAX_AREA = 110;++export interface GazeRange { left: number; right: number; up: number; down: number }++function isRecord(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v);+}++function num(v: unknown): v is number {+ return typeof v === 'number' && Number.isFinite(v);+}++/** Points on the outline of an eye pill expanded by `margin`. */+function eyeOutline(cx: number, cy: number, scale: number, margin: number): Point[] {+ const hw = (EYE_W * scale) / 2 + margin;+ const hh = (EYE_H * scale) / 2 + margin;+ const pts: Point[] = [];+ const straight = hh - hw; // half-length of the straight flank+ for (let k = 0; k < 16; k++) {+ const a = (k / 16) * Math.PI * 2;+ const x = Math.cos(a) * hw;+ const y = Math.sin(a) * hw + Math.sign(Math.sin(a)) * Math.max(0, straight);+ pts.push([cx + x, cy + y]);+ }+ for (const f of [-0.5, 0, 0.5]) {+ pts.push([cx - hw, cy + f * straight], [cx + hw, cy + f * straight]);+ }+ pts.push([cx, cy]);+ return pts;+}++/** Outline points of every shape the renderer may draw for one eye (pill and happy arc), expanded by `margin`. */+function drawnEyeOutline(cx: number, cy: number, scale: number, margin: number): Point[] {+ const pts = eyeOutline(cx, cy, scale, margin);+ const w = EYE_W * scale, h = EYE_H * scale;+ const x0 = cx - HAPPY_ARC.halfWidth * w, x1 = cx + HAPPY_ARC.halfWidth * w;+ const yb = cy + HAPPY_ARC.base * h, yc = cy - HAPPY_ARC.peak * h;+ const r = (HAPPY_ARC.stroke * w) / 2 + margin;+ for (let i = 0; i <= 8; i++) {+ const t = i / 8, m = 1 - t;+ const x = m * m * x0 + 2 * m * t * cx + t * t * x1;+ const y = (m * m + t * t) * yb + 2 * m * t * yc;+ for (let k = 0; k < 8; k++) {+ const a = (k / 8) * Math.PI * 2;+ pts.push([x + Math.cos(a) * r, y + Math.sin(a) * r]);+ }+ }+ return pts;+}++export function eyeCenters(eyes: AvatarEyes): [Point, Point] {+ return [[eyes.x - eyes.spacing / 2, eyes.y], [eyes.x + eyes.spacing / 2, eyes.y]];+}++export function eyesFit(polys: Point[][], eyes: AvatarEyes, dx: number, dy: number, margin: number): Point | null {+ for (const [cx, cy] of eyeCenters(eyes)) {+ for (const [x, y] of eyeOutline(cx + dx, cy + dy, eyes.scale, margin)) {+ if (!isInside(polys, x, y)) return [x, y];+ }+ }+ return null;+}++/** Like eyesFit, but for everything the renderer draws: the pill and the wider happy arc. */+export function drawnEyesFit(polys: Point[][], eyes: AvatarEyes, dx: number, dy: number, margin: number): Point | null {+ for (const [cx, cy] of eyeCenters(eyes)) {+ for (const [x, y] of drawnEyeOutline(cx + dx, cy + dy, eyes.scale, margin)) {+ if (!isInside(polys, x, y)) return [x, y];+ }+ }+ return null;+}++/** Largest gap (viewBox units, to 0.1) between the drawn eyes at rest and the outline; 0 when they touch it. */+export function eyeClearance(polys: Point[][], eyes: AvatarEyes): number {+ if (drawnEyesFit(polys, eyes, 0, 0, 0)) return 0;+ let lo = 0, hi = 20;+ while (hi - lo > 0.05) {+ const mid = (lo + hi) / 2;+ if (drawnEyesFit(polys, eyes, 0, 0, mid)) hi = mid;+ else lo = mid;+ }+ return Math.floor(lo * 10) / 10;+}++/**+ * How far (0..1 of GAZE_X/GAZE_Y) the drawn eyes can travel each way and keep+ * EYE_CLEARANCE from the outline.+ */+export function gazeRange(polys: Point[][], eyes: AvatarEyes): GazeRange {+ const reach = (ux: number, uy: number) => {+ for (const k of [1, 0.8, 0.6, 0.4, 0.2]) {+ if (!drawnEyesFit(polys, eyes, ux * k * GAZE_X * eyes.scale, uy * k * GAZE_Y * eyes.scale, EYE_CLEARANCE)) return k;+ }+ return 0;+ };+ return { left: reach(-1, 0), right: reach(1, 0), up: reach(0, -1), down: reach(0, 1) };+}++export function analyzeBody(path: string): BodyAnalysis {+ const segs = parsePath(path);+ const polys = flattenPath(segs);+ const b = bounds(polys);+ const holes: BodyHole[] = [];+ const subpaths: BodySubpath[] = [];+ for (const sub of splitSubpaths(segs)) {+ const own = flattenPath(sub);+ if (!own.length) continue;+ const ob = bounds(own);+ let inside = 0, cut = 0;+ let probe: Point | null = null, cutProbe: Point | null = null;+ // Small subpaths (buttons, sockets) need a fine grid; big ones classify fine on a coarser one.+ const step = (ob.maxX - ob.minX) * (ob.maxY - ob.minY) < 900 ? 0.5 : 1;+ const alone = own.length === polys.length;+ const xs: number[] = [];+ for (let x = Math.floor(ob.minX) + step / 2; x < ob.maxX; x += step) xs.push(x);+ const mine = new Uint8Array(xs.length), all = new Uint8Array(xs.length);+ for (let y = Math.floor(ob.minY) + step / 2; y < ob.maxY; y += step) {+ insideRow(own, y, xs, mine);+ if (!alone) insideRow(polys, y, xs, all);+ for (let k = 0; k < xs.length; k++) {+ if (!mine[k]) continue;+ inside++;+ probe ??= [xs[k], y];+ if (!alone && !all[k]) { cut++; cutProbe ??= [xs[k], y]; }+ }+ }+ cut *= step * step * 4;+ inside *= step * step * 4;+ const d = serializePath(sub);+ // A subpath that is mostly empty under the full fill rule is a cut-out.+ const hole = inside > 0 && cut / inside > 0.6;+ if (hole) holes.push({ d, area: Math.round(cut / 4) });+ subpaths.push({ d, polys: own, hole, probe: hole ? cutProbe : probe });+ }+ return { polys, bounds: b, area: filledArea(polys, b), holes, subpaths };+}++const r1 = (n: number) => Math.round(n * 10) / 10;++export function validateAvatar(input: unknown): ValidationResult {+ const errors: string[] = [];+ if (!isRecord(input)) return { ok: false, errors: ['definition must be a JSON object'] };++ for (const k of Object.keys(input)) if (!TOP_KEYS.includes(k)) errors.push(`unknown field "${k}" (allowed: ${TOP_KEYS.join(', ')})`);+ if (input.version !== 1) errors.push('version must be 1');++ const id = input.id;+ if (typeof id !== 'string' || !/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/.test(id)) {+ errors.push('id must be a lowercase slug of 1-40 chars [a-z0-9-]');+ }+ const name = typeof input.name === 'string' ? input.name.trim() : '';+ if (!name || name.length > 40 || /[\u0000-\u001f<>]/.test(name)) {+ errors.push('name must be 1-40 printable characters without < or >');+ }++ let path: string | null = null;+ if (!isRecord(input.body)) errors.push('body must be an object { "path": "..." }');+ else {+ for (const k of Object.keys(input.body)) if (k !== 'path') errors.push(`unknown field "body.${k}" (only "path" is allowed)`);+ if (typeof input.body.path !== 'string') errors.push('body.path must be a string');+ else path = input.body.path;+ }++ let eyes: AvatarEyes | null = null;+ if (!isRecord(input.eyes)) errors.push('eyes must be an object { x, y, spacing, scale }');+ else {+ const e = input.eyes;+ for (const k of Object.keys(e)) if (!EYE_KEYS.includes(k)) errors.push(`unknown field "eyes.${k}" (allowed: ${EYE_KEYS.join(', ')})`);+ const bad = EYE_KEYS.filter((k) => !num(e[k]));+ if (bad.length) errors.push(`eyes.${bad.join(', eyes.')} must be finite numbers`);+ else {+ eyes = { x: e.x as number, y: e.y as number, spacing: e.spacing as number, scale: e.scale as number };+ if (eyes.scale < 0.6 || eyes.scale > 1.8) errors.push(`eyes.scale ${eyes.scale} out of range 0.6..1.8`);+ const minSpacing = EYE_W * eyes.scale * 1.75;+ if (eyes.spacing < minSpacing || eyes.spacing > 40) {+ errors.push(`eyes.spacing ${eyes.spacing} out of range ${r1(minSpacing)}..40 for scale ${eyes.scale}`);+ }+ }+ }++ let normalized = '';+ let body: BodyAnalysis | null = null;+ if (path !== null) {+ try {+ const segs = parsePath(path);+ normalized = serializePath(segs);+ body = analyzeBody(normalized);+ } catch (err) {+ if (err instanceof PathError) errors.push(`body.path: ${err.message}`);+ else throw err;+ }+ }++ if (body) {+ const b = body.bounds;+ const out: string[] = [];+ if (b.minX < BODY_MIN) out.push(`left edge x=${r1(b.minX)}`);+ if (b.minY < BODY_MIN) out.push(`top edge y=${r1(b.minY)}`);+ if (b.maxX > BODY_MAX) out.push(`right edge x=${r1(b.maxX)}`);+ if (b.maxY > BODY_MAX) out.push(`bottom edge y=${r1(b.maxY)}`);+ if (out.length) errors.push(`body.path leaves the safe area (${out.join(', ')}); keep geometry within 8..92`);+ const w = b.maxX - b.minX, h = b.maxY - b.minY;+ if (Math.max(w, h) < 40 || Math.min(w, h) < 14) {+ errors.push(`body is too small (${r1(w)}x${r1(h)}); use at least 40 units on the long side and 14 on the short side`);+ }+ if (body.area < 600) errors.push(`body fill area ${body.area} is too thin to carry eyes; must be at least 600 units²`);++ if (eyes) {+ const miss = eyesFit(body.polys, eyes, 0, 0, EYE_MARGIN);+ if (miss) {+ errors.push(+ `eyes must sit inside the body with ${EYE_MARGIN} units margin; point (${r1(miss[0])}, ${r1(miss[1])}) is outside or in a hole. ` ++ 'Move eyes.x/y toward the widest solid area, reduce spacing or scale.',+ );+ }+ }+ }++ if (errors.length || !eyes) return { ok: false, errors };+ return {+ ok: true,+ value: { version: 1, id: id as string, name, body: { path: normalized }, eyes: { ...eyes } },+ };+}diff --git a/packages/phone-protocol/src/open-bot-avatar/volume.ts b/packages/phone-protocol/src/open-bot-avatar/volume.tsnew file mode 100644index 0000000000..6784e19729--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/volume.ts@@ -0,0 +1,669 @@+/**+ * Implied volume for a flat silhouette.+ *+ * The definition stays a 2D path. Here every filled subpath becomes a "part"+ * with a front-surface height field h(x, y) (the back mirrors it about z = 0):+ *+ * - inflate: a rounded slab. Height follows an elliptical edge fillet of the+ * distance to the outline, so sides curve and the face is flat.+ * - revolve-y: a solid of revolution about the part's vertical center line+ * (mug body, pot, bulb), taken from exact scanline widths.+ * - revolve-x: a solid of revolution about a horizontal axis shared by the+ * whole body (barbell: bar → cylinder, plates → discs).+ *+ * From the height field the part is cut, once, into two stacks of plain+ * cross-section paths: z-slices (planes facing the viewer, level sets of h)+ * and x-slices (planes facing sideways, column profiles of h). Rendered in a+ * single flat color, the union of a stack is the silhouette of the solid;+ * the renderer shows whichever stack faces the viewer more, so no plane is+ * ever seen edge-on. Everything here is pure and cached by the renderer.+ */+import { contourLoops, loopsToPath, simplifyLoop } from './contour.ts';+import { bounds, insideRow, isInside } from './path.ts';+import type { Bounds, Point } from './path.ts';+import { EYE_H, EYE_W, GAZE_X, GAZE_Y, analyzeBody, drawnEyesFit, eyeCenters, eyeClearance, gazeRange } from './validate.ts';+import type { BodyAnalysis, GazeRange } from './validate.ts';+import type { AvatarDefinition, AvatarEyes } from './types.ts';++export type PartKind = 'inflate' | 'revolve-x' | 'revolve-y';++export interface VolumeSlice {+ /** 'z': the plane z = at, path in (x, y). 'x': the plane x = at, path in (u = -z, y). */+ axis: 'z' | 'x';+ at: number;+ d: string;+ /** The same cross-section as polygons in its plane's coordinates (`d` is a rounded serialization of them). */+ loops: Point[][];+ /** Contour paths use evenodd; the core slice reuses the original nonzero outline. */+ evenOdd: boolean;+ /** Path bounds in its plane's coordinates. */+ box: { x: number; y: number; w: number; h: number };+ /** z-slices: smallest distance from this cross-section to the outline (0 for the core and walls). */+ inset: number;+}++export interface VolumePart {+ kind: PartKind;+ /** Outline plus the holes that cut it, serialized. */+ d: string;+ polys: Point[][];+ bounds: Bounds;+ center: Point;+ /** Twice the largest inscribed radius (inflate) or the largest diameter (revolved). */+ thickness: number;+ /** Front-to-back extent, centered on z = 0. */+ depth: number;+ /** Inflate only: elliptical edge fillet radii (in-plane and in depth). */+ rxy: number;+ rz: number;+ /** Revolved parts: the axis (y for revolve-x, x for revolve-y). */+ axis?: number;+ zSlices: VolumeSlice[];+ xSlices: VolumeSlice[];+ /** Front surface height at a point, 0 outside the part. */+ height: (x: number, y: number) => number;+}++export interface Volume {+ parts: VolumePart[];+ bounds: Bounds;+ /** Index of the part carrying the eyes. */+ eyePart: number;+ /** Depth of each eye's plane: the highest surface under the eye and its gaze travel. */+ eyeZ: [number, number];+ /** Drawn eye scale: the definition's scale enlarged as far as the body allows (see EYE_BOOST). */+ eyeScale: number;+ /**+ * Host surface normals under each eye (left edge, center, right edge). On a+ * curved host an eye is hidden once any of them turns away, so a flat eye+ * never hangs past the curved silhouette.+ */+ eyeNormals: [Vec3[], Vec3[]];+}++export type Vec3 = [number, number, number];++/** Largest depth an inflated part may take, viewBox units. */+export const MAX_PART_DEPTH = 30;+/** Drawn eyes are up to this much larger than the contract's 4 × 11 pill when the body has room. */+export const EYE_BOOST = 1.45;+/**+ * Gap every drawn eye shape (pill and happy arc) keeps from the outline at rest+ * before the renderer enlarges it, viewBox units. Below this the eyes stay at+ * the definition's own scale.+ */+export const EYE_BOOST_PAD = 3;+/**+ * Design target for generated avatars: the enlarged eyes keep this much+ * clearance at rest, which also leaves full gaze travel with EYE_CLEARANCE.+ * Advisory (validate.sh --strict); v1 imports below it still render.+ */+export const FACE_ROOM_TARGET = 4.5;+const MAX_X_SLICES = 40;+/**+ * Thin regions get refinement slices (see thinBoxes): where no inscribed circle+ * within THIN_REACH units has a radius of THIN or more. A thin, deep protrusion+ * seen at an angle shifts more between neighboring slices than it is wide, so+ * without them it fans out into separate copies.+ */+const THIN = 4;+const THIN_REACH = 5;+/** How far a refinement box reaches past its thin region into the body, units. */+const THIN_MARGIN = 2;+/** Depth spacing of refinement slices, units. */+const FINE_Z = 0.6;++function segDist2(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {+ const dx = bx - ax, dy = by - ay;+ const len = dx * dx + dy * dy;+ let t = len > 0 ? ((px - ax) * dx + (py - ay) * dy) / len : 0;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ const ex = ax + t * dx - px, ey = ay + t * dy - py;+ return ex * ex + ey * ey;+}++function segDist(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {+ return Math.sqrt(segDist2(px, py, ax, ay, bx, by));+}++/** Distance from a point to the nearest edge of the polygons. */+export function edgeDistance(polys: Point[][], x: number, y: number): number {+ let best = Infinity;+ for (const poly of polys) {+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {+ const d = segDist(x, y, poly[j][0], poly[j][1], poly[i][0], poly[i][1]);+ if (d < best) best = d;+ }+ }+ return best;+}++/** Inward distance to the outline, or 0 outside the fill. */+export function insideDistance(polys: Point[][], x: number, y: number): number {+ return isInside(polys, x, y) ? edgeDistance(polys, x, y) : 0;+}++/** Outline erosion of an inflated part at depth z (elliptical fillet). */+export function erosionAt(part: Pick<VolumePart, 'depth' | 'rxy' | 'rz'>, z: number): number {+ const half = part.depth / 2;+ if (part.rz <= 0) return 0;+ const u = (Math.abs(z) - (half - part.rz)) / part.rz;+ if (u <= 0) return 0;+ return part.rxy * (1 - Math.sqrt(Math.max(0, 1 - Math.min(1, u) ** 2)));+}++/** How far inside the outline an inflated part's surface reaches `level` (inverse of surfaceZ). */+export function insetAt(part: Pick<VolumePart, 'depth' | 'rxy' | 'rz'>, level: number): number {+ const half = part.depth / 2;+ if (part.rxy <= 0 || part.rz <= 0 || level <= half - part.rz) return 0;+ if (level >= half) return part.rxy;+ const s = (level - (half - part.rz)) / part.rz;+ return part.rxy * (1 - Math.sqrt(Math.max(0, 1 - s * s)));+}++/** Front surface depth of an inflated part at a point `dist` units inside the outline. */+export function surfaceZ(part: Pick<VolumePart, 'depth' | 'rxy' | 'rz'>, dist: number): number {+ const half = part.depth / 2;+ if (part.rxy <= 0 || dist >= part.rxy) return half;+ const k = 1 - Math.max(0, dist) / part.rxy;+ return half - part.rz + Math.sqrt(Math.max(0, 1 - k * k)) * part.rz;+}++/**+ * Depth heuristic for inflated parts: as deep as the part is thick, but tall+ * slender parts get up to 2.4x their thickness so they read as discs.+ */+export function partDepth(thickness: number, b: Bounds, volume: number): number {+ const long = Math.max(b.maxX - b.minX, b.maxY - b.minY);+ const raw = 0.8 * Math.max(thickness, Math.min(0.4 * long, 2.4 * thickness));+ return Math.min(MAX_PART_DEPTH, Math.max(3, raw)) * volume;+}++/** Sorted crossings of the line (y = s if `rows`, else x = s) with the polygons. */+function crossings(polys: Point[][], rows: boolean, s: number): number[] {+ const out: number[] = [];+ const a = rows ? 1 : 0, b = rows ? 0 : 1;+ for (const poly of polys) {+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {+ const p = poly[j], q = poly[i];+ if ((p[a] <= s && q[a] > s) || (q[a] <= s && p[a] > s)) out.push(p[b] + ((s - p[a]) * (q[b] - p[b])) / (q[a] - p[a]));+ }+ }+ return out.sort((m, n) => m - n);+}++interface Profile { start: number; step: number; r: Float64Array }++/**+ * Half-widths about `center` along rows (or columns) if every line crosses the+ * part as one interval centered on it; otherwise null (not a solid of revolution).+ */+function revolveProfile(polys: Point[][], rows: boolean, lo: number, hi: number, center: number): Profile | null {+ const step = 0.2;+ const n = Math.max(2, Math.ceil((hi - lo) / step) + 1);+ const r = new Float64Array(n);+ let span = 0;+ const mids: number[] = [];+ for (let k = 0; k < n; k++) {+ const s = Math.min(hi - 0.01, Math.max(lo + 0.01, lo + k * step));+ const xs = crossings(polys, rows, s);+ if (xs.length === 0) continue;+ if (xs.length !== 2) return null;+ r[k] = (xs[1] - xs[0]) / 2;+ span = Math.max(span, xs[1] - xs[0]);+ mids.push((xs[0] + xs[1]) / 2);+ }+ const tol = Math.max(0.8, 0.04 * span);+ if (!mids.length || mids.some((m) => Math.abs(m - center) > tol)) return null;+ return { start: lo, step, r };+}++function radiusAt(p: Profile, s: number): number {+ const t = (s - p.start) / p.step;+ if (t < 0 || t > p.r.length - 1) return 0;+ const k = Math.min(p.r.length - 2, Math.floor(t));+ return p.r[k] + (p.r[k + 1] - p.r[k]) * (t - k);+}++/**+ * Horizontal axis of revolution, if the body looks like a turned object seen+ * from the side: at least two parts, wider than tall, mirror-symmetric about+ * y = axis and with every part centered on it.+ */+export function revolveAxis(body: BodyAnalysis): number | null {+ const b = body.bounds;+ const outlines = body.subpaths.filter((s) => !s.hole);+ if (outlines.length < 2 || b.maxX - b.minX < 1.1 * (b.maxY - b.minY)) return null;+ const axis = (b.minY + b.maxY) / 2;+ for (const o of outlines) {+ const ob = bounds(o.polys);+ if (Math.abs((ob.minY + ob.maxY) / 2 - axis) > 1.5) return null;+ }+ let filled = 0, off = 0;+ const xs: number[] = [];+ for (let x = b.minX + 0.5; x < b.maxX; x += 1) xs.push(x);+ const top = new Uint8Array(xs.length), bottom = new Uint8Array(xs.length);+ for (let y = b.minY + 0.5; y < axis; y += 1) {+ insideRow(body.polys, y, xs, top);+ insideRow(body.polys, 2 * axis - y, xs, bottom);+ for (let k = 0; k < xs.length; k++) {+ if (top[k] || bottom[k]) filled++;+ if (top[k] !== bottom[k]) off++;+ }+ }+ return filled > 0 && off / filled < 0.02 ? axis : null;+}++/** Sampled signed distance (positive inside) and height over a part's bounds. */+interface Grid { x0: number; y0: number; step: number; nx: number; ny: number; sd: Float64Array; h: Float64Array }++/** Edges bucketed on a coarse grid, for nearest-edge queries that only visit nearby buckets. */+class EdgeIndex {+ private readonly cell = 6;+ private readonly buckets = new Map<number, number[]>();+ private readonly e: number[] = [];+ private readonly ox: number;+ private readonly oy: number;+ private readonly span: number;++ constructor(polys: Point[][], b: Bounds) {+ this.ox = b.minX - 4; this.oy = b.minY - 4;+ this.span = Math.ceil((Math.max(b.maxX - b.minX, b.maxY - b.minY) + 8) / this.cell) + 1;+ for (const poly of polys) {+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {+ const k = this.e.length;+ this.e.push(poly[j][0], poly[j][1], poly[i][0], poly[i][1]);+ const [x0, x1] = [Math.min(poly[j][0], poly[i][0]), Math.max(poly[j][0], poly[i][0])];+ const [y0, y1] = [Math.min(poly[j][1], poly[i][1]), Math.max(poly[j][1], poly[i][1])];+ for (let cy = this.cy(y0); cy <= this.cy(y1); cy++) {+ for (let cx = this.cx(x0); cx <= this.cx(x1); cx++) {+ const key = cy * this.span + cx;+ (this.buckets.get(key) ?? this.buckets.set(key, []).get(key)!).push(k);+ }+ }+ }+ }+ }++ private cx(x: number) { return Math.max(0, Math.min(this.span - 1, Math.floor((x - this.ox) / this.cell))); }+ private cy(y: number) { return Math.max(0, Math.min(this.span - 1, Math.floor((y - this.oy) / this.cell))); }++ /** Distance to the nearest edge, searching rings of buckets outward until no closer edge can exist. */+ distance(x: number, y: number): number {+ const bx = this.cx(x), by = this.cy(y);+ let best = Infinity;+ const e = this.e;+ for (let r = 0; r < this.span; r++) {+ for (let cy = by - r; cy <= by + r; cy++) {+ if (cy < 0 || cy >= this.span) continue;+ const edgeRow = cy === by - r || cy === by + r;+ for (let cx = bx - r; cx <= bx + r; cx += edgeRow ? 1 : 2 * r || 1) {+ if (cx < 0 || cx >= this.span) continue;+ const list = this.buckets.get(cy * this.span + cx);+ if (!list) continue;+ for (const k of list) {+ const d = segDist2(x, y, e[k], e[k + 1], e[k + 2], e[k + 3]);+ if (d < best) best = d;+ }+ }+ }+ // Every bucket outside ring r is at least r cells away (best is squared).+ if (best <= (r * this.cell) ** 2) break;+ }+ return Math.sqrt(best);+ }+}++function sampleGrid(polys: Point[][], b: Bounds, step: number, height: (x: number, y: number, sd: number) => number): Grid {+ const pad = 1;+ const x0 = b.minX - pad, y0 = b.minY - pad;+ const nx = Math.ceil((b.maxX - b.minX + 2 * pad) / step) + 1;+ const ny = Math.ceil((b.maxY - b.minY + 2 * pad) / step) + 1;+ const sd = new Float64Array(nx * ny), h = new Float64Array(nx * ny);+ const index = new EdgeIndex(polys, b);+ const xs = Array.from({ length: nx }, (_, i) => x0 + i * step);+ const inside = new Uint8Array(nx);+ for (let j = 0; j < ny; j++) {+ const y = y0 + j * step;+ insideRow(polys, y, xs, inside);+ for (let i = 0; i < nx; i++) {+ const d = index.distance(xs[i], y);+ sd[j * nx + i] = inside[i] ? d : -d;+ h[j * nx + i] = inside[i] ? height(xs[i], y, d) : 0;+ }+ }+ return { x0, y0, step, nx, ny, sd, h };+}++function loopBox(loops: Point[][]): VolumeSlice['box'] {+ const b = bounds(loops);+ return { x: b.minX, y: b.minY, w: b.maxX - b.minX, h: b.maxY - b.minY };+}++/** A rectangle of grid samples, inclusive. */+interface CellBox { i0: number; i1: number; j0: number; j1: number }++/** A thin region's box, and the highest surface over the thin samples themselves. */+interface ThinBox extends CellBox { top: number }++/**+ * A part's cross-section at `level` as a field that is positive inside it, zero on its edge and+ * roughly a distance in viewBox units: smooth across the rim, so contours interpolated between grid+ * samples follow the real edge instead of the grid. (Height itself is steep at the rim and zero+ * outside, and contouring it left the outline faceted and stair-stepped.)+ */+type LevelField = (x: number, y: number, sd: number, level: number) => number;++/** Cross-section at `level` clipped to the outline (and to `box`, if given), as loops. */+function levelLoops(g: Grid, level: number, field: LevelField, box?: CellBox): Point[][] {+ // A box is contoured on its own samples plus one ring outside it, where the clip is negative.+ const i0 = box ? Math.max(0, box.i0 - 1) : 0, i1 = box ? Math.min(g.nx - 1, box.i1 + 1) : g.nx - 1;+ const j0 = box ? Math.max(0, box.j0 - 1) : 0, j1 = box ? Math.min(g.ny - 1, box.j1 + 1) : g.ny - 1;+ const nx = i1 - i0 + 1, ny = j1 - j0 + 1;+ const values = new Float64Array(nx * ny);+ for (let j = 0; j < ny; j++) {+ for (let i = 0; i < nx; i++) {+ const k = (j + j0) * g.nx + i + i0;+ const sd = g.sd[k];+ // Both terms are continuous across the outline, so the min is too.+ let v = Math.min(field(g.x0 + (i + i0) * g.step, g.y0 + (j + j0) * g.step, sd, level), sd);+ if (box) v = Math.min(v, g.step * Math.min(i + i0 - box.i0, box.i1 - i - i0, j + j0 - box.j0, box.j1 - j - j0));+ values[j * nx + i] = v;+ }+ }+ return contourLoops({ values, nx, ny, x0: g.x0 + i0 * g.step, y0: g.y0 + j0 * g.step, step: g.step }, 0)+ .map((l) => simplifyLoop(l, 0.04))+ .filter((l) => l.length >= 3);+}++/**+ * Boxes around the thin parts of a part's outline, grown by THIN_MARGIN and+ * merged where they overlap, in grid samples. Thin means the widest inscribed+ * circle within THIN_REACH has a radius under THIN (a speech bubble's tail, a+ * leaf, a handle ring).+ */+function thinBoxes(g: Grid): ThinBox[] {+ const { nx, ny } = g;+ const reach = Math.ceil(THIN_REACH / g.step);+ // Largest inward distance within `reach` samples (a square window, rows then columns).+ const rows = new Float64Array(nx * ny), widest = new Float64Array(nx * ny);+ for (let j = 0; j < ny; j++) {+ for (let i = 0; i < nx; i++) {+ let m = 0;+ for (let k = Math.max(0, i - reach), e = Math.min(nx - 1, i + reach); k <= e; k++) m = Math.max(m, g.sd[j * nx + k]);+ rows[j * nx + i] = m;+ }+ }+ for (let i = 0; i < nx; i++) {+ for (let j = 0; j < ny; j++) {+ let m = 0;+ for (let k = Math.max(0, j - reach), e = Math.min(ny - 1, j + reach); k <= e; k++) m = Math.max(m, rows[k * nx + i]);+ widest[j * nx + i] = m;+ }+ }+ const thin = (k: number) => g.sd[k] > 0 && widest[k] < THIN;+ const seen = new Uint8Array(nx * ny);+ const grow = Math.ceil(THIN_MARGIN / g.step);+ const boxes: ThinBox[] = [];+ for (let start = 0; start < nx * ny; start++) {+ if (seen[start] || !thin(start)) continue;+ const box = { i0: nx, i1: -1, j0: ny, j1: -1, top: 0 };+ let cells = 0;+ const stack = [start];+ seen[start] = 1;+ while (stack.length) {+ const k = stack.pop()!;+ const i = k % nx, j = (k - i) / nx;+ cells++;+ box.top = Math.max(box.top, g.h[k]);+ box.i0 = Math.min(box.i0, i); box.i1 = Math.max(box.i1, i);+ box.j0 = Math.min(box.j0, j); box.j1 = Math.max(box.j1, j);+ for (const n of [i > 0 ? k - 1 : -1, i < nx - 1 ? k + 1 : -1, j > 0 ? k - nx : -1, j < ny - 1 ? k + nx : -1]) {+ if (n >= 0 && !seen[n] && thin(n)) { seen[n] = 1; stack.push(n); }+ }+ }+ // Specks are not worth a slice.+ if (cells * g.step * g.step < 2) continue;+ boxes.push({+ i0: Math.max(0, box.i0 - grow), i1: Math.min(nx - 1, box.i1 + grow),+ j0: Math.max(0, box.j0 - grow), j1: Math.min(ny - 1, box.j1 + grow), top: box.top,+ });+ }+ // Overlapping boxes become one, so no cross-section is drawn twice.+ for (let a = 0; a < boxes.length; a++) {+ for (let b = a + 1; b < boxes.length; b++) {+ const p = boxes[a], q = boxes[b];+ if (p.i0 > q.i1 || q.i0 > p.i1 || p.j0 > q.j1 || q.j0 > p.j1) continue;+ boxes[a] = { i0: Math.min(p.i0, q.i0), i1: Math.max(p.i1, q.i1), j0: Math.min(p.j0, q.j0), j1: Math.max(p.j1, q.j1), top: Math.max(p.top, q.top) };+ boxes.splice(b, 1);+ b = a;+ }+ }+ return boxes;+}++/**+ * Side profile for the slab of grid columns c0..c1, drawn as the plane at its+ * column `at`: loops in (u = -z, y), symmetric in u. Each row takes the largest+ * height across the slab, so a stack of these seen side-on adds up to the+ * solid's side silhouette instead of one tooth per column where the outline+ * slopes. Where a row run meets the outline the profile ends at the surface+ * height right there (`edgeHeight`: the wall of an inflated part, the rim of a+ * revolved one), not at the last sample's.+ */+function columnLoops(g: Grid, c0: number, c1: number, edgeHeight: (x: number, y: number) => number): Point[][] {+ const loops: Point[][] = [];+ const sd = new Float64Array(g.ny).fill(-Infinity), h = new Float64Array(g.ny);+ for (let j = 0; j < g.ny; j++) {+ for (let c = c0; c <= c1; c++) {+ const k = j * g.nx + c;+ if (g.sd[k] > sd[j]) sd[j] = g.sd[k];+ if (g.sd[k] > 0 && g.h[k] > h[j]) h[j] = g.h[k];+ }+ }+ const yAt = (jj: number) => g.y0 + jj * g.step;+ // Where the outline crosses between an inside and an outside sample, and the surface height there.+ const edge = (inside: number, outside: number) => yAt(inside) + ((yAt(outside) - yAt(inside)) * sd[inside]) / (sd[inside] - sd[outside]);+ const rim = (y: number, j: number) => {+ let top = 0;+ for (let c = c0; c <= c1; c++) top = Math.max(top, edgeHeight(g.x0 + c * g.step, y));+ return Math.min(h[j], top);+ };+ let j = 0;+ while (j < g.ny) {+ if (sd[j] <= 0) { j++; continue; }+ const j0 = j;+ while (j < g.ny && sd[j] > 0) j++;+ const j1 = j - 1;+ const yTop = j0 > 0 ? edge(j0, j0 - 1) : yAt(j0);+ const yBot = j1 < g.ny - 1 ? edge(j1, j1 + 1) : yAt(j1);+ const right: Point[] = [[j0 > 0 ? rim(yTop, j0) : h[j0], yTop]];+ for (let k = j0; k <= j1; k++) right.push([h[k], yAt(k)]);+ right.push([j1 < g.ny - 1 ? rim(yBot, j1) : h[j1], yBot]);+ if (Math.max(...right.map((p) => p[0])) < 0.05) continue;+ const left = right.map(([u, y]) => [-u, y] as Point).reverse();+ loops.push(simplifyLoop([...right, ...left], 0.04));+ }+ return loops;+}++/** Depth levels in (flat, flat + round): even in angle over the rounded part of the profile. */+function levels(flat: number, round: number, steps: number): number[] {+ const out: number[] = [];+ for (let k = 1; k < steps; k++) out.push(flat + round * Math.sin((k / steps) * (Math.PI / 2)));+ return out;+}++/** Build the implied volume. `volume` scales every depth (0 = flat). Pass `body` to reuse an analysis. */+export function buildVolume(def: AvatarDefinition, volume = 1, body: BodyAnalysis = analyzeBody(def.body.path)): Volume {+ const outlines = body.subpaths.filter((s) => !s.hole);+ const holes = body.subpaths.filter((s) => s.hole);+ const v = Number.isFinite(volume) ? Math.max(0, volume) : 1;+ const xAxis = revolveAxis(body);++ const parts: VolumePart[] = outlines.map((o) => {+ const cuts = holes.filter((h) => h.probe && isInside(o.polys, h.probe[0], h.probe[1]));+ const polys = [...o.polys, ...cuts.flatMap((h) => h.polys)];+ const b = bounds(o.polys);+ const center: Point = [(b.minX + b.maxX) / 2, (b.minY + b.maxY) / 2];+ const minDim = Math.min(b.maxX - b.minX, b.maxY - b.minY);+ const step = Math.max(0.25, Math.min(0.45, minDim / 24));++ // Classify: shared horizontal axis, own vertical axis (multi-part bodies only), or inflated.+ let kind: PartKind = 'inflate';+ let profile: Profile | null = null;+ if (xAxis !== null) {+ profile = revolveProfile(polys, false, b.minX, b.maxX, xAxis);+ if (profile) kind = 'revolve-x';+ } else if (outlines.length > 1 && cuts.length === 0) {+ profile = revolveProfile(polys, true, b.minY, b.maxY, center[0]);+ if (profile) kind = 'revolve-y';+ }++ let thickness: number, depth: number, rxy = 0, rz = 0;+ let heightOf: (x: number, y: number, sd: number) => number;+ let levelField: LevelField;+ if (kind === 'inflate' || !profile) {+ const coarse = sampleGrid(polys, b, Math.max(step, 0.6), () => 0);+ thickness = 2 * coarse.sd.reduce((m, d) => Math.max(m, d), 0);+ depth = partDepth(thickness, b, v);+ rxy = Math.min(thickness / 2, depth / 2) * 0.9;+ rz = (depth / 2) * 0.85;+ const shape = { depth, rxy, rz };+ heightOf = (_x, _y, sd) => surfaceZ(shape, sd);+ // Height grows with distance from the outline, so a level is reached at a fixed inset.+ levelField = (_x, _y, sd, level) => sd - insetAt(shape, level);+ } else {+ const p = profile;+ const axis = kind === 'revolve-x' ? (xAxis as number) : center[0];+ const radius = Math.max(...p.r);+ thickness = 2 * radius;+ depth = 2 * radius * v;+ heightOf = kind === 'revolve-x'+ ? (x, y) => v * Math.sqrt(Math.max(0, radiusAt(p, x) ** 2 - (y - axis) ** 2))+ : (x, y) => v * Math.sqrt(Math.max(0, radiusAt(p, y) ** 2 - (x - axis) ** 2));+ // Height ≥ level where t² ≤ R² - (level / v)²: that difference over 2R is about a distance.+ levelField = (x, y, _sd, level) => {+ const r = radiusAt(p, kind === 'revolve-x' ? x : y), t = kind === 'revolve-x' ? y - axis : x - axis;+ return (r * r - t * t - (level / Math.max(v, 1e-6)) ** 2) / (2 * Math.max(r, 0.5));+ };+ }+ const height = (x: number, y: number) =>+ isInside(polys, x, y) ? heightOf(x, y, kind === 'inflate' ? edgeDistance(polys, x, y) : 0) : 0;++ const core: VolumeSlice = {+ axis: 'z', at: 0, d: o.d + cuts.map((h) => h.d).join(''), loops: polys, evenOdd: false,+ box: { x: b.minX, y: b.minY, w: b.maxX - b.minX, h: b.maxY - b.minY }, inset: 0,+ };+ const zSlices: VolumeSlice[] = [core];+ const xSlices: VolumeSlice[] = [];+ const half = depth / 2;+ if (half > 0.05) {+ const g = sampleGrid(polys, b, step, heightOf);+ const steps = kind === 'inflate'+ ? Math.max(4, Math.min(14, Math.round(rz / 0.8)))+ : Math.max(5, Math.min(18, Math.round(half / 1.1)));+ // Inflated parts keep a straight wall up to half - rz; one slice at its end carries it.+ const ls = kind === 'inflate' ? [half - rz, ...levels(half - rz, rz, steps)] : levels(0, half, steps);+ const addLevel = (level: number, box?: CellBox) => {+ const loops = levelLoops(g, level, levelField, box);+ if (!loops.length) return false;+ const sample = loops.flat().filter((_, k) => k % 3 === 0);+ const inset = Math.min(...sample.map(([x, y]) => edgeDistance(polys, x, y)));+ const slice = { axis: 'z' as const, d: loopsToPath(loops), loops, evenOdd: true, box: loopBox(loops), inset };+ zSlices.push({ ...slice, at: level }, { ...slice, at: -level });+ return true;+ };+ const used = [0];+ for (const level of ls) if (level >= 0.02 && addLevel(level)) used.push(level);+ // Thin parts of an inflated outline (deep, narrow fins): more cross-sections between the levels,+ // the straight wall included, each clipped to its box. Revolved parts' slices span their thin side.+ const thin = kind === 'inflate' ? thinBoxes(g) : [];+ for (const box of thin) {+ for (let k = 1; k < used.length && used[k - 1] < box.top; k++) {+ const a = used[k - 1], gap = used[k] - a, m = Math.ceil(gap / FINE_Z - 1e-9);+ for (let q = 1; q < m && a + (gap * q) / m < box.top; q++) addLevel(a + (gap * q) / m, box);+ }+ }+ zSlices.sort((m, n) => m.at - n.at);++ const width = b.maxX - b.minX;+ const every = Math.max(1, Math.round(Math.max(1.1, width / MAX_X_SLICES) / g.step));+ const edgeHeight = (x: number, y: number) => heightOf(x, y, 0);+ // One plane per `every` grid columns, standing for the whole slab around it.+ const before = Math.floor((every - 1) / 2);+ for (let i = 1; i < g.nx - 1; i += every) {+ const loops = columnLoops(g, Math.max(0, i - before), Math.min(g.nx - 1, i - before + every - 1), edgeHeight);+ if (loops.length) xSlices.push({ axis: 'x', at: g.x0 + i * g.step, d: loopsToPath(loops), loops, evenOdd: true, box: loopBox(loops), inset: 0 });+ }+ }++ return {+ kind, d: core.d, polys, bounds: b, center, thickness, depth, rxy, rz,+ axis: kind === 'revolve-x' ? (xAxis as number) : kind === 'revolve-y' ? center[0] : undefined,+ zSlices, xSlices, height,+ };+ });++ const eyeScale = boostedEyeScale(body, def.eyes);+ // The eyes ride on whichever part is highest under their centers.+ const centers = eyeCenters(def.eyes);+ let eyePart = 0, bestZ = -Infinity;+ parts.forEach((part, i) => {+ const zs = centers.map(([x, y]) => part.height(x, y));+ if (zs.some((z) => z <= 0)) return;+ const z = Math.min(...zs);+ if (z > bestZ) { bestZ = z; eyePart = i; }+ });+ const host = parts[eyePart];+ // Flat eye planes sit at the highest surface under the eye and its gaze travel, so the body never cuts them.+ const w = (EYE_W * eyeScale) / 2 + GAZE_X * eyeScale, hh = (EYE_H * eyeScale) / 2 + GAZE_Y * eyeScale;+ const eyeZ = centers.map(([x, y]) => {+ let top = 0;+ for (const fx of [-1, -0.5, 0, 0.5, 1]) for (const fy of [-1, -0.5, 0, 0.5, 1]) top = Math.max(top, host ? host.height(x + fx * w, y + fy * hh) : 0);+ return top;+ }) as [number, number];++ const normal = (x: number, y: number): Vec3 => {+ if (!host) return [0, 0, 1];+ const e = 0.75;+ const gx = (host.height(x + e, y) - host.height(x - e, y)) / (2 * e);+ const gy = (host.height(x, y + e) - host.height(x, y - e)) / (2 * e);+ const n = Math.hypot(gx, gy, 1);+ return [-gx / n, -gy / n, 1 / n];+ };+ const half = (EYE_W * eyeScale) / 2;+ const eyeNormals = centers.map(([x, y]) => [normal(x - half, y), normal(x, y), normal(x + half, y)]) as [Vec3[], Vec3[]];++ return { parts, bounds: body.bounds, eyePart, eyeZ, eyeScale, eyeNormals };+}++/** Largest eye scale up to EYE_BOOST × the definition's whose drawn eyes keep EYE_BOOST_PAD from the outline. */+export function boostedEyeScale(body: BodyAnalysis, eyes: AvatarEyes): number {+ for (const k of [EYE_BOOST, 1.38, 1.3, 1.22, 1.15, 1.08]) {+ if (!drawnEyesFit(body.polys, { ...eyes, scale: eyes.scale * k }, 0, 0, EYE_BOOST_PAD)) return eyes.scale * k;+ }+ return eyes.scale;+}++export interface FaceRoom {+ /** Drawn eye size relative to the definition's (1..EYE_BOOST). */+ boost: number;+ /** Gap between the drawn eyes at rest (pill and happy arc) and the outline, viewBox units. */+ clearance: number;+ /** Gaze travel left at the drawn size (see gazeRange). */+ gaze: GazeRange;+ /** True when the face meets the design target: full boost, FACE_ROOM_TARGET clearance, full gaze. */+ ok: boolean;+}++/** How much room the face has as the renderer will actually draw it. */+export function faceRoom(def: AvatarDefinition, body: BodyAnalysis = analyzeBody(def.body.path)): FaceRoom {+ const scale = boostedEyeScale(body, def.eyes);+ const eyes = { ...def.eyes, scale };+ const clearance = eyeClearance(body.polys, eyes);+ const gaze = gazeRange(body.polys, eyes);+ const boost = Math.round((scale / def.eyes.scale) * 100) / 100;+ const ok = boost >= EYE_BOOST - 1e-9 && clearance >= FACE_ROOM_TARGET && Math.min(gaze.left, gaze.right, gaze.up, gaze.down) === 1;+ return { boost, clearance, gaze, ok };+}diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex 26b5bb041e..53712b8bf6 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -285,7 +285,7 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {mascotExpression?: MausExpression | null;mascotBody?: BotBodyId | null;/** Overrides both eyes and mouth. Absent or null preserves the body's default inks. */- mascotFaceColor?: MascotFaceColor | null;+ mascotFaceColor?: MascotFaceColor | null; /** Lowercase `#rrggbb` tint for the avatar body only. Absent or null uses `color`. */ mascotBodyColor?: string | null;/** App-owned attachment served as this bot's custom profile image;* always present on the wire, null when the bot has none. */avatarUrl: string | null;diff --git a/packages/phone-protocol/tsconfig.json b/packages/phone-protocol/tsconfig.jsonindex 0e1163938c..c9b766f9fe 100644--- a/packages/phone-protocol/tsconfig.json+++ b/packages/phone-protocol/tsconfig.json@@ -16,5 +16,5 @@"types": []},"include": ["src", "portable-globals.d.ts"],- "exclude": ["src/**/*.test.ts"]+ "exclude": ["src/**/*.test.ts", "src/open-bot-avatar/dom"]}diff --git a/scripts/gen-mascot-bodies.ts b/scripts/gen-mascot-bodies.tsindex 1034894fc0..0d4740d688 100644--- a/scripts/gen-mascot-bodies.ts+++ b/scripts/gen-mascot-bodies.ts@@ -55,10 +55,18 @@ const CLOUD_SETS = AIMS.map(aim => buildClouds(LOOK_AROUND, MOUTH_STROKE, aim))* placement. */const ALL_CLOUDS = CLOUD_SETS.flat()-/** The scale cap. 1.0 reproduces the proportions the expressions were drawn at. */+/** The cursor's scale cap. 1.0 reproduces the proportions the expressions were drawn at. */const CAP = 1+/** Every other body wears the largest face it holds, up to this cap... */+const ROOMY_CAP = 1.5++/** ...at this share of the largest, so the face keeps calm room around it instead of+ * grazing the outline when it looks to an edge. */+const ROOM = 0.9+function solveBody(def: BodyDef): Solved {+ const cap = def.id === DEFAULT_ID ? CAP : ROOMY_CAP// `def.viewBox` is advisory and wrong for two bodies; bounds come from the outline.const polylines = flatten(def.d)const fit = fitTransform(boundsOf(polylines))@@ -71,7 +79,7 @@ function solveBody(def: BodyDef): Solved {let best: Anchor = {x: circle.x,y: circle.y,- scale: maxScaleAt(ALL_CLOUDS, sdf, circle.x, circle.y, CAP),+ scale: maxScaleAt(ALL_CLOUDS, sdf, circle.x, circle.y, cap),}let step = Math.max(circle.radius, 12)for (let level = 0; level < 8; level++) {@@ -80,7 +88,7 @@ function solveBody(def: BodyDef): Solved {if (!dx && !dy) continueconst x = best.x + dx * stepconst y = best.y + dy * step- const scale = maxScaleAt(ALL_CLOUDS, sdf, x, y, CAP)+ const scale = maxScaleAt(ALL_CLOUDS, sdf, x, y, cap)if (scale > best.scale + 1e-4) best = { x, y, scale }}}@@ -196,10 +204,8 @@ function emit(bodies: Baked[]): string {* \`scripts/gen-mascot-bodies.ts\`, which solves each face placement against the real* expression geometry and verifies that nothing clips.*- * Every body carries the same face at the same size: the generator clamps the whole- * catalog to the smallest face any one body can hold, so the mascot reads as one- * character in different bodies rather than ten different mascots. Roomier bodies simply- * end up with more margin around the face.+ * The cursor keeps the face it shipped with. Every other body wears the largest face it+ * holds with room to spare, never smaller than the cursor's, so the face leads the shape.** The fields match \`CursorSilhouette\` exactly, so a body can be handed to the renderer* with no adapter in between.@@ -441,23 +447,20 @@ function main(): void {}console.log("")- const shared = solved.reduce((min, s) => Math.min(min, s.scale), Infinity)- if (shared < cursor.scale) {- const tighter = solved- .filter(s => s.scale < cursor.scale)- .map(s => `${s.def.id} (${s.scale})`)- .join(", ")+ const scaleOf = (body: Solved) =>+ body === cursor ? cursor.scale : Math.floor(body.scale * ROOM * 1000) / 1000+ const tighter = solved.filter(s => scaleOf(s) < cursor.scale)+ if (tighter.length > 0) {throw new Error(- `the shared face scale ${shared} is below ${DEFAULT_ID}'s own ${cursor.scale}: ` +- `${tighter} cannot hold the shipped face, so clamping the catalog would shrink ` +- `the mascot everyone already has. Widen those outlines rather than lowering the floor.`+ `${tighter.map(s => `${s.def.id} (${scaleOf(s)})`).join(", ")} cannot hold a face as big ` ++ `as ${DEFAULT_ID}'s ${cursor.scale}. Widen those outlines rather than lowering the floor.`)}const baked: Baked[] = []const clipped: string[] = []for (const body of solved) {- const anchor = anchorAt(body.sdf, body.seed, shared)+ const anchor = anchorAt(body.sdf, body.seed, scaleOf(body))const clipping = clippingAt(body.sdf, anchor)clipping.forEach((expressions, i) => {if (expressions.length === 0) return@@ -481,7 +484,6 @@ function main(): void {})}- console.log(`shared face scale ${shared} (${DEFAULT_ID}'s own floor is ${cursor.scale})`)console.log(`${"body".padEnd(width)} ${"scale".padStart(6)} ${"clearance".padStart(9)}`)for (const body of baked) {const scale = body.anchor.scale.toFixed(3).padStart(6)diff --git a/scripts/mascot-bodies/builders.ts b/scripts/mascot-bodies/builders.tsindex e1169abe47..2df2d996b3 100644--- a/scripts/mascot-bodies/builders.ts+++ b/scripts/mascot-bodies/builders.ts@@ -256,7 +256,7 @@ export const BODY_DEFS: BodyDef[] = [{ id: "diamond", name: "Diamond", d: buildPolygon(196, 196, 4, 0.12), viewBox: [0, 0, 200, 200] },// A face-fit constraint, not taste: at the classic 0.42 the notches pinch the// star to a 50-unit inscribed circle, and the smallest face clamps every body.- { id: "star", name: "Star", d: buildStar(196, 196, 5, 0.55), viewBox: [0, 0, 200, 200] },+ { id: "star", name: "Star", d: buildStar(196, 196, 5, 0.62), viewBox: [0, 0, 200, 200] },]export const BODY_IDS: string[] = BODY_DEFS.map(s => s.id)diff --git a/scripts/mascot-bodies/catalog.test.mjs b/scripts/mascot-bodies/catalog.test.mjsindex 79a7537e5c..005c031e5b 100644--- a/scripts/mascot-bodies/catalog.test.mjs+++ b/scripts/mascot-bodies/catalog.test.mjs@@ -32,15 +32,14 @@ describe("the generated catalog", () => {for (const id of MASCOT_BODY_IDS) {const { anchor } = MASCOT_BODIES[id];expect(anchor.scale, id).toBeGreaterThan(0);- expect(anchor.scale, id).toBeLessThanOrEqual(1);expect(anchor.x, id).toBeGreaterThan(0);expect(anchor.y, id).toBeGreaterThan(0);}});- it("clamps every face to one shared size", () => {- const scales = new Set(MASCOT_BODY_IDS.map(id => MASCOT_BODIES[id].anchor.scale));- expect([...scales]).toHaveLength(1);+ it("never gives a body a smaller face than the cursor's", () => {+ const floor = MASCOT_BODIES[DEFAULT_MASCOT_BODY].anchor.scale;+ for (const id of MASCOT_BODY_IDS) expect(MASCOT_BODIES[id].anchor.scale, id).toBeGreaterThanOrEqual(floor);});});diff --git a/scripts/sync-phone-protocol.mjs b/scripts/sync-phone-protocol.mjsindex fcef38322a..ee83351fe0 100644--- a/scripts/sync-phone-protocol.mjs+++ b/scripts/sync-phone-protocol.mjs@@ -12,6 +12,8 @@ import { fileURLToPath } from "node:url";const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");const PACKAGE = "packages/phone-protocol";+/** The vendored avatar engine's browser mount: the phone has no DOM. */+const DOM_ONLY = `${PACKAGE}/src/open-bot-avatar/dom/`;/** Where each copied file comes from, by its path under the output directory. */export function syncedFiles(ref, root = ROOT) {@@ -19,7 +21,7 @@ export function syncedFiles(ref, root = ROOT) {const git = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8" });const commit = git("rev-parse", "--verify", `${ref}^{commit}`).trim();const source = git("ls-tree", "-r", "--name-only", "-z", commit, "--", `${PACKAGE}/src`).split("\0")- .filter((path) => path.endsWith(".ts") && !path.endsWith(".test.ts"));+ .filter((path) => path && !path.endsWith(".test.ts") && !path.startsWith(DOM_ONLY));const files = new Map([["package.json", `${PACKAGE}/package.json`],...source.map((path) => [path.slice(PACKAGE.length + 1), path]),diff --git a/scripts/sync-phone-protocol.test.mjs b/scripts/sync-phone-protocol.test.mjsindex 8116939d2b..94f84c4e82 100644--- a/scripts/sync-phone-protocol.test.mjs+++ b/scripts/sync-phone-protocol.test.mjs@@ -36,14 +36,14 @@ function tree(dir) {}describe("sync-phone-protocol", () => {- it("copies the package's sources, the wire vectors and the app host page from HEAD, and names the commit", () => {+ it("copies the package's sources but the avatar engine's DOM mount, the wire vectors and the app host page from HEAD, and names the commit", () => {const out = join(scratch(), "protocol");execFileSync(process.execPath, [SCRIPT, "--out", out], { cwd: ROOT, stdio: "pipe" });const head = git("rev-parse", "HEAD");expect(readFileSync(join(out, "SOURCE"), "utf8")).toBe(`${head}\n`);const sources = git("ls-tree", "-r", "--name-only", "HEAD", "--", "packages/phone-protocol/src").split("\n")- .filter((path) => !path.endsWith(".test.ts"));+ .filter((path) => !path.endsWith(".test.ts") && !path.includes("/open-bot-avatar/dom/"));for (const name of ["wire", "responses", "pairing-code", "app-rpc", "cursor-face-data", "failed-turn", "mention-boundary", "upload-limits","markdown-plain-paths", "bot-limit", "codex-usage-limit", "cloud-hints", "waits",@@ -51,6 +51,8 @@ describe("sync-phone-protocol", () => {]) {expect(sources).toContain(`packages/phone-protocol/src/${name}.ts`);}+ expect(sources).toContain("packages/phone-protocol/src/open-bot-avatar/LICENSE");+ expect(sources).toContain("packages/phone-protocol/src/open-bot-avatar/render.ts");expect(Object.keys(tree(out)).sort()).toEqual(["SOURCE", "app-host.html", "package.json", "vectors/v1.json",...sources.map((path) => path.slice("packages/phone-protocol/".length)),diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex cbd40cad78..58db47a879 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -104,7 +104,7 @@ const endedSchema = z.array(z.object({ origin: z.string(), token: z.string(), atexport type EndedLink = z.infer<typeof endedSchema>[number];interface LocalBot { id: string; name: string; color?: string; hidden?: boolean; title?: string; description?: string; movedTo?: unknown;- mascotBody?: string | null; mascotFaceColor?: string | null; chiefOfStaff?: boolean; threadId?: string }+ mascotBody?: string | null; mascotFaceColor?: string | null; mascotBodyColor?: string | null; chiefOfStaff?: boolean; threadId?: string }export interface BotLinkDeps {dataDir: string;@@ -209,6 +209,7 @@ export function createBotLink(deps: BotLinkDeps) {id: bot.id, name: bot.name, ...(bot.title ? { title: bot.title.slice(0, 200) } : {}), ...(bot.description ? { description: bot.description.slice(0, 400) } : {}),...(deps.model?.(bot) ? { model: deps.model(bot)!.slice(0, 200) } : {}), level: deps.level(bot),...(bot.color ? { color: bot.color.slice(0, 64) } : {}), ...(bot.mascotBody ? { mascotBody: bot.mascotBody.slice(0, 64) } : {}), ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor.slice(0, 64) } : {}),+ ...(bot.mascotBodyColor ? { mascotBodyColor: bot.mascotBodyColor.slice(0, 64) } : {}),...(bot.chiefOfStaff ? { chief: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}),})).slice(0, 500);diff --git a/server/bot-link/protocol.ts b/server/bot-link/protocol.tsindex 4db18005da..cc28cdc54f 100644--- a/server/bot-link/protocol.ts+++ b/server/bot-link/protocol.ts@@ -55,7 +55,7 @@ const level = z.enum(["ask", "edits", "auto", "full", "custom"]);export const linkedBotSchema = z.object({id: botId, name, title: z.string().max(200).optional(), description: z.string().max(400).optional(), model: z.string().max(200).optional(), level: level.optional(),/** How it looks and where its own chat is, so the other place can draw it as it is drawn at home. */- color: z.string().max(64).optional(), mascotBody: z.string().max(64).optional(), mascotFaceColor: z.string().max(64).optional(), chief: z.boolean().optional(), threadId: botId.optional(),+ color: z.string().max(64).optional(), mascotBody: z.string().max(64).optional(), mascotFaceColor: z.string().max(64).optional(), mascotBodyColor: z.string().max(64).optional(), chief: z.boolean().optional(), threadId: botId.optional(),});export type LinkedBot = z.infer<typeof linkedBotSchema>;diff --git a/server/bot-profile.test.ts b/server/bot-profile.test.tsindex 681ddf98fb..2734c58fb2 100644--- a/server/bot-profile.test.ts+++ b/server/bot-profile.test.ts@@ -105,7 +105,7 @@ describe("mascotBody", () => {});});- it.each(["pumpkin", "laddu"])("accepts the festival body %s", (mascotBody) => {+ it.each(["pumpkin", "laddu", "obj-mug"])("accepts the festival or object body %s", (mascotBody) => {expect(parseBotProfilePatch({ mascotBody } as never, true)).toEqual({ok: true,patch: { mascotBody },@@ -118,7 +118,10 @@ describe("mascotBody", () => {error:"mascotBody must be cursor, blob, circle, squircle, capsule, drop, shield, hexagon, diamond, star, " +"pumpkin, ghost, witch, bat, cat, skull, monster, mummy, vampire, spider, " +- "rocket, anaar, chakri, sparkler, bomb, laddu, chakli, jalebi, katli, or karanji",+ "rocket, anaar, chakri, sparkler, bomb, laddu, chakli, jalebi, katli, karanji, " ++ "obj-controller, obj-barbell, obj-mug, obj-lightbulb, obj-chat, obj-sprout, obj-watering-can, obj-book, " ++ "obj-brain, obj-bull, obj-bunny, obj-camera, obj-cat, obj-cloud, obj-egg, obj-ghost, obj-magnifier, " ++ "obj-paint-brush, obj-palette, obj-rocket, or obj-witch-hat",});});});@@ -137,6 +140,20 @@ describe("mascotFaceColor", () => {});});+describe("mascotBodyColor", () => {+ it.each([["#12ab9f", "#12ab9f"], ["#ABCDEF", "#abcdef"], [null, null]] as const)("accepts %s at both profile boundaries", (input, saved) => {+ for (const strict of [true, false]) {+ expect(parseBotProfilePatch({ mascotBodyColor: input }, strict)).toEqual({ ok: true, patch: { mascotBodyColor: saved } });+ }+ });++ it.each(["red", "#fff", "#12ab9f0", "12ab9f", "url(#x)", "", 1, {}])("rejects %j", (mascotBodyColor) => {+ expect(parseBotProfilePatch({ mascotBodyColor } as never, true)).toEqual({+ ok: false, error: "mascotBodyColor must be a #rrggbb hex colour or null",+ });+ });+});+describe("soul (standing instructions)", () => {it("accepts soul on both the strict and broad boundaries", () => {expect(parseBotProfilePatch({ soul: "Be brief." }, true)).toEqual({ ok: true, patch: { soul: "Be brief." } });diff --git a/server/bot-profile.ts b/server/bot-profile.tsindex 63058a89c8..c1c2e8a65c 100644--- a/server/bot-profile.ts+++ b/server/bot-profile.ts@@ -6,6 +6,7 @@ import {BOT_AVATAR_CROPS,botAvatarCropSchema,botAvatarUrlSchema,+ mascotBodyColorSchema,mascotFaceColorSchema,} from "../shared/bot-avatar.ts";import { BOT_PROFILE_LIMITS, fitsOnOneLine } from "../shared/bot-profile.ts";@@ -29,6 +30,7 @@ export const BOT_PROFILE_PATCH_FIELDS = ["avatarFocusY","mascotBody","mascotFaceColor",+ "mascotBodyColor","voice","speakReplies","replyStyle",@@ -68,6 +70,7 @@ export const profilePatchSchema = z.object({avatarFocusY: z.number({ error: "avatarFocusY must be a number from 0 to 1" }).finite().min(0).max(1).optional(),mascotBody: botBodySchema.optional(),mascotFaceColor: mascotFaceColorSchema.nullable().optional(),+ mascotBodyColor: mascotBodyColorSchema.nullable().optional(),voice: z.string({ error: "voice must be a string" }).max(BOT_PROFILE_LIMITS.voice, { error: "voice must be at most 200 characters" })@@ -93,6 +96,7 @@ export type BotProfilePatch = Partial<| "avatarFocusY"| "mascotBody"| "mascotFaceColor"+ | "mascotBodyColor"| "voice"| "speakReplies"| "replyStyle"@@ -124,6 +128,9 @@ export function parseBotProfilePatch(input: BotProfilePatchInput, strict = falseif (issue?.path[0] === "mascotFaceColor") {return { ok: false, error: "mascotFaceColor must be white, black, or null" };}+ if (issue?.path[0] === "mascotBodyColor") {+ return { ok: false, error: "mascotBodyColor must be a #rrggbb hex colour or null" };+ }return { ok: false, error: issue?.message ?? "invalid profile patch" };}diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.tsindex 885ce74c0e..2ef92e5fe3 100644--- a/server/host/bot-link-host.ts+++ b/server/host/bot-link-host.ts@@ -2,6 +2,7 @@// server's store and coordinator, the computer's end that asks the Cloud, and the routes. With the link off (no// bot-link.json in the data folder) `start` asks nobody and every hook here answers as if the link did not exist.import { dirname } from "node:path";+import { mascotBodyColorSchema } from "../../shared/bot-avatar.ts";import { createDialer } from "../bot-link/dial.ts";import { createBotLink } from "../bot-link/link.ts";@@ -46,6 +47,12 @@ export interface BotLinkHostDeps {log(line: string): void;}+/** Another place's body tint lands here only as a valid hex, since the avatar paints it. */+const bodyColor = (value: string | undefined) => {+ const color = mascotBodyColorSchema.safeParse(value).data;+ return color ? { mascotBodyColor: color } : {};+};+export function createBotLinkHost(deps: BotLinkHostDeps) {const { store } = deps;/** Each bot of each linked place as a record this place finds by its address: its name and look, and where it lives.@@ -55,14 +62,15 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {for (const { id, peer, place, kind, bot } of link.linked()) {next.set(id, { id, name: bot.name, color: bot.color ?? "blue", threadId: "", tasks: [], resumeCursors: {}, modelSelection: { instanceId: "", model: bot.model ?? "" },home: { place: peer, placeName: place.name, botId: bot.id, kind }, ...(bot.title ? { title: bot.title } : {}), ...(bot.description ? { description: bot.description } : {}),- ...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}), ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}) } as unknown as BotRecord);+ ...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}), ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}),+ ...bodyColor(bot.mascotBodyColor) } as unknown as BotRecord);}// A far member of a room here that cannot be reached now (the link is off, its place is unlinked, or its place no// longer has it) stays a member: it is found by its address, named as it was last known, and takes no turn.rooms.sync();- for (const { id, gone, name, color, place, placeName, botId, kind, title, mascotBody, mascotFaceColor } of rooms.absent()) {+ for (const { id, gone, name, color, place, placeName, botId, kind, title, mascotBody, mascotFaceColor, mascotBodyColor } of rooms.absent()) {next.set(id, { id, name, color: color ?? "blue", threadId: "", tasks: [], resumeCursors: {}, modelSelection: { instanceId: "", model: "" },- home: { place, placeName, botId, ...(kind ? { kind } : {}), gone }, ...(title ? { title } : {}), ...(mascotBody ? { mascotBody } : {}), ...(mascotFaceColor ? { mascotFaceColor } : {}) } as unknown as BotRecord);+ home: { place, placeName, botId, ...(kind ? { kind } : {}), gone }, ...(title ? { title } : {}), ...(mascotBody ? { mascotBody } : {}), ...(mascotFaceColor ? { mascotFaceColor } : {}), ...bodyColor(mascotBodyColor) } as unknown as BotRecord);}store.standIns.clear();for (const [id, record] of next) if (isLinkedId(id)) store.standIns.set(id, record);diff --git a/server/host/bot-link-rooms.ts b/server/host/bot-link-rooms.tsindex 7a3ff3dec5..c402162568 100644--- a/server/host/bot-link-rooms.ts+++ b/server/host/bot-link-rooms.ts@@ -47,7 +47,7 @@ const FILE = "bot-link-rooms.json";const RECORDS_MAX = 2_000;/** What a far member was last known as, kept so that it can be named while its place cannot be asked. */-interface Known { name: string; color?: string; place: string; placeName: string; botId: string; kind?: "computer" | "cloud"; title?: string; mascotBody?: string; mascotFaceColor?: string }+interface Known { name: string; color?: string; place: string; placeName: string; botId: string; kind?: "computer" | "cloud"; title?: string; mascotBody?: string; mascotFaceColor?: string; mascotBodyColor?: string }/** One turn handed over: where its words started and ended, so that the same turn sent again says the same and more, never* less; and how many members' answers led to it. */interface Turn { seat: string; hop: number; at: number; composed?: boolean; after?: string; through?: string }@@ -72,7 +72,7 @@ export interface LinkedRoomsDeps {linked(peer: string): boolean;online(peer: string): boolean;/** The bots the linked places have now, by their address here. */- linkedBots(): ReadonlyArray<{ id: string; peer: string; place: { name: string }; kind?: "computer" | "cloud"; bot: { id: string; name: string; color?: string; title?: string; mascotBody?: string; mascotFaceColor?: string } }>;+ linkedBots(): ReadonlyArray<{ id: string; peer: string; place: { name: string }; kind?: "computer" | "cloud"; bot: { id: string; name: string; color?: string; title?: string; mascotBody?: string; mascotFaceColor?: string; mascotBodyColor?: string } }>;selfName(): string;/** There is work for a place that is not connected: a computer asks its Cloud for it now, as for any hand-off. */wanted(): void;@@ -179,7 +179,8 @@ export function createLinkedRooms(deps: LinkedRoomsDeps) {for (const id of ids) {const one = live.get(id);if (one) kept.members[id] = { name: one.bot.name, place: one.peer, placeName: one.place.name, botId: one.bot.id, ...(one.kind ? { kind: one.kind } : {}), ...(one.bot.color ? { color: one.bot.color } : {}),- ...(one.bot.title ? { title: one.bot.title } : {}), ...(one.bot.mascotBody ? { mascotBody: one.bot.mascotBody } : {}), ...(one.bot.mascotFaceColor ? { mascotFaceColor: one.bot.mascotFaceColor } : {}) };+ ...(one.bot.title ? { title: one.bot.title } : {}), ...(one.bot.mascotBody ? { mascotBody: one.bot.mascotBody } : {}), ...(one.bot.mascotFaceColor ? { mascotFaceColor: one.bot.mascotFaceColor } : {}),+ ...(one.bot.mascotBodyColor ? { mascotBodyColor: one.bot.mascotBodyColor } : {}) };}for (const id of Object.keys(kept.members)) if (!ids.has(id)) delete kept.members[id];if (JSON.stringify([kept.members, Object.keys(kept.seats)]) !== before) save();diff --git a/server/mascot-face-color.e2e.test.ts b/server/mascot-face-color.e2e.test.tsindex b4f8244eb8..2bc4d88fd5 100644--- a/server/mascot-face-color.e2e.test.ts+++ b/server/mascot-face-color.e2e.test.ts@@ -34,3 +34,33 @@ it("saves, reads and resets facial feature color through the isolated HTTP routeawait fixture.close();}}, 60_000);++it("saves, reads and clears a custom body color through the isolated HTTP routes", async () => {+ const fixture = await launchVerificationServer();+ const api = async (method: string, path: string, body?: unknown, status = 200) => {+ const response = await fetch(`${fixture.info.url}${path}`, {+ method, headers: { "content-type": "application/json", origin: fixture.info.url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ const data = await response.json() as { bot: WireBot; bots: WireBot[] };+ expect(response.status, JSON.stringify(data)).toBe(status);+ return data;+ };+ try {+ const { bot } = await api("POST", "/api/bots", {+ name: "Body color fixture", useDefaults: false, settings: { color: "yellow", mascotBodyColor: "#ABCDEF" },+ }, 201);+ expect(bot.mascotBodyColor).toBe("#abcdef");+ const path = `/api/bots/${bot.id}`;+ for (const mascotBodyColor of ["#12ab9f", null]) {+ expect((await api("PATCH", path, { mascotBodyColor })).bot.mascotBodyColor).toBe(mascotBodyColor);+ const saved = JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8"));+ expect(saved.find((value: { id: string }) => value.id === bot.id).mascotBodyColor).toBe(mascotBodyColor);+ }+ await api("PATCH", path, { mascotBodyColor: "red" }, 400);+ const after = (await api("GET", "/api/bots")).bots.find((value: { id: string }) => value.id === bot.id);+ expect(after).toMatchObject({ color: "yellow", mascotBodyColor: null });+ } finally {+ await fixture.close();+ }+}, 60_000);diff --git a/server/request-auth.ts b/server/request-auth.tsindex abbc44b29f..2a34de0191 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -521,12 +521,12 @@ export function requiredScope(method: string, path: string, features: { sharedCo/** A client may change how a bot looks, never what it may do. */const CLIENT_BOT_PATCH_FIELDS = new Set([- "unread", "pinned", "pinnedMessageId", "color", "mascotExpression", "mascotBody", "mascotFaceColor",+ "unread", "pinned", "pinnedMessageId", "color", "mascotExpression", "mascotBody", "mascotFaceColor", "mascotBodyColor","avatarUrl", "avatarCrop", "avatarZoom", "avatarFocusX", "avatarFocusY", "sidebarHidden", "welcomed",]);/** How a bot looks to everyone who sees it. */const SHARED_LOOK_FIELDS = new Set([- "color", "mascotExpression", "mascotBody", "mascotFaceColor", "avatarUrl", "avatarCrop", "avatarZoom", "avatarFocusX", "avatarFocusY",+ "color", "mascotExpression", "mascotBody", "mascotFaceColor", "mascotBodyColor", "avatarUrl", "avatarCrop", "avatarZoom", "avatarFocusX", "avatarFocusY",]);/** `ownMausBot`: the session's own MausBot on a Team Cloud, which its member may also rename. `teamMember`: a Team Cloud* member's session, which changes no other bot's look. */diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.tsindex 82a3e8767c..4bf6994b50 100644--- a/server/routes/bot-link.ts+++ b/server/routes/bot-link.ts@@ -103,7 +103,8 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {// Names and looks only, as each place told this one: no message, address or sign-in.return json(res, 200, { bots: link.linked().map(({ id, peer, place, kind, online, bot }) => ({ id, home: { id: place.id, key: peer, kind, name: place.name, online }, botId: bot.id, name: bot.name,...(bot.title ? { title: bot.title } : {}), ...(bot.color ? { color: bot.color } : {}), ...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}),- ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}), ...(bot.chief ? { chiefOfStaff: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}) })) });+ ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}), ...(bot.mascotBodyColor ? { mascotBodyColor: bot.mascotBodyColor } : {}),+ ...(bot.chief ? { chiefOfStaff: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}) })) });}if (path === STATE_PATH) {diff --git a/server/store.ts b/server/store.tsindex 8d6cf32eb4..7057a0f287 100644--- a/server/store.ts+++ b/server/store.ts@@ -1263,7 +1263,7 @@ export class Store {profile: Partial<Pick<BotRecord,- "name" | "title" | "description" | "soul" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor" | "modelSelection" | "section" | "cwd" | "visibility" | "toolScope" | "createdBy" | "reportsTo"+ "name" | "title" | "description" | "soul" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor" | "modelSelection" | "section" | "cwd" | "visibility" | "toolScope" | "createdBy" | "reportsTo">> = {},opts: {@@ -1285,7 +1285,7 @@ export class Store {soul: profile.soul ?? "",soulHash: soulHash(profile.soul ?? ""),notifications: true,- color: profile.color ?? rotationColor(this.bots.length), mascotFaceColor: profile.mascotFaceColor ?? undefined,+ color: profile.color ?? rotationColor(this.bots.length), mascotFaceColor: profile.mascotFaceColor ?? undefined, mascotBodyColor: profile.mascotBodyColor ?? undefined,...(profile.mascotExpression ? { mascotExpression: profile.mascotExpression } : {}),...(profile.mascotBody ? { mascotBody: profile.mascotBody } : {}),...this.newBotSharing(profile.visibility, newBotOwner(profile)),diff --git a/server/team-backup.test.ts b/server/team-backup.test.tsindex b70ad38111..d5d35decfc 100644--- a/server/team-backup.test.ts+++ b/server/team-backup.test.ts@@ -24,7 +24,7 @@ function fixture() {});const chief = store.createBot({ name: "Mira", section: "Engineering", description: "Full instructions\n".repeat(400) }, { seedMessages: false });store.setSoul(chief.id, " Cite sources.\nRespect the user's current request. 🐭\n");- const scout = store.createBot({ name: "Scout", section: "Engineering", mascotBody: "circle", mascotFaceColor: "black" }, { seedMessages: false });+ const scout = store.createBot({ name: "Scout", section: "Engineering", mascotBody: "circle", mascotFaceColor: "black", mascotBodyColor: "#12ab9f" }, { seedMessages: false });const otherChief = store.createBot({ name: "Ava", section: "Operations" }, { seedMessages: false });const archived = store.createBot({ name: "Archived" }, { seedMessages: false });store.patchBot(archived.id, { hidden: true });@@ -210,6 +210,7 @@ describe("additive portable team backups", () => {expect(store.bot(archived.id)?.hidden).toBe(true);expect(importedScout.mascotBody).toBe(scout.mascotBody);expect(importedScout.mascotFaceColor).toBe("black");+ expect(importedScout.mascotBodyColor).toBe("#12ab9f");expect(result.groups[0]).toMatchObject({ name: "Project room 2", section: "Engineering 2", memberIds: [importedChief.id, importedScout.id], defaultResponder: { kind: "member", botId: importedChief.id } });expect(result.groups[0].tasks?.map((task) => [task.title, task.createdAt])).toEqual(group.tasks?.map((task) => [task.title, task.createdAt]));const roomMessage = store.messagesFor(result.groups[0].threadId)[0];diff --git a/server/team-backup.ts b/server/team-backup.tsindex 46971682eb..7af4c724de 100644--- a/server/team-backup.ts+++ b/server/team-backup.ts@@ -115,7 +115,7 @@ export function createTeamBackup(store: Store, routines: Routine[], name: stringkey: bot.id, name: bot.name, title: bot.title, description: bot.description, soul: bot.soul,section: bot.section, color: bot.color,mascotExpression: bot.mascotExpression ?? undefined, mascotBody: bot.mascotBody ?? undefined,- mascotFaceColor: bot.mascotFaceColor ?? undefined,+ mascotFaceColor: bot.mascotFaceColor ?? undefined, mascotBodyColor: bot.mascotBodyColor ?? undefined,chiefOfStaff: Boolean(bot.chiefOfStaff), hidden: Boolean(bot.hidden), playbooks: bot.playbooks ?? [],// Grants travel so the team's shape survives, but the import still lands every bot grant-less....(bot.connectorTools ? { connectorTools: structuredClone(bot.connectorTools) } : {}),@@ -185,7 +185,7 @@ export function importTeamBackup(store: Store, routines: RoutineManager, input:name: takeImportName(source.name, takenNames), title: source.title, description: source.description, soul: source.soul,color: source.color, mascotExpression: source.mascotExpression,mascotBody: botBodyId(source.mascotBody),- mascotFaceColor: source.mascotFaceColor,+ mascotFaceColor: source.mascotFaceColor, mascotBodyColor: source.mascotBodyColor,modelSelection: selection, section: sectionFor(source.section),// who may see the imported team is the importing admin's choice...(options.visibility ? { visibility: options.visibility } : {}),diff --git a/shared/bot-body.test.ts b/shared/bot-body.test.tsindex 4f7b208499..ba0db29415 100644--- a/shared/bot-body.test.ts+++ b/shared/bot-body.test.ts@@ -1,13 +1,15 @@import { describe, expect, it } from "vitest";-import { BOT_BODY_IDS, FESTIVAL_IDS, FESTIVALS, botBodyId, botBodySchema, isCarvedBody, isFestival } from "./bot-body.ts";+import { BOT_BODY_IDS, FESTIVAL_IDS, FESTIVALS, botBodyId, botBodySchema, isCarvedBody, isFestival, isObjectBody } from "./bot-body.ts";import { CARVED_BODY_IDS } from "./carved-bodies.ts";import { MASCOT_BODY_IDS } from "./mascot-bodies.ts";+import { OBJECT_BODY_IDS } from "./object-bodies.ts";import { MAUS_COLOR_NAMES } from "./wire.ts";describe("bot bodies", () => {- it("accepts every gradient body and every festival body", () => {- expect(BOT_BODY_IDS).toEqual([...MASCOT_BODY_IDS, ...CARVED_BODY_IDS]);+ it("accepts every gradient body, every festival body and every object body", () => {+ expect(BOT_BODY_IDS).toEqual([...MASCOT_BODY_IDS, ...CARVED_BODY_IDS, ...OBJECT_BODY_IDS]);+ expect(new Set(BOT_BODY_IDS).size).toBe(BOT_BODY_IDS.length);for (const id of BOT_BODY_IDS) expect(botBodySchema.safeParse(id).success).toBe(true);});@@ -24,6 +26,9 @@ describe("bot bodies", () => {expect(isCarvedBody("jalebi")).toBe(true);expect(isCarvedBody("cursor")).toBe(false);expect(isCarvedBody(null)).toBe(false);+ expect(isCarvedBody("obj-ghost")).toBe(false);+ expect(isObjectBody("obj-ghost")).toBe(true);+ expect(isObjectBody("ghost")).toBe(false);});it("splits the festival bodies between the festivals, one pack each", () => {diff --git a/shared/new-bot-defaults.ts b/shared/new-bot-defaults.tsindex 5ff98abc8d..5ae1f616ce 100644--- a/shared/new-bot-defaults.ts+++ b/shared/new-bot-defaults.ts@@ -5,7 +5,7 @@ import type { ToolScope } from "./tool-scope";/** Data shared by the default template and an individual creation draft. */export type BotDefaultsProfile = Partial<Pick<WireBot,"name" | "title" | "description" | "soul" | "notifications" | "avatarUrl" | "avatarCrop" |- "mascotBody" | "mascotFaceColor" | "color" | "voice" | "speakReplies" | "section" | "modelSelection" |+ "mascotBody" | "mascotFaceColor" | "mascotBodyColor" | "color" | "voice" | "speakReplies" | "section" | "modelSelection" |"cloudBackend" | "autoStartVps" | "approvalMode" | "alwaysAllow" | "chiefOfStaff" |"managedSections" | "composio" | "browser" | "voiceNotes">> & {diff --git a/shared/object-bodies.test.ts b/shared/object-bodies.test.tsnew file mode 100644index 0000000000..009b085e26--- /dev/null+++ b/shared/object-bodies.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vitest";++import { validateAvatar } from "../packages/phone-protocol/src/open-bot-avatar/validate.ts";+import { MASCOT_BODY_IDS } from "./mascot-bodies.ts";+import { OBJECT_BODIES, OBJECT_BODY_IDS, SHAPE_BODIES, engineBody } from "./object-bodies.ts";++describe("object bodies", () => {+ it("holds a valid definition under each id, named for it", () => {+ expect(Object.keys(OBJECT_BODIES)).toEqual([...OBJECT_BODY_IDS]);+ for (const id of OBJECT_BODY_IDS) {+ const definition = OBJECT_BODIES[id];+ expect(id).toBe(`obj-${definition.id}`);+ const result = validateAvatar(definition);+ expect(result.ok ? [] : result.errors).toEqual([]);+ }+ });++ it("carries every starter and gallery avatar once, leaving Shield and Star to our shapes", () => {+ expect(OBJECT_BODY_IDS).toHaveLength(21);+ expect(new Set(OBJECT_BODY_IDS).size).toBe(21);+ expect(OBJECT_BODY_IDS).not.toContain("obj-shield");+ });++ it("draws every shape but the cursor with a valid definition", () => {+ expect(Object.keys(SHAPE_BODIES).sort()).toEqual(MASCOT_BODY_IDS.filter((id) => id !== "cursor").sort());+ for (const definition of Object.values(SHAPE_BODIES)) {+ const result = validateAvatar(definition);+ expect(result.ok ? [] : result.errors).toEqual([]);+ }+ });++ it("finds an engine definition only for engine bodies", () => {+ expect(engineBody("circle")?.id).toBe("circle");+ expect(engineBody("obj-mug")?.id).toBe("mug");+ for (const id of ["cursor", "pumpkin", "toString", "constructor", 3, null]) expect(engineBody(id)).toBeUndefined();+ });+});diff --git a/shared/object-bodies.ts b/shared/object-bodies.tsnew file mode 100644index 0000000000..40a77aafa4--- /dev/null+++ b/shared/object-bodies.ts@@ -0,0 +1 @@+export * from "../packages/phone-protocol/src/object-bodies.ts";diff --git a/shared/team-backup.ts b/shared/team-backup.tsindex e438a86152..332d28e3fa 100644--- a/shared/team-backup.ts+++ b/shared/team-backup.ts@@ -1,5 +1,5 @@import { z } from "zod";-import { mascotFaceColorSchema } from "./bot-avatar.ts";+import { mascotBodyColorSchema, mascotFaceColorSchema } from "./bot-avatar.ts";import { CONNECTOR_SLUG_PATTERN, CONNECTOR_TOOL_NAME_PATTERN, MAUS_COLOR_NAMES } from "./wire.ts";import { parseToolScope, type ToolScope } from "./tool-scope.ts";@@ -122,6 +122,7 @@ const backupSchema = z.object({mascotExpression: z.string().max(80).optional(),mascotBody: z.string().max(40).optional(),mascotFaceColor: mascotFaceColorSchema.optional(),+ mascotBodyColor: mascotBodyColorSchema.optional(),chiefOfStaff: z.boolean(),hidden: z.boolean(),playbooks: z.array(playbook).max(200),diff --git a/src/components/AskCard.tsx b/src/components/AskCard.tsxindex ecb2f4f50b..84bf48d3e8 100644--- a/src/components/AskCard.tsx+++ b/src/components/AskCard.tsx@@ -10,7 +10,7 @@ import { BotAvatar } from "./Avatar";import { ELEVATED_CARD, ELEVATED_FLOAT } from "./elevated";/** The bot a card asks for: its face and name lead the card. */-export type Asker = Pick<Bot, "name" | "color"> & Partial<Pick<Bot, "avatarUrl" | "avatarCrop" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "mascotBody" | "mascotFaceColor">>;+export type Asker = Pick<Bot, "name" | "color"> & Partial<Pick<Bot, "avatarUrl" | "avatarCrop" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor">>;export function AskHeader({ asker, line, origin }: { asker: Asker; line: string; origin?: { label: string; hint: string; open(): void } }) {return (diff --git a/src/components/Avatar.test.ts b/src/components/Avatar.test.tsindex 177b92b881..ff07ce26b2 100644--- a/src/components/Avatar.test.ts+++ b/src/components/Avatar.test.ts@@ -25,9 +25,16 @@ describe("MausAvatar body", () => {expect(render({})).toContain(MASCOT_BODIES.cursor.fit);});- it("wears the body it is given", () => {- const markup = render({ bodyId: "star" });- expect(markup).toContain(MASCOT_BODIES.star.fit);+ it("draws every shape but the cursor with the Open Bot Avatar engine", () => {+ expect(render({ bodyId: "star" })).toContain('data-object-body="star"');+ expect(render({ bodyId: "circle" })).toContain('data-object-body="circle"');+ expect(render({})).not.toContain("data-object-body");+ });++ it("paints the cursor in a gradient of its custom colour", () => {+ const stops = (markup: string) => [...markup.matchAll(/stop-color="([^"]+)"/g)].map((m) => m[1]);+ expect(stops(render({ bodyColor: "#123456" }))).toContain("#123456");+ expect(stops(render({ bodyColor: "not a colour" }))).not.toContain("not a colour");});it("falls back to the cursor for an unknown body", () => {@@ -38,8 +45,8 @@ describe("MausAvatar body", () => {);});- it("paints the body with the per-bot gradient, never a flat black fill", () => {- const markup = render({ bodyId: "circle" });+ it("paints the cursor with the per-bot gradient, never a flat black fill", () => {+ const markup = render({});expect(markup).not.toContain('fill="#000000"');expect(markup).not.toContain("{{GRADIENT}}");expect(markup).toContain("url(#");@@ -49,7 +56,7 @@ describe("MausAvatar body", () => {describe("mascot facial feature colors", () => {it.each(["white", "black"] as const)("uses %s for both eyes and mouth on every body type", (mascotFaceColor) => {const ink = mascotFaceColor === "white" ? "#ffffff" : "#000000";- for (const mascotBody of ["cursor", "star", "pumpkin", "vampire"] as const) {+ for (const mascotBody of ["cursor", "pumpkin", "vampire"] as const) {for (const color of ["green", "chrome"] as const) {const markup = renderBot({ color, mascotBody, mascotFaceColor });expect(markup).toContain(`fill="${ink}"`);@@ -116,10 +123,11 @@ describe("BotAvatar's two avatar outcomes", () => {});describe("theme hooks on faces", () => {- it("marks a bot's picture, its gradient mascot and its carved mascot, and leaves a decorative mascot unmarked", () => {+ it("marks a bot's picture, its gradient, carved and object mascots, and leaves a decorative mascot unmarked", () => {expect(renderBot({ avatarUrl: "/api/attachments/a.png", avatarCrop: "circle" })).toMatch(/<span data-avatar="picture" data-avatar-kind="bot"/);expect(renderBot({})).toMatch(/<span data-avatar="mascot" data-avatar-kind="bot"/);expect(renderBot({ mascotBody: "ghost" })).toMatch(/<span data-avatar="mascot" data-avatar-kind="bot"/);+ expect(renderBot({ mascotBody: "obj-ghost" })).toMatch(/<span data-avatar="mascot" data-avatar-kind="bot"/);expect(render({})).not.toContain("data-avatar");});diff --git a/src/components/Avatar.tsx b/src/components/Avatar.tsxindex 033cf97346..51d6db6864 100644--- a/src/components/Avatar.tsx+++ b/src/components/Avatar.tsx@@ -13,12 +13,14 @@ import { CHROME_EYES, CHROME_GRADIENT, MAUS_COLORS, type MausColor, type MausMotimport { CursorAvatar, type CursorAvatarHandle } from "./CursorAvatar";import { ACTIVE_STATES } from "./mascot-motion";import { MOTION_BEAT_MS } from "./mascot-beat";-import { avatarCropRadius, botAvatarProfile, clampAvatarFocus, clampAvatarZoom, mascotFaceInk, type BotAvatarCrop, type MascotFaceColor } from "../../shared/bot-avatar";+import { avatarCropRadius, botAvatarProfile, clampAvatarFocus, clampAvatarZoom, mascotBodyColorSchema, mascotFaceInk, type BotAvatarCrop, type MascotFaceColor } from "../../shared/bot-avatar";import { MASCOT_BODIES, botMascotBody } from "../../shared/mascot-bodies";import { isCarvedBody, type BotBodyId } from "../../shared/bot-body";+import { engineBody } from "../../shared/object-bodies";import { useFestivalDress, wornBody } from "@/lib/festival-dress";import { t } from "@/lib/i18n";-import { CarvedAvatar } from "./CarvedAvatar";+import { CarvedAvatar, vivid } from "./CarvedAvatar";+import { ObjectAvatar } from "./ObjectAvatar";import { steelBodyImage } from "@/lib/steel-body";export const EYE_SCALE = 1.12;@@ -59,12 +61,15 @@ function mix(hex: string, toward: string, t: number): string {.join("")}`;}-const gradientFor = (color: MausColor): [string, string, string] => {- if (color === "chrome") return CHROME_GRADIENT;- const fill = MAUS_COLORS[color] ?? MAUS_COLORS.green;+const gradientFor = (color: MausColor, custom?: string): [string, string, string] => {+ if (!custom && color === "chrome") return CHROME_GRADIENT;+ const fill = custom ?? MAUS_COLORS[color] ?? MAUS_COLORS.green;return [mix(fill, "#ffffff", 0.55), fill, mix(fill, "#000000", 0.42)];};+/** A bot's own body colour when it picked one, else undefined. */+const customFill = (value: unknown): string | undefined => mascotBodyColorSchema.safeParse(value).data;+const roomGradients = new Map<MausColor, [string, string, string]>();/** One array per colour, so a memoised mascot drawn with it does not draw again. */@@ -101,6 +106,8 @@ export type MausAvatarProps = {bodyId?: BotBodyId;gradient?: [string, string, string];faceColor?: MascotFaceColor | null;+ /** A custom `#rrggbb` body colour; it wins over `color` for the body only. */+ bodyColor?: string | null;/** Whose face this is; a decorative mascot has none. */kind?: AvatarKind;};@@ -126,6 +133,22 @@ function MausAvatarComponent(props: MausAvatarProps, ref: React.Ref<MausAvatarHa/>);}+ const definition = engineBody(bodyId);+ if (definition) {+ return (+ <ObjectAvatar+ definition={definition}+ fill={customFill(props.bodyColor) ?? vivid(MAUS_COLORS[color] ?? MAUS_COLORS.green)}+ faceColor={props.faceColor}+ size={size}+ state={state}+ trackPointer={trackPointer}+ animated={animated}+ label={label}+ kind={kind}+ />+ );+ }return <GradientAvatar ref={ref} {...props} />;}@@ -151,12 +174,15 @@ function GradientAvatarComponent(bodyId,gradient,faceColor,+ bodyColor,kind,}: MausAvatarProps,ref: React.Ref<MausAvatarHandle>,) {const silhouette = MASCOT_BODIES[botMascotBody(bodyId)];- const chrome = color === "chrome";+ const custom = customFill(bodyColor);+ const chrome = color === "chrome" && !custom;+ const paint = custom ? gradientFor(color, custom) : gradient ?? gradientFor(color);const faceInk = mascotFaceInk(faceColor);const inner = useRef<CursorAvatarHandle>(null);useImperativeHandle(ref, () => ({@@ -191,7 +217,7 @@ function GradientAvatarComponent(expression={expression}size={size}silhouette={silhouette}- gradient={gradient ?? gradientFor(color)}+ gradient={paint}picture={chrome && !faceInk ? steelBodyImage(silhouette.id, size, globalThis.devicePixelRatio ?? 1) : null}eyeColor={faceInk ?? (chrome ? CHROME_EYES : undefined)}title={label ?? null}@@ -225,6 +251,7 @@ export type BotAvatarProps = Omit<MausAvatarProps, "color" | "gradient"> & {avatarFocusY?: number;mascotBody?: BotBodyId | null;mascotFaceColor?: MascotFaceColor | null;+ mascotBodyColor?: string | null;};};@@ -263,6 +290,7 @@ export function BotAvatar({ bot, size = 44, label, readable = false, ...mascotPr{...mascotProps}color={bot.color}faceColor={bot.mascotFaceColor}+ bodyColor={bot.mascotBodyColor}gradient={readable ? roomAvatarGradient(bot.color) : undefined}size={size}label={label ?? bot.name}diff --git a/src/components/AvatarCredit.tsx b/src/components/AvatarCredit.tsxnew file mode 100644index 0000000000..4a4d29cab1--- /dev/null+++ b/src/components/AvatarCredit.tsx@@ -0,0 +1,21 @@+import { openExternalLink } from "@/lib/app-links";+import { t } from "@/lib/i18n";++const OPEN_BOT_AVATAR = "https://github.com/DominikScholz/open-bot-avatar";++/** Credit for the avatar shapes and engine we use from Open Bot Avatar (MIT). */+export function AvatarCredit() {+ return (+ <a+ href={OPEN_BOT_AVATAR}+ onClick={(event) => {+ event.preventDefault();+ void openExternalLink(OPEN_BOT_AVATAR);+ }}+ data-avatar-credit+ className="mx-auto mt-2 block w-fit text-center text-[11px] text-ink-tertiary hover:text-ink-secondary hover:underline"+ >+ {t("mascot.avatarCredit")}+ </a>+ );+}diff --git a/src/components/BotProfileAvatarCard.tsx b/src/components/BotProfileAvatarCard.tsxindex 09cfd23b3c..d96de58d96 100644--- a/src/components/BotProfileAvatarCard.tsx+++ b/src/components/BotProfileAvatarCard.tsx@@ -11,13 +11,14 @@ import {type MausState,} from "@/lib/mascot";import { BOT_AVATAR_CROPS } from "../../shared/bot-avatar";-import { MASCOT_BODY_IDS } from "../../shared/mascot-bodies";-import { FESTIVAL_IDS, FESTIVALS, type BotBodyId } from "../../shared/bot-body";+import { EVERYDAY_BODY_IDS, FESTIVAL_IDS, FESTIVALS, type BotBodyId } from "../../shared/bot-body";import { BotAvatar, MausAvatar } from "./Avatar";import { AvatarImageGenerator } from "./AvatarImageGenerator";import { AvatarFraming, OrganizationAvatarIcons, RESET_MASCOT_PATCH, useAvatarImage, type AvatarPatch } from "./avatar-editing";import { t } from "@/lib/i18n";import { bodyName, colorName, expressionName, festivalName } from "@/lib/mascot-names";+import { MascotBodyColorSwatch } from "./MascotBodyColorSwatch";+import { AvatarCredit } from "./AvatarCredit";import { MascotFaceColorPicker } from "./MascotFaceColorPicker";export function BotProfileAvatarCard({@@ -137,7 +138,7 @@ export function BotProfileAvatarCard({title={expressionName(expression)}aria-label={t("mascot.useExpression", { expression: expressionName(expression) })}>- <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyId={bot.mascotBody ?? undefined} state={expression} size={42} animated={false} />+ <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyColor={bot.mascotBodyColor} bodyId={bot.mascotBody ?? undefined} state={expression} size={42} animated={false} /></button>))}</div>@@ -153,17 +154,25 @@ export function BotProfileAvatarCard({key={color}type="button"disabled={busy}- aria-pressed={bot.color === color}- onClick={() => onPatch({ color })}+ aria-pressed={!bot.mascotBodyColor && bot.color === color}+ onClick={() => onPatch({ color, ...(bot.mascotBodyColor ? { mascotBodyColor: null } : {}) })}className={cn("size-10 rounded-full border-2 border-transparent transition-transform hover:scale-110 disabled:opacity-50",- bot.color === color && "ring-2 ring-accent-border ring-offset-2 ring-offset-card",+ !bot.mascotBodyColor && bot.color === color && "ring-2 ring-accent-border ring-offset-2 ring-offset-card",)}style={{ background: colorSwatch(color) }}title={t(MAUS_COLOR_LABEL[color])}aria-label={t("mascot.useColor", { color: colorName(color) })}/>))}+ <MascotBodyColorSwatch+ bot={bot}+ disabled={busy}+ onPatch={onPatch}+ className="size-10 transition-transform hover:scale-110"+ selectedClassName="ring-2 ring-accent-border ring-offset-2 ring-offset-card"+ holeClassName="bg-card"+ /></div>{crop === "mascot" && (@@ -172,10 +181,11 @@ export function BotProfileAvatarCard({{t("botIdentity.body")}</div><div className="grid grid-cols-5 gap-1.5">- {MASCOT_BODY_IDS.map((id) => (+ {EVERYDAY_BODY_IDS.map((id) => (<BodyButton key={id} id={id} name={bodyName(id)} bot={bot} busy={busy} onPatch={onPatch} />))}</div>+ <AvatarCredit />{FESTIVAL_IDS.map((festival) => (<div key={festival}><div className="mb-2 mt-4 text-[12px] font-medium uppercase tracking-[0.08em] text-ink-secondary">@@ -224,7 +234,7 @@ function BodyButton({ id, name, bot, busy, onPatch }: {selected ? "bg-control text-ink" : "text-ink-secondary hover:bg-control/60",)}>- <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyId={id} size={34} animated={false} trackPointer={false} />+ <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyColor={bot.mascotBodyColor} bodyId={id} size={34} animated={false} trackPointer={false} /></button>);}diff --git a/src/components/BotSettingsDialog.simple.test.ts b/src/components/BotSettingsDialog.simple.test.tsindex e36c13aead..1f7436ec69 100644--- a/src/components/BotSettingsDialog.simple.test.ts+++ b/src/components/BotSettingsDialog.simple.test.ts@@ -6,6 +6,7 @@ import type { Routine } from "@/lib/routines";import type { MemoryDoc } from "@/lib/memory";import type { Bot, BotSettingsSection, InstanceInfo } from "@/state/store";import { AVATAR_FOCUS_CENTER, AVATAR_ZOOM_MIN } from "../../shared/bot-avatar";+import { EVERYDAY_BODY_IDS } from "../../shared/bot-body";import type { ManagedSkill } from "./bot-settings/SkillsSection";import type { McpServerSummary } from "@/lib/mcp-servers";import type { BotApps } from "./bot-settings/useBotApps";@@ -149,6 +150,7 @@ const { SignedInSites } = await import("./SignedInSites");const { AvatarImageGenerator } = await import("./AvatarImageGenerator");const { AvatarFraming } = await import("./avatar-editing");const { MascotFaceColorPicker } = await import("./MascotFaceColorPicker");+const { MascotBodyColorSwatch } = await import("./MascotBodyColorSwatch");const { Switch } = await import("./SettingsPrimitives");const { OrgSkillsCard } = await import("./bot-settings/OrgSkillsCard");const { PackageProvenance } = await import("./bot-settings/PackageProvenance");@@ -510,10 +512,10 @@ describe("the hero", () => {describe("the avatar editor", () => {const editor = (bot: Bot) => capture(() => AvatarEditorCard({ bot, activeState: "idle", onPatch: patch, onClose }));- it("shows the ten bodies and twelve colors, with the festival bodies and the faces behind More looks", () => {+ it("shows the shapes and objects and twelve colors, with the festival bodies and the faces behind More looks", () => {const bot = makeBot();const rendered = editor(bot);- expect(rendered.html.match(/aria-label="Use the \w+ body"/g)).toHaveLength(10);+ expect(rendered.html.match(/aria-label="Use the [\w ]+ body"/g)).toHaveLength(EVERYDAY_BODY_IDS.length);expect(rendered.html.match(/aria-label="Use \w+ mascot color"/g)).toHaveLength(12);expect(rendered.html).not.toContain(">Halloween<");expect(rendered.html).not.toContain(">Diwali<");@@ -536,7 +538,7 @@ describe("the avatar editor", () => {click(more);const open = editor(bot);expect(find(open, "data-avatar-more").props["aria-expanded"]).toBe(true);- expect(open.html.match(/aria-label="Use the [\w ]+ body"/g)).toHaveLength(30);+ expect(open.html.match(/aria-label="Use the [\w ]+ body"/g)).toHaveLength(EVERYDAY_BODY_IDS.length + 20);expect(open.html).toContain(">Halloween<");expect(open.html).toContain(">Diwali<");click(find(open, "aria-label", "Use the Pumpkin body"));@@ -568,7 +570,28 @@ describe("the avatar editor", () => {it("resets the mascot as the Advanced card does", () => {click(find(editor(makeBot()), "data-avatar-reset"));- expect(patch).toHaveBeenLastCalledWith({ avatarCrop: "mascot", color: "green", mascotExpression: null, mascotBody: "cursor", mascotFaceColor: null });+ expect(patch).toHaveBeenLastCalledWith({ avatarCrop: "mascot", color: "green", mascotExpression: null, mascotBody: "cursor", mascotFaceColor: null, mascotBodyColor: null });+ });++ it("picks a custom body color after the swatches, and a named swatch clears it", () => {+ const plain = ofType(editor(makeBot()), MascotBodyColorSwatch)!.props as Parameters<typeof MascotBodyColorSwatch>[0];+ const unset = capture(() => MascotBodyColorSwatch(plain));+ const ring = find(unset, "data-avatar-body-color");+ expect(ring.props["aria-pressed"]).toBe(false);+ expect(ring.props["aria-label"]).toBe("Pick a custom body color");+ const input = find(unset, "type", "color");+ expect(input.props.value).toBe("#009957");+ (input.props.onChange as (event: { target: { value: string } }) => void)({ target: { value: "#12AB9F" } });+ expect(patch).toHaveBeenLastCalledWith({ mascotBodyColor: "#12ab9f" });++ fresh();+ const tinted = editor(makeBot({ mascotBodyColor: "#12ab9f" }));+ expect(find(tinted, "aria-label", "Use green mascot color").props["aria-pressed"]).toBe(false);+ const set = capture(() => MascotBodyColorSwatch(ofType(tinted, MascotBodyColorSwatch)!.props as Parameters<typeof MascotBodyColorSwatch>[0]));+ expect(find(set, "data-avatar-body-color").props["aria-pressed"]).toBe(true);+ expect(find(set, "type", "color").props.value).toBe("#12ab9f");+ click(find(tinted, "aria-label", "Use green mascot color"));+ expect(patch).toHaveBeenLastCalledWith({ color: "green", mascotBodyColor: null });});it("edits facial feature color without changing body color or expression", () => {diff --git a/src/components/MascotBodyColorSwatch.tsx b/src/components/MascotBodyColorSwatch.tsxnew file mode 100644index 0000000000..25952996b5--- /dev/null+++ b/src/components/MascotBodyColorSwatch.tsx@@ -0,0 +1,56 @@+import { useRef } from "react";++import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { MAUS_COLORS } from "@/lib/mascot";+import type { Bot } from "@/state/store";+import type { AvatarPatch } from "./avatar-editing";++const RAINBOW = "conic-gradient(#ff3b30, #ff9500, #ffcc00, #34c759, #00c7be, #007aff, #af52de, #ff2d55, #ff3b30)";++/** The last colour swatch: a rainbow ring that opens the system colour picker and tints only the avatar body. */+export function MascotBodyColorSwatch({ bot, disabled, onPatch, className, selectedClassName, holeClassName }: {+ bot: Pick<Bot, "color" | "mascotBodyColor">;+ disabled: boolean;+ onPatch: (patch: AvatarPatch) => void;+ /** Size of the swatch, matching the named swatches beside it. */+ className: string;+ /** The ring the selected named swatch wears. */+ selectedClassName: string;+ /** The surface behind the swatch, shown inside the ring until a colour is picked. */+ holeClassName: string;+}) {+ const input = useRef<HTMLInputElement>(null);+ const custom = bot.mascotBodyColor;+ const open = () => {+ const picker = input.current;+ if (!picker) return;+ try { picker.showPicker(); } catch { picker.click(); }+ };+ return (+ <>+ <button+ type="button"+ data-avatar-body-color+ disabled={disabled}+ aria-pressed={Boolean(custom)}+ aria-label={t("mascot.useCustomColor")}+ title={t("mascot.useCustomColor")}+ onClick={open}+ className={cn("rounded-full p-[3px] disabled:opacity-50", className, custom && selectedClassName)}+ style={{ background: RAINBOW }}+ >+ <span className={cn("block size-full rounded-full", !custom && holeClassName)} style={custom ? { background: custom } : undefined} />+ </button>+ <input+ ref={input}+ type="color"+ tabIndex={-1}+ aria-hidden="true"+ className="sr-only"+ value={custom ?? MAUS_COLORS[bot.color].toLowerCase()}+ onChange={(event) => onPatch({ mascotBodyColor: event.target.value.toLowerCase() })}+ />+ </>+ );+}diff --git a/src/components/ObjectAvatar.dom.test.ts b/src/components/ObjectAvatar.dom.test.tsnew file mode 100644index 0000000000..f262da8a08--- /dev/null+++ b/src/components/ObjectAvatar.dom.test.ts@@ -0,0 +1,79 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot } from "react-dom/client";+import { describe, expect, it, vi } from "vitest";++import { MAUS_STATES, type MausState } from "@/lib/mascot";+import { MausAvatar } from "./Avatar";+import { objectLook } from "./ObjectAvatar";++describe("objectLook", () => {+ it.each<[MausState, ReturnType<typeof objectLook>]>([+ ["idle", { state: "idle", mood: "neutral" }],+ ["thinking", { state: "thinking", mood: "neutral" }],+ ["writing", { state: "working", mood: "neutral" }],+ ["searching", { state: "working", mood: "neutral" }],+ ["alerting", { state: "waiting", mood: "neutral" }],+ ["sad", { state: "blocked", mood: "neutral" }],+ ["celebrate", { state: "done", mood: "neutral" }],+ ["laughing", { state: "idle", mood: "happy" }],+ ["sleeping", { state: "idle", mood: "neutral" }],+ ])("shows %s as %o", (state, expected) => {+ expect(objectLook(state)).toEqual(expected);+ });++ it("gives every mascot state a look", () => {+ for (const state of MAUS_STATES) expect(objectLook(state).state).toBeTypeOf("string");+ });+});++describe("an object body", () => {+ it("draws the avatar in the bot's colour, labelled, and clears it when unmounted", async () => {+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ flushSync(() => root.render(createElement(MausAvatar, { bodyId: "obj-mug", color: "blue", animated: false, label: "Mugsy", size: 64 })));+ const avatar = host.querySelector<HTMLElement>("[data-object-body='mug']")!;+ await vi.waitFor(() => expect(avatar.querySelector("svg")).not.toBeNull());+ expect(avatar.getAttribute("role")).toBe("img");+ expect(avatar.getAttribute("aria-label")).toBe("Mugsy");+ expect(avatar.style.width).toBe("64px");+ flushSync(() => root.unmount());+ expect(avatar.childElementCount).toBe(0);+ });++ it("paints a shape in the bot's custom colour", async () => {+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ flushSync(() => root.render(createElement(MausAvatar, { bodyId: "circle", color: "blue", bodyColor: "#123456", animated: false, size: 64 })));+ const avatar = host.querySelector<HTMLElement>("[data-object-body='circle']")!;+ await vi.waitFor(() => expect(avatar.innerHTML).toContain('fill="#123456"'));+ flushSync(() => root.unmount());+ });++ it("celebrates once with the ribbon cage when it finishes working, then rests", () => {+ vi.useFakeTimers();+ try {+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ const show = (state: MausState) => act(() => root.render(createElement(MausAvatar, { bodyId: "obj-mug", color: "blue", state, size: 64 })));+ const shown = () => host.querySelector<HTMLElement>("[data-object-body]")!.dataset.objectState;+ show("idle");+ expect(shown()).toBe("idle");+ show("working");+ expect(shown()).toBe("working");+ show("idle");+ expect(shown()).toBe("done");+ act(() => vi.advanceTimersByTime(5000));+ expect(shown()).toBe("idle");+ show("sleeping");+ expect(shown()).toBe("idle");+ act(() => root.unmount());+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/src/components/ObjectAvatar.tsx b/src/components/ObjectAvatar.tsxnew file mode 100644index 0000000000..238e3d2b9d--- /dev/null+++ b/src/components/ObjectAvatar.tsx@@ -0,0 +1,104 @@+import { memo, useEffect, useRef, useState } from "react";+import type { MausState } from "@/lib/mascot";+import { avatarMarks, type AvatarKind } from "@/lib/avatar-marks";+import { mascotFaceInk, type MascotFaceColor } from "../../shared/bot-avatar";+import { mountAvatar, type AvatarOptions, type MountedAvatar } from "../../packages/phone-protocol/src/open-bot-avatar/dom/index.ts";+import type { AvatarDefinition, AvatarMood, AvatarState } from "../../packages/phone-protocol/src/open-bot-avatar/types.ts";+import { DONE_TURN_S } from "../../packages/phone-protocol/src/open-bot-avatar/motion.ts";+import { usePrefersReducedMotion } from "./mascot-clock";+import { ACTIVE_STATES } from "./mascot-motion";++export type ObjectLook = { state: AvatarState; mood: AvatarMood };++const look = (state: AvatarState, mood: AvatarMood = "neutral"): ObjectLook => ({ state, mood });+const IDLE = look("idle");+const WORKING = look("working");+const WAITING = look("waiting");+const HAPPY = look("idle", "happy");+const DONE = look("done");++const LOOKS: Partial<Record<MausState, ObjectLook>> = {+ thinking: look("thinking"),+ working: WORKING, writing: WORKING, loading: WORKING, searching: WORKING, radar: WORKING, orbit: WORKING,+ progress: WORKING, uploading: WORKING, sending: WORKING, receiving: WORKING,+ alerting: WAITING, notifying: WAITING,+ sad: look("blocked"),+ celebrate: DONE,+ happy: HAPPY, laughing: HAPPY, proud: HAPPY, playful: HAPPY,+};++export const objectLook = (state: MausState): ObjectLook => LOOKS[state] ?? IDLE;++/** How long a bot celebrates after it finishes: one Done turn of the ribbon cage, and its settle. */+const CHEER_MS = DONE_TURN_S * 1000 + 300;++/** True for one celebration after the bot goes from thinking or working back to idle. */+function useFinishCheer(state: MausState): boolean {+ const [cheering, setCheering] = useState(false);+ const was = useRef(state);+ useEffect(() => {+ const before = objectLook(was.current).state;+ was.current = state;+ if (objectLook(state).state !== "idle" || (before !== "working" && before !== "thinking")) return;+ setCheering(true);+ const timer = setTimeout(() => setCheering(false), CHEER_MS);+ return () => {+ clearTimeout(timer);+ setCheering(false);+ };+ }, [state]);+ return cheering;+}++export type ObjectAvatarProps = {+ /** Engine definition: an Open Bot Avatar object or one of our shapes. */+ definition: AvatarDefinition;+ /** Body colour as a hex. */+ fill: string;+ faceColor?: MascotFaceColor | null;+ size?: number;+ state?: MausState;+ trackPointer?: boolean;+ animated?: boolean;+ label?: string;+ kind?: AvatarKind;+};++function ObjectAvatarComponent({ definition, fill, faceColor, size = 44, state = "idle", trackPointer = true, animated, label, kind }: ObjectAvatarProps) {+ const reduced = usePrefersReducedMotion();+ const cheering = useFinishCheer(state);+ const live = !reduced && (animated ?? (ACTIVE_STATES.has(state) || cheering));+ const shown = cheering && live ? DONE : objectLook(state);+ const options: AvatarOptions = {+ definition,+ color: fill,+ eyeColor: mascotFaceInk(faceColor),+ followPointer: trackPointer,+ still: !live,+ label: label ?? "",+ ...shown,+ };+ const host = useRef<HTMLSpanElement>(null);+ const avatar = useRef<MountedAvatar | null>(null);+ useEffect(() => {+ const mounted = mountAvatar(host.current!, options);+ avatar.current = mounted;+ return () => {+ mounted.destroy();+ avatar.current = null;+ };+ }, []);+ useEffect(() => avatar.current?.update(options));+ return (+ <span+ {...avatarMarks(kind, "mascot")}+ ref={host}+ className="inline-block shrink-0"+ style={{ width: size, height: size }}+ data-object-body={definition.id}+ data-object-state={shown.state}+ />+ );+}++export const ObjectAvatar = memo(ObjectAvatarComponent);diff --git a/src/components/OtherPlaceBots.tsx b/src/components/OtherPlaceBots.tsxindex d80ee1a6b1..9fd70c5acf 100644--- a/src/components/OtherPlaceBots.tsx+++ b/src/components/OtherPlaceBots.tsx@@ -3,7 +3,7 @@import { useState } from "react";import { Cloud } from "lucide-react";import { BOT_BODY_IDS, type BotBodyId } from "../../shared/bot-body";-import { MASCOT_FACE_COLORS, type MascotFaceColor } from "../../shared/bot-avatar";+import { MASCOT_FACE_COLORS, mascotBodyColorSchema, type MascotFaceColor } from "../../shared/bot-avatar";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useAdvancedMode } from "@/lib/interface-mode";@@ -41,7 +41,8 @@ function avatarOf(row: PlaceBotRow) {const color = (MAUS_COLOR_NAMES as readonly string[]).includes(row.color ?? "") ? row.color as MausColor : "green";const body = (BOT_BODY_IDS as readonly string[]).includes(row.mascotBody ?? "") ? row.mascotBody as BotBodyId : null;const face = (MASCOT_FACE_COLORS as readonly string[]).includes(row.mascotFaceColor ?? "") ? row.mascotFaceColor as MascotFaceColor : null;- return { name: row.name, color, mascotBody: body, mascotFaceColor: face };+ const tint = mascotBodyColorSchema.safeParse(row.mascotBodyColor).data ?? null;+ return { name: row.name, color, mascotBody: body, mascotFaceColor: face, mascotBodyColor: tint };}function OtherPlaceBotRow({ row, dim, iconOnly, simple }: { row: PlaceBotRow; dim: boolean; iconOnly: boolean; simple: boolean }) {diff --git a/src/components/avatar-editing.tsx b/src/components/avatar-editing.tsxindex 30f9713324..8fa7473b8f 100644--- a/src/components/avatar-editing.tsx+++ b/src/components/avatar-editing.tsx@@ -18,10 +18,10 @@ import { useBotEditor } from "./bot-settings/BotEditorContext";import { useStoreActions } from "@/state/store-select";export type AvatarPatch = Partial<- Pick<Bot, "avatarCrop" | "avatarUrl" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor">+ Pick<Bot, "avatarCrop" | "avatarUrl" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor">>;-export const RESET_MASCOT_PATCH: AvatarPatch = { avatarCrop: "mascot", color: "green", mascotExpression: null, mascotBody: "cursor", mascotFaceColor: null };+export const RESET_MASCOT_PATCH: AvatarPatch = { avatarCrop: "mascot", color: "green", mascotExpression: null, mascotBody: "cursor", mascotFaceColor: null, mascotBodyColor: null };export const CROP_LABEL = {mascot: "Mascot",diff --git a/src/components/bot-panel/AvatarEditorCard.tsx b/src/components/bot-panel/AvatarEditorCard.tsxindex a971612ed2..d23b107f06 100644--- a/src/components/bot-panel/AvatarEditorCard.tsx+++ b/src/components/bot-panel/AvatarEditorCard.tsx@@ -8,14 +8,15 @@ import type { LocaleKey } from "@/locales";import { colorSwatch, MAUS_COLOR_LABEL, MAUS_COLOR_NAMES, PICKABLE_STATES, type MausState } from "@/lib/mascot";import { type Bot } from "@/state/store";import { mayRename, useTeamPeople } from "@/state/team-people";-import { MASCOT_BODY_IDS } from "../../../shared/mascot-bodies";-import { FESTIVAL_IDS, FESTIVALS, isCarvedBody, type BotBodyId } from "../../../shared/bot-body";+import { EVERYDAY_BODY_IDS, FESTIVAL_IDS, FESTIVALS, isCarvedBody, type BotBodyId } from "../../../shared/bot-body";import { useFestivalDress, wornBody } from "@/lib/festival-dress";import { MausAvatar } from "../Avatar";import { AvatarImageGenerator } from "../AvatarImageGenerator";import { AvatarFraming, OrganizationAvatarIcons, RESET_MASCOT_PATCH, useAvatarImage, type AvatarPatch } from "../avatar-editing";import { Segmented } from "./rows";import { MascotFaceColorPicker } from "../MascotFaceColorPicker";+import { MascotBodyColorSwatch } from "../MascotBodyColorSwatch";+import { AvatarCredit } from "../AvatarCredit";import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";import { useBotsApartFromTurns } from "@/state/apart-from-turns";@@ -91,7 +92,7 @@ export function AvatarEditorCard({ bot, activeState, onPatch, onClose }: {!showsImage && body === id ? "bg-ink/[0.08] ring-[1.5px] ring-inset ring-ink/25" : "hover:bg-ink/[0.05]",)}>- <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyId={id} size={40} animated={false} trackPointer={false} />+ <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyColor={bot.mascotBodyColor} bodyId={id} size={40} animated={false} trackPointer={false} /></button>);@@ -142,8 +143,9 @@ export function AvatarEditorCard({ bot, activeState, onPatch, onClose }: {{tab === "bot" && (<><div className="grid grid-cols-5 gap-1.5">- {MASCOT_BODY_IDS.map((id) => bodyButton(id, bodyName(id)))}+ {EVERYDAY_BODY_IDS.map((id) => bodyButton(id, bodyName(id)))}</div>+ <AvatarCredit />{!showsImage && othersToMatch.length > 0 && (<buttontype="button"@@ -163,17 +165,25 @@ export function AvatarEditorCard({ bot, activeState, onPatch, onClose }: {key={color}type="button"disabled={busy}- aria-pressed={bot.color === color}+ aria-pressed={!bot.mascotBodyColor && bot.color === color}aria-label={t("mascot.useColor", { color: colorName(color) })}title={t(MAUS_COLOR_LABEL[color])}- onClick={() => pickMascot({ color })}+ onClick={() => pickMascot({ color, ...(bot.mascotBodyColor ? { mascotBodyColor: null } : {}) })}className={cn("size-6 rounded-full disabled:opacity-50",- bot.color === color && "ring-2 ring-ink/80 ring-offset-2 ring-offset-menu",+ !bot.mascotBodyColor && bot.color === color && "ring-2 ring-ink/80 ring-offset-2 ring-offset-menu",)}style={{ background: colorSwatch(color) }}/>))}+ <MascotBodyColorSwatch+ bot={bot}+ disabled={busy}+ onPatch={pickMascot}+ className="size-6"+ selectedClassName="ring-2 ring-ink/80 ring-offset-2 ring-offset-menu"+ holeClassName="bg-menu"+ /></div><MascotFaceColorPicker bot={bot} disabled={busy} onPatch={pickMascot} /><buttondiff --git a/src/components/bot-settings/useBotSettingsDerived.ts b/src/components/bot-settings/useBotSettingsDerived.tsindex 492956fffb..184dc42b5f 100644--- a/src/components/bot-settings/useBotSettingsDerived.ts+++ b/src/components/bot-settings/useBotSettingsDerived.ts@@ -22,6 +22,7 @@ export type BotPatch = Partial<| "mascotExpression"| "mascotBody"| "mascotFaceColor"+ | "mascotBodyColor"| "avatarUrl"| "avatarCrop"| "avatarZoom"diff --git a/src/lib/drawn-bots.ts b/src/lib/drawn-bots.tsindex 2d17e6eeaa..49af99196e 100644--- a/src/lib/drawn-bots.ts+++ b/src/lib/drawn-bots.ts@@ -3,7 +3,7 @@ import type { Bot } from "@/state/store";const drawn = (bot: Bot) => [// title and chiefOfStaff: the @-mention menu describes each bot by them.bot.id, bot.name, bot.title, bot.chiefOfStaff, bot.hidden, bot.sidebarHidden, JSON.stringify(bot.defaultBot ?? null), bot.color, bot.mascotBody, bot.mascotExpression,- bot.mascotFaceColor, bot.avatarUrl, bot.avatarCrop, bot.avatarZoom, bot.avatarFocusX, bot.avatarFocusY,+ bot.mascotFaceColor, bot.mascotBodyColor, bot.avatarUrl, bot.avatarCrop, bot.avatarZoom, bot.avatarFocusX, bot.avatarFocusY,].join("\u0001");/** For a reader that draws other bots only by name, look and whether they are shown: a turn changing none of thatdiff --git a/src/locales/en.json b/src/locales/en.jsonindex 3fd1ed1c07..11afc7fd0a 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -8831,6 +8831,29 @@"mascot.body.hexagon": "Hexagon","mascot.body.diamond": "Diamond","mascot.body.star": "Star",+ "mascot.body.obj-controller": "Controller",+ "mascot.body.obj-barbell": "Barbell",+ "mascot.body.obj-mug": "Mug",+ "mascot.body.obj-lightbulb": "Lightbulb",+ "mascot.body.obj-chat": "Chat",+ "mascot.body.obj-sprout": "Sprout",+ "mascot.body.obj-watering-can": "Watering Can",+ "mascot.body.obj-book": "Book",+ "mascot.body.obj-brain": "Brain",+ "mascot.body.obj-bull": "Bull",+ "mascot.body.obj-bunny": "Bunny",+ "mascot.body.obj-camera": "Camera",+ "mascot.body.obj-cat": "Cat",+ "mascot.body.obj-cloud": "Cloud",+ "mascot.body.obj-egg": "Egg",+ "mascot.body.obj-ghost": "Ghost",+ "mascot.body.obj-magnifier": "Magnifier",+ "mascot.body.obj-paint-brush": "Paint Brush",+ "mascot.body.obj-palette": "Palette",+ "mascot.body.obj-rocket": "Rocket",+ "mascot.body.obj-shield": "Shield",+ "mascot.body.obj-star": "Star",+ "mascot.body.obj-witch-hat": "Witch Hat","mascot.body.pumpkin": "Pumpkin","mascot.body.ghost": "Ghost","mascot.body.witch": "Witch",@@ -8875,6 +8898,8 @@"mascot.expression.proud": "proud","mascot.useExpression": "Use {expression} expression","mascot.useColor": "Use {color} mascot color",+ "mascot.useCustomColor": "Pick a custom body color",+ "mascot.avatarCredit": "Avatar designs from Open Bot Avatar by Dominik Scholz","mascot.useBody": "Use the {name} body","mascot.label": "{name} mascot","avatar.alt": "{name} avatar",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex eaf2f0fab7..3640b9601e 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -8763,6 +8763,29 @@"mascot.body.hexagon": "Hexágono","mascot.body.diamond": "Losango","mascot.body.star": "Estrela",+ "mascot.body.obj-controller": "Controle",+ "mascot.body.obj-barbell": "Barra de peso",+ "mascot.body.obj-mug": "Caneca",+ "mascot.body.obj-lightbulb": "Lâmpada",+ "mascot.body.obj-chat": "Conversa",+ "mascot.body.obj-sprout": "Broto",+ "mascot.body.obj-watering-can": "Regador",+ "mascot.body.obj-book": "Livro",+ "mascot.body.obj-brain": "Cérebro",+ "mascot.body.obj-bull": "Touro",+ "mascot.body.obj-bunny": "Coelhinho",+ "mascot.body.obj-camera": "Câmera",+ "mascot.body.obj-cat": "Gato",+ "mascot.body.obj-cloud": "Nuvem",+ "mascot.body.obj-egg": "Ovo",+ "mascot.body.obj-ghost": "Fantasma",+ "mascot.body.obj-magnifier": "Lupa",+ "mascot.body.obj-paint-brush": "Pincel",+ "mascot.body.obj-palette": "Paleta",+ "mascot.body.obj-rocket": "Foguete",+ "mascot.body.obj-shield": "Escudo",+ "mascot.body.obj-star": "Estrela",+ "mascot.body.obj-witch-hat": "Chapéu de bruxa","mascot.body.pumpkin": "Abóbora","mascot.body.ghost": "Fantasma","mascot.body.witch": "Bruxa",@@ -8807,6 +8830,8 @@"mascot.expression.proud": "orgulhoso","mascot.useExpression": "Usar a expressão “{expression}”","mascot.useColor": "Usar a cor {color} no mascote",+ "mascot.useCustomColor": "Escolher uma cor personalizada para o corpo",+ "mascot.avatarCredit": "Designs de avatar do Open Bot Avatar, de Dominik Scholz","mascot.useBody": "Usar o corpo {name}","mascot.label": "Mascote {name}","avatar.alt": "Avatar de {name}",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 6baf99b682..5343936d7b 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -33870,6 +33870,7 @@"mascot.expression.proud": "d069c85283b98c2c0ca831cb4fd19356e98813b5d0ee31e7b7a4a894e8aca23c","mascot.useExpression": "dd100240847c42eee553f2c6a660439d8971f643b9430ca2c72c3d6e4a24ed01","mascot.useColor": "3f11f6227ed5a14383e5eecbedc6de2de19a3d4a3d2dfb17475fc9ce9743d138",+ "mascot.useCustomColor": "a793fbed8a05b52d404159493d013ca24b701823f7e4ad4378b6c2c1a85569bf","mascot.useBody": "f851fc13f2e23316287654f1d0c8965e21a629035b5ab6cc34e511bc4868b18f","mascot.label": "9c609705aed8265d50642ca3f50d42a05e04712c2336aa3141f177b130d020c8","avatar.alt": "d246bedacf25b27434ca114cfa52d0a4ecc2357470744841af3b163a02cb4478",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 4c163e3a98..52e0c2d9b5 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -7901,6 +7901,29 @@"mascot.body.hexagon": "六角形","mascot.body.diamond": "菱形","mascot.body.star": "星星",+ "mascot.body.obj-controller": "手把",+ "mascot.body.obj-barbell": "槓鈴",+ "mascot.body.obj-mug": "馬克杯",+ "mascot.body.obj-lightbulb": "燈泡",+ "mascot.body.obj-chat": "聊天",+ "mascot.body.obj-sprout": "嫩芽",+ "mascot.body.obj-watering-can": "澆水壺",+ "mascot.body.obj-book": "書",+ "mascot.body.obj-brain": "大腦",+ "mascot.body.obj-bull": "公牛",+ "mascot.body.obj-bunny": "兔子",+ "mascot.body.obj-camera": "相機",+ "mascot.body.obj-cat": "貓",+ "mascot.body.obj-cloud": "雲",+ "mascot.body.obj-egg": "蛋",+ "mascot.body.obj-ghost": "幽靈",+ "mascot.body.obj-magnifier": "放大鏡",+ "mascot.body.obj-paint-brush": "畫筆",+ "mascot.body.obj-palette": "調色盤",+ "mascot.body.obj-rocket": "火箭",+ "mascot.body.obj-shield": "盾牌",+ "mascot.body.obj-star": "星星",+ "mascot.body.obj-witch-hat": "巫師帽","mascot.body.pumpkin": "南瓜","mascot.body.ghost": "幽靈","mascot.body.witch": "女巫",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 6c833730a2..6d4415bd1a 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -9791,6 +9791,29 @@"mascot.body.hexagon": "六边形","mascot.body.diamond": "菱形","mascot.body.star": "星星",+ "mascot.body.obj-controller": "手柄",+ "mascot.body.obj-barbell": "杠铃",+ "mascot.body.obj-mug": "马克杯",+ "mascot.body.obj-lightbulb": "灯泡",+ "mascot.body.obj-chat": "聊天",+ "mascot.body.obj-sprout": "嫩芽",+ "mascot.body.obj-watering-can": "洒水壶",+ "mascot.body.obj-book": "书",+ "mascot.body.obj-brain": "大脑",+ "mascot.body.obj-bull": "公牛",+ "mascot.body.obj-bunny": "兔子",+ "mascot.body.obj-camera": "相机",+ "mascot.body.obj-cat": "猫",+ "mascot.body.obj-cloud": "云",+ "mascot.body.obj-egg": "蛋",+ "mascot.body.obj-ghost": "幽灵",+ "mascot.body.obj-magnifier": "放大镜",+ "mascot.body.obj-paint-brush": "画笔",+ "mascot.body.obj-palette": "调色板",+ "mascot.body.obj-rocket": "火箭",+ "mascot.body.obj-shield": "盾牌",+ "mascot.body.obj-star": "星星",+ "mascot.body.obj-witch-hat": "巫师帽","mascot.body.pumpkin": "南瓜","mascot.body.ghost": "幽灵","mascot.body.witch": "女巫",diff --git a/src/state/bot-patch-queue.ts b/src/state/bot-patch-queue.tsindex 24a018d5a8..d0558bb375 100644--- a/src/state/bot-patch-queue.ts+++ b/src/state/bot-patch-queue.ts@@ -15,6 +15,7 @@ export type BotUpdatePatch = Partial<| "mascotExpression"| "mascotBody"| "mascotFaceColor"+ | "mascotBodyColor"| "avatarUrl"| "avatarCrop"| "avatarZoom"diff --git a/src/state/store.tsx b/src/state/store.tsxindex 99892ac85d..9fd0e33a1f 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -273,7 +273,7 @@ export interface TaskUsage {context?: { tokens: number; window?: number };}-export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" | "access" | "yourAccess" | "onlyPeopleAdded"> {+export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" | "mascotBodyColor" | "access" | "yourAccess" | "onlyPeopleAdded"> {toolScope?: ToolScope;waitingForTeammates?: boolean;id: string;