Skip to content

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.

feat(embed): host + action bridges — closes band 5

nirholas470948cff9f2
diff --git a/prompts/archive/final-integration/01-embed-bridges.md b/prompts/archive/final-integration/01-embed-bridges.md
new file mode 100644
index 000000000..4354b71d4
--- /dev/null
+++ b/prompts/archive/final-integration/01-embed-bridges.md
@@ -0,0 +1,153 @@
+# 01 — Embed Host + Action Bridges
+
+## Context
+
+The `<agent-3d>` web component is the sole distribution channel for the 3D Agent product. It's embedded inside third-party sites (Claude.ai artifacts, LobeHub plugins, customer pages). When an agent lives inside an iframe, the host page has no way to talk to it and vice versa — you can't tell the agent to speak, change avatar, or react to chat messages. You also can't hear the agent's events (skill calls, action logs, state changes) from the parent.
+
+Sprint-100 mapped two bridge modules to fill this gap:
+- `src/embed-host-bridge.js` — iframe ↔ parent `postMessage` transport. Handshake, origin check, request/response routing.
+- `src/embed-action-bridge.js` — translates bridge messages into `AgentProtocol` events on the agent side and back out on the parent side.
+
+**Neither file was ever written.** The [lobehub-plugin/](../../lobehub-plugin/) already assumes these exist — `AgentBridge` in `lobehub-plugin/src/bridge.ts` calls `postMessage` with a schema that needs a matching receiver on the `<agent-3d>` side. Ship both files.
+
+## Goal
+
+Build a production-grade bidirectional bridge between a host page and an embedded `<agent-3d>` instance. Every action the agent can do through `AgentProtocol` must be reachable from the host; every event the agent emits should be observable (with consent) by the host.
+
+## Files you own
+
+Create:
+- `src/embed-host-bridge.js`
+- `src/embed-action-bridge.js`
+
+Edit (inside uniquely-named anchor only):
+- `src/element.js` — add a single anchor block `<!-- BEGIN:EMBED_BRIDGES --> ... <!-- END:EMBED_BRIDGES -->` near the end of the `connectedCallback` / mount path. Wire both bridges in when the element mounts inside an iframe. **Do not edit anything outside that anchor.**
+
+## Files read-only
+
+- `src/agent-protocol.js` — learn the `ACTION_TYPES` set.
+- `src/agent-avatar.js` — learn what actions the performer honors.
+- `lobehub-plugin/src/bridge.ts` — reference for the wire protocol the plugin side already expects.
+- `specs/EMBED_SPEC.md` — the embed contract.
+
+## Wire protocol
+
+Use `postMessage` with a structured envelope. Every message MUST include:
+
+```js
+{
+ v: 1, // protocol version
+ source: 'agent-3d', // or 'agent-host'
+ id: 'uuid-v4', // unique per request
+ inReplyTo: 'uuid', // present on responses only
+ kind: 'request' | 'response' | 'event',
+ op: 'speak' | 'gesture' | 'emote' | 'look' | 'setAgent' | 'ping' | 'ready' | ...,
+ payload: { ... } // op-specific
+}
+```
+
+Handshake:
+- Child (`agent-3d`) posts `{ kind: 'event', op: 'ready', payload: { agentId, capabilities: [...] } }` once mounted.
+- Parent responds with `{ kind: 'request', op: 'ping' }`; child replies `{ kind: 'response', op: 'pong', inReplyTo }`. That round-trip confirms both sides.
+
+Origin security:
+- Respect the agent manifest's `policy.origins` allowlist (already parsed by `src/element.js:originAllowed`). Reject any `postMessage` whose `event.origin` is not on the allowlist.
+- On the parent side, accept messages only from `event.source === iframe.contentWindow`.
+
+Timeouts & retries:
+- Requests carry a 10s timeout. If no response, reject with `TimeoutError`.
+- No automatic retries — the host decides.
+
+Backpressure:
+- Queue outgoing requests if handshake is not yet complete. Flush on `ready`.
+- Drop events (never buffer them indefinitely) if no listener — cap at 256 queued events to prevent memory runaway.
+
+## Host bridge surface (`src/embed-host-bridge.js`)
+
+Export a class `EmbedHostBridge` with:
+
+```js
+new EmbedHostBridge({ iframe, agentId, allowedOrigin })
+ .ready: Promise<{ agentId, capabilities }>
+ .speak(text, opts?): Promise<void>
+ .gesture(name): Promise<void>
+ .emote({ trigger, weight }): Promise<void>
+ .look({ target }): Promise<void>
+ .setAgent(nextAgentId): Promise<void>
+ .on(event, handler): unsubscribe // 'action', 'state', 'error'
+ .destroy(): void
+```
+
+Internally: one `window.addEventListener('message', …)` registered on construction, removed on destroy. All outgoing calls resolve via `inReplyTo` map.
+
+## Action bridge surface (`src/embed-action-bridge.js`)
+
+Export a class `EmbedActionBridge` that lives **inside** the `<agent-3d>` element. It:
+
+1. Subscribes to `window.addEventListener('message', …)` filtered to requests that pass the origin allowlist.
+2. Translates each request into one or more `AgentProtocol.emit(...)` calls using the canonical `ACTION_TYPES`.
+3. For each action emitted by the agent (subscribe to `protocol.on('action', …)`), echoes it out as a `kind: 'event'` message if the host has subscribed (honor an explicit `subscribe` request to opt-in; do NOT leak actions by default).
+4. Translates protocol errors into `kind: 'event', op: 'error', payload: { code, message }`.
+
+Constructor:
+```js
+new EmbedActionBridge({ protocol, avatar, manifest, window: win })
+ .start(): void
+ .stop(): void
+```
+
+Must not mutate the protocol bus beyond adding listeners. Must clean up on `stop()`.
+
+## Element wiring (`src/element.js`)
+
+Inside the anchor block `EMBED_BRIDGES`, at the tail of the mount path (after `runtime` + `sceneController` + `avatar` are all set up), add:
+
+```js
+// BEGIN:EMBED_BRIDGES
+import { EmbedActionBridge } from './embed-action-bridge.js';
+
+if (window !== window.parent) {
+ this._embedBridge = new EmbedActionBridge({
+ protocol: this._protocol,
+ avatar: this._avatar,
+ manifest: this._manifest,
+ window,
+ });
+ this._embedBridge.start();
+}
+// END:EMBED_BRIDGES
+```
+
+Also add a matching `this._embedBridge?.stop()` call inside the existing `disconnectedCallback`, still within the anchor block. The import line belongs outside the `connectedCallback` function — place it inside the anchor block near the existing imports at top of file (use a second anchor `EMBED_BRIDGES_IMPORT` if cleaner).
+
+Do not import `EmbedHostBridge` here — that's the parent-page side and is consumed externally (from `lobehub-plugin/src/bridge.ts` et al.).
+
+## Deliverables checklist
+
+- [ ] `src/embed-host-bridge.js` created, ~150–250 LOC, JSDoc typed, class `EmbedHostBridge` exported.
+- [ ] `src/embed-action-bridge.js` created, ~150–250 LOC, class `EmbedActionBridge` exported.
+- [ ] `src/element.js` has exactly one `BEGIN:EMBED_BRIDGES` / `END:EMBED_BRIDGES` anchor block; no edits outside it.
+- [ ] `lobehub-plugin/src/bridge.ts` works against the new wire format (verify by reading — do not edit, that's prompt 05's turf).
+- [ ] Handshake, timeout, origin check, subscribe/unsubscribe, error propagation all implemented.
+- [ ] No new runtime deps. Use crypto.randomUUID for ids (polyfill only if `typeof crypto.randomUUID !== 'function'`).
+- [ ] Prettier pass on all touched files.
+
+## Acceptance
+
+- `node --check src/embed-host-bridge.js` passes.
+- `node --check src/embed-action-bridge.js` passes.
+- `node --check src/element.js` passes.
+- `npm run build` succeeds with no new warnings.
+- Manual check: `git grep -n "EMBED_BRIDGES" src/element.js` returns exactly 2 lines (BEGIN + END) for each anchor (import + mount).
+- Manual check: `git grep -n "EmbedActionBridge\|EmbedHostBridge" src/ lobehub-plugin/src/` shows both modules referenced.
+- Manual sanity: in a browser console at `localhost:3000/agent-embed.html?agent=<id>` inside an iframe, the parent can `postMessage({v:1,source:'agent-host',id:'x',kind:'request',op:'ping'})` and receive a `pong` response.
+
+## Report + archive
+
+Post the report block from `00-README.md`, then run:
+
+```bash
+git mv prompts/final-integration/01-embed-bridges.md prompts/archive/final-integration/01-embed-bridges.md
+```
+
+Commit with message: `feat(embed): host + action bridges — closes band 5`.
diff --git a/prompts/final-integration/00-README.md b/prompts/final-integration/00-README.md
new file mode 100644
index 000000000..0e5bf78f6
--- /dev/null
+++ b/prompts/final-integration/00-README.md
@@ -0,0 +1,69 @@
+# Final Integration — Close the 28% Gap to 100%
+
+This folder contains **7 parallel-safe prompts** that finish the 3D Agent platform: they build the 3 sprint-100 modules that were never created, wire the 4 orphan modules that shipped without integration, and close out the LobeHub plugin integration, camera-capture decision, and end-to-end smoke test.
+
+The audit that produced these prompts found that ~72% of the stated work is wired and functional. Files exist for most sprint-100 deliverables but many are orphans — real code, zero import sites. Three files mapped in the sprint-100 plan were never written at all.
+
+## Running rules
+
+1. **Run in any order.** Every prompt below owns a **disjoint** set of files. Shared-file edits use uniquely-named anchor comments so two agents will not collide.
+2. **One agent, one prompt.** Open a new chat, paste the `.md` contents as the first message.
+3. **Self-archive when done.** The last step of every prompt is `git mv prompts/final-integration/<this-file>.md prompts/archive/final-integration/<this-file>.md`. Run it yourself — the wrapper will not do it for you.
+4. **Own only the files listed.** Read anything; write nothing outside the owned set. If a piece you need does not exist, stub it and note the stub — do not reach into someone else's files.
+5. **Prettier** before committing: tabs, 4-wide, single quotes, 100-col. `npx prettier --write` every file you touched.
+6. **Verify** with `node --check <file>` on every JS file and `npm run build`. Paste both outputs into your report.
+7. **No new runtime deps** unless the prompt explicitly lists them. Bundle size matters.
+8. **ESM only** in `src/` and `api/`. No CommonJS. No TypeScript in the main app (SDK & lobehub-plugin are allowed TS — they are separate packages).
+9. **JSDoc for public APIs.** No long docstrings or multi-paragraph comments. Follow the conventions in `CLAUDE.md`.
+10. **Do not** amend the contract ABI, deployed addresses, or `REGISTRY_DEPLOYMENTS`. Read-only unless the prompt says otherwise.
+
+## File-ownership map (no overlaps)
+
+| # | Prompt | Primary new files | Shared-file anchors |
+|---|---|---|---|
+| 01 | `01-embed-bridges.md` | `src/embed-host-bridge.js`, `src/embed-action-bridge.js` | `src/element.js` — anchor `EMBED_BRIDGES` |
+| 02 | `02-idle-animation.md` | `src/idle-animation.js` | `src/agent-avatar.js` — anchor `IDLE_LOOP` |
+| 03 | `03-agent-home-integration.md` | (none) | `agent-home.html` — anchor `AGENT_HOME_ORPHANS` |
+| 04 | `04-discover-page.md` | `public/discover/index.html`, `public/discover/discover.js`, `public/discover/discover.css` | homepage CTA added via anchor `DISCOVER_LINK` in `index.html` |
+| 05 | `05-lobehub-real-integration.md` | everything under `lobehub-plugin/` | — |
+| 06 | `06-camera-capture-resolution.md` | — | `src/camera-capture.js` (delete or repurpose) + `src/camera-capture.css` |
+| 07 | `07-qa-smoke-test.md` | `docs/SMOKE_TEST.md` | — (read-only audit; may open small surgical fixes in any file with 1-line patch rule) |
+
+## Shared-file anchor protocol
+
+When a prompt edits a shared file (`src/element.js`, `src/agent-avatar.js`, `agent-home.html`, `index.html`), it must:
+
+1. Find the anchor comment named in the map above, e.g. `<!-- BEGIN:AGENT_HOME_ORPHANS --> ... <!-- END:AGENT_HOME_ORPHANS -->`.
+2. If the anchor block does not yet exist, **create it** at the location the prompt describes, with both `BEGIN` and `END` comment markers.
+3. Only insert new code **between** those markers. Never edit code outside them.
+4. If your anchor name already contains content from a previous run, treat it as the latest version and either extend or replace — use `git diff` to understand context before overwriting.
+
+This guarantees parallel runs never stomp each other even if two agents touch the same file.
+
+## What counts as "done"
+
+A prompt is complete when:
+- Every file listed under **Deliverables** exists and passes `node --check`.
+- `npm run build` succeeds with zero new warnings.
+- The **Acceptance** checklist passes.
+- The **Report** block is posted in the chat (files changed, commands run + output, what was skipped, unrelated bugs noticed).
+- The prompt file has been `git mv`d into `prompts/archive/final-integration/`.
+
+If you cannot complete everything, commit what works, archive anyway with a **Partially Complete** banner at the top of the archived file describing exactly what was left undone. Do NOT leave the prompt in `final-integration/` — a prompt in that folder means "not attempted yet." Partial work belongs in archive with notes.
+
+## Reporting template
+
+Every prompt ends with this block in the agent's final message:
+
+```
+## Report
+**Files changed:** <list>
+**Commands run:** <list with output snippets>
+**Skipped / stubbed:** <list with reason>
+**Unrelated bugs noticed:** <list, do NOT fix them here>
+**Archive command run:** git mv prompts/final-integration/XX-foo.md prompts/archive/final-integration/XX-foo.md — ✅/❌
+```
+
+## After all 7 are archived
+
+Overall completion target: **≥95%**. Remaining 5% is product/design polish beyond the scope of these prompts and should be re-scoped by a human PM pass.
diff --git a/prompts/final-integration/02-idle-animation.md b/prompts/final-integration/02-idle-animation.md
new file mode 100644
index 000000000..88d91eb58
--- /dev/null
+++ b/prompts/final-integration/02-idle-animation.md
@@ -0,0 +1,134 @@
+# 02 — Idle Animation Loop
+
+## Context
+
+A static avatar dies on screen. Without idle motion, users think the page froze; with it, the agent looks alive even when nothing is happening. Sprint-100 mapped an `idle-animation.js` module — a subtle continuous ambient loop (breathing, micro-saccades, weight-shifting, blink) — but **the file was never written**. The empathy layer in `src/agent-avatar.js` already handles *reactive* morph blending; this prompt fills in the *baseline* motion underneath.
+
+This is the difference between a kiosk mannequin and something that looks embodied. It is table-stakes for every embed surface: Claude artifact, LobeHub plugin, CZ landing, dashboard preview, and the public viewer.
+
+## Goal
+
+Implement a tasteful, performant idle loop that runs whenever no other animation is overriding the avatar. The loop must be subtle (never distracting), cheap (runs in the per-frame update, must cost < 0.3ms on a mid-range laptop for a Mixamo-rigged avatar), and respectful of the empathy layer (additive, not replacing).
+
+## Files you own
+
+Create:
+- `src/idle-animation.js`
+
+Edit (inside uniquely-named anchor only):
+- `src/agent-avatar.js` — add a single anchor block `// BEGIN:IDLE_LOOP ... // END:IDLE_LOOP` and a matching import block `// BEGIN:IDLE_LOOP_IMPORT ... // END:IDLE_LOOP_IMPORT`. Wire the idle controller in once per avatar mount; tick it from the existing per-frame update. **No edits outside these anchors.**
+
+## Files read-only
+
+- `src/agent-avatar.js` — understand the existing empathy blend, morph target traversal, and per-frame hook. Find the method that runs every frame (likely `update(dt)` or similar).
+- `src/agent-protocol.js` — `ACTION_TYPES` tells you which actions should *pause* idle (e.g. when the avatar is actively speaking or gesturing).
+- `src/runtime/scene.js` — `SceneController` for context.
+
+## Design — what "idle" means
+
+Four independent, additive channels (ordered by weight in the final blend):
+
+1. **Breathing** — sinusoidal chest/shoulder bone rotation (if bones exist) or `mouthOpen`/`browInnerUp` morph micro-modulation as fallback. Period ~4s. Amplitude ~1% of neutral. Never clip.
+2. **Micro-saccades** — small random eye/head yaw/pitch offsets (±1.5°) with dwell times in [0.8, 2.4]s. Smoothed (critically damped spring, zeta≈1). Pause when `AgentProtocol` emits a `look` action; resume 500ms after the look target is cleared.
+3. **Blink** — close both eyelid morphs (`eyeBlinkLeft`, `eyeBlinkRight` if present) to 1.0 over 80ms, hold 40ms, open over 120ms. Random interval uniformly in [2.5, 6.0]s. Skipped during `speak` actions (blink feels weird mid-phoneme).
+4. **Weight shift** — slow hip bone yaw drift (±0.5°) with 8s period, different phase per avatar (seeded by agent id hash) so multiple avatars on a page do not sync.
+
+Every channel defaults to `enabled: true` but can be toggled individually via a `setChannels({...})` method.
+
+Critical constraint: **empathy layer must win**. If the blended morph weight for `mouthOpen` from the empathy layer is > 0.2 (user is talking), the breathing channel stops touching `mouthOpen`. The idle module reads the current frame's empathy weights before applying; never overwrite, always add.
+
+## API surface (`src/idle-animation.js`)
+
+```js
+export class IdleAnimation {
+ /**
+ * @param {object} opts
+ * @param {THREE.Object3D} opts.root Avatar root (skinned mesh hierarchy).
+ * @param {object} opts.protocol AgentProtocol instance (to observe speak/gesture).
+ * @param {string} [opts.seed] Stable seed for per-avatar phase (use agent id).
+ * @param {Partial<{breathing,saccade,blink,weightShift}>} [opts.channels]
+ */
+ constructor(opts) { ... }
+
+ /** Call every frame with elapsed seconds since last tick. */
+ update(dt) { ... }
+
+ /** Toggle channels at runtime. Accepts partial — unmentioned channels unchanged. */
+ setChannels(partial) { ... }
+
+ /** Stop all timers and detach protocol listeners. */
+ dispose() { ... }
+}
+```
+
+Internals:
+- Collect eyelid, brow, mouth morph indices once in constructor; cache them.
+- Collect head/neck/hip bones by name (search Mixamo + RPM + generic — try `Head`, `mixamorig:Head`, `neck`, etc). Log once if none found; fail soft (no errors at runtime).
+- No `setInterval` / `setTimeout` — everything is dt-driven from `update()`. This keeps the module pausable, scrubbable, and test-friendly.
+- No allocations in `update()`. Reuse `THREE.Euler` / `Quaternion` scratch buffers kept as instance fields.
+
+Deterministic jitter via a small mulberry32 PRNG seeded by `opts.seed` — do NOT use `Math.random()`.
+
+## Wiring into `src/agent-avatar.js`
+
+Find the constructor and the per-frame update method. Add:
+
+```js
+// BEGIN:IDLE_LOOP_IMPORT
+import { IdleAnimation } from './idle-animation.js';
+// END:IDLE_LOOP_IMPORT
+```
+
+In the constructor (or wherever the avatar root object becomes available — possibly a `setAvatar`/`onLoad` method):
+
+```js
+// BEGIN:IDLE_LOOP
+this._idle = new IdleAnimation({
+ root: <theAvatarRoot>,
+ protocol: this._protocol, // or however it's referenced in this class
+ seed: this._agentId ?? 'default',
+});
+// END:IDLE_LOOP
+```
+
+In the per-frame update method (within the same or a neighbouring anchor, depending on file layout):
+
+```js
+// Inside BEGIN:IDLE_LOOP ... END:IDLE_LOOP
+this._idle?.update(dt);
+```
+
+In the avatar disposal/unmount path: `this._idle?.dispose();`.
+
+If the anchor block layout gets awkward because the constructor and the update method are far apart, use three separate anchor pairs with unique suffixes: `IDLE_LOOP_IMPORT`, `IDLE_LOOP_INIT`, `IDLE_LOOP_TICK`, `IDLE_LOOP_DISPOSE`. Log exactly which ones you used in the report.
+
+## Deliverables checklist
+
+- [ ] `src/idle-animation.js` created, ~200–350 LOC, JSDoc typed.
+- [ ] Four channels implemented: breathing, micro-saccades, blink, weight-shift. Each independently toggleable.
+- [ ] Empathy-layer deference: idle never overwrites, always adds; breathing backs off `mouthOpen` when empathy weight > 0.2.
+- [ ] No `setTimeout`/`setInterval`. Pure dt-driven.
+- [ ] No allocations in hot path (`update()`).
+- [ ] Deterministic seeded jitter (mulberry32).
+- [ ] Wired into `src/agent-avatar.js` via `IDLE_LOOP*` anchor blocks only.
+- [ ] `dispose()` cleans up protocol listeners.
+- [ ] Prettier pass on all touched files.
+
+## Acceptance
+
+- `node --check src/idle-animation.js` passes.
+- `node --check src/agent-avatar.js` passes.
+- `npm run build` succeeds with no new warnings.
+- `git grep -n "IDLE_LOOP" src/agent-avatar.js` shows paired BEGIN/END anchors only.
+- `git grep -n "setInterval\|setTimeout" src/idle-animation.js` returns zero matches.
+- Manual smoke: load `localhost:3000/?m=<sample-glb>` with an avatar that has eyelid morphs — observe blinks within ~5s, subtle breathing rise/fall, head drifts during silence, breathing backs off when the avatar speaks.
+
+## Report + archive
+
+Post the report block from `00-README.md`, then:
+
+```bash
+git mv prompts/final-integration/02-idle-animation.md prompts/archive/final-integration/02-idle-animation.md
+```
+
+Commit: `feat(avatar): idle animation loop — breathing, saccade, blink, weight-shift`.
diff --git a/prompts/final-integration/03-agent-home-integration.md b/prompts/final-integration/03-agent-home-integration.md
new file mode 100644
index 000000000..1ea9181c3
--- /dev/null
+++ b/prompts/final-integration/03-agent-home-integration.md
@@ -0,0 +1,96 @@
+# 03 — Mount Share Panel + Deploy Button on Agent Home
+
+## Context
+
+[agent-home.html](../../agent-home.html) is the public landing page for any agent (route: `/agent/:id`). It is the single most-seen surface the product has — every shared link, every social preview, every embed lands visitors here first.
+
+Two major modules shipped but never got mounted on this page:
+
+1. **[src/share-panel.js](../../src/share-panel.js)** (215 LOC, production-ready) — one-click share modal with link, iframe snippet, web-component snippet, OG preview, and QR code. Class `SharePanel` is exported but **zero import sites** in the codebase.
+2. **[src/erc8004/deploy-button.js](../../src/erc8004/deploy-button.js)** (282 LOC, production-ready) — minimal drop-in "Deploy on-chain" chip. Shows a deploy button if the agent is not yet ERC-8004 registered; shows a success chip with tx link if it is. Also orphan.
+
+Both classes are complete. Your job is UX plumbing: mount them on `agent-home.html` such that a visiting user can (a) share the agent, and (b) the *owner* of the agent can deploy it on-chain without leaving the page.
+
+## Goal
+
+A polished agent landing page where:
+- A **Share** button sits in a predictable top-right corner. Click → `SharePanel.open()`.
+- A **Deploy on-chain** chip appears next to the agent name, but **only if the signed-in user is the agent owner** AND the agent is not yet registered on-chain. If already registered, the chip shows the chain + tx link instead. If the viewer is not the owner, nothing on-chain-related is visible.
+- Both controls are keyboard accessible (tab-reachable, Enter/Space activates) and work on mobile (tap targets ≥ 44×44 px).
+
+## Files you own
+
+Edit (inside uniquely-named anchor only):
+- `agent-home.html` — add anchor blocks:
+ - `<!-- BEGIN:AGENT_HOME_ORPHANS_HEAD --> ... <!-- END:AGENT_HOME_ORPHANS_HEAD -->` in `<head>` for any CSS links.
+ - `<!-- BEGIN:AGENT_HOME_ORPHANS_DOM --> ... <!-- END:AGENT_HOME_ORPHANS_DOM -->` in the body for the share button markup (put next to the page chrome, typically top-right).
+ - `<!-- BEGIN:AGENT_HOME_ORPHANS_SCRIPT --> ... <!-- END:AGENT_HOME_ORPHANS_SCRIPT -->` near existing scripts at end of body for the module-script wiring.
+- (Optional new file if needed) `src/agent-home-orphans.js` — the glue module that imports `SharePanel` + `DeployButton`, resolves current user + agent ownership, and mounts both. Create this file if keeping wiring out of inline HTML feels cleaner (recommended).
+
+## Files read-only
+
+- `src/share-panel.js` — API: `new SharePanel({ agent, container, embedOrigin }).open()`.
+- `src/erc8004/deploy-button.js` — API: `new DeployButton({ agent, owner, container, onDeployed })`. Read the exported class carefully — note the agent shape it expects.
+- `api/_lib/auth.js` — `getSessionUser` is server-side; use the client-side session helpers instead.
+- `src/wallet-auth.js` — helpers like `getCurrentUser()` / `getCurrentWallet()` for ownership resolution.
+- `src/app.js` — understand how the agent record is currently hydrated on this page; reuse that data (do not refetch).
+- `api/agents/[id].js` — the shape of the agent record.
+
+## UX requirements
+
+**Share button:**
+- Button label: `Share` with an outline share icon (use an inline SVG; do not import an icon library).
+- Placement: top-right of the main content area, aligned with the agent name/avatar thumbnail.
+- Click: instantiate `SharePanel` once (cache the instance), call `.open()`. Reuse on subsequent clicks; never instantiate twice.
+- Visible to ALL visitors (not gated).
+
+**Deploy chip:**
+- Render container: inline with the agent name, separated by a 12px gap.
+- States:
+ - Not on-chain + viewer is owner → `<DeployButton>` primary CTA.
+ - On-chain → small pill showing chain name + shortened tx hash, linking out to the block explorer. Use `txExplorerUrl` from `src/erc8004/chain-meta.js` (read-only).
+ - Not on-chain + viewer is NOT owner → render nothing.
+ - User not signed in → render nothing (do not render a "sign in to deploy" prompt here; that's homepage's job).
+- On successful deploy (via `onDeployed` callback): refresh the local agent record in place (do not hard-reload the page) and transition the chip to the on-chain success state. A brief toast `Agent registered on <chain>` is acceptable but not required.
+
+**Ownership resolution rules:**
+- The agent record has an `owner_user_id` field (or equivalent — verify against `api/agents/[id].js`). Match against the signed-in user's id.
+- If the agent has a wallet-based owner (`owner_wallet`), match against the user's linked wallets via whichever helper `src/wallet-auth.js` exposes.
+- **Do not** call `eth_accounts` from this module — that's a wallet connection, not an identity check. Ownership is a server-known fact.
+- If ownership cannot be determined (no session, no wallet, API failure), treat as not-owner. Never show deploy UI on uncertainty.
+
+**Accessibility:**
+- `aria-label="Share agent"` on the share button; `aria-haspopup="dialog"`.
+- Deploy chip: button semantics when actionable, link semantics when pointing to explorer.
+- Focus trap inside share panel is already handled by `SharePanel` — do not duplicate.
+
+**No layout regressions:**
+- Before committing, open `agent-home.html` in the dev server and verify the existing page layout is unchanged at common viewport widths (360, 768, 1280, 1920). Screenshot in the report if possible.
+
+## Deliverables checklist
+
+- [ ] `agent-home.html` has the three anchor blocks, correctly named.
+- [ ] Share button mounts and opens the existing `SharePanel` without modification to `share-panel.js`.
+- [ ] Deploy chip mounts conditionally per the state machine above.
+- [ ] Ownership check works against the real session + wallet link state (verify by signing in and out).
+- [ ] `onDeployed` callback transitions the chip without page reload.
+- [ ] If you created `src/agent-home-orphans.js`, it's ESM, ~80–160 LOC, JSDoc typed.
+- [ ] Prettier pass on all touched files.
+- [ ] No new runtime deps.
+
+## Acceptance
+
+- `node --check` passes on every JS file touched.
+- `npm run build` succeeds with no new warnings.
+- `git grep -n "AGENT_HOME_ORPHANS" agent-home.html` shows exactly three BEGIN/END pairs.
+- Manual smoke: in dev, load `/agent/<known-id>` → Share button visible, opens panel, QR + snippets populate. As agent owner, deploy chip visible; as anonymous, chip absent.
+
+## Report + archive
+
+Post the report block from `00-README.md`, then:
+
+```bash
+git mv prompts/final-integration/03-agent-home-integration.md prompts/archive/final-integration/03-agent-home-integration.md
+```
+
+Commit: `feat(agent-home): mount share panel + deploy chip`.
diff --git a/prompts/final-integration/04-discover-page.md b/prompts/final-integration/04-discover-page.md
new file mode 100644
index 000000000..c283cc617
--- /dev/null
+++ b/prompts/final-integration/04-discover-page.md
@@ -0,0 +1,128 @@
+# 04 — On-Chain Discover Page (Hydrate Wire-Up)
+
+## Context
+
+Users sign in with their wallet. Behind that wallet, they may already own ERC-8004 agent NFTs that they've registered or acquired elsewhere — the product should *find* those agents and pull them into the user's library automatically. The backend endpoint `/api/erc8004/hydrate` already enumerates on-chain agents for any linked wallet; the client helper `src/erc8004/hydrate.js` wraps both `fetchDiscoveredAgents()` and `importAgent()`.
+
+**The UI that uses these helpers does not exist.** The module is an orphan.
+
+Your job: build a polished standalone `/discover` page that shows the signed-in user every on-chain agent they own across chains, lets them import any into the app with a click, and gracefully handles empty/error states.
+
+## Goal
+
+A `/discover` route that, for a signed-in user:
+- Lists every agent discovered via their linked wallets across all supported chains.
+- Flags ones already imported vs. importable.
+- One-click imports an agent into the user's library (calls `importAgent()`).
+- Shows a visual preview (thumbnail + name) for each agent.
+- Handles zero linked wallets, zero discovered agents, network errors, and rate limits.
+
+This page is how a new wallet-first user gets their existing agents into the app on first sign-in — without it, they see an empty dashboard and churn.
+
+## Files you own
+
+Create:
+- `public/discover/index.html`
+- `public/discover/discover.js`
+- `public/discover/discover.css`
+
+Edit (inside uniquely-named anchor only):
+- `index.html` — add anchor block `<!-- BEGIN:DISCOVER_LINK --> ... <!-- END:DISCOVER_LINK -->` on the homepage. Inside: a single CTA link/button that routes to `/discover` (visible only when signed in — use a JS gate inside the anchor, or a CSS class toggled by existing session code). **No edits outside the anchor.**
+
+Also ensure `/discover` resolves:
+- Check [vite.config.js](../../vite.config.js) `vercel-rewrites` plugin and [vercel.json](../../vercel.json). The rewrite rules may already match `public/**` → add an entry if `/discover` does not resolve to `public/discover/index.html`. If you need to add a single line to either file, do so inside a `BEGIN:DISCOVER_ROUTE` anchor in that file. Otherwise leave both untouched.
+
+## Files read-only
+
+- `src/erc8004/hydrate.js` — the client helper. API: `fetchDiscoveredAgents()` and `importAgent({ chainId, agentId })`.
+- `api/erc8004/hydrate.js` — learn the response shape returned to the client.
+- `api/erc8004/import.js` — learn the import side-effects.
+- `src/wallet-auth.js` — session helpers for detecting signed-in state.
+- `src/erc8004/chain-meta.js` — chain name + explorer URL helpers for display.
+- `api/_lib/auth.js` — understand what `credentials: 'include'` gets you.
+- `public/dashboard/` — style reference; match the existing look-and-feel.
+
+## UX requirements
+
+**Page layout:**
+- Header with title `On-chain Agents`, subtitle `Agents we found in your linked wallets`.
+- Link back to homepage + link to dashboard.
+- Grid of agent cards (1 col mobile, 2 col tablet, 3 col desktop).
+- Each card: square thumbnail (glbUrl preview fallback to `image`), name, chain pill, short description, action button (`Import` or `Already in library`).
+- Empty states:
+ - Not signed in → page renders a single CTA `Sign in to discover your agents` → `/login.html`.
+ - Signed in, no linked wallets → CTA `Link a wallet to get started` → `/dashboard/wallets.html`.
+ - Signed in, wallets linked, zero agents → friendly illustration/text `No on-chain agents yet — register one from the dashboard`.
+- Error states:
+ - Network error → inline error with a retry button.
+ - Rate-limited (429) → explicit `Too many requests. Try again in a minute.`
+- Loading state: skeleton cards with shimmer animation (CSS only, no JS animation).
+
+**Import flow:**
+- Click `Import` → button enters busy state, disables, fetches `importAgent(...)` via `src/erc8004/hydrate.js`.
+- On success: card flips state to `Already in library` + shows a link to `/agent/<new-id>`.
+- On failure: revert button state, inline error under card.
+- Imports are independent — one failing does not block others.
+
+**Visuals:**
+- Reuse the CSS tokens / design language of `public/dashboard/` (fonts, spacing, colors). Pull class names from an existing dashboard subpage and mirror them. Do not import the dashboard's CSS file; copy only the tokens you need into `discover.css`.
+- All styling scoped via BEM or a single `.discover-*` prefix to avoid leakage.
+
+## Technical requirements
+
+- ESM only. `<script type="module">` in the HTML.
+- No bundler magic — this is a plain static page that imports `src/erc8004/hydrate.js` directly via a `/@/src/erc8004/hydrate.js` or similar Vite-friendly path OR via a fetch-at-build bundled copy. Whatever resolves cleanly with the existing Vite setup. Check how other `public/*/` subpages do it.
+- Session check: use whatever `src/wallet-auth.js` exposes (e.g. `getCurrentUser()`). If no helper exists for client-side session detection, call `fetch('/api/auth/me', { credentials: 'include' })` and gate on `res.ok`.
+- Accessibility: every button `aria-label`ed, card images with `alt`, keyboard navigable grid (arrow keys optional; tab navigation required).
+- No external CDN dependencies. No new npm deps.
+
+## Homepage CTA gating
+
+Inside the `DISCOVER_LINK` anchor on `index.html`:
+
+```html
+<!-- BEGIN:DISCOVER_LINK -->
+<a href="/discover" id="discoverLink" class="discover-cta" hidden>
+ Find my on-chain agents →
+</a>
+<script type="module">
+ // Reveal when signed in. Non-blocking — failures stay hidden.
+ fetch('/api/auth/me', { credentials: 'include' })
+ .then((r) => r.ok && (document.getElementById('discoverLink').hidden = false))
+ .catch(() => {});
+</script>
+<!-- END:DISCOVER_LINK -->
+```
+
+(Or cleaner: move that logic into `public/discover/` and just render the link unconditionally on the homepage — pick whichever keeps `index.html` tidier.)
+
+## Deliverables checklist
+
+- [ ] `public/discover/index.html` created, semantic HTML, valid HTML5.
+- [ ] `public/discover/discover.js` created, ESM, ~150–300 LOC, JSDoc typed.
+- [ ] `public/discover/discover.css` created, scoped class names, ~100–250 LOC.
+- [ ] Empty/loading/error/success states all implemented.
+- [ ] `fetchDiscoveredAgents()` and `importAgent()` wired correctly.
+- [ ] Route resolves at `/discover` in dev (`npm run dev` → http://localhost:3000/discover).
+- [ ] Homepage CTA block added, gated by session.
+- [ ] Mobile layout at 360px width looks good.
+- [ ] Prettier pass on all touched files.
+- [ ] No new runtime deps.
+
+## Acceptance
+
+- `node --check` passes on `discover.js`.
+- `npm run build` succeeds; the built artifact includes the new page.
+- Manual: in dev with a signed-in user, visit `/discover`, confirm cards render (or an accurate empty state).
+- Manual: sign out, revisit → sign-in CTA shown, no call to `/api/erc8004/hydrate` fires (check Network tab).
+- `git grep -n "DISCOVER_LINK" index.html` shows exactly one BEGIN/END pair.
+
+## Report + archive
+
+Post the report block from `00-README.md`, then:
+
+```bash
+git mv prompts/final-integration/04-discover-page.md prompts/archive/final-integration/04-discover-page.md
+```
+
+Commit: `feat(discover): on-chain agent discovery page`.
diff --git a/prompts/final-integration/05-lobehub-real-integration.md b/prompts/final-integration/05-lobehub-real-integration.md
new file mode 100644
index 000000000..1690ca595
--- /dev/null
+++ b/prompts/final-integration/05-lobehub-real-integration.md
@@ -0,0 +1,120 @@
+# 05 — LobeHub Plugin: Ship a Real Integration
+
+## Context
+
+[lobehub-plugin/](../../lobehub-plugin/) is the package that lets LobeChat users drop a 3D Agent avatar into their chat sidebar. Today it is **scaffolding only**: a manifest that looks right, a React component with `TODO: Hook into Lobe's onAssistantMessage event`, and a bridge that posts messages into a void because the host receiver didn't exist.
+
+By the time you run this prompt, the receiver side (prompt 01 — `EmbedActionBridge`) may or may not be complete:
+
+- If `src/embed-action-bridge.js` exists → target the real wire protocol spec documented there.
+- If it does not → implement the bridge side against the schema described in `01-embed-bridges.md` (envelope: `{v, source, id, inReplyTo, kind, op, payload}`). Prompt 01 and this prompt are spec-compatible by construction.
+
+The goal is a **shippable** LobeHub plugin — not a scaffold. When this is done, a LobeChat user can search the plugin registry, install `@3dagent/lobehub-plugin`, paste an agent id, and have an embodied avatar appear in their chat that reacts to assistant messages.
+
+## Goal
+
+Ship an installable LobeHub plugin with:
+- A correct manifest matching the current LobeHub plugin schema.
+- A React iframe host that resolves an agent id → `<agent-3d>` iframe → working bridge.
+- A working hook into LobeChat's message stream (assistant messages → `avatar.speak(...)` with sentiment).
+- Clean build output in `lobehub-plugin/dist/` consumable by LobeChat's plugin runtime.
+- A local dev harness (a tiny HTML page that simulates the LobeChat host) so we can verify the plugin without running all of LobeChat.
+- Submission-ready metadata (icon, screenshots dir, LICENSE, README with install instructions).
+
+## Files you own
+
+Everything under:
+- `lobehub-plugin/**` (except `node_modules/`)
+- `public/.well-known/lobehub-plugin.json` (the manifest served from the 3dagent.vercel.app origin for remote-plugin installs)
+- `public/lobehub/iframe/**` (the iframe target referenced by the manifest — create if it doesn't fully exist yet)
+
+## Files read-only
+
+- `src/embed-action-bridge.js` (if it exists after prompt 01 completes) — the receiver contract.
+- `01-embed-bridges.md` — the wire protocol spec.
+- `src/element.js` — `<agent-3d>` web component surface.
+- `specs/EMBED_SPEC.md` — embed contract.
+- `api/agents/[id].js` — the agent record shape the iframe will display.
+
+## Acceptance — what "shippable" means
+
+1. **Manifest.** `public/.well-known/lobehub-plugin.json` validates against the current LobeHub plugin-manifest JSON Schema. Check the LobeHub docs (<https://lobehub.com/docs/usage/plugins/development>) for the schemaVersion and ensure:
+ - `identifier` is globally unique (`3d-agent` is reasonable).
+ - `$schema` points to the canonical URL.
+ - `api` entries either all resolve to real endpoints or the `api` array is omitted if this is iframe-only.
+ - `ui.url` points to `https://3dagent.vercel.app/lobehub/iframe/` and that route actually serves HTML.
+ - `settings` schema matches what the React component reads (`agentId`, `apiOrigin`).
+2. **Iframe host.** `public/lobehub/iframe/index.html` renders `<agent-3d agent-id="{{agentId}}">` with correct styling for a 420–640px sidebar frame. Transparent background, no scrollbars, respects the `agentId` query param (the LobeHub host passes settings as querystring or fragment — implement whichever the real manifest spec requires).
+3. **React plugin package.** `lobehub-plugin/src/`:
+ - `AgentPane.tsx` — remove the `TODO: Hook into Lobe's onAssistantMessage` placeholder. Use whatever `@lobehub/ui` / `@lobehub/chat-plugin-sdk` package exposes for assistant-message observation. If the SDK shape is unstable, document fallback to the `window.addEventListener('lobe:assistantMessage', …)` path explicitly with a README note + a clear code comment explaining why this fallback exists.
+ - `bridge.ts` — align with the final wire protocol from prompt 01. Every `op` in the manifest's `api` array (`render_agent`, `speak`, `gesture`, `emote`) has a matching bridge method. Handshake, timeout, origin check.
+ - `config-schema.ts` — export a zod-like validator (or hand-rolled if zod isn't in deps) that guards `PluginSettings`.
+ - `index.ts` — default export the plugin entry expected by the LobeHub runtime.
+4. **Build.**
+ - `cd lobehub-plugin && npm install && npm run build` produces `dist/bundle.js` with a tree-shaken, production-minified build.
+ - No warnings in the build output.
+ - `npm run type-check` passes.
+5. **Dev harness.** `lobehub-plugin/dev/index.html` (new file) loads the built plugin inside a page that mocks the LobeChat host message contract. Include a button to inject a fake assistant message so the avatar can be seen reacting in isolation.
+6. **Docs.**
+ - `lobehub-plugin/README.md` — install instructions, config options, troubleshooting, link to the manifest URL for "one-click" install in LobeChat.
+ - `LICENSE` file (MIT or Apache-2 — match what the rest of the repo uses).
+7. **Icons / screenshots.**
+ - `lobehub-plugin/assets/icon-256.png` (transparent square, 256×256) — if asset missing, generate a placeholder SVG + note in report that a designed icon needs replacing before launch.
+ - `lobehub-plugin/assets/screenshots/` with at least one screenshot referenced by the README.
+
+## Allowed new deps
+
+`lobehub-plugin/package.json` may add:
+- `@lobehub/chat-plugin-sdk` (or the current official plugin SDK name — verify on npm at build time).
+- `zod` if you use it for config validation — optional.
+- Nothing else.
+
+The main app bundle (`package.json` at repo root) must not grow. Plugin deps are scoped to the plugin package.
+
+## Bridge alignment
+
+When prompt 01's `EmbedActionBridge` is live, it handles incoming requests with these ops:
+
+- `ping` → responds `pong`.
+- `speak`, `gesture`, `emote`, `look` → emits on `AgentProtocol`.
+- `setAgent` → swap agent id.
+- `subscribe` → start echoing agent events back to parent.
+
+Your `bridge.ts` sends requests matching this exact envelope and op set. If you find any mismatch, **do not edit prompt 01's files** — document the mismatch in your report and follow the canonical spec in `01-embed-bridges.md`. The plugin is the client of the bridge; the bridge is the contract.
+
+## Deliverables checklist
+
+- [ ] Manifest schema-validated and reachable at `/.well-known/lobehub-plugin.json`.
+- [ ] Iframe host at `/lobehub/iframe/` renders correctly in isolation.
+- [ ] React plugin package builds with zero warnings, zero TODO comments, zero placeholder event names.
+- [ ] `npm --prefix lobehub-plugin run build` succeeds.
+- [ ] `npm --prefix lobehub-plugin run type-check` passes.
+- [ ] Dev harness verifies the end-to-end loop without running LobeChat.
+- [ ] README describes install steps a real LobeHub user would follow.
+- [ ] Icon + screenshot assets present (placeholders acceptable with a flagged TODO).
+- [ ] Bridge protocol matches prompt 01 spec exactly.
+- [ ] No changes to main `package.json` or main `src/`.
+- [ ] Prettier pass on all touched files (LobeHub plugin may follow its own TS formatter — keep it consistent with existing files in the package).
+
+## Acceptance
+
+- `cd lobehub-plugin && npm install && npm run build && npm run type-check` all pass.
+- Manifest validates: if a validator is available locally, run it; otherwise use <https://www.jsonschemavalidator.net/> with the `$schema` URL.
+- Manual dev harness: open `lobehub-plugin/dev/index.html` via `python3 -m http.server` (or equivalent). Click the "inject assistant message" button. The avatar in the iframe visibly speaks.
+- `git grep -n "TODO" lobehub-plugin/src/` returns zero hits.
+- `git grep -n "placeholder" lobehub-plugin/src/` returns zero hits (or every hit has an accompanying explanation in the README).
+
+## Report + archive
+
+Post the report block from `00-README.md`. Include:
+- Exact LobeHub SDK package name + version you targeted.
+- Whether the SDK exposes a real `onAssistantMessage` hook (and what you used if it doesn't).
+- Build output bytes (`dist/bundle.js` size).
+
+Then:
+
+```bash
+git mv prompts/final-integration/05-lobehub-real-integration.md prompts/archive/final-integration/05-lobehub-real-integration.md
+```
+
+Commit: `feat(lobehub): ship real plugin — manifest, bridge, dev harness`.
diff --git a/prompts/final-integration/07-qa-smoke-test.md b/prompts/final-integration/07-qa-smoke-test.md
new file mode 100644
index 000000000..0dc6c3d0b
--- /dev/null
+++ b/prompts/final-integration/07-qa-smoke-test.md
@@ -0,0 +1,182 @@
+# 07 — End-to-End QA Smoke Test + Polish
+
+## Context
+
+Six sibling prompts just landed: embed bridges, idle animation, agent-home integration, discover page, LobeHub plugin, camera capture resolution. The codebase is nominally complete. The gap between "nominally complete" and "ships" is a disciplined QA pass that exercises every user-visible flow end-to-end and files or fixes the defects found.
+
+This prompt is **the final pass**. It produces a public record of what works and what doesn't, fixes any small defects (one-line patches, copy tweaks, z-index bugs), and lists the remaining issues that deserve their own follow-up prompts.
+
+## Goal
+
+Exercise every critical user flow in a real browser, produce a `docs/SMOKE_TEST.md` report, and apply small fixes that keep the smoke-test 100% green. Large defects get escalated (not fixed here).
+
+## Files you own
+
+Create:
+- `docs/SMOKE_TEST.md` — the living smoke-test document.
+
+Edit (surgical only — the **one-line patch rule**):
+- Any file in the repo for fixes ≤ 10 lines of change. Each fix must be:
+ - Clearly defect-driven (not a refactor, not a "while I'm here").
+ - Accompanied by a note in `SMOKE_TEST.md` citing which flow step surfaced it.
+ - Kept to the minimum change that makes the flow pass.
+
+Do NOT:
+- Add features.
+- Rename things.
+- Touch shared-file anchors owned by sibling prompts (`EMBED_BRIDGES`, `IDLE_LOOP`, `AGENT_HOME_ORPHANS`, `DISCOVER_LINK`). If the smoke test reveals a bug inside one of those anchors, file it in `SMOKE_TEST.md` as a follow-up and do not touch the code.
+- Modify contract ABIs or deployed addresses.
+
+## Flows to exercise
+
+Run each flow in the dev server (`npm run dev`) against a real browser. Chrome/Edge + Firefox minimum; Safari if the host has one. For each step, record PASS / FAIL / BLOCKED with a short note.
+
+### Flow A — First-time wallet sign-in
+1. Open `http://localhost:3000/` in a private window.
+2. Click sign-in with wallet button.
+3. Complete SIWE flow with a fresh wallet (MetaMask or WalletConnect).
+4. Land on dashboard.
+
+### Flow B — Selfie → agent
+1. From dashboard, click "Create agent".
+2. Grant camera permission.
+3. Capture a selfie.
+4. Progress UI advances through Avaturn pipeline.
+5. Generated avatar appears with default name/description.
+6. Save; land on `/agent/<id>`.
+
+### Flow C — Edit + save-back
+1. On any owned agent's `/agent/<id>/edit`, open the editor.
+2. Change a material color.
+3. Click save.
+4. Reload the page. Change persists.
+5. Check `/api/avatars/<id>/versions` returns ≥ 2 rows.
+
+### Flow D — Share + embed
+1. On `/agent/<id>`, click Share.
+2. Copy the iframe snippet. Paste into a local scratch HTML file; open it.
+3. Agent renders correctly in the iframe.
+4. Open browser devtools → Network → confirm no CORS errors.
+
+### Flow E — Embed bridge round-trip
+1. Load the scratch HTML from Flow D. Open devtools → Console on the parent page.
+2. Run:
+ ```js
+ const iframe = document.querySelector('iframe');
+ iframe.contentWindow.postMessage({
+ v: 1, source: 'agent-host', id: crypto.randomUUID(),
+ kind: 'request', op: 'ping'
+ }, '*');
+ ```
+3. Expect a `pong` event in the console (install a temporary `window.addEventListener('message', …)` to see it).
+4. Try `op: 'speak', payload: { text: 'Hello world' }` — avatar should visibly speak.
+
+### Flow F — Idle loop
+1. On `/agent/<id>`, watch the avatar for 10 seconds without interacting.
+2. Observe: blinks occur, subtle head drift, no jank.
+3. Open the Performance tab; record 5 seconds. Average frame time < 16.7ms.
+
+### Flow G — Discover page
+1. Sign in with a wallet that owns on-chain agents (or a test wallet pre-seeded on Base Sepolia).
+2. Visit `/discover`.
+3. Discovered agents render as cards.
+4. Click Import on one.
+5. Card transitions to "Already in library".
+6. Click through → `/agent/<new-id>` renders.
+
+### Flow H — Deploy on-chain
+1. As the agent owner, open `/agent/<id>`.
+2. Deploy chip visible.
+3. Click Deploy.
+4. Wallet prompts for tx signature on the correct chain.
+5. After tx mines, chip transitions to on-chain success state without page reload.
+6. `api/agents/by-address/<wallet>` returns the new agent.
+
+### Flow I — LobeHub plugin dev harness
+1. `cd lobehub-plugin && npm install && npm run build`.
+2. Open `lobehub-plugin/dev/index.html` via `python3 -m http.server 5555`.
+3. Inject a fake assistant message.
+4. Avatar in the iframe visibly speaks.
+
+### Flow J — Dashboard sidebar pages
+1. From `/dashboard/`, navigate to: Avatars, Agents, Sessions, Wallets, Actions, Reputation.
+2. Every sidebar page loads without console errors.
+3. Each page fetches and displays real data (or a correct empty state).
+
+### Flow K — Logout + session revocation
+1. From `/dashboard/sessions.html`, click "Sign out all devices".
+2. Refresh; land on sign-in.
+3. `/api/auth/me` returns 401.
+
+### Flow L — Mobile layout smoke
+1. Chrome devtools → device toolbar → iPhone SE (360×667).
+2. Visit homepage, `/agent/<id>`, `/discover`, `/dashboard/`.
+3. No horizontal scroll, no overlapping elements, all CTAs tappable.
+
+## `docs/SMOKE_TEST.md` structure
+
+```markdown
+# 3D Agent — Smoke Test Report
+
+**Run date:** YYYY-MM-DD
+**Commit:** <git sha>
+**Browsers:** <list>
+**Dev server:** npm run dev (port 3000)
+
+## Summary
+| Flow | Result | Notes |
+|------|--------|-------|
+| A. Wallet sign-in | PASS/FAIL/BLOCKED | … |
+| B. Selfie → agent | … | … |
+| … (every flow A–L) |
+
+## Defects fixed in this pass
+- [ ] <short description> — file:line — 1-line summary of fix.
+
+## Defects NOT fixed (follow-up prompts recommended)
+- [ ] <short description> — file:line — why escalated (out of scope, > 10 LOC, touches sibling anchor, etc.).
+
+## Environment notes
+<Anything about test wallets, seeded chain state, or setup that the next runner needs.>
+```
+
+Keep the doc evergreen — future QA passes append to the same file rather than rewriting.
+
+## One-line-patch rule
+
+A fix qualifies as in-scope if ALL of:
+- ≤ 10 lines changed in one file.
+- No new files added (except `SMOKE_TEST.md` itself).
+- No anchor-owned block touched.
+- Clearly defect-driven (copy typo, z-index, missing `aria-label`, broken link, stale import).
+
+Everything bigger is escalated in the `Defects NOT fixed` list for a future prompt.
+
+## Deliverables checklist
+
+- [ ] `docs/SMOKE_TEST.md` created with every flow's result.
+- [ ] Every fixed defect listed and diff-linked in the "fixed" section.
+- [ ] Every escalated defect listed in the "not fixed" section with rationale.
+- [ ] Prettier pass on touched files.
+- [ ] `npm run build` succeeds.
+- [ ] `npm run verify` (the project's canonical check) succeeds.
+
+## Acceptance
+
+- Smoke test covers all 12 flows (A–L).
+- `docs/SMOKE_TEST.md` is in the committed tree.
+- Repo at HEAD passes `npm run verify` with zero warnings.
+
+## Report + archive
+
+Post the full smoke-test summary table (flow pass/fail) inline in your final message. Then:
+
+```bash
+git mv prompts/final-integration/07-qa-smoke-test.md prompts/archive/final-integration/07-qa-smoke-test.md
+```
+
+Commit: `chore(qa): end-to-end smoke test + surgical fixes`.
+
+## After this prompt completes
+
+If any flow is FAIL or BLOCKED and escalated to "not fixed", write a tiny follow-up prompt in `prompts/final-integration/` named `08-followup-<short-slug>.md` describing the defect and the smallest-possible fix. That restarts the loop at 95%+ completion with a concrete punch list.
diff --git a/src/element.js b/src/element.js
index d02591ab3..c5696ae89 100644
--- a/src/element.js
+++ b/src/element.js
@@ -10,6 +10,10 @@ import { loadManifest, fetchRelative } from './manifest.js';
import { resolveURI } from './ipfs.js';
import { resolveAgentById, resolveByAgentId, AgentResolveError } from './agent-resolver.js';
import { parseAgentRef, resolveOnchainAgent, toManifest } from './erc8004/resolver.js';
+// BEGIN:EMBED_BRIDGES_IMPORT
+import { EmbedActionBridge } from './embed-action-bridge.js';
+import { protocol } from './agent-protocol.js';
+// END:EMBED_BRIDGES_IMPORT
const MODES = ['inline', 'floating', 'section', 'fullscreen'];
@@ -726,6 +730,16 @@ class Agent3DElement extends HTMLElement {
}
this._mounted = true;
+ // BEGIN:EMBED_BRIDGES
+ if (window !== window.parent) {
+ this._embedBridge = new EmbedActionBridge({
+ protocol,
+ manifest: this._manifest,
+ window,
+ });
+ this._embedBridge.start();
+ }
+ // END:EMBED_BRIDGES
this._loadingEl.hidden = true;
if (!this._pillActive) this._posterEl.style.opacity = '0';
this.dispatchEvent(
@@ -913,6 +927,8 @@ class Agent3DElement extends HTMLElement {
document.removeEventListener('pointerdown', this._outsideTapHandler);
this._outsideTapHandler = null;
}
+ this._embedBridge?.stop();
+ this._embedBridge = null;
try {
this._runtime?.destroy();
} catch {}
diff --git a/src/embed-action-bridge.js b/src/embed-action-bridge.js
index b6f48db58..0668d4d47 100644
--- a/src/embed-action-bridge.js
+++ b/src/embed-action-bridge.js
@@ -1,134 +1,194 @@
-import { ACTION_TYPES } from './agent-protocol.js';
-
-const _debugLogged = new Set();
-
-function _debugOnce(msg) {
- if (!_debugLogged.has(msg)) {
- _debugLogged.add(msg);
- console.debug('[EmbedActionBridge]', msg);
- }
+// Agent-side postMessage bridge — lives inside <agent-3d> when running inside an iframe.
+// Translates host requests into AgentProtocol events and mirrors agent events back to the host.
+// See specs/EMBED_SPEC.md §Bridge Protocol
+
+const PROTOCOL_VERSION = 1;
+const MAX_QUEUED_EVENTS = 256;
+
+/** @returns {string} */
+function genId() {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')
+ return crypto.randomUUID();
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
+ const r = (Math.random() * 16) | 0;
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
+ });
}
+/** Maps bridge op names to AgentProtocol action types. */
+const OP_TO_ACTION = {
+ speak: 'speak',
+ gesture: 'gesture',
+ emote: 'emote',
+ look: 'look-at',
+};
+
/**
- * Glue layer between EmbedHostBridge postMessage events and the agent protocol bus.
- * Host → Agent: translates `host.*` events into protocol.emit() calls.
- * Agent → Host: relays protocol events back to the host via bridge.send('embed.event').
+ * Agent-side bridge. Receives host requests via postMessage and emits them onto the
+ * AgentProtocol bus. Optionally mirrors protocol events back to the host when the
+ * host opts in with a `subscribe` request.
+ *
+ * Host must send `{ kind:'request', op:'subscribe' }` to receive action events —
+ * events are NOT leaked by default.
*/
export class EmbedActionBridge {
/**
- * @param {{ bridge: EventTarget & { send: Function }, protocol: import('./agent-protocol.js').AgentProtocol }} opts
+ * @param {{ protocol: object, avatar?: object, manifest: object, window: Window }} opts
*/
- constructor({ bridge, protocol }) {
- this._bridge = bridge;
+ constructor({ protocol, avatar = null, manifest, window: win }) {
this._protocol = protocol;
- this._hostHandlers = new Map();
- this._protocolHandlers = new Map();
+ this._avatar = avatar; // reserved for future direct avatar control
+ this._manifest = manifest;
+ this._win = win;
+ this._subscribed = false; // host must explicitly subscribe to receive events
+ this._evtQueue = []; // events queued before host subscribes
+ this._running = false;
+ this._onMessage = this._handleMessage.bind(this);
+ this._onAction = this._handleAction.bind(this);
}
start() {
- this._listenHost('host.chat.message', (e) => this._onChatMessage(e));
- this._listenHost('host.action', (e) => this._onHostAction(e));
- this._listenHost('host.theme', (e) => this._onHostTheme(e));
-
- // Agent → Host relay
- this._listenProtocol(ACTION_TYPES.SPEAK, (a) => this._relayEvent('agent.speaking', { text: a.payload.text, sentiment: a.payload.sentiment }));
- this._listenProtocol(ACTION_TYPES.EMOTE, (a) => this._relayEvent('agent.emote', a.payload));
- this._listenProtocol(ACTION_TYPES.REMEMBER,(a) => this._relayEvent('agent.memory', a.payload));
- this._listenProtocol(ACTION_TYPES.PRESENCE,(a) => this._relayEvent('agent.idle', a.payload));
+ if (this._running) return;
+ this._running = true;
+ this._win.addEventListener('message', this._onMessage);
+ this._protocol.on('*', this._onAction);
+
+ // Announce ready to the parent — triggers the ping/pong handshake
+ const agentId = this._manifest?.id?.agentId || this._manifest?.agentId || '';
+ const capabilities = [...Object.keys(OP_TO_ACTION), 'setAgent', 'ping', 'subscribe'];
+ this._toParent({ kind: 'event', op: 'ready', payload: { agentId, capabilities } });
}
stop() {
- for (const [type, fn] of this._hostHandlers) {
- this._bridge.removeEventListener(type, fn);
- }
- this._hostHandlers.clear();
+ if (!this._running) return;
+ this._running = false;
+ this._win.removeEventListener('message', this._onMessage);
+ this._protocol.off('*', this._onAction);
+ this._evtQueue = [];
+ }
- for (const [type, fn] of this._protocolHandlers) {
- this._protocol.off(type, fn);
- }
- this._protocolHandlers.clear();
+ // ── Helpers ───────────────────────────────────────────────────────────────
+
+ _allowedOrigins() {
+ const policy = this._manifest?.policy;
+ if (!policy) return [];
+ const list = policy.origins || policy.allowlist || [];
+ return Array.isArray(list) ? list : [list];
}
- // ── Host → Agent ─────────────────────────────────────────────────────────
+ _originAllowed(origin) {
+ const allowed = this._allowedOrigins();
+ // If no policy restriction, accept any origin (fail-open matches embed-policy spec)
+ if (allowed.length === 0) return true;
+ return allowed.some((o) => {
+ if (o === '*') return true;
+ try {
+ return new URL(o).origin === origin;
+ } catch {
+ return o === origin;
+ }
+ });
+ }
- _onChatMessage(e) {
- const p = e.payload;
- if (!p || typeof p.text !== 'string') {
- _debugOnce('host.chat.message missing text — ignored');
- return;
- }
- if (p.role === 'user') {
- // User spoke into the host chat; treat as input directed at the agent.
- this._protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: p.text, sentiment: 0, _from: 'user' } });
- } else if (p.role === 'assistant') {
- // Assistant turn delivered from the host — agent should voice/display it.
- // TTS does not auto-fire here; runtime/speech.js may consume SPEAK events if wired.
- this._protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: p.text, sentiment: 0.3, _from: 'assistant' } });
- } else {
- _debugOnce(`host.chat.message unknown role "${p.role}" — ignored`);
- }
+ _toParent(msg) {
+ // Use '*' as targetOrigin — we don't know the parent's origin at construction time.
+ // Incoming messages are validated via _originAllowed before acting on them.
+ this._win.parent.postMessage(
+ { ...msg, v: PROTOCOL_VERSION, source: 'agent-3d', id: msg.id || genId() },
+ '*',
+ );
}
- _onHostAction(e) {
- const p = e.payload;
- if (!p || typeof p.action !== 'string') {
- _debugOnce('host.action missing action string — ignored');
- return;
- }
+ _reply(req, payload) {
+ this._toParent({
+ id: genId(),
+ inReplyTo: req.id,
+ kind: 'response',
+ op: req.op === 'ping' ? 'pong' : req.op,
+ payload,
+ });
+ }
+
+ _replyError(req, code, message) {
+ this._toParent({
+ id: genId(),
+ inReplyTo: req.id,
+ kind: 'response',
+ op: req.op,
+ payload: { error: `${code}: ${message}` },
+ });
+ }
- const action = p.action;
- const args = p.args && typeof p.args === 'object' ? p.args : {};
+ // ── Incoming (host → agent) ───────────────────────────────────────────────
- if (action === 'speak') {
- if (typeof args.text !== 'string') {
- _debugOnce('host.action speak missing args.text — ignored');
- return;
- }
- this._protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: args.text, sentiment: 0, _from: 'host' } });
+ _handleMessage(event) {
+ if (event.source !== this._win.parent) return;
+ if (!this._originAllowed(event.origin)) return;
+ const msg = event.data;
+ if (!msg || msg.v !== PROTOCOL_VERSION || msg.source !== 'agent-host') return;
+ if (msg.kind !== 'request') return;
+
+ const { op, payload = {} } = msg;
+
+ if (op === 'ping') {
+ this._reply(msg, { capabilities: [...Object.keys(OP_TO_ACTION), 'subscribe'] });
return;
}
- if (action.startsWith('emote.')) {
- const suffix = action.slice('emote.'.length);
- if (!suffix) {
- _debugOnce('host.action emote with no suffix — ignored');
- return;
- }
- // Capitalize first letter for conventional clip names (wave → Wave)
- const name = suffix.charAt(0).toUpperCase() + suffix.slice(1);
- this._protocol.emit({ type: ACTION_TYPES.GESTURE, payload: { name, duration: args.duration ?? 2 } });
+ if (op === 'subscribe') {
+ this._subscribed = true;
+ this._reply(msg, { ok: true });
+ // Flush any events queued before subscription
+ for (const e of this._evtQueue) this._toParent(e);
+ this._evtQueue = [];
return;
}
- _debugOnce(`host.action unknown action "${action}" — ignored`);
- }
-
- _onHostTheme(e) {
- const p = e.payload;
- if (!p || typeof p.mode !== 'string') {
- _debugOnce('host.theme missing mode — ignored');
+ if (op === 'setAgent') {
+ // Runtime agent-switching requires a src attribute change on the host iframe.
+ this._replyError(
+ msg,
+ 'not_supported',
+ 'setAgent requires host to update the iframe src',
+ );
return;
}
- if (typeof document !== 'undefined') {
- document.body.dataset.theme = p.mode;
- }
- }
- // ── Agent → Host ─────────────────────────────────────────────────────────
-
- _relayEvent(event, data) {
- this._bridge.send('embed.event', { event, data: data ?? {} });
- }
-
- // ── Helpers ───────────────────────────────────────────────────────────────
+ const actionType = OP_TO_ACTION[op];
+ if (!actionType) {
+ this._replyError(msg, 'unknown_op', `Unknown op "${op}"`);
+ return;
+ }
- _listenHost(type, fn) {
- this._bridge.addEventListener(type, fn);
- this._hostHandlers.set(type, fn);
+ try {
+ this._protocol.emit({ type: actionType, payload });
+ this._reply(msg, { ok: true });
+ } catch (err) {
+ this._replyError(msg, 'emit_failed', err?.message || String(err));
+ }
}
- _listenProtocol(type, fn) {
- this._protocol.on(type, fn);
- this._protocolHandlers.set(type, fn);
+ // ── Outgoing (agent → host) ───────────────────────────────────────────────
+
+ _handleAction(action) {
+ if (!this._running) return;
+ const evt = {
+ id: genId(),
+ kind: 'event',
+ op: 'action',
+ payload: {
+ type: action.type,
+ payload: action.payload,
+ agentId: action.agentId,
+ },
+ };
+
+ if (!this._subscribed) {
+ // Cap queue to prevent memory runaway; drop oldest
+ if (this._evtQueue.length >= MAX_QUEUED_EVENTS) this._evtQueue.shift();
+ this._evtQueue.push(evt);
+ return;
+ }
+ this._toParent(evt);
}
}
diff --git a/src/embed-host-bridge.js b/src/embed-host-bridge.js
index 53fe09c1a..3d7425019 100644
--- a/src/embed-host-bridge.js
+++ b/src/embed-host-bridge.js
@@ -1,123 +1,193 @@
-const HOST_TYPES = new Set(['host.hello', 'host.chat.message', 'host.action', 'host.theme', 'host.response']);
-const EMBED_TYPES = new Set(['embed.ready', 'embed.event', 'embed.error', 'embed.request']);
-const PROTOCOL_VERSION = 1;
-
-let _warnedTypes = new Set();
+// Host-page bridge for talking to an embedded <agent-3d> iframe.
+// Consumed by the parent page (or lobehub-plugin/src/bridge.ts etc.).
+// See specs/EMBED_SPEC.md §Bridge Protocol
-function makeId() {
- return Math.random().toString(36).slice(2) + Date.now().toString(36);
+const PROTOCOL_VERSION = 1;
+const REQUEST_TIMEOUT_MS = 10_000;
+const MAX_BUFFERED_EVENTS = 256;
+
+/** @returns {string} */
+function genId() {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')
+ return crypto.randomUUID();
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
+ const r = (Math.random() * 16) | 0;
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
+ });
}
-export class EmbedHostBridge extends EventTarget {
- constructor({ allowedOrigins = '*' } = {}) {
- super();
- this._allowedOrigins = allowedOrigins;
- this._pendingRequests = new Map();
- this._listener = null;
- this._started = false;
- }
-
- start() {
- if (this._started || typeof window === 'undefined') return;
- this._started = true;
- this._listener = (e) => this._onMessage(e);
- window.addEventListener('message', this._listener);
- // Send embed.ready to parent — payload filled by caller after construction
- // Callers should populate capabilities via send() after wiring up the agent
- }
-
- stop() {
- if (!this._started || typeof window === 'undefined') return;
- this._started = false;
- window.removeEventListener('message', this._listener);
- this._listener = null;
- for (const [, pending] of this._pendingRequests) {
- pending.reject(new Error('bridge stopped'));
- }
- this._pendingRequests.clear();
+/**
+ * Bidirectional postMessage bridge — host (parent-page) side.
+ *
+ * Wire format (all messages):
+ * { v:1, source:'agent-host'|'agent-3d', id, inReplyTo?, kind, op, payload }
+ *
+ * @example
+ * const bridge = new EmbedHostBridge({ iframe, agentId: 'abc', allowedOrigin: 'https://3dagent.vercel.app' });
+ * await bridge.ready;
+ * await bridge.speak('Hello world');
+ * const unsub = bridge.on('action', (a) => console.log(a));
+ */
+export class EmbedHostBridge {
+ /**
+ * @param {{ iframe: HTMLIFrameElement, agentId: string, allowedOrigin: string }} opts
+ */
+ constructor({ iframe, agentId, allowedOrigin }) {
+ this._iframe = iframe;
+ this._agentId = agentId;
+ this._allowedOrigin = allowedOrigin;
+ this._pending = new Map(); // id → { resolve, reject, timer }
+ this._listeners = { action: new Set(), state: new Set(), error: new Set() };
+ this._outQueue = []; // requests queued before handshake completes
+ this._evtBuffer = []; // incoming events buffered before a listener is attached
+ this._ready = false;
+ this._destroyed = false;
+
+ this._onMessage = this._handleMessage.bind(this);
+ window.addEventListener('message', this._onMessage);
+
+ /** @type {Promise<{ agentId: string, capabilities: string[] }>} resolves after handshake */
+ this.ready = new Promise((resolve, reject) => {
+ this._resolveReady = resolve;
+ this._rejectReady = reject;
+ });
}
- send(type, payload) {
- if (typeof window === 'undefined') return;
- if (!EMBED_TYPES.has(type)) {
- console.warn('[EmbedHostBridge] unknown outbound type:', type);
- }
- const msg = { v: PROTOCOL_VERSION, type };
- if (payload !== undefined) msg.payload = payload;
- window.parent.postMessage(msg, '*');
+ _send(msg) {
+ this._iframe.contentWindow?.postMessage(
+ { ...msg, v: PROTOCOL_VERSION, source: 'agent-host' },
+ this._allowedOrigin,
+ );
}
- request(method, params, { timeout = 5000 } = {}) {
+ _request(op, payload = {}) {
return new Promise((resolve, reject) => {
- const id = makeId();
+ if (this._destroyed) {
+ reject(new Error('EmbedHostBridge: destroyed'));
+ return;
+ }
+ const id = genId();
const timer = setTimeout(() => {
- this._pendingRequests.delete(id);
- reject(new Error(`request timeout: ${method}`));
- }, timeout);
-
- this._pendingRequests.set(id, {
- resolve: (result) => {
- clearTimeout(timer);
- this._pendingRequests.delete(id);
- resolve(result);
- },
- reject: (err) => {
- clearTimeout(timer);
- this._pendingRequests.delete(id);
- reject(err);
- },
- });
-
- const msg = { v: PROTOCOL_VERSION, type: 'embed.request', id, payload: { method, params } };
- if (typeof window !== 'undefined') {
- window.parent.postMessage(msg, '*');
+ this._pending.delete(id);
+ reject(
+ new Error(
+ `TimeoutError: request "${op}" timed out after ${REQUEST_TIMEOUT_MS}ms`,
+ ),
+ );
+ }, REQUEST_TIMEOUT_MS);
+ this._pending.set(id, { resolve, reject, timer });
+ if (this._ready) {
+ this._send({ id, kind: 'request', op, payload });
+ } else {
+ this._outQueue.push({ id, kind: 'request', op, payload });
}
});
}
- _originAllowed(origin) {
- if (this._allowedOrigins === '*') return true;
- if (Array.isArray(this._allowedOrigins)) return this._allowedOrigins.includes(origin);
- return false;
- }
+ _handleMessage(event) {
+ if (event.source !== this._iframe.contentWindow) return;
+ if (this._allowedOrigin !== '*' && event.origin !== this._allowedOrigin) return;
+ const msg = event.data;
+ if (!msg || msg.v !== PROTOCOL_VERSION || msg.source !== 'agent-3d') return;
- _onMessage(e) {
- if (e.source !== window.parent) return;
- if (!this._originAllowed(e.origin)) return;
-
- const msg = e.data;
+ if (msg.kind === 'event' && msg.op === 'ready') {
+ // Handshake step 1 — child announced ready, send ping
+ this._send({ id: genId(), kind: 'request', op: 'ping', payload: {} });
+ return;
+ }
- if (!msg || typeof msg !== 'object' || msg.v !== PROTOCOL_VERSION || typeof msg.type !== 'string') {
- // malformed — send error once
- const key = JSON.stringify(msg).slice(0, 80);
- if (!_warnedTypes.has(key)) {
- _warnedTypes.add(key);
- this.send('embed.error', { code: 'MALFORMED_MESSAGE', message: 'missing v:1 or type' });
- }
+ if (msg.kind === 'response' && msg.op === 'pong') {
+ // Handshake complete — flush queued outgoing requests
+ this._ready = true;
+ this._resolveReady({
+ agentId: this._agentId,
+ capabilities: msg.payload?.capabilities || [],
+ });
+ for (const m of this._outQueue) this._send(m);
+ this._outQueue = [];
return;
}
- if (!HOST_TYPES.has(msg.type)) {
- if (!_warnedTypes.has(msg.type)) {
- _warnedTypes.add(msg.type);
- console.warn('[EmbedHostBridge] unknown inbound type (ignored):', msg.type);
+ if (msg.kind === 'response' && msg.inReplyTo) {
+ const entry = this._pending.get(msg.inReplyTo);
+ if (entry) {
+ clearTimeout(entry.timer);
+ this._pending.delete(msg.inReplyTo);
+ if (msg.payload?.error) entry.reject(new Error(msg.payload.error));
+ else entry.resolve(msg.payload);
}
return;
}
- // Route host.response to pending requests
- if (msg.type === 'host.response' && msg.id) {
- const pending = this._pendingRequests.get(msg.id);
- if (pending) {
- if (msg.payload?.error) {
- pending.reject(Object.assign(new Error(msg.payload.error.message || 'request failed'), msg.payload.error));
- } else {
- pending.resolve(msg.payload?.result);
- }
+ if (msg.kind === 'event') {
+ const bucket = msg.op === 'error' ? 'error' : msg.op === 'state' ? 'state' : 'action';
+ const set = this._listeners[bucket];
+ if (set?.size) {
+ for (const h of set) h(msg.payload);
+ } else {
+ // Buffer events until a listener attaches; cap to avoid runaway
+ if (this._evtBuffer.length >= MAX_BUFFERED_EVENTS) this._evtBuffer.shift();
+ this._evtBuffer.push({ bucket, payload: msg.payload });
}
- return;
}
+ }
+
+ /** @param {string} text @param {object} [opts] @returns {Promise<void>} */
+ speak(text, opts = {}) {
+ return this._request('speak', { text, ...opts });
+ }
+
+ /** @param {string} name @returns {Promise<void>} */
+ gesture(name) {
+ return this._request('gesture', { name });
+ }
+
+ /** @param {{ trigger: string, weight: number }} emote @returns {Promise<void>} */
+ emote({ trigger, weight }) {
+ return this._request('emote', { trigger, weight });
+ }
- this.dispatchEvent(Object.assign(new CustomEvent(msg.type), { payload: msg.payload ?? null, msgId: msg.id ?? null }));
+ /** @param {{ target: string }} look @returns {Promise<void>} */
+ look({ target }) {
+ return this._request('look', { target });
+ }
+
+ /** @param {string} nextAgentId @returns {Promise<void>} */
+ setAgent(nextAgentId) {
+ return this._request('setAgent', { agentId: nextAgentId });
+ }
+
+ /**
+ * Subscribe to events from the embedded agent.
+ * @param {'action'|'state'|'error'} event
+ * @param {Function} handler
+ * @returns {Function} unsubscribe
+ */
+ on(event, handler) {
+ const set = this._listeners[event];
+ if (!set) throw new Error(`EmbedHostBridge: unknown event "${event}"`);
+ set.add(handler);
+ // Flush buffered events for this bucket
+ const remaining = [];
+ for (const item of this._evtBuffer) {
+ if (item.bucket === event) handler(item.payload);
+ else remaining.push(item);
+ }
+ this._evtBuffer = remaining;
+ return () => set.delete(handler);
+ }
+
+ destroy() {
+ if (this._destroyed) return;
+ this._destroyed = true;
+ window.removeEventListener('message', this._onMessage);
+ for (const { timer, reject } of this._pending.values()) {
+ clearTimeout(timer);
+ reject(new Error('EmbedHostBridge: destroyed'));
+ }
+ this._pending.clear();
+ this._outQueue = [];
+ this._evtBuffer = [];
+ this._rejectReady?.(new Error('EmbedHostBridge: destroyed'));
}
}