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.

docs(memory): document the Farcaster seeding lane and finish the vault and identity invariant tests

nirholascea6543818f6
diff --git a/contracts/test/GreenfieldVault.t.sol b/contracts/test/GreenfieldVault.t.sol
index ba6ce4fe5..fd68b133d 100644
--- a/contracts/test/GreenfieldVault.t.sol
+++ b/contracts/test/GreenfieldVault.t.sol
@@ -8,6 +8,29 @@ import {IPermissionHub} from "../src/greenfield/IPermissionHub.sol";
import {MockCrossChain, MockPermissionHub, MockGnfdAccessControl} from "./mocks/MockGreenfield.sol";
import {Reentrant} from "./mocks/Reentrant.sol";
+/// @notice Counterparty with no `receive`, so any ETH the vault sends it fails.
+/// Proves the payout-failure branches of `buy`, `revoke`, and
+/// `withdraw` revert instead of silently discarding the credit.
+contract EthRejector {
+ function doList(GreenfieldVault vault, bytes32 objectId, uint256 price) external {
+ vault.list(objectId, price, address(this));
+ }
+
+ function doBuy(GreenfieldVault vault, bytes32 objectId, bytes calldata policyData) external payable {
+ vault.buy{value: msg.value}(objectId, policyData);
+ }
+
+ function doRevoke(GreenfieldVault vault, uint256 saleId) external payable {
+ vault.revoke{value: msg.value}(saleId);
+ }
+
+ function doWithdraw(GreenfieldVault vault) external {
+ vault.withdraw();
+ }
+}
+
+/// @dev Invariants under proof: GV-1 .. GV-8 of
+/// `specs/ECONOMY_CONTRACT_INVARIANTS.md`.
contract GreenfieldVaultTest is Test {
MockCrossChain internal crossChain;
MockPermissionHub internal permissionHub;
@@ -107,6 +130,9 @@ contract GreenfieldVaultTest is Test {
vm.expectRevert(GreenfieldVault.BadPrice.selector);
vault.list(OBJECT_ID, 0, seller);
+
+ vm.expectRevert(GreenfieldVault.ZeroAddress.selector);
+ vault.list(OBJECT_ID, PRICE, address(0));
vm.stopPrank();
}
@@ -396,6 +422,77 @@ contract GreenfieldVaultTest is Test {
vault.withdraw();
}
+ /// GV-4: a seller that cannot receive ETH gets a revert, not a silent
+ /// zeroing of its credited balance.
+ function testWithdrawToARejectingSellerReverts() public {
+ EthRejector badSeller = new EthRejector();
+ bytes32 role = vault.ROLE_CREATE();
+ vm.prank(address(badSeller));
+ accessControl.grantRole(role, address(vault), 0);
+ badSeller.doList(vault, OBJECT_ID, PRICE);
+
+ _buy(buyer, OBJECT_ID);
+ assertEq(vault.pendingWithdrawals(address(badSeller)), PRICE);
+
+ vm.expectRevert(GreenfieldVault.TransferFailed.selector);
+ badSeller.doWithdraw(vault);
+
+ assertEq(vault.pendingWithdrawals(address(badSeller)), PRICE, "GV-4: the credit survives a failed payout");
+ }
+
+ /// GV-3: a buyer that cannot receive its refund gets a revert, so the
+ /// purchase never half-lands.
+ function testBuyRefundFailureRevertsTheWholePurchase() public {
+ _list(seller, OBJECT_ID, PRICE);
+
+ EthRejector badBuyer = new EthRejector();
+ vm.deal(address(badBuyer), 10 ether);
+
+ vm.expectRevert(GreenfieldVault.TransferFailed.selector);
+ badBuyer.doBuy{value: TOTAL_REQUIRED + 1 ether}(vault, OBJECT_ID, POLICY_DATA);
+
+ assertEq(vault.saleIdOf(OBJECT_ID, address(badBuyer)), 0, "GV-3: no sale may survive a failed refund");
+ assertEq(vault.pendingWithdrawals(seller), 0);
+ }
+
+ /// GV-7: same for a seller's excess relay fee on revoke.
+ function testRevokeRefundFailureReverts() public {
+ EthRejector badSeller = new EthRejector();
+ bytes32 role = vault.ROLE_CREATE();
+ vm.prank(address(badSeller));
+ accessControl.grantRole(role, address(vault), 0);
+ badSeller.doList(vault, OBJECT_ID, PRICE);
+ vm.deal(address(badSeller), 10 ether);
+
+ uint256 saleId = _buy(buyer, OBJECT_ID);
+ vm.prank(address(permissionHub));
+ vault.greenfieldCall(STATUS_SUCCESS, 0x07, 2, 777, abi.encode(saleId));
+
+ vm.expectRevert(GreenfieldVault.TransferFailed.selector);
+ badSeller.doRevoke{value: TOTAL_FEE + 1 ether}(vault, saleId);
+
+ (,,,,, GreenfieldVault.SaleStatus status) = vault.sales(saleId);
+ assertEq(uint8(status), uint8(GreenfieldVault.SaleStatus.Granted), "the sale stays Granted");
+ }
+
+ // ── GV-5: the vault always holds enough to pay every seller ──────────────
+
+ function testVaultBalanceCoversEveryPendingWithdrawal() public {
+ _list(seller, OBJECT_ID, PRICE);
+ _list(seller, OBJECT_ID_2, 2 ether);
+
+ _buy(buyer, OBJECT_ID);
+ vm.prank(buyer2);
+ vault.buy{value: 2 ether + TOTAL_FEE}(OBJECT_ID_2, POLICY_DATA);
+
+ assertEq(vault.pendingWithdrawals(seller), 3 ether);
+ assertGe(address(vault).balance, vault.pendingWithdrawals(seller), "GV-5: held ETH must cover every credit");
+
+ vm.prank(seller);
+ vault.withdraw();
+ assertGe(address(vault).balance, vault.pendingWithdrawals(seller));
+ }
+
// ── views ────────────────────────────────────────────────────────────
function testQuoteRelayFee() public view {
diff --git a/contracts/test/IdentityRegistry.t.sol b/contracts/test/IdentityRegistry.t.sol
index 1021a46e6..a6e64f3d2 100644
--- a/contracts/test/IdentityRegistry.t.sol
+++ b/contracts/test/IdentityRegistry.t.sol
@@ -525,6 +525,24 @@ contract IdentityRegistryTest is Test {
assertEq(address(reg).balance, 1 ether);
}
+ function testSpendPayoutFailureRevertsTheWholeCall() public {
+ EthRejectingRecipient sink = new EthRejectingRecipient();
+
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 1 ether}(id);
+ vm.prank(alice);
+ reg.setSpendAllowance(id, spender, 1 ether);
+
+ vm.prank(spender);
+ vm.expectRevert(IdentityRegistry.EthTransferFailed.selector);
+ reg.spend(id, payable(address(sink)), 1 ether, "undeliverable");
+
+ assertEq(reg.agentBalance(id), 1 ether, "ID-9: the debit must not survive a failed payout");
+ assertEq(reg.spendAllowance(id, spender), 1 ether);
+ }
+
// ── ID-10: reentrancy ────────────────────────────────────────────────────
function testReentrantSpendIsBlocked() public {
diff --git a/docs/farcaster-memory-seeding.md b/docs/farcaster-memory-seeding.md
new file mode 100644
index 000000000..a357309d8
--- /dev/null
+++ b/docs/farcaster-memory-seeding.md
@@ -0,0 +1,243 @@
+# Farcaster memory seeding
+
+Give an agent your Farcaster voice: your public profile and casts, distilled and
+written into the agent's long-term memory, so it can talk the way you talk.
+
+The whole surface is built around one constraint. Farcaster has no OAuth, and we
+deliberately never ask for a Farcaster signer, so the usual "log in with" flow
+does not exist. Anyone can read anyone's casts from a public hub, which means a
+naive seeder would happily pull a stranger's posts into your agent. This lane
+refuses to do that: **the account has to be proved yours before a single cast is
+read into memory**, and the proof is a wallet signature against the protocol's
+own verification records.
+
+- **Surface**: the Farcaster panel in the agent persona editor at [/dashboard/agents](https://three.ws/dashboard/agents)
+- **API**: `/api/agents/:id/memory/seed/farcaster`
+- **Related**: [Memory system](./memory.md), [`@three-ws/agent-memory`](https://www.npmjs.com/package/@three-ws/agent-memory)
+
+---
+
+## How ownership is proved
+
+A Farcaster ID (fid) publishes the wallets it controls as **verification
+messages** on the protocol. They are public, they are signed by the fid's own
+key, and they name a chain: Solana (`PROTOCOL_SOLANA`) or Ethereum. That list is
+the allowlist for consent.
+
+```
+ you enter @handle
+ │
+ ▼
+ resolve fid ──▶ read the fid's verified wallets ──▶ none? stop, nothing read
+ │
+ ▼
+ server issues a one-time challenge naming the agent, the fid, the wallet,
+ the scope, and an expiry — and stores the exact text
+ │
+ ▼
+ you sign it in Phantom (ed25519) ← Solana leads; an EVM
+ │ verification signs with
+ ▼ personal_sign instead
+ server re-reads the verifications, checks the wallet is still in the set,
+ verifies the signature against ITS copy of the message, burns the nonce
+ │
+ ▼
+ consent row written ──▶ casts read ──▶ memories written
+```
+
+Three properties fall out of that shape:
+
+- **Nothing is stored before the signature verifies.** The lookup step reads
+ public data and writes only a challenge row; no memory exists until consent does.
+- **A tampered message cannot be signed into a different grant.** The server
+ compares against the copy it issued, so changing the fid, the agent, or the
+ scope in transit invalidates the signature.
+- **A revoked wallet stops working immediately.** Verifications are re-read at
+ grant time, not trusted from the challenge.
+
+Solana leads because it is the home chain and the wallet our users already have
+connected. When a fid has verified both a Solana and an Ethereum wallet, the
+Solana one is offered first and is what the wallet prompt defaults to.
+
+## What is read, and what is not
+
+The scope string on every consent record is:
+
+```
+farcaster:profile.read farcaster:casts.read
+```
+
+| Read | Never touched |
+|---|---|
+| Public profile: display name, bio, pfp, username | Direct casts / private data |
+| Up to 100 recent top-level casts | Anything requiring a Farcaster signer |
+| The fid's public verification records | Posting, recasting, following on your behalf |
+
+## What lands in memory
+
+A seed writes three kinds of row into `agent_memories`, all tagged `farcaster`
+and all stamped with the consent id that produced them:
+
+| Kind | Type | Salience | Content |
+|---|---|---|---|
+| `profile` | `user` | 0.80 | One identity memory: display name, handle, fid, bio, follower count |
+| `fact` | `user` | 0.70 | Up to 15 distilled facts: recurring topics, opinions, projects, style |
+| `cast` | `reference` | 0.62 decaying by rank | Up to 12 of the strongest casts, verbatim, dated |
+
+The profile and cast rows are derived without a model, so a seed still produces
+real memory when the distillation lane is down: the run degrades, it does not
+fail. Casts are filtered before they are ranked. Replies, near-empty posts, and
+link-only posts are dropped, duplicate text is collapsed, and what remains is
+ranked by engagement when the data source reports it and by recency when it
+does not.
+
+## Where the data comes from
+
+Two rungs, tried in order:
+
+1. **Neynar** (`@neynar/nodejs-sdk`, MIT) when `NEYNAR_API_KEY` is set. Indexed
+ data, so casts carry reaction counts and profiles carry follower counts. That
+ is what makes engagement ranking possible.
+2. **A public Farcaster hub over its HTTP API, keyless.** Default
+ `https://hub.pinata.cloud`, override with `FARCASTER_HUB_URL`. Serves raw
+ protocol messages, so there are no reaction counts, but it needs no vendor
+ key and does not go dark when a billing plan lapses.
+
+Neither key is required for the feature to work. The SDK is imported lazily and
+only when a key is configured, so the keyless lane carries no dependency on the
+vendor package being installed.
+
+---
+
+## API
+
+All four calls are owner-only: the session (or bearer) user must own the agent.
+Browser calls also carry the standard CSRF token.
+
+### `GET /api/agents/:id/memory/seed/farcaster`
+
+Current link and consent status.
+
+```bash
+curl -s https://three.ws/api/agents/$AGENT_ID/memory/seed/farcaster \
+ -H "authorization: Bearer $THREE_WS_TOKEN"
+```
+
+```json
+{
+ "connected": true,
+ "fid": 987654,
+ "fname": "threewsdemo",
+ "scope": "farcaster:profile.read farcaster:casts.read",
+ "consent": {
+ "id": "22222222-2222-4222-8222-222222222222",
+ "proof_chain": "solana",
+ "proof_address": "So1anaAddressPlaceholder1111111111111111111",
+ "granted_at": "2026-08-11T12:00:00.000Z",
+ "memories_seeded": 15,
+ "casts_ingested": 31
+ },
+ "memory_count": 15,
+ "cast_limit": 100
+}
+```
+
+### `POST … { "intent": "challenge" }`
+
+Resolve the account and get the text to sign. Send `fid` or `fname`; add
+`address` to pick a different one of the fid's verified wallets.
+
+```bash
+curl -s https://three.ws/api/agents/$AGENT_ID/memory/seed/farcaster \
+ -H "authorization: Bearer $THREE_WS_TOKEN" \
+ -H 'content-type: application/json' \
+ -d '{"intent":"challenge","fname":"threewsdemo"}'
+```
+
+The response carries `nonce`, `message` (sign this verbatim), `chain`, `address`,
+`scope`, `cast_limit`, `expires_at` (10 minutes), the resolved `profile`, and
+`wallets` split into `solana` and `ethereum`.
+
+A fid with no verified wallet answers `409 no_verified_wallet`, because there is
+no way to establish it is yours.
+
+### `POST … { "intent": "grant" }`
+
+Sign the message and hand back the signature. Solana signatures may be base58
+(Phantom) or base64; Ethereum uses `personal_sign`.
+
+```js
+const challenge = await post(url, { intent: 'challenge', fname: 'threewsdemo' });
+
+const signed = await window.solana.signMessage(
+ new TextEncoder().encode(challenge.message),
+ 'utf8',
+);
+
+const result = await post(url, {
+ intent: 'grant',
+ nonce: challenge.nonce,
+ address: challenge.address,
+ chain: challenge.chain,
+ signature: btoa(String.fromCharCode(...signed.signature)),
+});
+// → { granted: true, consent_id, seeded: 15, casts_ingested: 31, facts: [...] }
+```
+
+### `POST … { "intent": "reseed" }`
+
+Re-run the ingest under the existing grant, replacing that grant's memories.
+Rate-limited to one seed per agent per 6 hours, matching the X and GitHub lanes.
+Issuing a challenge is deliberately outside that budget, so retrying the wallet
+step never burns the window.
+
+### `DELETE /api/agents/:id/memory/seed/farcaster`
+
+Revoke. This marks the consent revoked, clears the agent's Farcaster link, and
+**deletes every Farcaster-seeded memory on the agent**, including rows a
+superseded grant left behind. Asking to be forgotten means all of it.
+
+```json
+{ "revoked": true, "consent_id": "2222…", "deleted": 15 }
+```
+
+## Errors
+
+| Code | HTTP | Meaning |
+|---|---|---|
+| `no_verified_wallet` | 409 | The fid has verified no wallet, so ownership cannot be proved |
+| `address_not_verified` | 403 | The signing wallet is not in the fid's verification set |
+| `challenge_not_found` | 404 | No such nonce for this agent and user |
+| `challenge_used` | 409 | Nonce already burned |
+| `challenge_expired` | 410 | Older than 10 minutes; request a new one |
+| `address_mismatch` | 400 | The challenge was issued for a different wallet |
+| `invalid_signature` | 401 | Signature does not verify against the stored message |
+| `not_connected` | 412 | `reseed` with no live grant |
+| `farcaster_user_not_found` | 404 | No such fid or fname |
+| `farcaster_upstream` | 502 | The hub or indexer is unavailable |
+
+## Storage
+
+Two tables, created by
+`api/_lib/migrations/20260811130000_farcaster_memory_consent.sql`:
+
+- `farcaster_seed_challenges` holds the one-time nonce and the exact signable
+ text. Storing the message server-side is what lets verification compare against
+ what we issued rather than a client-supplied copy.
+- `farcaster_memory_consents` is the durable grant: fid, scope, proof chain,
+ proof address, signature, message, and revocation timestamp. At most one live
+ grant per agent.
+
+Every seeded row in `agent_memories` carries `context->>'source' =
+'farcaster_seed'` and `context->>'consent_id'`, which is how a re-seed replaces
+only its own rows and a revoke deletes exactly what was granted.
+
+## Source
+
+| Piece | File |
+|---|---|
+| HTTP surface | [api/agents/[id]/memory-seed-farcaster.js](../api/agents/%5Bid%5D/memory-seed-farcaster.js) |
+| Pure transforms (message, normalisation, selection, memory rows) | [api/_lib/farcaster-seed.js](../api/_lib/farcaster-seed.js) |
+| Read lane with failover | [api/_lib/farcaster-client.js](../api/_lib/farcaster-client.js) |
+| Consent panel | [src/dashboard-next/farcaster-seed.js](../src/dashboard-next/farcaster-seed.js) |
+| Tests | [tests/api/farcaster-memory-seed.test.js](../tests/api/farcaster-memory-seed.test.js) |
diff --git a/packages/concierge-mcp/README.md b/packages/concierge-mcp/README.md
index 7a7c2bb0f..f79d5aa96 100644
--- a/packages/concierge-mcp/README.md
+++ b/packages/concierge-mcp/README.md
@@ -23,7 +23,7 @@ Three tools:
| Tool | What it does | Network |
| --- | --- | --- |
| **`concierge_ask`** | Ask a website's AI concierge a question. Give it a `url` and it fetches that page and answers grounded in the real content (title, headings, nav, main text), the way to *ask any website a question*. Or pass `knowledge`/`content` to answer from text you already have. | Free three.ws lane + fetches the URL |
-| **`concierge_embed`** | Generate ready-to-paste embed code that adds a Concierge to a website: the one-tag `<script>`, the `<three-concierge>` web component, or an npm snippet, configured with accent, avatar, greeting, curated knowledge, and suggested prompts. | Offline |
+| **`concierge_embed`** | Generate ready-to-paste embed code that adds a Concierge to a website: the one-tag `<script>`, the `<three-concierge>` web component, an npm snippet, or an imperative `mount()` call, configured with accent, avatar, greeting, curated knowledge, and suggested prompts. | Offline |
| **`concierge_avatars`** | List the rigged 3D avatars a Concierge can wear. | Offline |
No API key, no signer, no payment. `concierge_ask` runs on the public, free `POST /api/concierge` answer lane; the other two are pure local generators.
@@ -104,15 +104,15 @@ Read-only, open-world.
| `persona` | string | Tone instruction for the reply. |
| `lang` | string | BCP-47 hint, e.g. `en`, `es`. |
-At least one of `url`, `knowledge`, or `content` is required. Returns `{ answer, grounded_in, provider, model }`.
+At least one of `url`, `knowledge`, or `content` is required. Returns `{ ok, question, answer, grounded_in, provider, model, endpoint }`.
### `concierge_embed`
Read-only, idempotent, offline.
-Key parameters: `siteName`, `flavor` (`script` \| `web-component` \| `npm` \| `imperative` \| `all`), `accent`, `avatar`, `customAvatar`, `position`, `theme`, `greeting`, `persona`, `knowledge`, `suggestions[]`, `endpoint`, `muted`, `open`, `noPicker`, `noTeaser`, `lang`. Returns `{ snippets, applied_config }`.
+Key parameters: `siteName`, `flavor` (`script` \| `web-component` \| `npm` \| `imperative` \| `all`, default `all`), `accent`, `avatar`, `customAvatar`, `position`, `theme`, `greeting`, `persona`, `knowledge`, `suggestions[]`, `endpoint`, `muted`, `open`, `noPicker`, `noTeaser`, `lang`. Returns `{ ok, flavor, snippets, applied_config, docs }`. The `script`, `web-component`, and `imperative` snippets are all plain-HTML paste-ready (they load the CDN global build); the `npm` snippet is for bundler users.
### `concierge_avatars`
-Read-only, idempotent, offline. No parameters. Returns the catalog (`id`, `name`, `tagline`, `style`).
+Read-only, idempotent, offline. No parameters. Returns `{ ok, default, count, avatars, note }`, each avatar carrying `id`, `name`, `tagline`, `style`, and `framing`.
## Configuration
@@ -124,6 +124,20 @@ All optional environment variables:
| `THREE_WS_TIMEOUT_MS` | `45000` | Timeout for the concierge answer (it may fail over across LLM providers). |
| `CONCIERGE_PAGE_TIMEOUT_MS` | `12000` | Timeout for fetching a page in `concierge_ask`. |
+## Errors
+
+A failed tool call returns an MCP error result (`isError: true`) whose text is a single JSON object: `{ "ok": false, "error": "<code>", "message": "…" }`, plus `status` on upstream rejections:
+
+| `error` | Meaning | Recovery |
+| --- | --- | --- |
+| `bad_request` | Bad arguments: no `url`/`knowledge`/`content` on `concierge_ask`, a non-http(s) `url`, or an unknown `avatar` id. | Fix the call. |
+| `unsupported_media` | The fetched `url` is not an HTML/text page. | Point at a readable page, or pass `content`. |
+| `upstream_error` | The answer endpoint rejected the request; `status` carries the HTTP code (`429` = the free lane's IP rate limit). | Act on `status`; back off on `429`. |
+| `stream_error` | The answer stream failed before completing. | Retry. |
+| `timeout` | No answer within `THREE_WS_TIMEOUT_MS`, or the page fetch outran `CONCIERGE_PAGE_TIMEOUT_MS`. | Retry or raise the timeout. |
+| `network_error` | The request never reached the API (DNS, offline, TLS). | Check connectivity / `THREE_WS_BASE`. |
+| `bad_config` | `THREE_WS_TIMEOUT_MS` is not a positive number. Thrown while the server starts (module load), so the process exits before serving. | Fix the env var. |
+
## How it relates to the widget
This server is the agent-facing side of [`@three-ws/concierge`](https://www.npmjs.com/package/@three-ws/concierge), the browser widget. Same answer engine, same avatar catalog, same grounding model, exposed as MCP tools so an assistant can *use* a site's concierge or *install* one, not just a human visitor.
diff --git a/packages/concierge-mcp/src/lib/harvest.js b/packages/concierge-mcp/src/lib/harvest.js
index 12ee8ac2f..d9b17a3eb 100644
--- a/packages/concierge-mcp/src/lib/harvest.js
+++ b/packages/concierge-mcp/src/lib/harvest.js
@@ -107,7 +107,8 @@ export function harvestHtml(html, opts = {}) {
const content = collapse(stripTags(mainMatch ? mainMatch[0] : cleaned)).slice(0, MAX_CONTENT_CHARS);
return {
- url: opts.url || '',
+ // The answer endpoint caps site.url at 600 chars; a longer one would 400.
+ url: (opts.url || '').slice(0, 600),
name: siteName.slice(0, 120),
title,
description,