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.

fix(agent): change memory mode to local in resolveAgentById function fix(element): prevent multiple render shell calls during loading

nirholasf8960c33cecf
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index 429882f78..451d5aa7a 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -132,6 +132,10 @@ function readSessionCookie(req) {
return m ? decodeURIComponent(m[1]) : null;
}
+export function hasSessionCookie(req) {
+ return readSessionCookie(req) !== null;
+}
+
/**
* Issue a new session and revoke the old one. Returns the new plaintext token.
* @param {{ currentSid: string, userId: string, userAgent: string|null, ip: string|null }} opts
diff --git a/api/auth/[action].js b/api/auth/[action].js
index 54c2f5a58..dcdff49e8 100644
--- a/api/auth/[action].js
+++ b/api/auth/[action].js
@@ -7,7 +7,7 @@
import { sql } from '../_lib/db.js';
import {
verifyPassword, hashPassword, createSession, destroySession, sessionCookie,
- getSessionUser, revokeRefreshToken,
+ getSessionUser, hasSessionCookie, revokeRefreshToken,
} from '../_lib/auth.js';
import { randomToken, sha256 } from '../_lib/crypto.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
@@ -102,11 +102,19 @@ async function handleRegister(req, res) {
// ── me ────────────────────────────────────────────────────────────────────────
+// Probe endpoint: anonymous callers (no cookie) get 200 { user: null } so the
+// browser doesn't log a network error on every page load. A 401 here means a
+// cookie was presented but didn't resolve to a live session — the client
+// should clear local state and treat it as a forced logout.
async function handleMe(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
+ if (!hasSessionCookie(req)) return json(res, 200, { user: null });
const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthenticated', 'not signed in');
+ if (!user) {
+ res.setHeader('Set-Cookie', sessionCookie('', { clear: true }));
+ return error(res, 401, 'invalid_session', 'session expired or revoked');
+ }
return json(res, 200, { user });
}
diff --git a/chat/src/providers.js b/chat/src/providers.js
index 5d7528ecf..74b637451 100644
--- a/chat/src/providers.js
+++ b/chat/src/providers.js
@@ -6,6 +6,7 @@ import {
remoteServer,
mistralAPIKey,
anthropicAPIKey,
+ localProvidersEnabled,
} from './stores.js';
export const BUILTIN_MODELS = [
diff --git a/chat/src/stores.js b/chat/src/stores.js
index a08ca1305..54564393c 100644
--- a/chat/src/stores.js
+++ b/chat/src/stores.js
@@ -54,6 +54,7 @@ export function setAPIKeysFromObject(obj) {
}
export const remoteServer = persisted('remoteServer', { address: 'http://localhost:8081', password: '' });
+export const localProvidersEnabled = persisted('localProvidersEnabled', false);
export const syncServer = persisted('syncServer', {
address: syncHostedAddress,
token: uuidv4(),
diff --git a/chat/src/sync.js b/chat/src/sync.js
index 50de8bdf1..a853bd489 100644
--- a/chat/src/sync.js
+++ b/chat/src/sync.js
@@ -6,6 +6,51 @@ export const syncHostedAddress = 'https://sync.three.ws';
// Encryption state
let encryptionKey = null;
+// Network failure circuit-breaker: after MAX_FAILURES consecutive errors,
+// stop attempting requests for COOLDOWN_MS so we don't spam an unreachable host.
+const MAX_FAILURES = 3;
+const COOLDOWN_MS = 5 * 60 * 1000;
+let consecutiveFailures = 0;
+let circuitOpenedAt = 0;
+let failureWarned = false;
+
+function circuitOpen() {
+ if (consecutiveFailures < MAX_FAILURES) return false;
+ if (Date.now() - circuitOpenedAt > COOLDOWN_MS) {
+ // Cool-down elapsed — allow one probe to test recovery.
+ consecutiveFailures = 0;
+ failureWarned = false;
+ return false;
+ }
+ return true;
+}
+
+async function safePostJson(url, body, fallback) {
+ if (circuitOpen()) return fallback;
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ const json = await response.json();
+ consecutiveFailures = 0;
+ failureWarned = false;
+ return json;
+ } catch (e) {
+ consecutiveFailures++;
+ if (consecutiveFailures >= MAX_FAILURES) circuitOpenedAt = Date.now();
+ if (!failureWarned) {
+ console.warn(
+ `[sync] sync server unreachable (${url}): ${e?.message || e}. Sync paused.`
+ );
+ failureWarned = true;
+ }
+ return fallback;
+ }
+}
+
// Initialize encryption with password
export async function initEncryption(password) {
if (!password) {
@@ -328,59 +373,35 @@ export async function syncPush({ conversations, messages }) {
}
async function checkClientMissing(baseUrl, token, localConversationIds, localMessageIds) {
- const response = await fetch(`${baseUrl}/api/sync/check-client-missing`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- token,
- conversationIds: localConversationIds,
- messageIds: localMessageIds,
- }),
- });
-
- return await response.json();
+ return safePostJson(
+ `${baseUrl}/api/sync/check-client-missing`,
+ { token, conversationIds: localConversationIds, messageIds: localMessageIds },
+ { missingConversationIds: [], missingMessageIds: [] }
+ );
}
async function getMissingItems(baseUrl, token, missingConversationIds, missingMessageIds) {
- const response = await fetch(`${baseUrl}/api/sync/get-items`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- token,
- conversationIds: missingConversationIds,
- messageIds: missingMessageIds,
- }),
- });
-
- return await response.json(); // Returns { conversations, messages, apiKeys }
+ return safePostJson(
+ `${baseUrl}/api/sync/get-items`,
+ { token, conversationIds: missingConversationIds, messageIds: missingMessageIds },
+ { conversations: {}, messages: {}, apiKeys: {} }
+ );
}
async function checkServerMissing(baseUrl, token, allLocalConversationIds, allLocalMessageIds) {
- const response = await fetch(`${baseUrl}/api/sync/check-server-missing`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- token,
- conversationIds: allLocalConversationIds,
- messageIds: allLocalMessageIds,
- }),
- });
-
- return await response.json(); // Returns { missingConversationIds, missingMessageIds }
+ return safePostJson(
+ `${baseUrl}/api/sync/check-server-missing`,
+ { token, conversationIds: allLocalConversationIds, messageIds: allLocalMessageIds },
+ { missingConversationIds: [], missingMessageIds: [] }
+ );
}
async function sendMissingItems(baseUrl, token, conversationsToSend, messagesToSend) {
- const response = await fetch(`${baseUrl}/api/sync/send-items`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- token,
- conversations: conversationsToSend,
- messages: messagesToSend,
- }),
- });
-
- return await response.json(); // Returns { success: true }
+ return safePostJson(
+ `${baseUrl}/api/sync/send-items`,
+ { token, conversations: conversationsToSend, messages: messagesToSend },
+ { success: false }
+ );
}
export async function sendSingleItem(
@@ -403,18 +424,16 @@ export async function sendSingleItem(
}
}
- const response = await fetch(`${baseUrl}/api/sync/send-single-item`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
+ return safePostJson(
+ `${baseUrl}/api/sync/send-single-item`,
+ {
token,
conversation: encryptedItem.conversation || null,
message: encryptedItem.message || null,
apiKeys: encryptedItem.apiKeys || null,
- }),
- });
-
- return await response.json(); // Returns { success: true }
+ },
+ { success: false }
+ );
}
export async function deleteSingleItem(
@@ -422,15 +441,13 @@ export async function deleteSingleItem(
token,
item = { conversationId: null, messageId: null }
) {
- const response = await fetch(`${baseUrl}/api/sync/delete-single-item`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
+ return safePostJson(
+ `${baseUrl}/api/sync/delete-single-item`,
+ {
token,
conversationId: item.conversationId || null,
messageId: item.messageId || null,
- }),
- });
-
- return await response.json(); // Returns { success: true }
+ },
+ { success: false }
+ );
}
diff --git a/prompts/fix-console-errors/00-README.md b/prompts/fix-console-errors/00-README.md
new file mode 100644
index 000000000..a86980c08
--- /dev/null
+++ b/prompts/fix-console-errors/00-README.md
@@ -0,0 +1,16 @@
+# Fix Console Errors at https://three.ws/chat
+
+These prompts address the errors observed in the browser console at `https://three.ws/chat`. Each file is a self-contained task you can hand to an engineer or coding agent.
+
+## Priority order
+
+1. [01-agent-3d-boot-race.md](01-agent-3d-boot-race.md) — `<agent-3d>` web component crashes during boot (highest impact: blocks embed).
+2. [02-agent-3d-unknown-memory-mode-remote.md](02-agent-3d-unknown-memory-mode-remote.md) — `Unknown memory mode: remote` thrown by loader.
+3. [03-agent-3d-embed-policy-404.md](03-agent-3d-embed-policy-404.md) — `/api/agents/:id/embed-policy` returns 404.
+4. [04-skills-api-500-and-object-category.md](04-skills-api-500-and-object-category.md) — `/api/skills` 500s; client sends `category=[object Object]`.
+5. [05-sync-three-ws-dns.md](05-sync-three-ws-dns.md) — `sync.three.ws` DNS does not resolve and unhandled rejection.
+6. [06-plugin-manifests-404.md](06-plugin-manifests-404.md) — Plugin registry references missing manifest JSONs.
+7. [07-auth-me-401-handling.md](07-auth-me-401-handling.md) — `/api/auth/me` 401 logged loudly for anonymous users.
+8. [08-localhost-probes.md](08-localhost-probes.md) — Probes to `localhost:8081` and `localhost:11434` (Ollama) noisy when not running.
+9. [09-chat-proxy-402-429.md](09-chat-proxy-402-429.md) — `/api/chat/proxy` 402 (payment) and 429 (rate-limit) surfaced as opaque failures.
+10. [10-ses-and-autofocus-warnings.md](10-ses-and-autofocus-warnings.md) — SES lockdown line + duplicate `autofocus` warning (cosmetic).
diff --git a/prompts/fix-console-errors/01-agent-3d-boot-race.md b/prompts/fix-console-errors/01-agent-3d-boot-race.md
new file mode 100644
index 000000000..35830b9d2
--- /dev/null
+++ b/prompts/fix-console-errors/01-agent-3d-boot-race.md
@@ -0,0 +1,31 @@
+# Fix `<agent-3d>` boot race in attributeChangedCallback
+
+## Symptom
+
+```
+agent-3d.js:68935 [agent-3d] boot failed
+TypeError: Cannot set properties of undefined (setting 'hidden')
+ at HTMLElement._boot (agent-3d.js:68795:32)
+ at HTMLElement.attributeChangedCallback (agent-3d.js:68591:14)
+ at agent-3d.js:69344:50
+```
+
+## Cause
+
+`attributeChangedCallback` fires before the element's internal DOM is initialized (i.e. before `connectedCallback` finishes / before `_boot` has assigned the referenced child). When `_boot` tries to set `.hidden` on that not-yet-created element, it throws.
+
+## Task
+
+In the `<agent-3d>` custom element source (compiled into `agent-3d.js`, source likely under [src/](../../src/) — check [src/element.js](../../src/element.js) and [src/agent-resolver.js](../../src/agent-resolver.js)):
+
+1. Add a readiness guard. Either:
+ - Defer `_boot` work until after `connectedCallback`, OR
+ - In `attributeChangedCallback`, queue attribute changes and replay them once `_boot` has initialized the DOM, OR
+ - Null-check the target element before setting `.hidden`.
+2. Initialize the target element reference in the constructor or at the top of `_boot` *before* any attribute-driven mutation runs.
+3. Add a regression test that constructs the element with attributes pre-set in HTML (so `attributeChangedCallback` runs before `connectedCallback`) and asserts no throw.
+
+## Acceptance
+
+- No `Cannot set properties of undefined (setting 'hidden')` error when loading `https://three.ws/chat`.
+- `_boot` completes for an `<agent-3d agent-id="…">` placed in static HTML.
diff --git a/prompts/fix-console-errors/02-agent-3d-unknown-memory-mode-remote.md b/prompts/fix-console-errors/02-agent-3d-unknown-memory-mode-remote.md
new file mode 100644
index 000000000..b18650a07
--- /dev/null
+++ b/prompts/fix-console-errors/02-agent-3d-unknown-memory-mode-remote.md
@@ -0,0 +1,28 @@
+# Handle `memory="remote"` in `<agent-3d>` loader
+
+## Symptom
+
+```
+agent-3d.js:68935 [agent-3d] boot failed
+Error: Unknown memory mode: remote
+ at Ws.load (agent-3d.js:53866:11)
+ at HTMLElement._boot (agent-3d.js:68848:37)
+```
+
+## Cause
+
+The component is being instantiated with `memory="remote"` (or a config that resolves to `remote`), but the memory loader's switch only handles known modes (likely `local`, `session`, `none`).
+
+## Task
+
+1. Find the loader (`Ws.load` in the bundle; source likely lives near memory/storage helpers under [src/](../../src/)).
+2. Decide:
+ - If `remote` should be supported — implement the branch (fetch/POST against the agent's remote memory endpoint).
+ - If it should not — coerce unknown modes to a safe default (e.g. `local`) with a single `console.warn`, instead of throwing.
+3. Document supported memory modes in the component's README / JSDoc.
+4. Add a unit test for each accepted mode and one for the fallback path.
+
+## Acceptance
+
+- No `Unknown memory mode: remote` error when loading `https://three.ws/chat`.
+- Either remote memory works end-to-end, or unsupported values fall back gracefully without breaking `_boot`.
diff --git a/prompts/fix-console-errors/03-agent-3d-embed-policy-404.md b/prompts/fix-console-errors/03-agent-3d-embed-policy-404.md
new file mode 100644
index 000000000..0c011c842
--- /dev/null
+++ b/prompts/fix-console-errors/03-agent-3d-embed-policy-404.md
@@ -0,0 +1,24 @@
+# Fix `/api/agents/:id/embed-policy` 404
+
+## Symptom
+
+```
+agent-3d.js:68811 GET https://three.ws/api/agents/1930551f-a558-40df-bcb5-6f2e893b8786/embed-policy 404 (Not Found)
+```
+
+## Cause
+
+`<agent-3d>` boot calls `GET /api/agents/:id/embed-policy` to determine which origins/features are allowed to embed the agent. Either the route is not implemented, or the agent id (`1930551f-a558-40df-bcb5-6f2e893b8786`) does not exist.
+
+## Task
+
+1. Confirm whether the route exists on the API (search [api/](../../api/) and [server.json](../../server.json)).
+2. If missing — implement `GET /api/agents/:id/embed-policy` returning the policy shape the client expects (referrer allowlist, allowed features, default model, etc.). Default to a permissive-but-safe policy when the agent has not customized it.
+3. If the agent id is simply absent — return `404` with a JSON body the client can act on, AND make the client treat 404 as "use default policy" rather than logging a hard failure.
+4. On the client side ([src/element.js](../../src/element.js) `_boot`), when the policy fetch returns 404 or non-2xx, fall back to a default policy and continue boot instead of aborting.
+
+## Acceptance
+
+- For valid agent ids, the endpoint returns 200 with a policy.
+- For unknown ids, boot continues with a default policy and no uncaught error.
+- No 404 noise in console for the default deployment.
diff --git a/prompts/fix-console-errors/04-skills-api-500-and-object-category.md b/prompts/fix-console-errors/04-skills-api-500-and-object-category.md
new file mode 100644
index 000000000..b3f01962c
--- /dev/null
+++ b/prompts/fix-console-errors/04-skills-api-500-and-object-category.md
@@ -0,0 +1,39 @@
+# Fix `/api/skills` 500s and `category=[object Object]` client bug
+
+## Symptom
+
+```
+GET https://three.ws/api/skills?sort=popular 500
+GET https://three.ws/api/skills?category=%5Bobject+Object%5D&sort=popular 500 (×7)
+POST https://three.ws/api/skills 401
+```
+
+## Cause
+
+Two separate bugs:
+
+1. **Client** is passing a category *object* into the query string instead of a string id/slug. The result is the literal `[object Object]` getting URL-encoded as `%5Bobject+Object%5D`. Somewhere the code does roughly `?category=${category}` instead of `?category=${category.id}` (or `.slug`).
+2. **Server** throws 500 on both the malformed category value AND on the well-formed `?sort=popular` request. The handler should validate inputs and return 4xx for bad input, never 500.
+
+## Task
+
+### Client
+1. Find the call site that builds the `/api/skills` request. Likely in the marketplace / skills browse page — search for `api/skills` and `sort=popular`.
+2. Pass the category's primitive id (string) rather than the object. Type the helper so this can't regress.
+3. When no category is selected, omit the `category` param entirely (don't send `category=undefined` or `category=null`).
+
+### Server
+1. In the `/api/skills` route ([api/](../../api/) — search `skills`), wrap the handler so:
+ - Invalid `category` returns 400 with `{ error: "..." }`.
+ - Unknown `sort` falls back to a default with a warning, not a 500.
+ - All thrown errors are caught and logged with the request context.
+2. Fix whatever is throwing on the plain `?sort=popular` request — likely a missing column, missing index, or unhandled empty-result path. Reproduce locally before deploying.
+
+### POST 401
+The 401 on `POST /api/skills` is expected when logged out. No fix needed unless the UI is offering the action to anonymous users — if so, gate the button behind an auth check.
+
+## Acceptance
+
+- `GET /api/skills?sort=popular` returns 200 with the popular skills list.
+- The client never sends `category=[object Object]`.
+- Bad inputs return 4xx with a useful error body, not 500.
diff --git a/prompts/fix-console-errors/05-sync-three-ws-dns.md b/prompts/fix-console-errors/05-sync-three-ws-dns.md
new file mode 100644
index 000000000..342db2fa2
--- /dev/null
+++ b/prompts/fix-console-errors/05-sync-three-ws-dns.md
@@ -0,0 +1,27 @@
+# Fix unresolved `sync.three.ws` host and unhandled rejection
+
+## Symptom
+
+```
+POST https://sync.three.ws/ net::ERR_NAME_NOT_RESOLVED
+Uncaught (in promise) TypeError: Failed to fetch
+ at index-DPO-3TaM.js:16330:3413
+```
+
+## Cause
+
+The client posts to `https://sync.three.ws/` but DNS has no record for that subdomain. The fetch caller also lacks a `.catch()`, so the failure surfaces as an uncaught promise rejection.
+
+## Task
+
+1. Decide the intent:
+ - If `sync.three.ws` is a real backend that hasn't shipped yet — provision DNS + the service, OR feature-flag the client call off until it's live.
+ - If it was renamed/retired — point the client at the correct host or remove the call.
+2. Whichever path: wrap the fetch in `try/catch` (or `.catch()`) so a network failure logs once at `warn` level and does not produce an uncaught rejection.
+3. Add an exponential backoff or "give up after N attempts" so the client doesn't spam the host once it starts failing.
+4. Search the bundle source for the call (look for `sync.three.ws` and the function `Nt` referenced in the stack).
+
+## Acceptance
+
+- No `ERR_NAME_NOT_RESOLVED` in console under normal operation, OR
+- If the host is intentionally optional, failures are caught silently with at most one warning, and no uncaught promise rejection.
diff --git a/prompts/fix-console-errors/06-plugin-manifests-404.md b/prompts/fix-console-errors/06-plugin-manifests-404.md
new file mode 100644
index 000000000..8b79d67c6
--- /dev/null
+++ b/prompts/fix-console-errors/06-plugin-manifests-404.md
@@ -0,0 +1,29 @@
+# Fix missing plugin manifest 404s
+
+## Symptom
+
+```
+GET https://ai-agent-plugins.vercel.app/cow-swap.json 404
+GET https://ai-agent-plugins.vercel.app/contract-scanner.json 404
+GET https://ai-agent-plugins.vercel.app/dao-treasury.json 404
+GET https://ai-agent-plugins.vercel.app/SEO.json 404
+GET https://ai-agent-plugins.vercel.app/StockData.json 404
+```
+
+## Cause
+
+The plugin registry references manifest JSON files that are not deployed at `https://ai-agent-plugins.vercel.app/`.
+
+## Task
+
+1. Locate the plugin registry / list (search for `cow-swap`, `contract-scanner`, `ai-agent-plugins.vercel.app`).
+2. Decide per plugin:
+ - **Keep** — write the manifest JSON, deploy it to the `ai-agent-plugins` site, verify 200 from the URL above.
+ - **Remove** — drop the entry from the registry so the client never tries to fetch it.
+3. Wrap the manifest fetch loop so a single 404 logs at `warn` and does not break the rest of the registry load.
+4. Optional: cache the registry's verified-good list server-side so the client only sees plugins whose manifests actually exist.
+
+## Acceptance
+
+- No 404s for plugin manifests on a fresh load of `https://three.ws/chat`.
+- If a manifest is later removed upstream, the rest of the registry still loads cleanly.
diff --git a/prompts/fix-console-errors/07-auth-me-401-handling.md b/prompts/fix-console-errors/07-auth-me-401-handling.md
new file mode 100644
index 000000000..7a1bff1ae
--- /dev/null
+++ b/prompts/fix-console-errors/07-auth-me-401-handling.md
@@ -0,0 +1,27 @@
+# Quiet `/api/auth/me` 401 for anonymous visitors
+
+## Symptom
+
+```
+GET https://three.ws/api/auth/me 401 (Unauthorized)
+```
+
+…logged on every page load for unauthenticated users.
+
+## Cause
+
+`/api/auth/me` is a probe that asks "is there a session?" The natural answer for an anonymous visitor is "no," but the client surfaces it as a network error in the console.
+
+## Task
+
+1. Find the `/api/auth/me` call site (search the client bundle source).
+2. Either:
+ - Treat `401` as the documented "not signed in" response — no `console.error`, just resolve to `{ user: null }` and continue. OR
+ - Change the server to return `200 { user: null }` for anonymous callers and reserve `401` for genuine token-validation failures.
+3. Make sure the rest of the app's "am I logged in?" branches read from this normalized result.
+
+## Acceptance
+
+- Anonymous visitors see no `auth/me` 401 noise in the console.
+- Logged-in users still get their user object back unchanged.
+- A genuinely invalid/expired token still produces a distinguishable error path.
diff --git a/prompts/fix-console-errors/08-localhost-probes.md b/prompts/fix-console-errors/08-localhost-probes.md
new file mode 100644
index 000000000..c563d2b34
--- /dev/null
+++ b/prompts/fix-console-errors/08-localhost-probes.md
@@ -0,0 +1,32 @@
+# Make `localhost` provider probes silent when nothing is running
+
+## Symptom
+
+```
+GET http://localhost:8081/list_directory net::ERR_CONNECTION_REFUSED
+GET http://localhost:11434/api/tags net::ERR_CONNECTION_REFUSED
+Error fetching models from provider Ollama TypeError: Failed to fetch
+```
+
+## Cause
+
+The app probes local helper services on every load:
+
+- `localhost:8081` — local filesystem / MCP-style helper.
+- `localhost:11434` — Ollama's default port, used to enumerate local models.
+
+When the user has not started those services (the common case), the failed fetches are logged loudly.
+
+## Task
+
+1. Find the provider probe code (search for `11434`, `Ollama`, `list_directory`, `localhost:8081`).
+2. Gate the probes behind one of:
+ - An explicit user opt-in setting (e.g. "Enable local model providers").
+ - A one-shot probe at startup whose failure marks the provider unavailable for the rest of the session, instead of retrying.
+3. On `ERR_CONNECTION_REFUSED` / `Failed to fetch`, log at `debug` (or not at all) — do not use `console.error`. The message should make it obvious this is expected when the local service is not running.
+4. In the UI, render the local provider as "not detected" rather than "error."
+
+## Acceptance
+
+- A fresh load with no local services running produces no red errors for these probes.
+- Users who do run Ollama / the local helper still get models discovered.
diff --git a/prompts/fix-console-errors/09-chat-proxy-402-429.md b/prompts/fix-console-errors/09-chat-proxy-402-429.md
new file mode 100644
index 000000000..2111d17e3
--- /dev/null
+++ b/prompts/fix-console-errors/09-chat-proxy-402-429.md
@@ -0,0 +1,44 @@
+# Handle `/api/chat/proxy` 402 (Payment Required) and 429 (Rate Limited)
+
+## Symptom
+
+```
+POST https://three.ws/api/chat/proxy 402 (initial load)
+POST https://three.ws/api/chat/proxy 429 (Too Many Requests)
+Fetch failed loading: POST "https://three.ws/api/chat/proxy".
+```
+
+The request is the chat send-message proxy. Two distinct failures stack:
+
+- `402` — server rejecting because the caller has no funded plan / no credits / no payment method on file.
+- `429` — server rejecting because the caller has exceeded a rate limit (per-IP, per-user, or per-agent).
+
+## Cause
+
+The client treats both as opaque network errors. The user just sees the message fail with no explanation, and the call may retry into a 429 storm.
+
+## Task
+
+### Server side
+
+1. Find the proxy handler (search [api/](../../api/) for `chat/proxy` or the route that fronts the LLM provider).
+2. Make sure 402 and 429 responses include a JSON body the client can render:
+ - `402 { error: 'payment_required', reason: 'no_credits' | 'plan_required', upgradeUrl }`
+ - `429 { error: 'rate_limited', retryAfter: <seconds>, scope: 'ip' | 'user' | 'agent' }`
+3. Set the `Retry-After` header on 429 responses.
+
+### Client side
+
+1. Find the chat send call (search bundle source for `api/chat/proxy`).
+2. Branch on status:
+ - `402` → surface a clear "out of credits / upgrade" UI with the `upgradeUrl` from the body. Do not retry.
+ - `429` → respect `Retry-After` (or body's `retryAfter`), debounce the next attempt, and show a "slow down" hint to the user. Do not retry in a tight loop.
+ - Other 4xx → show the server's error message.
+ - 5xx → retry with backoff (max 2 attempts), then surface a generic failure.
+3. Disable the send button while a request is in flight so users can't queue duplicates that all hit the limiter.
+
+## Acceptance
+
+- A 402 from the proxy renders an actionable upgrade prompt, not a silent failure.
+- A 429 produces at most one user-visible message and one queued retry after `Retry-After`.
+- No uncaught promise rejection from `Fetch failed loading: POST .../api/chat/proxy`.
diff --git a/prompts/fix-console-errors/10-ses-and-autofocus-warnings.md b/prompts/fix-console-errors/10-ses-and-autofocus-warnings.md
new file mode 100644
index 000000000..2c0cedec3
--- /dev/null
+++ b/prompts/fix-console-errors/10-ses-and-autofocus-warnings.md
@@ -0,0 +1,33 @@
+# Quiet SES lockdown and autofocus warnings
+
+## Symptom
+
+```
+lockdown-install.js:1 SES Removing unpermitted intrinsics
+chat#:1 Autofocus processing was blocked because a document already has a focused element.
+```
+
+## Cause
+
+Both are **warnings, not errors**. They are documented here so a future engineer doesn't chase them as bugs.
+
+- `SES Removing unpermitted intrinsics` — emitted by Hardened JavaScript / Lockdown, almost always injected by a wallet browser extension (MetaMask, Rabby, Phantom, etc.). It tightens the realm at page load. Not from this app's code; cannot be silenced from the page.
+- `Autofocus processing was blocked` — Chrome refuses to honor a second `autofocus` attribute when another element already holds focus. Cosmetic.
+
+## Task
+
+### SES warning
+
+1. Confirm by loading `https://three.ws/chat` in a clean profile with no wallet extensions — the warning should disappear.
+2. No code change. Document it in the team's "known harmless console output" note so it isn't re-investigated.
+
+### Autofocus warning
+
+1. Find the offending element (search for `autofocus` in the chat page templates / components).
+2. Decide which input should actually receive focus on load. Remove `autofocus` from the others.
+3. If multiple inputs legitimately need focus depending on state, drive focus imperatively in `useEffect` / `connectedCallback` based on the active state, instead of declaring `autofocus` on all of them.
+
+## Acceptance
+
+- No `Autofocus processing was blocked` warning on chat page load.
+- The SES line is acknowledged as extension-induced and documented; not treated as a regression.
diff --git a/src/agent-resolver.js b/src/agent-resolver.js
index ddef32831..b0ec5507d 100644
--- a/src/agent-resolver.js
+++ b/src/agent-resolver.js
@@ -164,7 +164,7 @@ export async function resolveAgentById(
stt: { provider: 'browser' },
},
skills,
- memory: { mode: 'remote', namespace: agent.id },
+ memory: { mode: 'local', namespace: agent.id },
tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],
version: '0.1.0',
_baseURI: `${origin}/agent/${agent.id}/`,
diff --git a/src/element.js b/src/element.js
index 24cea469b..c2396bbba 100644
--- a/src/element.js
+++ b/src/element.js
@@ -374,6 +374,7 @@ class Agent3DElement extends HTMLElement {
}
_renderShell() {
+ if (this._loadingEl) return;
const style = document.createElement('style');
style.textContent = BASE_STYLE;
this.shadowRoot.appendChild(style);
@@ -809,6 +810,7 @@ class Agent3DElement extends HTMLElement {
async _boot() {
if (this._booting || this._mounted) return;
+ this._renderShell();
this._booting = true;
try {
this._loadingEl.hidden = false;
diff --git a/src/memory/index.js b/src/memory/index.js
index f350906f9..2bcd8a93f 100644
--- a/src/memory/index.js
+++ b/src/memory/index.js
@@ -33,19 +33,22 @@ function pack({ nonce, ciphertext }) {
}
export class Memory {
- constructor({ mode = 'local', namespace, index = {}, files = {}, timeline = [], cryptoKey = null } = {}) {
+ constructor({ mode = 'local', namespace, index = {}, files = {}, timeline = [], cryptoKey = null, remoteIds = {} } = {}) {
this.mode = mode;
this.namespace = namespace;
this.files = new Map(Object.entries(files));
this.timeline = timeline;
this.indexText = index.text || '';
this.cryptoKey = cryptoKey;
+ // remote mode: filename -> backend entry id, for upsert round-trip
+ this._remoteIds = new Map(Object.entries(remoteIds));
this._dirty = false;
}
static async load({ mode = 'local', namespace, manifestURI, fetchFn, deriveKey }) {
if (mode === 'none') return new Memory({ mode: 'none', namespace });
if (mode === 'local') return Memory._loadLocal(namespace);
+ if (mode === 'remote') return Memory._loadRemote({ namespace, fetchFn });
if (mode === 'ipfs' || mode === 'encrypted-ipfs') {
if (mode === 'encrypted-ipfs' && !deriveKey)
throw new Error('encrypted-ipfs mode requires a deriveKey function');
@@ -54,6 +57,32 @@ export class Memory {
throw new Error(`Unknown memory mode: ${mode}`);
}
+ static async _loadRemote({ namespace, fetchFn }) {
+ const f = fetchFn || fetch.bind(globalThis);
+ if (!namespace) return new Memory({ mode: 'remote', namespace });
+ try {
+ const resp = await f(`/api/agent-memory?agentId=${encodeURIComponent(namespace)}&limit=500`, {
+ credentials: 'include',
+ });
+ if (!resp.ok) return new Memory({ mode: 'remote', namespace });
+ const { entries } = await resp.json();
+ const files = {};
+ const remoteIds = {};
+ for (const entry of entries || []) {
+ const filename = entry.context?.filename
+ || (entry.id ? `${entry.id}.md` : null);
+ if (!filename) continue;
+ files[filename] = entry.content || '';
+ if (entry.id) remoteIds[filename] = entry.id;
+ }
+ const mem = new Memory({ mode: 'remote', namespace, files, remoteIds });
+ mem._rebuildIndex();
+ return mem;
+ } catch {
+ return new Memory({ mode: 'remote', namespace });
+ }
+ }
+
static _loadLocal(namespace) {
const key = `agent:${namespace}:memory`;
try {
@@ -132,10 +161,12 @@ export class Memory {
const created = existing ? parseFrontmatter(existing).meta.created || now : now;
const meta = { name, description, type, created, updated: now };
if (decay) meta.decay = decay;
- this.files.set(file, stringifyFrontmatter(meta, body || ''));
+ const raw = stringifyFrontmatter(meta, body || '');
+ this.files.set(file, raw);
this._rebuildIndex();
this._dirty = true;
this._persist();
+ if (this.mode === 'remote') this._remoteUpsert(file, type, raw);
}
note(type, data) {
@@ -226,6 +257,34 @@ export class Memory {
}
}
+ // Fire-and-forget upsert of one file to /api/agent-memory.
+ // Backend validates type ∈ {user, feedback, project, reference}; falls back to 'project'.
+ async _remoteUpsert(file, type, raw) {
+ if (!this.namespace) return;
+ const validTypes = ['user', 'feedback', 'project', 'reference'];
+ const memType = validTypes.includes(type) ? type : 'project';
+ const entry = {
+ type: memType,
+ content: raw,
+ context: { filename: file },
+ };
+ const existingId = this._remoteIds.get(file);
+ if (existingId) entry.id = existingId;
+ try {
+ const resp = await fetch('/api/agent-memory', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ agentId: this.namespace, entry }),
+ });
+ if (!resp.ok) return;
+ const { entry: saved } = await resp.json();
+ if (saved?.id) this._remoteIds.set(file, saved.id);
+ } catch {
+ // network unavailable — in-memory state is the fallback
+ }
+ }
+
// Encrypt all files and pin to IPFS. Returns { cids, memoryCid }.
// For local mode, falls back to synchronous _persist(). Noop for other modes.
async save() {
@@ -233,6 +292,14 @@ export class Memory {
this._persist();
return;
}
+ if (this.mode === 'remote') {
+ for (const [file, raw] of this.files) {
+ const { meta } = parseFrontmatter(raw);
+ await this._remoteUpsert(file, meta.type, raw);
+ }
+ this._dirty = false;
+ return;
+ }
if (this.mode !== 'encrypted-ipfs') return;
if (!this.cryptoKey) throw new Error('No cryptoKey — derive key before calling save()');
if (!this.namespace) throw new Error('namespace required for encrypted-ipfs save');