Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
agent-ui: introduce @three-ws/agent-ui SDK
overstepping56658d00b2ac
diff --git a/agent-ui-sdk/CHANGELOG.md b/agent-ui-sdk/CHANGELOG.mdnew file mode 100644index 000000000..339a4a5b5--- /dev/null+++ b/agent-ui-sdk/CHANGELOG.md@@ -0,0 +1,11 @@+# @three-ws/agent-ui++## 0.1.0++Initial release.++- `createAgentUI()` — orthographic overlay canvas, GLB avatar, JSON clip loader, animation mixer with crossfade.+- Behaviors: `play`, `moveTo`, `lookAt`, `walkTo`, `standOn`, `fallOnto`, `runOff`, `interceptNavigation`.+- FX: dust splash, impact pulse, proximity shadow, mouse parallax.+- Caret tracking helper for input typing.+- Declarative scanner: wires `data-agent-action` attributes on elements (`stand-on`, `track-typing`, `privacy-mode`, `navigate-on-click`, `react-on-click`).diff --git a/agent-ui-sdk/LICENSE b/agent-ui-sdk/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/agent-ui-sdk/LICENSE@@ -0,0 +1,180 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship made available under+ the License, as indicated by a copyright notice that is included in+ or attached to the work (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other transformations+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean, as submitted to the Licensor for inclusion+ in the Work by the copyright owner or by an individual or Legal Entity+ authorized to submit on behalf of the copyright owner. For the purposes+ of this definition, "submitted" means any form of electronic, verbal,+ or written communication sent to the Licensor or its representatives,+ including but not limited to communication on electronic mailing lists,+ source code control systems, and issue tracking systems that are managed+ by, or on behalf of, the Licensor for the purpose of discussing and+ improving the Work, but excluding communication that is conspicuously+ marked or designated in writing by the copyright owner as "Not a+ Contribution."++ "Contributor" shall mean Licensor and any Legal Entity on behalf of+ whom a Contribution has been received by the Licensor and included+ within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by the combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a cross-claim+ or counterclaim in a lawsuit) alleging that the Work or any+ Contribution embodied within the Work constitutes direct or contributory+ patent infringement, then any patent licenses granted to You under+ this License for that Work shall terminate as of the date such+ litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or Derivative+ Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, You must include a readable copy of the+ attribution notices contained within such NOTICE file, in+ at least one of the following places: within a NOTICE text+ file distributed as part of the Derivative Works; within+ the Source form or documentation, if provided along with the+ Derivative Works; or, within a display generated by the+ Derivative Works, if and wherever such third-party notices+ normally appear. The contents of the NOTICE file are for+ informational purposes only and do not modify the License.+ You may add Your own attribution notices within Derivative+ Works that You distribute, alongside or in addition to the+ NOTICE text from the Work, provided that such additional+ attribution notices cannot be construed as modifying the License.++ You may add Your own license statement for Your modifications and+ may provide additional grant of rights to use, copy, modify, merge,+ publish, distribute, sublicense, and/or sell copies of the+ Derivative Works, and to permit persons to whom the Derivative Works+ are furnished to do so.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or reproducing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or exemplary damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or all other+ commercial damages or losses), even if such Contributor has been+ advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may offer only+ conditions consistent with this License.++ END OF TERMS AND CONDITIONS++ Copyright 2026 nirholas++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/agent-ui-sdk/README.md b/agent-ui-sdk/README.mdnew file mode 100644index 000000000..4ae9877fe--- /dev/null+++ b/agent-ui-sdk/README.md@@ -0,0 +1,107 @@+# @three-ws/agent-ui++Drop a 3D avatar into your UI and let it react to buttons, inputs, and navigation.++A small Three.js overlay SDK that takes the avatar-stage runtime used by the [three.ws](https://three.ws) demos (`404`, `login`, `3d-home`) and packages it as a drop-in API. The avatar lives on a transparent fullscreen canvas above your DOM, anchored to real elements — it can stand on a card, fall onto a heading, walk over to focus an input, cover its eyes when you type a password, or run off-screen before navigating away.++```bash+npm install @three-ws/agent-ui three+```++## Quick start++```html+<canvas></canvas>+<button id="go" data-agent-action="navigate-on-click">Take me home</button>++<script type="module">+ import { createAgentUI } from '@three-ws/agent-ui';++ const agent = await createAgentUI({+ avatar: '/avatars/cz.glb',+ clipsBase: '/animations/clips/',+ clips: ['idle', 'walk', 'falling'],+ });++ agent.fallOnto(document.getElementById('hero'), {+ onLand: () => {+ agent.fx.dust(document.getElementById('hero'));+ agent.fx.impactPulse(document.getElementById('hero'));+ },+ });++ agent.scan(); // wires any data-agent-action attributes in the page+</script>+```++## Imperative API++```js+agent.play('idle', { loop: true });+agent.play('covereyes', { loop: false, hold: true, onComplete: () => {} });++agent.standOn(formCard, { anchor: 'top-center' });+agent.walkTo(emailInput);+agent.fallOnto(heading, { duration: 1.4 });+agent.runOff('right');+agent.interceptNavigation(homeLink, { direction: 'right', delay: 1100 });++agent.lookAt(450); // screen-X in pixels+agent.faceFront();++const stopShadow = agent.fx.proximityShadow(heading);+agent.fx.dust(buttonEl);+agent.fx.impactPulse(buttonEl);+```++## Declarative attributes++Mark up the page and call `agent.scan()` once — no per-element JS needed.++```html+<input data-agent-action="track-typing" />+<input data-agent-action="privacy-mode" type="password" />++<a href="/" data-agent-action="navigate-on-click" data-agent-direction="right">Home</a>+<button data-agent-action="react-on-click" data-agent-clip="celebrate">Subscribe</button>++<div class="card" data-agent-action="stand-on"></div>+```++| `data-agent-action` | Behavior |+| -------------------- | ------------------------------------------------------------------------- |+| `stand-on` | Park the avatar above this element on ready. |+| `track-typing` | On focus, walk to the input, play `lookdown`, follow the caret with yaw. |+| `privacy-mode` | On focus, walk to the input, play `covereyes` once and hold. |+| `navigate-on-click` | Intercept click, run off-screen, then follow `href`. |+| `react-on-click` | Play `data-agent-clip` once on click. |++## Options++```ts+createAgentUI({+ avatar: '/avatars/cz.glb',+ clipsBase: '/animations/clips/',+ clips: ['idle', 'walk', 'lookdown', 'covereyes', 'falling', 'celebrate'],+ subclips: {+ // Trim a long Mixamo clip down to just the settle frames+ covereyes: { start: 0, end: 48, fps: 30 },+ },+ pixelsPerUnit: 120,+ zIndex: 999,+ parallax: true,+ crossfade: 0.3,+ lights: true,+});+```++## Notes++- **Assets are yours.** The SDK does not bundle the avatar GLB or animation JSONs — point it at whatever you host. The three.ws CDN paths used in the demos are the defaults but every URL is configurable.+- **Three.js is a peer dep** so your bundler de-dupes it. Works with Three r150+.+- **No gsap dep.** All tweens use built-in `requestAnimationFrame` easings.+- **Root motion is locked** automatically so walk-cycle hip translation doesn't drift the avatar off-screen.++## License++Apache-2.0 © three.wsdiff --git a/agent-ui-sdk/build.mjs b/agent-ui-sdk/build.mjsnew file mode 100644index 000000000..5c058a67a--- /dev/null+++ b/agent-ui-sdk/build.mjs@@ -0,0 +1,32 @@+#!/usr/bin/env node+/**+ * Build script for @three-ws/agent-ui+ *+ * Bundles src/index.js into dist/index.mjs via esbuild from the root+ * node_modules. `three` is marked external so consumers' bundlers de-dupe it+ * against their own copy.+ */++import { build } from '../node_modules/esbuild/lib/main.js';+import { copyFileSync, mkdirSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const here = dirname(fileURLToPath(import.meta.url));+const outDir = join(here, 'dist');+mkdirSync(outDir, { recursive: true });++await build({+ entryPoints: [join(here, 'src/index.js')],+ bundle: true,+ format: 'esm',+ outfile: join(outDir, 'index.mjs'),+ external: ['three', 'three/addons/loaders/GLTFLoader.js'],+ target: ['es2020'],+ sourcemap: false,+ logLevel: 'info',+});++copyFileSync(join(here, 'types/index.d.ts'), join(outDir, 'index.d.ts'));++console.log('[agent-ui] built dist/index.mjs');diff --git a/agent-ui-sdk/package.json b/agent-ui-sdk/package.jsonnew file mode 100644index 000000000..336ceec6e--- /dev/null+++ b/agent-ui-sdk/package.json@@ -0,0 +1,59 @@+{+ "name": "@three-ws/agent-ui",+ "version": "0.1.0",+ "description": "Drop a 3D avatar into your UI and let it react to buttons, inputs, and navigation. The three.ws agent overlay SDK.",+ "keywords": [+ "3d",+ "avatar",+ "three.js",+ "webgl",+ "ui",+ "overlay",+ "agent",+ "interactive",+ "three-ws"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws.git",+ "directory": "agent-ui-sdk"+ },+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "types": "./types/index.d.ts",+ "exports": {+ ".": {+ "types": "./types/index.d.ts",+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./bundle": {+ "types": "./types/index.d.ts",+ "import": "./dist/index.mjs",+ "default": "./dist/index.mjs"+ },+ "./src/*": "./src/*"+ },+ "files": [+ "dist",+ "src",+ "types",+ "README.md",+ "LICENSE",+ "CHANGELOG.md"+ ],+ "scripts": {+ "build": "node build.mjs",+ "prepublishOnly": "npm run build"+ },+ "peerDependencies": {+ "three": ">=0.150.0"+ },+ "engines": {+ "node": ">=18"+ }+}diff --git a/agent-ui-sdk/src/avatar.js b/agent-ui-sdk/src/avatar.jsnew file mode 100644index 000000000..4cab22405--- /dev/null+++ b/agent-ui-sdk/src/avatar.js@@ -0,0 +1,113 @@+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';++const ROOT_BONE_RX = /^(Hips|Root|mixamorig:?Hips)$/i;++/**+ * Load the avatar GLB and parse the named clip JSONs in parallel.+ *+ * @param {{+ * avatar: string,+ * clipsBase: string,+ * clips: string[],+ * subclips?: Record<string, { start: number, end: number, fps?: number }>+ * }} options+ */+export async function loadAvatar({ avatar, clipsBase, clips, subclips = {} }) {+ const loader = new GLTFLoader();+ const [gltf, clipJsons] = await Promise.all([+ new Promise((resolve, reject) => loader.load(avatar, resolve, undefined, reject)),+ Promise.all(clips.map((name) =>+ fetch(`${clipsBase}${name}.json`).then((r) => {+ if (!r.ok) throw new Error(`[agent-ui] failed to load clip "${name}": ${r.status}`);+ return r.json();+ })+ )),+ ]);++ const object = gltf.scene;+ let rootBone = null;+ object.traverse((n) => {+ if (!rootBone && ROOT_BONE_RX.test(n.name)) rootBone = n;+ });+ object.rotation.y = 0;++ const parsed = {};+ clips.forEach((name, i) => {+ let clip = THREE.AnimationClip.parse(clipJsons[i]);+ const sub = subclips[name];+ if (sub) {+ clip = THREE.AnimationUtils.subclip(clip, name, sub.start, sub.end, sub.fps ?? 30);+ }+ parsed[name] = clip;+ });++ return { object, rootBone, clips: parsed };+}++/**+ * Wrap a mixer + actions table with crossfade semantics matching the demos.+ * Returns a small controller exposing play() / current() / onFinished().+ */+export function createAnimator({ object, clips, crossfade = 0.3 }) {+ const mixer = new THREE.AnimationMixer(object);+ const actions = {};+ for (const [name, clip] of Object.entries(clips)) {+ actions[name] = mixer.clipAction(clip);+ }+ let current = null;+ let currentName = null;++ const finishCallbacks = new Map();+ mixer.addEventListener('finished', (e) => {+ const cb = finishCallbacks.get(e.action);+ if (cb) {+ finishCallbacks.delete(e.action);+ cb();+ }+ });++ function play(name, { loop = true, hold = false, onComplete } = {}) {+ const next = actions[name];+ if (!next) {+ console.warn(`[agent-ui] no such clip: "${name}"`);+ return;+ }+ if (next === current && loop) return;+ next.reset();+ next.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, loop ? Infinity : 1);+ next.clampWhenFinished = hold;+ if (current) next.crossFadeFrom(current, crossfade, false).play();+ else next.fadeIn(crossfade).play();+ current = next;+ currentName = name;+ if (!loop && onComplete) finishCallbacks.set(next, onComplete);+ }++ function clipDuration(name) {+ return clips[name]?.duration ?? 1.0;+ }++ function update(dt) {+ mixer.update(dt);+ }++ return { play, update, clipDuration, get currentName() { return currentName; }, actions, clips };+}++/**+ * Many Mixamo clips bake hip translation into the walk cycle; if we let that+ * through, the avatar drifts off-screen during 'walk' loops or rises during+ * 'falling' loops. Patch renderer.render to clamp the root bone back to its+ * rest position every frame.+ */+export function lockRootMotion(renderer, rootBone) {+ if (!rootBone) return () => {};+ const basePos = rootBone.position.clone();+ const original = renderer.render.bind(renderer);+ renderer.render = (sc, cam) => {+ try { rootBone.position.copy(basePos); } catch (_) {}+ original(sc, cam);+ };+ return () => { renderer.render = original; };+}diff --git a/agent-ui-sdk/src/behaviors.js b/agent-ui-sdk/src/behaviors.jsnew file mode 100644index 000000000..2af4f3b19--- /dev/null+++ b/agent-ui-sdk/src/behaviors.js@@ -0,0 +1,187 @@+import { tween, tweenProp, smoothstep, easeInQuad, easeOutCubic } from './tween.js';++// Anchor helpers — convert a DOM element into a world-space target that the+// avatar should stand at. Default anchor is the visual top of the element+// because the avatar's pivot is at the feet.+export function worldOfElement(el, agent, { anchor = 'top-center', offsetX = 0, offsetY = 0 } = {}) {+ const r = el.getBoundingClientRect();+ let sx = r.left + r.width / 2;+ let sy = r.top;+ switch (anchor) {+ case 'top-left': sx = r.left; sy = r.top; break;+ case 'top-right': sx = r.right; sy = r.top; break;+ case 'top-center': sx = r.left + r.width/2; sy = r.top; break;+ case 'center': sx = r.left + r.width/2; sy = r.top + r.height/2; break;+ case 'bottom-center': sx = r.left + r.width/2; sy = r.bottom; break;+ case 'left-of': sx = r.left; sy = r.top + r.height/2; break;+ case 'right-of': sx = r.right; sy = r.top + r.height/2; break;+ }+ return agent.domToWorld(sx + offsetX, sy + offsetY);+}++/**+ * Slide the avatar from its current world position to `target`.+ * Returns a Promise resolving when the move completes.+ */+export function moveTo(agent, target, { duration = 520, ease = smoothstep } = {}) {+ if (!agent.avatar) return Promise.resolve();+ const av = agent.avatar;+ const fromX = av.position.x, fromY = av.position.y;+ return tween({+ duration,+ ease,+ onUpdate: (e) => {+ av.position.x = fromX + (target.x - fromX) * e;+ av.position.y = fromY + (target.y - fromY) * e;+ },+ });+}++/**+ * Smoothly turn the avatar's yaw toward a screen X position. Used to make+ * the avatar's body follow a caret or a button being moused.+ */+export function lookAtScreenX(agent, targetScreenX, { duration = 180, maxYaw = 0.45, sensitivity = 450 } = {}) {+ if (!agent.avatar) return Promise.resolve();+ const projected = agent.worldToScreen(agent.avatar.position.x, agent.avatar.position.y);+ const dxPx = targetScreenX - projected.x;+ const yaw = Math.max(-maxYaw, Math.min(maxYaw, dxPx / sensitivity));+ return tweenProp(agent.avatar.rotation, 'y', yaw, { duration });+}++export function faceFront(agent, { duration = 250 } = {}) {+ if (!agent.avatar) return Promise.resolve();+ return tweenProp(agent.avatar.rotation, 'y', 0, { duration });+}++/**+ * Walk-cycle to `element`: switches to the walk clip, slides over, then leaves+ * the animator on the walk clip — caller decides what to play next.+ */+export async function walkTo(agent, element, { walkClip = 'walk', duration = 540, anchor = 'top-center', offsetX = 0, offsetY = 0 } = {}) {+ if (!agent.avatar) return;+ agent.play(walkClip, { loop: true });+ const target = worldOfElement(element, agent, { anchor, offsetX, offsetY });+ await moveTo(agent, target, { duration });+}++/**+ * Park the avatar above `element` without traversal — used on initial mount+ * to position the avatar at rest on a card / button / heading.+ */+export function standOn(agent, element, { idleClip = 'idle', anchor = 'top-center', offsetX = 0, offsetY = 0 } = {}) {+ if (!agent.avatar) return;+ const target = worldOfElement(element, agent, { anchor, offsetX, offsetY });+ agent.avatar.position.set(target.x, target.y, 0);+ agent.play(idleClip, { loop: true });+}++/**+ * Drop the avatar from above the viewport onto `element`. Calls `onLand` once+ * the impact frame is reached so the caller can fire dust/pulse FX.+ */+export function fallOnto(agent, element, {+ fallClip = 'falling',+ duration = 1.4,+ startOffsetVh = 0.6,+ anchor = 'top-center',+ landingOffsetPx = 90,+ tumble = 0.25,+ onLand,+} = {}) {+ if (!agent.avatar) return Promise.resolve();+ const getStart = () => {+ const r = element.getBoundingClientRect();+ return agent.domToWorld(r.left + r.width / 2, -window.innerHeight * startOffsetVh);+ };+ const getTarget = () => {+ const r = element.getBoundingClientRect();+ const sx = r.left + r.width / 2;+ const sy = (anchor === 'top-center') ? (r.top + landingOffsetPx) : (r.top + r.height / 2);+ return agent.domToWorld(sx, sy);+ };+ const start = getStart();+ const target = getTarget();+ agent.avatar.position.set(start.x, start.y, 0);+ agent.avatar.rotation.set(0, 0, 0);+ agent.play(fallClip, { loop: true });++ return new Promise((resolve) => {+ tween({+ duration: duration * 1000,+ ease: (t) => t, // we apply per-axis easing inside+ onUpdate: (_, t) => {+ const ey = easeInQuad(t); // gravity vertical+ const ex = smoothstep(t); // smooth horizontal+ agent.avatar.position.x = start.x + (target.x - start.x) * ex;+ agent.avatar.position.y = start.y + (target.y - start.y) * ey;+ agent.avatar.rotation.y = (1 - t) * tumble * Math.sin(t * 8);+ },+ onComplete: () => {+ onLand?.();+ resolve();+ },+ });+ });+}++/**+ * Walk the avatar off-screen in `direction`. Resolves once she clears the+ * viewport so caller can navigate away or unmount.+ */+export function runOff(agent, direction = 'right', {+ walkClip = 'walk',+ rotationDuration = 300,+ minDuration = 900,+ pxPerMs = 0.45, // walk speed for distance-based timing+} = {}) {+ if (!agent.avatar) return Promise.resolve();+ const dir = direction === 'left' ? -1 : 1;+ agent.play(walkClip, { loop: true });+ tweenProp(agent.avatar.rotation, 'y', dir * Math.PI * 0.5, { duration: rotationDuration });+ const targetWorldX = (window.innerWidth / agent.pixelsPerUnit) * 0.7 * dir;+ const curX = agent.avatar.position.x;+ const distancePx = Math.abs(targetWorldX - curX) * agent.pixelsPerUnit;+ const duration = Math.max(minDuration, distancePx / pxPerMs);+ return tweenProp(agent.avatar.position, 'x', targetWorldX, { duration, ease: easeOutCubic });+}++/**+ * Intercept a link/button click: prevent default, run the avatar off-screen,+ * then navigate to `linkEl.href` (or call `onAfter`).+ */+export function interceptNavigation(agent, linkEl, {+ direction = 'right',+ delay = 1100,+ onAfter,+} = {}) {+ const handler = (e) => {+ if (agent._runningOff) return;+ e.preventDefault();+ agent._runningOff = true;+ runOff(agent, direction);+ setTimeout(() => {+ if (onAfter) onAfter();+ else if (linkEl.href) window.location.href = linkEl.href;+ }, delay);+ };+ linkEl.addEventListener('click', handler);+ return () => linkEl.removeEventListener('click', handler);+}++/**+ * Pick a clip from `pool` while avoiding the most recent pick. Useful for+ * fail / react rotations so the same animation doesn't fire twice in a row.+ */+export function createRandomPicker(pool) {+ let last = null;+ return () => {+ if (pool.length === 0) return null;+ if (pool.length === 1) return pool[0];+ let pick;+ do { pick = pool[Math.floor(Math.random() * pool.length)]; }+ while (pick === last);+ last = pick;+ return pick;+ };+}diff --git a/agent-ui-sdk/src/caret.js b/agent-ui-sdk/src/caret.jsnew file mode 100644index 000000000..8e31ade39--- /dev/null+++ b/agent-ui-sdk/src/caret.js@@ -0,0 +1,58 @@+// Caret-X tracker for <input> elements. Renders a hidden mirror <div> with+// matching typography, copies the prefix-up-to-caret, and measures the rendered+// text width. Works for both text inputs and password inputs (the latter by+// substituting bullet glyphs so width matches what the user sees).++let mirror = null;+function ensureMirror() {+ if (mirror) return mirror;+ mirror = document.createElement('div');+ mirror.setAttribute('aria-hidden', 'true');+ mirror.style.cssText =+ 'position:absolute;visibility:hidden;white-space:pre;' ++ 'padding:0;margin:0;border:0;pointer-events:none;top:-9999px;left:-9999px;';+ document.body.appendChild(mirror);+ return mirror;+}++export function caretScreenX(input) {+ const m = ensureMirror();+ const cs = getComputedStyle(input);+ m.style.font = cs.font;+ m.style.letterSpacing = cs.letterSpacing;+ m.style.textTransform = cs.textTransform;++ const rect = input.getBoundingClientRect();+ const padL = parseFloat(cs.paddingLeft) || 0;+ const padR = parseFloat(cs.paddingRight) || 0;+ const innerW = rect.width - padL - padR;++ const raw = input.value || '';+ const display = input.type === 'password' ? '•'.repeat(raw.length) : raw;+ const caretIdx = input.selectionStart ?? display.length;+ m.textContent = display.slice(0, caretIdx) || ' ';+ const textW = m.getBoundingClientRect().width;++ const offset = Math.min(textW, innerW);+ return rect.left + padL + offset;+}++/**+ * Track the caret X position on every animation frame while `input` is the+ * "active" target. The caller passes a `getActive()` thunk so the tracker+ * cleanly exits when focus moves to a different input.+ */+export function startCaretTracking(input, onChange, getActive) {+ let raf = 0;+ let lastX = -1;+ (function loop() {+ if (getActive() !== input) return;+ const cx = caretScreenX(input);+ if (cx !== lastX) {+ lastX = cx;+ onChange(cx);+ }+ raf = requestAnimationFrame(loop);+ })();+ return () => cancelAnimationFrame(raf);+}diff --git a/agent-ui-sdk/src/fx.js b/agent-ui-sdk/src/fx.jsnew file mode 100644index 000000000..ac9805c8a--- /dev/null+++ b/agent-ui-sdk/src/fx.js@@ -0,0 +1,124 @@+// Lightweight HTML/CSS-driven FX layered over the avatar canvas. Kept here so+// the demos don't need to reimplement these helpers each time.++/**+ * Spray ballistic dust particles from the impact point on `element`. Neutral+ * grey palette — reads as kicked-up dust rather than confetti.+ */+export function dust(element, {+ count = 16,+ gravity = 1400,+ minSpeed = 180,+ maxSpeed = 460,+ minSize = 4,+ maxSize = 10,+ maxLifeMs = 1100,+ yWithin = 0.78, // 0..1 fraction down the element box for the origin+ zIndex = 30,+ color = 'radial-gradient(circle at 35% 30%,#cfd2dd,#7a7d8e 60%,#3c3e4c)',+} = {}) {+ const r = element.getBoundingClientRect();+ const ox = r.left + r.width / 2;+ const oy = r.top + r.height * yWithin;++ const drops = [];+ for (let i = 0; i < count; i++) {+ const size = minSize + Math.random() * (maxSize - minSize);+ const el = document.createElement('div');+ el.style.cssText =+ `position:fixed;left:${ox - size/2}px;top:${oy - size/2}px;` ++ `width:${size}px;height:${size}px;border-radius:50%;` ++ `background:${color};` ++ 'box-shadow:0 0 5px rgba(255,255,255,0.18);' ++ `pointer-events:none;z-index:${zIndex};will-change:transform,opacity;`;+ document.body.appendChild(el);+ const angle = -Math.PI / 2 + (Math.random() - 0.5) * Math.PI * 1.3;+ const speed = minSpeed + Math.random() * (maxSpeed - minSpeed);+ drops.push({+ el, x: 0, y: 0,+ vx: Math.cos(angle) * speed,+ vy: Math.sin(angle) * speed,+ life: 0,+ max: (maxLifeMs / 1000) * (0.6 + Math.random() * 0.6),+ });+ }++ let last = performance.now();+ (function step(now) {+ const dt = Math.min((now - last) / 1000, 0.04); last = now;+ let alive = false;+ for (const d of drops) {+ if (!d.el) continue;+ d.life += dt;+ d.vy += gravity * dt;+ d.x += d.vx * dt; d.y += d.vy * dt;+ const t = d.life / d.max;+ if (t >= 1) { d.el.remove(); d.el = null; continue; }+ d.el.style.opacity = String(1 - t * t);+ d.el.style.transform = `translate(${d.x.toFixed(1)}px,${d.y.toFixed(1)}px)`;+ alive = true;+ }+ if (alive) requestAnimationFrame(step);+ })(last);+}++/**+ * Brief vertical translate + elastic settle on `element`. Sells the weight of+ * a landing on top of it.+ */+export function impactPulse(element, { dropPx = 4, elasticMs = 500 } = {}) {+ let raf = 0;+ const t0 = performance.now();+ const down = 80;+ (function down1(now) {+ const t = Math.min((now - t0) / down, 1);+ element.style.transform = `translateY(${(dropPx * t).toFixed(2)}px)`;+ if (t < 1) raf = requestAnimationFrame(down1);+ else {+ const t1 = performance.now();+ (function up(now2) {+ const t2 = Math.min((now2 - t1) / elasticMs, 1);+ // Damped sin elastic+ const e = (1 - t2) * Math.sin(t2 * Math.PI * 3.5) * 0.45 + (1 - t2) * (1 - t2);+ element.style.transform = `translateY(${(dropPx * e).toFixed(2)}px)`;+ if (t2 < 1) raf = requestAnimationFrame(up);+ else element.style.transform = '';+ })(performance.now());+ }+ })(t0);+ return () => cancelAnimationFrame(raf);+}++/**+ * Continuously paint a CSS text-shadow on `targetEl` whose intensity scales+ * with the avatar's vertical proximity to the target. Caller must invoke the+ * returned tick() in their render loop and the returned dispose() on cleanup.+ *+ * Sets a CSS custom property `--agent-shadow` on `targetEl`. The element's+ * stylesheet should consume it via e.g. `text-shadow: var(--agent-shadow, none)`.+ */+export function proximityShadow(targetEl, agent, {+ maxDistancePx = 280,+ maxAlpha = 0.6,+ cssVar = '--agent-shadow',+} = {}) {+ function tick() {+ if (!agent.avatar) return;+ const r = targetEl.getBoundingClientRect();+ const proj = agent.worldToScreen(agent.avatar.position.x, agent.avatar.position.y);+ const dy = Math.max(0, r.top - proj.y);+ const prox = 1 - Math.min(dy / maxDistancePx, 1);+ if (prox <= 0.01) {+ targetEl.style.setProperty(cssVar, 'none');+ return;+ }+ const blur = (12 * (1 - prox) + 3).toFixed(2);+ const offsetY = (3 + 8 * prox).toFixed(2);+ const alpha = (maxAlpha * prox).toFixed(3);+ targetEl.style.setProperty(cssVar, `0 ${offsetY}px ${blur}px rgba(0,0,0,${alpha})`);+ }+ function dispose() {+ targetEl.style.removeProperty(cssVar);+ }+ return { tick, dispose };+}diff --git a/agent-ui-sdk/src/index.js b/agent-ui-sdk/src/index.jsnew file mode 100644index 000000000..3b1526701--- /dev/null+++ b/agent-ui-sdk/src/index.js@@ -0,0 +1,200 @@+import * as THREE from 'three';++import { createRenderer } from './renderer.js';+import { loadAvatar, createAnimator, lockRootMotion } from './avatar.js';+import {+ worldOfElement,+ moveTo,+ lookAtScreenX,+ faceFront,+ walkTo,+ standOn,+ fallOnto,+ runOff,+ interceptNavigation,+ createRandomPicker,+} from './behaviors.js';+import { caretScreenX, startCaretTracking } from './caret.js';+import { dust, impactPulse, proximityShadow } from './fx.js';+import { scan } from './scan.js';++const DEFAULTS = {+ avatar: '/avatars/cz.glb',+ clipsBase: '/animations/clips/',+ clips: ['idle', 'walk'],+ subclips: {},+ container: null, // resolved to document.body+ canvas: null, // explicit canvas; else created+ zIndex: 999,+ pixelsPerUnit: 120,+ parallax: true,+ crossfade: 0.3,+ lights: true,+};++/**+ * Create an avatar overlay bound to the current document.+ *+ * Returns a Promise that resolves to an AgentUI handle once the GLB and clip+ * JSONs have loaded and the avatar is in scene playing 'idle' (or whatever+ * the caller plays first).+ */+export async function createAgentUI(userOptions = {}) {+ const opts = { ...DEFAULTS, ...userOptions };+ if (!opts.container) opts.container = document.body;++ const rendererCtx = createRenderer({+ container: opts.container,+ canvas: opts.canvas,+ zIndex: opts.zIndex,+ pixelsPerUnit: opts.pixelsPerUnit,+ lights: opts.lights,+ parallax: opts.parallax,+ });++ // Build the public handle in stages — methods need a reference to it for+ // passing into the free behavior functions below.+ const agent = {+ // Three.js objects+ THREE,+ renderer: rendererCtx.renderer,+ scene: rendererCtx.scene,+ camera: rendererCtx.camera,+ canvas: rendererCtx.canvas,+ pixelsPerUnit: rendererCtx.pixelsPerUnit,+ avatar: null,+ rootBone: null,+ animator: null,++ // Coordinate helpers+ domToWorld: rendererCtx.domToWorld,+ worldToScreen: rendererCtx.worldToScreen,+ worldOfElement: (el, o) => worldOfElement(el, agent, o),++ // Animation+ play: (name, o) => agent.animator?.play(name, o),+ clip: (name) => agent.animator?.clipDuration(name) ?? 0,+ get currentClip() { return agent.animator?.currentName ?? null; },++ // Movement / posing+ moveTo: (target, o) => moveTo(agent, target, o),+ lookAt: (screenX, o) => lookAtScreenX(agent, screenX, o),+ faceFront: (o) => faceFront(agent, o),++ // DOM-anchored behaviors+ standOn: (el, o) => standOn(agent, el, o),+ walkTo: (el, o) => walkTo(agent, el, o),+ fallOnto:(el, o) => fallOnto(agent, el, o),+ runOff: (dir, o) => runOff(agent, dir, o),+ interceptNavigation: (el, o) => interceptNavigation(agent, el, o),++ // FX helpers+ fx: {+ dust: (el, o) => dust(el, o),+ impactPulse: (el, o) => impactPulse(el, o),+ proximityShadow: (el, o) => {+ const handle = proximityShadow(el, agent, o);+ agent._proximityTickers.push(handle.tick);+ return () => {+ const i = agent._proximityTickers.indexOf(handle.tick);+ if (i >= 0) agent._proximityTickers.splice(i, 1);+ handle.dispose();+ };+ },+ },++ // Caret helper — exposed for consumers writing imperative typing UX+ caretScreenX,+ startCaretTracking,++ // Random non-repeating picker (e.g. fail reaction rotations)+ pickFrom: (pool) => createRandomPicker(pool),++ // Declarative DOM scanner+ scan: (root = document) => scan(root, agent),++ // Ready signaling+ ready: false,+ whenReady(fn) {+ if (agent.ready) fn(agent);+ else agent._readyHandlers.push(fn);+ },++ // Lifecycle+ destroy() {+ agent._destroyed = true;+ cancelAnimationFrame(agent._raf);+ agent._unlockRoot?.();+ rendererCtx.destroy();+ },++ // Internal+ _readyHandlers: [],+ _proximityTickers: [],+ _runningOff: false,+ _destroyed: false,+ _unlockRoot: null,+ _raf: 0,+ };++ // Load avatar + clips+ const { object, rootBone, clips } = await loadAvatar({+ avatar: opts.avatar,+ clipsBase: opts.clipsBase,+ clips: opts.clips,+ subclips: opts.subclips,+ });+ agent.avatar = object;+ agent.rootBone = rootBone;+ agent.scene.add(object);++ agent.animator = createAnimator({ object, clips, crossfade: opts.crossfade });+ agent._unlockRoot = lockRootMotion(agent.renderer, rootBone);++ // Default to idle if it's loaded; consumer can override via play().+ if (clips.idle) agent.animator.play('idle', { loop: true });++ // Render loop+ const clock = new THREE.Clock();+ (function tick() {+ if (agent._destroyed) return;+ agent._raf = requestAnimationFrame(tick);+ try {+ const dt = Math.min(clock.getDelta(), 0.05);+ agent.animator.update(dt);+ rendererCtx.updateParallax();+ for (const t of agent._proximityTickers) t();+ agent.renderer.render(agent.scene, agent.camera);+ } catch (_) {}+ })();++ agent.ready = true;+ for (const fn of agent._readyHandlers) fn(agent);+ agent._readyHandlers.length = 0;++ return agent;+}++// Re-exports for advanced consumers building their own compositions.+export {+ createRenderer,+ loadAvatar,+ createAnimator,+ lockRootMotion,+ worldOfElement,+ moveTo,+ lookAtScreenX,+ faceFront,+ walkTo,+ standOn,+ fallOnto,+ runOff,+ interceptNavigation,+ createRandomPicker,+ caretScreenX,+ startCaretTracking,+ dust,+ impactPulse,+ proximityShadow,+ scan,+};diff --git a/agent-ui-sdk/src/renderer.js b/agent-ui-sdk/src/renderer.jsnew file mode 100644index 000000000..1c8742a6b--- /dev/null+++ b/agent-ui-sdk/src/renderer.js@@ -0,0 +1,118 @@+import * as THREE from 'three';++// Build the fullscreen overlay renderer + orthographic scene that the+// avatar runs in. Returns a small handle of the live objects plus the+// DOM↔world coordinate helpers (which are bound to *this* camera, so the+// caller never accidentally projects against a stale frustum).+export function createRenderer({+ container = document.body,+ canvas,+ zIndex = 999,+ pixelsPerUnit = 120,+ lights = true,+ parallax = true,+} = {}) {+ let ownsCanvas = false;+ if (!canvas) {+ canvas = document.createElement('canvas');+ canvas.style.cssText =+ 'position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;' ++ `z-index:${zIndex};`;+ container.appendChild(canvas);+ ownsCanvas = true;+ }++ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.1;++ const scene = new THREE.Scene();+ const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);+ camera.position.z = 10;++ if (lights) {+ scene.add(new THREE.AmbientLight(0xffffff, 0.6));+ const key = new THREE.DirectionalLight(0xfff4dc, 2.0); key.position.set(3, 6, 5); scene.add(key);+ const rim = new THREE.DirectionalLight(0x4060ff, 0.6); rim.position.set(-4, 3, -2); scene.add(rim);+ const fill = new THREE.DirectionalLight(0xffeedd, 0.4); fill.position.set(0, 2, 7); scene.add(fill);+ }++ function updateFrustum() {+ const hw = window.innerWidth / pixelsPerUnit / 2;+ const hh = window.innerHeight / pixelsPerUnit / 2;+ camera.left = -hw; camera.right = hw;+ camera.top = hh; camera.bottom = -hh;+ camera.updateProjectionMatrix();+ }++ const _v3 = new THREE.Vector3();+ function domToWorld(screenX, screenY) {+ _v3.set(+ (screenX / window.innerWidth) * 2 - 1,+ -(screenY / window.innerHeight) * 2 + 1,+ 0,+ );+ _v3.unproject(camera);+ return { x: _v3.x, y: _v3.y };+ }++ // Project an arbitrary world point back to screen pixels — used by FX+ // (proximity shadow, dust origin) that need to draw HTML on top of the+ // avatar's actual screen position rather than its DOM anchor.+ const _proj = new THREE.Vector3();+ function worldToScreen(x, y) {+ _proj.set(x, y, 0).project(camera);+ return {+ x: (_proj.x + 1) * 0.5 * window.innerWidth,+ y: (1 - _proj.y) * 0.5 * window.innerHeight,+ };+ }++ function resize() {+ renderer.setSize(window.innerWidth, window.innerHeight, false);+ updateFrustum();+ }+ window.addEventListener('resize', resize);+ resize();++ // Camera parallax — pan slightly with the mouse instead of changing FOV,+ // which keeps domToWorld() correct since it always reads from `camera`.+ let mouseNx = 0, mouseNy = 0;+ let mouseMoveHandler = null;+ if (parallax) {+ mouseMoveHandler = (e) => {+ mouseNx = (e.clientX / window.innerWidth) * 2 - 1;+ mouseNy = (e.clientY / window.innerHeight) * 2 - 1;+ };+ window.addEventListener('mousemove', mouseMoveHandler);+ }++ function updateParallax() {+ if (!parallax) return;+ const tx = mouseNx * 0.12;+ const ty = -mouseNy * 0.08;+ camera.position.x += (tx - camera.position.x) * 0.04;+ camera.position.y += (ty - camera.position.y) * 0.04;+ }++ function destroy() {+ window.removeEventListener('resize', resize);+ if (mouseMoveHandler) window.removeEventListener('mousemove', mouseMoveHandler);+ renderer.dispose();+ if (ownsCanvas) canvas.remove();+ }++ return {+ canvas,+ renderer,+ scene,+ camera,+ pixelsPerUnit,+ domToWorld,+ worldToScreen,+ updateParallax,+ destroy,+ };+}diff --git a/agent-ui-sdk/src/scan.js b/agent-ui-sdk/src/scan.jsnew file mode 100644index 000000000..5ed351bda--- /dev/null+++ b/agent-ui-sdk/src/scan.js@@ -0,0 +1,105 @@+// Declarative scanner: reads `data-agent-*` attributes from a root element+// and wires the corresponding behaviors. Lets a static HTML page describe its+// avatar interactions without writing JS.+//+// Supported actions:+// data-agent-action="stand-on" — park the avatar here on ready+// data-agent-action="track-typing" — focus walks to + caret tracking+// data-agent-action="privacy-mode" — focus walks to + covereyes (once+hold)+// data-agent-action="navigate-on-click" — runOff before following href+// data-agent-action="react-on-click" — play a clip on click+//+// Optional per-element attributes:+// data-agent-direction="left|right" — runOff direction (default right)+// data-agent-clip="<clipName>" — clip to play+// data-agent-anchor="<anchorName>" — anchor for walkTo target+// data-agent-delay="<ms>" — pre-navigation delay+// data-agent-loop="true|false" — loop flag for react-on-click clip+// data-agent-hold="true|false" — clampWhenFinished for react clip++import { startCaretTracking, caretScreenX } from './caret.js';++export function scan(root, agent) {+ const cleanups = [];+ let activeInput = null;+ let stopTracking = null;++ function clearTracking() {+ stopTracking?.();+ stopTracking = null;+ activeInput = null;+ }++ const els = root.querySelectorAll('[data-agent-action]');+ els.forEach((el) => {+ const action = el.dataset.agentAction;+ const dir = el.dataset.agentDirection === 'left' ? 'left' : 'right';+ const clip = el.dataset.agentClip;+ const anchor = el.dataset.agentAnchor;+ const delay = el.dataset.agentDelay ? parseInt(el.dataset.agentDelay, 10) : undefined;+ const loop = el.dataset.agentLoop === 'true';+ const hold = el.dataset.agentHold === 'true';++ switch (action) {+ case 'stand-on': {+ agent.whenReady(() => agent.standOn(el, anchor ? { anchor } : undefined));+ break;+ }+ case 'track-typing': {+ const onFocus = async () => {+ clearTracking();+ await agent.walkTo(el, anchor ? { anchor } : undefined);+ agent.play('lookdown', { loop: true });+ activeInput = el;+ stopTracking = startCaretTracking(el, (cx) => agent.lookAt(cx), () => activeInput);+ };+ const onBlur = () => { clearTracking(); agent.faceFront(); };+ const reaim = () => { if (activeInput === el) agent.lookAt(caretScreenX(el)); };+ el.addEventListener('focus', onFocus);+ el.addEventListener('blur', onBlur);+ el.addEventListener('input', reaim);+ el.addEventListener('keyup', reaim);+ el.addEventListener('click', reaim);+ cleanups.push(() => {+ el.removeEventListener('focus', onFocus);+ el.removeEventListener('blur', onBlur);+ el.removeEventListener('input', reaim);+ el.removeEventListener('keyup', reaim);+ el.removeEventListener('click', reaim);+ });+ break;+ }+ case 'privacy-mode': {+ const onFocus = async () => {+ clearTracking();+ await agent.walkTo(el, anchor ? { anchor } : undefined);+ agent.play(clip || 'covereyes', { loop: false, hold: true });+ agent.faceFront();+ };+ const onBlur = () => agent.play('idle', { loop: true });+ el.addEventListener('focus', onFocus);+ el.addEventListener('blur', onBlur);+ cleanups.push(() => {+ el.removeEventListener('focus', onFocus);+ el.removeEventListener('blur', onBlur);+ });+ break;+ }+ case 'navigate-on-click': {+ cleanups.push(agent.interceptNavigation(el, { direction: dir, delay }));+ break;+ }+ case 'react-on-click': {+ const onClick = () => {+ if (!clip) return;+ agent.play(clip, { loop, hold });+ };+ el.addEventListener('click', onClick);+ cleanups.push(() => el.removeEventListener('click', onClick));+ break;+ }+ }+ });++ return () => { cleanups.forEach((fn) => fn()); clearTracking(); };+}diff --git a/agent-ui-sdk/src/tween.js b/agent-ui-sdk/src/tween.jsnew file mode 100644index 000000000..b5a26d0d2--- /dev/null+++ b/agent-ui-sdk/src/tween.js@@ -0,0 +1,34 @@+// Tiny tween utilities used in place of gsap. Each fn returns a Promise that+// resolves when the tween ends and exposes .cancel() on the same promise so+// in-flight tweens can be interrupted.++export const smoothstep = (t) => t * t * (3 - 2 * t);+export const easeInQuad = (t) => t * t;+export const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);++export function tween({ duration = 400, ease = smoothstep, onUpdate, onComplete }) {+ let raf = 0;+ let cancelled = false;+ const t0 = performance.now();+ const p = new Promise((resolve) => {+ (function step(now) {+ if (cancelled) return;+ const t = Math.min((now - t0) / duration, 1);+ onUpdate(ease(t), t);+ if (t < 1) raf = requestAnimationFrame(step);+ else { onComplete?.(); resolve(); }+ })(performance.now());+ });+ p.cancel = () => { cancelled = true; cancelAnimationFrame(raf); };+ return p;+}++// Tween a numeric property on `obj` toward `to` over `duration` ms.+export function tweenProp(obj, prop, to, options = {}) {+ const from = obj[prop];+ const delta = to - from;+ return tween({+ ...options,+ onUpdate: (e) => { obj[prop] = from + delta * e; },+ });+}diff --git a/agent-ui-sdk/types/index.d.ts b/agent-ui-sdk/types/index.d.tsnew file mode 100644index 000000000..5118fedb5--- /dev/null+++ b/agent-ui-sdk/types/index.d.ts@@ -0,0 +1,254 @@+// Type definitions for @three-ws/agent-ui+// Project: https://three.ws++import type {+ AnimationClip,+ AnimationAction,+ Object3D,+ OrthographicCamera,+ Scene,+ WebGLRenderer,+ Bone,+} from 'three';++export interface SubclipSpec {+ /** Start frame (inclusive) */+ start: number;+ /** End frame (inclusive) */+ end: number;+ /** Frame rate the source clip was authored at. Default 30. */+ fps?: number;+}++export interface AgentUIOptions {+ /** Path to a .glb avatar. Default '/avatars/cz.glb'. */+ avatar?: string;+ /** Base URL for clip JSONs (joined with `${name}.json`). Default '/animations/clips/'. */+ clipsBase?: string;+ /** Names of clips to load eagerly. */+ clips?: string[];+ /** Per-clip subclip windows (e.g. trim the tail of a long Mixamo clip). */+ subclips?: Record<string, SubclipSpec>;+ /** Element to mount the overlay canvas into. Default document.body. */+ container?: HTMLElement;+ /** Pre-existing canvas to render into; else one is created. */+ canvas?: HTMLCanvasElement;+ /** z-index for the auto-created overlay canvas. Default 999. */+ zIndex?: number;+ /** How many screen pixels equal one Three.js world unit. Default 120. */+ pixelsPerUnit?: number;+ /** Enable mouse-driven camera parallax. Default true. */+ parallax?: boolean;+ /** Crossfade duration in seconds for animation transitions. Default 0.3. */+ crossfade?: number;+ /** Add default 3-point lighting rig. Default true. */+ lights?: boolean;+}++export interface PlayOptions {+ /** Loop the clip. Default true. */+ loop?: boolean;+ /** Hold the final frame after a non-looping clip ends. Default false. */+ hold?: boolean;+ /** Callback fired when a non-looping clip's last frame is reached. */+ onComplete?: () => void;+}++export interface MoveOptions {+ duration?: number;+ ease?: (t: number) => number;+}++export interface AnchorOptions {+ /** Where on the element the avatar should stand. Default 'top-center'. */+ anchor?:+ | 'top-left'+ | 'top-right'+ | 'top-center'+ | 'center'+ | 'bottom-center'+ | 'left-of'+ | 'right-of';+ offsetX?: number;+ offsetY?: number;+}++export interface WalkOptions extends AnchorOptions {+ walkClip?: string;+ duration?: number;+}++export interface StandOptions extends AnchorOptions {+ idleClip?: string;+}++export interface FallOptions extends AnchorOptions {+ fallClip?: string;+ /** Seconds. */+ duration?: number;+ /** Multiple of viewport height above the target to start. Default 0.6. */+ startOffsetVh?: number;+ /** Pixels above the element top to land on. Default 90. */+ landingOffsetPx?: number;+ /** Tumble amplitude during the fall. Default 0.25 radians. */+ tumble?: number;+ /** Called once the impact frame is reached. */+ onLand?: () => void;+}++export interface RunOffOptions {+ walkClip?: string;+ rotationDuration?: number;+ minDuration?: number;+ /** Travel speed for distance-based timing. Default 0.45 px/ms. */+ pxPerMs?: number;+}++export interface InterceptNavigationOptions {+ direction?: 'left' | 'right';+ /** Time in ms to wait after firing runOff before navigating. Default 1100. */+ delay?: number;+ /** Custom callback instead of following linkEl.href. */+ onAfter?: () => void;+}++export interface DustOptions {+ count?: number;+ gravity?: number;+ minSpeed?: number;+ maxSpeed?: number;+ minSize?: number;+ maxSize?: number;+ maxLifeMs?: number;+ yWithin?: number;+ zIndex?: number;+ color?: string;+}++export interface ImpactPulseOptions {+ dropPx?: number;+ elasticMs?: number;+}++export interface ProximityShadowOptions {+ maxDistancePx?: number;+ maxAlpha?: number;+ cssVar?: string;+}++export interface LookAtOptions {+ duration?: number;+ maxYaw?: number;+ sensitivity?: number;+}++export interface WorldPoint { x: number; y: number; }++export interface AgentUI {+ readonly THREE: typeof import('three');+ readonly renderer: WebGLRenderer;+ readonly scene: Scene;+ readonly camera: OrthographicCamera;+ readonly canvas: HTMLCanvasElement;+ readonly pixelsPerUnit: number;+ readonly avatar: Object3D;+ readonly rootBone: Bone | null;+ readonly currentClip: string | null;+ readonly ready: boolean;++ domToWorld(screenX: number, screenY: number): WorldPoint;+ worldToScreen(worldX: number, worldY: number): { x: number; y: number };+ worldOfElement(el: Element, options?: AnchorOptions): WorldPoint;++ play(name: string, options?: PlayOptions): void;+ clip(name: string): number;++ moveTo(target: WorldPoint, options?: MoveOptions): Promise<void>;+ lookAt(screenX: number, options?: LookAtOptions): Promise<void>;+ faceFront(options?: { duration?: number }): Promise<void>;++ standOn(el: Element, options?: StandOptions): void;+ walkTo(el: Element, options?: WalkOptions): Promise<void>;+ fallOnto(el: Element, options?: FallOptions): Promise<void>;+ runOff(direction?: 'left' | 'right', options?: RunOffOptions): Promise<void>;+ interceptNavigation(linkEl: HTMLAnchorElement | HTMLElement, options?: InterceptNavigationOptions): () => void;++ fx: {+ dust(el: Element, options?: DustOptions): void;+ impactPulse(el: Element, options?: ImpactPulseOptions): () => void;+ /** Returns a disposer that stops the per-frame update + clears the CSS var. */+ proximityShadow(el: Element, options?: ProximityShadowOptions): () => void;+ };++ caretScreenX(input: HTMLInputElement): number;+ startCaretTracking(+ input: HTMLInputElement,+ onChange: (screenX: number) => void,+ getActive: () => HTMLInputElement | null,+ ): () => void;++ pickFrom(pool: string[]): () => string | null;++ scan(root?: ParentNode): () => void;+ whenReady(fn: (agent: AgentUI) => void): void;+ destroy(): void;+}++export function createAgentUI(options?: AgentUIOptions): Promise<AgentUI>;++// Lower-level exports for power users assembling their own pipeline.+export function createRenderer(options?: {+ container?: HTMLElement;+ canvas?: HTMLCanvasElement;+ zIndex?: number;+ pixelsPerUnit?: number;+ lights?: boolean;+ parallax?: boolean;+}): {+ canvas: HTMLCanvasElement;+ renderer: WebGLRenderer;+ scene: Scene;+ camera: OrthographicCamera;+ pixelsPerUnit: number;+ domToWorld(x: number, y: number): WorldPoint;+ worldToScreen(x: number, y: number): { x: number; y: number };+ updateParallax(): void;+ destroy(): void;+};++export function loadAvatar(options: {+ avatar: string;+ clipsBase: string;+ clips: string[];+ subclips?: Record<string, SubclipSpec>;+}): Promise<{ object: Object3D; rootBone: Bone | null; clips: Record<string, AnimationClip>; }>;++export function createAnimator(options: {+ object: Object3D;+ clips: Record<string, AnimationClip>;+ crossfade?: number;+}): {+ play(name: string, options?: PlayOptions): void;+ update(dt: number): void;+ clipDuration(name: string): number;+ readonly currentName: string | null;+ actions: Record<string, AnimationAction>;+ clips: Record<string, AnimationClip>;+};++export function lockRootMotion(renderer: WebGLRenderer, rootBone: Bone | null): () => void;+export function createRandomPicker(pool: string[]): () => string | null;+export function caretScreenX(input: HTMLInputElement): number;+export function startCaretTracking(+ input: HTMLInputElement,+ onChange: (screenX: number) => void,+ getActive: () => HTMLInputElement | null,+): () => void;+export function dust(el: Element, options?: DustOptions): void;+export function impactPulse(el: Element, options?: ImpactPulseOptions): () => void;+export function proximityShadow(+ el: Element,+ agent: { avatar: Object3D | null; worldToScreen(x: number, y: number): { x: number; y: number } },+ options?: ProximityShadowOptions,+): { tick(): void; dispose(): void };+export function scan(root: ParentNode, agent: AgentUI): () => void;diff --git a/package-lock.json b/package-lock.jsonindex 69764c9f1..153e3a533 100644--- a/package-lock.json+++ b/package-lock.json@@ -11,6 +11,7 @@"license": "Apache-2.0","workspaces": ["agent-payments-sdk",+ "agent-ui-sdk","avatar-sdk","character-studio","mcp-bridge",@@ -187,6 +188,17 @@"dev": true,"license": "MIT"},+ "agent-ui-sdk": {+ "name": "@three-ws/agent-ui",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "three": ">=0.150.0"+ }+ },"avatar-sdk": {"name": "@three-ws/avatar","version": "0.1.0",@@ -19902,6 +19914,10 @@}}},+ "node_modules/@three-ws/agent-ui": {+ "resolved": "agent-ui-sdk",+ "link": true+ },"node_modules/@three-ws/avatar": {"resolved": "avatar-sdk","link": truediff --git a/package.json b/package.jsonindex 59c5399c9..a0fe6dd78 100644--- a/package.json+++ b/package.json@@ -24,6 +24,7 @@],"workspaces": ["agent-payments-sdk",+ "agent-ui-sdk","avatar-sdk","character-studio","mcp-bridge",