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.

refactor(ipfs): share one gateway list and racing fetch across every manifest reader

nirholasc730d524027e
diff --git a/api/_lib/agent-manifest-publish.js b/api/_lib/agent-manifest-publish.js
index 3159abf69..fad85f0c2 100644
--- a/api/_lib/agent-manifest-publish.js
+++ b/api/_lib/agent-manifest-publish.js
@@ -12,7 +12,7 @@
import { sql } from './db.js';
import { loadAttesterKeypair } from './attest-event.js';
-import { pinToIPFS, ipfsGatewayUrl, ipfsPinningConfigured } from './ipfs-pin.js';
+import { pinToIPFS, ipfsGatewayUrl, ipfsPinningConfigured, fetchFromGateways, IPFS_READ_GATEWAYS } from './ipfs-pin.js';
import { publicUrl as r2PublicUrl } from './r2.js';
import {
buildAgentManifest,
@@ -21,14 +21,12 @@ import {
manifestBodyDigest,
} from './agent-manifest-sign.js';
-/** Public IPFS gateways tried, in order, when fetching a manifest by CID. */
-export const IPFS_GATEWAYS = [
- 'https://ipfs.io/ipfs/',
- 'https://dweb.link/ipfs/',
- 'https://cloudflare-ipfs.com/ipfs/',
-];
+/**
+ * Gateways a manifest can be fetched from, shared with every other IPFS reader
+ * on the platform (api/_lib/ipfs-pin.js) so a dead host is retired in one place.
+ */
+export const IPFS_GATEWAYS = IPFS_READ_GATEWAYS;
-const GATEWAY_TIMEOUT_MS = 12000;
const MAX_ENVELOPE_BYTES = 1024 * 1024;
function appOrigin() {
@@ -256,46 +254,25 @@ export async function publishAgentManifestSafely(agentId, opts) {
}
/**
- * Fetch a signed envelope by CID from the public IPFS gateways, in order.
- * Independent of our database on purpose: this is the same path an outside
- * verifier walks, so if it works here it works for them.
+ * Fetch a signed envelope by CID from the IPFS gateway network, taking the
+ * first gateway that answers. Independent of our database on purpose: this is
+ * the same path an outside verifier walks, so if it works here it works for
+ * them. The gateway that served it is returned so the caller can report which
+ * copy of the network it actually checked.
*
* @param {string} cid
* @returns {Promise<{envelope:object, gateway:string}>}
* @throws {Error & {code:string}} when no gateway returns usable JSON
*/
export async function fetchEnvelopeFromIPFS(cid) {
- const failures = [];
- for (const gateway of IPFS_GATEWAYS) {
- const url = `${gateway}${cid}`;
- try {
- const resp = await fetch(url, {
- redirect: 'follow',
- headers: { accept: 'application/json' },
- signal: AbortSignal.timeout(GATEWAY_TIMEOUT_MS),
- });
- if (!resp.ok) {
- failures.push(`${gateway} ${resp.status}`);
- continue;
- }
- const length = Number(resp.headers.get('content-length') || 0);
- if (length > MAX_ENVELOPE_BYTES) {
- failures.push(`${gateway} too_large`);
- continue;
- }
- const text = await resp.text();
- if (text.length > MAX_ENVELOPE_BYTES) {
- failures.push(`${gateway} too_large`);
- continue;
- }
- return { envelope: JSON.parse(text), gateway: url };
- } catch (err) {
- failures.push(`${gateway} ${err?.message || 'error'}`);
- }
+ const { text, gateway } = await fetchFromGateways(cid, { maxBytes: MAX_ENVELOPE_BYTES });
+ try {
+ return { envelope: JSON.parse(text), gateway };
+ } catch {
+ throw Object.assign(new Error(`${gateway} served ${cid} but it is not JSON`), {
+ code: 'gateway_unreachable',
+ });
}
- throw Object.assign(new Error(`no IPFS gateway served ${cid}: ${failures.join('; ')}`), {
- code: 'gateway_unreachable',
- });
}
/**
diff --git a/api/_lib/ipfs-pin.js b/api/_lib/ipfs-pin.js
index 9512d02de..4a7c05334 100644
--- a/api/_lib/ipfs-pin.js
+++ b/api/_lib/ipfs-pin.js
@@ -1,5 +1,6 @@
/**
- * IPFS pinning helper — single entry point for putting bytes on IPFS.
+ * IPFS transport helper: the single entry point for putting bytes on IPFS and
+ * for reading them back out of the public gateway network.
*
* Pump.fun's own frontend pins coin images and metadata JSON to IPFS (via
* Pinata) and points the on-chain `uri` at `https://ipfs.io/ipfs/{cid}`.
@@ -8,7 +9,7 @@
*
* Provider order mirrors api/pinning/[action].js: Pinata (preferred),
* web3.storage (fallback). When neither is configured, returns null so callers
- * fall back to R2 HTTPS hosting — a valid metadata URI, just not a CID.
+ * fall back to R2 HTTPS hosting, a valid metadata URI but not a CID.
*/
const PINATA_FILE_ENDPOINT = 'https://api.pinata.cloud/pinning/pinFileToIPFS';
@@ -19,6 +20,83 @@ export function ipfsGatewayUrl(cid) {
return `https://ipfs.io/ipfs/${cid}`;
}
+/**
+ * Gateways tried when reading content-addressed bytes back off IPFS.
+ *
+ * Two properties matter and they pull in opposite directions, so the list
+ * carries both kinds. The public gateways come first because verification is
+ * only meaningful if it does not route through us or our vendor. The pinning
+ * provider's own gateway comes last as the guaranteed-complete copy: a freshly
+ * pinned CID takes minutes to hours to propagate across the DHT, and until it
+ * does the public gateways answer 504 for a document that is perfectly pinned.
+ *
+ * Deliberately absent: cloudflare-ipfs.com and cf-ipfs.com (Cloudflare retired
+ * both in 2024, so they fail DNS, see src/ipfs.js) and flk-ipfs.xyz (no longer
+ * accepting connections). A dead host in a fallback chain is worse than no
+ * fallback: it burns the retry budget and reports a network error as a miss.
+ */
+export const IPFS_READ_GATEWAYS = [
+ 'https://ipfs.io/ipfs/',
+ 'https://dweb.link/ipfs/',
+ 'https://w3s.link/ipfs/',
+ 'https://gateway.pinata.cloud/ipfs/',
+];
+
+const GATEWAY_TIMEOUT_MS = 15000;
+
+/**
+ * Fetch a CID from every gateway at once and take the first usable answer.
+ *
+ * Concurrent on purpose. Walking the list serially makes the slowest gateway
+ * the floor on every read: a cold CID that one gateway serves in 6s would sit
+ * behind two 15s timeouts first, and a caller that gave up at 30s would call a
+ * retrievable document unretrievable.
+ *
+ * @param {string} cid
+ * @param {object} [opts]
+ * @param {number} [opts.maxBytes=1048576] reject bodies larger than this
+ * @param {string[]} [opts.gateways] override the gateway list (tests)
+ * @param {number} [opts.timeoutMs]
+ * @returns {Promise<{text:string, gateway:string}>}
+ * @throws {Error & {code:'gateway_unreachable'}} when no gateway serves it
+ */
+export async function fetchFromGateways(cid, { maxBytes = 1024 * 1024, gateways, timeoutMs } = {}) {
+ const list = gateways?.length ? gateways : IPFS_READ_GATEWAYS;
+ const budget = timeoutMs || GATEWAY_TIMEOUT_MS;
+ const failures = [];
+
+ const attempt = async (gateway) => {
+ const url = `${gateway}${cid}`;
+ const resp = await fetch(url, {
+ redirect: 'follow',
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(budget),
+ });
+ if (!resp.ok) throw new Error(`${resp.status}`);
+ if (Number(resp.headers.get('content-length') || 0) > maxBytes) throw new Error('too_large');
+ const text = await resp.text();
+ if (text.length > maxBytes) throw new Error('too_large');
+ return { text, gateway: url };
+ };
+
+ // Promise.any resolves on the first fulfilment and only rejects once every
+ // attempt has failed, which is exactly the semantics wanted here.
+ try {
+ return await Promise.any(
+ list.map((gateway) =>
+ attempt(gateway).catch((err) => {
+ failures.push(`${gateway} ${err?.message || 'error'}`);
+ throw err;
+ }),
+ ),
+ );
+ } catch {
+ throw Object.assign(new Error(`no IPFS gateway served ${cid}: ${failures.join('; ')}`), {
+ code: 'gateway_unreachable',
+ });
+ }
+}
+
// Bounded so a hung provider cannot hold an interactive request (persona save
// pins inline) open until the platform's own request timeout fires.
const PIN_TIMEOUT_MS = 25000;
diff --git a/scripts/verify-agent-manifest.mjs b/scripts/verify-agent-manifest.mjs
index f11110104..e2737eaf8 100644
--- a/scripts/verify-agent-manifest.mjs
+++ b/scripts/verify-agent-manifest.mjs
@@ -19,8 +19,8 @@
import { readFile } from 'node:fs/promises';
import { verifyAgentManifest, sha256Hex } from '../api/_lib/agent-manifest-sign.js';
+import { fetchFromGateways } from '../api/_lib/ipfs-pin.js';
-const GATEWAYS = ['https://ipfs.io/ipfs/', 'https://dweb.link/ipfs/', 'https://cloudflare-ipfs.com/ipfs/'];
const TIMEOUT_MS = 15000;
function parseArgs(argv) {
@@ -44,21 +44,12 @@ const USAGE = `Verify a signed three.ws agent manifest.
--json print the result as JSON
`;
-async function fetchFromGateways(cid) {
- const failures = [];
- for (const gateway of GATEWAYS) {
- try {
- const resp = await fetch(`${gateway}${cid}`, { signal: AbortSignal.timeout(TIMEOUT_MS) });
- if (!resp.ok) {
- failures.push(`${gateway} -> HTTP ${resp.status}`);
- continue;
- }
- return { envelope: await resp.json(), from: `${gateway}${cid}` };
- } catch (err) {
- failures.push(`${gateway} -> ${err?.message || 'failed'}`);
- }
- }
- throw new Error(`no gateway served ${cid}\n ${failures.join('\n ')}`);
+// The gateway list and the concurrent read live in api/_lib/ipfs-pin.js, which
+// is dependency-free, so this script shares exactly the retrieval path the
+// platform uses without dragging in a database client.
+async function loadFromIPFS(cid) {
+ const { text, gateway } = await fetchFromGateways(cid);
+ return { envelope: JSON.parse(text), from: gateway };
}
async function resolveAgentCid(agentId, origin) {
@@ -85,7 +76,7 @@ async function main() {
source = args.file;
} else {
const cid = args.cid || (await resolveAgentCid(args.agent, args.origin || 'https://three.ws'));
- const got = await fetchFromGateways(cid);
+ const got = await loadFromIPFS(cid);
envelope = got.envelope;
source = got.from;
}
diff --git a/specs/AGENT_MANIFEST.md b/specs/AGENT_MANIFEST.md
index fa89ee232..0f1336dd4 100644
--- a/specs/AGENT_MANIFEST.md
+++ b/specs/AGENT_MANIFEST.md
@@ -89,6 +89,20 @@ Everything is optional except `manifest.json` and a `body` reference.
},
},
+ // Persona — the compiled voice, described but never disclosed
+ "persona": {
+ "has_persona": true, // false when the agent still runs on no persona at all
+ "tone_tags": ["blunt", "dry", "analytical"],
+ "extracted_at": "2026-08-13T09:12:00Z", // null when the persona was hand-written
+ // Present only when an onboarding interview produced the voice.
+ // Counts and source only; the answers themselves stay private.
+ "interview": {
+ "source": "create-wizard", // "create-wizard" | "brain-studio"
+ "questions_answered": 7,
+ "questions_total": 7,
+ },
+ },
+
// Skills — capability bundles, composable, content-addressed
"skills": [
{ "uri": "skills/wave/", "version": "0.1.0" },
@@ -168,6 +182,26 @@ Skills load lazily. The `<agent-3d>` element emits `skill:loaded` events as each
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).
+### `persona`
+
+Describes the agent's voice without ever disclosing it. The compiled system prompt is deliberately excluded (see "What is deliberately excluded" below): a manifest tells a consumer what an agent sounds like, never how to impersonate it.
+
+| Field | Meaning |
+| --- | --- |
+| `has_persona` | `true` once a compiled persona prompt is stored. `false` means the agent runs on the platform default and has no voice of its own yet. |
+| `tone_tags` | Up to 8 lowercase single-word tone descriptors. The one machine-readable handle on register, so a directory can facet on it. Empty array when none were set. |
+| `extracted_at` | When an onboarding interview last produced this persona. `null` for a hand-written persona, which is the normal case for an agent whose owner typed the profile directly. |
+| `interview` | Provenance for an interview-derived voice. **Absent entirely** when no interview ever ran, so its presence is itself the signal. |
+
+`interview` carries counts and origin only:
+
+- `source` is `create-wizard` when the interview ran before the agent existed (the create flow, via `POST /api/persona/interview`) or `brain-studio` when it was re-run against a live agent (`POST /api/agents/:id/persona/extract`).
+- `questions_answered` / `questions_total` say how much of the interview was actually filled in. The interview is optional question by question, so a voice built from 3 of 7 answers is a normal outcome, not a degraded one.
+
+**The answers are never published.** They are the owner's own words about their agent, held server-side in `persona_traits.interview` and reported here only as a count. A consumer can tell that a voice was interviewed and how thoroughly, and nothing more.
+
+Backwards compatibility: consumers must treat the whole `persona` block as optional. A manifest without it, or with `has_persona: false`, describes an agent that still speaks (on the platform default), so absence is never an error.
+
## Worked examples
### Coach Leo (v0.1 — no on-chain permissions)
@@ -467,7 +501,7 @@ The inner `sha256` is deliberately redundant with the outer signature. It lets a
Five checks, all offline except the fetch:
-1. **Fetch** the CID from any IPFS gateway. `https://ipfs.io/ipfs/<cid>` is the default; `dweb.link` and `cloudflare-ipfs.com` are the documented fallbacks.
+1. **Fetch** the CID from any IPFS gateway. Any gateway will do, because the check that follows is cryptographic: the gateway supplies bytes, it does not vouch for them. three.ws queries `ipfs.io`, `dweb.link`, `w3s.link`, and `gateway.pinata.cloud` concurrently and takes the first that answers. Note that a just-published CID is often served only by the pinning provider's gateway at first: DHT propagation to the public gateways takes minutes to hours, during which the others correctly answer 504 for a document that is genuinely pinned.
2. **Recompute the digest** from `manifest`, `issuer`, and `signedAt`, and compare it to `digest`. A mismatch means the document was edited after signing.
3. **Verify the signature** over `"threews.agent.manifest.v1:" + digest` against `issuer`.
4. **Check the issuer** against the identity you expect. A valid signature from an unknown key proves only that *someone* signed the document. `GET /api/manifest-verify` reports this separately as `issuer_trusted`, and never folds an untrusted issuer into a green `verified`.
@@ -505,6 +539,8 @@ Volatile operational state (view counts, balances, last-seen timestamps) never e
A private avatar's body is omitted rather than embedded as a presigned URL: a URL that expires would turn a permanent document into a broken pointer.
+The compiled persona prompt is excluded from the live `GET /api/agents/:id/manifest` body, and so are any onboarding-interview answers behind it. The `persona` block describes the voice (see [`persona`](#persona)) without handing over the text needed to wear it. The signed envelope is the one place a prompt is disclosed, and only deliberately: `instructions` is inlined there so a reader can verify that the prompt they were shown is the prompt that actually runs (see "Inline instructions" above). Interview answers are never inlined, in either form.
+
### Publishing rules
- Signing and pinning happen automatically on every persona save, extract, and restore, and never fail the save. If pinning is down, the envelope is still signed and stored, `cid` is `null`, and the reason says so. Nothing is ever reported as pinned when it is not.
@@ -513,6 +549,10 @@ A private avatar's body is omitted rather than embedded as a presigned URL: a UR
## Changelog
+### v0.3.2 (2026-08-13)
+
+- Documented the `persona` block that `GET /api/agents/:id/manifest` has been serving: `has_persona`, `tone_tags`, `extracted_at`, and the optional `interview` provenance (`source`, `questions_answered`, `questions_total`). Descriptive only; the compiled prompt and the owner's interview answers are never published, and that exclusion is now stated where the other exclusions live. Documentation of existing behavior, so no version bump and no consumer change: the block stays optional and its absence stays valid.
+
### v0.3.1 (2026-08-11)
- Documented `voice.tts.proxyURL` and added `voice.tts.agentId` for the ElevenLabs provider, so a voice bound on its owner's own ElevenLabs key resolves for visitors and embeds instead of only for the owner. Additive and optional: a manifest without `agentId` stays valid.