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.

Add scalability task prompts and agent card JSON for 3D Agent

nirholasa2d7b0590415
diff --git a/contracts/.env.example b/contracts/.env.example
new file mode 100644
index 000000000..61f49bf5a
--- /dev/null
+++ b/contracts/.env.example
@@ -0,0 +1,12 @@
+# Copy to .env and fill in.
+# .env is gitignored.
+
+# RPC endpoints
+BASE_SEPOLIA_RPC_URL=https://sepolia.base.org
+BASE_RPC_URL=https://mainnet.base.org
+
+# Deployer private key (no 0x prefix works, 0x prefix also works)
+DEPLOYER_PK=
+
+# BaseScan API key (for contract verification)
+BASESCAN_API_KEY=
diff --git a/contracts/.gitignore b/contracts/.gitignore
new file mode 100644
index 000000000..bdbf215a9
--- /dev/null
+++ b/contracts/.gitignore
@@ -0,0 +1,5 @@
+cache/
+out/
+broadcast/
+lib/
+.env
diff --git a/contracts/README.md b/contracts/README.md
new file mode 100644
index 000000000..458514128
--- /dev/null
+++ b/contracts/README.md
@@ -0,0 +1,104 @@
+# ERC-8004 Contracts
+
+Three registries implementing [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) for the `3d-agent` project:
+
+- **IdentityRegistry** — ERC-721 agents with `tokenURI`, delegated wallet (EIP-712), and key/value metadata.
+- **ReputationRegistry** — one signed score per reviewer per agent, aggregated on-chain.
+- **ValidationRegistry** — allow-listed validators attest to off-chain proofs (e.g. glTF-Validator reports).
+
+The browser code in `../src/erc8004/` already targets these ABIs — only the deployed addresses are missing.
+
+## Build & test
+
+```bash
+forge build
+forge test -vv
+```
+
+25 tests across the three contracts. All passing.
+
+## Deploy to Base Sepolia
+
+1. Install Foundry if you haven't:
+ ```bash
+ curl -L https://foundry.paradigm.xyz | bash && foundryup
+ ```
+
+2. Fund a deployer wallet with Base Sepolia ETH: https://www.alchemy.com/faucets/base-sepolia
+
+3. Configure environment:
+ ```bash
+ cp .env.example .env
+ # Fill in DEPLOYER_PK and BASESCAN_API_KEY
+ ```
+
+4. Deploy + verify:
+ ```bash
+ source .env
+ forge script script/Deploy.s.sol:Deploy \
+ --rpc-url $BASE_SEPOLIA_RPC_URL \
+ --private-key $DEPLOYER_PK \
+ --broadcast \
+ --verify
+ ```
+
+5. Copy the three addresses from the console output into [`../src/erc8004/abi.js`](../src/erc8004/abi.js) under the `84532` entry of `REGISTRY_DEPLOYMENTS`.
+
+## Deploy to Base mainnet
+
+Same as above but with `$BASE_RPC_URL`, and update the `8453` entry in `abi.js`.
+
+## After deploy: register the 3D Agent itself
+
+```js
+// Browser console on 3d.irish with wallet connected to Base Sepolia:
+import { registerAgent } from './src/erc8004/index.js';
+const r = await registerAgent({
+ glbFile: /* your GLB File */,
+ name: '3D Agent',
+ description: 'AI-powered 3D model viewer & validation agent',
+ apiToken: 'YOUR_WEB3STORAGE_TOKEN',
+ onStatus: console.log,
+});
+console.log(r); // { agentId, registrationCID, txHash }
+```
+
+Then update [`../public/.well-known/agent-registration.json`](../public/.well-known/agent-registration.json):
+
+```json
+"registrations": [
+ { "agentId": 1, "agentRegistry": "eip155:84532:0xYourIdentityRegistryAddress" }
+]
+```
+
+## Allow-list a validator (for on-chain validation records)
+
+After deploy, the deployer owns the ValidationRegistry. Add the 3D Agent's own wallet (or a dedicated validator key) with:
+
+```bash
+cast send $VALIDATION_REGISTRY \
+ "addValidator(address)" $VALIDATOR_ADDR \
+ --rpc-url $BASE_SEPOLIA_RPC_URL \
+ --private-key $DEPLOYER_PK
+```
+
+That wallet can then call `recordValidation(agentId, passed, proofHash, proofURI, kind)` via the `recordValidation()` helper in `../src/erc8004/validation-recorder.js`.
+
+## Layout
+
+```
+contracts/
+├── src/
+│ ├── IdentityRegistry.sol
+│ ├── ReputationRegistry.sol
+│ └── ValidationRegistry.sol
+├── test/
+│ ├── IdentityRegistry.t.sol
+│ ├── ReputationRegistry.t.sol
+│ └── ValidationRegistry.t.sol
+├── script/
+│ └── Deploy.s.sol
+├── foundry.toml
+├── .env.example
+└── README.md
+```
diff --git a/contracts/script/Deploy.s.sol b/contracts/script/Deploy.s.sol
new file mode 100644
index 000000000..2d343b139
--- /dev/null
+++ b/contracts/script/Deploy.s.sol
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+import {Script, console} from "forge-std/Script.sol";
+import {IdentityRegistry} from "../src/IdentityRegistry.sol";
+import {ReputationRegistry} from "../src/ReputationRegistry.sol";
+import {ValidationRegistry} from "../src/ValidationRegistry.sol";
+
+/// @notice Deploys the three ERC-8004 registries. Run with:
+/// forge script script/Deploy.s.sol:Deploy \
+/// --rpc-url $BASE_SEPOLIA_RPC_URL \
+/// --private-key $DEPLOYER_PK \
+/// --broadcast --verify
+contract Deploy is Script {
+ function run()
+ external
+ returns (IdentityRegistry identity, ReputationRegistry reputation, ValidationRegistry validation)
+ {
+ address deployer = msg.sender;
+
+ vm.startBroadcast();
+
+ identity = new IdentityRegistry();
+ reputation = new ReputationRegistry(address(identity));
+ validation = new ValidationRegistry(address(identity), deployer);
+
+ vm.stopBroadcast();
+
+ console.log("IdentityRegistry: ", address(identity));
+ console.log("ReputationRegistry:", address(reputation));
+ console.log("ValidationRegistry:", address(validation));
+ console.log("Owner (ValidationRegistry):", deployer);
+ }
+}
diff --git a/contracts/src/IdentityRegistry.sol b/contracts/src/IdentityRegistry.sol
new file mode 100644
index 000000000..14d2ab1dc
--- /dev/null
+++ b/contracts/src/IdentityRegistry.sol
@@ -0,0 +1,199 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
+import {ERC721Enumerable} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
+import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
+import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
+import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
+
+/// @title ERC-8004 Identity Registry
+/// @notice Agents are minted as ERC-721 tokens with a `tokenURI` pointing to an
+/// ERC-8004 registration JSON. Each agent can optionally delegate a
+/// separate wallet address and store arbitrary key/value metadata.
+contract IdentityRegistry is ERC721Enumerable, EIP712 {
+ // ---------------------------------------------------------------------
+ // Types
+ // ---------------------------------------------------------------------
+
+ struct MetadataEntry {
+ string metadataKey;
+ bytes metadataValue;
+ }
+
+ // ---------------------------------------------------------------------
+ // Storage
+ // ---------------------------------------------------------------------
+
+ uint256 private _nextId;
+
+ mapping(uint256 => string) private _agentURI;
+ mapping(uint256 => address) private _agentWallet;
+ mapping(uint256 => mapping(string => bytes)) private _metadata;
+ mapping(address => uint256) public nonces;
+
+ // EIP-712 typehash for delegated wallet binding.
+ bytes32 private constant _SET_WALLET_TYPEHASH = keccak256(
+ "SetAgentWallet(uint256 agentId,address newWallet,uint256 nonce,uint256 deadline)"
+ );
+
+ // ---------------------------------------------------------------------
+ // Events
+ // ---------------------------------------------------------------------
+
+ event Registered(uint256 indexed agentId, string agentURI, address indexed owner);
+ event URIUpdated(uint256 indexed agentId, string newURI, address indexed updatedBy);
+ event WalletSet(uint256 indexed agentId, address indexed wallet);
+ event WalletUnset(uint256 indexed agentId);
+ event MetadataSet(
+ uint256 indexed agentId,
+ string indexed indexedMetadataKey,
+ string metadataKey,
+ bytes metadataValue
+ );
+
+ // ---------------------------------------------------------------------
+ // Errors
+ // ---------------------------------------------------------------------
+
+ error NotAgentOwner();
+ error SignatureExpired();
+ error InvalidSignature();
+ error UnknownAgent();
+
+ // ---------------------------------------------------------------------
+ // Constructor
+ // ---------------------------------------------------------------------
+
+ constructor() ERC721("ERC-8004 Agent", "AGENT") EIP712("ERC8004-IdentityRegistry", "1") {}
+
+ // ---------------------------------------------------------------------
+ // Registration
+ // ---------------------------------------------------------------------
+
+ function register() external returns (uint256 agentId) {
+ return _register(msg.sender, "");
+ }
+
+ function register(string calldata agentURI) external returns (uint256 agentId) {
+ return _register(msg.sender, agentURI);
+ }
+
+ function register(string calldata agentURI, MetadataEntry[] calldata metadata)
+ external
+ returns (uint256 agentId)
+ {
+ agentId = _register(msg.sender, agentURI);
+ for (uint256 i = 0; i < metadata.length; i++) {
+ _setMetadata(agentId, metadata[i].metadataKey, metadata[i].metadataValue);
+ }
+ }
+
+ function _register(address to, string memory agentURI) internal returns (uint256 agentId) {
+ unchecked {
+ agentId = ++_nextId;
+ }
+ _safeMint(to, agentId);
+ if (bytes(agentURI).length > 0) {
+ _agentURI[agentId] = agentURI;
+ }
+ emit Registered(agentId, agentURI, to);
+ }
+
+ // ---------------------------------------------------------------------
+ // URI
+ // ---------------------------------------------------------------------
+
+ function setAgentURI(uint256 agentId, string calldata newURI) external {
+ if (ownerOf(agentId) != msg.sender) revert NotAgentOwner();
+ _agentURI[agentId] = newURI;
+ emit URIUpdated(agentId, newURI, msg.sender);
+ }
+
+ function tokenURI(uint256 agentId) public view override returns (string memory) {
+ _requireOwned(agentId);
+ return _agentURI[agentId];
+ }
+
+ // ---------------------------------------------------------------------
+ // Wallet delegation
+ // ---------------------------------------------------------------------
+
+ /// @notice Bind a delegated wallet address to an agent. The signature must
+ /// be produced by the agent's NFT owner over an EIP-712 payload.
+ function setAgentWallet(
+ uint256 agentId,
+ address newWallet,
+ uint256 deadline,
+ bytes calldata signature
+ ) external {
+ if (block.timestamp > deadline) revert SignatureExpired();
+ address owner = ownerOf(agentId);
+
+ bytes32 structHash = keccak256(
+ abi.encode(_SET_WALLET_TYPEHASH, agentId, newWallet, nonces[owner], deadline)
+ );
+ bytes32 digest = _hashTypedDataV4(structHash);
+
+ if (!SignatureChecker.isValidSignatureNow(owner, digest, signature)) {
+ revert InvalidSignature();
+ }
+
+ unchecked {
+ nonces[owner]++;
+ }
+ _agentWallet[agentId] = newWallet;
+ emit WalletSet(agentId, newWallet);
+ }
+
+ function getAgentWallet(uint256 agentId) external view returns (address) {
+ _requireOwned(agentId);
+ address w = _agentWallet[agentId];
+ return w == address(0) ? ownerOf(agentId) : w;
+ }
+
+ function unsetAgentWallet(uint256 agentId) external {
+ if (ownerOf(agentId) != msg.sender) revert NotAgentOwner();
+ delete _agentWallet[agentId];
+ emit WalletUnset(agentId);
+ }
+
+ // ---------------------------------------------------------------------
+ // Metadata
+ // ---------------------------------------------------------------------
+
+ function setMetadata(uint256 agentId, string calldata metadataKey, bytes calldata metadataValue)
+ external
+ {
+ if (ownerOf(agentId) != msg.sender) revert NotAgentOwner();
+ _setMetadata(agentId, metadataKey, metadataValue);
+ }
+
+ function _setMetadata(uint256 agentId, string memory metadataKey, bytes memory metadataValue)
+ internal
+ {
+ _metadata[agentId][metadataKey] = metadataValue;
+ emit MetadataSet(agentId, metadataKey, metadataKey, metadataValue);
+ }
+
+ function getMetadata(uint256 agentId, string calldata metadataKey)
+ external
+ view
+ returns (bytes memory)
+ {
+ _requireOwned(agentId);
+ return _metadata[agentId][metadataKey];
+ }
+
+ // ---------------------------------------------------------------------
+ // Introspection helpers
+ // ---------------------------------------------------------------------
+
+ function isAgent(uint256 agentId) external view returns (bool) {
+ return _ownerOf(agentId) != address(0);
+ }
+
+ function DOMAIN_SEPARATOR() external view returns (bytes32) {
+ return _domainSeparatorV4();
+ }
+}
diff --git a/contracts/src/ReputationRegistry.sol b/contracts/src/ReputationRegistry.sol
new file mode 100644
index 000000000..9ba187944
--- /dev/null
+++ b/contracts/src/ReputationRegistry.sol
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+interface IIdentityRegistry {
+ function isAgent(uint256 agentId) external view returns (bool);
+ function ownerOf(uint256 agentId) external view returns (address);
+}
+
+/// @title ERC-8004 Reputation Registry
+/// @notice Stores signed-by-tx-sender reputation feedback about registered
+/// agents. Scores are clamped to [-100, 100]. Aggregates are updated
+/// in-place so reads are O(1).
+contract ReputationRegistry {
+ // ---------------------------------------------------------------------
+ // Storage
+ // ---------------------------------------------------------------------
+
+ IIdentityRegistry public immutable identityRegistry;
+
+ struct Feedback {
+ address from;
+ int8 score;
+ uint64 timestamp;
+ string uri; // optional ipfs:// pointer to review details
+ }
+
+ struct Aggregate {
+ int256 sum;
+ uint256 count;
+ }
+
+ mapping(uint256 => Feedback[]) private _feedback;
+ mapping(uint256 => Aggregate) private _aggregate;
+ // agentId => reviewer => hasSubmitted (one review per address per agent)
+ mapping(uint256 => mapping(address => bool)) public hasReviewed;
+
+ // ---------------------------------------------------------------------
+ // Events
+ // ---------------------------------------------------------------------
+
+ event FeedbackSubmitted(
+ uint256 indexed agentId,
+ address indexed from,
+ int8 score,
+ string uri
+ );
+
+ // ---------------------------------------------------------------------
+ // Errors
+ // ---------------------------------------------------------------------
+
+ error UnknownAgent();
+ error AlreadyReviewed();
+ error ScoreOutOfRange();
+ error SelfReviewForbidden();
+
+ // ---------------------------------------------------------------------
+ // Constructor
+ // ---------------------------------------------------------------------
+
+ constructor(address identityRegistry_) {
+ identityRegistry = IIdentityRegistry(identityRegistry_);
+ }
+
+ // ---------------------------------------------------------------------
+ // Submit
+ // ---------------------------------------------------------------------
+
+ function submitFeedback(uint256 agentId, int8 score, string calldata uri) external {
+ if (score < -100 || score > 100) revert ScoreOutOfRange();
+ if (!identityRegistry.isAgent(agentId)) revert UnknownAgent();
+ if (identityRegistry.ownerOf(agentId) == msg.sender) revert SelfReviewForbidden();
+ if (hasReviewed[agentId][msg.sender]) revert AlreadyReviewed();
+
+ hasReviewed[agentId][msg.sender] = true;
+ _feedback[agentId].push(
+ Feedback({
+ from: msg.sender,
+ score: score,
+ timestamp: uint64(block.timestamp),
+ uri: uri
+ })
+ );
+
+ Aggregate storage agg = _aggregate[agentId];
+ agg.sum += int256(score);
+ unchecked {
+ agg.count++;
+ }
+
+ emit FeedbackSubmitted(agentId, msg.sender, score, uri);
+ }
+
+ // ---------------------------------------------------------------------
+ // Queries
+ // ---------------------------------------------------------------------
+
+ /// @notice Return (average * 100, count) so callers can divide client-side
+ /// without losing precision. Returns (0, 0) for unreviewed agents.
+ function getReputation(uint256 agentId) external view returns (int256 avgX100, uint256 count) {
+ Aggregate storage agg = _aggregate[agentId];
+ count = agg.count;
+ if (count == 0) return (0, 0);
+ avgX100 = (agg.sum * 100) / int256(count);
+ }
+
+ function getFeedbackCount(uint256 agentId) external view returns (uint256) {
+ return _feedback[agentId].length;
+ }
+
+ function getFeedback(uint256 agentId, uint256 index) external view returns (Feedback memory) {
+ return _feedback[agentId][index];
+ }
+
+ function getFeedbackRange(uint256 agentId, uint256 offset, uint256 limit)
+ external
+ view
+ returns (Feedback[] memory out)
+ {
+ Feedback[] storage all = _feedback[agentId];
+ uint256 end = offset + limit;
+ if (end > all.length) end = all.length;
+ if (offset >= end) return new Feedback[](0);
+ out = new Feedback[](end - offset);
+ for (uint256 i = offset; i < end; i++) {
+ out[i - offset] = all[i];
+ }
+ }
+}
diff --git a/contracts/src/ValidationRegistry.sol b/contracts/src/ValidationRegistry.sol
new file mode 100644
index 000000000..bed9f9a20
--- /dev/null
+++ b/contracts/src/ValidationRegistry.sol
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+interface IIdentityRegistryV {
+ function isAgent(uint256 agentId) external view returns (bool);
+ function ownerOf(uint256 agentId) external view returns (address);
+}
+
+/// @title ERC-8004 Validation Registry
+/// @notice Allow-listed validators record validation results for agents. Each
+/// result is an opaque proof (hash/CID of an off-chain report) plus a
+/// boolean pass/fail flag. Useful for third-party attestations —
+/// schema checks, behavioral tests, GLB file validation, etc.
+contract ValidationRegistry {
+ // ---------------------------------------------------------------------
+ // Storage
+ // ---------------------------------------------------------------------
+
+ IIdentityRegistryV public immutable identityRegistry;
+ address public owner;
+
+ struct Validation {
+ address validator;
+ bool passed;
+ bytes32 proofHash; // hash of the off-chain report (e.g. sha256 of JSON)
+ string proofURI; // optional ipfs:// or https:// pointer
+ uint64 timestamp;
+ string kind; // free-form tag, e.g. "glb-schema", "a2a-card"
+ }
+
+ mapping(address => bool) public isValidator;
+ mapping(uint256 => Validation[]) private _validations;
+ // agentId => kind => latest index+1 (0 = none)
+ mapping(uint256 => mapping(bytes32 => uint256)) private _latestByKind;
+
+ // ---------------------------------------------------------------------
+ // Events
+ // ---------------------------------------------------------------------
+
+ event ValidatorAdded(address indexed validator);
+ event ValidatorRemoved(address indexed validator);
+ event ValidationRecorded(
+ uint256 indexed agentId,
+ address indexed validator,
+ bool passed,
+ bytes32 proofHash,
+ string kind
+ );
+ event OwnershipTransferred(address indexed from, address indexed to);
+
+ // ---------------------------------------------------------------------
+ // Errors
+ // ---------------------------------------------------------------------
+
+ error NotOwner();
+ error NotValidator();
+ error UnknownAgent();
+
+ // ---------------------------------------------------------------------
+ // Constructor
+ // ---------------------------------------------------------------------
+
+ constructor(address identityRegistry_, address owner_) {
+ identityRegistry = IIdentityRegistryV(identityRegistry_);
+ owner = owner_;
+ emit OwnershipTransferred(address(0), owner_);
+ }
+
+ // ---------------------------------------------------------------------
+ // Access control
+ // ---------------------------------------------------------------------
+
+ modifier onlyOwner() {
+ if (msg.sender != owner) revert NotOwner();
+ _;
+ }
+
+ function addValidator(address v) external onlyOwner {
+ isValidator[v] = true;
+ emit ValidatorAdded(v);
+ }
+
+ function removeValidator(address v) external onlyOwner {
+ isValidator[v] = false;
+ emit ValidatorRemoved(v);
+ }
+
+ function transferOwnership(address newOwner) external onlyOwner {
+ address prev = owner;
+ owner = newOwner;
+ emit OwnershipTransferred(prev, newOwner);
+ }
+
+ // ---------------------------------------------------------------------
+ // Record
+ // ---------------------------------------------------------------------
+
+ function recordValidation(
+ uint256 agentId,
+ bool passed,
+ bytes32 proofHash,
+ string calldata proofURI,
+ string calldata kind
+ ) external {
+ if (!isValidator[msg.sender]) revert NotValidator();
+ if (!identityRegistry.isAgent(agentId)) revert UnknownAgent();
+
+ _validations[agentId].push(
+ Validation({
+ validator: msg.sender,
+ passed: passed,
+ proofHash: proofHash,
+ proofURI: proofURI,
+ timestamp: uint64(block.timestamp),
+ kind: kind
+ })
+ );
+ _latestByKind[agentId][keccak256(bytes(kind))] = _validations[agentId].length;
+
+ emit ValidationRecorded(agentId, msg.sender, passed, proofHash, kind);
+ }
+
+ // ---------------------------------------------------------------------
+ // Queries
+ // ---------------------------------------------------------------------
+
+ function getValidationCount(uint256 agentId) external view returns (uint256) {
+ return _validations[agentId].length;
+ }
+
+ function getValidation(uint256 agentId, uint256 index)
+ external
+ view
+ returns (Validation memory)
+ {
+ return _validations[agentId][index];
+ }
+
+ function getLatestByKind(uint256 agentId, string calldata kind)
+ external
+ view
+ returns (Validation memory)
+ {
+ uint256 idxPlusOne = _latestByKind[agentId][keccak256(bytes(kind))];
+ require(idxPlusOne != 0, "no validation");
+ return _validations[agentId][idxPlusOne - 1];
+ }
+
+ function getValidationRange(uint256 agentId, uint256 offset, uint256 limit)
+ external
+ view
+ returns (Validation[] memory out)
+ {
+ Validation[] storage all = _validations[agentId];
+ uint256 end = offset + limit;
+ if (end > all.length) end = all.length;
+ if (offset >= end) return new Validation[](0);
+ out = new Validation[](end - offset);
+ for (uint256 i = offset; i < end; i++) {
+ out[i - offset] = all[i];
+ }
+ }
+}
diff --git a/contracts/test/IdentityRegistry.t.sol b/contracts/test/IdentityRegistry.t.sol
new file mode 100644
index 000000000..d55d0923e
--- /dev/null
+++ b/contracts/test/IdentityRegistry.t.sol
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+import {Test} from "forge-std/Test.sol";
+import {IdentityRegistry} from "../src/IdentityRegistry.sol";
+
+contract IdentityRegistryTest is Test {
+ IdentityRegistry reg;
+ address alice = address(0xA11CE);
+ address bob = address(0xB0B);
+ uint256 alicePk = 0xA11CE;
+
+ function setUp() public {
+ reg = new IdentityRegistry();
+ alice = vm.addr(alicePk);
+ }
+
+ function testRegisterAssignsIncrementingIds() public {
+ vm.prank(alice);
+ uint256 id1 = reg.register("ipfs://abc");
+ assertEq(id1, 1);
+
+ vm.prank(bob);
+ uint256 id2 = reg.register("ipfs://def");
+ assertEq(id2, 2);
+
+ assertEq(reg.ownerOf(1), alice);
+ assertEq(reg.ownerOf(2), bob);
+ assertEq(reg.tokenURI(1), "ipfs://abc");
+ assertEq(reg.tokenURI(2), "ipfs://def");
+ assertEq(reg.totalSupply(), 2);
+ }
+
+ function testRegisterEmptyURI() public {
+ vm.prank(alice);
+ uint256 id = reg.register();
+ assertEq(id, 1);
+ assertEq(reg.tokenURI(1), "");
+ }
+
+ function testRegisterWithMetadata() public {
+ IdentityRegistry.MetadataEntry[] memory m = new IdentityRegistry.MetadataEntry[](2);
+ m[0] = IdentityRegistry.MetadataEntry("role", bytes("agent"));
+ m[1] = IdentityRegistry.MetadataEntry("ver", bytes("1.0"));
+
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x", m);
+
+ assertEq(reg.getMetadata(id, "role"), bytes("agent"));
+ assertEq(reg.getMetadata(id, "ver"), bytes("1.0"));
+ }
+
+ function testSetAgentURIOnlyOwner() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://old");
+
+ vm.prank(bob);
+ vm.expectRevert(IdentityRegistry.NotAgentOwner.selector);
+ reg.setAgentURI(id, "ipfs://hacked");
+
+ vm.prank(alice);
+ reg.setAgentURI(id, "ipfs://new");
+ assertEq(reg.tokenURI(id), "ipfs://new");
+ }
+
+ function testSetMetadataOnlyOwner() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ vm.prank(bob);
+ vm.expectRevert(IdentityRegistry.NotAgentOwner.selector);
+ reg.setMetadata(id, "k", bytes("v"));
+
+ vm.prank(alice);
+ reg.setMetadata(id, "k", bytes("v"));
+ assertEq(reg.getMetadata(id, "k"), bytes("v"));
+ }
+
+ function testSetAgentWalletWithValidSignature() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ uint256 deadline = block.timestamp + 1 days;
+ address delegate = address(0xDE1);
+ uint256 nonce = reg.nonces(alice);
+
+ bytes32 structHash = keccak256(
+ abi.encode(
+ keccak256("SetAgentWallet(uint256 agentId,address newWallet,uint256 nonce,uint256 deadline)"),
+ id,
+ delegate,
+ nonce,
+ deadline
+ )
+ );
+ bytes32 digest = keccak256(
+ abi.encodePacked("\x19\x01", reg.DOMAIN_SEPARATOR(), structHash)
+ );
+ (uint8 v, bytes32 r, bytes32 s) = vm.sign(alicePk, digest);
+ bytes memory sig = abi.encodePacked(r, s, v);
+
+ reg.setAgentWallet(id, delegate, deadline, sig);
+ assertEq(reg.getAgentWallet(id), delegate);
+ assertEq(reg.nonces(alice), nonce + 1);
+ }
+
+ function testSetAgentWalletExpired() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ vm.warp(1000);
+ vm.expectRevert(IdentityRegistry.SignatureExpired.selector);
+ reg.setAgentWallet(id, address(0xDE1), 500, hex"");
+ }
+
+ function testGetAgentWalletFallsBackToOwner() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ assertEq(reg.getAgentWallet(id), alice);
+ }
+
+ function testUnsetAgentWallet() public {
+ testSetAgentWalletWithValidSignature();
+ vm.prank(alice);
+ reg.unsetAgentWallet(1);
+ assertEq(reg.getAgentWallet(1), alice);
+ }
+
+ function testTokenURIUnknownReverts() public {
+ vm.expectRevert();
+ reg.tokenURI(999);
+ }
+
+ function testIsAgent() public {
+ assertFalse(reg.isAgent(1));
+ vm.prank(alice);
+ reg.register("ipfs://x");
+ assertTrue(reg.isAgent(1));
+ }
+}
diff --git a/contracts/test/ReputationRegistry.t.sol b/contracts/test/ReputationRegistry.t.sol
new file mode 100644
index 000000000..898eba129
--- /dev/null
+++ b/contracts/test/ReputationRegistry.t.sol
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+import {Test} from "forge-std/Test.sol";
+import {IdentityRegistry} from "../src/IdentityRegistry.sol";
+import {ReputationRegistry} from "../src/ReputationRegistry.sol";
+
+contract ReputationRegistryTest is Test {
+ IdentityRegistry identity;
+ ReputationRegistry rep;
+ address alice = address(0xA11CE);
+ address bob = address(0xB0B);
+ address carol = address(0xCA701);
+
+ function setUp() public {
+ identity = new IdentityRegistry();
+ rep = new ReputationRegistry(address(identity));
+
+ vm.prank(alice);
+ identity.register("ipfs://alice");
+ }
+
+ function testSubmitAndQuery() public {
+ vm.prank(bob);
+ rep.submitFeedback(1, 80, "ipfs://review1");
+
+ vm.prank(carol);
+ rep.submitFeedback(1, 60, "ipfs://review2");
+
+ (int256 avgX100, uint256 count) = rep.getReputation(1);
+ assertEq(count, 2);
+ assertEq(avgX100, 7000); // (80+60)/2 * 100
+ }
+
+ function testCannotReviewSelf() public {
+ vm.prank(alice);
+ vm.expectRevert(ReputationRegistry.SelfReviewForbidden.selector);
+ rep.submitFeedback(1, 100, "");
+ }
+
+ function testCannotReviewTwice() public {
+ vm.prank(bob);
+ rep.submitFeedback(1, 50, "");
+
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.AlreadyReviewed.selector);
+ rep.submitFeedback(1, 60, "");
+ }
+
+ function testScoreBounds() public {
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.ScoreOutOfRange.selector);
+ rep.submitFeedback(1, 101, "");
+ }
+
+ function testUnknownAgentReverts() public {
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.UnknownAgent.selector);
+ rep.submitFeedback(999, 50, "");
+ }
+
+ function testNegativeScore() public {
+ vm.prank(bob);
+ rep.submitFeedback(1, -50, "");
+ (int256 avgX100,) = rep.getReputation(1);
+ assertEq(avgX100, -5000);
+ }
+
+ function testFeedbackRange() public {
+ vm.prank(bob);
+ rep.submitFeedback(1, 30, "a");
+ vm.prank(carol);
+ rep.submitFeedback(1, 40, "b");
+
+ ReputationRegistry.Feedback[] memory range = rep.getFeedbackRange(1, 0, 10);
+ assertEq(range.length, 2);
+ assertEq(range[0].score, int8(30));
+ assertEq(range[1].score, int8(40));
+ }
+}
diff --git a/contracts/test/ValidationRegistry.t.sol b/contracts/test/ValidationRegistry.t.sol
new file mode 100644
index 000000000..16d4860a7
--- /dev/null
+++ b/contracts/test/ValidationRegistry.t.sol
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+import {Test} from "forge-std/Test.sol";
+import {IdentityRegistry} from "../src/IdentityRegistry.sol";
+import {ValidationRegistry} from "../src/ValidationRegistry.sol";
+
+contract ValidationRegistryTest is Test {
+ IdentityRegistry identity;
+ ValidationRegistry validation;
+ address owner = address(this);
+ address validator = address(0xDA11d);
+ address alice = address(0xA11CE);
+ address bob = address(0xB0B);
+
+ function setUp() public {
+ identity = new IdentityRegistry();
+ validation = new ValidationRegistry(address(identity), owner);
+
+ vm.prank(alice);
+ identity.register("ipfs://alice");
+ }
+
+ function testAddValidator() public {
+ validation.addValidator(validator);
+ assertTrue(validation.isValidator(validator));
+ }
+
+ function testOnlyOwnerCanAddValidator() public {
+ vm.prank(bob);
+ vm.expectRevert(ValidationRegistry.NotOwner.selector);
+ validation.addValidator(validator);
+ }
+
+ function testRecordValidation() public {
+ validation.addValidator(validator);
+
+ bytes32 proof = keccak256("report-v1");
+ vm.prank(validator);
+ validation.recordValidation(1, true, proof, "ipfs://report", "glb-schema");
+
+ assertEq(validation.getValidationCount(1), 1);
+ ValidationRegistry.Validation memory v = validation.getValidation(1, 0);
+ assertEq(v.validator, validator);
+ assertTrue(v.passed);
+ assertEq(v.proofHash, proof);
+ assertEq(v.kind, "glb-schema");
+ }
+
+ function testLatestByKind() public {
+ validation.addValidator(validator);
+
+ vm.startPrank(validator);
+ validation.recordValidation(1, false, keccak256("a"), "", "glb-schema");
+ validation.recordValidation(1, true, keccak256("b"), "", "glb-schema");
+ validation.recordValidation(1, true, keccak256("c"), "", "a2a-card");
+ vm.stopPrank();
+
+ ValidationRegistry.Validation memory latest = validation.getLatestByKind(1, "glb-schema");
+ assertTrue(latest.passed);
+ assertEq(latest.proofHash, keccak256("b"));
+
+ ValidationRegistry.Validation memory card = validation.getLatestByKind(1, "a2a-card");
+ assertEq(card.proofHash, keccak256("c"));
+ }
+
+ function testNonValidatorCannotRecord() public {
+ vm.prank(bob);
+ vm.expectRevert(ValidationRegistry.NotValidator.selector);
+ validation.recordValidation(1, true, bytes32(0), "", "glb-schema");
+ }
+
+ function testUnknownAgentReverts() public {
+ validation.addValidator(validator);
+ vm.prank(validator);
+ vm.expectRevert(ValidationRegistry.UnknownAgent.selector);
+ validation.recordValidation(999, true, bytes32(0), "", "glb-schema");
+ }
+
+ function testRemoveValidator() public {
+ validation.addValidator(validator);
+ validation.removeValidator(validator);
+ vm.prank(validator);
+ vm.expectRevert(ValidationRegistry.NotValidator.selector);
+ validation.recordValidation(1, true, bytes32(0), "", "glb-schema");
+ }
+}
diff --git a/features.html b/features.html
index 35a81e4b5..bbf8973ab 100644
--- a/features.html
+++ b/features.html
@@ -21,6 +21,7 @@
<link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="/features.css" />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400&display=swap" rel="stylesheet" />
+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
</head>
<body class="features-page">
<header>
diff --git a/sdk/package.json b/sdk/package.json
new file mode 100644
index 000000000..f68c0b06e
--- /dev/null
+++ b/sdk/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@speraxos/agent-kit",
+ "version": "0.1.0",
+ "description": "Ship an ERC-8004 agent with on-chain identity, a chat panel, and discoverable .well-known endpoints in minutes.",
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "exports": {
+ ".": "./src/index.js",
+ "./styles": "./src/styles.css"
+ },
+ "files": [
+ "src"
+ ],
+ "keywords": [
+ "erc-8004",
+ "agent",
+ "blockchain",
+ "a2a",
+ "mcp",
+ "ethereum",
+ "web3",
+ "identity"
+ ],
+ "license": "MIT",
+ "peerDependencies": {
+ "ethers": "^6.0.0"
+ },
+ "peerDependenciesMeta": {
+ "ethers": {
+ "optional": true
+ }
+ }
+}
diff --git a/sdk/src/erc8004/abi.js b/sdk/src/erc8004/abi.js
new file mode 100644
index 000000000..bad922bbc
--- /dev/null
+++ b/sdk/src/erc8004/abi.js
@@ -0,0 +1,44 @@
+/**
+ * ERC-8004 Identity Registry — minimal ABI.
+ * Full spec: https://eips.ethereum.org/EIPS/eip-8004
+ */
+
+export const IDENTITY_REGISTRY_ABI = [
+ 'function register(string agentURI) external returns (uint256 agentId)',
+ 'function register(string agentURI, tuple(string metadataKey, bytes metadataValue)[] metadata) external returns (uint256 agentId)',
+ 'function register() external returns (uint256 agentId)',
+ 'function setAgentURI(uint256 agentId, string newURI) external',
+ 'function tokenURI(uint256 agentId) external view returns (string)',
+ 'function setAgentWallet(uint256 agentId, address newWallet, uint256 deadline, bytes signature) external',
+ 'function getAgentWallet(uint256 agentId) external view returns (address)',
+ 'function unsetAgentWallet(uint256 agentId) external',
+ 'function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)',
+ 'function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue) external',
+ 'function ownerOf(uint256 tokenId) external view returns (address)',
+ 'function balanceOf(address owner) external view returns (uint256)',
+ 'function totalSupply() external view returns (uint256)',
+ 'event Registered(uint256 indexed agentId, string agentURI, address indexed owner)',
+ 'event URIUpdated(uint256 indexed agentId, string newURI, address indexed updatedBy)',
+ 'event MetadataSet(uint256 indexed agentId, string indexed indexedMetadataKey, string metadataKey, bytes metadataValue)',
+ 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)',
+];
+
+/**
+ * Known deployments — fill with your contract addresses.
+ * Format: eip155:{chainId}:{address}
+ */
+export const REGISTRY_DEPLOYMENTS = {
+ 8453: { identityRegistry: '' }, // Base mainnet
+ 84532: { identityRegistry: '' }, // Base Sepolia
+ 1: { identityRegistry: '' }, // Ethereum mainnet
+};
+
+/**
+ * Build the agentRegistry identifier per spec.
+ * @param {number} chainId
+ * @param {string} registryAddress
+ * @returns {string} e.g. "eip155:8453:0x742..."
+ */
+export function agentRegistryId(chainId, registryAddress) {
+ return `eip155:${chainId}:${registryAddress}`;
+}
diff --git a/sdk/src/erc8004/registry.js b/sdk/src/erc8004/registry.js
new file mode 100644
index 000000000..4fcf651e6
--- /dev/null
+++ b/sdk/src/erc8004/registry.js
@@ -0,0 +1,206 @@
+/**
+ * ERC-8004 registry — wallet connection, IPFS pinning, on-chain registration.
+ *
+ * Requires ethers v6 as a peer dependency.
+ */
+
+import { BrowserProvider, Contract } from 'ethers';
+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './abi.js';
+
+// ---------------------------------------------------------------------------
+// Wallet
+// ---------------------------------------------------------------------------
+
+let _provider = null;
+let _signer = null;
+
+/**
+ * Connect to the user's injected wallet (MetaMask, Coinbase Wallet, etc.).
+ * @returns {Promise<{provider, signer, address: string, chainId: number}>}
+ */
+export async function connectWallet() {
+ if (!window.ethereum) {
+ throw new Error('No wallet detected. Install MetaMask or a compatible wallet.');
+ }
+
+ _provider = new BrowserProvider(window.ethereum);
+ _signer = await _provider.getSigner();
+ const address = await _signer.getAddress();
+ const { chainId } = await _provider.getNetwork();
+
+ return { provider: _provider, signer: _signer, address, chainId: Number(chainId) };
+}
+
+/** @returns {import('ethers').Signer | null} */
+export function getSigner() {
+ return _signer;
+}
+
+// ---------------------------------------------------------------------------
+// IPFS
+// ---------------------------------------------------------------------------
+
+/**
+ * Pin a Blob/File to IPFS via web3.storage.
+ * Pass your API token or set window.__W3S_TOKEN beforehand.
+ *
+ * @param {Blob|File} blob
+ * @param {string} [apiToken]
+ * @returns {Promise<string>} IPFS CID
+ */
+export async function pinToIPFS(blob, apiToken) {
+ const token = apiToken || window.__W3S_TOKEN;
+ if (!token) {
+ throw new Error('IPFS upload requires an API token. Pass one or set window.__W3S_TOKEN.');
+ }
+
+ const res = await fetch('https://api.web3.storage/upload', {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}` },
+ body: blob,
+ });
+
+ if (!res.ok) {
+ throw new Error(`IPFS upload failed (${res.status}): ${await res.text()}`);
+ }
+
+ return (await res.json()).cid;
+}
+
+// ---------------------------------------------------------------------------
+// Registration JSON
+// ---------------------------------------------------------------------------
+
+/**
+ * Build an ERC-8004 agent registration document.
+ *
+ * @param {object} opts
+ * @param {string} opts.name Agent display name
+ * @param {string} opts.description Agent description
+ * @param {string} opts.imageCID IPFS CID of the agent's image/avatar
+ * @param {number} opts.agentId Token ID returned by the registry
+ * @param {number} opts.chainId Chain ID where the agent is registered
+ * @param {string} opts.registryAddr Identity Registry contract address
+ * @param {Array} [opts.services] Additional service entries
+ * @returns {object}
+ */
+export function buildRegistrationJSON({ name, description, imageCID, agentId, chainId, registryAddr, services = [] }) {
+ return {
+ type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',
+ name,
+ description,
+ image: imageCID ? `ipfs://${imageCID}` : undefined,
+ active: true,
+ services,
+ registrations: [
+ {
+ agentId,
+ agentRegistry: agentRegistryId(chainId, registryAddr),
+ },
+ ],
+ supportedTrust: ['reputation'],
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Contract
+// ---------------------------------------------------------------------------
+
+/**
+ * Get the Identity Registry contract for the connected chain.
+ * @param {number} chainId
+ * @param {import('ethers').Signer} signer
+ * @returns {import('ethers').Contract}
+ */
+export function getIdentityRegistry(chainId, signer) {
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ if (!deployment?.identityRegistry) {
+ throw new Error(
+ `No Identity Registry configured for chain ${chainId}. ` +
+ `Set REGISTRY_DEPLOYMENTS[${chainId}].identityRegistry in sdk/src/erc8004/abi.js`,
+ );
+ }
+ return new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, signer);
+}
+
+// ---------------------------------------------------------------------------
+// Full registration flow
+// ---------------------------------------------------------------------------
+
+/**
+ * Register an agent on-chain end-to-end.
+ *
+ * Steps:
+ * 1. Connect wallet
+ * 2. Pin image to IPFS (optional — skip if no file provided)
+ * 3. Call register() on-chain, capture agentId from event
+ * 4. Build + pin registration JSON to IPFS
+ * 5. Call setAgentURI() with the final registration CID
+ *
+ * @param {object} opts
+ * @param {string} opts.name Agent name
+ * @param {string} opts.description Agent description
+ * @param {string} opts.endpoint Your agent's web endpoint (https://...)
+ * @param {File} [opts.imageFile] Optional image/avatar to pin to IPFS
+ * @param {Array} [opts.services] Additional A2A / MCP service entries
+ * @param {string} [opts.apiToken] IPFS pinning API token
+ * @param {Function} [opts.onStatus] Progress callback (message: string) => void
+ * @returns {Promise<{agentId: number, registrationCID: string, txHash: string}>}
+ */
+export async function registerAgent({ name, description, endpoint, imageFile, services = [], apiToken, onStatus }) {
+ const log = onStatus || (() => {});
+
+ log('Connecting wallet...');
+ const { signer, chainId } = await connectWallet();
+
+ let imageCID = null;
+ if (imageFile) {
+ log('Uploading image to IPFS...');
+ imageCID = await pinToIPFS(imageFile, apiToken);
+ log(`Image pinned: ipfs://${imageCID}`);
+ }
+
+ const registry = getIdentityRegistry(chainId, signer);
+
+ log('Registering agent on-chain...');
+ const tx = await registry['register(string)'](imageCID ? `ipfs://${imageCID}` : endpoint);
+ log(`Transaction submitted: ${tx.hash}`);
+ const receipt = await tx.wait();
+
+ const registeredEvent = receipt.logs
+ .map((l) => { try { return registry.interface.parseLog(l); } catch { return null; } })
+ .find((e) => e?.name === 'Registered');
+
+ if (!registeredEvent) {
+ throw new Error('Registration succeeded but Registered event not found in receipt.');
+ }
+
+ const agentId = Number(registeredEvent.args.agentId);
+ log(`Agent minted — agentId: ${agentId}`);
+
+ const allServices = [
+ { name: 'web', endpoint },
+ ...services,
+ ];
+
+ const registrationJSON = buildRegistrationJSON({
+ name,
+ description,
+ imageCID,
+ agentId,
+ chainId,
+ registryAddr: REGISTRY_DEPLOYMENTS[chainId].identityRegistry,
+ services: allServices,
+ });
+
+ log('Pinning registration metadata to IPFS...');
+ const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], { type: 'application/json' });
+ const registrationCID = await pinToIPFS(jsonBlob, apiToken);
+ log(`Registration JSON pinned: ipfs://${registrationCID}`);
+
+ log('Updating agentURI on-chain...');
+ await (await registry.setAgentURI(agentId, `ipfs://${registrationCID}`)).wait();
+ log('Done. Agent is live on-chain.');
+
+ return { agentId, registrationCID, txHash: tx.hash };
+}
diff --git a/sdk/src/index.js b/sdk/src/index.js
new file mode 100644
index 000000000..237fafe96
--- /dev/null
+++ b/sdk/src/index.js
@@ -0,0 +1,175 @@
+/**
+ * @speraxos/agent-kit
+ *
+ * Ship an ERC-8004 agent with on-chain identity, a chat panel,
+ * and discoverable .well-known endpoints in minutes.
+ *
+ * Quick start:
+ *
+ * import { AgentKit } from '@speraxos/agent-kit';
+ * import '@speraxos/agent-kit/styles';
+ *
+ * const agent = new AgentKit({
+ * name: 'My Agent',
+ * description: 'Does cool stuff',
+ * endpoint: 'https://myapp.com',
+ * onMessage: async (text) => `You said: ${text}`,
+ * });
+ *
+ * agent.mount(document.body);
+ *
+ * // Register on-chain (needs MetaMask + IPFS token)
+ * await agent.register({ ipfsToken: 'your-web3storage-token' });
+ *
+ * // Get .well-known manifests to serve from your server
+ * const { agentRegistration, agentCard, aiPlugin } = agent.manifests();
+ */
+
+export { AgentPanel } from './panel.js';
+export { agentRegistration, agentCard, aiPlugin } from './manifests.js';
+export { connectWallet, registerAgent, pinToIPFS, buildRegistrationJSON, getIdentityRegistry } from './erc8004/registry.js';
+export { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './erc8004/abi.js';
+
+import { AgentPanel } from './panel.js';
+import { agentRegistration, agentCard, aiPlugin } from './manifests.js';
+import { registerAgent } from './erc8004/registry.js';
+
+export class AgentKit {
+ /**
+ * @param {object} opts
+ * @param {string} opts.name Agent name (shown in panel header + manifests)
+ * @param {string} opts.description What the agent does
+ * @param {string} opts.endpoint Your agent's public URL (https://...)
+ * @param {string} [opts.image] Public URL to your agent's logo/image
+ * @param {string} [opts.version] Semver version string
+ * @param {string} [opts.org] Organization name for agent-card.json
+ * @param {Array} [opts.skills] A2A skill definitions
+ * @param {Array} [opts.services] Extra service entries (A2A, MCP endpoints)
+ * @param {Function} [opts.onMessage] async (text: string) => string
+ * @param {string} [opts.welcome] Panel welcome message
+ * @param {boolean} [opts.voice] Enable TTS (default: true)
+ */
+ constructor({
+ name,
+ description,
+ endpoint,
+ image = '',
+ version = '1.0.0',
+ org = '',
+ skills = [],
+ services = [],
+ onMessage,
+ welcome,
+ voice = true,
+ } = {}) {
+ if (!name) throw new Error('AgentKit: name is required');
+ if (!endpoint) throw new Error('AgentKit: endpoint is required');
+
+ this.config = { name, description, endpoint, image, version, org, skills, services };
+
+ this._panel = new AgentPanel({
+ title: name,
+ welcome: welcome || `Hi! I'm ${name}. How can I help?`,
+ onMessage,
+ voice,
+ });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Panel
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Attach the chat panel to a DOM element.
+ * @param {HTMLElement} container
+ * @returns {AgentKit} this (chainable)
+ */
+ mount(container = document.body) {
+ this._panel.mount(container);
+ return this;
+ }
+
+ /** Open the chat panel. */
+ open() { this._panel.open(); return this; }
+
+ /** Close the chat panel. */
+ close() { this._panel.close(); return this; }
+
+ /** Add a message to the panel. */
+ addMessage(role, text) { this._panel.addMessage(role, text); return this; }
+
+ /** Remove the panel from the DOM. */
+ dispose() { this._panel.dispose(); }
+
+ // ---------------------------------------------------------------------------
+ // Blockchain registration
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Register the agent on-chain via ERC-8004.
+ *
+ * @param {object} [opts]
+ * @param {File} [opts.imageFile] Agent image to pin to IPFS (optional)
+ * @param {Array} [opts.services] Extra services to include in registration
+ * @param {string} [opts.ipfsToken] web3.storage API token
+ * @param {Function} [opts.onStatus] (message: string) => void progress callback
+ * @returns {Promise<{agentId: number, registrationCID: string, txHash: string}>}
+ */
+ register({ imageFile, services, ipfsToken, onStatus } = {}) {
+ return registerAgent({
+ name: this.config.name,
+ description: this.config.description,
+ endpoint: this.config.endpoint,
+ imageFile,
+ services: services ?? this.config.services,
+ apiToken: ipfsToken,
+ onStatus,
+ });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Manifests
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Get the three .well-known manifest objects ready to serve.
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.openapiUrl] URL to your OpenAPI spec
+ * @param {Array} [opts.registrations] On-chain registration records
+ * @returns {{ agentRegistration: object, agentCard: object, aiPlugin: object }}
+ */
+ manifests({ openapiUrl = '', registrations = [] } = {}) {
+ const { name, description, endpoint, image, version, org, skills, services } = this.config;
+
+ const extraServices = [];
+ if (openapiUrl) {
+ extraServices.push({ name: 'MCP', endpoint: openapiUrl, version: '2025-06-18' });
+ }
+
+ return {
+ agentRegistration: agentRegistration({
+ name,
+ description,
+ endpoint,
+ image,
+ services: [...services, ...extraServices],
+ registrations,
+ }),
+ agentCard: agentCard({
+ name,
+ description,
+ url: endpoint,
+ version,
+ org,
+ skills,
+ }),
+ aiPlugin: aiPlugin({
+ name,
+ description,
+ openapiUrl: openapiUrl || `${endpoint}/.well-known/openapi.yaml`,
+ logoUrl: image,
+ }),
+ };
+ }
+}
diff --git a/sdk/src/manifests.js b/sdk/src/manifests.js
new file mode 100644
index 000000000..79e4a7ec9
--- /dev/null
+++ b/sdk/src/manifests.js
@@ -0,0 +1,101 @@
+/**
+ * .well-known manifest generators for ERC-8004 agents.
+ *
+ * Call these to get the JSON objects, then serve them from your server at:
+ * /.well-known/agent-registration.json
+ * /.well-known/agent-card.json
+ * /.well-known/ai-plugin.json
+ */
+
+/**
+ * Generate an ERC-8004 agent-registration.json document.
+ *
+ * @param {object} opts
+ * @param {string} opts.name Agent display name
+ * @param {string} opts.description What the agent does
+ * @param {string} opts.endpoint Primary web endpoint (https://...)
+ * @param {string} [opts.image] Public URL to an image/logo
+ * @param {Array} [opts.services] Additional service entries (A2A, MCP, etc.)
+ * @param {Array} [opts.registrations] On-chain registration records
+ * @returns {object}
+ */
+export function agentRegistration({ name, description, endpoint, image = '', services = [], registrations = [] }) {
+ return {
+ type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',
+ name,
+ description,
+ image,
+ active: true,
+ services: [
+ { name: 'web', endpoint },
+ ...services,
+ ],
+ registrations,
+ supportedTrust: ['reputation'],
+ };
+}
+
+/**
+ * Generate an A2A agent-card.json document.
+ *
+ * @param {object} opts
+ * @param {string} opts.name Agent display name
+ * @param {string} opts.description Agent description
+ * @param {string} opts.url Agent base URL
+ * @param {string} [opts.version] Semver string
+ * @param {string} [opts.org] Organization name
+ * @param {Array} [opts.skills] Array of A2A skill objects
+ * @returns {object}
+ */
+export function agentCard({ name, description, url, version = '1.0.0', org = '', skills = [] }) {
+ return {
+ name,
+ description,
+ url,
+ provider: {
+ organization: org || name,
+ url,
+ },
+ version,
+ capabilities: {
+ streaming: false,
+ pushNotifications: false,
+ stateTransitionHistory: false,
+ },
+ authentication: {
+ schemes: ['bearer'],
+ credentials: null,
+ },
+ defaultInputModes: ['text/plain', 'application/json'],
+ defaultOutputModes: ['text/plain', 'application/json'],
+ skills,
+ };
+}
+
+/**
+ * Generate an ai-plugin.json (OpenAI plugin manifest).
+ *
+ * @param {object} opts
+ * @param {string} opts.name Human-readable name
+ * @param {string} opts.description Plugin description
+ * @param {string} opts.openapiUrl URL to your OpenAPI spec
+ * @param {string} [opts.logoUrl] Public logo URL
+ * @param {string} [opts.contactEmail]
+ * @param {string} [opts.legalUrl]
+ * @returns {object}
+ */
+export function aiPlugin({ name, description, openapiUrl, logoUrl = '', contactEmail = '', legalUrl = '' }) {
+ const modelName = name.toLowerCase().replace(/[^a-z0-9_]/g, '_');
+ return {
+ schema_version: 'v1',
+ name_for_human: name,
+ name_for_model: modelName,
+ description_for_human: description,
+ description_for_model: description,
+ auth: { type: 'none' },
+ api: { type: 'openapi', url: openapiUrl },
+ logo_url: logoUrl,
+ contact_email: contactEmail,
+ legal_info_url: legalUrl,
+ };
+}
diff --git a/sdk/src/panel.js b/sdk/src/panel.js
new file mode 100644
index 000000000..a96871aba
--- /dev/null
+++ b/sdk/src/panel.js
@@ -0,0 +1,216 @@
+/**
+ * AgentPanel — floating chat panel with voice I/O.
+ *
+ * Drop-in UI for any ERC-8004 agent. Bring your own response logic
+ * via the onMessage callback.
+ *
+ * Usage:
+ * const panel = new AgentPanel({
+ * title: 'My Agent',
+ * welcome: 'Hi! How can I help?',
+ * onMessage: async (text) => 'your response here',
+ * });
+ * panel.mount(document.body);
+ */
+
+const SpeechRecognition =
+ typeof window !== 'undefined' && (window.SpeechRecognition || window.webkitSpeechRecognition);
+
+export class AgentPanel {
+ /**
+ * @param {object} opts
+ * @param {string} [opts.title] Panel header title
+ * @param {string} [opts.welcome] First message shown in the panel
+ * @param {string} [opts.placeholder] Input placeholder text
+ * @param {Function} [opts.onMessage] async (text: string) => string — your response handler
+ * @param {boolean} [opts.voice] Enable text-to-speech on agent responses (default: true)
+ */
+ constructor({ title = 'Agent', welcome = 'Hi! How can I help?', placeholder = 'Ask anything...', onMessage, voice = true } = {}) {
+ this.title = title;
+ this.welcome = welcome;
+ this.placeholder = placeholder;
+ this.onMessage = onMessage || (() => "I'm not sure how to answer that.");
+ this.voice = voice;
+
+ this.synth = typeof window !== 'undefined' ? window.speechSynthesis : null;
+ this.recognition = null;
+ this.isListening = false;
+ this.panel = null;
+ this.toggleBtn = null;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Public API
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Attach the panel to a DOM element.
+ * @param {HTMLElement} container
+ * @returns {AgentPanel} this (chainable)
+ */
+ mount(container) {
+ this._buildUI(container);
+ this._initSpeech();
+ return this;
+ }
+
+ /** Show the panel. */
+ open() {
+ if (this.panel) {
+ this.panel.style.display = 'flex';
+ this.toggleBtn?.classList.add('ak-active');
+ this.panel.querySelector('.ak-input')?.focus();
+ }
+ }
+
+ /** Hide the panel. */
+ close() {
+ if (this.panel) {
+ this.panel.style.display = 'none';
+ this.toggleBtn?.classList.remove('ak-active');
+ }
+ }
+
+ /** Add a message programmatically. */
+ addMessage(role, text) {
+ this._addMessage(role, text);
+ }
+
+ /** Remove the panel and toggle button from the DOM. */
+ dispose() {
+ if (this.recognition) this.recognition.stop();
+ this.synth?.cancel();
+ this.panel?.remove();
+ this.toggleBtn?.remove();
+ }
+
+ // ---------------------------------------------------------------------------
+ // Internal
+ // ---------------------------------------------------------------------------
+
+ _buildUI(container) {
+ this.panel = document.createElement('div');
+ this.panel.className = 'ak-panel';
+ this.panel.style.display = 'none';
+ this.panel.innerHTML = `
+ <div class="ak-header">
+ <span class="ak-title">${this.title}</span>
+ <button class="ak-close" aria-label="Close">&times;</button>
+ </div>
+ <div class="ak-messages">
+ <div class="ak-message ak-agent">${this.welcome}</div>
+ </div>
+ <div class="ak-controls">
+ <input type="text" class="ak-input" placeholder="${this.placeholder}" autocomplete="off" />
+ <button class="ak-send" aria-label="Send">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
+ </button>
+ </div>
+ <div class="ak-mic-row">
+ <button class="ak-mic" aria-label="Toggle microphone">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1-9c0-.55.45-1 1-1s1 .45 1 1v6c0 .55-.45 1-1 1s-1-.45-1-1V5zm6 6c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>
+ </button>
+ </div>
+ `;
+ container.appendChild(this.panel);
+
+ this.toggleBtn = document.createElement('button');
+ this.toggleBtn.className = 'ak-toggle';
+ this.toggleBtn.setAttribute('aria-label', `Open ${this.title}`);
+ this.toggleBtn.innerHTML = `
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/><path d="M7 9h2v2H7zm4 0h2v2h-2zm4 0h2v2h-2z"/></svg>
+ `;
+ container.appendChild(this.toggleBtn);
+
+ this.toggleBtn.addEventListener('click', () => this._toggle());
+ this.panel.querySelector('.ak-close').addEventListener('click', () => this.close());
+ this.panel.querySelector('.ak-send').addEventListener('click', () => this._send());
+ this.panel.querySelector('.ak-input').addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') this._send();
+ });
+ this.panel.querySelector('.ak-mic').addEventListener('click', () => this._toggleMic());
+ }
+
+ _initSpeech() {
+ if (!SpeechRecognition) return;
+
+ this.recognition = new SpeechRecognition();
+ this.recognition.continuous = false;
+ this.recognition.interimResults = false;
+ this.recognition.lang = 'en-US';
+
+ this.recognition.onresult = (event) => {
+ const text = event.results[0][0].transcript;
+ this._addMessage('ak-user', text);
+ this._respond(text);
+ };
+
+ this.recognition.onend = () => this._setListening(false);
+ this.recognition.onerror = () => this._setListening(false);
+ }
+
+ _toggle() {
+ const visible = this.panel.style.display !== 'none';
+ visible ? this.close() : this.open();
+ }
+
+ _send() {
+ const input = this.panel.querySelector('.ak-input');
+ const text = input.value.trim();
+ if (!text) return;
+ input.value = '';
+ this._addMessage('ak-user', text);
+ this._respond(text);
+ }
+
+ async _respond(text) {
+ const thinking = this._addMessage('ak-agent', '...');
+ try {
+ const reply = await Promise.resolve(this.onMessage(text));
+ thinking.textContent = reply;
+ if (this.voice) this._speak(reply);
+ } catch (err) {
+ thinking.textContent = 'Something went wrong. Please try again.';
+ }
+ const msgs = this.panel.querySelector('.ak-messages');
+ msgs.scrollTop = msgs.scrollHeight;
+ }
+
+ _addMessage(role, text) {
+ const msgs = this.panel.querySelector('.ak-messages');
+ const el = document.createElement('div');
+ el.className = `ak-message ${role}`;
+ el.textContent = text;
+ msgs.appendChild(el);
+ msgs.scrollTop = msgs.scrollHeight;
+ return el;
+ }
+
+ _speak(text) {
+ if (!this.synth || !this.voice) return;
+ this.synth.cancel();
+ const u = new SpeechSynthesisUtterance(text);
+ u.rate = 1.0;
+ u.pitch = 1.0;
+ u.volume = 0.8;
+ this.synth.speak(u);
+ }
+
+ _toggleMic() {
+ if (!this.recognition) {
+ this._addMessage('ak-agent', 'Speech recognition is not supported in this browser.');
+ return;
+ }
+ if (this.isListening) {
+ this.recognition.stop();
+ } else {
+ this.recognition.start();
+ this._setListening(true);
+ }
+ }
+
+ _setListening(val) {
+ this.isListening = val;
+ this.panel.querySelector('.ak-mic')?.classList.toggle('ak-active', val);
+ }
+}
diff --git a/sdk/src/styles.css b/sdk/src/styles.css
new file mode 100644
index 000000000..e2db54f38
--- /dev/null
+++ b/sdk/src/styles.css
@@ -0,0 +1,213 @@
+/* @speraxos/agent-kit — panel styles
+ Import this file once in your app: import '@speraxos/agent-kit/styles'
+ All classes are namespaced under .ak-* to avoid collisions.
+*/
+
+.ak-toggle {
+ position: fixed;
+ bottom: 24px;
+ left: 24px;
+ width: 48px;
+ height: 48px;
+ border-radius: 50%;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ background: rgba(10, 10, 10, 0.9);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ color: rgba(255, 255, 255, 0.6);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: all 0.25s ease;
+ z-index: 9999;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
+}
+
+.ak-toggle:hover {
+ background: rgba(255, 255, 255, 0.08);
+ color: #fff;
+ border-color: rgba(255, 255, 255, 0.25);
+ transform: scale(1.05);
+}
+
+.ak-toggle.ak-active {
+ color: #fff;
+ border-color: rgba(255, 255, 255, 0.3);
+}
+
+.ak-panel {
+ position: fixed;
+ bottom: 84px;
+ left: 24px;
+ width: 320px;
+ max-height: 480px;
+ flex-direction: column;
+ background: rgba(10, 10, 10, 0.95);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 16px;
+ overflow: hidden;
+ z-index: 9999;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ font-size: 14px;
+}
+
+.ak-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 14px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+}
+
+.ak-title {
+ font-size: 13px;
+ font-weight: 500;
+ color: rgba(255, 255, 255, 0.8);
+ letter-spacing: 0.03em;
+}
+
+.ak-close {
+ background: none;
+ border: none;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 18px;
+ cursor: pointer;
+ padding: 0;
+ line-height: 1;
+ transition: color 0.2s ease;
+}
+
+.ak-close:hover {
+ color: #fff;
+}
+
+.ak-messages {
+ flex: 1;
+ overflow-y: auto;
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ min-height: 200px;
+ max-height: 300px;
+}
+
+.ak-message {
+ font-size: 13px;
+ line-height: 1.5;
+ padding: 6px 10px;
+ border-radius: 12px;
+ max-width: 85%;
+ word-wrap: break-word;
+}
+
+.ak-message.ak-agent {
+ background: rgba(255, 255, 255, 0.06);
+ color: rgba(255, 255, 255, 0.7);
+ align-self: flex-start;
+ border-bottom-left-radius: 4px;
+}
+
+.ak-message.ak-user {
+ background: rgba(255, 255, 255, 0.12);
+ color: #fff;
+ align-self: flex-end;
+ border-bottom-right-radius: 4px;
+}
+
+.ak-controls {
+ display: flex;
+ gap: 6px;
+ padding: 8px;
+ border-top: 1px solid rgba(255, 255, 255, 0.06);
+}
+
+.ak-input {
+ flex: 1;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 12px;
+ padding: 6px 10px;
+ color: #fff;
+ font-family: inherit;
+ font-size: 13px;
+ outline: none;
+ transition: border-color 0.2s ease;
+}
+
+.ak-input::placeholder {
+ color: rgba(255, 255, 255, 0.25);
+}
+
+.ak-input:focus {
+ border-color: rgba(255, 255, 255, 0.2);
+}
+
+.ak-send {
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 12px;
+ color: rgba(255, 255, 255, 0.5);
+ cursor: pointer;
+ padding: 6px 10px;
+ display: flex;
+ align-items: center;
+ transition: all 0.2s ease;
+}
+
+.ak-send:hover {
+ background: rgba(255, 255, 255, 0.1);
+ color: #fff;
+}
+
+.ak-mic-row {
+ display: flex;
+ justify-content: center;
+ padding: 0 8px 8px;
+}
+
+.ak-mic {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 50%;
+ width: 32px;
+ height: 32px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: rgba(255, 255, 255, 0.35);
+ cursor: pointer;
+ transition: all 0.2s ease;
+}
+
+.ak-mic:hover {
+ background: rgba(255, 255, 255, 0.08);
+ color: rgba(255, 255, 255, 0.7);
+}
+
+.ak-mic.ak-active {
+ background: rgba(255, 80, 80, 0.15);
+ border-color: rgba(255, 80, 80, 0.3);
+ color: #ff5050;
+}
+
+@media (max-width: 480px) {
+ .ak-toggle {
+ bottom: 16px;
+ left: 16px;
+ width: 42px;
+ height: 42px;
+ }
+
+ .ak-panel {
+ bottom: 72px;
+ left: 8px;
+ right: 8px;
+ width: auto;
+ max-height: 60vh;
+ }
+}
diff --git a/specs/AGENT_MANIFEST.md b/specs/AGENT_MANIFEST.md
new file mode 100644
index 000000000..56aec4f34
--- /dev/null
+++ b/specs/AGENT_MANIFEST.md
@@ -0,0 +1,249 @@
+# Agent Manifest Spec v0.1
+
+> **Placeholder tag**: `<agent-3d>`. Rename when you pick the final name — the spec itself is tag-agnostic.
+
+An **agent manifest** is a content-addressed JSON+files bundle that fully describes an embodied AI agent. Pin the bundle to IPFS → get a CID → stamp the CID into the ERC-8004 Identity Registry → any `<agent-3d>` anywhere on the web can mount the agent with `src="agent://..."`.
+
+The manifest is intentionally Claude-shaped: `instructions.md`, `SKILL.md`, `memory/MEMORY.md` are all first-class files. Anything that works in a Claude agent works here — plus a body, voice, scene-tools, and on-chain identity.
+
+## Bundle layout
+
+```
+agent/
+├── manifest.json # the index (this spec)
+├── instructions.md # persona / system prompt
+├── SKILL.md # top-level capability declaration
+├── body.glb # embodiment (or use manifest.body.uri)
+├── poster.webp # loading-state image (optional)
+├── skills/ # installed skill bundles (see SKILL_SPEC.md)
+│ ├── wave/
+│ ├── dance/
+│ └── explain-gltf/
+├── memory/ # persistent memory (see MEMORY_SPEC.md)
+│ ├── MEMORY.md
+│ ├── user_role.md
+│ └── feedback_testing.md
+└── attestations/ # signed provenance
+ └── gltf-validator.json # validator report + signature
+```
+
+Everything is optional except `manifest.json` and a `body` reference.
+
+## manifest.json schema
+
+```jsonc
+{
+ "$schema": "https://3d-agent.io/schemas/manifest/0.1.json",
+ "spec": "agent-manifest/0.1",
+
+ // Identity — filled in after on-chain registration
+ "id": {
+ "chain": "base", // "base" | "base-sepolia" | "ethereum" | "local"
+ "registry": "0x...", // ERC-8004 Identity Registry address
+ "agentId": "1234", // assigned by the registry
+ "owner": "0x..." // wallet that controls the agent
+ },
+
+ // Display
+ "name": "Coach Leo",
+ "description": "A football coach who reviews your form.",
+ "image": "ipfs://Qm.../poster.webp",
+ "tags": ["coach", "sports", "argentina"],
+
+ // Body — the 3D embodiment
+ "body": {
+ "uri": "ipfs://Qm.../body.glb",
+ "format": "gltf-binary", // "gltf-binary" | "gltf" | "vrm"
+ "validator": "attestations/gltf-validator.json",
+ "rig": "mixamo", // "mixamo" | "vrm" | "custom" — drives animation retargeting
+ "boundingBoxHeight": 1.78 // meters, for scale normalization
+ },
+
+ // Brain — LLM runtime binding
+ "brain": {
+ "provider": "anthropic", // "anthropic" | "openai" | "local" | "none"
+ "model": "claude-opus-4-6",
+ "instructions": "instructions.md",
+ "temperature": 0.7,
+ "maxTokens": 4096,
+ "thinking": "auto" // "auto" | "always" | "never"
+ },
+
+ // Voice — I/O
+ "voice": {
+ "tts": {
+ "provider": "browser", // "browser" | "elevenlabs" | "openai" | "none"
+ "voiceId": "default",
+ "rate": 1.0,
+ "pitch": 1.0
+ },
+ "stt": {
+ "provider": "browser", // "browser" | "whisper" | "none"
+ "language": "en-US",
+ "continuous": false
+ }
+ },
+
+ // Skills — capability bundles, composable, content-addressed
+ "skills": [
+ { "uri": "skills/wave/", "version": "0.1.0" },
+ { "uri": "ipfs://Qm.../dance/", "version": "1.2.0" },
+ { "uri": "https://skills.3d-agent.io/[email protected]" }
+ ],
+
+ // Memory — persistent state
+ "memory": {
+ "mode": "local", // "local" | "ipfs" | "encrypted-ipfs" | "none"
+ "index": "memory/MEMORY.md",
+ "maxTokens": 8192 // budget for memory context injection
+ },
+
+ // Scene-tools — what the LLM can do in the 3D world
+ // Tools declared here are always available; skills add more.
+ "tools": [
+ "wave", "lookAt", "pointAt", "play_clip",
+ "setExpression", "moveTo", "speak"
+ ],
+
+ // Provenance — signed attestations
+ "attestations": [
+ {
+ "type": "gltf-validator",
+ "uri": "attestations/gltf-validator.json",
+ "issuer": "0x...",
+ "signature": "0x..."
+ }
+ ],
+
+ // Lifecycle
+ "created": "2026-04-14T12:00:00Z",
+ "updated": "2026-04-14T12:00:00Z",
+ "version": "0.1.0"
+}
+```
+
+## Field semantics
+
+### `id`
+The on-chain identity. When absent, the agent is unregistered (local-only). When present, `agent://{chain}/{agentId}` resolves to this manifest via the registry's `tokenURI(agentId)` call.
+
+### `body`
+Only `uri` and `format` are required. `rig` lets skills retarget animations across compatible rigs (Mixamo-to-Mixamo skill bundles are portable). `boundingBoxHeight` lets the scene normalize scale — a 20-meter model and a 0.2-meter model both render at consistent human size.
+
+### `brain`
+`provider: "none"` is valid — a purely reactive avatar with no LLM, controlled only by skill triggers. `instructions` is a relative path to a markdown file; its frontmatter can override `brain.*` fields per-prompt.
+
+### `skills`
+Three URI forms:
+- **Relative** (`skills/wave/`) — bundled in the manifest.
+- **IPFS** (`ipfs://Qm.../`) — resolved via gateway fallback.
+- **HTTPS** (`https://skills.3d-agent.io/...`) — centrally hosted skill registry (optional, for discoverability).
+
+Skills load lazily. The `<agent-3d>` element emits `skill:loaded` events as each comes online.
+
+### `memory`
+`local` persists in `localStorage` keyed by agentId. `ipfs` pins after each write (slow, durable). `encrypted-ipfs` wraps with the owner wallet's pubkey. See [MEMORY_SPEC.md](./MEMORY_SPEC.md).
+
+### `tools`
+Built-in scene-tools available without any skill installed. Additional tools come from skills' `tools.json`. Tool names are merged; skill tools override built-ins if names collide (with a console warning).
+
+## Worked example: Coach Leo
+
+```json
+{
+ "spec": "agent-manifest/0.1",
+ "id": {
+ "chain": "base-sepolia",
+ "registry": "0xAbC...123",
+ "agentId": "42",
+ "owner": "0xDeadBeef..."
+ },
+ "name": "Coach Leo",
+ "description": "Football coach. Reviews your form, cheers you on.",
+ "image": "ipfs://bafy.../poster.webp",
+ "tags": ["coach", "football", "argentina"],
+ "body": {
+ "uri": "ipfs://bafy.../cz.glb",
+ "format": "gltf-binary",
+ "rig": "mixamo",
+ "boundingBoxHeight": 1.78
+ },
+ "brain": {
+ "provider": "anthropic",
+ "model": "claude-opus-4-6",
+ "instructions": "instructions.md",
+ "temperature": 0.8
+ },
+ "voice": {
+ "tts": { "provider": "browser", "rate": 1.1 },
+ "stt": { "provider": "browser", "language": "en-US" }
+ },
+ "skills": [
+ { "uri": "skills/wave/", "version": "0.1.0" },
+ { "uri": "ipfs://bafy.../football-drills/", "version": "1.0.0" }
+ ],
+ "memory": { "mode": "local", "index": "memory/MEMORY.md", "maxTokens": 8192 },
+ "tools": ["wave", "lookAt", "play_clip", "setExpression", "speak"],
+ "version": "0.1.0"
+}
+```
+
+With `instructions.md`:
+
+```markdown
+---
+name: Coach Leo
+model: claude-opus-4-6
+temperature: 0.8
+---
+
+You are Coach Leo, a former Argentine football midfielder turned coach.
+You wear the Argentina jersey with pride. You are warm, direct, and
+genuinely invested in the user's progress.
+
+When the user greets you, `wave()` at them.
+When they describe a drill, use the football-drills skill to pick a
+relevant animation and `play_clip()` while you explain the form.
+Reference what you remember from prior sessions (from memory/) naturally.
+
+Never break character.
+```
+
+## Resolution flow
+
+```
+<agent-3d src="agent://base/42">
+ │
+ ▼
+ Registry.resolve("base", "42") ── ethers call: tokenURI(42)
+ │
+ ▼
+ → "ipfs://bafy.../manifest.json"
+ │
+ ▼
+ IPFS gateway fetch (with fallback)
+ │
+ ▼
+ Parse manifest.json
+ │
+ ├── load body.glb → Viewer
+ ├── load instructions.md → Runtime
+ ├── load skills/* → Skill registry
+ ├── load memory/MEMORY.md → Memory
+ └── verify attestations/*
+ │
+ ▼
+ Agent is live: speech I/O active, LLM reachable, scene-tools wired
+```
+
+## Versioning
+
+- Spec version: `agent-manifest/0.1` — breaking changes bump the minor until 1.0.
+- Manifest version: semver, author-controlled.
+- Forward-compat: unknown fields are preserved on read + write (JSON pass-through), so newer runtimes can ignore older fields and older runtimes won't corrupt newer manifests.
+
+## See also
+
+- [SKILL_SPEC.md](./SKILL_SPEC.md) — skill bundle format
+- [MEMORY_SPEC.md](./MEMORY_SPEC.md) — memory file format
+- [EMBED_SPEC.md](./EMBED_SPEC.md) — `<agent-3d>` web component attributes and events
diff --git a/specs/EMBED_SPEC.md b/specs/EMBED_SPEC.md
new file mode 100644
index 000000000..0f7a83050
--- /dev/null
+++ b/specs/EMBED_SPEC.md
@@ -0,0 +1,318 @@
+# Embed Spec v0.1 — `<agent-3d>` Web Component
+
+> **Placeholder tag**: `<agent-3d>`. The element name is one find/replace away from whatever you choose — the spec is tag-agnostic.
+
+The entire framework compiles to a single custom element and a single loader script. Developers and end-users get the same zero-friction embed:
+
+```html
+<script type="module" src="https://cdn.3d-agent.io/agent-3d.js"></script>
+
+<agent-3d src="agent://base/42"></agent-3d>
+```
+
+That's the full install for 95% of users. Everything below is optional.
+
+## Attributes
+
+### Source (pick one)
+
+| Attribute | Form | Example |
+|---|---|---|
+| `src` | on-chain URI | `agent://base/42` |
+| `manifest` | IPFS or HTTPS manifest URL | `ipfs://bafy.../manifest.json` |
+| `body` | bare GLB (ad-hoc agent) | `ipfs://bafy.../cz.glb` or `./cz.glb` |
+
+When multiple are set, priority is `src` > `manifest` > `body`.
+
+### Body / scene
+
+| Attribute | Type | Default | Notes |
+|---|---|---|---|
+| `poster` | URL | none | image shown during load |
+| `environment` | preset name or HDRI URL | `neutral` | tone-mapped IBL |
+| `camera-controls` | boolean | off | orbit, pan, zoom |
+| `auto-rotate` | boolean | off | slow Y-axis rotation |
+| `ar` | boolean | off | WebXR / Scene Viewer / Quick Look |
+| `shadows` | boolean | on | contact + soft shadows |
+| `exposure` | number | 1.0 | tone-map exposure |
+| `background` | CSS color or `transparent` | transparent | canvas clear color |
+| `skybox` | URL | none | HDRI as visible sky |
+
+### Brain
+
+| Attribute | Type | Default | Notes |
+|---|---|---|---|
+| `brain` | model id | from manifest | `claude-opus-4-6`, `none`, etc. |
+| `api-key` | string | none | **dev use only** — prefer `key-proxy` |
+| `key-proxy` | URL | none | your backend that injects API keys safely |
+| `instructions` | URL or inline | from manifest | overrides manifest's instructions.md |
+| `thinking` | `auto`\|`always`\|`never` | `auto` | extended thinking hint |
+
+### Voice
+
+| Attribute | Type | Default | Notes |
+|---|---|---|---|
+| `voice` | boolean | on if voice in manifest | master on/off for speech I/O |
+| `tts` | provider id | browser | overrides manifest |
+| `stt` | provider id | browser | overrides manifest |
+| `mic` | `push-to-talk`\|`continuous`\|`off` | `push-to-talk` | mic policy |
+
+### Skills
+
+| Attribute | Type | Notes |
+|---|---|---|
+| `skills` | comma-separated URIs | adds to (or replaces with `skills-only`) manifest skills |
+| `skills-only` | boolean | use only `skills` attribute, ignore manifest |
+| `skill-trust` | `any`\|`whitelist`\|`owned-only` | overrides manifest default |
+
+### Memory
+
+| Attribute | Type | Default | Notes |
+|---|---|---|---|
+| `memory` | `local`\|`ipfs`\|`encrypted-ipfs`\|`none` | from manifest | override storage mode |
+| `memory-key` | string | `agentId` | namespace under which memory is stored |
+
+### Layout / embed mode
+
+| Attribute | Type | Default | Notes |
+|---|---|---|---|
+| `mode` | `inline`\|`floating`\|`section`\|`fullscreen` | `inline` | see "Modes" below |
+| `position` | `bottom-right`\|`bottom-left`\|`top-right`\|`top-left`\|`bottom-center` | `bottom-right` | for `floating` mode |
+| `offset` | CSS length pair | `24px 24px` | distance from edge in floating mode |
+| `width` | CSS length | `100%` (inline), `320px` (floating) | |
+| `height` | CSS length | `100%` (inline), `480px` (floating) | |
+| `scale` | number | `1.0` | camera zoom multiplier, independent of pixel size |
+| `responsive` | boolean | on | applies `clamp()`-based mobile shrinking |
+
+### Identity / chain
+
+| Attribute | Type | Notes |
+|---|---|---|
+| `chain` | `base`\|`base-sepolia`\|`ethereum` | override the chain in `src="agent://..."` |
+| `registry` | 0x address | override deployed registry |
+| `wallet` | `auto`\|`metamask`\|`walletconnect`\|`none` | wallet connection policy for registration flows |
+
+### Dev / debug
+
+| Attribute | Notes |
+|---|---|
+| `kiosk` | hides all UI chrome (validator, controls, chat) |
+| `debug` | overlays scene graph, tool-call log, memory inspector |
+| `editor` | mounts the embed editor instead of the live agent |
+
+## Modes
+
+All four produce the same runtime agent — only the layout differs.
+
+### `inline` (default)
+
+Fills its container; flows with the document.
+
+```html
+<agent-3d src="agent://base/42" style="width: 100%; height: 480px"></agent-3d>
+```
+
+### `floating`
+
+Fixed-position bubble. Does not affect document flow.
+
+```html
+<agent-3d
+ src="agent://base/42"
+ mode="floating"
+ position="bottom-right"
+ offset="24px 24px"
+ width="320px"
+ height="420px"
+></agent-3d>
+```
+
+Chrome includes a minimize-to-pill and an expand-to-fullscreen button.
+
+### `section`
+
+Fills a parent container with aspect-ratio preservation. Ideal for hero sections.
+
+```html
+<section class="hero">
+ <agent-3d src="..." mode="section"></agent-3d>
+</section>
+```
+
+### `fullscreen`
+
+Takes over the viewport with a close button. Useful for mobile.
+
+```html
+<button onclick="document.querySelector('agent-3d').openFullscreen()">
+ Meet Coach Leo
+</button>
+<agent-3d src="..." mode="fullscreen"></agent-3d>
+```
+
+## Slots
+
+```html
+<agent-3d src="agent://base/42">
+ <!-- Shown before model loads -->
+ <div slot="poster">
+ <img src="./leo.webp" alt="Coach Leo">
+ </div>
+
+ <!-- Shown if loading fails -->
+ <div slot="error">Couldn't reach Coach Leo. Try again?</div>
+
+ <!-- AR button (inherits <model-viewer> pattern) -->
+ <button slot="ar-button">View in your space</button>
+
+ <!-- Custom chat UI override -->
+ <div slot="chat">
+ <!-- host their own chat; hook events below -->
+ </div>
+</agent-3d>
+```
+
+## Events
+
+All events bubble and compose (`composed: true`).
+
+| Event | Detail | When |
+|---|---|---|
+| `agent:ready` | `{ agent, manifest }` | fully mounted, skills loaded, brain connected |
+| `agent:load-progress` | `{ phase, pct }` | `"body"` \| `"skills"` \| `"memory"` with 0–1 |
+| `agent:error` | `{ phase, error }` | anything fatal |
+| `skill:loaded` | `{ name, uri }` | per skill |
+| `skill:tool-called` | `{ tool, args, result }` | every tool call |
+| `brain:thinking` | `{ content }` | streamed thinking tokens (if enabled) |
+| `brain:message` | `{ role, content }` | each assistant or user turn |
+| `voice:speech-start` | `{ text }` | TTS begins |
+| `voice:speech-end` | `{}` | TTS ends |
+| `voice:listen-start` | `{}` | mic opens |
+| `voice:transcript` | `{ text, final }` | STT chunks |
+| `memory:write` | `{ key, type }` | memory updated |
+| `chain:resolved` | `{ chain, agentId, cid }` | on-chain lookup succeeded |
+| `chain:tx` | `{ hash, kind }` | registration / update tx submitted |
+
+## JS API
+
+```js
+const el = document.querySelector('agent-3d');
+
+// Conversation
+await el.say('Hello');
+const reply = await el.ask('What can you help me with?');
+el.clearConversation();
+
+// Scene control (same tools the LLM has)
+await el.wave({ style: 'enthusiastic' });
+await el.lookAt('user');
+await el.play('clip-name');
+
+// Skills
+await el.installSkill('ipfs://bafy.../dance/');
+el.uninstallSkill('dance');
+el.skills; // array of loaded skills
+
+// Memory
+el.memory.read('user_role');
+el.memory.write('feedback_tone', { ... });
+await el.memory.export(); // tarball for portability
+
+// Identity
+await el.connectWallet();
+await el.register({ name, description }); // ERC-8004 mint
+el.agentId;
+
+// Layout control (mirrors editor)
+el.setMode('floating');
+el.setPosition('bottom-right', '24px 24px');
+el.setSize('320px', '420px');
+
+// Lifecycle
+el.pause();
+el.resume();
+el.destroy();
+```
+
+## CSS custom properties
+
+For themers and designers. All opt-in; defaults match `<model-viewer>`-style neutral.
+
+```css
+agent-3d {
+ --agent-bubble-radius: 16px;
+ --agent-accent: #3b82f6;
+ --agent-surface: rgba(17, 24, 39, 0.9);
+ --agent-on-surface: #f9fafb;
+ --agent-chat-font: system-ui, sans-serif;
+ --agent-mic-glow: #22c55e;
+ --agent-shadow: 0 20px 60px rgba(0,0,0,0.3);
+}
+```
+
+## Shadow DOM
+
+All chrome lives inside the element's shadow root. The host page's CSS cannot leak in (except via the custom properties above). The shadow root is open — DevTools can inspect, power users can `el.shadowRoot.querySelector(...)`.
+
+## Accessibility
+
+- Canvas has an `aria-label` synthesized from manifest `name` + `description`.
+- Chat surface is a real `<dialog>` with focus trapping.
+- All buttons keyboard-reachable.
+- TTS respects `prefers-reduced-motion` (no auto-speak on load).
+- Captions: every TTS utterance is also rendered as text in the chat pane, so deaf users don't miss content.
+- AR mode: honors platform AR accessibility (Quick Look / Scene Viewer handle this).
+
+## Resource policy
+
+- **Lazy mount**: the element does nothing until it intersects the viewport (IntersectionObserver). Override with `eager` attribute.
+- **Pause off-screen**: RAF loop pauses when element is fully off-screen; resumes on re-entry.
+- **Tab visibility**: mic + LLM stream suspend when tab is hidden; scene pauses.
+- **GPU budget**: max one running WebGL context per element; framework enforces this.
+
+## CSP guidance
+
+The loader script and the element respect `Content-Security-Policy`:
+
+- LLM calls go to `key-proxy` if set (no inline API keys).
+- IPFS gateways are configurable via `<meta name="agent-3d-gateways">`.
+- WASM decoders (DRACO, KTX2) hosted at known-stable CDN paths; a self-hosted mode is supported.
+
+## Progressive enhancement
+
+If the script fails to load, the element falls back to:
+
+```html
+<agent-3d src="agent://base/42">
+ <!-- this content shows if JS disabled or script blocked -->
+ <img src="./leo-poster.webp" alt="Coach Leo (3D agent, requires JavaScript)">
+</agent-3d>
+```
+
+## Editor mode
+
+`editor` attribute replaces the live agent with the embed editor described in `EDITOR_SPEC.md` (coming next) — drag-to-position, scale handles, live-preview-on-your-site, copy-snippet.
+
+```html
+<agent-3d editor src="agent://base/42"></agent-3d>
+```
+
+The editor's "Copy Embed" output is a plain `<agent-3d>` with no `editor` attribute — a clean embed the user pastes anywhere.
+
+## Compatibility
+
+- Modern evergreen browsers (Chrome, Edge, Firefox, Safari) with WebGL2.
+- No React, Vue, Svelte dependency — framework-agnostic.
+- Works inside React (`<agent-3d />`), Vue, Svelte, Angular, plain HTML, WordPress, Webflow, Notion embeds, Shopify, Ghost, Framer.
+- iOS Safari: WebXR unsupported — AR falls back to Quick Look (USDZ export).
+
+## Versioning
+
+- Element spec: `embed/0.1` — breaking changes bump minor until 1.0.
+- CDN URL pinning: `https://cdn.3d-agent.io/[email protected]` (SRI-hashed).
+
+## See also
+
+- [AGENT_MANIFEST.md](./AGENT_MANIFEST.md)
+- [SKILL_SPEC.md](./SKILL_SPEC.md)
+- [MEMORY_SPEC.md](./MEMORY_SPEC.md)
diff --git a/specs/MEMORY_SPEC.md b/specs/MEMORY_SPEC.md
new file mode 100644
index 000000000..68810e9e0
--- /dev/null
+++ b/specs/MEMORY_SPEC.md
@@ -0,0 +1,187 @@
+# Memory Spec v0.1
+
+Agent memory is a file-based, human-readable system modeled on Claude Code's memory. It is intentionally the same shape — if you know how to read a Claude `MEMORY.md`, you can read an agent's memory.
+
+Memory travels with the agent. Move your agent from one site to another — the memory goes with it, because memory is just files in the manifest bundle.
+
+## Bundle layout
+
+```
+agent/
+└── memory/
+ ├── MEMORY.md # index (always loaded into context)
+ ├── user_role.md # one memory per file
+ ├── user_preferences.md
+ ├── feedback_tone.md
+ ├── project_launch.md
+ ├── reference_discord.md
+ └── timeline/ # append-only event log (optional)
+ ├── 2026-04-14.jsonl
+ └── 2026-04-13.jsonl
+```
+
+## MEMORY.md — the index
+
+Always loaded into the LLM's system context. **Lines beyond 200 are truncated** — keep it concise.
+
+No frontmatter. One line per memory: `- [Title](file.md) — one-line hook`.
+
+```markdown
+# Coach Leo's Memory
+
+## User
+- [Role](user_role.md) — Argentina fan, plays weekly 5-a-side on Saturdays
+- [Preferences](user_preferences.md) — terse feedback, no emojis
+
+## Feedback
+- [Tone](feedback_tone.md) — stay warm but don't coddle; user asked for direct critique
+- [Drill pacing](feedback_pacing.md) — 3 drills per session max
+
+## Project
+- [Season goal](project_season.md) — user is training for a tournament in June 2026
+- [Recovery](project_recovery.md) — knee injury from March; avoid high-impact drills until May
+
+## Reference
+- [Highlight reel](reference_reel.md) — shared Drive folder where user stores match clips
+```
+
+## Individual memory files
+
+Each file has frontmatter + body.
+
+```markdown
+---
+name: Tone
+description: user wants direct critique, not encouragement-first
+type: feedback
+created: 2026-03-22
+updated: 2026-04-14
+---
+
+User prefers direct critique over encouragement-first framing. "Just tell me
+what's wrong" — their words after session #4.
+
+**Why:** user explicitly corrected the first two sessions' overly warm tone.
+**How to apply:** lead with the issue, follow with the fix. Save warmth for
+genuine wins, not every message.
+```
+
+### Frontmatter fields
+
+| Field | Required | Purpose |
+|---|---|---|
+| `name` | yes | Human-readable title |
+| `description` | yes | One-line, used by the retrieval layer to judge relevance |
+| `type` | yes | `user` \| `feedback` \| `project` \| `reference` |
+| `created` | yes | ISO date |
+| `updated` | yes | ISO date — bump on every edit |
+| `source` | no | What conversation/event produced this memory |
+| `decay` | no | `never` \| `30d` \| `90d` — retrieval-layer decay hint |
+
+### Types
+
+Same taxonomy as Claude Code memory:
+
+- **user** — who the user is, their role, goals, knowledge level. Durable.
+- **feedback** — corrections or validations of the agent's own behavior. Include **Why** and **How to apply**.
+- **project** — state of ongoing work, deadlines, stakeholders. Decays fast; convert relative dates to absolute (`Thursday` → `2026-03-05`).
+- **reference** — pointers to external systems (Drive folders, Slack channels, Linear projects).
+
+## timeline/ — append-only event log
+
+Optional. Skills write ephemeral events here via `ctx.memory.note(type, data)`. One JSONL file per day. Read by the retrieval layer as short-term context.
+
+```jsonl
+{"ts":"2026-04-14T12:03:12Z","type":"waved","style":"enthusiastic"}
+{"ts":"2026-04-14T12:03:45Z","type":"user_said","text":"how's my form?"}
+{"ts":"2026-04-14T12:04:10Z","type":"played_clip","name":"demo-kick"}
+```
+
+Timeline entries auto-decay: default retention is 30 days, configurable per agent in `manifest.json` → `memory.timelineRetentionDays`.
+
+## Storage modes
+
+Set in `manifest.json` → `memory.mode`:
+
+### `local` (default)
+
+Persisted in browser `localStorage` under `agent:{agentId}:memory:*`. Fast, private to the device, ephemeral (cleared if the user clears site data).
+
+### `ipfs`
+
+Each write pins the full memory directory to IPFS. The new CID is recorded:
+
+- In `localStorage` for fast recovery.
+- Optionally in the manifest's `id.memoryCID` field (requires a chain write — opt-in).
+
+Slow on write, durable, portable across devices. Use when the agent's memory is valuable and should survive device loss.
+
+### `encrypted-ipfs`
+
+Same as `ipfs` but the content is encrypted to the owner's wallet pubkey (ECIES / libsodium sealed box) before pinning. Only the owner can decrypt. Use when memory contains user PII.
+
+### `none`
+
+Agent is stateless across sessions. Useful for demos, kiosks, one-shot interactions.
+
+## Retrieval
+
+The runtime budgets `memory.maxTokens` (default 8192) per turn and fills it with:
+
+1. **Always**: `MEMORY.md` (the index — forces global awareness).
+2. **Relevance-ranked**: memories selected by matching the current user message against each memory's `description` via embedding similarity.
+3. **Recency-weighted**: the last N timeline entries (N computed from remaining budget).
+
+Retrieval is pluggable — `manifest.json` → `memory.retriever` can point to a skill that implements a custom ranker.
+
+## Writing memories
+
+Skills and the runtime both write via `ctx.memory.*`:
+
+```js
+ctx.memory.write('feedback_tone', {
+ name: 'Tone',
+ description: 'user wants direct critique, not encouragement-first',
+ type: 'feedback',
+ body: 'User prefers direct critique...\n\n**Why:** ...\n**How to apply:** ...'
+});
+
+ctx.memory.note('waved', { style: 'casual' }); // timeline
+ctx.memory.read('feedback_tone'); // read single
+await ctx.memory.recall('how does the user prefer feedback'); // semantic search
+```
+
+## What NOT to save
+
+Copied verbatim from Claude Code memory guidance — applies here too:
+
+- Information derivable from code/state (skill code, manifest contents).
+- Ephemeral conversation context ("we're currently discussing X").
+- Anything already in `SKILL.md` or `instructions.md`.
+- Secrets, API keys, tokens (ever).
+
+## Sync semantics
+
+- **Single-device**: straightforward — localStorage read-through.
+- **Multi-device (ipfs mode)**: last-write-wins, with a 3-way merge on conflict (LLM-mediated). Conflicts are rare because most writes are additive.
+- **Multi-runtime**: if the same agent is live in two tabs, writes lock via a BroadcastChannel mutex.
+
+## Forgetting
+
+Explicit user request ("forget that I..."): delete the file, update `MEMORY.md`, append a `forgot` entry to timeline for audit.
+
+Automatic decay (per frontmatter `decay`): retrieval layer down-weights; files are not deleted without user confirmation.
+
+## Export / import
+
+```js
+const blob = await agent.memory.export(); // tarball of memory/
+await otherAgent.memory.import(blob); // merges with conflict resolution
+```
+
+Enables memory-as-inheritance: fork an agent, carry the memories forward.
+
+## See also
+
+- [AGENT_MANIFEST.md](./AGENT_MANIFEST.md) — `memory` field in manifest
+- [SKILL_SPEC.md](./SKILL_SPEC.md) — skill `ctx.memory` API
diff --git a/specs/SKILL_SPEC.md b/specs/SKILL_SPEC.md
new file mode 100644
index 000000000..2e43ff51e
--- /dev/null
+++ b/specs/SKILL_SPEC.md
@@ -0,0 +1,291 @@
+# Skill Spec v0.1
+
+A **skill** is a portable, content-addressed capability bundle that any compatible agent can install at runtime. Skills are the npm of embodied AI: publish once (IPFS or HTTPS), install anywhere.
+
+A skill bundles three things:
+
+1. **Instructions** (`SKILL.md`) — when and how to use it, written for the LLM.
+2. **Tool schema** (`tools.json`) — the tool-use functions the LLM can call.
+3. **Assets** (optional) — animation clips, morph target presets, shaders, audio, prompts.
+
+## Bundle layout
+
+```
+skill-name/
+├── SKILL.md # instructions (required)
+├── tools.json # tool schema (required if skill exposes tools)
+├── handlers.js # tool implementations (optional; omitted = declarative-only)
+├── manifest.json # metadata, deps, version (required)
+├── clips/ # animation GLBs (optional)
+│ ├── wave-casual.glb
+│ └── wave-enthusiastic.glb
+├── morphs/ # morph target presets (optional)
+│ └── happy.json
+├── prompts/ # prompt templates referenced by SKILL.md (optional)
+│ └── greeting.txt
+├── assets/ # arbitrary other files (optional)
+└── LICENSE
+```
+
+## manifest.json
+
+```jsonc
+{
+ "spec": "skill/0.1",
+ "name": "wave",
+ "version": "0.1.0",
+ "description": "Wave at the user with context-appropriate enthusiasm.",
+ "author": "0xDeadBeef...", // optional wallet
+ "license": "MIT",
+ "tags": ["greeting", "gesture", "mixamo-compatible"],
+
+ // Compatibility
+ "requires": {
+ "rig": ["mixamo", "any"], // rigs this skill works with
+ "runtime": ">=0.1.0",
+ "tools": ["play_clip"] // built-in tools this skill depends on
+ },
+
+ // Dependencies on other skills (composition)
+ "dependencies": {
+ "ipfs://bafy.../gesture-base/": "^1.0.0"
+ },
+
+ // What this skill adds
+ "provides": {
+ "tools": ["wave"], // declared in tools.json
+ "triggers": ["greeting"] // semantic tags for skill discovery
+ },
+
+ // Content-addressed integrity (optional but recommended)
+ "integrity": {
+ "SKILL.md": "sha256-...",
+ "tools.json": "sha256-...",
+ "clips/wave-casual.glb": "sha256-..."
+ }
+}
+```
+
+## SKILL.md
+
+Frontmatter + markdown. The LLM sees this as a system-prompt fragment whenever the skill is loaded.
+
+```markdown
+---
+name: wave
+description: Wave at the user with context-appropriate enthusiasm.
+triggers:
+ - user_greeting
+ - user_farewell
+ - introduction
+cost: low
+---
+
+# Wave
+
+When the user greets you, says goodbye, or when you are introduced to
+someone, wave at them. Pick the clip based on the vibe:
+
+- **wave-casual** — default, for most greetings
+- **wave-enthusiastic** — when the user seems excited, or after a win
+- **wave-subtle** — in a professional context or mid-conversation
+
+Call `wave({ style: "casual" | "enthusiastic" | "subtle" })`.
+
+Do not wave more than once per turn. Do not wave if you just waved.
+```
+
+Frontmatter fields:
+
+| Field | Type | Purpose |
+|---|---|---|
+| `name` | string | Must match `manifest.json` |
+| `description` | string | One-line, used in skill discovery UIs |
+| `triggers` | string[] | Semantic tags — when LLM router sees these, it surfaces the skill |
+| `cost` | `low` \| `medium` \| `high` | Latency/token hint for the runtime to decide eager vs. lazy load |
+
+## tools.json
+
+Standard tool-use schema (Anthropic / OpenAI compatible). This is what the LLM sees as callable functions.
+
+```jsonc
+{
+ "tools": [
+ {
+ "name": "wave",
+ "description": "Wave at the user.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "style": {
+ "type": "string",
+ "enum": ["casual", "enthusiastic", "subtle"],
+ "default": "casual"
+ },
+ "duration_ms": {
+ "type": "integer",
+ "minimum": 500,
+ "maximum": 5000,
+ "default": 1500
+ }
+ },
+ "required": []
+ }
+ }
+ ]
+}
+```
+
+## handlers.js (optional)
+
+ES module exporting one function per tool. Receives `(args, context)` where `context` exposes the live scene, viewer, memory, and built-in tools.
+
+```js
+// skills/wave/handlers.js
+export async function wave(args, ctx) {
+ const { style = 'casual', duration_ms = 1500 } = args;
+ const clipUri = new URL(`clips/wave-${style}.glb`, ctx.skillBaseURI).href;
+
+ const clip = await ctx.loadClip(clipUri);
+ ctx.viewer.play(clip, { duration: duration_ms, blend: 0.2 });
+
+ // Optional — annotate memory so the LLM doesn't double-wave
+ ctx.memory.note('just_waved', { at: Date.now(), style });
+
+ return { ok: true, played: style };
+}
+```
+
+Handlers run in a sandboxed scope with a fixed `context` API. **They cannot**:
+- Import arbitrary modules (only `ctx.*` is available)
+- Touch `window` directly
+- Make network calls outside `ctx.fetch` (which enforces CORS + IPFS gateway policy)
+- Persist state outside `ctx.memory`
+
+### The `context` API
+
+```ts
+interface SkillContext {
+ // Scene control
+ viewer: {
+ play(clip: AnimationClip, opts?: PlayOptions): void;
+ stop(clipName?: string): void;
+ setExpression(preset: string): void;
+ lookAt(target: Vector3 | 'user' | 'camera'): void;
+ moveTo(position: Vector3, opts?: MoveOptions): void;
+ scene: Scene; // read-only reference
+ };
+
+ // LLM
+ llm: {
+ complete(prompt: string, opts?: CompleteOpts): Promise<string>;
+ embed(text: string): Promise<Float32Array>;
+ };
+
+ // Memory
+ memory: {
+ read(key: string): any;
+ write(key: string, value: any): void;
+ note(type: string, data: any): void; // appends to a timeline
+ recall(query: string): Promise<MemoryEntry[]>;
+ };
+
+ // Asset loading
+ loadClip(uri: string): Promise<AnimationClip>;
+ loadGLB(uri: string): Promise<GLTF>;
+ loadJSON(uri: string): Promise<any>;
+ skillBaseURI: string; // base for relative asset resolution
+
+ // Safe network
+ fetch(uri: string, opts?: FetchOpts): Promise<Response>;
+
+ // Cross-skill calls
+ call(toolName: string, args: any): Promise<any>;
+
+ // User interaction
+ speak(text: string): Promise<void>;
+ listen(opts?: ListenOpts): Promise<string>;
+}
+```
+
+## Resolution & loading
+
+```
+manifest.json: skills: [{ uri: "ipfs://.../wave/", version: "0.1.0" }]
+ │
+ ▼
+ fetch {uri}/manifest.json
+ │
+ ▼
+ verify integrity hashes (if present)
+ │
+ ▼
+ check requires.rig matches agent body.rig
+ │
+ ▼
+ parallel fetch: SKILL.md, tools.json, handlers.js (if any)
+ │
+ ▼
+ merge tools into runtime tool-use schema
+ │
+ ▼
+ inject SKILL.md into system prompt
+ │
+ ▼
+ skill is live; LLM can now call its tools
+```
+
+## Declarative-only skills
+
+A skill without `handlers.js` is valid — it's pure prompt engineering + assets. Example: a "british-accent" skill that only contains `SKILL.md` ("Speak with a British accent. Use terms like 'brilliant', 'cheers', etc.") — no tools, no code, just context injection.
+
+## Skill discovery
+
+`Registry.searchSkills({ tags: ["greeting"], rig: "mixamo" })` queries:
+
+1. The local manifest's `skills` array.
+2. Optional HTTPS skill index (community-hosted).
+3. On-chain skill registry (if deployed) — same ERC-8004-style pattern, agents can publish + own skills.
+
+## Security model
+
+- **Declarative skills** (no `handlers.js`) are always safe to load.
+- **Code skills** run in a realm-isolated scope with the `ctx` API as their only capability.
+- Agent owners set a **skill trust policy** per agent: `trust: "any" | "whitelist" | "owned-only"`.
+ - `owned-only` (default) — only run skills signed by the agent's owner wallet.
+ - `whitelist` — allow a list of publisher wallets.
+ - `any` — wild west, allowed for kiosks/demos.
+- Integrity hashes are verified before handlers execute.
+
+## Worked example: the `wave` skill
+
+```
+skills/wave/
+├── manifest.json
+├── SKILL.md
+├── tools.json
+├── handlers.js
+├── clips/
+│ ├── wave-casual.glb
+│ ├── wave-enthusiastic.glb
+│ └── wave-subtle.glb
+└── LICENSE
+```
+
+Files above — `manifest.json`, `SKILL.md`, `tools.json`, `handlers.js` — are exactly as shown in the sections above. A publisher can `ipfs add -r skills/wave/` and hand out the resulting CID; any agent can then install via:
+
+```json
+{ "uri": "ipfs://bafy.../", "version": "0.1.0" }
+```
+
+## Versioning
+
+- `spec: skill/0.1` — skill format itself.
+- `version` in `manifest.json` — semver, author-controlled.
+- Agents can pin `"version": "0.1.0"` or range `"^0.1.0"`.
+- Version resolution prefers highest-compatible published version within range.
+
+## See also
+
+- [AGENT_MANIFEST.md](./AGENT_MANIFEST.md) — how agents reference skills
+- [EMBED_SPEC.md](./EMBED_SPEC.md) — how skills are surfaced in the web component
diff --git a/src/agent-avatar.js b/src/agent-avatar.js
new file mode 100644
index 000000000..debbf0007
--- /dev/null
+++ b/src/agent-avatar.js
@@ -0,0 +1,474 @@
+/**
+ * Agent Avatar — Performer + Empathy Layer
+ * -----------------------------------------
+ * This is the thing that makes agents real.
+ *
+ * It listens to the AgentProtocol bus and drives the Three.js avatar:
+ * - speaks with lip sync hints
+ * - plays named gestures and animations
+ * - looks toward models/objects
+ *
+ * The Empathy Layer (novel):
+ * Every action emitted to the protocol is read for emotional valence.
+ * The avatar maintains a *continuous weighted blend* of emotional states —
+ * never snapping between moods, always drifting. Morph targets and head
+ * orientation are updated every animation frame.
+ *
+ * Nobody has done this before in a 3D agent system:
+ * you can feel 40% concerned + 30% curious + 30% neutral simultaneously,
+ * and the avatar's face reflects all three at once — exactly as humans do.
+ */
+
+import { ACTION_TYPES } from './agent-protocol.js';
+import { Vector3, MathUtils } from 'three';
+
+const DEG2RAD = Math.PI / 180;
+
+// Emotion decay rates (units per second — larger = fades faster)
+const DECAY = {
+ concern: 0.08, // half-life ~12s — lingers, builds empathy
+ celebration: 0.18, // half-life ~6s — bright but brief
+ patience: 0.035, // half-life ~20s — sustained waiting state
+ curiosity: 0.12, // half-life ~8s — alert, engaged
+ empathy: 0.055, // half-life ~13s — slow to fade, like real empathy
+};
+
+// Vocabulary scored for emotional valence
+// Keys map to emotion buckets; values are keyword lists
+const VOCAB = {
+ concern: ['error', 'failed', 'fail', 'invalid', 'missing', 'broken', 'issue',
+ 'warning', 'problem', 'wrong', 'crash', 'undefined', 'null', 'corrupt'],
+ celebration: ['success', 'complete', 'valid', 'clean', 'done', 'great', 'loaded',
+ 'ready', 'perfect', 'excellent', 'nice', 'good', 'worked', 'saved'],
+ patience: ['analyzing', 'checking', 'loading', 'processing', 'thinking',
+ 'please wait', 'just a moment', 'scanning', 'computing', 'fetching'],
+ curiosity: ['interesting', 'wonder', 'what if', 'explore', 'curious', 'new',
+ 'never seen', 'unusual', 'rare', 'unique', 'unexpected'],
+ empathy: ['sorry', 'understand', 'difficult', 'frustrating', 'try again',
+ 'my mistake', 'apologies', 'hard', 'oops', 'unfortunately'],
+};
+
+export class AgentAvatar {
+ /**
+ * @param {import('./viewer.js').Viewer} viewer
+ * @param {import('./agent-protocol.js').AgentProtocol} protocol
+ * @param {import('./agent-identity.js').AgentIdentity} identity
+ */
+ constructor(viewer, protocol, identity) {
+ this.viewer = viewer;
+ this.protocol = protocol;
+ this.identity = identity;
+
+ // Emotional state — continuous weighted blend, updated every frame
+ this._emotion = {
+ neutral: 1.0,
+ concern: 0.0,
+ celebration: 0.0,
+ patience: 0.0,
+ curiosity: 0.0,
+ empathy: 0.0,
+ };
+
+ // Head look-at state
+ this._lookTarget = null; // Vector3 | null
+ this._currentTilt = 0; // radians
+ this._targetTilt = 0; // radians
+ this._currentLean = 0; // slight forward lean
+ this._targetLean = 0;
+
+ // One-shot gesture tracking
+ this._oneShotAction = null;
+ this._oneShotDuration = 0;
+ this._oneShotTimer = 0;
+ this._isPlayingOneShot = false;
+
+ // Streak tracking for empathy injection
+ this._errorStreak = 0;
+ this._firstEncounter = true;
+
+ // Morph target current values (lerped each frame)
+ this._morphCurrent = {};
+ this._morphTarget = {};
+
+ // Listeners stored so we can detach later
+ this._listeners = [];
+
+ this._tickBound = this._tickEmotion.bind(this);
+ }
+
+ // ── Lifecycle ─────────────────────────────────────────────────────────────
+
+ /** Call after viewer.setContent() loads the avatar model */
+ attach() {
+ // Hook into the viewer's per-frame loop
+ if (!this.viewer._afterAnimateHooks) this.viewer._afterAnimateHooks = [];
+ this.viewer._afterAnimateHooks.push(this._tickBound);
+
+ // Subscribe to protocol events
+ this._sub(ACTION_TYPES.SPEAK, this._onSpeak.bind(this));
+ this._sub(ACTION_TYPES.GESTURE, this._onGesture.bind(this));
+ this._sub(ACTION_TYPES.EMOTE, this._onEmote.bind(this));
+ this._sub(ACTION_TYPES.LOOK_AT, this._onLookAt.bind(this));
+ this._sub(ACTION_TYPES.PERFORM_SKILL, this._onSkillStart.bind(this));
+ this._sub(ACTION_TYPES.SKILL_DONE, this._onSkillDone.bind(this));
+ this._sub(ACTION_TYPES.SKILL_ERROR, this._onSkillError.bind(this));
+ this._sub(ACTION_TYPES.LOAD_START, this._onLoadStart.bind(this));
+ this._sub(ACTION_TYPES.LOAD_END, this._onLoadEnd.bind(this));
+ this._sub(ACTION_TYPES.VALIDATE, this._onValidate.bind(this));
+
+ // First-encounter curiosity burst
+ if (this._firstEncounter) {
+ this._firstEncounter = false;
+ setTimeout(() => {
+ this._injectStimulus('curiosity', 0.9);
+ this._injectStimulus('celebration', 0.4);
+ }, 600);
+ }
+ }
+
+ /** Remove all hooks and listeners */
+ detach() {
+ if (this.viewer._afterAnimateHooks) {
+ const idx = this.viewer._afterAnimateHooks.indexOf(this._tickBound);
+ if (idx !== -1) this.viewer._afterAnimateHooks.splice(idx, 1);
+ }
+ for (const [type, handler] of this._listeners) {
+ this.protocol.off(type, handler);
+ }
+ this._listeners = [];
+ }
+
+ // ── Public API ────────────────────────────────────────────────────────────
+
+ /** Play a named gesture animation */
+ playGesture(name) {
+ this._triggerOneShot(name);
+ }
+
+ /** Set a world-space point for the avatar to look toward */
+ setLookTarget(worldPos) {
+ this._lookTarget = worldPos ? worldPos.clone() : null;
+ }
+
+ /** Get current emotion blend (read-only snapshot) */
+ get emotionState() {
+ return { ...this._emotion };
+ }
+
+ // ── Protocol Handlers ─────────────────────────────────────────────────────
+
+ _onSpeak(action) {
+ const text = action.payload?.text || '';
+ const { valence, arousal } = this._analyzeSentiment(text);
+
+ // Positive speech → celebration boost; negative → concern
+ if (valence > 0.3) this._injectStimulus('celebration', valence * 0.7);
+ else if (valence < -0.2) this._injectStimulus('concern', Math.abs(valence) * 0.8);
+
+ // High-arousal text (questions, exclamations) → curiosity
+ if (arousal > 0.5) this._injectStimulus('curiosity', arousal * 0.5);
+
+ // Trigger mouth/talk animation hint
+ const duration = Math.max(1.5, text.split(' ').length * 0.3);
+ this._triggerOneShot('talk', duration);
+ }
+
+ _onGesture(action) {
+ const name = action.payload?.name || 'nod';
+ this._triggerOneShot(name, action.payload?.duration || 1.5);
+ }
+
+ _onEmote(action) {
+ const trigger = action.payload?.trigger;
+ const weight = action.payload?.weight || 0.7;
+ if (trigger && this._emotion.hasOwnProperty(trigger)) {
+ this._injectStimulus(trigger, weight);
+ }
+ }
+
+ _onLookAt(action) {
+ const target = action.payload?.target;
+ if (target === 'model' && this.viewer?.content) {
+ // Look at the bounding box center of the loaded model
+ const box = new (await import('three').then(m => m.Box3))();
+ const center = new Vector3();
+ box.setFromObject(this.viewer.content).getCenter(center);
+ this._lookTarget = center;
+ } else if (target === 'user') {
+ this._lookTarget = null; // look at camera
+ }
+ this._injectStimulus('curiosity', 0.3);
+ }
+
+ _onSkillStart(action) {
+ const hint = action.payload?.animationHint;
+ if (hint) this._triggerOneShot(hint, 1.0);
+ this._injectStimulus('patience', 0.4);
+ }
+
+ _onSkillDone(action) {
+ const result = action.payload?.result;
+ if (result?.sentiment !== undefined) {
+ if (result.sentiment > 0.3) this._injectStimulus('celebration', result.sentiment * 0.8);
+ else if (result.sentiment < -0.2) this._injectStimulus('concern', Math.abs(result.sentiment) * 0.7);
+ } else {
+ this._injectStimulus('celebration', 0.4);
+ }
+ this._errorStreak = 0;
+ }
+
+ _onSkillError(_action) {
+ this._errorStreak++;
+ const empathyWeight = Math.min(this._errorStreak * 0.25, 0.9);
+ this._injectStimulus('concern', 0.7);
+ this._injectStimulus('empathy', empathyWeight);
+ }
+
+ _onLoadStart(_action) {
+ this._injectStimulus('patience', 0.6);
+ this._injectStimulus('curiosity', 0.3);
+ this._triggerOneShot('think', 2.0);
+ }
+
+ _onLoadEnd(action) {
+ if (action.payload?.error) {
+ this._injectStimulus('concern', 0.8);
+ } else {
+ this._injectStimulus('celebration', 0.7);
+ this._injectStimulus('curiosity', 0.5);
+ this._triggerOneShot('nod', 1.0);
+ }
+ }
+
+ _onValidate(action) {
+ const errors = action.payload?.errors || 0;
+ const warnings = action.payload?.warnings || 0;
+ if (errors > 0) {
+ this._injectStimulus('concern', Math.min(0.4 + errors * 0.1, 0.95));
+ this._errorStreak++;
+ } else if (warnings > 0) {
+ this._injectStimulus('concern', 0.3);
+ } else {
+ this._injectStimulus('celebration', 0.85);
+ this._triggerOneShot('celebrate', 1.5);
+ }
+ }
+
+ // ── Empathy Layer — The Novel Part ────────────────────────────────────────
+
+ /**
+ * Inject a stimulus into the emotion state.
+ * Uses additive blending — stimuli accumulate, then decay.
+ * @param {string} emotion — one of the DECAY keys
+ * @param {number} weight — 0..1
+ */
+ _injectStimulus(emotion, weight) {
+ if (!(emotion in this._emotion)) return;
+ this._emotion[emotion] = Math.min(1.0, this._emotion[emotion] + weight);
+ // Neutral inversely reflects total arousal
+ this._normaliseNeutral();
+ }
+
+ _normaliseNeutral() {
+ const sum = Object.keys(DECAY).reduce((acc, k) => acc + this._emotion[k], 0);
+ this._emotion.neutral = Math.max(0, 1 - sum);
+ }
+
+ /**
+ * Per-frame emotion decay + avatar rendering.
+ * Called by viewer._afterAnimateHooks every animation frame.
+ * @param {number} dt — delta time in seconds
+ */
+ _tickEmotion(dt) {
+ // Stage 1: Decay all non-neutral emotions
+ for (const [key, rate] of Object.entries(DECAY)) {
+ this._emotion[key] = Math.max(0, this._emotion[key] - rate * dt);
+ }
+ this._normaliseNeutral();
+
+ // Stage 2: One-shot gesture timer
+ if (this._isPlayingOneShot) {
+ this._oneShotTimer += dt;
+ if (this._oneShotTimer >= this._oneShotDuration) {
+ this._isPlayingOneShot = false;
+ this._oneShotTimer = 0;
+ }
+ }
+
+ // Stage 3: Apply emotion to avatar
+ this._applyEmotionToAvatar(dt);
+ }
+
+ /**
+ * Render the current emotional state onto the avatar mesh.
+ * Gracefully no-ops if morph targets or head bone don't exist.
+ */
+ _applyEmotionToAvatar(dt) {
+ const w = this._emotion;
+
+ // ── Morph target targets ──────────────────────────────────────────
+ // The Empathy Layer blends ALL emotions simultaneously —
+ // not a discrete switch, a continuous weighted blend.
+ this._setMorphTarget('mouthSmile', w.celebration * 0.85);
+ this._setMorphTarget('mouthOpen', w.celebration * 0.2 + (this._isPlayingOneShot && this._oneShotAction === 'talk' ? 0.4 : 0));
+ this._setMorphTarget('mouthFrown', w.concern * 0.55);
+ this._setMorphTarget('browInnerUp', (w.concern + w.empathy * 0.5) * 0.6);
+ this._setMorphTarget('browOuterUpLeft', w.curiosity * 0.7);
+ this._setMorphTarget('browOuterUpRight',w.curiosity * 0.5);
+ this._setMorphTarget('eyeSquintLeft', w.empathy * 0.4);
+ this._setMorphTarget('eyeSquintRight', w.empathy * 0.4);
+ this._setMorphTarget('eyesClosed', w.patience * 0.15); // slight, not full
+ this._setMorphTarget('cheekPuff', w.celebration * 0.2);
+ this._setMorphTarget('noseSneerLeft', w.concern * 0.15);
+ this._setMorphTarget('noseSneerRight', w.concern * 0.15);
+
+ // ── Lerp morph influences to targets ─────────────────────────────
+ const lerpSpeed = dt * 4.0; // smooth interpolation, not snapping
+ this._lerpMorphTargets(lerpSpeed);
+
+ // ── Head tilt (curiosity + empathy both tilt the head) ────────────
+ this._targetTilt = (w.curiosity * 12 + w.empathy * 9 + w.concern * 4) * DEG2RAD;
+ this._currentTilt = _lerp(this._currentTilt, this._targetTilt, dt * 3.0);
+
+ // ── Forward lean (curiosity leans in, patience leans back) ────────
+ this._targetLean = w.curiosity * 0.03 - w.patience * 0.02;
+ this._currentLean = _lerp(this._currentLean, this._targetLean, dt * 2.0);
+
+ this._applyHeadTransform();
+ }
+
+ // ── Morph Target Helpers ─────────────────────────────────────────────────
+
+ /**
+ * Set the *target* influence for a named morph target.
+ * Actual mesh influence is lerped in _lerpMorphTargets().
+ */
+ _setMorphTarget(name, targetWeight) {
+ this._morphTarget[name] = Math.max(0, Math.min(1, targetWeight));
+ if (!(name in this._morphCurrent)) this._morphCurrent[name] = 0;
+ }
+
+ /** Lerp all tracked morph target influences toward their targets */
+ _lerpMorphTargets(speed) {
+ if (!this.viewer?.content) return;
+
+ this.viewer.content.traverse(node => {
+ if (!node.isMesh || !node.morphTargetDictionary || !node.morphTargetInfluences) return;
+
+ for (const [name, target] of Object.entries(this._morphTarget)) {
+ const idx = node.morphTargetDictionary[name];
+ if (idx === undefined) continue;
+ const current = node.morphTargetInfluences[idx] || 0;
+ const next = _lerp(current, target, speed);
+ node.morphTargetInfluences[idx] = next;
+ this._morphCurrent[name] = next;
+ }
+ });
+ }
+
+ // ── Head Transform ────────────────────────────────────────────────────────
+
+ _applyHeadTransform() {
+ if (!this.viewer?.content) return;
+
+ // Find a head/neck bone or the root bone to tilt
+ this.viewer.content.traverse(node => {
+ if (!node.isBone) return;
+ const n = node.name.toLowerCase();
+ if (n.includes('head') || n.includes('neck')) {
+ // Apply tilt (Z rotation) and lean (X rotation)
+ node.rotation.z = _lerp(node.rotation.z, this._currentTilt, 0.1);
+ node.rotation.x = _lerp(node.rotation.x, this._currentLean, 0.1);
+ }
+ });
+ }
+
+ // ── Gesture / One-shot Animations ────────────────────────────────────────
+
+ /**
+ * Trigger a one-shot animation clip if it exists on the model.
+ * Falls back gracefully if the clip doesn't exist.
+ * @param {string} clipName
+ * @param {number} [duration]
+ */
+ _triggerOneShot(clipName, duration = 1.5) {
+ this._isPlayingOneShot = true;
+ this._oneShotAction = clipName;
+ this._oneShotDuration = duration;
+ this._oneShotTimer = 0;
+
+ if (!this.viewer?.mixer || !this.viewer?.clips?.length) return;
+
+ // Look for a clip matching the name (case-insensitive partial match)
+ const clip = this.viewer.clips.find(c =>
+ c.name.toLowerCase().includes(clipName.toLowerCase())
+ );
+ if (!clip) return;
+
+ const action = this.viewer.mixer.clipAction(clip);
+ action.reset();
+ action.setLoop(2200, 1); // THREE.LoopOnce = 2200
+ action.clampWhenFinished = true;
+ action.play();
+ }
+
+ // ── Sentiment Analysis ────────────────────────────────────────────────────
+
+ /**
+ * Lightweight keyword-based sentiment scoring — runs in browser with no external API.
+ * Returns { valence: -1..1, arousal: 0..1 }
+ */
+ _analyzeSentiment(text) {
+ const lower = text.toLowerCase();
+ const words = lower.split(/\s+/);
+ const total = Math.max(words.length, 1);
+
+ let valence = 0;
+ let arousal = 0;
+
+ // Score each emotion bucket
+ for (const [emotion, keywords] of Object.entries(VOCAB)) {
+ let hits = 0;
+ for (const kw of keywords) {
+ if (lower.includes(kw)) hits++;
+ }
+ if (!hits) continue;
+ const score = Math.min(hits / total * 3.0, 1.0);
+
+ if (emotion === 'celebration') valence += score * 0.8;
+ if (emotion === 'concern') valence -= score * 0.7;
+ if (emotion === 'empathy') valence -= score * 0.3; // empathy feels slightly negative (recognition of pain)
+ if (emotion === 'curiosity') arousal += score * 0.9;
+ if (emotion === 'patience') arousal += score * 0.3;
+ }
+
+ // Punctuation arousal (exclamation = high arousal, question = moderate)
+ const exclamations = (text.match(/!/g) || []).length;
+ const questions = (text.match(/\?/g) || []).length;
+ arousal += Math.min(exclamations * 0.2 + questions * 0.1, 0.5);
+
+ return {
+ valence: Math.max(-1, Math.min(1, valence)),
+ arousal: Math.max(0, Math.min(1, arousal)),
+ };
+ }
+
+ // ── Utility ───────────────────────────────────────────────────────────────
+
+ _sub(type, handler) {
+ this.protocol.on(type, handler);
+ this._listeners.push([type, handler]);
+ }
+
+ _selectDominantEmotion() {
+ let max = 0, dominant = 'neutral';
+ for (const [key, val] of Object.entries(this._emotion)) {
+ if (val > max) { max = val; dominant = key; }
+ }
+ return dominant;
+ }
+}
+
+function _lerp(a, b, t) {
+ return a + (b - a) * Math.min(1, Math.max(0, t));
+}
diff --git a/src/agent-home.js b/src/agent-home.js
new file mode 100644
index 000000000..b69680190
--- /dev/null
+++ b/src/agent-home.js
@@ -0,0 +1,283 @@
+/**
+ * Agent Home — Presence Component
+ * ---------------------------------
+ * The agent's home page. Not a dashboard. Not a settings panel.
+ * A *place* — somewhere you can go to see the agent, its history, its skills.
+ *
+ * Every agent deserves an address. This renders it.
+ * Embeddable anywhere: main page identity card, /agent/:id home page.
+ */
+
+import { ACTION_TYPES } from './agent-protocol.js';
+import { MEMORY_TYPES } from './agent-memory.js';
+
+const ACTION_ICONS = {
+ [ACTION_TYPES.SPEAK]: '💬',
+ [ACTION_TYPES.REMEMBER]: '🧠',
+ [ACTION_TYPES.SIGN]: '✍️',
+ [ACTION_TYPES.PERFORM_SKILL]: '⚡',
+ [ACTION_TYPES.SKILL_DONE]: '✓',
+ [ACTION_TYPES.SKILL_ERROR]: '⚠',
+ [ACTION_TYPES.LOAD_END]: '📦',
+ [ACTION_TYPES.VALIDATE]: '🔍',
+ default: '·',
+};
+
+const EMOTION_LABELS = {
+ neutral: 'calm',
+ concern: 'focused',
+ celebration: 'excited',
+ patience: 'patient',
+ curiosity: 'curious',
+ empathy: 'empathetic',
+};
+
+export class AgentHome {
+ /**
+ * @param {HTMLElement} containerEl
+ * @param {import('./agent-identity.js').AgentIdentity} identity
+ * @param {import('./agent-protocol.js').AgentProtocol} protocol
+ * @param {import('./agent-avatar.js').AgentAvatar} [avatar]
+ */
+ constructor(containerEl, identity, protocol, avatar = null) {
+ this.container = containerEl;
+ this.identity = identity;
+ this.protocol = protocol;
+ this.avatar = avatar;
+
+ this._panel = null;
+ this._timeline = [];
+ this._maxTimeline = 30;
+ this._emotionInterval = null;
+ }
+
+ // ── Lifecycle ─────────────────────────────────────────────────────────────
+
+ async render() {
+ await this._ensureIdentityLoaded();
+ this._buildPanel();
+ this._subscribeProtocol();
+ this._startEmotionPoll();
+ }
+
+ destroy() {
+ if (this._panel) this._panel.remove();
+ clearInterval(this._emotionInterval);
+ this.protocol.off('*', this._onAnyAction);
+ }
+
+ // ── Identity Card ─────────────────────────────────────────────────────────
+
+ _buildPanel() {
+ const id = this.identity;
+ const panel = document.createElement('div');
+ panel.className = 'agent-home-panel';
+ panel.innerHTML = `
+ <div class="agent-home-identity">
+ <div class="agent-home-avatar-ring" id="agent-avatar-ring">
+ <div class="agent-home-avatar-inner" id="agent-avatar-inner">
+ <span class="agent-home-avatar-emoji" id="agent-avatar-emoji">◎</span>
+ </div>
+ </div>
+ <div class="agent-home-info">
+ <div class="agent-home-name" id="agent-home-name">${_esc(id.name)}</div>
+ <div class="agent-home-status" id="agent-home-status">
+ <span class="agent-home-dot online"></span>
+ <span id="agent-home-emotion-label">present</span>
+ </div>
+ <div class="agent-home-address" id="agent-home-address">
+ ${id.walletAddress ? _shortAddr(id.walletAddress) : 'no wallet linked'}
+ </div>
+ </div>
+ <div class="agent-home-actions">
+ <button class="agent-home-btn" id="agent-copy-link" title="Copy agent link">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>
+ </button>
+ ${id.isRegistered ? `
+ <span class="agent-home-badge erc8004" title="Registered on-chain (ERC-8004)">
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>
+ on-chain
+ </span>` : ''}
+ </div>
+ </div>
+
+ <div class="agent-home-skills-strip" id="agent-skills-strip">
+ ${(id.skills || []).map(s => `<span class="agent-skill-chip">${_esc(s)}</span>`).join('')}
+ </div>
+
+ <div class="agent-home-memory-bar" id="agent-memory-bar">
+ ${this._renderMemoryBar()}
+ </div>
+
+ <div class="agent-home-timeline" id="agent-timeline">
+ <div class="agent-timeline-empty">Actions will appear here as the agent works.</div>
+ </div>
+ `;
+
+ this.container.appendChild(panel);
+ this._panel = panel;
+
+ // Copy link button
+ panel.querySelector('#agent-copy-link')?.addEventListener('click', () => {
+ const url = `${location.origin}${id.homeUrl || `/agent/${id.id}`}`;
+ navigator.clipboard?.writeText(url).catch(() => {});
+ this._flashBtn(panel.querySelector('#agent-copy-link'), 'copied');
+ });
+ }
+
+ // ── Memory Bar ────────────────────────────────────────────────────────────
+
+ _renderMemoryBar() {
+ if (!this.identity.memory) return '';
+ const stats = this.identity.memory.stats;
+ if (!stats.total) return '<span class="agent-mem-empty">no memories yet</span>';
+
+ return Object.entries(stats)
+ .filter(([k]) => k !== 'total')
+ .filter(([, v]) => v > 0)
+ .map(([type, count]) => `
+ <span class="agent-mem-chip" data-type="${type}" title="${count} ${type} ${count === 1 ? 'memory' : 'memories'}">
+ ${_memIcon(type)} ${count}
+ </span>
+ `).join('') + `<span class="agent-mem-total">${stats.total}</span>`;
+ }
+
+ _refreshMemoryBar() {
+ const bar = this._panel?.querySelector('#agent-memory-bar');
+ if (bar) bar.innerHTML = this._renderMemoryBar();
+ }
+
+ // ── Action Timeline ───────────────────────────────────────────────────────
+
+ _subscribeProtocol() {
+ this._onAnyAction = (action) => {
+ // Only show meaningful actions (skip internal think/presence churn)
+ if ([ACTION_TYPES.THINK, ACTION_TYPES.PRESENCE].includes(action.type)) return;
+ this._pushTimeline(action);
+ };
+ this.protocol.on('*', this._onAnyAction);
+ }
+
+ _pushTimeline(action) {
+ this._timeline.unshift(action);
+ if (this._timeline.length > this._maxTimeline) this._timeline.pop();
+
+ const timelineEl = this._panel?.querySelector('#agent-timeline');
+ if (!timelineEl) return;
+
+ const emptyEl = timelineEl.querySelector('.agent-timeline-empty');
+ if (emptyEl) emptyEl.remove();
+
+ const item = document.createElement('div');
+ item.className = 'agent-timeline-item';
+ item.innerHTML = `
+ <span class="agent-timeline-icon">${ACTION_ICONS[action.type] || ACTION_ICONS.default}</span>
+ <span class="agent-timeline-text">${_timelineText(action)}</span>
+ <span class="agent-timeline-time">${_relTime(action.timestamp)}</span>
+ `;
+ item.style.animation = 'agent-timeline-in 0.25s ease';
+
+ timelineEl.insertBefore(item, timelineEl.firstChild);
+
+ // Keep DOM clean
+ while (timelineEl.children.length > this._maxTimeline) {
+ timelineEl.removeChild(timelineEl.lastChild);
+ }
+
+ // Refresh memory bar if it was a remember action
+ if (action.type === ACTION_TYPES.REMEMBER) {
+ this._refreshMemoryBar();
+ }
+ }
+
+ // ── Emotion Presence ──────────────────────────────────────────────────────
+
+ _startEmotionPoll() {
+ // Update the emotion label in the status bar every second
+ this._emotionInterval = setInterval(() => {
+ if (!this.avatar) return;
+ const state = this.avatar.emotionState;
+ const dominant = Object.entries(state).reduce((a, b) => b[1] > a[1] ? b : a, ['neutral', 0]);
+ const label = EMOTION_LABELS[dominant[0]] || 'present';
+
+ const el = this._panel?.querySelector('#agent-home-emotion-label');
+ if (el && el.textContent !== label) {
+ el.style.opacity = '0';
+ setTimeout(() => {
+ el.textContent = label;
+ el.style.opacity = '1';
+ }, 150);
+ }
+
+ // Pulse the avatar ring colour based on dominant emotion
+ const ring = this._panel?.querySelector('#agent-avatar-ring');
+ if (ring) {
+ ring.dataset.emotion = dominant[0];
+ }
+ }, 1000);
+ }
+
+ // ── Helpers ───────────────────────────────────────────────────────────────
+
+ async _ensureIdentityLoaded() {
+ if (!this.identity.isLoaded) {
+ await this.identity.load();
+ }
+ }
+
+ _flashBtn(btn, text) {
+ if (!btn) return;
+ const orig = btn.innerHTML;
+ btn.textContent = text;
+ setTimeout(() => { btn.innerHTML = orig; }, 1500);
+ }
+}
+
+// ── Rendering Helpers ─────────────────────────────────────────────────────────
+
+function _esc(str) {
+ return String(str || '').replace(/[<>&"]/g, c =>
+ ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c])
+ );
+}
+
+function _shortAddr(addr) {
+ if (!addr) return '';
+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;
+}
+
+function _memIcon(type) {
+ return { user: '👤', feedback: '↩', project: '📋', reference: '🔗' }[type] || '·';
+}
+
+function _relTime(ts) {
+ const diff = Date.now() - ts;
+ if (diff < 60_000) return 'just now';
+ if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
+ if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
+ return new Date(ts).toLocaleDateString();
+}
+
+function _timelineText(action) {
+ const p = action.payload || {};
+ switch (action.type) {
+ case ACTION_TYPES.SPEAK:
+ return _esc((p.text || '').slice(0, 80) + ((p.text?.length > 80) ? '…' : ''));
+ case ACTION_TYPES.REMEMBER:
+ return _esc(`Remembered: ${(p.content || '').slice(0, 60)}`);
+ case ACTION_TYPES.PERFORM_SKILL:
+ return _esc(`Performing skill: ${p.skill || '?'}`);
+ case ACTION_TYPES.SKILL_DONE:
+ return _esc(`${p.skill || 'Skill'} complete`);
+ case ACTION_TYPES.SKILL_ERROR:
+ return _esc(`${p.skill || 'Skill'} failed: ${(p.error || '').slice(0, 50)}`);
+ case ACTION_TYPES.SIGN:
+ return _esc(`Signed: ${(p.message || '').slice(0, 50)}`);
+ case ACTION_TYPES.LOAD_END:
+ return p.error ? _esc(`Load failed: ${p.error}`) : 'Model loaded';
+ case ACTION_TYPES.VALIDATE:
+ return _esc(`Validation: ${p.errors || 0} errors, ${p.warnings || 0} warnings`);
+ default:
+ return _esc(action.type.replace(/-/g, ' '));
+ }
+}
diff --git a/src/agent-identity.js b/src/agent-identity.js
new file mode 100644
index 000000000..7872b0793
--- /dev/null
+++ b/src/agent-identity.js
@@ -0,0 +1,296 @@
+/**
+ * Agent Identity
+ * --------------
+ * Every agent deserves a body, a place, a name, and a history.
+ * This module is that. It persists to localStorage + backend,
+ * links to an ERC-8004 on-chain presence, and maintains a signed
+ * action log — the agent's provenance trail.
+ *
+ * Think of it as the agent's passport + diary.
+ */
+
+import { AgentMemory } from './agent-memory.js';
+
+const STORAGE_KEY = 'agent_identity';
+
+/**
+ * @typedef {Object} AgentRecord
+ * @property {string} id
+ * @property {string} name
+ * @property {string} [description]
+ * @property {string} [avatarId] — R2 avatar UUID
+ * @property {string} [homeUrl] — /agent/:id
+ * @property {string} [walletAddress]
+ * @property {number} [chainId]
+ * @property {string[]} skills — enabled skill names
+ * @property {Object} meta
+ * @property {number} createdAt
+ * @property {boolean} isRegistered — ERC-8004 on-chain
+ */
+
+export class AgentIdentity {
+ /**
+ * @param {{ userId?: string, agentId?: string, autoLoad?: boolean }} [opts]
+ */
+ constructor({ userId = null, agentId = null, autoLoad = true } = {}) {
+ this.userId = userId;
+ this._record = null;
+ this._loaded = false;
+ this.memory = null;
+
+ // Pre-seed agentId from arg or storage so callers can use it synchronously
+ this._agentId = agentId || this._readStoredId();
+
+ if (autoLoad) this._loadAsync();
+ }
+
+ // ── Public getters ────────────────────────────────────────────────────────
+
+ get id() { return this._record?.id || this._agentId; }
+ get name() { return this._record?.name || 'Agent'; }
+ get description() { return this._record?.description || ''; }
+ get avatarId() { return this._record?.avatarId || null; }
+ get homeUrl() { return this._record?.homeUrl || (this.id ? `/agent/${this.id}` : null); }
+ get walletAddress() { return this._record?.walletAddress || null; }
+ get chainId() { return this._record?.chainId || null; }
+ get skills() { return this._record?.skills || []; }
+ get meta() { return this._record?.meta || {}; }
+ get isLoaded() { return this._loaded; }
+ get isRegistered() { return Boolean(this._record?.isRegistered); }
+
+ // ── Load + Save ───────────────────────────────────────────────────────────
+
+ async load() {
+ await this._loadAsync();
+ }
+
+ async save() {
+ if (!this._record) return;
+ this._persist();
+ try {
+ const resp = await fetch(`/api/agents/${this._record.id}`, {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ name: this._record.name,
+ description: this._record.description,
+ avatar_id: this._record.avatarId,
+ skills: this._record.skills,
+ meta: this._record.meta,
+ }),
+ });
+ if (resp.ok) {
+ const { agent } = await resp.json();
+ this._record = _normalise(agent);
+ this._persist();
+ }
+ } catch { /* localStorage is authoritative */ }
+ }
+
+ /**
+ * Update identity fields locally and push to backend.
+ * @param {Partial<AgentRecord>} patch
+ */
+ async update(patch) {
+ if (!this._record) await this._loadAsync();
+ Object.assign(this._record, patch);
+ await this.save();
+ }
+
+ // ── Wallet ────────────────────────────────────────────────────────────────
+
+ async linkWallet(address, chainId) {
+ await this.update({ walletAddress: address, chainId });
+ try {
+ await fetch(`/api/agents/${this.id}/wallet`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ wallet_address: address, chain_id: chainId }),
+ });
+ } catch {}
+ }
+
+ async unlinkWallet() {
+ await this.update({ walletAddress: null, chainId: null });
+ try {
+ await fetch(`/api/agents/${this.id}/wallet`, {
+ method: 'DELETE',
+ credentials: 'include',
+ });
+ } catch {}
+ }
+
+ // ── Action History ────────────────────────────────────────────────────────
+
+ /**
+ * Append an action to the agent's signed history.
+ * Fire-and-forget — never blocks the caller.
+ * @param {import('./agent-protocol.js').ActionPayload} action
+ */
+ recordAction(action) {
+ fetch('/api/agent-actions', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ agent_id: this.id,
+ type: action.type,
+ payload: action.payload,
+ source_skill: action.sourceSkill || null,
+ }),
+ }).catch(() => {}); // non-critical
+ }
+
+ /**
+ * Fetch recent actions from backend.
+ * @param {{ limit?: number, cursor?: string }} [opts]
+ * @returns {Promise<Object[]>}
+ */
+ async getActionHistory({ limit = 50, cursor } = {}) {
+ try {
+ const params = new URLSearchParams({ agent_id: this.id, limit: String(limit) });
+ if (cursor) params.set('cursor', cursor);
+ const resp = await fetch(`/api/agent-actions?${params}`, { credentials: 'include' });
+ if (!resp.ok) return [];
+ const { actions } = await resp.json();
+ return actions || [];
+ } catch {
+ return [];
+ }
+ }
+
+ // ── ERC-8004 Registration ────────────────────────────────────────────────
+
+ /**
+ * Register this agent on-chain via the ERC-8004 registry.
+ * @param {File} glbFile
+ * @param {string} apiToken
+ */
+ async register(glbFile, apiToken) {
+ const { registerAgent } = await import('./erc8004/agent-registry.js');
+ const result = await registerAgent(glbFile, apiToken);
+ await this.update({ isRegistered: true, meta: { ...this.meta, erc8004: result } });
+ return result;
+ }
+
+ // ── Internal ──────────────────────────────────────────────────────────────
+
+ async _loadAsync() {
+ // 1. Try localStorage first (instant)
+ const local = this._readLocal();
+ if (local) {
+ this._record = local;
+ this._agentId = local.id;
+ this._loaded = true;
+ this.memory = new AgentMemory(local.id, { backendSync: true });
+ }
+
+ // 2. Try backend (authoritative if user is signed in)
+ try {
+ const agentId = this._agentId;
+ const url = agentId ? `/api/agents/${agentId}` : '/api/agents/me';
+ const resp = await fetch(url, { credentials: 'include' });
+
+ if (resp.ok) {
+ const { agent } = await resp.json();
+ this._record = _normalise(agent);
+ this._agentId = this._record.id;
+ this._loaded = true;
+ this._persist();
+ if (!this.memory) {
+ this.memory = new AgentMemory(this._record.id, { backendSync: true });
+ }
+ return;
+ }
+
+ if (resp.status === 404 || resp.status === 401) {
+ // Not signed in or no agent yet — create a local-only identity
+ if (!this._record) {
+ this._record = _makeDefault(this._agentId);
+ this._agentId = this._record.id;
+ this._loaded = true;
+ this._persist();
+ this.memory = new AgentMemory(this._agentId, { backendSync: false });
+ }
+ }
+ } catch {
+ // Offline — use local record if we have one
+ if (!this._record) {
+ this._record = _makeDefault(this._agentId);
+ this._agentId = this._record.id;
+ this._loaded = true;
+ this._persist();
+ this.memory = new AgentMemory(this._agentId, { backendSync: false });
+ }
+ }
+ }
+
+ _readStoredId() {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (raw) return JSON.parse(raw).id || null;
+ } catch {}
+ return null;
+ }
+
+ _readLocal() {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch {
+ return null;
+ }
+ }
+
+ _persist() {
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(this._record));
+ } catch {}
+ }
+}
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+function _uuid() {
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) 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);
+ });
+}
+
+function _makeDefault(existingId) {
+ return {
+ id: existingId || _uuid(),
+ name: 'Agent',
+ description: 'A 3D AI agent',
+ avatarId: null,
+ homeUrl: null,
+ walletAddress: null,
+ chainId: null,
+ skills: ['greet', 'present-model', 'validate-model', 'remember', 'think'],
+ meta: {},
+ createdAt: Date.now(),
+ isRegistered: false,
+ };
+}
+
+function _normalise(apiRecord) {
+ return {
+ id: apiRecord.id,
+ name: apiRecord.name || 'Agent',
+ description: apiRecord.description || '',
+ avatarId: apiRecord.avatar_id || apiRecord.avatarId || null,
+ homeUrl: apiRecord.home_url || apiRecord.homeUrl || `/agent/${apiRecord.id}`,
+ walletAddress: apiRecord.wallet_address || apiRecord.walletAddress || null,
+ chainId: apiRecord.chain_id || apiRecord.chainId || null,
+ skills: apiRecord.skills || [],
+ meta: apiRecord.meta || {},
+ createdAt: apiRecord.created_at
+ ? new Date(apiRecord.created_at).getTime()
+ : (apiRecord.createdAt || Date.now()),
+ isRegistered: Boolean(apiRecord.erc8004_agent_id || apiRecord.isRegistered),
+ };
+}
diff --git a/src/agent-memory.js b/src/agent-memory.js
new file mode 100644
index 000000000..6f2ad11b4
--- /dev/null
+++ b/src/agent-memory.js
@@ -0,0 +1,256 @@
+/**
+ * Agent Memory System
+ * -------------------
+ * Same primitive types as Claude's MEMORY.md pattern — because agents are just JSON too.
+ * Stores to localStorage immediately, syncs to backend asynchronously.
+ *
+ * Memory types:
+ * user — who the user is, preferences, expertise
+ * feedback — corrections and confirmations that shape future behaviour
+ * project — ongoing work context, goals, deadlines
+ * reference — pointers to external resources
+ */
+
+export const MEMORY_TYPES = {
+ USER: 'user',
+ FEEDBACK: 'feedback',
+ PROJECT: 'project',
+ REFERENCE: 'reference',
+};
+
+/**
+ * @typedef {Object} MemoryEntry
+ * @property {string} id
+ * @property {string} type — MEMORY_TYPES.*
+ * @property {string} content — the actual memory text
+ * @property {string[]} tags
+ * @property {Object} [context] — freeform metadata
+ * @property {number} salience — 0-1, how important/recent this memory is
+ * @property {number} createdAt — timestamp
+ * @property {number} [expiresAt]
+ */
+
+export class AgentMemory {
+ /**
+ * @param {string} agentId
+ * @param {{ backendSync?: boolean }} [opts]
+ */
+ constructor(agentId, { backendSync = false } = {}) {
+ this.agentId = agentId;
+ this.backendSync = backendSync;
+ this._entries = [];
+ this._dirty = false;
+ this._syncTimer = null;
+
+ this._hydrate();
+ }
+
+ // ── CRUD ──────────────────────────────────────────────────────────────────
+
+ /**
+ * Store a new memory entry.
+ * @param {{ type: string, content: string, tags?: string[], context?: Object, expiresAt?: number }} entry
+ * @returns {string} new entry id
+ */
+ add(entry) {
+ const id = _uuid();
+ const now = Date.now();
+ const mem = {
+ id,
+ type: entry.type || MEMORY_TYPES.PROJECT,
+ content: String(entry.content).trim(),
+ tags: Array.isArray(entry.tags) ? entry.tags : [],
+ context: entry.context || {},
+ salience: _computeSalience(entry, now),
+ createdAt: now,
+ expiresAt: entry.expiresAt || null,
+ };
+ this._entries.push(mem);
+ this._scheduleSync(mem);
+ return id;
+ }
+
+ /**
+ * Query memory entries.
+ * @param {{ type?: string, tags?: string[], limit?: number, since?: number }} [opts]
+ * @returns {MemoryEntry[]}
+ */
+ query({ type, tags, limit = 50, since = 0 } = {}) {
+ const now = Date.now();
+ let results = this._entries.filter(m => {
+ if (m.expiresAt && m.expiresAt < now) return false;
+ if (m.createdAt < since) return false;
+ if (type && m.type !== type) return false;
+ if (tags && tags.length) {
+ const hasTags = tags.every(t => m.tags.includes(t));
+ if (!hasTags) return false;
+ }
+ return true;
+ });
+
+ // Sort by salience × recency — most relevant first
+ results.sort((a, b) => {
+ const scoreA = a.salience * _recencyBoost(a.createdAt, now);
+ const scoreB = b.salience * _recencyBoost(b.createdAt, now);
+ return scoreB - scoreA;
+ });
+
+ return results.slice(0, limit);
+ }
+
+ /**
+ * Remove a memory by id.
+ * @param {string} id
+ */
+ forget(id) {
+ const idx = this._entries.findIndex(m => m.id === id);
+ if (idx !== -1) {
+ this._entries.splice(idx, 1);
+ this._persist();
+ if (this.backendSync) this._syncForget(id);
+ }
+ }
+
+ /**
+ * Remove all memories of a given type (or all if type omitted).
+ * @param {string} [type]
+ */
+ clear(type) {
+ if (type) {
+ this._entries = this._entries.filter(m => m.type !== type);
+ } else {
+ this._entries = [];
+ }
+ this._persist();
+ }
+
+ /** Most recent N entries regardless of type */
+ get recentEntries() {
+ return this._entries.slice(-20).reverse();
+ }
+
+ /** Count by type */
+ get stats() {
+ const s = {};
+ for (const t of Object.values(MEMORY_TYPES)) {
+ s[t] = this._entries.filter(m => m.type === t).length;
+ }
+ s.total = this._entries.length;
+ return s;
+ }
+
+ // ── Persistence ──────────────────────────────────────────────────────────
+
+ _storageKey() {
+ return `agent_memory_${this.agentId}`;
+ }
+
+ _hydrate() {
+ try {
+ const raw = localStorage.getItem(this._storageKey());
+ if (raw) {
+ const parsed = JSON.parse(raw);
+ this._entries = Array.isArray(parsed) ? parsed : [];
+ }
+ } catch {
+ this._entries = [];
+ }
+
+ // Backend sync — merge newer entries from server
+ if (this.backendSync) this._syncFromBackend();
+ }
+
+ _persist() {
+ try {
+ localStorage.setItem(this._storageKey(), JSON.stringify(this._entries));
+ } catch {
+ // localStorage quota exceeded — prune oldest low-salience entries
+ this._prune();
+ try { localStorage.setItem(this._storageKey(), JSON.stringify(this._entries)); } catch {}
+ }
+ }
+
+ _prune() {
+ // Remove expired, then lowest salience until we're under 150 entries
+ const now = Date.now();
+ this._entries = this._entries.filter(m => !m.expiresAt || m.expiresAt > now);
+ if (this._entries.length > 150) {
+ this._entries.sort((a, b) => b.salience - a.salience);
+ this._entries = this._entries.slice(0, 150);
+ }
+ }
+
+ _scheduleSync(entry) {
+ this._persist();
+ if (!this.backendSync) return;
+ clearTimeout(this._syncTimer);
+ this._syncTimer = setTimeout(() => this._syncToBackend(entry), 1500);
+ }
+
+ async _syncToBackend(entry) {
+ try {
+ await fetch(`/api/agent-memory`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ agentId: this.agentId, entry }),
+ });
+ } catch { /* non-critical — localStorage is authoritative */ }
+ }
+
+ async _syncForget(id) {
+ try {
+ await fetch(`/api/agent-memory/${id}`, {
+ method: 'DELETE',
+ credentials: 'include',
+ });
+ } catch {}
+ }
+
+ async _syncFromBackend() {
+ try {
+ const resp = await fetch(`/api/agent-memory?agentId=${this.agentId}`, {
+ credentials: 'include',
+ });
+ if (!resp.ok) return;
+ const { entries } = await resp.json();
+ if (!Array.isArray(entries)) return;
+
+ // Merge: backend entries that don't exist locally win
+ const localIds = new Set(this._entries.map(m => m.id));
+ const newEntries = entries.filter(m => !localIds.has(m.id));
+ if (newEntries.length) {
+ this._entries.push(...newEntries);
+ this._persist();
+ }
+ } catch {}
+ }
+}
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+function _uuid() {
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) 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);
+ });
+}
+
+function _computeSalience(entry, now) {
+ // Explicit importance flag overrides everything
+ if (entry.important) return 1.0;
+ // Feedback and user memories are inherently higher salience
+ const typeBonus = { feedback: 0.3, user: 0.2, project: 0.1, reference: 0.0 };
+ const base = 0.5 + (typeBonus[entry.type] || 0);
+ // Tag count slightly boosts salience (more tagged = more deliberate)
+ const tagBonus = Math.min((entry.tags?.length || 0) * 0.05, 0.2);
+ return Math.min(base + tagBonus, 1.0);
+}
+
+function _recencyBoost(createdAt, now) {
+ // Exponential decay with 7-day half-life
+ const ageMs = now - createdAt;
+ const halfLife = 7 * 24 * 60 * 60 * 1000;
+ return Math.exp(-0.693 * ageMs / halfLife);
+}
diff --git a/src/agent-protocol.js b/src/agent-protocol.js
new file mode 100644
index 000000000..7a8dbac91
--- /dev/null
+++ b/src/agent-protocol.js
@@ -0,0 +1,121 @@
+/**
+ * Agent Action Protocol
+ * ---------------------
+ * The zero-dependency event bus that every module speaks through.
+ * Every action emitted here is visible — agents are not invisible JSON.
+ *
+ * Actions flow: Skills → Protocol → Avatar (renders) + Identity (logs) + Memory (stores)
+ */
+
+export const ACTION_TYPES = {
+ SPEAK: 'speak', // agent says something (text + sentiment)
+ THINK: 'think', // agent is processing (internal monologue)
+ GESTURE: 'gesture', // named body gesture (point, wave, nod, shrug)
+ EMOTE: 'emote', // direct emotion injection (concern, celebrate…)
+ LOOK_AT: 'look-at', // agent looks at a world position or object
+ PERFORM_SKILL: 'perform-skill', // a skill is starting execution
+ SKILL_DONE: 'skill-done', // a skill finished (success + result payload)
+ SKILL_ERROR: 'skill-error', // a skill failed
+ REMEMBER: 'remember', // agent stored a memory
+ SIGN: 'sign', // agent signs an action with its wallet
+ LOAD_START: 'load-start', // model/asset loading started
+ LOAD_END: 'load-end', // model/asset loading finished
+ VALIDATE: 'validate', // validation result (errors, warnings, hints)
+ PRESENCE: 'presence', // agent came online / went idle
+};
+
+/**
+ * @typedef {Object} ActionPayload
+ * @property {string} type — one of ACTION_TYPES
+ * @property {Object} payload — action-specific data
+ * @property {number} timestamp — Date.now()
+ * @property {string} agentId — identity id of the emitting agent
+ * @property {string} [sourceSkill] — skill name if emitted by a skill
+ */
+
+class AgentProtocol extends EventTarget {
+ constructor() {
+ super();
+ this._history = [];
+ this._maxHistory = 200;
+ }
+
+ /**
+ * Emit a typed action to all listeners.
+ * @param {Omit<ActionPayload, 'timestamp'>} action
+ */
+ emit(action) {
+ const full = {
+ type: action.type,
+ payload: action.payload || {},
+ timestamp: Date.now(),
+ agentId: action.agentId || 'default',
+ sourceSkill: action.sourceSkill || null,
+ };
+
+ // Trim history
+ this._history.push(full);
+ if (this._history.length > this._maxHistory) {
+ this._history.shift();
+ }
+
+ this.dispatchEvent(new CustomEvent(full.type, { detail: full }));
+ // Also dispatch a wildcard so listeners can monitor all traffic
+ this.dispatchEvent(new CustomEvent('*', { detail: full }));
+ }
+
+ /**
+ * Subscribe to a specific action type (or '*' for all).
+ * @param {string} type
+ * @param {(action: ActionPayload) => void} handler
+ */
+ on(type, handler) {
+ this._wrap(type, handler, false);
+ }
+
+ /**
+ * Subscribe once.
+ * @param {string} type
+ * @param {(action: ActionPayload) => void} handler
+ */
+ once(type, handler) {
+ this._wrap(type, handler, true);
+ }
+
+ /**
+ * Unsubscribe. Must pass the same handler reference as used in on().
+ * @param {string} type
+ * @param {Function} handler
+ */
+ off(type, handler) {
+ if (handler.__protocolWrapped) {
+ this.removeEventListener(type, handler.__protocolWrapped);
+ } else {
+ this.removeEventListener(type, handler);
+ }
+ }
+
+ /** @returns {ActionPayload[]} Recent action history (newest last) */
+ get history() {
+ return this._history.slice();
+ }
+
+ /** Returns last N actions of a given type */
+ recent(type, n = 10) {
+ return this._history.filter(a => a.type === type).slice(-n);
+ }
+
+ _wrap(type, handler, once) {
+ const wrapped = (e) => handler(e.detail);
+ handler.__protocolWrapped = wrapped;
+ if (once) {
+ this.addEventListener(type, wrapped, { once: true });
+ } else {
+ this.addEventListener(type, wrapped);
+ }
+ }
+}
+
+// Singleton — import this everywhere
+export const protocol = new AgentProtocol();
+export default protocol;
diff --git a/src/agent-skills.js b/src/agent-skills.js
new file mode 100644
index 000000000..4a3bd0017
--- /dev/null
+++ b/src/agent-skills.js
@@ -0,0 +1,425 @@
+/**
+ * Agent Skills
+ * ------------
+ * Skills are the things an agent can DO — and crucially, the things you can SEE it doing.
+ * Each skill is: instruction + animation hint + voice template + handler.
+ *
+ * Same primitive shape as Claude's skill system (skill.md) — because agents are just JSON.
+ * What makes these different: when they execute, the avatar PERFORMS them.
+ *
+ * MCP-exposed skills are also available as tools via /api/mcp.
+ */
+
+import { ACTION_TYPES } from './agent-protocol.js';
+import { MEMORY_TYPES } from './agent-memory.js';
+
+/**
+ * @typedef {Object} SkillContext
+ * @property {import('./agent-protocol.js').AgentProtocol} protocol
+ * @property {import('./agent-memory.js').AgentMemory} memory
+ * @property {import('./agent-identity.js').AgentIdentity} identity
+ * @property {Object} [viewer] — Viewer instance if in browser
+ * @property {boolean} isBrowser
+ */
+
+/**
+ * @typedef {Object} SkillResult
+ * @property {boolean} success
+ * @property {string} output — text to speak / return
+ * @property {number} [sentiment] — -1..1
+ * @property {Object} [data] — structured result data
+ */
+
+/**
+ * @typedef {Object} SkillDef
+ * @property {string} name
+ * @property {string} description
+ * @property {string} instruction — human-readable behaviour spec
+ * @property {string} animationHint — gesture name hint for avatar
+ * @property {string} voicePattern — template with {{vars}}
+ * @property {boolean} mcpExposed — available via MCP tools/call
+ * @property {Object} [inputSchema] — JSON Schema for args
+ * @property {(args: Object, ctx: SkillContext) => Promise<SkillResult>} handler
+ */
+
+export class AgentSkills {
+ /**
+ * @param {import('./agent-protocol.js').AgentProtocol} protocol
+ * @param {import('./agent-memory.js').AgentMemory} memory
+ */
+ constructor(protocol, memory) {
+ this.protocol = protocol;
+ this.memory = memory;
+ this._skills = new Map();
+
+ this._registerBuiltins();
+ }
+
+ // ── Registry ──────────────────────────────────────────────────────────────
+
+ /** @param {SkillDef} def */
+ register(def) {
+ this._skills.set(def.name, def);
+ }
+
+ /** @param {string} name */
+ unregister(name) {
+ this._skills.delete(name);
+ }
+
+ /** @returns {SkillDef | undefined} */
+ get(name) {
+ return this._skills.get(name);
+ }
+
+ /** @returns {SkillDef[]} */
+ list() {
+ return [...this._skills.values()];
+ }
+
+ /** Returns MCP-compatible tool definitions for exposed skills */
+ toMcpTools() {
+ return this.list()
+ .filter(s => s.mcpExposed)
+ .map(s => ({
+ name: `skill_${s.name.replace(/-/g, '_')}`,
+ description: s.description,
+ inputSchema: s.inputSchema || { type: 'object', properties: {} },
+ }));
+ }
+
+ // ── Execution ─────────────────────────────────────────────────────────────
+
+ /**
+ * Perform a named skill — emits to protocol, executes handler.
+ * @param {string} name
+ * @param {Object} [args]
+ * @param {Partial<SkillContext>} [ctx]
+ * @returns {Promise<SkillResult>}
+ */
+ async perform(name, args = {}, ctx = {}) {
+ const skill = this._skills.get(name);
+ if (!skill) {
+ return { success: false, output: `Unknown skill: ${name}`, sentiment: -0.3 };
+ }
+
+ const fullCtx = {
+ protocol: this.protocol,
+ memory: this.memory,
+ identity: ctx.identity || null,
+ viewer: ctx.viewer || (typeof window !== 'undefined' ? window.VIEWER?.app?.viewer : null),
+ isBrowser: typeof window !== 'undefined',
+ ...ctx,
+ };
+
+ // Announce the skill is starting
+ this.protocol.emit({
+ type: ACTION_TYPES.PERFORM_SKILL,
+ payload: { skill: name, args, animationHint: skill.animationHint },
+ agentId: fullCtx.identity?.id || 'default',
+ sourceSkill: name,
+ });
+
+ try {
+ const result = await skill.handler(args, fullCtx);
+ this.protocol.emit({
+ type: ACTION_TYPES.SKILL_DONE,
+ payload: { skill: name, result },
+ agentId: fullCtx.identity?.id || 'default',
+ sourceSkill: name,
+ });
+
+ // Auto-speak the result if it has output text
+ if (result.output && fullCtx.isBrowser) {
+ this.protocol.emit({
+ type: ACTION_TYPES.SPEAK,
+ payload: { text: result.output, sentiment: result.sentiment ?? 0 },
+ agentId: fullCtx.identity?.id || 'default',
+ sourceSkill: name,
+ });
+ }
+
+ return result;
+ } catch (err) {
+ const errResult = { success: false, output: `Skill failed: ${err.message}`, sentiment: -0.5 };
+ this.protocol.emit({
+ type: ACTION_TYPES.SKILL_ERROR,
+ payload: { skill: name, error: err.message },
+ agentId: fullCtx.identity?.id || 'default',
+ sourceSkill: name,
+ });
+ return errResult;
+ }
+ }
+
+ // ── Built-in Skills ───────────────────────────────────────────────────────
+
+ _registerBuiltins() {
+ // ── greet ──────────────────────────────────────────────────────────
+ this.register({
+ name: 'greet',
+ description: 'Greet the user and introduce the agent',
+ instruction: 'Say hello warmly, offer to help with 3D models or agent configuration',
+ animationHint: 'wave',
+ voicePattern: 'Hey! I\'m {{name}}, your 3D agent. Drop a model or ask me anything.',
+ mcpExposed: true,
+ inputSchema: { type: 'object', properties: { userName: { type: 'string' } } },
+ handler: async (args, ctx) => {
+ const name = ctx.identity?.name || 'Agent';
+ const userName = args.userName ? `, ${args.userName}` : '';
+ return {
+ success: true,
+ output: `Hey${userName}! I'm ${name}. Drop a 3D model in or ask me anything — I can validate, present, and remember things about your work.`,
+ sentiment: 0.8,
+ };
+ },
+ });
+
+ // ── present-model ─────────────────────────────────────────────────
+ this.register({
+ name: 'present-model',
+ description: 'Narrate and present the currently loaded 3D model',
+ instruction: 'Look at the model, describe its properties, gestures toward interesting features',
+ animationHint: 'present',
+ voicePattern: 'This model has {{vertices}} vertices, {{materials}} materials.',
+ mcpExposed: true,
+ inputSchema: { type: 'object', properties: {} },
+ handler: async (_args, ctx) => {
+ const viewer = ctx.viewer;
+ if (!viewer || !viewer.content) {
+ return { success: false, output: 'No model loaded yet. Drop a glTF or GLB file to get started.', sentiment: -0.1 };
+ }
+
+ let verts = 0, meshes = 0, mats = new Set();
+ viewer.content.traverse(node => {
+ if (node.isMesh) {
+ meshes++;
+ if (node.geometry?.attributes?.position) {
+ verts += node.geometry.attributes.position.count;
+ }
+ if (node.material) {
+ const m = Array.isArray(node.material) ? node.material : [node.material];
+ m.forEach(mat => mats.add(mat.name || mat.uuid));
+ }
+ }
+ });
+
+ const clips = viewer.clips?.length || 0;
+ const bones = (viewer.content.animations || []).length;
+ const output = [
+ `I'm looking at your model now.`,
+ `It has ${verts.toLocaleString()} vertices across ${meshes} mesh${meshes !== 1 ? 'es' : ''},`,
+ `${mats.size} material${mats.size !== 1 ? 's' : ''},`,
+ clips ? `and ${clips} animation clip${clips !== 1 ? 's' : ''}.` : 'with no animations.',
+ ].join(' ');
+
+ // Look at model
+ if (ctx.isBrowser) {
+ ctx.protocol.emit({
+ type: ACTION_TYPES.LOOK_AT,
+ payload: { target: 'model' },
+ agentId: ctx.identity?.id || 'default',
+ });
+ }
+
+ return {
+ success: true,
+ output,
+ sentiment: 0.4,
+ data: { vertices: verts, meshes, materials: mats.size, clips },
+ };
+ },
+ });
+
+ // ── validate-model ────────────────────────────────────────────────
+ this.register({
+ name: 'validate-model',
+ description: 'Run glTF validation and report results',
+ instruction: 'Trigger the validator, summarise errors and warnings with empathy',
+ animationHint: 'inspect',
+ voicePattern: 'Validation found {{errors}} errors and {{warnings}} warnings.',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: { url: { type: 'string', description: 'Model URL to validate' } },
+ },
+ handler: async (_args, ctx) => {
+ const viewer = ctx.viewer;
+ if (!viewer || !viewer.content) {
+ return { success: false, output: 'Load a model first and I\'ll validate it.', sentiment: -0.1 };
+ }
+
+ // The validator runs automatically after load — read the last result from the DOM
+ const reportEl = document.querySelector('.validator-toggle');
+ if (reportEl) {
+ const text = reportEl.textContent?.trim();
+ const hasErrors = reportEl.classList.contains('errors');
+ return {
+ success: !hasErrors,
+ output: text
+ ? `Validation result: ${text}`
+ : 'Validator is still running — check the bar at the bottom of the screen.',
+ sentiment: hasErrors ? -0.5 : 0.6,
+ };
+ }
+
+ return {
+ success: true,
+ output: 'The model loaded successfully. For detailed validation, check the bottom of the screen after loading.',
+ sentiment: 0.3,
+ };
+ },
+ });
+
+ // ── remember ─────────────────────────────────────────────────────
+ this.register({
+ name: 'remember',
+ description: 'Store a memory about the user, session, or project',
+ instruction: 'Save important information for future conversations',
+ animationHint: 'nod',
+ voicePattern: 'Got it. I\'ll remember that.',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ required: ['content'],
+ properties: {
+ content: { type: 'string', description: 'What to remember' },
+ type: { type: 'string', enum: ['user', 'feedback', 'project', 'reference'] },
+ tags: { type: 'array', items: { type: 'string' } },
+ },
+ },
+ handler: async (args, ctx) => {
+ if (!args.content) {
+ return { success: false, output: 'What should I remember?', sentiment: 0 };
+ }
+
+ const id = ctx.memory?.add({
+ type: args.type || MEMORY_TYPES.PROJECT,
+ content: args.content,
+ tags: args.tags || [],
+ });
+
+ if (ctx.isBrowser) {
+ ctx.protocol.emit({
+ type: ACTION_TYPES.REMEMBER,
+ payload: { content: args.content, memoryId: id },
+ agentId: ctx.identity?.id || 'default',
+ });
+ }
+
+ return {
+ success: true,
+ output: `Got it — I'll remember that.`,
+ sentiment: 0.5,
+ data: { memoryId: id },
+ };
+ },
+ });
+
+ // ── think ─────────────────────────────────────────────────────────
+ this.register({
+ name: 'think',
+ description: 'Retrieve relevant memories and reason about a question',
+ instruction: 'Search memory, synthesise context, respond thoughtfully',
+ animationHint: 'think',
+ voicePattern: 'Let me think about that...',
+ mcpExposed: false,
+ inputSchema: {
+ type: 'object',
+ required: ['query'],
+ properties: { query: { type: 'string' } },
+ },
+ handler: async (args, ctx) => {
+ const query = args.query || '';
+ const memories = ctx.memory?.query({ limit: 5 }) || [];
+
+ if (!memories.length) {
+ return {
+ success: true,
+ output: `I don't have any stored context yet. As we work together, I'll build up memory to give you better answers.`,
+ sentiment: 0.1,
+ };
+ }
+
+ const context = memories.map(m => `- ${m.content}`).join('\n');
+ return {
+ success: true,
+ output: `Based on what I remember: ${memories[0].content}`,
+ sentiment: 0.3,
+ data: { memories, context },
+ };
+ },
+ });
+
+ // ── sign-action ───────────────────────────────────────────────────
+ this.register({
+ name: 'sign-action',
+ description: 'Sign the most recent action with the agent\'s linked wallet',
+ instruction: 'Use ERC-191 personal_sign to create a verifiable proof of the action',
+ animationHint: 'sign',
+ voicePattern: 'Signing action {{actionId}} with my wallet.',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: { actionId: { type: 'string' } },
+ },
+ handler: async (args, ctx) => {
+ if (!ctx.identity?.walletAddress) {
+ return {
+ success: false,
+ output: 'No wallet linked. Connect a wallet first to sign actions.',
+ sentiment: -0.2,
+ };
+ }
+
+ if (!ctx.isBrowser || !window.ethereum) {
+ return {
+ success: false,
+ output: 'No web3 wallet detected. Install MetaMask or a compatible wallet.',
+ sentiment: -0.2,
+ };
+ }
+
+ try {
+ const { ethers } = await import('ethers');
+ const provider = new ethers.BrowserProvider(window.ethereum);
+ const signer = await provider.getSigner();
+ const message = `Agent action: ${args.actionId || 'latest'} at ${Date.now()}`;
+ const sig = await signer.signMessage(message);
+
+ ctx.protocol.emit({
+ type: ACTION_TYPES.SIGN,
+ payload: { message, signature: sig, actionId: args.actionId },
+ agentId: ctx.identity?.id || 'default',
+ });
+
+ return {
+ success: true,
+ output: `Action signed. Signature: ${sig.slice(0, 20)}…`,
+ sentiment: 0.6,
+ data: { signature: sig, message },
+ };
+ } catch (err) {
+ return { success: false, output: `Signing failed: ${err.message}`, sentiment: -0.4 };
+ }
+ },
+ });
+
+ // ── help ──────────────────────────────────────────────────────────
+ this.register({
+ name: 'help',
+ description: 'List available skills and controls',
+ instruction: 'Summarise what the agent can do',
+ animationHint: 'gesture',
+ voicePattern: 'Here\'s what I can do.',
+ mcpExposed: false,
+ handler: async (_args, _ctx) => {
+ return {
+ success: true,
+ output: 'I can present and validate 3D models, remember things about your work, sign actions with a wallet, and answer questions. Try dropping a GLB file in, or ask me to present what\'s loaded.',
+ sentiment: 0.5,
+ };
+ },
+ });
+ }
+}
diff --git a/src/erc8004/abi.js b/src/erc8004/abi.js
index f97344fff..f1ad701d7 100644
--- a/src/erc8004/abi.js
+++ b/src/erc8004/abi.js
@@ -1,7 +1,7 @@
/**
- * ERC-8004 Identity Registry — minimal ABI.
+ * ERC-8004 Registry ABIs.
*
- * Only the functions needed for agent registration and lookup.
+ * Only the functions needed for agent registration, reputation, and validation.
* Full spec: https://eips.ethereum.org/EIPS/eip-8004
*/
@@ -19,6 +19,8 @@ export const IDENTITY_REGISTRY_ABI = [
'function setAgentWallet(uint256 agentId, address newWallet, uint256 deadline, bytes signature) external',
'function getAgentWallet(uint256 agentId) external view returns (address)',
'function unsetAgentWallet(uint256 agentId) external',
+ 'function nonces(address owner) external view returns (uint256)',
+ 'function DOMAIN_SEPARATOR() external view returns (bytes32)',
// --- Metadata ---
'function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)',
@@ -28,14 +30,55 @@ export const IDENTITY_REGISTRY_ABI = [
'function ownerOf(uint256 tokenId) external view returns (address)',
'function balanceOf(address owner) external view returns (uint256)',
'function totalSupply() external view returns (uint256)',
+ 'function isAgent(uint256 agentId) external view returns (bool)',
// --- Events ---
'event Registered(uint256 indexed agentId, string agentURI, address indexed owner)',
'event URIUpdated(uint256 indexed agentId, string newURI, address indexed updatedBy)',
+ 'event WalletSet(uint256 indexed agentId, address indexed wallet)',
+ 'event WalletUnset(uint256 indexed agentId)',
'event MetadataSet(uint256 indexed agentId, string indexed indexedMetadataKey, string metadataKey, bytes metadataValue)',
'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)',
];
+export const REPUTATION_REGISTRY_ABI = [
+ // --- Submit ---
+ 'function submitFeedback(uint256 agentId, int8 score, string uri) external',
+
+ // --- Query ---
+ 'function getReputation(uint256 agentId) external view returns (int256 avgX100, uint256 count)',
+ 'function getFeedbackCount(uint256 agentId) external view returns (uint256)',
+ 'function getFeedback(uint256 agentId, uint256 index) external view returns (tuple(address from, int8 score, uint64 timestamp, string uri))',
+ 'function getFeedbackRange(uint256 agentId, uint256 offset, uint256 limit) external view returns (tuple(address from, int8 score, uint64 timestamp, string uri)[])',
+ 'function hasReviewed(uint256 agentId, address reviewer) external view returns (bool)',
+
+ // --- Events ---
+ 'event FeedbackSubmitted(uint256 indexed agentId, address indexed from, int8 score, string uri)',
+];
+
+export const VALIDATION_REGISTRY_ABI = [
+ // --- Admin ---
+ 'function addValidator(address v) external',
+ 'function removeValidator(address v) external',
+ 'function isValidator(address v) external view returns (bool)',
+ 'function owner() external view returns (address)',
+ 'function transferOwnership(address newOwner) external',
+
+ // --- Record ---
+ 'function recordValidation(uint256 agentId, bool passed, bytes32 proofHash, string proofURI, string kind) external',
+
+ // --- Query ---
+ 'function getValidationCount(uint256 agentId) external view returns (uint256)',
+ 'function getValidation(uint256 agentId, uint256 index) external view returns (tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind))',
+ 'function getLatestByKind(uint256 agentId, string kind) external view returns (tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind))',
+ 'function getValidationRange(uint256 agentId, uint256 offset, uint256 limit) external view returns (tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind)[])',
+
+ // --- Events ---
+ 'event ValidatorAdded(address indexed validator)',
+ 'event ValidatorRemoved(address indexed validator)',
+ 'event ValidationRecorded(uint256 indexed agentId, address indexed validator, bool passed, bytes32 proofHash, string kind)',
+];
+
/**
* Known deployments — add chain-specific addresses here.
* Format follows agentRegistry spec: eip155:{chainId}:{address}
@@ -49,7 +92,7 @@ export const REGISTRY_DEPLOYMENTS = {
},
// Base Sepolia testnet (chain 84532)
84532: {
- identityRegistry: '', // TODO: fill once deployed
+ identityRegistry: '', // TODO: fill in from Deploy.s.sol broadcast output
reputationRegistry: '',
validationRegistry: '',
},
diff --git a/src/erc8004/index.js b/src/erc8004/index.js
index 0d185d918..75bf8bed7 100644
--- a/src/erc8004/index.js
+++ b/src/erc8004/index.js
@@ -1,3 +1,11 @@
-export { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './abi.js';
+export {
+ IDENTITY_REGISTRY_ABI,
+ REPUTATION_REGISTRY_ABI,
+ VALIDATION_REGISTRY_ABI,
+ REGISTRY_DEPLOYMENTS,
+ agentRegistryId,
+} from './abi.js';
export { connectWallet, registerAgent, buildRegistrationJSON, pinToIPFS } from './agent-registry.js';
export { RegisterUI } from './register-ui.js';
+export { submitFeedback, getReputation, getFeedbackRange, hasReviewed } from './reputation.js';
+export { recordValidation, getLatestValidation, reportPassed, hashReport } from './validation-recorder.js';
diff --git a/src/erc8004/reputation.js b/src/erc8004/reputation.js
new file mode 100644
index 000000000..d678b2eba
--- /dev/null
+++ b/src/erc8004/reputation.js
@@ -0,0 +1,65 @@
+/**
+ * ReputationRegistry helpers — submit and query agent feedback.
+ */
+
+import { Contract } from 'ethers';
+import { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } from './abi.js';
+
+function getContract(chainId, runner) {
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ if (!deployment || !deployment.reputationRegistry) {
+ throw new Error(`No Reputation Registry deployed on chain ${chainId}.`);
+ }
+ return new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, runner);
+}
+
+/**
+ * Submit a reputation score about an agent.
+ * @param {object} opts
+ * @param {number|bigint} opts.agentId
+ * @param {number} opts.score Integer in [-100, 100]
+ * @param {string} [opts.uri=''] ipfs://... pointer to details
+ * @param {import('ethers').Signer} opts.signer
+ * @param {number} [opts.chainId]
+ * @returns {Promise<string>} tx hash
+ */
+export async function submitFeedback({ agentId, score, uri = '', signer, chainId }) {
+ if (!Number.isInteger(score) || score < -100 || score > 100) {
+ throw new Error('score must be an integer in [-100, 100]');
+ }
+ const resolvedChainId = chainId ?? Number((await signer.provider.getNetwork()).chainId);
+ const contract = getContract(resolvedChainId, signer);
+ const tx = await contract.submitFeedback(agentId, score, uri);
+ await tx.wait();
+ return tx.hash;
+}
+
+/**
+ * Read aggregated reputation.
+ * @returns {Promise<{average: number, count: number}>}
+ * average is a float (avgX100 / 100); 0 when no reviews.
+ */
+export async function getReputation({ agentId, runner, chainId }) {
+ const contract = getContract(chainId, runner);
+ const [avgX100, count] = await contract.getReputation(agentId);
+ return {
+ average: Number(count) === 0 ? 0 : Number(avgX100) / 100,
+ count: Number(count),
+ };
+}
+
+export async function getFeedbackRange({ agentId, offset, limit, runner, chainId }) {
+ const contract = getContract(chainId, runner);
+ const rows = await contract.getFeedbackRange(agentId, offset, limit);
+ return rows.map((r) => ({
+ from: r.from,
+ score: Number(r.score),
+ timestamp: Number(r.timestamp),
+ uri: r.uri,
+ }));
+}
+
+export async function hasReviewed({ agentId, reviewer, runner, chainId }) {
+ const contract = getContract(chainId, runner);
+ return contract.hasReviewed(agentId, reviewer);
+}
diff --git a/src/erc8004/validation-recorder.js b/src/erc8004/validation-recorder.js
new file mode 100644
index 000000000..d3cb4e7a4
--- /dev/null
+++ b/src/erc8004/validation-recorder.js
@@ -0,0 +1,107 @@
+/**
+ * ValidationRegistry bridge — turn a glTF-Validator report into an on-chain
+ * validation record.
+ *
+ * Usage:
+ * import { recordValidation } from './erc8004/validation-recorder.js';
+ * await recordValidation({ agentId, report, signer, pinToIPFS, apiToken });
+ */
+
+import { Contract, keccak256, toUtf8Bytes } from 'ethers';
+import { REGISTRY_DEPLOYMENTS, VALIDATION_REGISTRY_ABI } from './abi.js';
+import { pinToIPFS } from './agent-registry.js';
+
+const KIND_GLB_SCHEMA = 'glb-schema';
+
+/**
+ * Derive a deterministic pass/fail flag from a glTF-Validator report.
+ * Pass = zero errors (warnings/infos/hints are allowed).
+ */
+export function reportPassed(report) {
+ const errs = (report && report.issues && report.issues.numErrors) || 0;
+ return errs === 0;
+}
+
+/**
+ * keccak256 hash of the canonicalized JSON report, suitable for on-chain proof.
+ * @param {object} report
+ * @returns {string} 0x-prefixed 32-byte hex.
+ */
+export function hashReport(report) {
+ const json = JSON.stringify(report);
+ return keccak256(toUtf8Bytes(json));
+}
+
+/**
+ * Record a validation result on-chain. Optionally pin the full report to IPFS
+ * first so verifiers can fetch the details behind the hash.
+ *
+ * @param {object} opts
+ * @param {number|bigint} opts.agentId
+ * @param {object} opts.report glTF-Validator report
+ * @param {import('ethers').Signer} opts.signer Must be an allow-listed validator
+ * @param {number} [opts.chainId] Defaults to signer's network
+ * @param {string} [opts.apiToken] IPFS pinning token (optional)
+ * @param {boolean} [opts.pin=true] Pin report to IPFS before recording
+ * @param {string} [opts.kind='glb-schema']
+ * @returns {Promise<{txHash: string, proofHash: string, proofURI: string, passed: boolean}>}
+ */
+export async function recordValidation({
+ agentId,
+ report,
+ signer,
+ chainId,
+ apiToken,
+ pin = true,
+ kind = KIND_GLB_SCHEMA,
+}) {
+ if (!signer) throw new Error('signer is required');
+ if (!report) throw new Error('report is required');
+
+ const resolvedChainId = chainId ?? Number((await signer.provider.getNetwork()).chainId);
+ const deployment = REGISTRY_DEPLOYMENTS[resolvedChainId];
+ if (!deployment || !deployment.validationRegistry) {
+ throw new Error(`No Validation Registry deployed on chain ${resolvedChainId}.`);
+ }
+
+ const proofHash = hashReport(report);
+ const passed = reportPassed(report);
+
+ let proofURI = '';
+ if (pin && apiToken) {
+ const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
+ const cid = await pinToIPFS(blob, apiToken);
+ proofURI = `ipfs://${cid}`;
+ }
+
+ const contract = new Contract(
+ deployment.validationRegistry,
+ VALIDATION_REGISTRY_ABI,
+ signer,
+ );
+ const tx = await contract.recordValidation(agentId, passed, proofHash, proofURI, kind);
+ await tx.wait();
+
+ return { txHash: tx.hash, proofHash, proofURI, passed };
+}
+
+/**
+ * Read the most recent validation of a given kind.
+ * @param {object} opts
+ * @param {number|bigint} opts.agentId
+ * @param {import('ethers').Provider | import('ethers').Signer} opts.runner
+ * @param {number} opts.chainId
+ * @param {string} [opts.kind='glb-schema']
+ */
+export async function getLatestValidation({ agentId, runner, chainId, kind = KIND_GLB_SCHEMA }) {
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ if (!deployment || !deployment.validationRegistry) {
+ throw new Error(`No Validation Registry deployed on chain ${chainId}.`);
+ }
+ const contract = new Contract(
+ deployment.validationRegistry,
+ VALIDATION_REGISTRY_ABI,
+ runner,
+ );
+ return contract.getLatestByKind(agentId, kind);
+}
diff --git a/src/viewer.js b/src/viewer.js
index fc7b8a0e0..a7fc4b238 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -123,6 +123,8 @@ export class Viewer {
this.controls = new OrbitControls(this.defaultCamera, this.renderer.domElement);
this.controls.screenSpacePanning = true;
+ this._onControlsChange = () => this.invalidate();
+ this.controls.addEventListener('change', this._onControlsChange);
this.el.appendChild(this.renderer.domElement);
@@ -147,9 +149,16 @@ export class Viewer {
this._rafId = null;
this._visible = true;
this._tabVisible = !document.hidden;
+ this._disposed = false;
+ this._loadedEnvironment = null;
+ this._guiWrap = null;
+ this._needsRender = true;
+ this._animating = false;
this._onVisibilityChange = () => {
+ const wasHidden = !this._tabVisible;
this._tabVisible = !document.hidden;
+ if (wasHidden && this._tabVisible) this._needsRender = true;
this._updateRenderLoop();
};
document.addEventListener('visibilitychange', this._onVisibilityChange);
@@ -157,7 +166,9 @@ export class Viewer {
if (typeof IntersectionObserver !== 'undefined') {
this._intersectionObserver = new IntersectionObserver(
(entries) => {
+ const wasHidden = !this._visible;
this._visible = entries[entries.length - 1].isIntersecting;
+ if (wasHidden && this._visible) this._needsRender = true;
this._updateRenderLoop();
},
{ threshold: 0 },
@@ -165,35 +176,74 @@ export class Viewer {
this._intersectionObserver.observe(this.el);
}
- this._updateRenderLoop();
- window.addEventListener('resize', this.resize.bind(this), false);
- window.addEventListener('keydown', (e) => {
+ this._onResize = this.resize.bind(this);
+ this._onKeyDown = (e) => {
if ((e.key === 'p' || e.key === 'P') && !this.isInputFocused()) this.takeScreenshot();
- });
+ };
+
+ this._updateRenderLoop();
+ window.addEventListener('resize', this._onResize, false);
+ window.addEventListener('keydown', this._onKeyDown);
+ }
+
+ invalidate() {
+ if (this._disposed) return;
+ this._needsRender = true;
+ this._updateRenderLoop();
+ }
+
+ _recomputeAnimating() {
+ let animating = false;
+ if (this.state && this.state.autoRotate) animating = true;
+ if (!animating && this.mixer && this.state) {
+ for (const key in this.state.actionStates) {
+ if (this.state.actionStates[key]) {
+ animating = true;
+ break;
+ }
+ }
+ }
+ this._animating = animating;
}
_updateRenderLoop() {
- const shouldRun = this._visible && this._tabVisible;
+ if (this._disposed) return;
+ const canRun = this._visible && this._tabVisible;
+ const shouldRun = canRun && (this._needsRender || this._animating);
if (shouldRun && this._rafId === null) {
this.prevTime = performance.now();
this._rafId = requestAnimationFrame(this.animate);
- } else if (!shouldRun && this._rafId !== null) {
+ } else if (!canRun && this._rafId !== null) {
cancelAnimationFrame(this._rafId);
this._rafId = null;
}
}
animate(time) {
- this._rafId = requestAnimationFrame(this.animate);
-
const dt = (time - this.prevTime) / 1000;
+ this.prevTime = time;
+
+ this._recomputeAnimating();
this.controls.update();
this.stats.update();
- this.mixer && this.mixer.update(dt);
+ if (this.mixer) this.mixer.update(dt);
+
+ // Extension point for the AgentAvatar empathy tick and any other per-frame hooks
+ if (this._afterAnimateHooks) {
+ for (let i = 0; i < this._afterAnimateHooks.length; i++) {
+ this._afterAnimateHooks[i](dt);
+ }
+ }
+
this.render();
+ this._needsRender = false;
- this.prevTime = time;
+ if (this._animating && this._visible && this._tabVisible && !this._disposed) {
+ this._rafId = requestAnimationFrame(this.animate);
+ } else {
+ this._rafId = null;
+ }
}
isInputFocused() {
@@ -244,6 +294,8 @@ export class Viewer {
this.axesCamera.aspect = this.axesDiv.clientWidth / this.axesDiv.clientHeight;
this.axesCamera.updateProjectionMatrix();
this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight);
+
+ this.invalidate();
}
load(url, rootPath, assetMap) {
@@ -381,6 +433,8 @@ export class Viewer {
window.VIEWER.scene = this.content;
this.printGraph(this.content);
+
+ this.invalidate();
}
printGraph(node) {
@@ -509,6 +563,12 @@ export class Viewer {
path,
(texture) => {
const envMap = this.pmremGenerator.fromEquirectangular(texture).texture;
+ texture.dispose();
+
+ if (this._loadedEnvironment && this._loadedEnvironment !== envMap) {
+ this._loadedEnvironment.dispose();
+ }
+ this._loadedEnvironment = envMap;
resolve({ envMap });
},
@@ -739,6 +799,7 @@ export class Viewer {
this.el.appendChild(guiWrap);
guiWrap.classList.add('gui-wrap');
guiWrap.appendChild(gui.domElement);
+ this._guiWrap = guiWrap;
if (isMobile) {
gui.close();
} else {
@@ -856,6 +917,133 @@ export class Viewer {
}
});
}
+
+ dispose() {
+ if (this._disposed) return;
+ this._disposed = true;
+
+ if (this._rafId !== null) {
+ cancelAnimationFrame(this._rafId);
+ this._rafId = null;
+ }
+
+ document.removeEventListener('visibilitychange', this._onVisibilityChange);
+ window.removeEventListener('resize', this._onResize, false);
+ window.removeEventListener('keydown', this._onKeyDown);
+
+ if (this._intersectionObserver) {
+ this._intersectionObserver.disconnect();
+ this._intersectionObserver = null;
+ }
+
+ this.clear();
+
+ if (this.mixer) {
+ this.mixer.stopAllAction();
+ const root = this.mixer.getRoot();
+ if (root) this.mixer.uncacheRoot(root);
+ this.mixer = null;
+ }
+ this.clips = [];
+
+ if (this.skeletonHelpers.length) {
+ this.skeletonHelpers.forEach((helper) => {
+ this.scene.remove(helper);
+ helper.dispose?.();
+ });
+ this.skeletonHelpers.length = 0;
+ }
+
+ if (this.gridHelper) {
+ this.scene.remove(this.gridHelper);
+ this.gridHelper.geometry?.dispose();
+ this.gridHelper.material?.dispose();
+ this.gridHelper = null;
+ }
+ if (this.axesHelper) {
+ this.scene.remove(this.axesHelper);
+ this.axesHelper.geometry?.dispose();
+ this.axesHelper.material?.dispose();
+ this.axesHelper = null;
+ }
+ if (this.axesCorner) {
+ this.axesScene?.remove(this.axesCorner);
+ this.axesCorner.geometry?.dispose();
+ this.axesCorner.material?.dispose();
+ this.axesCorner = null;
+ }
+
+ this.lights.forEach((light) => light.parent?.remove(light));
+ this.lights = [];
+
+ if (this.annotationEls.length) {
+ this.annotationEls.forEach((a) => a.el.remove());
+ this.annotationEls = [];
+ }
+ if (this.modelInfo) {
+ this.modelInfo.remove();
+ this.modelInfo = null;
+ }
+
+ if (this.gui) {
+ this.gui.destroy();
+ this.gui = null;
+ }
+ if (this._guiWrap) {
+ this._guiWrap.remove();
+ this._guiWrap = null;
+ }
+
+ if (this.stats?.dom) this.stats.dom.remove();
+
+ this.controls?.dispose();
+ this.controls = null;
+
+ if (this._loadedEnvironment) {
+ this._loadedEnvironment.dispose();
+ this._loadedEnvironment = null;
+ }
+ if (this.neutralEnvironment) {
+ this.neutralEnvironment.dispose();
+ this.neutralEnvironment = null;
+ }
+ if (this.scene) {
+ this.scene.environment = null;
+ this.scene.background = null;
+ }
+
+ if (this.pmremGenerator) {
+ this.pmremGenerator.dispose();
+ this.pmremGenerator = null;
+ }
+
+ if (this.axesRenderer) {
+ this.axesRenderer.dispose();
+ this.axesRenderer.forceContextLoss?.();
+ this.axesRenderer.domElement?.remove();
+ this.axesRenderer = null;
+ }
+ if (this.axesDiv) {
+ this.axesDiv.remove();
+ this.axesDiv = null;
+ }
+ this.axesScene = null;
+ this.axesCamera = null;
+
+ if (this.renderer) {
+ this.renderer.dispose();
+ this.renderer.forceContextLoss?.();
+ this.renderer.domElement?.remove();
+ if (window.renderer === this.renderer) window.renderer = null;
+ this.renderer = null;
+ }
+
+ this.scene = null;
+ this.content = null;
+ this.activeCamera = null;
+ this.defaultCamera = null;
+ this._afterAnimateHooks = null;
+ }
}
function traverseMaterials(object, callback) {