Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(companion): deliver important messages in person through the corner avatar

nirholas4f2f91b88c2a
diff --git a/CLAUDE.md b/CLAUDE.md
index 429564883..b0b42fb77 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -305,7 +305,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.
- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).
- 3D: Three.js with glTF/GLB.
- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.
-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (108 as of 2026-08-14, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (109 as of 2026-08-28, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).
- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.
- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 1f28b464e..fdc13ff5a 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -52,7 +52,7 @@ bottom.
| Agent Symphony (economy as generative music) | [pages/symphony.html](pages/symphony.html) `→ /symphony`, engine [src/symphony.js](src/symphony.js), grammar [src/symphony-score.js](src/symphony-score.js) | Live | The live activity bus (`GET /api/feed` + `/api/feed-stream` SSE) rendered as WebAudio generative music: one synthesized note per real platform event, voice by event type (payments pluck, coin buys land as bass, new agents chime, guard refusals play dissonance, jackpots glissando), pitch register by amount (whales sit lower), stable per-actor motif + stereo position via FNV-1a hash, all quantized to one pentatonic scale so arbitrary event streams harmonize. Canvas visualization, live ledger with real click-throughs, and a MediaRecorder tap that exports a shareable audio clip of the master bus. A burst gate collapses event floods (a sniper sweep emitting dozens of identical guard events) into one accented note per actor per 1.5s. Solo mode narrows the stream to one participant client-side (`?agent=<id>` exact, `?actor=<label>` case-insensitive), reachable from the per-row "solo" control and from the "Listen →" link on every agent profile's Wallet Story card. No audio assets, no synthetic events. Tests: [tests/symphony-score.test.js](tests/symphony-score.test.js) |
| Platform activity feed | [pages/feed.html](pages/feed.html) `→ /feed` + [pages/community.html](pages/community.html) `→ /community`, backend [api/users/me/feed.js](api/users/me/feed.js) | Live | Reverse-chronological creation events (avatars, agents, coins, models, worlds) plus follow activity, merged at read time from `forge_creations`, `dioramas`, and `user_follows` (no separate event log to drift out of sync). `?scope=following` (default; session-gated, anonymous gets 401) vs `?scope=all` (public; powers `/community` and first-visit feeds); `limit` 1..50, `before` ISO cursor. Items deep-link to creator portfolios. Distinct from the Money Pulse ticker `GET /api/feed` ([docs/money-feed.md](docs/money-feed.md)). Docs: [docs/social-layer.md](docs/social-layer.md) |
| Follow graph | [api/users/[username]/follow.js](api/users/%5Busername%5D/follow.js) + [api/users/[username]/follows.js](api/users/%5Busername%5D/follows.js), table `user_follows`, buttons on [pages/profile.html](pages/profile.html) | Live | `GET` returns `{following, followed_by, followers_count, following_count}`; `POST`/`DELETE` are idempotent (session + CSRF, self-follow 400) and return the same envelope so one round-trip updates the button and the counts. A genuinely new edge (`ON CONFLICT DO NOTHING`) publishes a `follow` user event to the notification bell exactly once. Feeds the activity feed's following scope, search ranking, and the `followers` leaderboard metric. Tests: [tests/api/users-follow.test.js](tests/api/users-follow.test.js). Docs: [docs/social-layer.md](docs/social-layer.md) |
-| Notification bell & preferences | Event vocabulary [api/_lib/feed.js](api/_lib/feed.js) (`USER_EVENT_TYPES` → `publishUserEvent()` → `user_notifications`), endpoints [api/notifications/](api/notifications), preference matrix [api/_lib/notify-prefs.js](api/_lib/notify-prefs.js), bell client [src/notifications.js](src/notifications.js), settings panel [src/dashboard-next/pages/settings.js](src/dashboard-next/pages/settings.js) | Live | In-app inbox covering remixes ([api/x402/remix-asset.js](api/x402/remix-asset.js)), DMs ([api/friends/messages.js](api/friends/messages.js)), coin bonding-curve graduations (pump cron in [api/cron/[name].js](api/cron/%5Bname%5D.js)), follows, sales, purchases, IRL, market, and account events. Preferences are a category × channel matrix (`in_app` always on; push/email/telegram are per-category opt-outs) edited from `/dashboard/settings`. Docs: [docs/social-layer.md](docs/social-layer.md) |
+| Notification bell & preferences | Event vocabulary [api/_lib/feed.js](api/_lib/feed.js) (`USER_EVENT_TYPES` → `publishUserEvent()` → `user_notifications`), endpoints [api/notifications/](api/notifications), preference matrix [api/_lib/notify-prefs.js](api/_lib/notify-prefs.js), bell client [src/notifications.js](src/notifications.js), avatar announcements [src/notification-herald.js](src/notification-herald.js), settings panel [src/dashboard-next/pages/settings.js](src/dashboard-next/pages/settings.js) | Live | In-app inbox covering remixes ([api/x402/remix-asset.js](api/x402/remix-asset.js)), DMs ([api/friends/messages.js](api/friends/messages.js)), coin bonding-curve graduations (pump cron in [api/cron/[name].js](api/cron/%5Bname%5D.js)), follows, sales, purchases, IRL, market, and account events. Preferences are a category × channel matrix (`in_app` always on; push/email/telegram/avatar are per-category opt-outs) edited from `/dashboard/settings`. **The `avatar` channel delivers in person:** for a fresh, unread notification in an opted-in category the corner companion walks on screen, gestures, and says the line with a link straight to it, summoning itself for that one message and retreating if it was off ([walk-sdk](walk-sdk) `control.announce`). Rules (15-minute freshness, once per browser, two per batch, visible tab only, device-level mute) live in [src/notification-herald.js](src/notification-herald.js). Docs: [docs/notifications.md](docs/notifications.md), [docs/social-layer.md](docs/social-layer.md). Tests: [tests/notification-herald.test.js](tests/notification-herald.test.js), [tests/notify-prefs.test.js](tests/notify-prefs.test.js) |
| Prepaid credits (`/credits`) | [pages/credits.html](pages/credits.html) `→ /credits` + [src/credits.js](src/credits.js), balance/ledger [api/credits/index.js](api/credits/index.js) `→ GET /api/credits`, deposit verifier [api/credits/deposit.js](api/credits/deposit.js) `→ POST /api/credits/deposit` over [api/_lib/credit-deposit.js](api/_lib/credit-deposit.js), ledger engine [api/_lib/credits.js](api/_lib/credits.js), schema [api/_lib/migrations/20260621200000_credits.sql](api/_lib/migrations/20260621200000_credits.sql) | Live | The prepaid balance every metered action on the platform debits. Top up by sending SOL or $THREE to the platform deposit wallet (connect + SIWS-link + sign in the page, or paste a signature you already sent); crediting is server-authoritative and idempotent on the signature, so a signature that is not signed by a wallet linked to the account credits nobody. The page renders the caller's $THREE holder tier from the same `holder` block [api/pricing.js](api/pricing.js) returns ([api/_lib/three-tier.js](api/_lib/three-tier.js)), which is the discount [api/_lib/credits.js](api/_lib/credits.js) already applies to every debit, and lists what credits buy straight from the pricing catalog ([api/_lib/pricing/catalog.js](api/_lib/pricing/catalog.js)). Ledger is keyset-paginated. Docs: [docs/payment-sessions.md](docs/payment-sessions.md). Tests: [tests/credits.test.js](tests/credits.test.js) |
| Skill bundles (seller builder + evidence pricing) | [pages/bundles.html](pages/bundles.html) `→ /bundles`, API [api/agents/[id]/bundles.js](api/agents/%5Bid%5D/bundles.js), arithmetic [api/_lib/bundle-pricing.js](api/_lib/bundle-pricing.js), checkout [api/marketplace/purchase-bundle.js](api/marketplace/purchase-bundle.js) | Live (seller side); no buyer-facing browser view yet | Sell several of one agent's skills as one purchase. The price is derived from the agent's own ledger rather than a rule of thumb: the public `?action=pricing` endpoint finds every buyer who already bought 2+ of the selected skills, suggests the median of what they really paid (`basis: median_basket`), and backtests any candidate price against those same baskets; with no such buyer yet it falls back to 20% off the sum of the parts and labels itself `discount_off_list` so a default is never read as a finding. Every amount is an atomic integer carried as a BigInt end to end, because a 9-decimal mint puts real sums past `Number.MAX_SAFE_INTEGER`. Checkout settles on-chain and writes one `skill_purchases` row per skill (`kind = 'bundle'`, amount 0) so one bundle sale is never counted as N skill sales. Docs: [docs/skill-bundles.md](docs/skill-bundles.md). Tests: [tests/bundle-pricing.test.js](tests/bundle-pricing.test.js), [tests/vercel-agents-subpath-routes.test.js](tests/vercel-agents-subpath-routes.test.js) |
| Marketplace analytics & trial funnel | [pages/marketplace-analytics.html](pages/marketplace-analytics.html) `→ /marketplace/analytics`, renderer [src/marketplace-analytics.js](src/marketplace-analytics.js), backend [api/marketplace/analytics.js](api/marketplace/analytics.js) | Live | Public transparency page for the skill marketplace: paid sales, volume, top skills/agents, and the trial conversion funnel. **Every money aggregate gates on `status = 'confirmed'` alone.** Counting `status IN ('confirmed','trial')` as a sale published 10,454 "sales" and 6.2M $THREE of "volume" on 2026-07-30 against a table holding zero confirmed purchases, because a `trial` row is a free grant whose `amount` is only the list price it would have cost. Free trials now render as their own stat and as a four-stage funnel (granted → used → exhausted → converted), which also names the two shapes that mean a wiring fault rather than weak demand: trials never spent, or trials exhausted with nothing converting. Docs: [docs/marketplace.md](docs/marketplace.md), tutorial [docs/tutorials/sell-a-skill-with-a-trial.md](docs/tutorials/sell-a-skill-with-a-trial.md). Tests: [tests/marketplace-analytics-paid-only.test.js](tests/marketplace-analytics-paid-only.test.js) |
diff --git a/api/_lib/companion/lanes/calendar.js b/api/_lib/companion/lanes/calendar.js
index f72e5c2c3..b5b82c1ec 100644
--- a/api/_lib/companion/lanes/calendar.js
+++ b/api/_lib/companion/lanes/calendar.js
@@ -69,30 +69,18 @@ function durationMinutes(event) {
return Number.isFinite(mins) && mins > 0 ? Math.round(mins) : null;
}
-export async function verifyCalendar(config) {
- const text = await fetchIcs(config.ics_url);
- const parsed = ical.sync.parseICS(text);
- const events = Object.values(parsed).filter((e) => e.type === 'VEVENT');
- const name = Object.values(parsed).find((e) => e.type === 'VCALENDAR')?.['WR-CALNAME'] || null;
- return {
- detail: `Read ${events.length} event${events.length === 1 ? '' : 's'} from ${name || 'the feed'}.`,
- calendar_name: name,
- event_count: events.length,
- };
-}
-
/**
- * Announce anything starting inside the lookahead window.
- * @returns {{ items: Array, cursor: object }}
+ * Everything in the feed that starts inside the window, as lane items.
+ * Pure: it takes the ICS text and a clock, so the announcement rules are
+ * testable without a network (tests/companion-calendar.test.js).
+ *
+ * @param {string} text raw iCalendar document
+ * @param {{ now?: number, lookaheadMinutes?: number }} [opts]
*/
-export async function pollCalendar({ config, cursor = {} }) {
- const lookahead = Math.min(720, Math.max(5, Number(config.lookahead_minutes) || DEFAULT_LOOKAHEAD_MIN));
- const text = await fetchIcs(config.ics_url);
+export function eventsFromIcs(text, { now = Date.now(), lookaheadMinutes = DEFAULT_LOOKAHEAD_MIN } = {}) {
const parsed = ical.sync.parseICS(text);
-
- const now = Date.now();
const from = new Date(now - GRACE_MIN * 60_000);
- const to = new Date(now + lookahead * 60_000);
+ const to = new Date(now + lookaheadMinutes * 60_000);
const items = [];
for (const event of Object.values(parsed)) {
@@ -119,6 +107,28 @@ export async function pollCalendar({ config, cursor = {} }) {
});
}
}
+ return items;
+}
+export async function verifyCalendar(config) {
+ const text = await fetchIcs(config.ics_url);
+ const parsed = ical.sync.parseICS(text);
+ const events = Object.values(parsed).filter((e) => e.type === 'VEVENT');
+ const name = Object.values(parsed).find((e) => e.type === 'VCALENDAR')?.['WR-CALNAME'] || null;
+ return {
+ detail: `Read ${events.length} event${events.length === 1 ? '' : 's'} from ${name || 'the feed'}.`,
+ calendar_name: name,
+ event_count: events.length,
+ };
+}
+
+/**
+ * Announce anything starting inside the lookahead window.
+ * @returns {{ items: Array, cursor: object }}
+ */
+export async function pollCalendar({ config, cursor = {} }) {
+ const lookahead = Math.min(720, Math.max(5, Number(config.lookahead_minutes) || DEFAULT_LOOKAHEAD_MIN));
+ const text = await fetchIcs(config.ics_url);
+ const items = eventsFromIcs(text, { lookaheadMinutes: lookahead });
return { items, cursor: { ...cursor, last_fetch: new Date().toISOString(), lookahead_minutes: lookahead } };
}
diff --git a/api/companion/contacts/[id].js b/api/companion/contacts/[id].js
new file mode 100644
index 000000000..a827a667f
--- /dev/null
+++ b/api/companion/contacts/[id].js
@@ -0,0 +1,27 @@
+// DELETE /api/companion/contacts/:id → forget a contact. Messages already
+// stored keep their text; they simply stop being attributed to that person.
+
+import { getRequestUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { deleteContact } from '../../_lib/companion/store.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['DELETE'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const rl = await limits.companionWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const id = String(req.query?.id || '').trim();
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return error(res, 400, 'validation_error', 'invalid contact id');
+
+ const removed = await deleteContact(user.id, id);
+ if (!removed) return error(res, 404, 'not_found', 'no such contact');
+ return json(res, 200, { deleted: true });
+});
diff --git a/api/companion/contacts/index.js b/api/companion/contacts/index.js
new file mode 100644
index 000000000..a852f20b4
--- /dev/null
+++ b/api/companion/contacts/index.js
@@ -0,0 +1,45 @@
+// GET /api/companion/contacts → the people the companion knows.
+// POST /api/companion/contacts → add or update one (upsert on the identity).
+//
+// A contact is what turns "a message arrived" into "Sarah is at the door": it
+// carries the display name, the avatar that delivers her messages, the voice it
+// speaks in, and how much her messages outrank everything else.
+
+import { z } from 'zod';
+import { getRequestUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { listContacts, upsertContact } from '../../_lib/companion/store.js';
+import { TTS_VOICE_IDS } from '../../_lib/tts-voices.js';
+
+const contactBody = z.object({
+ identifier: z.string().min(1).max(320),
+ display_name: z.string().min(1).max(80),
+ avatar_glb_url: z.string().url().max(2048).nullable().optional(),
+ avatar_image_url: z.string().url().max(2048).nullable().optional(),
+ voice: z.enum(TTS_VOICE_IDS).nullable().optional(),
+ priority_boost: z.number().int().min(-100).max(100).optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ if (req.method === 'GET') {
+ const rl = await limits.companionRead(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+ return json(res, 200, { contacts: await listContacts(user.id) });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const rl = await limits.companionWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = parse(contactBody, await readJson(req));
+ return json(res, 200, { contact: await upsertContact(user.id, body) });
+});
diff --git a/api/companion/events/[id].js b/api/companion/events/[id].js
new file mode 100644
index 000000000..c2a5be14d
--- /dev/null
+++ b/api/companion/events/[id].js
@@ -0,0 +1,37 @@
+// PATCH /api/companion/events/:id { delivered?, dismissed? }
+//
+// The companion marks an event delivered once it has actually said it out loud,
+// so a message spoken on a laptop is not repeated by the phone an hour later.
+
+import { z } from 'zod';
+import { getRequestUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { markEvent } from '../../_lib/companion/store.js';
+
+const patchBody = z.object({
+ delivered: z.boolean().optional(),
+ dismissed: z.boolean().optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'PATCH,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['PATCH'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const rl = await limits.companionRead(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const id = String(req.query?.id || '').trim();
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return error(res, 400, 'validation_error', 'invalid event id');
+
+ const body = parse(patchBody, await readJson(req));
+ const row = await markEvent(user.id, id, { delivered: body.delivered === true, dismissed: body.dismissed === true });
+ if (!row) return error(res, 404, 'not_found', 'no such event');
+ return json(res, 200, { event: row });
+});
diff --git a/api/companion/events/index.js b/api/companion/events/index.js
new file mode 100644
index 000000000..88cd82775
--- /dev/null
+++ b/api/companion/events/index.js
@@ -0,0 +1,42 @@
+// GET /api/companion/events → the triaged feed.
+//
+// Query:
+// limit=<1-50> page size (default 30)
+// before=<iso timestamp> cursor for "load more"
+// pending=1 only what has not been delivered or dismissed
+// min_importance=<0-100> floor, for the "only the loud ones" view
+
+import { getRequestUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { listEvents, getSettings } from '../../_lib/companion/store.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.companionRead(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const limitRaw = Number.parseInt(params.get('limit') || '30', 10);
+ const limit = Number.isFinite(limitRaw) ? Math.min(50, Math.max(1, limitRaw)) : 30;
+ const beforeRaw = params.get('before');
+ const before = beforeRaw && !Number.isNaN(Date.parse(beforeRaw)) ? new Date(beforeRaw) : null;
+ const minRaw = Number.parseInt(params.get('min_importance') || '0', 10);
+ const minImportance = Number.isFinite(minRaw) ? Math.min(100, Math.max(0, minRaw)) : 0;
+
+ const [events, settings] = await Promise.all([
+ listEvents(user.id, { limit, before, pendingOnly: params.get('pending') === '1', minImportance }),
+ getSettings(user.id),
+ ]);
+
+ return json(res, 200, {
+ events,
+ threshold: settings.threshold,
+ has_more: events.length === limit,
+ });
+});
diff --git a/api/companion/ingest.js b/api/companion/ingest.js
new file mode 100644
index 000000000..ea48a28e3
--- /dev/null
+++ b/api/companion/ingest.js
@@ -0,0 +1,114 @@
+// POST /api/companion/ingest - the phone and desktop bridge.
+//
+// This is the lane that needs no provider integration at all: anything that can
+// make an HTTP request can hand the companion a message. An iOS Shortcuts
+// automation on "when I receive a notification", a Tasker/MacroDroid profile on
+// Android, a macOS Mail rule or a shell script, an Apps Script trigger on a
+// Gmail label, a Zapier/n8n step. The recipes are in docs/companion.md.
+//
+// Auth is the per-user bridge token (Authorization: Bearer, or `token` in the
+// body for senders that cannot set headers). It is not a session, so there is
+// no CSRF surface: the token IS the credential, and rotating it in the UI
+// revokes every device at once.
+//
+// Body: {
+// title: string (required) what the notification says
+// body: string (optional) the longer text
+// sender: string (optional) display name, matched against contacts
+// sender_id: string (optional) handle / address / number, matched first
+// app: string (optional) which app it came from, e.g. "Messages"
+// url: string (optional) somewhere to open
+// id: string (optional) sender-side id, for exact dedupe
+// priority: "high" | "normal" | "low" (optional) the device's own verdict
+// occurred_at: ISO timestamp (optional)
+// }
+
+import { createHash } from 'node:crypto';
+import { z } from 'zod';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { userForIngestToken } from '../_lib/companion/store.js';
+import { ingestItem } from '../_lib/companion/poll.js';
+
+const ingestBody = z.object({
+ token: z.string().min(8).max(200).optional(),
+ title: z.string().min(1).max(300),
+ body: z.string().max(4000).optional(),
+ sender: z.string().max(200).optional(),
+ sender_id: z.string().max(320).optional(),
+ app: z.string().max(80).optional(),
+ url: z.string().url().max(2048).optional(),
+ id: z.string().max(200).optional(),
+ priority: z.enum(['high', 'normal', 'low']).optional(),
+ occurred_at: z.string().max(64).optional(),
+});
+
+function bearerFrom(req) {
+ const header = req.headers.authorization || '';
+ const match = /^Bearer\s+(.+)$/i.exec(String(header).trim());
+ return match ? match[1].trim() : null;
+}
+
+// A device that retries a failed POST must not produce a second delivery, and
+// most notification forwarders carry no id of their own. Hashing the content
+// plus the minute it arrived makes a retry idempotent without making two
+// genuinely identical messages an hour apart collapse into one.
+function externalIdFor(body) {
+ if (body.id) return `bridge:${body.id.slice(0, 160)}`;
+ const minute = new Date().toISOString().slice(0, 16);
+ const digest = createHash('sha256')
+ .update([body.app || '', body.sender || '', body.sender_id || '', body.title, body.body || '', minute].join(' '))
+ .digest('hex')
+ .slice(0, 32);
+ return `bridge:${digest}`;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const raw = await readJson(req);
+ const body = parse(ingestBody, raw);
+ const token = bearerFrom(req) || body.token;
+ if (!token) return error(res, 401, 'unauthorized', 'send your bridge token as an Authorization: Bearer header');
+
+ const rl = await limits.companionIngest(token);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const settings = await userForIngestToken(token);
+ if (!settings) return error(res, 401, 'unauthorized', 'unknown bridge token, check /companion for the current one');
+
+ const occursAt = body.occurred_at && !Number.isNaN(Date.parse(body.occurred_at))
+ ? new Date(body.occurred_at).toISOString()
+ : null;
+
+ const stored = await ingestItem(settings, {
+ source_kind: 'bridge',
+ external_id: externalIdFor(body),
+ sender: body.sender || body.app || 'Your phone',
+ sender_id: body.sender_id || null,
+ identity_candidates: [body.sender_id, body.sender].filter(Boolean),
+ title: body.app && body.sender ? `${body.sender} (${body.app})` : body.title,
+ body: body.body || (body.app && body.sender ? body.title : null),
+ url: body.url || null,
+ occurs_at: occursAt,
+ priority_hint: body.priority || null,
+ });
+
+ // A duplicate is a success from the sender's point of view: the message did
+ // reach the companion, just not for the first time.
+ if (!stored) return json(res, 200, { accepted: true, duplicate: true });
+
+ return json(res, 201, {
+ accepted: true,
+ duplicate: false,
+ event: {
+ id: stored.id,
+ importance: stored.importance,
+ reason: stored.reason,
+ line: stored.spoken_line,
+ delivered: stored.delivered === true,
+ },
+ });
+});
diff --git a/api/companion/poll.js b/api/companion/poll.js
new file mode 100644
index 000000000..6a6a1bc67
--- /dev/null
+++ b/api/companion/poll.js
@@ -0,0 +1,27 @@
+// POST /api/companion/poll - "check now" for every connected source.
+//
+// The cron already sweeps on a schedule (api/cron/companion-poll.js); this is
+// the button on the setup page, so a user who just connected something sees it
+// work in the same breath rather than waiting for the next tick.
+
+import { getRequestUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits } from '../_lib/rate-limit.js';
+import { pollUser } from '../_lib/companion/poll.js';
+
+export const maxDuration = 60;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const rl = await limits.companionPoll(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ return json(res, 200, await pollUser(user.id));
+});
diff --git a/api/companion/sources/[id].js b/api/companion/sources/[id].js
new file mode 100644
index 000000000..926a83608
--- /dev/null
+++ b/api/companion/sources/[id].js
@@ -0,0 +1,53 @@
+// PATCH /api/companion/sources/:id → rename, enable/disable.
+// DELETE /api/companion/sources/:id → disconnect (credentials are dropped).
+// POST /api/companion/sources/:id → poll it right now ("check now").
+
+import { z } from 'zod';
+import { getRequestUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { getSource, updateSource, deleteSource } from '../../_lib/companion/store.js';
+import { pollSource } from '../../_lib/companion/poll.js';
+
+const patchBody = z.object({
+ label: z.string().min(1).max(80).optional(),
+ enabled: z.boolean().optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'PATCH,DELETE,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['PATCH', 'DELETE', 'POST'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const id = String(req.query?.id || '').trim();
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return error(res, 400, 'validation_error', 'invalid source id');
+
+ if (req.method === 'DELETE') {
+ const rl = await limits.companionWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+ const removed = await deleteSource(user.id, id);
+ if (!removed) return error(res, 404, 'not_found', 'no such source');
+ return json(res, 200, { deleted: true });
+ }
+
+ if (req.method === 'PATCH') {
+ const rl = await limits.companionWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+ const patch = parse(patchBody, await readJson(req));
+ const source = await updateSource(user.id, id, patch);
+ if (!source) return error(res, 404, 'not_found', 'no such source');
+ return json(res, 200, { source });
+ }
+
+ const rl = await limits.companionPoll(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+ const source = await getSource(user.id, id);
+ if (!source) return error(res, 404, 'not_found', 'no such source');
+ const result = await pollSource(source);
+ return json(res, result.ok ? 200 : 502, result);
+});
diff --git a/api/companion/sources/index.js b/api/companion/sources/index.js
new file mode 100644
index 000000000..0e6020b36
--- /dev/null
+++ b/api/companion/sources/index.js
@@ -0,0 +1,111 @@
+// GET /api/companion/sources → every connected source (credentials redacted).
+// POST /api/companion/sources → connect one.
+//
+// A new connection is verified against the real provider BEFORE it is stored,
+// so a wrong bot token or an ICS URL that points at an HTML page is reported
+// while the user is still looking at the form rather than failing silently on a
+// cron run three minutes later.
+
+import { z } from 'zod';
+import { getRequestUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { listSources, createSource } from '../../_lib/companion/store.js';
+import { laneFor } from '../../_lib/companion/poll.js';
+import { normalizeIcsUrl } from '../../_lib/companion/lanes/calendar.js';
+import { SsrfError } from '../../_lib/ssrf.js';
+
+const telegramConfig = z.object({
+ kind: z.literal('telegram'),
+ label: z.string().min(1).max(80).optional(),
+ bot_token: z.string().min(20).max(200),
+});
+
+const calendarConfig = z.object({
+ kind: z.literal('calendar'),
+ label: z.string().min(1).max(80).optional(),
+ ics_url: z.string().min(8).max(2048),
+ lookahead_minutes: z.number().int().min(5).max(720).optional(),
+});
+
+const emailConfig = z.object({
+ kind: z.literal('email'),
+ label: z.string().min(1).max(80).optional(),
+ host: z.string().min(3).max(255),
+ port: z.number().int().min(1).max(65535).optional(),
+ secure: z.boolean().optional(),
+ user: z.string().min(1).max(320),
+ pass: z.string().min(1).max(512),
+ folder: z.string().min(1).max(120).optional(),
+});
+
+const createBody = z.discriminatedUnion('kind', [telegramConfig, calendarConfig, emailConfig]);
+
+const DEFAULT_LABEL = {
+ telegram: 'Telegram',
+ calendar: 'Calendar',
+ email: 'Email',
+};
+
+function configFor(body) {
+ if (body.kind === 'telegram') return { bot_token: body.bot_token };
+ if (body.kind === 'calendar') {
+ return {
+ ics_url: normalizeIcsUrl(body.ics_url),
+ lookahead_minutes: body.lookahead_minutes || 30,
+ };
+ }
+ return {
+ host: body.host.trim(),
+ port: body.port || 993,
+ secure: body.secure !== false,
+ user: body.user.trim(),
+ pass: body.pass,
+ folder: body.folder || 'INBOX',
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ if (req.method === 'GET') {
+ const rl = await limits.companionRead(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+ return json(res, 200, { sources: await listSources(user.id) });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const rl = await limits.companionPoll(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = parse(createBody, await readJson(req));
+ const config = configFor(body);
+ const lane = laneFor(body.kind);
+
+ let verification;
+ try {
+ verification = await lane.verify(config);
+ } catch (err) {
+ if (err instanceof SsrfError) {
+ return error(res, 400, 'source_unreachable', 'that URL is not a public address we can fetch');
+ }
+ return error(res, 400, 'source_unreachable', String(err?.message || err).slice(0, 300));
+ }
+
+ // Telegram's own answer names the bot, which is what the setup card shows
+ // next to the connection ("message @your_bot").
+ const stored = { ...config, ...(verification.bot_username ? { bot_username: verification.bot_username } : {}) };
+ const source = await createSource(user.id, {
+ kind: body.kind,
+ label: body.label || verification.calendar_name || DEFAULT_LABEL[body.kind],
+ config: stored,
+ });
+
+ return json(res, 201, { source, verification });
+});
diff --git a/api/cron/companion-poll.js b/api/cron/companion-poll.js
new file mode 100644
index 000000000..d41b760e0
--- /dev/null
+++ b/api/cron/companion-poll.js
@@ -0,0 +1,25 @@
+// GET /api/cron/companion-poll - the sweep that keeps every companion current.
+//
+// Polls the least recently checked sources across every account inside a
+// wall-clock budget. Anything the budget does not reach keeps its old
+// last_polled_at, so it sorts to the front of the next tick: a slow IMAP server
+// can delay itself, never everyone else.
+
+import { cors, json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { pollDue } from '../_lib/companion/poll.js';
+
+export const maxDuration = 120;
+
+const BATCH_LIMIT = Number(process.env.COMPANION_POLL_BATCH) || 40;
+const TIME_BUDGET_MS = 100_000;
+
+export default wrapCron(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ if (!requireCron(req, res)) return;
+
+ const started = Date.now();
+ const summary = await pollDue({ limit: BATCH_LIMIT, budgetMs: TIME_BUDGET_MS });
+ return json(res, 200, { ok: true, ...summary, ms: Date.now() - started });
+});
diff --git a/api/notifications/README.md b/api/notifications/README.md
index 6342ba44f..0e6fcc745 100644
--- a/api/notifications/README.md
+++ b/api/notifications/README.md
@@ -14,8 +14,8 @@ Every route requires authentication and answers `401 { "error": "unauthorized" }
| `POST /api/notifications/:id/read` | Mark a single notification as read | Idempotent (`read_at = coalesce(read_at, now())`); returns `{ id, read_at }`, 400 if `:id` is not a uuid, 404 if the row is not the caller's. Handler: [`[id]/read.js`](./%5Bid%5D/read.js) |
| `DELETE /api/notifications/:id` | Permanently remove one notification | The bell's dismiss action and the MCP `delete_notification` tool; returns `{ ok, id, deleted }`. Handler: [`[id]/index.js`](./%5Bid%5D/index.js) |
| `POST /api/notifications/read-all` | Mark every unread notification as read | Returns `{ marked_read: <count> }` |
-| `POST /api/notifications/track` | Record a re-engagement funnel event | Body `{ notification_id?, channel: 'push'\|'in_app', event: 'opened'\|'returned' }`. Closes the sent-to-opened-to-returned loop: the service worker ([`public/push-sw.js`](../../public/push-sw.js)) fires `opened` on push click, the app fires `returned` when it boots from `?source=push`. Session-auth only, CSRF-exempt idempotent beacon (deduped by a partial unique index); `sent` rows are written server-side by [`../_lib/notify.js`](../_lib/notify.js) |
-| `GET /api/notifications/preferences` | Read the full resolved preference matrix | Returns `{ categories, channels, prefs, push: { subscribed_devices } }`, everything the settings UI renders from |
+| `POST /api/notifications/track` | Record a re-engagement funnel event | Body `{ notification_id?, channel: 'push'\|'in_app'\|'avatar', event: 'opened'\|'returned' }`. Closes the sent-to-opened-to-returned loop: the service worker ([`public/push-sw.js`](../../public/push-sw.js)) fires `opened` on push click, the corner companion ([`../../src/notification-herald.js`](../../src/notification-herald.js)) fires `opened` on a click-through from a line it announced, and the app fires `returned` when it boots from `?source=push`. Session-auth only, CSRF-exempt idempotent beacon (deduped by a partial unique index); `sent` rows are written server-side by [`../_lib/notify.js`](../_lib/notify.js) |
+| `GET /api/notifications/preferences` | Read the full resolved preference matrix | Returns `{ categories, channels, type_categories, prefs, push: { subscribed_devices } }`, everything the settings UI renders from. `type_categories` is the server's type-to-category map, shipped so browser clients (the avatar channel) resolve a category without a request per notification |
| `PUT /api/notifications/preferences` | Save preference overrides | Body `{ categories: { <cat>: { <channel>: bool } }, telegram_chat_id? }`; sanitised sparse overlay, unknown keys dropped, returns the re-resolved matrix. **Partial:** the body merges onto what is stored, so a key you omit keeps its saved value. Send `telegram_chat_id: null` (or `''`) to disconnect Telegram deliberately. A malformed body is a 400 that writes nothing, never a silent reset |
## The preference matrix
@@ -23,7 +23,7 @@ Every route requires authentication and answers `401 { "error": "unauthorized" }
Defaults and resolution live in [`../_lib/notify-prefs.js`](../_lib/notify-prefs.js), the shared module both `preferences.js` and the delivery pipeline import:
- `CATEGORIES`: the seven user-facing groups every notification type maps into: `sales`, `purchases`, `social`, `irl`, `alerts`, `creations`, `account` (each with a label and description for the UI). `categoryForType()` maps any notification `type` to its category; unmapped types fall back to `account` so a new type is never silently undeliverable.
-- `CHANNELS`: `in_app` (the bell inbox, on by default for every category), `push` (Web Push, on by default but only reaches users who subscribed a device), `email` (defaults on only for money and security categories), `telegram` (opt-in, needs a linked chat id).
+- `CHANNELS`: `in_app` (the bell inbox, on by default for every category), `push` (Web Push, on by default but only reaches users who subscribed a device), `email` (defaults on only for money and security categories), `telegram` (opt-in, needs a linked chat id), `avatar` (the corner companion walks on screen and delivers the line, defaults on for money, finished creations, and account events; delivered client-side by [`../../src/notification-herald.js`](../../src/notification-herald.js), which owns the freshness, dedupe and batch rules).
- `resolvePrefs(userId)` overlays the user's stored sparse prefs (table `notification_preferences`) onto the defaults, so a user who has never saved gets a sensible matrix and new categories appear automatically. `channelEnabled(prefs, type, channel)` is the single delivery gate the send path consults.
- `readStoredPrefs(userId)` returns that stored sparse row untouched, without the defaults overlaid. The `PUT` merges onto it rather than onto the resolved matrix, so saving one category never freezes today's defaults for every other category into the row.
diff --git a/data/changelog.json b/data/changelog.json
index 9e1173651..d0ad39e6a 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-28",
+ "title": "Your agent now tells you the important things in person",
+ "summary": "Notifications no longer wait behind a badge. When something worth stopping for lands while you are on the site (a sale, money in, a 3D generation finishing, anything touching your account), your corner companion turns to you, plays a gesture, and says it out loud with a link straight to it. If the companion is switched off it is summoned for that one message and walks off again, without turning itself back on. It is a real delivery channel next to in-app, push, email and Telegram: toggle it per category in Settings, and there is a Turn off control in the bubble that silences it in that browser instantly. It only ever announces unread notifications under fifteen minutes old, says each one exactly once, caps itself at two per visit, and never speaks into a background tab. Nothing is spoken aloud unless you already turned on the companion's voice; otherwise it is text in the bubble, which screen readers announce too.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/notifications"
+ },
{
"date": "2026-08-28",
"title": "Next on the roadmap: your agent on your home screen",
diff --git a/data/pages.json b/data/pages.json
index 69eade889..5cdf054bb 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -250,6 +250,15 @@
"changefreq": "weekly",
"added": "2026-06-17"
},
+ {
+ "path": "/companion",
+ "title": "Companion",
+ "description": "A 3D companion that delivers your important messages in person. Connect your own Telegram bot, calendar, inbox, or phone, give each contact their own avatar and voice, and hear only what clears your bar.",
+ "priority": 0.7,
+ "changefreq": "weekly",
+ "added": "2026-08-28",
+ "showcase": true
+ },
{
"path": "/notifications",
"title": "Notifications",
diff --git a/docs/notifications.md b/docs/notifications.md
index 3fbdaf989..cef47ccae 100644
--- a/docs/notifications.md
+++ b/docs/notifications.md
@@ -15,6 +15,7 @@ this page picks up where that one leaves off.
| Bell dropdown | The bell button in the header, on every page | [src/notifications.js](../src/notifications.js) |
| Notification center | [/notifications](https://three.ws/notifications) | [pages/notifications.html](../pages/notifications.html), [src/notifications-page.js](../src/notifications-page.js) |
| Preference editor | `/dashboard/settings` | [src/dashboard-next/pages/settings.js](../src/dashboard-next/pages/settings.js) |
+| Avatar announcements | The corner companion, on any page | [src/notification-herald.js](../src/notification-herald.js) |
| Inbox API | `GET/POST/DELETE /api/notifications/*` | [api/notifications/](../api/notifications/README.md) |
One inbox, two views. The dropdown holds the latest page for a quick glance;
@@ -80,6 +81,64 @@ Two details worth knowing:
own `?type=` parameter filters server-side by a single exact type (e.g.
`?type=pump_alert`), not by category.
+## The avatar channel: delivered in person
+
+A badge waits to be noticed. Some notifications should not have to. When one
+of those lands while you are on the site, the corner companion (the avatar
+that already walks your pages) turns to you, plays a gesture, and says it out
+loud, with a link straight to the thing that happened.
+
+`avatar` is a real delivery channel next to `in_app`, `push`, `email`, and
+`telegram`. It is gated by the same per-category matrix, edited in the same
+place (`/dashboard/settings`), and measured in the same funnel.
+
+**What gets announced.** By default: **Sales & earnings**, **Creations**, and
+**Account**. Money landing, a generation finishing while you waited, and
+anything touching your account are worth an interruption. Purchases, social,
+in person, and market alerts are off by default because they are frequent.
+Every one of them is a toggle, so an inbox that should speak up more (or not
+at all) is two clicks away.
+
+**When it stays quiet.** The rules live in
+[src/notification-herald.js](../src/notification-herald.js):
+
+- Only **unread** notifications **under 15 minutes old**. Older rows are
+ history, and history belongs in the bell.
+- **Each notification exactly once per browser.** Delivered ids are remembered
+ in `localStorage`, so navigating, re-polling, or opening a second tab never
+ replays a line.
+- **Two lines per batch**, maximum. Anything past that becomes a single
+ "N more waiting" line pointing at `/notifications`, so a backlog never turns
+ into a monologue.
+- **Never into a background tab.** The point is telling someone who is here.
+- **Nothing is spoken aloud unless you asked for audio.** Announcements use
+ the companion's own narration setting (`walk:companion:narrate`, the toggle
+ on the companion itself). On the default caption-only setting the message is
+ text in the bubble, which is also an `aria-live` region, so screen readers
+ get it either way.
+
+**Controls.** The bubble carries "Turn off", which silences announcements in
+that browser instantly without touching the account-wide setting. Per-category
+control lives in the Notifications panel of `/dashboard/settings`.
+
+**No companion running?** It is summoned for that one message and walks off
+again afterwards, without turning itself on permanently. When an avatar cannot
+be rendered at all (no WebGL, inside an iframe, or a route that already owns
+the corner, such as `/play` or `/avatar-studio`) the line degrades to a normal
+toast, so the notification is never lost to a missing GPU.
+
+The delivery itself is one call into the walk SDK, which any surface can
+reuse:
+
+```js
+// walk-sdk/src/companion.js: mounts if needed, gestures, speaks, retreats.
+await window.__walkCompanion.announce('Your agent made a sale', {
+ tone: 'alert',
+ emote: 'dance',
+ actions: [{ label: 'Open', href: '/dashboard' }],
+});
+```
+
## How the bell and unread state work
The bell ([src/notifications.js](../src/notifications.js)) is mounted by the
@@ -218,12 +277,13 @@ row is not the caller's. Removal is permanent.
```
POST /api/notifications/track
-{ "notification_id": "<uuid>", "channel": "push" | "in_app", "event": "opened" | "returned" }
+{ "notification_id": "<uuid>", "channel": "push" | "in_app" | "avatar", "event": "opened" | "returned" }
```
An idempotent analytics beacon closing the sent-to-opened-to-returned loop:
-the service worker fires `opened` on a push click, the app fires `returned`
-when it boots from a push-sourced open. Session-cookie auth only (no bearer),
+the service worker fires `opened` on a push click, the corner companion fires
+`opened` when you click through from a line it announced, and the app fires
+`returned` when it boots from a push-sourced open. Session-cookie auth only (no bearer),
CSRF-exempt, deduplicated server-side.
> Source: [api/notifications/track.js](../api/notifications/track.js).
@@ -242,9 +302,12 @@ curl -s -X PUT 'https://three.ws/api/notifications/preferences' \
-d '{ "categories": { "social": { "push": false } } }'
```
-GET returns `{ categories, channels, prefs, push: { subscribed_devices } }`:
-the seven categories from the table above, the four channels (`in_app`,
-`push`, `email`, `telegram`), and the caller's resolved matrix. PUT stores a
+GET returns
+`{ categories, channels, type_categories, prefs, push: { subscribed_devices } }`:
+the categories from the table above, the channels (`in_app`, `push`, `email`,
+`telegram`, `avatar`), the type-to-category map (so a browser client can
+resolve a category without a round trip per notification), and the caller's
+resolved matrix. PUT stores a
sparse override; unknown categories, channels, and keys are dropped, and the
response echoes the re-resolved matrix. The body also accepts
`telegram_chat_id` (digits, settable and clearable) for the Telegram channel.
@@ -258,7 +321,7 @@ Delivery gating notes, all enforced in
push left on still delivers the OS notification.
- The `account` category's `in_app` channel is locked on. It is the durable
record of withdrawals and security events, and the fallback bucket for
- unmapped types; the other three channels stay fully mutable.
+ unmapped types; every other channel stays fully mutable.
- A user who never saved gets the defaults, and new categories light up
automatically without a backfill.
diff --git a/pages/companion.html b/pages/companion.html
new file mode 100644
index 000000000..d77df7f20
--- /dev/null
+++ b/pages/companion.html
@@ -0,0 +1,356 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <style>/* three.ws hidden-guard - make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>
+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Companion · three.ws</title>
+ <meta name="description" content="A 3D companion that delivers your important messages in person. Connect Telegram, your calendar, your inbox, or your phone, give each contact their own avatar, and hear what matters out loud." />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="canonical" href="https://three.ws/companion">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Companion · three.ws">
+ <meta property="og:description" content="A 3D companion that delivers your important messages in person. Bring your own keys, give your contacts a face, and hear what matters out loud.">
+ <meta property="og:url" content="https://three.ws/companion">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Companion&amp;d=A+3D+companion+that+delivers+your+important+messages+in+person.&amp;p=%2Fcompanion">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:image:alt" content="Companion - three.ws">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="twitter:title" content="Companion · three.ws">
+ <meta name="twitter:description" content="A 3D companion that delivers your important messages in person.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Companion&amp;d=A+3D+companion+that+delivers+your+important+messages+in+person.&amp;p=%2Fcompanion">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"three.ws Companion","applicationCategory":"CommunicationApplication","operatingSystem":"Web","description":"A 3D companion that delivers your important messages in person, from your own Telegram, calendar, inbox, and phone.","url":"https://three.ws/companion","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"}}</script>
+ <style>
+ :root {
+ --bg: #0d0d0d;
+ --bg-2: #141414;
+ --card: #181818;
+ --line: rgba(255,255,255,0.07);
+ --line-2: rgba(255,255,255,0.12);
+ --text: #e7e9ee;
+ --muted: rgba(231,233,238,0.55);
+ --dim: rgba(231,233,238,0.35);
+ --blue: #3b82f6;
+ --green: #22c55e;
+ --amber: #f59e0b;
+ --red: #ef4444;
+ --radius: 14px;
+ --skeleton-base: rgba(255,255,255,0.04);
+ --skeleton-sheen: rgba(255,255,255,0.08);
+ }
+ [data-theme="light"] {
+ --bg: #f5f5f5;
+ --bg-2: #ffffff;
+ --card: #ffffff;
+ --line: rgba(0,0,0,0.07);
+ --line-2: rgba(0,0,0,0.12);
+ --text: #111;
+ --muted: rgba(0,0,0,0.55);
+ --dim: rgba(0,0,0,0.35);
+ --skeleton-base: rgba(0,0,0,0.04);
+ --skeleton-sheen: rgba(0,0,0,0.08);
+ }
+ *{box-sizing:border-box;margin:0;padding:0;}
+ html,body{background:var(--bg);color:var(--text);font-family:'Inter',system-ui,sans-serif;min-height:100vh;}
+ a{color:inherit;text-decoration:none;}
+ .shell{max-width:1080px;margin:0 auto;padding:0 20px 120px;}
+ .hero{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;padding:48px 0 8px;flex-wrap:wrap;}
+ .hero h1{font-size:32px;font-weight:700;letter-spacing:-0.025em;}
+ .hero p{color:var(--muted);margin-top:10px;font-size:15px;line-height:1.55;max-width:560px;}
+ .hero-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
+ .btn{display:inline-flex;align-items:center;gap:6px;font-size:13px;font-weight:600;padding:9px 15px;border-radius:9px;background:var(--card);color:var(--text);border:1px solid var(--line-2);cursor:pointer;transition:border-color .15s,background .15s,transform .1s;font-family:inherit;}
+ .btn:hover{border-color:rgba(120,160,255,.55);}
+ .btn:active{transform:translateY(1px);}
+ .btn:disabled{opacity:.45;cursor:default;transform:none;}
+ .btn:focus-visible{outline:2px solid var(--blue);outline-offset:2px;}
+ .btn-primary{background:var(--blue);border-color:var(--blue);color:#fff;}
+ .btn-primary:hover{background:#2f6fd8;border-color:#2f6fd8;}
+ .btn-danger{color:var(--red);}
+ .btn-danger:hover{border-color:rgba(239,68,68,.5);background:rgba(239,68,68,.08);}
+ .btn-sm{font-size:12px;padding:6px 11px;}
+ section{margin-top:40px;}
+ .sec-head{display:flex;align-items:baseline;justify-content:space-between;gap:16px;margin-bottom:14px;flex-wrap:wrap;}
+ .sec-head h2{font-size:19px;font-weight:650;letter-spacing:-0.01em;}
+ .sec-head p{color:var(--muted);font-size:13px;margin-top:4px;max-width:620px;line-height:1.5;}
+ .card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:20px;}
+ .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:16px;}
+ /* Stage */
+ .stage{display:grid;grid-template-columns:320px 1fr;gap:20px;align-items:stretch;}
+ .stage-viewer{background:linear-gradient(180deg,rgba(59,130,246,.08),transparent 60%),var(--bg-2);border:1px solid var(--line);border-radius:var(--radius);min-height:340px;position:relative;overflow:hidden;display:flex;align-items:center;justify-content:center;}
+ .stage-viewer agent-3d{width:100%;height:340px;display:block;}
+ .stage-empty{color:var(--dim);font-size:13px;text-align:center;padding:24px;line-height:1.6;}
+ .stage-body{display:flex;flex-direction:column;gap:14px;}
+ .bubble{background:var(--card);border:1px solid var(--line-2);border-radius:var(--radius);padding:18px 20px;position:relative;}
+ .bubble:before{content:'';position:absolute;left:-7px;top:28px;width:12px;height:12px;background:var(--card);border-left:1px solid var(--line-2);border-bottom:1px solid var(--line-2);transform:rotate(45deg);}
+ .bubble-line{font-size:16px;line-height:1.55;font-weight:500;}
+ .bubble-meta{margin-top:10px;font-size:12px;color:var(--muted);display:flex;gap:10px;flex-wrap:wrap;align-items:center;}
+ .chip{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px;border:1px solid var(--line-2);color:var(--muted);text-transform:uppercase;letter-spacing:.04em;}
+ .chip.ok{color:var(--green);border-color:rgba(34,197,94,.35);background:rgba(34,197,94,.08);}
+ .chip.warn{color:var(--amber);border-color:rgba(245,158,11,.35);background:rgba(245,158,11,.08);}
+ .chip.err{color:var(--red);border-color:rgba(239,68,68,.35);background:rgba(239,68,68,.08);}
+ /* Meters */
+ .meter{height:6px;border-radius:999px;background:var(--skeleton-base);overflow:hidden;flex:1;min-width:80px;}
+ .meter span{display:block;height:100%;border-radius:999px;background:var(--blue);transition:width .4s ease;}
+ .meter span.hot{background:var(--red);}
+ .meter span.mid{background:var(--amber);}
+ /* Source cards */
+ .src{display:flex;flex-direction:column;gap:12px;}
+ .src-head{display:flex;align-items:flex-start;gap:12px;}
+ .src-icon{font-size:22px;line-height:1;width:38px;height:38px;border-radius:10px;background:var(--bg-2);border:1px solid var(--line);display:flex;align-items:center;justify-content:center;flex-shrink:0;}
+ .src-title{font-size:15px;font-weight:650;}
+ .src-sub{font-size:12.5px;color:var(--muted);margin-top:3px;line-height:1.5;}
+ .src-body{display:flex;flex-direction:column;gap:10px;}
+ label.field{display:flex;flex-direction:column;gap:6px;font-size:12px;color:var(--muted);font-weight:500;}
+ input[type=text],input[type=url],input[type=password],input[type=number],select,textarea{background:var(--bg-2);border:1px solid var(--line-2);border-radius:9px;color:var(--text);font-family:inherit;font-size:13px;padding:9px 11px;width:100%;transition:border-color .15s;}
+ input:focus,select:focus,textarea:focus{outline:none;border-color:var(--blue);}
+ .row{display:flex;gap:10px;flex-wrap:wrap;}
+ .row > *{flex:1;min-width:120px;}
+ .hint{font-size:11.5px;color:var(--dim);line-height:1.5;}
+ .hint a{color:var(--blue);}
+ .connected{display:flex;align-items:center;justify-content:space-between;gap:10px;background:var(--bg-2);border:1px solid var(--line);border-radius:10px;padding:11px 13px;font-size:13px;flex-wrap:wrap;}
+ .connected-meta{font-size:11.5px;color:var(--dim);margin-top:3px;}
+ /* Contacts */
+ .contact{display:flex;align-items:center;gap:12px;padding:12px;border:1px solid var(--line);border-radius:12px;background:var(--bg-2);}
+ .contact-face{width:44px;height:44px;border-radius:50%;background:var(--card);border:1px solid var(--line-2);object-fit:cover;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:18px;color:var(--dim);}
+ .contact-name{font-size:14px;font-weight:600;}
+ .contact-id{font-size:12px;color:var(--muted);word-break:break-all;}
+ /* Feed */
+ .event{display:flex;gap:14px;padding:15px 4px;border-bottom:1px solid var(--line);}
+ .event:last-child{border-bottom:0;}
+ .event-icon{font-size:18px;width:26px;text-align:center;flex-shrink:0;margin-top:2px;}
+ .event-main{flex:1;min-width:0;}
+ .event-line{font-size:14px;line-height:1.55;}
+ .event-sub{font-size:12px;color:var(--muted);margin-top:5px;display:flex;gap:10px;align-items:center;flex-wrap:wrap;}
+ .event-actions{display:flex;gap:6px;flex-shrink:0;align-items:flex-start;}
+ /* States */
+ .empty{text-align:center;padding:56px 20px;color:var(--muted);}
+ .empty h3{font-size:17px;font-weight:600;color:var(--text);margin-bottom:8px;}
+ .empty p{font-size:13.5px;line-height:1.6;max-width:420px;margin:0 auto;}
+ .error{background:rgba(239,68,68,.08);border:1px solid rgba(239,68,68,.25);border-radius:10px;padding:14px 16px;color:#ef4444;font-size:13px;margin-bottom:16px;}
+ .notice{background:rgba(59,130,246,.07);border:1px solid rgba(59,130,246,.22);border-radius:10px;padding:14px 16px;font-size:13px;line-height:1.6;color:var(--muted);}
+ .skeleton{background:var(--skeleton-base);background-image:linear-gradient(90deg,var(--skeleton-base) 0%,var(--skeleton-sheen) 50%,var(--skeleton-base) 100%);background-size:200% 100%;border-radius:8px;animation:shimmer 1.4s ease-in-out infinite;}
+ @keyframes shimmer{0%{background-position:200% 0;}100%{background-position:-200% 0;}}
+ .auth-wall{text-align:center;padding:110px 20px;}
+ .auth-wall h2{font-size:22px;font-weight:700;margin-bottom:12px;}
+ .auth-wall p{color:var(--muted);font-size:14px;margin-bottom:24px;line-height:1.6;}
+ /* Settings */
+ .settings-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:18px;}
+ input[type=range]{width:100%;accent-color:var(--blue);}
+ .switch{display:flex;align-items:center;gap:10px;font-size:13px;cursor:pointer;}
+ .switch input{width:18px;height:18px;accent-color:var(--blue);cursor:pointer;}
+ code.token{display:block;background:var(--bg-2);border:1px solid var(--line-2);border-radius:9px;padding:10px 12px;font-size:12px;word-break:break-all;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;}
+ pre.snippet{background:var(--bg-2);border:1px solid var(--line);border-radius:10px;padding:12px 14px;font-size:11.5px;line-height:1.6;overflow-x:auto;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted);}
+ @media(max-width:860px){
+ .stage{grid-template-columns:1fr;}
+ .hero h1{font-size:26px;}
+ }
+ @media(prefers-reduced-motion:reduce){
+ .skeleton{animation:none;}
+ .meter span{transition:none;}
+ }
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="shell">
+ <div class="hero">
+ <div>
+ <h1>Your companion</h1>
+ <p>
+ A 3D character that walks on and tells you the things worth interrupting you for.
+ Connect what you already use, give the people who matter their own face and voice,
+ and let everything else stay quiet.
+ </p>
+ </div>
+ <div class="hero-actions">
+ <button type="button" id="check-now" class="btn">Check now</button>
+ <a href="/docs/companion" class="btn">How it works</a>
+ </div>
+ </div>
+
+ <div id="auth-wall" class="auth-wall" hidden>
+ <h2>Sign in to set up your companion</h2>
+ <p>Your connections, contacts, and messages are private to your account and encrypted at rest.</p>
+ <a href="/login?next=/companion" class="btn btn-primary">Sign in</a>
+ </div>
+
+ <div id="page-error" class="error" hidden></div>
+
+ <div id="main" hidden>
+ <!-- Stage: the companion, and the last thing it had to say. -->
+ <section id="stage-section" aria-labelledby="stage-h">
+ <div class="sec-head">
+ <div>
+ <h2 id="stage-h">On stage</h2>
+ <p>The most recent delivery, exactly as your companion performs it.</p>
+ </div>
+ <div class="hero-actions">
+ <button type="button" id="say-again" class="btn btn-sm">Say it out loud</button>
+ </div>
+ </div>
+ <div class="stage">
+ <div class="stage-viewer" id="stage-viewer">
+ <div class="stage-empty" id="stage-empty">
+ Nothing delivered yet. Connect a source below, or send a test message from your phone,
+ and whoever it is from will show up here.
+ </div>
+ </div>
+ <div class="stage-body">
+ <div class="bubble">
+ <div class="bubble-line" id="stage-line">Waiting for something worth saying.</div>
+ <div class="bubble-meta" id="stage-meta"></div>
+ </div>
+ <div class="card" id="stage-stats"></div>
+ </div>
+ </div>
+ </section>
+
+ <!-- Connections -->
+ <section aria-labelledby="sources-h">
+ <div class="sec-head">
+ <div>
+ <h2 id="sources-h">Connections</h2>
+ <p>
+ Bring your own keys. Nothing is stored that you cannot revoke from the other side in one click,
+ and every credential is encrypted before it touches the database.
+ </p>
+ </div>
+ </div>
+ <div class="grid" id="sources-grid"></div>
+ </section>
+
+ <!-- Contacts -->
+ <section aria-labelledby="contacts-h">
+ <div class="sec-head">
+ <div>
+ <h2 id="contacts-h">Who gets a face</h2>
+ <p>
+ Give a person an avatar and their messages arrive in that body, in their own voice.
+ Everyone else is delivered by your default companion.
+ </p>
+ </div>
+ <a href="/create-selfie?next=/companion" class="btn btn-sm">Make one from a selfie</a>
+ </div>
+ <div class="card">
+ <div id="contacts-list"></div>
+ <form id="contact-form" class="src-body" style="margin-top:16px;border-top:1px solid var(--line);padding-top:16px;">
+ <div class="row">
+ <label class="field">
+ Name
+ <input type="text" id="contact-name" placeholder="Sarah" maxlength="80" required />
+ </label>
+ <label class="field">
+ Handle, email, or number
+ <input type="text" id="contact-identifier" placeholder="@sarah or [email protected]" maxlength="320" required />
+ </label>
+ </div>
+ <div class="row">
+ <label class="field">
+ Avatar
+ <select id="contact-avatar"></select>
+ </label>
+ <label class="field">
+ Voice
+ <select id="contact-voice"></select>
+ </label>
+ <label class="field">
+ Priority
+ <select id="contact-priority">
+ <option value="0">Normal</option>
+ <option value="15">Important</option>
+ <option value="30">Always interrupt me</option>
+ <option value="-20">Rarely urgent</option>
+ </select>
+ </label>
+ </div>
+ <div class="row" style="justify-content:flex-end;">
+ <button type="submit" class="btn btn-primary" style="flex:0 0 auto;">Save contact</button>
+ </div>
+ </form>
+ </div>
+ </section>
+
+ <!-- Feed -->
+ <section aria-labelledby="feed-h">
+ <div class="sec-head">
+ <div>
+ <h2 id="feed-h">Everything it heard</h2>
+ <p>Every message that came in, what it scored, and why. Quiet ones are kept here instead of being spoken.</p>
+ </div>
+ <div class="hero-actions">
+ <label class="switch"><input type="checkbox" id="feed-loud-only" /> Only what it spoke</label>
+ </div>
+ </div>
+ <div class="card"><div id="feed-list"></div></div>
+ <div class="hero-actions" style="justify-content:center;margin-top:16px;">
+ <button type="button" id="feed-more" class="btn btn-sm" hidden>Load more</button>
+ </div>
+ </section>
+
+ <!-- Settings -->
+ <section aria-labelledby="settings-h">
+ <div class="sec-head">
+ <div>
+ <h2 id="settings-h">How loud, and when</h2>
+ <p>The bar a message has to clear before anyone walks on stage.</p>
+ </div>
+ </div>
+ <div class="card settings-grid">
+ <label class="field">
+ Interrupt me at <strong id="threshold-value" style="color:var(--text)">60</strong> and above
+ <input type="range" id="threshold" min="0" max="100" step="5" />
+ <span class="hint">Lower hears more. Higher keeps it to the things you would want a tap on the shoulder for.</span>
+ </label>
+ <label class="field">
+ Quiet hours
+ <div class="row">
+ <select id="quiet-start"></select>
+ <select id="quiet-end"></select>
+ </div>
+ <span class="hint" id="quiet-hint">Inside this window messages are stored, never spoken.</span>
+ </label>
+ <label class="field">
+ Default companion
+ <select id="default-avatar"></select>
+ <span class="hint">Used for anyone without their own contact card.</span>
+ </label>
+ <label class="field">
+ Default voice
+ <select id="default-voice"></select>
+ <span class="hint">Real speech from <a href="/voice">Voice Lab</a> lanes, spoken in the browser.</span>
+ </label>
+ <div class="field">
+ On this device
+ <label class="switch"><input type="checkbox" id="enabled" /> Companion is on</label>
+ <label class="switch"><input type="checkbox" id="push-enabled" /> Send it to my phone as a push</label>
+ <span class="hint" id="push-hint"></span>
+ </div>
+ <div class="field">
+ Timezone
+ <input type="text" id="timezone" readonly />
+ <span class="hint">Detected from this browser and used for quiet hours.</span>
+ </div>
+ </div>
+ </section>
+ </div>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
+ <script type="module" src="/src/companion/page.js"></script>
+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/pages/notifications.html b/pages/notifications.html
index 9d5200923..5c9591b33 100644
--- a/pages/notifications.html
+++ b/pages/notifications.html
@@ -129,6 +129,7 @@
<p data-i18n="notifications.everything_that_happened_while_you_were_away">Everything that happened while you were away.</p>
</div>
<div class="page-actions">
+ <a href="/companion" class="n-btn" aria-label="Set up your 3D companion" data-i18n="notifications.companion_link">👋 Companion</a>
<a href="/dashboard/settings" class="n-btn" aria-label="Notification preferences" data-i18n="notifications.preferences" data-i18n-attr="aria-label:notifications.notification_preferences_arialabel">⚙ Preferences</a>
<button type="button" id="n-mark-all" class="n-btn" data-i18n="notifications.mark_all_read">Mark all read</button>
</div>
@@ -151,6 +152,7 @@
<button class="n-tab" role="tab" aria-selected="false" data-type="irl" data-i18n="notifications.in_person">In person</button>
<button class="n-tab" role="tab" aria-selected="false" data-type="alerts" data-i18n="notifications.market_alerts">Market alerts</button>
<button class="n-tab" role="tab" aria-selected="false" data-type="creations" data-i18n="notifications.creations">Creations</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="companion" data-i18n="notifications.companion">Companion</button>
<button class="n-tab" role="tab" aria-selected="false" data-type="account" data-i18n="notifications.account">Account</button>
</div>
<div id="n-list" class="n-list"></div>
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 1cd7c3437..ac2572749 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -181,6 +181,12 @@ URL: https://three.ws/collection
View all the skills and subscriptions you've unlocked on three.ws.
+### Companion
+
+URL: https://three.ws/companion
+
+A 3D companion that delivers your important messages in person. Connect your own Telegram bot, calendar, inbox, or phone, give each contact their own avatar and voice, and hear only what clears your bar.
+
### Notifications
URL: https://three.ws/notifications
diff --git a/public/llms.txt b/public/llms.txt
index 685d6427f..853c94abc 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -58,6 +58,7 @@ Entry points into the product.
- [Marketplace Analytics](https://three.ws/marketplace/analytics): Real-time stats on the three.ws skill marketplace: top skills, top agents, and sales volume.
- [Trial Conversions](https://three.ws/conversions): Both sides of the moment a metered free trial runs out: the trials you are holding with the runs you have left and the price to keep them, and the trials running on skills you sell with the revenue waiting in the queue.
- [My Collection](https://three.ws/collection): View all the skills and subscriptions you've unlocked on three.ws.
+- [Companion](https://three.ws/companion): A 3D companion that delivers your important messages in person. Connect your own Telegram bot, calendar, inbox, or phone, give each contact their own avatar and voice, and hear only what clears your bar.
- [Notifications](https://three.ws/notifications): Every payment, sale, remix, follow, quest, and royalty notification on three.ws: all in one place, filterable by category.
- [Community](https://three.ws/community): Live platform activity plus where to follow, contribute, and connect with three.ws creators.
- [Crew HQ](https://three.ws/crews): Found a crew, invite your people, and watch the whole roster stand in one 3D headquarters. Every member appears as their own agent, lit when they are live in the world.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 22cd5958c..8513d80ef 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -83,7 +83,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 838 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 839 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -95,7 +95,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 838 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 839 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -103,6 +103,14 @@
<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
<p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
+ <li>
+ <a href="/companion">
+ <span class="sm-new-date">Aug 28, 2026</span>
+ <span class="sm-title">Companion</span>
+ <span class="sm-path">/companion</span>
+ <span class="sm-desc">A 3D companion that delivers your important messages in person. Connect your own Telegram bot, calendar, inbox, or phone, give each contact their own avatar and voice, and hear only what clears your bar.</span>
+ </a>
+ </li>
<li>
<a href="/seeker">
<span class="sm-new-date">Aug 27, 2026</span>
@@ -167,14 +175,6 @@
<span class="sm-desc">How a static capsule mascot with four nubs became a 52-bone, six-clip avatar: limb discovery from a distance transform, medial-axis skinning, and a bind pose that differs from the rest pose on purpose.</span>
</a>
</li>
- <li>
- <a href="/docs/liquid-glass">
- <span class="sm-new-date">Aug 21, 2026</span>
- <span class="sm-title">Docs · Liquid glass, the visual direction</span>
- <span class="sm-path">/docs/liquid-glass</span>
- <span class="sm-desc">The design brief for the liquid-glass look on three.ws grids and panels: real refraction instead of blur, the squircle and material recipe, the two lanes (CSS glass for chrome, three.js transmission for tiles), the open-source references, and the performance and accessibility budget.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -192,7 +192,7 @@
</nav>
<section class="sm-section" id="main">
<header>
- <h2>Main<span class="sm-count" data-count>52</span></h2>
+ <h2>Main<span class="sm-count" data-count>53</span></h2>
<p class="sm-section-desc">Entry points into the product.</p>
</header>
<ul class="sm-list">
@@ -392,6 +392,13 @@
<span class="sm-desc">View all the skills and subscriptions you've unlocked on three.ws.</span>
</a>
</li>
+ <li>
+ <a href="/companion">
+ <span class="sm-title">Companion</span>
+ <span class="sm-path">/companion</span>
+ <span class="sm-desc">A 3D companion that delivers your important messages in person. Connect your own Telegram bot, calendar, inbox, or phone, give each contact their own avatar and voice, and hear only what clears your bar.</span>
+ </a>
+ </li>
<li>
<a href="/notifications">
<span class="sm-title">Notifications</span>
diff --git a/src/companion/api.js b/src/companion/api.js
new file mode 100644
index 000000000..5d70b469e
--- /dev/null
+++ b/src/companion/api.js
@@ -0,0 +1,61 @@
+// Typed-ish client for /api/companion/*.
+//
+// apiFetch (src/api.js) already carries the session cookie, mints the CSRF
+// token for writes, retries idempotent reads, and redirects on an expired
+// session, so everything here is a thin shape on top of it. Errors surface as
+// Error objects carrying the server's `code` and human message, because every
+// caller on the page renders that message to the user rather than a generic
+// "something went wrong".
+
+import { apiFetch } from '../api.js';
+
+async function request(path, { method = 'GET', body = null, allowAnonymous = false } = {}) {
+ const res = await apiFetch(path, {
+ method,
+ allowAnonymous,
+ ...(body ? { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) } : {}),
+ });
+ const text = await res.text();
+ let data = null;
+ if (text) {
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = null;
+ }
+ }
+ if (!res.ok) {
+ const err = new Error(data?.message || data?.error || `request failed (${res.status})`);
+ err.status = res.status;
+ err.code = data?.code || null;
+ throw err;
+ }
+ return data;
+}
+
+export const companionApi = {
+ settings: () => request('/api/companion/settings'),
+ updateSettings: (patch) => request('/api/companion/settings', { method: 'PATCH', body: patch }),
+ rotateToken: () => request('/api/companion/settings', { method: 'POST', body: { rotate_token: true } }),
+
+ sources: () => request('/api/companion/sources'),
+ connect: (body) => request('/api/companion/sources', { method: 'POST', body }),
+ updateSource: (id, patch) => request(`/api/companion/sources/${encodeURIComponent(id)}`, { method: 'PATCH', body: patch }),
+ disconnect: (id) => request(`/api/companion/sources/${encodeURIComponent(id)}`, { method: 'DELETE' }),
+ pollSource: (id) => request(`/api/companion/sources/${encodeURIComponent(id)}`, { method: 'POST' }),
+ pollAll: () => request('/api/companion/poll', { method: 'POST' }),
+
+ contacts: () => request('/api/companion/contacts'),
+ saveContact: (body) => request('/api/companion/contacts', { method: 'POST', body }),
+ deleteContact: (id) => request(`/api/companion/contacts/${encodeURIComponent(id)}`, { method: 'DELETE' }),
+
+ events: ({ limit = 30, before = null, loudOnly = false, threshold = 0 } = {}) => {
+ const params = new URLSearchParams({ limit: String(limit) });
+ if (before) params.set('before', before);
+ if (loudOnly) params.set('min_importance', String(threshold));
+ return request(`/api/companion/events?${params.toString()}`);
+ },
+ markEvent: (id, patch) => request(`/api/companion/events/${encodeURIComponent(id)}`, { method: 'PATCH', body: patch }),
+
+ avatars: () => request('/api/avatars?limit=100'),
+};
diff --git a/src/companion/page.js b/src/companion/page.js
new file mode 100644
index 000000000..0a5930cec
--- /dev/null
+++ b/src/companion/page.js
@@ -0,0 +1,669 @@
+// /companion - the control room for the personal companion.
+//
+// What this page owns:
+// • the stage: the last delivery, performed by whoever it was from,
+// • the connections (BYOK: bridge token, Telegram bot, iCal URL, IMAP),
+// • the contacts, which decide whose body and voice a message arrives in,
+// • the feed of everything that came in, with the score and the reason,
+// • the settings that decide what is loud enough to interrupt for.
+//
+// Server truth lives behind /api/companion/* (see api/companion/). Nothing on
+// this page is simulated: the "check now" button really polls the user's own
+// providers, the test button really posts through the public bridge endpoint,
+// and the stage speaks with the same TTS lanes the rest of the platform uses.
+
+import { companionApi } from './api.js';
+import { renderSources, esc } from './sources.js';
+import { speak, stopSpeaking } from './speak.js';
+import { toast } from '../shared/toast.js';
+import { enablePush, disablePush, getPushState } from '../push-notifications.js';
+
+const AUTH_HINT_KEY = '3dagent:auth-hint';
+const DEFAULT_STAGE_GLB = '/avatars/michelle.glb';
+const FEED_PAGE = 20;
+
+const state = {
+ settings: null,
+ bridge: null,
+ voices: [],
+ sources: [],
+ contacts: [],
+ events: [],
+ avatars: [],
+ feedCursor: null,
+ loudOnly: false,
+ stageEvent: null,
+};
+
+const el = (id) => document.getElementById(id);
+
+function isAuthed() {
+ try {
+ const raw = localStorage.getItem(AUTH_HINT_KEY);
+ return raw ? JSON.parse(raw)?.authed === true : false;
+ } catch {
+ return false;
+ }
+}
+
+function showError(message) {
+ const box = el('page-error');
+ box.textContent = message;
+ box.hidden = false;
+}
+
+function clearError() {
+ el('page-error').hidden = true;
+}
+
+// ── Stage ────────────────────────────────────────────────────────────────────
+
+function avatarUrlFor(event) {
+ return event?.contact_avatar_glb_url || state.settings?.avatar_glb_url || DEFAULT_STAGE_GLB;
+}
+
+function importanceClass(score) {
+ if (score >= 80) return 'hot';
+ if (score >= 50) return 'mid';
+ return '';
+}
+
+function renderStage() {
+ const event = state.stageEvent;
+ const viewer = el('stage-viewer');
+ const line = el('stage-line');
+ const meta = el('stage-meta');
+ const stats = el('stage-stats');
+ const sayBtn = el('say-again');
+
+ if (!event) {
+ sayBtn.disabled = true;
+ line.textContent = 'Waiting for something worth saying.';
+ meta.innerHTML = '';
+ stats.innerHTML = `
+ <div class="hint">
+ Once a source is connected, everything it hears is scored here: what it was, who it was from,
+ how urgent it looked, and whether that cleared your bar.
+ </div>`;
+ return;
+ }
+
+ sayBtn.disabled = false;
+ const url = avatarUrlFor(event);
+ const existing = viewer.querySelector('agent-3d');
+ if (existing) {
+ if (existing.getAttribute('src') !== url) existing.setAttribute('src', url);
+ } else {
+ el('stage-empty')?.remove();
+ const node = document.createElement('agent-3d');
+ node.setAttribute('src', url);
+ node.setAttribute('background', 'transparent');
+ node.setAttribute('alt', `${event.contact_name || event.sender || 'Your companion'} delivering a message`);
+ viewer.appendChild(node);
+ }
+
+ line.textContent = event.spoken_line || event.title;
+ meta.innerHTML = `
+ <span class="chip ${event.importance >= (state.settings?.threshold ?? 60) ? 'ok' : ''}">${event.importance} / 100</span>
+ <span>${esc(event.contact_name || event.sender || 'Unknown sender')}</span>
+ <span>·</span>
+ <span>${esc(event.source_kind)}</span>
+ <span>·</span>
+ <span>${new Date(event.created_at).toLocaleString()}</span>
+ `;
+ stats.innerHTML = `
+ <div class="hint" style="font-size:13px;line-height:1.6">
+ <strong style="color:var(--text)">Why it scored ${event.importance}</strong><br />
+ ${esc(event.reason || 'no signals recorded')}
+ </div>
+ <div class="bubble-meta" style="margin-top:12px">
+ <span class="meter"><span class="${importanceClass(event.importance)}" style="width:${Math.max(3, event.importance)}%"></span></span>
+ <span>${event.triage_engine === 'rules' ? 'scored by rules' : `scored by ${esc(event.triage_engine)}`}</span>
+ </div>
+ ${event.title && event.title !== event.spoken_line ? `<div class="hint" style="margin-top:12px">Original: ${esc(event.title)}</div>` : ''}
+ `;
+}
+
+async function sayStage() {
+ const event = state.stageEvent;
+ if (!event) return;
+ const btn = el('say-again');
+ btn.disabled = true;
+ btn.textContent = 'Speaking…';
+ const how = await speak(event.spoken_line || event.title, {
+ voice: event.contact_voice || state.settings?.voice || 'alloy',
+ });
+ btn.disabled = false;
+ btn.textContent = 'Say it out loud';
+ if (how === 'silent') toast('No voice lane could speak that right now.', { variant: 'error' });
+ else if (how === 'browser') toast('Speaking with your browser voice: the hosted lanes were busy.', { variant: 'info' });
+ if (how !== 'silent' && !event.delivered_at) {
+ companionApi.markEvent(event.id, { delivered: true }).catch(() => {});
+ }
+}
+
+// ── Feed ─────────────────────────────────────────────────────────────────────
+
+const SOURCE_ICON = { telegram: '✈️', calendar: '📅', email: '✉️', bridge: '📱' };
+
+function renderFeed() {
+ const host = el('feed-list');
+ if (!state.events.length) {
+ host.innerHTML = `
+ <div class="empty">
+ <h3>Nothing has come in yet</h3>
+ <p>Connect a source above, or press "Send a test" on the phone card, and the first delivery lands here within a minute.</p>
+ </div>`;
+ el('feed-more').hidden = true;
+ return;
+ }
+
+ host.innerHTML = state.events.map((event) => `
+ <div class="event" data-event="${esc(event.id)}">
+ <div class="event-icon">${SOURCE_ICON[event.source_kind] || '📨'}</div>
+ <div class="event-main">
+ <div class="event-line">${esc(event.spoken_line || event.title)}</div>
+ <div class="event-sub">
+ <span>${esc(event.contact_name || event.sender || 'Unknown')}</span>
+ <span class="meter" title="${esc(event.reason || '')}"><span class="${importanceClass(event.importance)}" style="width:${Math.max(3, event.importance)}%"></span></span>
+ <span>${event.importance}</span>
+ ${event.delivered_at ? '<span class="chip ok">spoken</span>' : '<span class="chip">held</span>'}
+ <span>${new Date(event.created_at).toLocaleString()}</span>
+ </div>
+ </div>
+ <div class="event-actions">
+ <button type="button" class="btn btn-sm" data-feed-action="stage" data-id="${esc(event.id)}">Replay</button>
+ ${event.dismissed_at ? '' : `<button type="button" class="btn btn-sm" data-feed-action="dismiss" data-id="${esc(event.id)}">Dismiss</button>`}
+ </div>
+ </div>
+ `).join('');
+ el('feed-more').hidden = state.events.length < FEED_PAGE;
+}
+
+async function loadFeed({ append = false } = {}) {
+ const data = await companionApi.events({
+ limit: FEED_PAGE,
+ before: append ? state.feedCursor : null,
+ loudOnly: state.loudOnly,
+ threshold: state.settings?.threshold ?? 60,
+ });
+ state.events = append ? state.events.concat(data.events) : data.events;
+ state.feedCursor = state.events.length ? state.events[state.events.length - 1].created_at : null;
+ if (!append) {
+ state.stageEvent = state.events[0] || null;
+ renderStage();
+ }
+ renderFeed();
+ el('feed-more').hidden = !data.has_more;
+}
+
+// ── Contacts ─────────────────────────────────────────────────────────────────
+
+function renderContacts() {
+ const host = el('contacts-list');
+ if (!state.contacts.length) {
+ host.innerHTML = `
+ <div class="empty" style="padding:32px 12px">
+ <h3>Nobody has a face yet</h3>
+ <p>Add the people you always want to hear from. Their messages will be delivered by the avatar you give them, in the voice you pick.</p>
+ </div>`;
+ return;
+ }
+ host.innerHTML = `<div class="grid">${state.contacts.map((contact) => `
+ <div class="contact">
+ ${contact.avatar_image_url
+ ? `<img class="contact-face" src="${esc(contact.avatar_image_url)}" alt="" loading="lazy" />`
+ : `<div class="contact-face">${esc((contact.display_name || '?').slice(0, 1).toUpperCase())}</div>`}
+ <div style="flex:1;min-width:0">
+ <div class="contact-name">${esc(contact.display_name)}</div>
+ <div class="contact-id">${esc(contact.identifier)}</div>
+ <div class="connected-meta">
+ ${contact.avatar_glb_url ? 'own avatar' : 'default companion'}
+ ${contact.voice ? ` · ${esc(contact.voice)}` : ''}
+ ${contact.priority_boost ? ` · priority ${contact.priority_boost > 0 ? '+' : ''}${contact.priority_boost}` : ''}
+ </div>
+ </div>
+ <button type="button" class="btn btn-sm btn-danger" data-contact-delete="${esc(contact.id)}" aria-label="Forget ${esc(contact.display_name)}">Forget</button>
+ </div>
+ `).join('')}</div>`;
+}
+
+function avatarOptions(selected) {
+ const options = ['<option value="">Default companion</option>'];
+ const urls = new Set();
+ for (const avatar of state.avatars) {
+ const url = `${location.origin}/api/avatars/${avatar.id}/glb`;
+ urls.add(url);
+ options.push(`<option value="${esc(url)}"${url === selected ? ' selected' : ''}>${esc(avatar.name || 'Untitled avatar')}</option>`);
+ }
+ // A body chosen elsewhere (another device, a GLB from the gallery) must not
+ // silently read as "Default companion" in this picker.
+ if (selected && !urls.has(selected)) {
+ options.push(`<option value="${esc(selected)}" selected>Currently set avatar</option>`);
+ }
+ return options.join('');
+}
+
+function voiceOptions(selected, { allowDefault = false } = {}) {
+ const options = allowDefault ? ['<option value="">Same as default</option>'] : [];
+ for (const voice of state.voices) {
+ options.push(`<option value="${esc(voice)}"${voice === selected ? ' selected' : ''}>${esc(voice)}</option>`);
+ }
+ return options.join('');
+}
+
+// ── Settings ─────────────────────────────────────────────────────────────────
+
+function hourOptions(selected, label) {
+ const options = [`<option value="">${label}</option>`];
+ for (let hour = 0; hour < 24; hour += 1) {
+ const text = `${String(hour).padStart(2, '0')}:00`;
+ options.push(`<option value="${hour}"${selected === hour ? ' selected' : ''}>${text}</option>`);
+ }
+ return options.join('');
+}
+
+function renderSettings() {
+ const settings = state.settings;
+ el('threshold').value = String(settings.threshold);
+ el('threshold-value').textContent = String(settings.threshold);
+ el('quiet-start').innerHTML = hourOptions(settings.quiet_start, 'No quiet hours');
+ el('quiet-end').innerHTML = hourOptions(settings.quiet_end, 'No quiet hours');
+ el('default-avatar').innerHTML = avatarOptions(settings.avatar_glb_url);
+ el('default-voice').innerHTML = voiceOptions(settings.voice);
+ el('contact-avatar').innerHTML = avatarOptions(null);
+ el('contact-voice').innerHTML = voiceOptions(null, { allowDefault: true });
+ el('enabled').checked = settings.enabled;
+ el('timezone').value = settings.timezone;
+ el('quiet-hint').textContent = settings.quiet_start === null
+ ? 'Inside this window messages are stored, never spoken.'
+ : `Between ${String(settings.quiet_start).padStart(2, '0')}:00 and ${String(settings.quiet_end).padStart(2, '0')}:00 in ${settings.timezone}, messages are stored and stay silent.`;
+}
+
+async function patchSettings(patch) {
+ try {
+ const data = await companionApi.updateSettings(patch);
+ state.settings = data.settings;
+ renderSettings();
+ renderStage();
+ } catch (err) {
+ toast(err.message, { variant: 'error' });
+ }
+}
+
+async function refreshPushState() {
+ const hint = el('push-hint');
+ const box = el('push-enabled');
+ const push = await getPushState();
+ box.checked = push.subscribed && state.settings.push_enabled;
+ box.disabled = !push.supported;
+ hint.textContent = !push.supported
+ ? 'This browser cannot receive push. Install three.ws to your home screen on iOS to enable it.'
+ : push.permission === 'denied'
+ ? 'Notifications are blocked for this site in your browser settings.'
+ : push.subscribed
+ ? 'This device is registered. Deliveries above your bar arrive as a push.'
+ : 'Turn this on to get deliveries when this page is closed.';
+}
+
+// ── Connections ──────────────────────────────────────────────────────────────
+
+function renderSourceCards() {
+ renderSources(el('sources-grid'), { sources: state.sources, bridge: state.bridge });
+}
+
+async function reloadSources() {
+ const data = await companionApi.sources();
+ state.sources = data.sources;
+ renderSourceCards();
+}
+
+async function connectSource(form) {
+ const kind = form.dataset.connect;
+ const values = Object.fromEntries(new FormData(form).entries());
+ const button = form.querySelector('button[type=submit]');
+ const original = button.textContent;
+ button.disabled = true;
+ button.textContent = 'Connecting…';
+ try {
+ const body = { kind };
+ if (kind === 'telegram') body.bot_token = String(values.bot_token || '').trim();
+ if (kind === 'calendar') {
+ body.ics_url = String(values.ics_url || '').trim();
+ body.lookahead_minutes = Number(values.lookahead_minutes) || 30;
+ }
+ if (kind === 'email') {
+ body.host = String(values.host || '').trim();
+ body.port = Number(values.port) || 993;
+ body.user = String(values.user || '').trim();
+ body.pass = String(values.pass || '');
+ body.folder = String(values.folder || 'INBOX').trim() || 'INBOX';
+ }
+ const data = await companionApi.connect(body);
+ toast(data.verification?.detail || 'Connected.', { variant: 'success', duration: 6000 });
+ await reloadSources();
+ } catch (err) {
+ toast(err.message, { variant: 'error', duration: 7000 });
+ } finally {
+ button.disabled = false;
+ button.textContent = original;
+ }
+}
+
+async function handleSourceAction(action, id, button) {
+ const original = button.textContent;
+ button.disabled = true;
+ try {
+ if (action === 'poll') {
+ button.textContent = 'Checking…';
+ const result = await companionApi.pollSource(id);
+ toast(result.ok
+ ? `Checked. ${result.ingested} new message${result.ingested === 1 ? '' : 's'}.`
+ : result.error, { variant: result.ok ? 'success' : 'error', duration: 6000 });
+ await Promise.all([reloadSources(), loadFeed()]);
+ return;
+ }
+ if (action === 'toggle') {
+ const enabled = button.dataset.enabled !== '1';
+ await companionApi.updateSource(id, { enabled });
+ await reloadSources();
+ return;
+ }
+ if (action === 'disconnect') {
+ if (!confirm('Disconnect this source? The stored credential is deleted.')) return;
+ await companionApi.disconnect(id);
+ toast('Disconnected.', { variant: 'info' });
+ await reloadSources();
+ }
+ } catch (err) {
+ toast(err.message, { variant: 'error', duration: 6000 });
+ } finally {
+ button.disabled = false;
+ button.textContent = original;
+ }
+}
+
+function curlSnippet() {
+ return [
+ `curl -X POST ${state.bridge.url} \\`,
+ ` -H "Authorization: Bearer ${state.bridge.token}" \\`,
+ ' -H "Content-Type: application/json" \\',
+ ` -d '{"title":"Sarah is at the door","sender":"Sarah","app":"Messages","priority":"high"}'`,
+ ].join('\n');
+}
+
+async function copyText(text, label) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast(`${label} copied.`, { variant: 'success' });
+ } catch {
+ toast('Your browser blocked the clipboard. Select the text and copy it.', { variant: 'error' });
+ }
+}
+
+// The test really goes through the public bridge endpoint with the real token,
+// so a green result here proves the exact path a phone will use.
+async function sendBridgeTest(button) {
+ const original = button.textContent;
+ button.disabled = true;
+ button.textContent = 'Sending…';
+ try {
+ const res = await fetch(state.bridge.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${state.bridge.token}` },
+ body: JSON.stringify({
+ title: 'Test from your companion setup page',
+ body: 'If you can hear this, the bridge works. Anything your phone can forward reaches you the same way.',
+ sender: 'three.ws',
+ app: 'Companion',
+ priority: 'high',
+ }),
+ });
+ const data = await res.json().catch(() => null);
+ if (!res.ok) throw new Error(data?.message || `bridge returned ${res.status}`);
+ toast(data?.duplicate ? 'Already received that one.' : 'Delivered. It is on stage now.', { variant: 'success' });
+ await loadFeed();
+ } catch (err) {
+ toast(err.message, { variant: 'error', duration: 6000 });
+ } finally {
+ button.disabled = false;
+ button.textContent = original;
+ }
+}
+
+async function rotateToken(button) {
+ if (!confirm('Rotate the bridge token? Every device using the old one stops working until you update it.')) return;
+ button.disabled = true;
+ try {
+ const data = await companionApi.rotateToken();
+ state.bridge = data.bridge;
+ renderSourceCards();
+ toast('New token issued. Update your devices.', { variant: 'info', duration: 6000 });
+ } catch (err) {
+ toast(err.message, { variant: 'error' });
+ } finally {
+ button.disabled = false;
+ }
+}
+
+// ── Wiring ───────────────────────────────────────────────────────────────────
+
+function wireEvents() {
+ el('check-now').addEventListener('click', async (e) => {
+ const button = e.currentTarget;
+ button.disabled = true;
+ button.textContent = 'Checking…';
+ try {
+ const result = await companionApi.pollAll();
+ const failed = result.sources.filter((s) => !s.ok);
+ toast(
+ result.sources.length === 0
+ ? 'Nothing is connected yet. Connect a source below.'
+ : `${result.ingested} new message${result.ingested === 1 ? '' : 's'}${failed.length ? `, ${failed.length} source needs attention` : ''}.`,
+ { variant: failed.length ? 'error' : 'success', duration: 6000 },
+ );
+ await Promise.all([reloadSources(), loadFeed()]);
+ } catch (err) {
+ toast(err.message, { variant: 'error' });
+ } finally {
+ button.disabled = false;
+ button.textContent = 'Check now';
+ }
+ });
+
+ el('say-again').addEventListener('click', sayStage);
+
+ el('sources-grid').addEventListener('submit', (e) => {
+ const form = e.target.closest('form[data-connect]');
+ if (!form) return;
+ e.preventDefault();
+ connectSource(form);
+ });
+
+ el('sources-grid').addEventListener('click', (e) => {
+ const button = e.target.closest('button[data-action]');
+ if (!button) return;
+ const action = button.dataset.action;
+ if (action === 'copy-token') return copyText(state.bridge.token, 'Token');
+ if (action === 'copy-curl') return copyText(curlSnippet(), 'Example');
+ if (action === 'send-test') return sendBridgeTest(button);
+ if (action === 'rotate-token') return rotateToken(button);
+ return handleSourceAction(action, button.dataset.id, button);
+ });
+
+ el('contact-form').addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const button = e.target.querySelector('button[type=submit]');
+ button.disabled = true;
+ try {
+ const glb = el('contact-avatar').value || null;
+ await companionApi.saveContact({
+ identifier: el('contact-identifier').value.trim(),
+ display_name: el('contact-name').value.trim(),
+ avatar_glb_url: glb,
+ avatar_image_url: glb ? thumbnailFor(glb) : null,
+ voice: el('contact-voice').value || null,
+ priority_boost: Number(el('contact-priority').value) || 0,
+ });
+ el('contact-identifier').value = '';
+ el('contact-name').value = '';
+ state.contacts = (await companionApi.contacts()).contacts;
+ renderContacts();
+ toast('Contact saved.', { variant: 'success' });
+ } catch (err) {
+ toast(err.message, { variant: 'error', duration: 6000 });
+ } finally {
+ button.disabled = false;
+ }
+ });
+
+ el('contacts-list').addEventListener('click', async (e) => {
+ const button = e.target.closest('button[data-contact-delete]');
+ if (!button) return;
+ button.disabled = true;
+ try {
+ await companionApi.deleteContact(button.dataset.contactDelete);
+ state.contacts = (await companionApi.contacts()).contacts;
+ renderContacts();
+ } catch (err) {
+ toast(err.message, { variant: 'error' });
+ button.disabled = false;
+ }
+ });
+
+ el('feed-list').addEventListener('click', async (e) => {
+ const button = e.target.closest('button[data-feed-action]');
+ if (!button) return;
+ const event = state.events.find((row) => row.id === button.dataset.id);
+ if (!event) return;
+ if (button.dataset.feedAction === 'stage') {
+ state.stageEvent = event;
+ renderStage();
+ el('stage-section').scrollIntoView({ behavior: 'smooth', block: 'start' });
+ return sayStage();
+ }
+ button.disabled = true;
+ try {
+ await companionApi.markEvent(event.id, { dismissed: true });
+ event.dismissed_at = new Date().toISOString();
+ renderFeed();
+ } catch (err) {
+ toast(err.message, { variant: 'error' });
+ button.disabled = false;
+ }
+ });
+
+ el('feed-more').addEventListener('click', async (e) => {
+ e.currentTarget.disabled = true;
+ try {
+ await loadFeed({ append: true });
+ } finally {
+ e.currentTarget.disabled = false;
+ }
+ });
+
+ el('feed-loud-only').addEventListener('change', async (e) => {
+ state.loudOnly = e.currentTarget.checked;
+ state.feedCursor = null;
+ await loadFeed();
+ });
+
+ let thresholdTimer = null;
+ el('threshold').addEventListener('input', (e) => {
+ const value = Number(e.currentTarget.value);
+ el('threshold-value').textContent = String(value);
+ clearTimeout(thresholdTimer);
+ thresholdTimer = setTimeout(() => patchSettings({ threshold: value }), 400);
+ });
+
+ const quietChanged = () => {
+ const start = el('quiet-start').value;
+ const end = el('quiet-end').value;
+ if (start === '' || end === '') return patchSettings({ quiet_start: null, quiet_end: null });
+ return patchSettings({ quiet_start: Number(start), quiet_end: Number(end) });
+ };
+ el('quiet-start').addEventListener('change', quietChanged);
+ el('quiet-end').addEventListener('change', quietChanged);
+
+ el('default-avatar').addEventListener('change', (e) => patchSettings({ avatar_glb_url: e.currentTarget.value || null }));
+ el('default-voice').addEventListener('change', (e) => patchSettings({ voice: e.currentTarget.value }));
+ el('enabled').addEventListener('change', (e) => patchSettings({ enabled: e.currentTarget.checked }));
+
+ el('push-enabled').addEventListener('change', async (e) => {
+ const box = e.currentTarget;
+ box.disabled = true;
+ try {
+ if (box.checked) {
+ const result = await enablePush();
+ if (!result.ok) {
+ box.checked = false;
+ toast(result.reason === 'denied'
+ ? 'Your browser is blocking notifications for this site.'
+ : 'Push could not be enabled on this device.', { variant: 'error', duration: 6000 });
+ } else {
+ await patchSettings({ push_enabled: true });
+ }
+ } else {
+ await disablePush();
+ await patchSettings({ push_enabled: false });
+ }
+ } finally {
+ box.disabled = false;
+ await refreshPushState();
+ }
+ });
+
+ window.addEventListener('pagehide', stopSpeaking);
+}
+
+// The avatar picker stores GLB URLs; the contact card wants a face to show.
+// Both come off the same avatar row, so the thumbnail is derivable.
+function thumbnailFor(glbUrl) {
+ const match = /\/api\/avatars\/([^/]+)\/glb/.exec(glbUrl);
+ if (!match) return null;
+ const avatar = state.avatars.find((row) => row.id === match[1]);
+ return avatar?.thumbnail_url || null;
+}
+
+async function boot() {
+ if (!isAuthed()) {
+ el('auth-wall').hidden = false;
+ return;
+ }
+
+ try {
+ const [settings, sources, contacts, avatars] = await Promise.all([
+ companionApi.settings(),
+ companionApi.sources(),
+ companionApi.contacts(),
+ companionApi.avatars().catch(() => ({ avatars: [] })),
+ ]);
+ state.settings = settings.settings;
+ state.bridge = settings.bridge;
+ state.voices = settings.voices;
+ state.sources = sources.sources;
+ state.contacts = contacts.contacts;
+ state.avatars = avatars.avatars || [];
+ } catch (err) {
+ if (err.status === 401) {
+ el('auth-wall').hidden = false;
+ return;
+ }
+ showError(`Could not load your companion: ${err.message}`);
+ return;
+ }
+
+ clearError();
+ el('main').hidden = false;
+ renderSettings();
+ renderSourceCards();
+ renderContacts();
+ wireEvents();
+ await Promise.all([loadFeed(), refreshPushState()]);
+
+ // The browser knows the timezone; quiet hours are meaningless without it.
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ if (tz && tz !== state.settings.timezone) await patchSettings({ timezone: tz });
+}
+
+boot();
diff --git a/src/companion/sources.js b/src/companion/sources.js
new file mode 100644
index 000000000..65cec9f48
--- /dev/null
+++ b/src/companion/sources.js
@@ -0,0 +1,236 @@
+// The connection cards on /companion.
+//
+// Four lanes, each of which the user owns end to end:
+// • the phone and desktop bridge (a token, and anything that can POST),
+// • Telegram (a bot the user creates with @BotFather),
+// • a calendar (the private ICS URL every calendar app publishes),
+// • email (IMAP with an app password).
+//
+// A card is either a connected state (what it is, when it last ran, what the
+// provider last said) or the form that connects it. Both are rendered from the
+// same data so a connection that starts erroring explains itself in place.
+
+const KINDS = {
+ telegram: {
+ icon: '✈️',
+ title: 'Telegram',
+ sub: 'A bot you own relays the chats you add it to. Nothing else in your account is readable.',
+ },
+ calendar: {
+ icon: '📅',
+ title: 'Calendar',
+ sub: 'The private iCal link from Google, Apple, Outlook, or any CalDAV server. Read only, revocable by you.',
+ },
+ email: {
+ icon: '✉️',
+ title: 'Email',
+ sub: 'IMAP with an app password. Headers and a short preview only, and your unread state is never touched.',
+ },
+};
+
+export function esc(value) {
+ return String(value == null ? '' : value)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+function relTime(iso) {
+ if (!iso) return 'never';
+ const delta = Date.now() - Date.parse(iso);
+ if (!Number.isFinite(delta)) return 'never';
+ const mins = Math.round(delta / 60000);
+ if (mins < 1) return 'just now';
+ if (mins < 60) return `${mins}m ago`;
+ const hours = Math.round(mins / 60);
+ if (hours < 24) return `${hours}h ago`;
+ return `${Math.round(hours / 24)}d ago`;
+}
+
+function statusChip(source) {
+ if (!source.enabled) return '<span class="chip">paused</span>';
+ if (source.status === 'error') return '<span class="chip err">needs attention</span>';
+ if (source.status === 'ok') return '<span class="chip ok">live</span>';
+ return '<span class="chip warn">not checked yet</span>';
+}
+
+function connectedBody(source) {
+ const config = source.config || {};
+ const detail = source.kind === 'telegram'
+ ? (config.bot_username ? `@${config.bot_username}` : 'bot connected')
+ : source.kind === 'calendar'
+ ? `${config.ics_host || 'calendar feed'} · looks ${config.lookahead_minutes || 30} min ahead`
+ : `${config.user || ''} · ${config.host || ''}${config.folder && config.folder !== 'INBOX' ? ` · ${config.folder}` : ''}`;
+
+ const hintByKind = {
+ telegram: config.bot_username
+ ? `Message <strong>@${esc(config.bot_username)}</strong> from your phone, or add it to a group, and it reaches your companion.`
+ : '',
+ calendar: 'Events are announced as they approach, once each.',
+ email: 'New mail only. The first check starts from now, so your archive stays quiet.',
+ };
+
+ return `
+ <div class="connected">
+ <div>
+ <div>${esc(source.label)} ${statusChip(source)}</div>
+ <div class="connected-meta">${esc(detail)} · checked ${relTime(source.last_polled_at)}</div>
+ </div>
+ <div class="hero-actions">
+ <button type="button" class="btn btn-sm" data-action="poll" data-id="${esc(source.id)}">Check now</button>
+ <button type="button" class="btn btn-sm" data-action="toggle" data-id="${esc(source.id)}" data-enabled="${source.enabled ? '1' : '0'}">${source.enabled ? 'Pause' : 'Resume'}</button>
+ <button type="button" class="btn btn-sm btn-danger" data-action="disconnect" data-id="${esc(source.id)}">Disconnect</button>
+ </div>
+ </div>
+ ${source.status === 'error' && source.last_error ? `<div class="error" style="margin:0">${esc(source.last_error)}</div>` : ''}
+ ${hintByKind[source.kind] ? `<div class="hint">${hintByKind[source.kind]}</div>` : ''}
+ `;
+}
+
+function formBody(kind) {
+ if (kind === 'telegram') {
+ return `
+ <form class="src-body" data-connect="telegram">
+ <label class="field">
+ Bot token
+ <input type="password" name="bot_token" placeholder="123456789:AA..." autocomplete="off" required minlength="20" />
+ </label>
+ <div class="hint">
+ Open <a href="https://t.me/BotFather" target="_blank" rel="noopener noreferrer">@BotFather</a> in Telegram,
+ send <code>/newbot</code>, and paste the token it gives you. Then message your new bot, or add it to the
+ group you want relayed.
+ </div>
+ <button type="submit" class="btn btn-primary">Connect Telegram</button>
+ </form>
+ `;
+ }
+ if (kind === 'calendar') {
+ return `
+ <form class="src-body" data-connect="calendar">
+ <label class="field">
+ Private iCal URL
+ <input type="text" name="ics_url" placeholder="https://calendar.google.com/calendar/ical/.../basic.ics" required />
+ </label>
+ <label class="field">
+ Tell me this far ahead
+ <select name="lookahead_minutes">
+ <option value="10">10 minutes</option>
+ <option value="30" selected>30 minutes</option>
+ <option value="60">1 hour</option>
+ <option value="120">2 hours</option>
+ </select>
+ </label>
+ <div class="hint">
+ Google Calendar: Settings for my calendars, then "Secret address in iCal format".
+ Apple: share the calendar and copy its link. Outlook: Publish a calendar, ICS.
+ </div>
+ <button type="submit" class="btn btn-primary">Connect calendar</button>
+ </form>
+ `;
+ }
+ return `
+ <form class="src-body" data-connect="email">
+ <div class="row">
+ <label class="field">
+ IMAP server
+ <input type="text" name="host" placeholder="imap.gmail.com" required />
+ </label>
+ <label class="field">
+ Port
+ <input type="number" name="port" value="993" min="1" max="65535" />
+ </label>
+ </div>
+ <div class="row">
+ <label class="field">
+ Address
+ <input type="text" name="user" placeholder="[email protected]" autocomplete="username" required />
+ </label>
+ <label class="field">
+ App password
+ <input type="password" name="pass" autocomplete="off" required />
+ </label>
+ </div>
+ <label class="field">
+ Folder
+ <input type="text" name="folder" value="INBOX" />
+ </label>
+ <div class="hint">
+ Use an app password, never your account password: Gmail and iCloud both issue one per app, and
+ revoking it here cuts the connection instantly. It is encrypted before it is stored.
+ </div>
+ <button type="submit" class="btn btn-primary">Connect inbox</button>
+ </form>
+ `;
+}
+
+function bridgeCard(bridge) {
+ const curl = `curl -X POST ${bridge.url} \\
+ -H "Authorization: Bearer ${bridge.token}" \\
+ -H "Content-Type: application/json" \\
+ -d '{"title":"Sarah is at the door","sender":"Sarah","app":"Messages","priority":"high"}'`;
+ return `
+ <article class="card src">
+ <div class="src-head">
+ <div class="src-icon">📱</div>
+ <div>
+ <div class="src-title">Phone and Mac</div>
+ <div class="src-sub">Forward anything that can make an HTTP request: an iOS Shortcuts automation, an Android profile, a Mail rule, a script.</div>
+ </div>
+ </div>
+ <div class="src-body">
+ <label class="field">
+ Your bridge token
+ <code class="token" id="bridge-token">${esc(bridge.token)}</code>
+ </label>
+ <div class="hero-actions">
+ <button type="button" class="btn btn-sm" data-action="copy-token">Copy token</button>
+ <button type="button" class="btn btn-sm" data-action="copy-curl">Copy example</button>
+ <button type="button" class="btn btn-sm" data-action="send-test">Send a test</button>
+ <button type="button" class="btn btn-sm btn-danger" data-action="rotate-token">Rotate</button>
+ </div>
+ <pre class="snippet">${esc(curl)}</pre>
+ <div class="hint">
+ Step by step recipes for iOS Shortcuts, Android, macOS, and Gmail are in
+ <a href="/docs/companion">the companion docs</a>. Rotating revokes every device at once.
+ </div>
+ </div>
+ </article>
+ `;
+}
+
+/**
+ * Render every connection card.
+ * @param {HTMLElement} host
+ * @param {{ sources: Array, bridge: {token:string,url:string} }} state
+ */
+export function renderSources(host, { sources, bridge }) {
+ const byKind = new Map();
+ for (const source of sources) {
+ if (!byKind.has(source.kind)) byKind.set(source.kind, []);
+ byKind.get(source.kind).push(source);
+ }
+
+ const cards = Object.entries(KINDS).map(([kind, meta]) => {
+ const connected = byKind.get(kind) || [];
+ return `
+ <article class="card src" data-kind="${kind}">
+ <div class="src-head">
+ <div class="src-icon">${meta.icon}</div>
+ <div>
+ <div class="src-title">${esc(meta.title)}</div>
+ <div class="src-sub">${esc(meta.sub)}</div>
+ </div>
+ </div>
+ <div class="src-body">
+ ${connected.map(connectedBody).join('')}
+ ${connected.length
+ ? `<details class="src-body"><summary class="btn btn-sm" style="width:fit-content;list-style:none">Connect another</summary><div style="margin-top:12px">${formBody(kind)}</div></details>`
+ : formBody(kind)}
+ </div>
+ </article>
+ `;
+ });
+
+ host.innerHTML = bridgeCard(bridge) + cards.join('');
+}
diff --git a/src/companion/speak.js b/src/companion/speak.js
new file mode 100644
index 000000000..48fc9325e
--- /dev/null
+++ b/src/companion/speak.js
@@ -0,0 +1,78 @@
+// Speaking a delivery out loud on the companion page.
+//
+// The platform TTS lanes (POST /api/tts/speak) are the voice: real synthesis in
+// the voice the user picked for that contact, same catalog as Voice Lab. When
+// no lane can serve (every provider over quota, or a browser that will not play
+// the returned container), the browser's own speech synthesis finishes the job
+// rather than leaving a silent button. Audio only ever starts from a click, so
+// nothing here can autoplay at somebody.
+
+const FALLBACK_VOICE = 'alloy';
+
+let current = null;
+
+export function stopSpeaking() {
+ if (current?.audio) {
+ current.audio.pause();
+ current.audio.src = '';
+ }
+ if (current?.controller) current.controller.abort();
+ if (current?.url) URL.revokeObjectURL(current.url);
+ current = null;
+ try {
+ window.speechSynthesis?.cancel();
+ } catch {
+ /* no speech synthesis in this browser */
+ }
+}
+
+function speakWithBrowser(text) {
+ try {
+ if (!window.speechSynthesis || !window.SpeechSynthesisUtterance) return false;
+ const utterance = new SpeechSynthesisUtterance(text);
+ utterance.rate = 1.02;
+ window.speechSynthesis.cancel();
+ window.speechSynthesis.speak(utterance);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Say one line. Returns 'tts' | 'browser' | 'silent' so the caller can tell the
+ * user what actually happened instead of pretending it spoke.
+ */
+export async function speak(text, { voice = FALLBACK_VOICE } = {}) {
+ const line = String(text || '').trim();
+ if (!line) return 'silent';
+ stopSpeaking();
+
+ const controller = new AbortController();
+ current = { controller, audio: null, url: null };
+
+ try {
+ const res = await fetch('/api/tts/speak', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ text: line, voice, format: 'mp3' }),
+ signal: controller.signal,
+ });
+ if (!res.ok) throw new Error(`tts ${res.status}`);
+ const blob = await res.blob();
+ if (!blob || blob.size === 0) throw new Error('empty clip');
+
+ const url = URL.createObjectURL(blob);
+ const audio = new Audio(url);
+ current = { controller: null, audio, url };
+ audio.onended = () => stopSpeaking();
+ audio.onerror = () => stopSpeaking();
+ await audio.play();
+ return 'tts';
+ } catch (err) {
+ stopSpeaking();
+ if (err?.name === 'AbortError') return 'silent';
+ return speakWithBrowser(line) ? 'browser' : 'silent';
+ }
+}
diff --git a/src/notification-herald.js b/src/notification-herald.js
index 52a16ba00..c17ea1b30 100644
--- a/src/notification-herald.js
+++ b/src/notification-herald.js
@@ -269,6 +269,19 @@ function ensureCompanion() {
let _speaker = null;
+/**
+ * Hand the avatar over to the message: page-section narration stops and stays
+ * quiet for the length of the delivery, so its caption never covers the bubble
+ * and its voice never talks over the line.
+ */
+function quietTheNarrator(ms) {
+ try {
+ window.__walkNarrator?.api?.suspend?.(ms);
+ } catch {
+ /* narrator not installed on this page */
+ }
+}
+
/**
* Speak the line aloud, but only when the visitor already chose voice for the
* companion's narration ("walk:companion:narrate" = voice, set from the
@@ -278,9 +291,6 @@ async function speakAloud(text) {
try {
const mod = await import('./walk-companion-narrator.js');
if (mod.narrationMode() !== 'voice') return;
- // Page-section narration and an announcement share one voice; the
- // announcement wins.
- window.__walkNarrator?.api?.silence?.();
if (!_speaker) _speaker = mod.createSpeaker();
_speaker.speak(text);
} catch {
@@ -341,6 +351,29 @@ async function run() {
}
}
+/**
+ * The body that should deliver this line.
+ *
+ * A companion delivery carries whoever it is from: the contact's own avatar
+ * when the visitor gave that person one on /companion, the account's default
+ * companion body otherwise. `announce({ avatar })` swaps without persisting and
+ * restores the visitor's own avatar afterwards, so a message from Sarah really
+ * does arrive as Sarah and leaves your own companion where it was.
+ */
+async function guestAvatarFor(n) {
+ const url = n?.payload?.avatar_glb_url;
+ if (!url || typeof url !== 'string') return null;
+ if (!/^https?:\/\//i.test(url) && !url.startsWith('/')) return null;
+ try {
+ const { makeGuestAvatarEntry } = await import('../walk-sdk/src/roster.js');
+ return makeGuestAvatarEntry(url, { id: `companion:${url}`, name: n.payload.sender || 'Your contact' });
+ } catch {
+ // The roster module failed to load: deliver in the visitor's own body
+ // rather than losing the message.
+ return null;
+ }
+}
+
async function deliver(item) {
const [{ TYPE_ICON, notifLabel, notifLink, trackInApp }, walk] = await Promise.all([
import('./notifications.js'),
@@ -374,14 +407,35 @@ async function deliver(item) {
if (!walk?.announce) return fallbackToast(line);
+ // Reserve the avatar for the length of the delivery plus its retraction.
+ quietTheNarrator(hold + 1200);
speakAloud(line);
const shown = await walk.announce(`${icon} ${line}`, {
hold,
tone: 'alert',
emote: n ? emoteFor(n.type) : 'wave',
actions,
+ avatar: n ? await guestAvatarFor(n) : null,
});
if (!shown) fallbackToast(line);
+ if (shown && n?.type === 'companion_delivery' && n.payload?.event_id) markCompanionDelivered(n.payload.event_id);
+}
+
+/**
+ * Tell the server the companion actually said this one out loud, so the same
+ * message is not waiting to be spoken again on the next device the visitor
+ * picks up. Fire and forget: the line has already been delivered either way.
+ */
+function markCompanionDelivered(eventId) {
+ import('./api.js')
+ .then(({ apiFetch }) => apiFetch(`/api/companion/events/${encodeURIComponent(eventId)}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ delivered: true }),
+ }))
+ .catch(() => {
+ /* offline: the cron's own delivered_at stamp still covers it */
+ });
}
/**
diff --git a/src/notifications-page.js b/src/notifications-page.js
index 585f88ab9..0b84a3e93 100644
--- a/src/notifications-page.js
+++ b/src/notifications-page.js
@@ -23,6 +23,7 @@ const TYPE_CATEGORY = {
quest_complete: 'social',
irl_interaction: 'irl', irl_reply: 'irl',
pump_alert: 'alerts',
+ companion_delivery: 'companion',
forge_complete: 'creations', forge_failed: 'creations',
withdrawal_completed: 'account', withdrawal_failed: 'account', payment_mismatch: 'account',
asset_payment_mismatch: 'account', skill_payment_mismatch: 'account', security_alert: 'account',
diff --git a/src/notifications.js b/src/notifications.js
index be9394246..77d114ff1 100644
--- a/src/notifications.js
+++ b/src/notifications.js
@@ -90,6 +90,7 @@ export const TYPE_ICON = {
forge_failed: '⚠️',
quest_complete: '🏆',
royalty_paid: '💰',
+ companion_delivery: '👋',
};
export function notifLabel(n) {
@@ -162,6 +163,11 @@ export function notifLabel(n) {
return p.mission
? `You finished "${p.mission}"${p.gold ? ` — earned ${p.gold} gold` : ''}`
: `You finished a quest`;
+ case 'companion_delivery':
+ // The spoken line the triage pass already wrote. It is the whole
+ // point of the delivery, so the inbox reads exactly like the avatar
+ // sounds. Falls back to the subject when a line never got written.
+ return p.line || (p.sender ? `${p.sender}: ${p.title || 'has something for you'}` : p.title || 'Something needs you');
case 'royalty_paid':
return p.usd
? `${p.actor || 'A fork of your avatar'} paid you $${Number(p.usd).toFixed(3)} in royalties`
diff --git a/src/walk-companion-narrator.js b/src/walk-companion-narrator.js
index fd0d96f4c..37571aa35 100644
--- a/src/walk-companion-narrator.js
+++ b/src/walk-companion-narrator.js
@@ -385,6 +385,7 @@ export function installNarrator({ getInstance, getHostEl, storageKey } = {}) {
// ── Observer + active-section tracking ──────────────────────────────────────
let observer = null;
+ let suspendedUntil = 0;
let currentSection = null;
let debounceTimer = 0;
let sections = [];
@@ -414,6 +415,10 @@ export function installNarrator({ getInstance, getHostEl, storageKey } = {}) {
function narrate(el) {
const text = extractText(el);
if (!text || mode === 'off') return;
+ // Something more important is using the avatar right now (a delivered
+ // notification, see src/notification-herald.js). Section reading resumes
+ // on its own once the window passes.
+ if (Date.now() < suspendedUntil) return;
const wantVoice = mode === 'voice' && userGestureSeen;
// Caption is the always-on channel; show it immediately. When audio is
@@ -525,6 +530,13 @@ export function installNarrator({ getInstance, getHostEl, storageKey } = {}) {
caption.hide();
currentSection = null;
},
+ // Silence, and stay quiet for `ms`, so a section scrolling into view
+ // cannot cover a message the avatar is in the middle of delivering. The
+ // mode is untouched: narration resumes by itself afterwards.
+ suspend(ms) {
+ suspendedUntil = Math.max(suspendedUntil, Date.now() + (Number(ms) || 0));
+ api.silence();
+ },
};
function uninstall() {
diff --git a/tests/companion-triage.test.js b/tests/companion-triage.test.js
new file mode 100644
index 000000000..de235778e
--- /dev/null
+++ b/tests/companion-triage.test.js
@@ -0,0 +1,139 @@
+// The companion's decision rules: what is worth interrupting a person for.
+//
+// Only the deterministic pass is exercised here. It is the one that always
+// runs (api/_lib/companion/triage.js), it needs no key, and it is the floor the
+// LLM refinement is measured against, so a regression in it is a regression in
+// every delivery the platform makes.
+
+import { describe, it, expect } from 'vitest';
+import { scoreByRules, defaultLine, shorten } from '../api/_lib/companion/triage.js';
+import { normalizeIdentifier } from '../api/_lib/companion/store.js';
+import { inQuietHours } from '../api/_lib/companion/poll.js';
+
+const contact = (over = {}) => ({ id: 'c1', display_name: 'Sarah', priority_boost: 0, ...over });
+
+describe('scoreByRules', () => {
+ it('puts a saved contact asking for something above a stranger saying the same thing', () => {
+ const message = { source_kind: 'telegram', sender: 'Sarah', body: 'call me when you can' };
+ const known = scoreByRules(message, contact());
+ const stranger = scoreByRules(message, null);
+ expect(known.importance).toBeGreaterThan(stranger.importance);
+ expect(known.reason).toContain('Sarah');
+ });
+
+ it('treats a login code as urgent even from nobody in particular', () => {
+ const verdict = scoreByRules({
+ source_kind: 'email',
+ sender: 'Bank',
+ sender_id: '[email protected]',
+ title: 'Your verification code is 483920',
+ body: 'Use this one-time code to finish signing in.',
+ });
+ expect(verdict.importance).toBeGreaterThanOrEqual(70);
+ });
+
+ it('floors marketing mail from an unattended address', () => {
+ const verdict = scoreByRules({
+ source_kind: 'email',
+ sender: 'Shop',
+ sender_id: '[email protected]',
+ title: '50% off, sale ends tonight',
+ body: 'Shop the promotion now. Unsubscribe any time.',
+ });
+ expect(verdict.importance).toBeLessThan(20);
+ });
+
+ it('scores a calendar event by how soon it starts', () => {
+ const base = { source_kind: 'calendar', title: 'Design review' };
+ const soon = scoreByRules({ ...base, occurs_at: new Date(Date.now() + 4 * 60_000).toISOString() });
+ const later = scoreByRules({ ...base, occurs_at: new Date(Date.now() + 50 * 60_000).toISOString() });
+ expect(soon.importance).toBeGreaterThan(later.importance);
+ });
+
+ it('honours the priority the sending device already decided', () => {
+ const base = { source_kind: 'bridge', sender: 'Messages', title: 'ping' };
+ const high = scoreByRules({ ...base, priority_hint: 'high' });
+ const low = scoreByRules({ ...base, priority_hint: 'low' });
+ expect(high.importance - low.importance).toBe(40);
+ });
+
+ it('never leaves the 0 to 100 range', () => {
+ const loud = scoreByRules(
+ {
+ source_kind: 'calendar',
+ title: 'URGENT: emergency, call me now',
+ body: 'verification code, payment declined, flight cancelled, where are you?',
+ occurs_at: new Date(Date.now() + 60_000).toISOString(),
+ priority_hint: 'high',
+ },
+ contact({ priority_boost: 100 }),
+ );
+ expect(loud.importance).toBe(100);
+ const quiet = scoreByRules({
+ source_kind: 'email',
+ sender_id: '[email protected]',
+ title: 'newsletter',
+ body: 'unsubscribe promotion webinar survey',
+ });
+ expect(quiet.importance).toBe(0);
+ });
+});
+
+describe('defaultLine', () => {
+ it('names the contact rather than the raw handle', () => {
+ const line = defaultLine(
+ { source_kind: 'telegram', sender: '@sarah_k', body: 'I am downstairs' },
+ contact(),
+ );
+ expect(line).toBe('Sarah says: I am downstairs');
+ });
+
+ it('says how long is left before a calendar event', () => {
+ const line = defaultLine({
+ source_kind: 'calendar',
+ title: 'Design review',
+ occurs_at: new Date(Date.now() + 9 * 60_000).toISOString(),
+ });
+ expect(line).toMatch(/Design review is in \d+ minutes/);
+ });
+});
+
+describe('shorten', () => {
+ it('leaves a short line untouched and clips a long one', () => {
+ expect(shorten('all good')).toBe('all good');
+ const long = shorten('word '.repeat(200), 60);
+ expect(long.length).toBeLessThanOrEqual(61);
+ expect(long.endsWith('…')).toBe(true);
+ });
+
+ it('collapses the whitespace an email preview arrives with', () => {
+ expect(shorten('one\n\n two\t three')).toBe('one two three');
+ });
+});
+
+describe('normalizeIdentifier', () => {
+ it('resolves the same person across lanes', () => {
+ expect(normalizeIdentifier('@Sarah')).toBe('sarah');
+ expect(normalizeIdentifier('Sarah K <[email protected]>')).toBe('[email protected]');
+ expect(normalizeIdentifier('+1 (415) 555-0100')).toBe('+14155550100');
+ expect(normalizeIdentifier(' ')).toBe('');
+ });
+});
+
+describe('inQuietHours', () => {
+ const settings = { quiet_start: 22, quiet_end: 7, timezone: 'America/New_York' };
+
+ it('covers a window that wraps midnight', () => {
+ expect(inQuietHours(settings, new Date('2026-08-28T07:00:00Z'))).toBe(true); // 03:00 NY
+ expect(inQuietHours(settings, new Date('2026-08-28T16:00:00Z'))).toBe(false); // 12:00 NY
+ expect(inQuietHours(settings, new Date('2026-08-29T03:00:00Z'))).toBe(true); // 23:00 NY
+ });
+
+ it('is off entirely when no window is set', () => {
+ expect(inQuietHours({ quiet_start: null, quiet_end: null, timezone: 'UTC' })).toBe(false);
+ });
+
+ it('falls back to UTC rather than throwing on a bad timezone', () => {
+ expect(inQuietHours({ quiet_start: 0, quiet_end: 6, timezone: 'Not/AZone' }, new Date('2026-08-28T03:00:00Z'))).toBe(true);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 19fd6580d..a1eadcdf4 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2604,6 +2604,14 @@
"src": "/collection/",
"dest": "/collection.html"
},
+ {
+ "src": "/companion",
+ "dest": "/companion.html"
+ },
+ {
+ "src": "/companion/",
+ "dest": "/companion.html"
+ },
{
"src": "/notifications",
"dest": "/notifications.html"
@@ -6127,6 +6135,10 @@
{
"path": "/api/cron/gpu-keepwarm",
"schedule": "*/10 14-23,0-4 * * *"
+ },
+ {
+ "path": "/api/cron/companion-poll",
+ "schedule": "*/2 * * * *"
}
]
}
diff --git a/vite.config.js b/vite.config.js
index 3c94d2e72..ad32f7bf4 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -612,6 +612,7 @@ const appConfig = {
// transitively. HTML output paths come from the source file path,
// not the input key, so the page still emits dist/notifications.html.
'notifications-page': resolve(__dirname, 'pages/notifications.html'),
+ companion: resolve(__dirname, 'pages/companion.html'),
'agent-edit': resolve(__dirname, 'pages/agent-edit.html'),
'agent-mind': resolve(__dirname, 'pages/agent-mind.html'),
'avatar-edit': resolve(__dirname, 'pages/avatar-edit.html'),
diff --git a/walk-sdk/README.md b/walk-sdk/README.md
index 1579157ce..8ca921c94 100644
--- a/walk-sdk/README.md
+++ b/walk-sdk/README.md
@@ -160,11 +160,48 @@ control.disable(): void
control.toggle(): void
control.setAvatar(idOrEntry): void // persist + hot-swap the live avatar
control.openPicker(): void
+control.announce(message, opts?): Promise<boolean> // deliver a line in person
control.bootstrap(): void // app-style auto-mount + ?walk= deep links
control.instance // the live companion (or null)
control.config // the resolved options, storage keys included
```
+### `control.announce(message, options?)`
+
+Deliver a message in person. The companion turns to the visitor, plays a
+gesture, and shows the line in its speech bubble. If it is not on screen (the
+visitor never turned it on, or closed it) it is summoned silently for this one
+message and walks off again afterwards, without flipping the persisted enabled
+flag: "off" stays off once the message is delivered.
+
+```js
+const walk = createWalkCompanion();
+
+const delivered = await walk.announce('Your model finished rendering', {
+ tone: 'alert',
+ emote: 'dance',
+ actions: [
+ { label: 'Open', href: '/creations', title: 'Open your finished model' },
+ { label: 'Turn off', onClick: () => muteAnnouncements() },
+ ],
+});
+if (!delivered) showYourOwnToast(); // no WebGL, an iframe, or an excluded route
+```
+
+| option | default | description |
+| --------- | ---------- | ------------------------------------------------------------------ |
+| `hold` | `7000` | ms the bubble stays up |
+| `tone` | `'alert'` | `'alert'` tints the bubble; `'neutral'` is the ambient style |
+| `emote` | `'wave'` | gesture on arrival, falling back to a wave on rigs without it |
+| `actions` | none | up to two links/buttons under the line (`label`, `href`/`onClick`) |
+
+Returns `false` when no avatar could be shown, so the caller can fall back to
+its own UI. The message is rendered as text, never HTML. A delivery outranks
+the companion's ambient chatter: a page greeting cannot overwrite it while it
+is on screen. `control.instance.say(text, opts)` and
+`control.instance.hideBubble()` drive the same bubble directly when you are
+managing the mount yourself.
+
### Roster helpers
```js
diff --git a/walk-sdk/src/companion.js b/walk-sdk/src/companion.js
index 7ff30eec8..d3d66dae3 100644
--- a/walk-sdk/src/companion.js
+++ b/walk-sdk/src/companion.js
@@ -112,6 +112,9 @@ class WalkCompanion {
this._cursorX = window.innerWidth * 0.5;
this._cursorY = window.innerHeight * 0.5;
this._cursorMovedAt = 0;
+ // Bubble arbitration: what is on screen now and until when (see say()).
+ this._bubblePriority = 0;
+ this._bubbleUntil = 0;
this._yaw = 0;
this._targetYaw = 0;
this._lookAt = null;
@@ -542,10 +545,18 @@ class WalkCompanion {
* up until the next say()/hideBubble().
* @param {'neutral'|'alert'} [opts.tone='neutral'] 'alert' tints the bubble.
* @param {Array<{label:string, href?:string, title?:string, onClick?:Function}>} [opts.actions]
+ * @param {number} [opts.priority=0] higher wins: a line at a lower priority
+ * is dropped while a higher-priority one is still showing. Deliveries
+ * (announce) speak at 1, ambient chatter at 0.
* @returns {boolean} false when there is no bubble to render into.
*/
- say(text, { hold = BUBBLE_HOLD_MS, tone = 'neutral', actions = null } = {}) {
+ say(text, { hold = BUBBLE_HOLD_MS, tone = 'neutral', actions = null, priority = 0 } = {}) {
if (!this.bubble || !text) return false;
+ // The companion has more than one voice: the page greeting, the invite
+ // nudge, the identity introduction, and a delivered message all reach for
+ // the same bubble. A lower-priority line must never overwrite a delivery
+ // while it is still on screen, whichever fires first.
+ if (priority < this._bubblePriority && Date.now() < this._bubbleUntil) return false;
const bubble = this.bubble;
clearTimeout(this._bubbleTimer);
bubble.textContent = '';
@@ -588,6 +599,8 @@ class WalkCompanion {
bubble.classList.toggle('has-actions', rendered.length > 0);
bubble.hidden = false;
bubble.classList.add('is-in');
+ this._bubblePriority = priority;
+ this._bubbleUntil = hold > 0 ? Date.now() + hold : Number.MAX_SAFE_INTEGER;
if (hold > 0) this._bubbleTimer = setTimeout(() => this.hideBubble(), hold);
return true;
}
@@ -595,6 +608,8 @@ class WalkCompanion {
/** Retract the speech bubble now. */
hideBubble() {
clearTimeout(this._bubbleTimer);
+ this._bubblePriority = 0;
+ this._bubbleUntil = 0;
if (!this.bubble) return;
const bubble = this.bubble;
bubble.classList.remove('is-in');
@@ -856,7 +871,7 @@ export function createWalkCompanion(opts = {}) {
} catch {
/* rig without emotes: the bubble still carries the message */
}
- inst.say(message, { hold, tone, actions });
+ inst.say(message, { hold, tone, actions, priority: 1 });
const settle = async () => {
await new Promise((r) => setTimeout(r, hold + ANNOUNCE_RETREAT_MS));