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(herald): give a machine a voice on the owner's screen, not another inbox

nirholas466036792c80
diff --git a/api/_lib/herald.js b/api/_lib/herald.js
new file mode 100644
index 000000000..5ffa91fb1
--- /dev/null
+++ b/api/_lib/herald.js
@@ -0,0 +1,87 @@
+// Shared shape for the herald delivery rail (api/herald/*).
+//
+// One module owns the queue key, the caps, and the announcement shape so the
+// writer (announce.js) and the reader (stream.js) can never disagree about
+// what is in Redis. Pure: no I/O, no env, unit-testable on its own.
+
+/** Live channel, not an archive: an unheard line expires rather than piles up. */
+export const QUEUE_TTL_SECONDS = 300;
+/** A backlog beyond this is noise; the newest win. */
+export const QUEUE_CAP = 20;
+/** Cap the line length the same way the API validates it. */
+export const TEXT_MAX = 280;
+
+export function queueKey(userId) {
+ return `herald:${userId}:queue`;
+}
+
+/**
+ * Only same-origin paths and absolute http(s) URLs may drive a click-through.
+ * Anything else (javascript:, data:, a protocol-relative //host) is dropped, so
+ * a compromised integration cannot turn a spoken line into a script execution
+ * or an off-site redirect on the recipient's own page.
+ */
+export function safeUrl(raw) {
+ if (!raw || typeof raw !== 'string') return null;
+ const s = raw.trim();
+ if (!s) return null;
+ if (s.startsWith('/') && !s.startsWith('//')) return s;
+ if (/^https?:\/\//i.test(s)) return s;
+ return null;
+}
+
+/** Collapse whitespace and hard-cap a line so one long payload cannot dominate. */
+export function cleanText(raw, max = TEXT_MAX) {
+ return String(raw ?? '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, max);
+}
+
+/**
+ * Build the announcement record that goes on the wire.
+ * @param {object} input validated request body plus `text`
+ * @param {() => number} [clock] injectable for tests
+ * @param {() => string} [idFactory]
+ */
+export function normalizeAnnouncement(input, clock = Date.now, idFactory = randomId) {
+ const at = clock();
+ const text = cleanText(input.text);
+ return {
+ id: idFactory(),
+ text,
+ from: input.from ? cleanText(input.from, 60) : undefined,
+ importance:
+ input.importance == null ? 70 : Math.max(0, Math.min(100, Math.round(input.importance))),
+ url: safeUrl(input.url) || undefined,
+ tone: input.tone || 'alert',
+ emote: input.emote ? cleanText(input.emote, 40) : undefined,
+ // The dedupe key defaults to the id, which makes every announcement
+ // distinct; an integrator sending the same key twice is telling us the
+ // two are the same event, and the SDK will only say it once.
+ key: input.key ? cleanText(input.key, 120) : undefined,
+ meta: input.meta && typeof input.meta === 'object' ? input.meta : undefined,
+ at,
+ };
+}
+
+function randomId() {
+ // crypto.randomUUID exists in every runtime this ships on (Node 18+ and
+ // modern browsers); the fallback keeps the module usable in a bare test env.
+ return globalThis.crypto?.randomUUID?.() ?? `h_${Math.random().toString(36).slice(2, 12)}`;
+}
+
+/**
+ * Decode one record read back out of Redis. The Upstash REST client parses JSON
+ * responses, so a value written as a JSON string can come back already parsed.
+ * Both shapes are valid; anything else is unusable and skipped.
+ */
+export function parseRecord(value) {
+ if (value && typeof value === 'object') return value;
+ if (typeof value !== 'string') return null;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return null;
+ }
+}
diff --git a/api/api-keys.js b/api/api-keys.js
index f5a3fd3db..de334427f 100644
--- a/api/api-keys.js
+++ b/api/api-keys.js
@@ -7,7 +7,7 @@ import { requireCsrf } from './_lib/csrf.js';
import { parse } from './_lib/validate.js';
import { z } from 'zod';
-const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile', 'memory:read', 'memory:write', 'agents:read', 'agents:write']);
+const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile', 'memory:read', 'memory:write', 'agents:read', 'agents:write', 'herald:announce']);
const createSchema = z.object({
name: z.string().trim().min(1).max(80),
diff --git a/api/herald/announce.js b/api/herald/announce.js
new file mode 100644
index 000000000..908596478
--- /dev/null
+++ b/api/herald/announce.js
@@ -0,0 +1,105 @@
+// POST /api/herald/announce: make your own avatar say something, from anywhere.
+//
+// This is the rail behind @three-ws/herald (herald-sdk/). Anything that can
+// make an HTTPS request (a deploy script, a CI job, a cron, an AI agent holding
+// an API key) posts a line here, and the browser tab the human is actually
+// looking at hears it: the corner companion walks on, gestures, and says it.
+//
+// curl -X POST https://three.ws/api/herald/announce \
+// -H "Authorization: Bearer sk_live_..." \
+// -H 'content-type: application/json' \
+// -d '{"text":"Deploy is green","importance":80,"url":"/dashboard"}'
+//
+// Addressing is the security model: a message is always delivered to the
+// *authenticated caller's own* sessions. There is no `to` field, so no key can
+// ever be used to interrupt somebody else, and a leaked key can annoy exactly
+// one person: the person who leaked it. Revoke it at /dashboard/developers.
+//
+// Storage is a short-lived Redis list per user (no table, no migration, no
+// retention question). GET /api/herald/stream drains it. A message nobody was
+// online to hear expires on its own: this is a live channel, and the durable
+// record of what happened to an account is the notification bell, not this.
+
+import { z } from 'zod';
+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { limits } from '../_lib/rate-limit.js';
+import { getRedis } from '../_lib/redis.js';
+import { parse } from '../_lib/validate.js';
+import { queueKey, QUEUE_TTL_SECONDS, QUEUE_CAP, normalizeAnnouncement } from '../_lib/herald.js';
+
+const body = z.object({
+ // `text` is the line. `message` is accepted as an alias because every
+ // integrator's first guess is one or the other, and a 400 on a synonym is a
+ // bad first minute with an API.
+ text: z.string().trim().min(1).max(280).optional(),
+ message: z.string().trim().min(1).max(280).optional(),
+ from: z.string().trim().max(60).optional(),
+ importance: z.coerce.number().int().min(0).max(100).optional(),
+ url: z.string().trim().max(2048).optional(),
+ tone: z.enum(['neutral', 'alert', 'celebrate', 'error']).optional(),
+ emote: z.string().trim().max(40).optional(),
+ key: z.string().trim().max(120).optional(),
+ meta: z.record(z.unknown()).optional(),
+});
+
+async function resolveCaller(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, via: 'session' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ // An API key needs the scope explicitly: a key minted for avatar reads must
+ // not gain the ability to interrupt its owner because this route shipped.
+ if (bearer && hasScope(bearer.scope, 'herald:announce')) {
+ return { userId: bearer.userId, via: 'apikey' };
+ }
+ if (bearer) return { userId: null, via: 'insufficient_scope' };
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const caller = await resolveCaller(req);
+ if (!caller) {
+ return error(res, 401, 'unauthorized', 'sign in or send a key with the herald:announce scope');
+ }
+ if (!caller.userId) {
+ return error(res, 403, 'insufficient_scope', 'this key is missing the herald:announce scope');
+ }
+
+ const rl = await limits.heraldAnnounce(caller.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const input = parse(body, await readJson(req));
+ const text = input.text || input.message;
+ if (!text) return error(res, 400, 'validation_error', 'text is required');
+
+ const announcement = normalizeAnnouncement({ ...input, text });
+
+ const redis = getRedis();
+ if (!redis) {
+ // No Redis configured is a deployment problem, not a caller problem, and
+ // it must not read as "delivered".
+ return error(res, 503, 'service_unavailable', 'the delivery rail is not available right now');
+ }
+
+ const key = queueKey(caller.userId);
+ try {
+ await redis.rpush(key, JSON.stringify(announcement));
+ await redis.ltrim(key, -QUEUE_CAP, -1);
+ await redis.expire(key, QUEUE_TTL_SECONDS);
+ } catch (err) {
+ console.error('[herald] queue write failed:', err.message);
+ return error(res, 503, 'service_unavailable', 'could not queue the announcement');
+ }
+
+ // `queued` is honest: it says the line is waiting for a live surface, not
+ // that a human heard it. Nothing here can promise the second thing.
+ return json(res, 202, {
+ queued: true,
+ id: announcement.id,
+ expires_in: QUEUE_TTL_SECONDS,
+ announcement,
+ });
+});
diff --git a/api/herald/stream.js b/api/herald/stream.js
new file mode 100644
index 000000000..f8d75a6cf
--- /dev/null
+++ b/api/herald/stream.js
@@ -0,0 +1,107 @@
+// GET /api/herald/stream: the live end of the delivery rail (SSE).
+//
+// The browser subscribes; POST /api/herald/announce writes; this drains the
+// caller's queue and emits each line as an `announce` event. @three-ws/herald's
+// railSource() consumes it, but it is plain SSE: `new EventSource()` in any
+// page, or `curl -N`, works exactly as well.
+//
+// Events:
+// event: open { ts } once, on connect
+// event: announce { id, text, ... } one per queued line
+// event: ping { ts } keepalive every 15s
+//
+// Session-cookie auth only, and it only ever reads the caller's own queue: a
+// stream cannot be pointed at another account, and an API key (which can write)
+// deliberately cannot read this. Writing is for machines, listening is for the
+// person sitting in front of the browser.
+//
+// The connection is capped below the platform's request ceiling and EventSource
+// reconnects on its own, so a long-lived page keeps hearing without any
+// reconnect logic of its own.
+
+import { cors, error, method, rateLimited, wrap } from '../_lib/http.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { limits } from '../_lib/rate-limit.js';
+import { getRedis } from '../_lib/redis.js';
+import { queueKey, parseRecord } from '../_lib/herald.js';
+
+export const maxDuration = 300;
+
+const MAX_DURATION_MS = 280_000;
+const PING_INTERVAL_MS = 15_000;
+const POLL_INTERVAL_MS = 1_000;
+const DRAIN_BATCH = 10;
+
+export default wrap(async function handleHeraldStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.heraldStream(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const redis = getRedis();
+ if (!redis) {
+ return error(res, 503, 'service_unavailable', 'the delivery rail is not available right now');
+ }
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active || res.writableEnded) return;
+ try {
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ } catch {
+ active = false;
+ }
+ };
+
+ req.on('close', () => {
+ active = false;
+ });
+
+ send('open', { ts: Date.now() });
+
+ const key = queueKey(user.id);
+ const started = Date.now();
+ let lastPing = started;
+
+ // LPOP with a count drains what is waiting and leaves nothing behind for a
+ // second tab to say again: a message is delivered to exactly one live
+ // surface, which is the whole difference between this and a broadcast.
+ while (active && Date.now() - started < MAX_DURATION_MS) {
+ let batch = [];
+ try {
+ const popped = await redis.lpop(key, DRAIN_BATCH);
+ batch = Array.isArray(popped) ? popped : popped ? [popped] : [];
+ } catch (err) {
+ // A transient Redis fault must not kill a stream the page depends on;
+ // keep the connection and try again on the next tick.
+ console.error('[herald] queue read failed:', err.message);
+ batch = [];
+ }
+
+ for (const raw of batch) {
+ const record = parseRecord(raw);
+ if (record) send('announce', record);
+ }
+
+ if (Date.now() - lastPing >= PING_INTERVAL_MS) {
+ lastPing = Date.now();
+ send('ping', { ts: lastPing });
+ }
+
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
+ }
+
+ if (!res.writableEnded) res.end();
+});
diff --git a/herald-sdk/LICENSE b/herald-sdk/LICENSE
new file mode 100644
index 000000000..b5ae2a4e1
--- /dev/null
+++ b/herald-sdk/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/herald-sdk/README.md b/herald-sdk/README.md
new file mode 100644
index 000000000..ee316a29a
--- /dev/null
+++ b/herald-sdk/README.md
@@ -0,0 +1,306 @@
+# @three-ws/herald
+
+**Deliver a message in person.**
+
+A notification is a badge you have to notice, in a tray you have to open,
+competing with forty others. This library delivers the ones that matter the way
+a colleague would: a 3D character walks into the corner of the page, looks at
+the person using it, and tells them, with a link to the thing it is about.
+
+```js
+import { createHerald } from '@three-ws/herald';
+
+const herald = createHerald();
+herald.announce({ text: 'Deploy is green', importance: 80, url: '/builds' });
+```
+
+That is the whole integration. What you get for it is not a toast library, it
+is a delivery discipline: importance scoring, an interrupt floor, quiet hours,
+a rate limit, dedupe with a TTL, freshness, batching with a collapse line, focus
+awareness, an accessible fallback for machines that cannot render 3D, and an
+audit trail of every message that did not make it and why.
+
+And from your terminal:
+
+```sh
+npx @three-ws/herald watch -- npm test
+```
+
+Your build runs. When it finishes, your avatar walks onto the browser tab you
+already have open and tells you whether it passed. The exit code is preserved,
+so it drops into a pipeline unchanged.
+
+---
+
+## Why
+
+Every alerting surface we have is a queue that competes for the same
+half-second of attention: a red dot, a rectangle that slides in, a phone buzz.
+They are all the same shape, they are all ignorable, and the important ones
+look exactly like the noise.
+
+A person walking up to your desk to tell you something is not ignorable, and
+nobody has to design an "unread state" for it. This is that, on the web, for
+the handful of events per day that deserve it. The scarcity is the feature:
+everything here exists to keep the interruption rare enough to stay effective.
+
+## Install
+
+```sh
+npm install @three-ws/herald
+# the 3D body is optional, and only needed for the avatar presenter
+npm install @three-ws/walk three
+```
+
+No build step, no bundler requirement, no CSS to import. The package is plain
+ES modules and ships its own styles inline. Node 18+ for the CLI.
+
+Without a bundler:
+
+```html
+<script type="module">
+ import { createHerald } from 'https://three.ws/herald.js';
+ createHerald().announce('Deployed to production');
+</script>
+```
+
+## Quick start
+
+### 1. Announce something
+
+```js
+const herald = createHerald({
+ rules: { minImportance: 60 },
+ voice: 'auto',
+});
+
+herald.announce({
+ text: 'Payment received from Acme',
+ from: 'Stripe',
+ importance: 85,
+ url: '/payments/inv_123',
+ tone: 'celebrate',
+});
+```
+
+`announce()` returns the verdict, so nothing is ever mysteriously silent:
+
+```js
+const verdict = herald.announce({ text: 'noise', importance: 5 });
+// { action: 'drop', reason: 'below-importance-floor', message: {...} }
+```
+
+### 2. Point it at a feed
+
+```js
+import { createHerald, pollSource, sseSource } from '@three-ws/herald';
+
+const herald = createHerald();
+
+// Any JSON endpoint. It stops polling while the tab is hidden.
+herald.source(pollSource({
+ url: '/api/alerts',
+ intervalMs: 30_000,
+ map: (a) => ({ id: a.id, text: a.title, importance: a.severity * 20, url: a.link }),
+}));
+
+// Or a stream you already have.
+herald.source(sseSource({ url: '/events', events: ['alert'] }));
+```
+
+A source is `{ name, start(emit) => stop }`. Anything you can subscribe to in
+five lines is a source, and the rules engine normalises whatever shape it
+emits, so pointing this at an existing feed rarely needs a mapper at all.
+
+### 3. Teach it what matters
+
+```js
+herald.rule((m) => (m.from === 'oncall' ? 100 : undefined));
+herald.rule((m) => (/\bfailed\b/i.test(m.text) ? 90 : undefined));
+```
+
+A scorer returns 0-100, or `undefined` to abstain. The highest opinion wins, a
+scorer that throws is ignored, and the score a message was judged with comes
+back in the verdict.
+
+## The rules
+
+Every default is chosen so that dropping this into a page cannot make it
+obnoxious. Override what you need.
+
+| Rule | Default | What it does |
+| --- | --- | --- |
+| `minImportance` | `50` | The interrupt floor. Below it, nothing is shown. |
+| `freshnessMs` | `15 min` | Older than this is history, and history belongs in an inbox. |
+| `dedupeTtlMs` | `6 h` | The same key is said once, however many times a feed repeats it. |
+| `quietHours` | `null` | Local `[start, end)`, wrapping past midnight (`[22, 7]`). |
+| `quietHoursMinImportance` | `90` | What still gets through the night. |
+| `maxPerWindow` | `4` | Deliveries per rate window. |
+| `rateWindowMs` | `60 s` | The window. |
+| `focusOnly` | `true` | Hold while the tab is in the background. |
+| `batchSize` | `2` | Said per burst, before the rest collapse into one line. |
+
+Anything that cannot be delivered right now is **held**, not lost, and
+re-examined when the thing blocking it clears (the window drains, quiet hours
+end, the tab comes back). Anything that will never be delivered is **dropped**
+with a reason you can read:
+
+```js
+herald.stats();
+// { received: 12, delivered: 5, dropped: 6, held: 1, spoken: 3,
+// drops: [{ at: 176..., reason: 'duplicate', text: 'Build failed' }, ...] }
+```
+
+Reasons are stable strings: `duplicate`, `stale`, `below-importance-floor`,
+`muted`, `empty`, and for holds `quiet-hours`, `rate-limited`,
+`window-not-focused`, `delivering-another`.
+
+## Presenters
+
+| Presenter | Needs | Used when |
+| --- | --- | --- |
+| `avatar` | `@three-ws/walk` or the CDN build, WebGL | A body can be rendered |
+| `card` | Nothing | Everything else |
+
+`presenter: 'auto'` (the default) tries the avatar and falls back to the card,
+per page, once. The card is not a consolation prize: it is theme-aware, honours
+`prefers-reduced-motion` and `prefers-color-scheme`, is dismissible with
+`Escape`, and lives in an `aria-live` region so a screen reader announces the
+line exactly when everyone else hears it.
+
+On a page that already runs a walk companion, the avatar presenter reuses it,
+so the person's own character delivers the message instead of a second one
+appearing beside it.
+
+## Voice
+
+```js
+createHerald({
+ voice: 'auto', // 'off' (default) | 'auto' | 'always'
+ voiceOptions: { endpoint: '/api/tts/speak', voice: 'nova' },
+});
+```
+
+`auto` speaks only once the browser has seen a real user gesture, which is what
+autoplay policy requires and what good manners require anyway. With no endpoint
+configured it falls back to the browser's own `speechSynthesis`. If audio is
+refused at any point, the text is already on screen: there is no silent failure
+and no "click to enable sound" nag.
+
+## The rail: announce from anywhere
+
+Running on three.ws, the SDK can listen to a hosted delivery rail. Anything
+that can make an HTTPS request can then reach the browser tab you have open:
+
+```js
+import { createHerald, railSource } from '@three-ws/herald';
+createHerald({ voice: 'auto' }).source(railSource());
+```
+
+```sh
+curl -X POST https://three.ws/api/herald/announce \
+ -H "Authorization: Bearer $THREE_WS_API_KEY" \
+ -H 'content-type: application/json' \
+ -d '{"text":"Deploy is green","importance":80,"url":"/dashboard"}'
+```
+
+A message is always delivered to the **authenticated caller's own** sessions.
+There is no "to" field, so a key can never be used to interrupt somebody else,
+and the worst a leaked key can do is annoy the person who leaked it. Keys are
+minted at `/dashboard/developers` with the `herald:announce` scope.
+
+## CLI
+
+```sh
+npm i -g @three-ws/herald # or npx @three-ws/herald ...
+export THREE_WS_API_KEY=sk_live_...
+
+herald say "Migration finished" --from "db" --url https://three.ws/dashboard
+herald watch --from CI -- npm test
+herald ping
+```
+
+`watch` runs the command with its stdio attached, keeps its exit code, times
+it, and announces the result (`passed in 2m` / `failed (exit 1) after 47s`).
+Failures arrive at importance 95, so they cut through quiet hours; successes at
+60, so they do not.
+
+## Recipes
+
+**Only interrupt for the on-call channel, and never at night:**
+
+```js
+const herald = createHerald({
+ rules: { minImportance: 70, quietHours: [22, 7], quietHoursMinImportance: 95 },
+});
+herald.rule((m) => (m.meta?.channel === 'oncall' ? 96 : undefined));
+```
+
+**Bridge an existing event bus:**
+
+```js
+import { manualSource } from '@three-ws/herald';
+const bus = manualSource();
+herald.source(bus);
+myEmitter.on('alert', (a) => bus.send({ id: a.id, text: a.title, importance: a.level }));
+```
+
+**Let the person silence it without losing the message:**
+
+```js
+createHerald({
+ actionsFor: (m) => [{ label: 'Mute 1h', onClick: () => herald.mute(3_600_000) }],
+});
+```
+
+**Server-side triage, client-side delivery:** score on your backend, send the
+number, and keep the client rules simple.
+
+```js
+herald.source(sseSource({ url: '/events', map: (e) => ({ ...e, importance: e.score }) }));
+```
+
+## API
+
+```ts
+createHerald(options?) => Herald
+
+Herald.announce(message | string) => { action, reason?, message }
+Herald.source(source) => stop
+Herald.rule(scorer) => Herald
+Herald.mute(ms?) => Herald
+Herald.unmute() => Herald
+Herald.muted: boolean
+Herald.rules: Rules
+Herald.stats() => { received, delivered, dropped, held, spoken, holding, drops }
+Herald.stop() => void
+```
+
+A `Message` is `{ id?, key?, text, importance?, from?, url?, at?, tone?, emote?,
+meta? }`. Only `text` is required. `tone` is `neutral | alert | celebrate |
+error`; `emote` is a gesture name the avatar rig understands (`wave`, `dance`,
+`punch`, `backflip`).
+
+The rules engine is exported on its own for anyone who wants the judgement
+without the delivery:
+
+```js
+import { decide, planBatch, resolveRules } from '@three-ws/herald/rules';
+```
+
+## Accessibility and performance
+
+- Every delivery is in a live region, spoken to assistive technology at the
+ same moment it is spoken to everyone else.
+- `prefers-reduced-motion` removes the entrance animation and the countdown
+ bar, not the message.
+- The card presenter has a real focus ring, an `Escape` handler, and buttons
+ that are buttons.
+- Nothing is loaded until it is needed: the 3D body is a dynamic import that
+ only happens when an avatar delivery actually occurs.
+- Polling sources stop while the tab is hidden.
+
+## License
+
+Apache-2.0. Built by [three.ws](https://three.ws), where it delivers the
+platform's own notifications: see [the herald playground](https://three.ws/herald).
diff --git a/herald-sdk/bin/herald.mjs b/herald-sdk/bin/herald.mjs
new file mode 100755
index 000000000..902da2f55
--- /dev/null
+++ b/herald-sdk/bin/herald.mjs
@@ -0,0 +1,230 @@
+#!/usr/bin/env node
+// herald: make your avatar say something, from your terminal.
+//
+// npx @three-ws/herald say "Deploy is green"
+// npx @three-ws/herald watch -- npm test
+//
+// `watch` is the one worth putting in your muscle memory: it runs any command,
+// keeps its exit code and its output, and when it finishes your 3D agent walks
+// onto whatever browser tab you have open and tells you how it went. Long test
+// runs, builds, migrations, and training jobs stop needing a babysitter.
+//
+// Zero dependencies. Node 18+ (global fetch). Auth is one env var:
+// export THREE_WS_API_KEY=sk_live_... # /dashboard/developers
+// export THREE_WS_ORIGIN=https://three.ws # optional, for self-hosting
+
+import { spawn } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+
+const DEFAULT_ORIGIN = process.env.THREE_WS_ORIGIN || 'https://three.ws';
+const VERSION = '0.1.0';
+
+const HELP = `herald ${VERSION}: deliver a message in person.
+
+USAGE
+ herald say <text> [options]
+ herald watch [options] -- <command...>
+ herald ping
+ herald --help
+
+COMMANDS
+ say Announce one line on your own avatar.
+ watch Run a command, then announce how it went (keeps its exit code).
+ ping Verify your key and the rail, without announcing anything.
+
+OPTIONS
+ --from <name> Who it is from ("CI", "Stripe", "your build").
+ --importance <0-100> How hard it should interrupt. Default 70 (say),
+ 60 on success and 95 on failure (watch).
+ --url <url> Where clicking through goes.
+ --tone <t> neutral | alert | celebrate | error
+ --emote <name> Gesture on arrival: wave, dance, punch, backflip.
+ --key <dedupe-key> Same key twice is said once.
+ --quiet Print nothing on success.
+ --origin <url> Rail origin. Default ${DEFAULT_ORIGIN}
+ --api-key <key> Overrides THREE_WS_API_KEY.
+ --api-key-file <path> Read the key from a file (CI secret mounts).
+
+EXAMPLES
+ herald say "Deploy is green" --url https://three.ws/dashboard
+ herald watch --from CI -- npm test
+ herald watch --from "db migrate" -- npm run db:migrate
+ TESTS=$(herald watch -- npm test; echo $?) # exit code is preserved
+
+ENVIRONMENT
+ THREE_WS_API_KEY API key with the herald:announce scope.
+ THREE_WS_ORIGIN Rail origin (default ${DEFAULT_ORIGIN}).
+`;
+
+function parseArgs(argv) {
+ const out = { _: [], flags: {}, command: null, rest: [] };
+ const dashdash = argv.indexOf('--');
+ const head = dashdash === -1 ? argv : argv.slice(0, dashdash);
+ out.rest = dashdash === -1 ? [] : argv.slice(dashdash + 1);
+
+ for (let i = 0; i < head.length; i++) {
+ const token = head[i];
+ if (token.startsWith('--')) {
+ const name = token.slice(2);
+ // Boolean flags take no value; everything else consumes the next token.
+ if (name === 'quiet' || name === 'help' || name === 'version') {
+ out.flags[name] = true;
+ } else {
+ out.flags[name] = head[++i];
+ }
+ } else if (!out.command) {
+ out.command = token;
+ } else {
+ out._.push(token);
+ }
+ }
+ return out;
+}
+
+function resolveKey(flags) {
+ if (flags['api-key']) return flags['api-key'].trim();
+ if (flags['api-key-file']) {
+ try {
+ return readFileSync(flags['api-key-file'], 'utf8').trim();
+ } catch (err) {
+ fail(`could not read --api-key-file: ${err.message}`);
+ }
+ }
+ const env = (process.env.THREE_WS_API_KEY || '').trim();
+ if (env) return env;
+ fail(
+ 'no API key. Set THREE_WS_API_KEY (create one at ' +
+ `${DEFAULT_ORIGIN}/dashboard/developers with the herald:announce scope), ` +
+ 'or pass --api-key / --api-key-file.',
+ );
+}
+
+function fail(message, code = 2) {
+ process.stderr.write(`herald: ${message}\n`);
+ process.exit(code);
+}
+
+async function announce(body, { origin, apiKey, quiet }) {
+ let res;
+ try {
+ res = await fetch(`${origin.replace(/\/$/, '')}/api/herald/announce`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${apiKey}`,
+ },
+ body: JSON.stringify(body),
+ });
+ } catch (err) {
+ fail(`could not reach the rail at ${origin}: ${err.message}`, 3);
+ }
+
+ const payload = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const detail = payload.error_description || payload.error || `HTTP ${res.status}`;
+ if (res.status === 401 || res.status === 403) {
+ fail(`${detail} (check the key's herald:announce scope)`, 4);
+ }
+ fail(detail, 5);
+ }
+ if (!quiet) {
+ process.stdout.write(`herald: queued "${body.text}"\n`);
+ }
+ return payload;
+}
+
+async function cmdSay(args) {
+ const text = args._.join(' ').trim() || args.rest.join(' ').trim();
+ if (!text) fail('nothing to say. Usage: herald say "your message"');
+ await announce(
+ {
+ text,
+ from: args.flags.from,
+ importance: args.flags.importance != null ? Number(args.flags.importance) : undefined,
+ url: args.flags.url,
+ tone: args.flags.tone,
+ emote: args.flags.emote,
+ key: args.flags.key,
+ },
+ context(args),
+ );
+}
+
+async function cmdWatch(args) {
+ const command = args.rest;
+ if (!command.length) fail('nothing to run. Usage: herald watch -- npm test');
+
+ const label = args.flags.from || command.join(' ');
+ const started = Date.now();
+ const child = spawn(command[0], command.slice(1), { stdio: 'inherit', shell: false });
+
+ const code = await new Promise((resolve) => {
+ child.on('error', (err) => {
+ fail(`could not run "${command[0]}": ${err.message}`, 127);
+ });
+ child.on('close', (exitCode) => resolve(exitCode ?? 0));
+ });
+
+ const seconds = Math.max(1, Math.round((Date.now() - started) / 1000));
+ const took = seconds >= 60 ? `${Math.round(seconds / 60)}m` : `${seconds}s`;
+ const ok = code === 0;
+
+ await announce(
+ {
+ text: ok ? `${label} passed in ${took}` : `${label} failed (exit ${code}) after ${took}`,
+ from: args.flags.from,
+ importance:
+ args.flags.importance != null ? Number(args.flags.importance) : ok ? 60 : 95,
+ url: args.flags.url,
+ tone: args.flags.tone || (ok ? 'celebrate' : 'error'),
+ emote: args.flags.emote || (ok ? 'dance' : undefined),
+ key: args.flags.key,
+ meta: { exitCode: code, seconds, command: command.join(' ') },
+ },
+ context(args),
+ );
+
+ // The whole point of `watch` is being transparent in a pipeline: it must
+ // exit with the command's status, not its own.
+ process.exit(code);
+}
+
+async function cmdPing(args) {
+ const { origin, apiKey } = context(args);
+ const res = await fetch(`${origin.replace(/\/$/, '')}/api/herald/announce`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },
+ body: JSON.stringify({ text: 'herald ping', importance: 0, key: 'herald:cli:ping' }),
+ }).catch((err) => fail(`could not reach the rail at ${origin}: ${err.message}`, 3));
+
+ if (res.status === 401 || res.status === 403) fail('key rejected: check herald:announce scope', 4);
+ if (!res.ok) fail(`rail returned HTTP ${res.status}`, 5);
+ // importance 0 means the browser's own floor drops it: this proves the key
+ // and the rail without interrupting anybody.
+ process.stdout.write(`herald: rail reachable at ${origin}, key accepted\n`);
+}
+
+function context(args) {
+ return {
+ origin: args.flags.origin || DEFAULT_ORIGIN,
+ apiKey: resolveKey(args.flags),
+ quiet: !!args.flags.quiet,
+ };
+}
+
+const args = parseArgs(process.argv.slice(2));
+
+if (args.flags.help || (!args.command && !args.rest.length)) {
+ process.stdout.write(HELP);
+ process.exit(0);
+}
+if (args.flags.version) {
+ process.stdout.write(`${VERSION}\n`);
+ process.exit(0);
+}
+
+const commands = { say: cmdSay, watch: cmdWatch, ping: cmdPing };
+const run = commands[args.command];
+if (!run) fail(`unknown command "${args.command}". Try: herald --help`);
+
+run(args).catch((err) => fail(err?.message || String(err), 1));
diff --git a/herald-sdk/examples/README.md b/herald-sdk/examples/README.md
new file mode 100644
index 000000000..40b0b8747
--- /dev/null
+++ b/herald-sdk/examples/README.md
@@ -0,0 +1,25 @@
+# @three-ws/herald examples
+
+Three runnable examples, smallest first. Each one is a single file with no
+build step: open the HTML in a browser, or run the Node file with `node`.
+
+| File | What it shows |
+| --- | --- |
+| [`plain-html.html`](./plain-html.html) | The whole feature in one `<script type="module">`, no bundler, no install |
+| [`feed.html`](./feed.html) | Point it at a live feed, with custom scoring and quiet hours |
+| [`ci-notify.mjs`](./ci-notify.mjs) | Announce from a build script or a GitHub Action step |
+
+## Run them
+
+```sh
+# from the repo root
+npx serve herald-sdk/examples # or any static server
+open http://localhost:3000/plain-html.html
+```
+
+`ci-notify.mjs` needs a key with the `herald:announce` scope:
+
+```sh
+export THREE_WS_API_KEY=sk_live_...
+node herald-sdk/examples/ci-notify.mjs "Nightly build finished" 0
+```
diff --git a/herald-sdk/examples/ci-notify.mjs b/herald-sdk/examples/ci-notify.mjs
new file mode 100755
index 000000000..b589efd50
--- /dev/null
+++ b/herald-sdk/examples/ci-notify.mjs
@@ -0,0 +1,37 @@
+#!/usr/bin/env node
+// Announce a build result from a script, a GitHub Action step, or a cron.
+//
+// THREE_WS_API_KEY=sk_live_... node ci-notify.mjs "Nightly build" 0
+//
+// Exit code 0 announces a pass, anything else announces a failure at an
+// importance high enough to cut through quiet hours. The CLI shipped with this
+// package does the same thing with more options: `herald watch -- npm test`.
+
+const [, , label = 'Build', rawCode = '0'] = process.argv;
+const code = Number(rawCode);
+const ok = code === 0;
+
+const key = process.env.THREE_WS_API_KEY;
+if (!key) {
+ console.error('set THREE_WS_API_KEY (herald:announce scope) first');
+ process.exit(2);
+}
+
+const res = await fetch(`${process.env.THREE_WS_ORIGIN || 'https://three.ws'}/api/herald/announce`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify({
+ text: ok ? `${label} passed` : `${label} failed (exit ${code})`,
+ from: 'CI',
+ importance: ok ? 60 : 95,
+ tone: ok ? 'celebrate' : 'error',
+ url: process.env.BUILD_URL,
+ key: `ci:${label}`,
+ }),
+});
+
+if (!res.ok) {
+ console.error(`herald rail returned ${res.status}`);
+ process.exit(1);
+}
+console.log(ok ? 'announced: passed' : 'announced: failed');
diff --git a/herald-sdk/examples/feed.html b/herald-sdk/examples/feed.html
new file mode 100644
index 000000000..d431681fe
--- /dev/null
+++ b/herald-sdk/examples/feed.html
@@ -0,0 +1,58 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>herald: from a live feed</title>
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<style>
+ body { font: 16px/1.6 system-ui, sans-serif; max-width: 46rem; margin: 6vh auto; padding: 0 1.2rem;
+ background: #0d0f16; color: #e8ecf6; }
+ code, pre { background: #11141f; border: 1px solid #232a40; border-radius: 8px; padding: 2px 6px; }
+ pre { padding: 12px; overflow-x: auto; }
+</style>
+
+<h1>Point it at a feed</h1>
+<p>
+ This page polls a public JSON endpoint, scores what comes back, and only
+ interrupts for the ones that clear the bar. Nothing is said twice, nothing is
+ said at night, and nothing is said while this tab is in the background.
+</p>
+
+<pre id="log">watching...</pre>
+
+<script type="module">
+ import { createHerald, pollSource } from 'https://three.ws/herald.js';
+
+ const log = document.getElementById('log');
+ const print = (line) => {
+ log.textContent = `${line}\n${log.textContent}`.split('\n').slice(0, 14).join('\n');
+ };
+
+ const herald = createHerald({
+ rules: {
+ minImportance: 65,
+ quietHours: [22, 7],
+ quietHoursMinImportance: 95,
+ maxPerWindow: 3,
+ },
+ voice: 'auto',
+ onDeliver: (m) => print(`said: ${m.text}`),
+ onDrop: (m, reason) => print(`skipped (${reason}): ${m?.text ?? ''}`),
+ });
+
+ // Anything that scores itself is easier to live with than anything that does not.
+ herald.rule((m) => (/\bfailed|down|breach\b/i.test(m.text) ? 96 : undefined));
+ herald.rule((m) => (m.from === 'status' ? 80 : undefined));
+
+ herald.source(pollSource({
+ url: 'https://three.ws/api/changelog',
+ intervalMs: 60_000,
+ select: (body) => body.entries?.slice(0, 5) ?? [],
+ map: (entry) => ({
+ id: entry.date + entry.title,
+ text: entry.title,
+ from: 'changelog',
+ importance: 70,
+ url: 'https://three.ws/changelog',
+ at: Date.parse(entry.date),
+ }),
+ }));
+</script>
diff --git a/herald-sdk/examples/plain-html.html b/herald-sdk/examples/plain-html.html
new file mode 100644
index 000000000..098367a90
--- /dev/null
+++ b/herald-sdk/examples/plain-html.html
@@ -0,0 +1,55 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>herald: the whole feature in one script tag</title>
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<style>
+ body { font: 16px/1.6 system-ui, sans-serif; max-width: 44rem; margin: 6vh auto; padding: 0 1.2rem;
+ background: #0d0f16; color: #e8ecf6; }
+ h1 { font-size: 1.6rem; margin-bottom: .2rem; }
+ p.sub { color: #98a2b8; margin-top: 0; }
+ button { font: 600 14px system-ui; padding: 10px 14px; border-radius: 10px; cursor: pointer;
+ border: 1px solid #2b3350; background: #161b2b; color: inherit; margin: 4px 6px 4px 0; }
+ button:hover { border-color: #7aa2ff; }
+ pre { background: #11141f; border: 1px solid #232a40; border-radius: 10px; padding: 12px; overflow-x: auto; }
+</style>
+
+<h1>Deliver a message in person</h1>
+<p class="sub">No bundler, no install, no CSS to import. Click a button and watch the corner.</p>
+
+<button id="normal">Ordinary news (importance 60)</button>
+<button id="big">Something that matters (85)</button>
+<button id="noise">Noise (10, dropped)</button>
+<button id="burst">A burst of five</button>
+
+<pre id="log">verdicts appear here</pre>
+
+<script type="module">
+ import { createHerald } from 'https://three.ws/herald.js';
+
+ const log = document.getElementById('log');
+ const herald = createHerald({
+ voice: 'auto',
+ onDrop: (m, reason) => print(`dropped: ${reason} (${m?.text ?? 'empty'})`),
+ onHold: (m, reason) => print(`held: ${reason} (${m.text})`),
+ onDeliver: (m) => print(`delivered: ${m.text}`),
+ });
+
+ function print(line) {
+ log.textContent = `${line}\n${log.textContent}`.split('\n').slice(0, 12).join('\n');
+ }
+
+ document.getElementById('normal').onclick = () =>
+ herald.announce({ text: 'Your export is ready', importance: 60, url: '#export' });
+
+ document.getElementById('big').onclick = () =>
+ herald.announce({ text: 'Payment received from Acme', from: 'Stripe', importance: 85, tone: 'celebrate' });
+
+ document.getElementById('noise').onclick = () =>
+ herald.announce({ text: 'Someone viewed your profile', importance: 10 });
+
+ document.getElementById('burst').onclick = () => {
+ for (let i = 1; i <= 5; i++) {
+ herald.announce({ id: `burst-${Date.now()}-${i}`, text: `Alert number ${i}`, importance: 60 + i });
+ }
+ };
+</script>
diff --git a/herald-sdk/package.json b/herald-sdk/package.json
new file mode 100644
index 000000000..84a129995
--- /dev/null
+++ b/herald-sdk/package.json
@@ -0,0 +1,67 @@
+{
+ "name": "@three-ws/herald",
+ "version": "0.1.0",
+ "description": "Deliver a message in person: a 3D character walks onto your page and tells the user, with importance scoring, quiet hours, dedupe and an accessible fallback. Works with any feed, plus a CLI that announces when your build finishes.",
+ "keywords": [
+ "notifications",
+ "3d",
+ "avatar",
+ "agent",
+ "alerts",
+ "toast",
+ "sse",
+ "webhooks",
+ "tts",
+ "accessibility",
+ "cli",
+ "ci",
+ "three.js"
+ ],
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws/herald",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "herald-sdk"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "exports": {
+ ".": "./src/index.js",
+ "./rules": "./src/rules.js",
+ "./sources": "./src/sources/index.js",
+ "./presenters/card": "./src/presenters/card.js",
+ "./presenters/avatar": "./src/presenters/avatar.js",
+ "./voice": "./src/voice.js"
+ },
+ "bin": {
+ "herald": "./bin/herald.mjs"
+ },
+ "files": [
+ "src",
+ "bin",
+ "examples",
+ "README.md",
+ "LICENSE"
+ ],
+ "sideEffects": false,
+ "peerDependencies": {
+ "@three-ws/walk": ">=0.3.0"
+ },
+ "peerDependenciesMeta": {
+ "@three-ws/walk": {
+ "optional": true
+ }
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/herald-sdk/src/index.js b/herald-sdk/src/index.js
new file mode 100644
index 000000000..2fde6e544
--- /dev/null
+++ b/herald-sdk/src/index.js
@@ -0,0 +1,386 @@
+// @three-ws/herald: deliver a message in person.
+// =============================================================================
+// Notifications are a badge you have to notice, in a tray you have to open,
+// competing with forty others. This SDK delivers the ones that matter the way a
+// colleague would: a character walks into the corner of the page, looks at you,
+// and tells you, with a link to the thing it is about.
+//
+// Three lines to the whole feature:
+//
+// import { createHerald } from '@three-ws/herald';
+// const herald = createHerald();
+// herald.announce({ text: 'Deploy is green', importance: 80, url: '/builds' });
+//
+// What you get for those three lines is not a toast library. It is a delivery
+// discipline: importance scoring, an interrupt floor, quiet hours, a rate
+// limit, dedupe with a TTL, freshness, batching with a collapse line, focus
+// awareness, an accessible fallback for machines that cannot render 3D, and an
+// audit trail of every message that did not make it and why.
+//
+// The avatar is optional and so is the network. Everything degrades: no
+// @three-ws/walk and no WebGL leaves you with an accessible DOM card; no audio
+// permission leaves you with text; no rules leaves you with sane defaults.
+
+import {
+ DEFAULT_RULES,
+ DROP_REASONS,
+ HOLD_REASONS,
+ decide,
+ dwellMsFor,
+ planBatch,
+ pruneSeen,
+ resolveRules,
+ toMessage,
+} from './rules.js';
+import { createAvatarPresenter } from './presenters/avatar.js';
+import { createCardPresenter } from './presenters/card.js';
+import { createVoice } from './voice.js';
+import { manualSource } from './sources/index.js';
+
+export const VERSION = '0.1.0';
+
+export {
+ DEFAULT_RULES,
+ DROP_REASONS,
+ HOLD_REASONS,
+ decide,
+ dwellMsFor,
+ planBatch,
+ resolveRules,
+ scoreMessage,
+ toMessage,
+ withinQuietHours,
+} from './rules.js';
+export { createAvatarPresenter } from './presenters/avatar.js';
+export { createCardPresenter } from './presenters/card.js';
+export { createVoice } from './voice.js';
+export { pollSource, sseSource, railSource, manualSource } from './sources/index.js';
+
+// How often a held queue is re-examined. Holds are cleared by the passage of
+// time (a rate window draining, quiet hours ending) or by an event we already
+// listen for (focus), so this is a safety net rather than the mechanism.
+const SWEEP_MS = 5_000;
+const PRUNE_EVERY = 20;
+
+/**
+ * @param {object} [options]
+ * @param {'auto'|'avatar'|'card'} [options.presenter='auto'] `auto` uses the
+ * avatar when one can be rendered and the card when it cannot.
+ * @param {object} [options.presenters] override the built-in presenters
+ * (`{ avatar, card }`), for tests or a bespoke body.
+ * @param {import('./rules.js').Rules} [options.rules]
+ * @param {'off'|'auto'|'always'} [options.voice='off'] `auto` speaks only when
+ * audio is already unlocked by a gesture; `always` tries every time.
+ * @param {object} [options.voiceOptions] see createVoice
+ * @param {Array<(m: import('./rules.js').Message) => number|undefined>} [options.scorers]
+ * @param {(m: object) => void} [options.onDeliver]
+ * @param {(m: object, reason: string) => void} [options.onDrop]
+ * @param {(m: object, reason: string) => void} [options.onHold]
+ * @param {(m: object) => Array<object>} [options.actionsFor] extra buttons on a
+ * delivery; the default gives "Open" for a message with a url.
+ * @param {object} [options.companion] a live @three-ws/walk control to reuse
+ * @param {() => number} [options.now] clock seam, for tests
+ */
+export function createHerald(options = {}) {
+ const opts = { presenter: 'auto', voice: 'off', ...options };
+ const rules = resolveRules(opts.rules);
+ const now = typeof opts.now === 'function' ? opts.now : () => Date.now();
+ const scorers = [...(opts.scorers || [])];
+
+ const seen = new Map();
+ const recent = [];
+ const held = [];
+ const stops = [];
+ const stats = { received: 0, delivered: 0, dropped: 0, held: 0, spoken: 0 };
+ const drops = [];
+
+ let busy = false;
+ let muted = false;
+ let mutedUntil = 0;
+ let stopped = false;
+ let sweepTimer = 0;
+ let sincePrune = 0;
+
+ const presenters = {
+ avatar: opts.presenters?.avatar || createAvatarPresenter({ companion: opts.companion }),
+ card: opts.presenters?.card || createCardPresenter(),
+ };
+ const voice =
+ opts.voice === 'off' ? null : opts.voiceOptions === null ? null : createVoice(opts.voiceOptions);
+
+ const manual = manualSource();
+ attach(manual);
+
+ // ── Intake ────────────────────────────────────────────────────────────────
+
+ function intake(raw) {
+ if (stopped) return null;
+ const message = toMessage(raw);
+ if (!message) {
+ record(null, DROP_REASONS.EMPTY);
+ return null;
+ }
+ stats.received += 1;
+ return route(message);
+ }
+
+ function route(message) {
+ const verdict = decide(message, {
+ rules,
+ now: now(),
+ hour: localHour(now()),
+ seen,
+ recent,
+ focused: isFocused(),
+ busy,
+ muted: isMuted(),
+ scorers,
+ });
+ message.importance = verdict.importance;
+
+ if (verdict.action === 'drop') {
+ record(message, verdict.reason);
+ return { action: 'drop', reason: verdict.reason, message };
+ }
+ if (verdict.action === 'hold') {
+ stats.held += 1;
+ held.push(message);
+ opts.onHold?.(message, verdict.reason);
+ scheduleSweep();
+ return { action: 'hold', reason: verdict.reason, message };
+ }
+ deliver(message);
+ return { action: 'deliver', message };
+ }
+
+ function record(message, reason) {
+ stats.dropped += 1;
+ drops.push({ at: now(), reason, text: message?.text || '' });
+ if (drops.length > 50) drops.shift();
+ opts.onDrop?.(message, reason);
+ }
+
+ // ── Delivery ──────────────────────────────────────────────────────────────
+
+ async function deliver(message) {
+ busy = true;
+ const stamp = now();
+ seen.set(message.key || message.id || message.text, stamp);
+ recent.push(stamp);
+ while (recent.length && recent[0] < stamp - rules.rateWindowMs) recent.shift();
+ if (++sincePrune >= PRUNE_EVERY) {
+ sincePrune = 0;
+ pruneSeen(seen, stamp, rules.dedupeTtlMs);
+ }
+
+ const dwellMs = dwellMsFor(message.text);
+ const actions = buildActions(message);
+ const spoken = message.from ? `${message.from} says: ${message.text}` : message.text;
+
+ if (voice && (opts.voice === 'always' || voice.unlocked)) {
+ voice.speak(spoken).then((ok) => {
+ if (ok) stats.spoken += 1;
+ });
+ }
+
+ try {
+ const presenter = await pickPresenter();
+ const shown = await presenter.present(message, { dwellMs, actions });
+ // A presenter that reports it could not render is not a delivery: fall
+ // through to the card so the message still reaches a human.
+ if (shown === false && presenter.name !== 'card') {
+ await presenters.card.present(message, { dwellMs, actions });
+ }
+ stats.delivered += 1;
+ opts.onDeliver?.(message);
+ } catch {
+ // A presenter that throws must not wedge the queue; the message is
+ // counted as dropped so `stats()` never over-reports delivery.
+ record(message, 'presenter-failed');
+ } finally {
+ busy = false;
+ scheduleSweep(0);
+ }
+ }
+
+ function buildActions(message) {
+ const built = [];
+ if (message.url) {
+ built.push({
+ label: message.actionLabel || 'Open',
+ href: message.url,
+ title: `Open: ${message.text}`,
+ });
+ }
+ const extra = opts.actionsFor?.(message);
+ if (Array.isArray(extra)) built.push(...extra);
+ return built.slice(0, 3);
+ }
+
+ let preferred = null;
+ async function pickPresenter() {
+ if (opts.presenter === 'card') return presenters.card;
+ if (opts.presenter === 'avatar') return presenters.avatar;
+ if (preferred) return preferred;
+ preferred = (await presenters.avatar.ready?.()) ? presenters.avatar : presenters.card;
+ return preferred;
+ }
+
+ // ── The held queue ────────────────────────────────────────────────────────
+
+ function scheduleSweep(delay = SWEEP_MS) {
+ clearTimeout(sweepTimer);
+ if (stopped || !held.length) return;
+ sweepTimer = setTimeout(sweep, delay);
+ }
+
+ function sweep() {
+ if (stopped || busy || !held.length) return scheduleSweep();
+ const ready = [];
+ const stillHeld = [];
+ for (const message of held) {
+ const verdict = decide(message, {
+ rules,
+ now: now(),
+ hour: localHour(now()),
+ // A held message has not been delivered, so it must not be judged
+ // against its own dedupe entry.
+ seen: new Map(),
+ recent,
+ focused: isFocused(),
+ busy: false,
+ muted: isMuted(),
+ scorers,
+ });
+ if (verdict.action === 'deliver') ready.push({ ...message, importance: verdict.importance });
+ else if (verdict.action === 'hold') stillHeld.push(message);
+ else record(message, verdict.reason);
+ }
+ held.length = 0;
+ held.push(...stillHeld);
+
+ if (!ready.length) return scheduleSweep();
+
+ const plan = planBatch(ready, rules.batchSize);
+ (async () => {
+ for (const message of plan.deliver) {
+ await deliver(message);
+ }
+ if (plan.summary) {
+ await deliver({
+ text: plan.summary,
+ importance: 60,
+ tone: 'neutral',
+ url: plan.collapsed.find((m) => m.url)?.url,
+ key: `herald:summary:${now()}`,
+ });
+ }
+ scheduleSweep();
+ })();
+ }
+
+ // ── Environment ───────────────────────────────────────────────────────────
+
+ function isFocused() {
+ const doc = globalThis.document;
+ if (!doc) return true; // headless: nothing to hide behind
+ return doc.visibilityState !== 'hidden';
+ }
+
+ function isMuted() {
+ if (muted) return true;
+ if (mutedUntil && now() < mutedUntil) return true;
+ if (mutedUntil && now() >= mutedUntil) mutedUntil = 0;
+ return false;
+ }
+
+ function localHour(ts) {
+ return new Date(ts).getHours();
+ }
+
+ if (globalThis.document?.addEventListener) {
+ globalThis.document.addEventListener('visibilitychange', () => {
+ if (isFocused()) scheduleSweep(400);
+ });
+ }
+
+ // ── Public surface ────────────────────────────────────────────────────────
+
+ function attach(source) {
+ if (!source?.start) return () => {};
+ const stop = source.start((raw) => intake(raw));
+ stops.push(stop);
+ return stop;
+ }
+
+ const herald = {
+ VERSION,
+
+ /**
+ * Deliver one message. Returns the verdict, so a caller can log why a
+ * message was not shown instead of guessing.
+ * @param {import('./rules.js').Message|string} message
+ */
+ announce(message) {
+ return intake(typeof message === 'string' ? { text: message } : message);
+ },
+
+ /** Attach a source (poll, SSE, rail, or your own). Returns its stopper. */
+ source: attach,
+
+ /** Add an importance scorer: `(message) => number | undefined`. */
+ rule(scorer) {
+ if (typeof scorer === 'function') scorers.push(scorer);
+ return herald;
+ },
+
+ /** Silence deliveries. `ms` omitted means until `unmute()`. */
+ mute(ms) {
+ if (ms == null) muted = true;
+ else mutedUntil = now() + Number(ms);
+ voice?.cancel();
+ return herald;
+ },
+
+ unmute() {
+ muted = false;
+ mutedUntil = 0;
+ scheduleSweep(0);
+ return herald;
+ },
+
+ get muted() {
+ return isMuted();
+ },
+
+ /** Counters plus the last 50 drops with their reasons. */
+ stats() {
+ return { ...stats, holding: held.length, drops: [...drops] };
+ },
+
+ /** The resolved rules, after defaults. */
+ get rules() {
+ return { ...rules };
+ },
+
+ /** Tear down every source, presenter, and timer. */
+ stop() {
+ stopped = true;
+ clearTimeout(sweepTimer);
+ for (const stop of stops.splice(0)) {
+ try {
+ stop?.();
+ } catch {
+ /* a source that fails to stop must not block the rest */
+ }
+ }
+ voice?.cancel();
+ presenters.avatar.stop?.();
+ presenters.card.stop?.();
+ },
+ };
+
+ return herald;
+}
+
+export default createHerald;
diff --git a/herald-sdk/src/presenters/avatar.js b/herald-sdk/src/presenters/avatar.js
new file mode 100644
index 000000000..ea2f91f53
--- /dev/null
+++ b/herald-sdk/src/presenters/avatar.js
@@ -0,0 +1,109 @@
+// The avatar presenter: a 3D character walks into the corner and says it.
+//
+// This is the whole point of the SDK, and it is deliberately the thinnest file
+// in it. The body, the rig, the retargeted walk cycle, the speech bubble and
+// the corner arbitration all already exist in @three-ws/walk; this presenter's
+// only job is to find a companion (a live one on the page, the package, or the
+// CDN build) and hand it a line.
+//
+// Resolution order, cheapest first:
+// 1. `window.__walkCompanion`: three.ws pages already run one, and reusing
+// it means the visitor's own avatar delivers the message instead of a
+// second character appearing beside it.
+// 2. A companion the integrator passed in (`companion` option).
+// 3. `import('@three-ws/walk')`: bundlers resolve this at build time.
+// 4. `import(cdn)`: a plain <script type="module"> page with no bundler.
+// Every rung is optional. If none resolve, `ready()` is false and the runtime
+// falls back to the card presenter, which needs nothing at all.
+
+const DEFAULT_CDN = 'https://three.ws/agent-3d/latest/walk.mjs';
+
+/**
+ * @param {object} [opts]
+ * @param {object} [opts.companion] a control object from createWalkCompanion()
+ * @param {object} [opts.companionOptions] options used when this presenter
+ * creates its own companion (avatars, defaultAvatarId, assetBase, apiBase...)
+ * @param {string|null} [opts.cdn] module URL used when the package is absent
+ * @param {(name: string) => any} [opts.globalLookup] test seam for window lookups
+ */
+export function createAvatarPresenter({
+ companion = null,
+ companionOptions = null,
+ cdn = DEFAULT_CDN,
+ globalLookup = (name) => globalThis?.[name],
+} = {}) {
+ let control = companion;
+ let resolving = null;
+
+ async function resolveControl() {
+ if (control) return control;
+ if (resolving) return resolving;
+ resolving = (async () => {
+ const live = globalLookup('__walkCompanion');
+ if (live && typeof live.announce === 'function') return live;
+
+ const mod = await importWalk(cdn);
+ if (!mod?.createWalkCompanion) return null;
+ const created = mod.createWalkCompanion(companionOptions || {});
+ // Never flip the visitor's persisted companion preference on: the
+ // SDK borrows the corner for a message and gives it straight back.
+ return created;
+ })()
+ .catch(() => null)
+ .then((resolved) => {
+ control = resolved;
+ resolving = null;
+ return resolved;
+ });
+ return resolving;
+ }
+
+ async function ready() {
+ if (typeof globalThis?.document === 'undefined') return false;
+ return !!(await resolveControl())?.announce;
+ }
+
+ /**
+ * @param {import('../rules.js').Message} message
+ * @param {{dwellMs:number, actions?:Array<object>}} opts
+ * @returns {Promise<boolean>} false when no avatar could be shown, which is
+ * the runtime's signal to fall back rather than drop the message.
+ */
+ async function present(message, { dwellMs = 6000, actions = [] } = {}) {
+ const ctl = await resolveControl();
+ if (!ctl?.announce) return false;
+ const line = message.from ? `${message.from}: ${message.text}` : message.text;
+ return !!(await ctl.announce(line, {
+ hold: dwellMs,
+ tone: message.tone === 'neutral' ? 'neutral' : 'alert',
+ emote: message.emote || (message.tone === 'celebrate' ? 'dance' : 'wave'),
+ actions,
+ ...(message.avatar ? { avatar: message.avatar } : {}),
+ }));
+ }
+
+ function stop() {
+ try {
+ control?.instance?.hideBubble?.();
+ } catch {
+ /* companion already gone */
+ }
+ }
+
+ return { name: 'avatar', ready, present, stop, get control() { return control; } };
+}
+
+// Kept separate so a bundler that cannot resolve the optional package still
+// produces a working build: the failure is caught and the CDN rung runs.
+async function importWalk(cdn) {
+ try {
+ return await import(/* @vite-ignore */ '@three-ws/walk');
+ } catch {
+ if (!cdn) return null;
+ try {
+ return await import(/* @vite-ignore */ cdn);
+ } catch {
+ return null;
+ }
+ }
+}
diff --git a/herald-sdk/src/presenters/card.js b/herald-sdk/src/presenters/card.js
new file mode 100644
index 000000000..4490a4f9f
--- /dev/null
+++ b/herald-sdk/src/presenters/card.js
@@ -0,0 +1,206 @@
+// The card presenter: a message delivered without a GPU.
+//
+// The avatar presenter is the point of this SDK, but it needs WebGL, a rig, and
+// a corner to stand in. None of those are guaranteed: a locked-down browser, a
+// machine with the GPU blocklisted, an iframe, a page that already owns the
+// corner, or simply an integrator who wants the delivery discipline without the
+// 3D. This presenter is the floor under all of that. It is dependency-free,
+// self-styling, theme-aware, keyboard-operable, and announced to screen
+// readers, and it is what the runtime falls back to so a message is never lost
+// to a missing capability.
+
+const STYLE_ID = 'three-herald-card-style';
+const ROOT_ID = 'three-herald-cards';
+
+const TONE_ACCENT = {
+ neutral: '#7aa2ff',
+ alert: '#ffb454',
+ celebrate: '#5ddc8f',
+ error: '#ff6b6b',
+};
+
+function ensureStyles(doc) {
+ if (doc.getElementById(STYLE_ID)) return;
+ const style = doc.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+#${ROOT_ID}{position:fixed;right:16px;bottom:16px;z-index:2147483000;display:flex;flex-direction:column;gap:10px;align-items:flex-end;pointer-events:none;max-width:min(360px,calc(100vw - 32px))}
+.three-herald-card{pointer-events:auto;box-sizing:border-box;width:100%;display:flex;gap:12px;padding:14px 14px 12px;border-radius:14px;background:var(--three-herald-bg,rgba(18,20,28,.96));color:var(--three-herald-ink,#f2f4f8);border:1px solid var(--three-herald-stroke,rgba(255,255,255,.12));box-shadow:0 18px 44px rgba(0,0,0,.42);font:500 13.5px/1.45 system-ui,-apple-system,'Segoe UI',sans-serif;opacity:0;transform:translateY(10px) scale(.98);transition:opacity .28s ease,transform .28s cubic-bezier(.34,1.56,.64,1);position:relative;overflow:hidden}
+.three-herald-card.is-in{opacity:1;transform:translateY(0) scale(1)}
+.three-herald-card.is-out{opacity:0;transform:translateY(6px) scale(.99)}
+.three-herald-card::before{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--three-herald-accent,#7aa2ff)}
+.three-herald-face{flex:0 0 auto;width:38px;height:38px;border-radius:11px;overflow:hidden;background:linear-gradient(150deg,var(--three-herald-accent,#7aa2ff),rgba(255,255,255,.06));display:grid;place-items:center;font-size:18px;line-height:1}
+.three-herald-face img{width:100%;height:100%;object-fit:cover;display:block}
+.three-herald-body{min-width:0;flex:1 1 auto}
+.three-herald-from{font-size:11.5px;font-weight:700;letter-spacing:.02em;text-transform:uppercase;color:var(--three-herald-accent,#7aa2ff);margin-bottom:2px}
+.three-herald-text{overflow-wrap:anywhere}
+.three-herald-actions{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}
+.three-herald-action{appearance:none;font:600 12px/1 system-ui,-apple-system,'Segoe UI',sans-serif;padding:7px 11px;border-radius:999px;border:1px solid var(--three-herald-stroke,rgba(255,255,255,.16));background:rgba(255,255,255,.06);color:inherit;cursor:pointer;text-decoration:none;transition:background .15s ease,border-color .15s ease,transform .12s ease}
+.three-herald-action:hover{background:rgba(122,162,255,.22);border-color:var(--three-herald-accent,#7aa2ff)}
+.three-herald-action:active{transform:translateY(1px)}
+.three-herald-action:focus-visible{outline:2px solid var(--three-herald-accent,#7aa2ff);outline-offset:2px}
+.three-herald-close{position:absolute;top:6px;right:8px;width:22px;height:22px;border:none;border-radius:50%;background:transparent;color:inherit;opacity:.45;cursor:pointer;font-size:15px;line-height:1;display:grid;place-items:center;padding:0}
+.three-herald-close:hover{opacity:1;background:rgba(255,255,255,.08)}
+.three-herald-close:focus-visible{opacity:1;outline:2px solid var(--three-herald-accent,#7aa2ff);outline-offset:1px}
+.three-herald-life{position:absolute;left:0;bottom:0;height:2px;width:100%;transform-origin:left center;background:var(--three-herald-accent,#7aa2ff);opacity:.5}
+@media (prefers-color-scheme:light){.three-herald-card{--three-herald-bg:rgba(255,255,255,.98);--three-herald-ink:#12141c;--three-herald-stroke:rgba(0,0,0,.12);box-shadow:0 18px 44px rgba(20,24,40,.18)}.three-herald-action{background:rgba(0,0,0,.04)}}
+@media (max-width:520px){#${ROOT_ID}{left:12px;right:12px;bottom:12px;max-width:none}}
+@media (prefers-reduced-motion:reduce){.three-herald-card{transition:opacity .01s linear}.three-herald-life{display:none}}
+`;
+ doc.head.appendChild(style);
+}
+
+function ensureRoot(doc) {
+ let root = doc.getElementById(ROOT_ID);
+ if (root) return root;
+ root = doc.createElement('div');
+ root.id = ROOT_ID;
+ // The stack is a live region so a delivery is announced by a screen reader
+ // the moment it lands, exactly like it is spoken to everyone else.
+ root.setAttribute('role', 'status');
+ root.setAttribute('aria-live', 'polite');
+ root.setAttribute('aria-atomic', 'false');
+ doc.body.appendChild(root);
+ return root;
+}
+
+/**
+ * Build the DOM-card presenter.
+ * @param {{document?: Document, face?: string|null}} [opts] `face` is an image
+ * URL or a single emoji shown as the sender's face.
+ */
+export function createCardPresenter({ document: doc = globalThis.document, face = '📣' } = {}) {
+ let current = null;
+
+ async function ready() {
+ return !!(doc && doc.body);
+ }
+
+ /**
+ * @param {import('../rules.js').Message} message
+ * @param {{dwellMs:number, actions?:Array<{label:string,href?:string,onClick?:Function}>}} opts
+ * @returns {Promise<boolean>} resolves when the card has left the screen
+ */
+ function present(message, { dwellMs = 6000, actions = [] } = {}) {
+ if (!doc?.body) return Promise.resolve(false);
+ ensureStyles(doc);
+ const root = ensureRoot(doc);
+ dismissCurrent();
+
+ const card = doc.createElement('div');
+ card.className = 'three-herald-card';
+ card.style.setProperty(
+ '--three-herald-accent',
+ TONE_ACCENT[message.tone] || TONE_ACCENT.neutral,
+ );
+
+ const faceEl = doc.createElement('div');
+ faceEl.className = 'three-herald-face';
+ faceEl.setAttribute('aria-hidden', 'true');
+ const faceValue = message.face || face;
+ if (faceValue && /^(https?:|\/|data:)/.test(String(faceValue))) {
+ const img = doc.createElement('img');
+ img.src = String(faceValue);
+ img.alt = '';
+ faceEl.appendChild(img);
+ } else if (faceValue) {
+ faceEl.textContent = String(faceValue);
+ }
+ card.appendChild(faceEl);
+
+ const body = doc.createElement('div');
+ body.className = 'three-herald-body';
+ if (message.from) {
+ const from = doc.createElement('div');
+ from.className = 'three-herald-from';
+ from.textContent = message.from;
+ body.appendChild(from);
+ }
+ const text = doc.createElement('div');
+ text.className = 'three-herald-text';
+ text.textContent = message.text;
+ body.appendChild(text);
+
+ const usable = (actions || []).filter((a) => a && a.label).slice(0, 3);
+ if (usable.length) {
+ const row = doc.createElement('div');
+ row.className = 'three-herald-actions';
+ for (const action of usable) {
+ const el = doc.createElement(action.href ? 'a' : 'button');
+ el.className = 'three-herald-action';
+ el.textContent = action.label;
+ if (action.href) el.href = action.href;
+ else el.type = 'button';
+ if (action.title) {
+ el.title = action.title;
+ el.setAttribute('aria-label', action.title);
+ }
+ el.addEventListener('click', () => {
+ try {
+ action.onClick?.();
+ } finally {
+ if (!action.href) finish();
+ }
+ });
+ row.appendChild(el);
+ }
+ body.appendChild(row);
+ }
+ card.appendChild(body);
+
+ const close = doc.createElement('button');
+ close.type = 'button';
+ close.className = 'three-herald-close';
+ close.setAttribute('aria-label', 'Dismiss');
+ close.textContent = '×';
+ close.addEventListener('click', () => finish());
+ card.appendChild(close);
+
+ const life = doc.createElement('div');
+ life.className = 'three-herald-life';
+ card.appendChild(life);
+
+ root.appendChild(card);
+ // Force layout so the entry transition runs from the pre-state.
+ void card.offsetWidth;
+ card.classList.add('is-in');
+ life.animate?.(
+ [{ transform: 'scaleX(1)' }, { transform: 'scaleX(0)' }],
+ { duration: dwellMs, easing: 'linear', fill: 'forwards' },
+ );
+
+ let settle;
+ const done = new Promise((resolve) => {
+ settle = resolve;
+ });
+ const timer = setTimeout(() => finish(), dwellMs);
+ const onKey = (e) => {
+ if (e.key === 'Escape') finish();
+ };
+ doc.addEventListener('keydown', onKey);
+
+ function finish() {
+ if (!current || current.card !== card) return;
+ clearTimeout(timer);
+ doc.removeEventListener('keydown', onKey);
+ card.classList.add('is-out');
+ current = null;
+ setTimeout(() => card.remove(), 300);
+ settle(true);
+ }
+
+ current = { card, finish };
+ return done;
+ }
+
+ function dismissCurrent() {
+ current?.finish?.();
+ }
+
+ function stop() {
+ dismissCurrent();
+ doc?.getElementById(ROOT_ID)?.remove();
+ }
+
+ return { name: 'card', ready, present, dismiss: dismissCurrent, stop };
+}
diff --git a/herald-sdk/src/rules.js b/herald-sdk/src/rules.js
new file mode 100644
index 000000000..c198ade42
--- /dev/null
+++ b/herald-sdk/src/rules.js
@@ -0,0 +1,283 @@
+// The rules engine: everything that decides WHETHER a message is worth
+// interrupting a human for, and how it should be delivered.
+//
+// Pure by design. No DOM, no timers, no network, no globals. The runtime
+// (index.js) owns the clock and the side effects; this file owns the judgement,
+// which is the part worth testing exhaustively and the part an integrator will
+// want to reason about before they let anything walk onto their page.
+//
+// The model in one paragraph: a message arrives from a source with an optional
+// `importance` (0-100). Scorers may raise or lower it. The decision function
+// then answers one question, "deliver, hold, or drop", against the caller's
+// rules: freshness, dedupe, importance floor, quiet hours, rate limit, focus.
+// Anything held is retried by the runtime; anything dropped is reported with a
+// reason, so an integrator can always answer "why didn't I hear about that?".
+
+/** Every reason a message can fail to reach a human, as a stable string. */
+export const DROP_REASONS = /** @type {const} */ ({
+ DUPLICATE: 'duplicate',
+ STALE: 'stale',
+ BELOW_FLOOR: 'below-importance-floor',
+ MUTED: 'muted',
+ EMPTY: 'empty',
+});
+
+/** Reasons a message is not delivered *yet*, but will be. */
+export const HOLD_REASONS = /** @type {const} */ ({
+ QUIET_HOURS: 'quiet-hours',
+ RATE_LIMITED: 'rate-limited',
+ UNFOCUSED: 'window-not-focused',
+ BUSY: 'delivering-another',
+});
+
+/** The importance a message gets when nothing said otherwise. */
+export const DEFAULT_IMPORTANCE = 50;
+
+/**
+ * @typedef {object} Message
+ * @property {string} [id] stable id; dedupe key when `key` is absent
+ * @property {string} text the line a human hears or reads
+ * @property {string} [key] explicit dedupe key (two builds of the same alert)
+ * @property {number} [importance] 0-100; higher interrupts harder
+ * @property {string} [from] who it is from, shown and spoken as attribution
+ * @property {string} [url] where clicking through goes
+ * @property {number} [at] epoch ms the underlying event happened
+ * @property {string} [tone] 'neutral' | 'alert' | 'celebrate'
+ * @property {string} [emote] gesture the avatar arrives with
+ * @property {object} [meta] anything the integrator wants back in callbacks
+ */
+
+/**
+ * @typedef {object} Rules
+ * @property {number} [minImportance=50] floor a message must clear to deliver
+ * @property {number} [freshnessMs=900000] older than this and it is history
+ * @property {number} [dedupeTtlMs=21600000] how long a delivered key is remembered
+ * @property {[number, number]|null} [quietHours=null] local [startHour, endHour)
+ * @property {number} [quietHoursMinImportance=90] what still gets through quiet hours
+ * @property {number} [maxPerWindow=4] deliveries allowed per rate window
+ * @property {number} [rateWindowMs=60000] the rate window
+ * @property {boolean} [focusOnly=true] hold while the tab is in the background
+ * @property {number} [batchSize=2] delivered per burst before the rest collapse
+ */
+
+/** The defaults, exported so integrators can read them and docs can quote them. */
+export const DEFAULT_RULES = Object.freeze({
+ minImportance: DEFAULT_IMPORTANCE,
+ freshnessMs: 15 * 60_000,
+ dedupeTtlMs: 6 * 60 * 60_000,
+ quietHours: null,
+ quietHoursMinImportance: 90,
+ maxPerWindow: 4,
+ rateWindowMs: 60_000,
+ focusOnly: true,
+ batchSize: 2,
+});
+
+/** Merge a caller's partial rules onto the defaults. */
+export function resolveRules(rules) {
+ return { ...DEFAULT_RULES, ...(rules || {}) };
+}
+
+/** Clamp anything to a 0-100 importance. */
+export function clampImportance(value, fallback = DEFAULT_IMPORTANCE) {
+ const n = Number(value);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.max(0, Math.min(100, Math.round(n)));
+}
+
+/**
+ * Run the caller's scorers over a message, highest wins.
+ *
+ * A scorer is `(message) => number | undefined`. Returning undefined means "no
+ * opinion", which is what lets a scorer speak only about the messages it knows
+ * about. A scorer that throws is ignored rather than allowed to break delivery:
+ * an integrator's bad rule must never cost a user their message.
+ *
+ * @param {Message} message
+ * @param {Array<(m: Message) => number|undefined>} [scorers]
+ * @returns {number} 0-100
+ */
+export function scoreMessage(message, scorers = []) {
+ let score = clampImportance(message?.importance, DEFAULT_IMPORTANCE);
+ for (const scorer of scorers) {
+ if (typeof scorer !== 'function') continue;
+ let opinion;
+ try {
+ opinion = scorer(message);
+ } catch {
+ continue;
+ }
+ if (opinion == null) continue;
+ const n = clampImportance(opinion, null);
+ if (n != null && n > score) score = n;
+ }
+ return score;
+}
+
+/** The dedupe key for a message: explicit key, then id, then the text itself. */
+export function dedupeKeyFor(message) {
+ return String(message?.key || message?.id || message?.text || '').trim();
+}
+
+/**
+ * Is `hour` inside a [start, end) window that may wrap past midnight?
+ * `[22, 7]` means 22:00 to 06:59.
+ */
+export function withinQuietHours(hour, quietHours) {
+ if (!Array.isArray(quietHours) || quietHours.length !== 2) return false;
+ const [start, end] = quietHours.map((h) => Number(h));
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start === end) return false;
+ const h = Number(hour);
+ return start < end ? h >= start && h < end : h >= start || h < end;
+}
+
+/**
+ * Decide what happens to one message.
+ *
+ * @param {Message} message
+ * @param {object} ctx
+ * @param {Rules} ctx.rules resolved rules
+ * @param {number} ctx.now epoch ms
+ * @param {number} ctx.hour local hour 0-23
+ * @param {Map<string, number>} ctx.seen dedupe key to the ms it was delivered
+ * @param {number[]} ctx.recent delivery timestamps inside the rate window
+ * @param {boolean} ctx.focused is the surface in front of the human
+ * @param {boolean} [ctx.busy] is a delivery already on screen
+ * @param {boolean} [ctx.muted] has the human silenced this device
+ * @param {Array<(m: Message) => number|undefined>} [ctx.scorers]
+ * @returns {{action:'deliver'|'hold'|'drop', reason?:string, importance:number}}
+ */
+export function decide(message, ctx) {
+ const rules = ctx.rules;
+ const importance = scoreMessage(message, ctx.scorers);
+ const text = String(message?.text || '').trim();
+
+ if (!text) return { action: 'drop', reason: DROP_REASONS.EMPTY, importance };
+ if (ctx.muted) return { action: 'drop', reason: DROP_REASONS.MUTED, importance };
+
+ const key = dedupeKeyFor(message);
+ const lastSeen = ctx.seen?.get(key);
+ if (lastSeen != null && ctx.now - lastSeen < rules.dedupeTtlMs) {
+ return { action: 'drop', reason: DROP_REASONS.DUPLICATE, importance };
+ }
+
+ // `at` is when the underlying event happened. A source that does not know
+ // (a manual announce, a webhook with no timestamp) is treated as now, so
+ // freshness never silently swallows a message that has no clock on it.
+ const at = Number.isFinite(Number(message?.at)) ? Number(message.at) : ctx.now;
+ if (ctx.now - at > rules.freshnessMs) {
+ return { action: 'drop', reason: DROP_REASONS.STALE, importance };
+ }
+
+ if (importance < rules.minImportance) {
+ return { action: 'drop', reason: DROP_REASONS.BELOW_FLOOR, importance };
+ }
+
+ // Holds are ordered cheapest-to-recover first: focus and busy resolve in
+ // seconds, the rate window in a minute, quiet hours in hours.
+ if (ctx.busy) return { action: 'hold', reason: HOLD_REASONS.BUSY, importance };
+ if (rules.focusOnly && !ctx.focused) {
+ return { action: 'hold', reason: HOLD_REASONS.UNFOCUSED, importance };
+ }
+
+ const windowStart = ctx.now - rules.rateWindowMs;
+ const inWindow = (ctx.recent || []).filter((t) => t > windowStart).length;
+ if (inWindow >= rules.maxPerWindow) {
+ return { action: 'hold', reason: HOLD_REASONS.RATE_LIMITED, importance };
+ }
+
+ if (
+ withinQuietHours(ctx.hour, rules.quietHours) &&
+ importance < rules.quietHoursMinImportance
+ ) {
+ return { action: 'hold', reason: HOLD_REASONS.QUIET_HOURS, importance };
+ }
+
+ return { action: 'deliver', importance };
+}
+
+/**
+ * Split a burst into what gets said and what gets summarised.
+ *
+ * Three alerts in one second is three interruptions; the third is noise. The
+ * batch plan delivers the most important few in order and collapses the rest
+ * into a single line, so a storm costs the human one extra sentence.
+ *
+ * @param {Array<Message & {importance?: number}>} messages
+ * @param {number} [batchSize=2]
+ * @returns {{deliver: Message[], collapsed: Message[], summary: string|null}}
+ */
+export function planBatch(messages, batchSize = DEFAULT_RULES.batchSize) {
+ const list = (Array.isArray(messages) ? messages : []).filter(Boolean);
+ const ordered = [...list].sort(
+ (a, b) =>
+ clampImportance(b.importance) - clampImportance(a.importance) ||
+ (Number(b.at) || 0) - (Number(a.at) || 0),
+ );
+ const size = Math.max(1, Math.floor(batchSize) || 1);
+ const deliver = ordered.slice(0, size);
+ const collapsed = ordered.slice(size);
+ return {
+ deliver,
+ collapsed,
+ summary: collapsed.length
+ ? `${collapsed.length} more ${collapsed.length === 1 ? 'message' : 'messages'} waiting`
+ : null,
+ };
+}
+
+/**
+ * How long a line should stay on screen: long enough to read comfortably,
+ * capped so a verbose payload can never park an avatar in someone's corner.
+ * Roughly 200 words per minute plus a beat to notice it.
+ */
+export function dwellMsFor(text, { min = 4200, max = 14_000, perChar = 55 } = {}) {
+ const chars = String(text || '').length;
+ return Math.max(min, Math.min(max, min + chars * perChar));
+}
+
+/**
+ * Prune a dedupe map in place and return it. Called by the runtime on a slow
+ * cadence so a long-lived page cannot grow an unbounded key set.
+ */
+export function pruneSeen(seen, now, ttlMs, cap = 500) {
+ if (!seen) return seen;
+ for (const [key, ts] of seen) {
+ if (now - ts > ttlMs) seen.delete(key);
+ }
+ if (seen.size > cap) {
+ const excess = seen.size - cap;
+ let i = 0;
+ for (const key of seen.keys()) {
+ if (i++ >= excess) break;
+ seen.delete(key);
+ }
+ }
+ return seen;
+}
+
+/**
+ * Normalise anything a source hands over into a Message.
+ * Sources are allowed to be sloppy so integrators can point one at an existing
+ * feed without writing a mapper; this is where that sloppiness stops.
+ */
+export function toMessage(raw) {
+ if (raw == null) return null;
+ if (typeof raw === 'string') return { text: raw.trim() } ;
+ const text = String(raw.text ?? raw.message ?? raw.title ?? raw.body ?? '').trim();
+ if (!text) return null;
+ const at = raw.at ?? raw.timestamp ?? raw.created_at ?? raw.createdAt;
+ const parsed = typeof at === 'string' ? Date.parse(at) : Number(at);
+ return {
+ id: raw.id != null ? String(raw.id) : undefined,
+ key: raw.key != null ? String(raw.key) : undefined,
+ text,
+ importance: raw.importance ?? raw.priority ?? undefined,
+ from: raw.from != null ? String(raw.from) : undefined,
+ url: raw.url ?? raw.link ?? undefined,
+ at: Number.isFinite(parsed) ? parsed : undefined,
+ tone: raw.tone,
+ emote: raw.emote,
+ meta: raw.meta ?? undefined,
+ };
+}
diff --git a/herald-sdk/src/sources/index.js b/herald-sdk/src/sources/index.js
new file mode 100644
index 000000000..d963a1c93
--- /dev/null
+++ b/herald-sdk/src/sources/index.js
@@ -0,0 +1,170 @@
+// Sources: where messages come from.
+//
+// A source is an object `{ name, start(emit) => stop }`. It calls `emit(raw)`
+// with anything message-shaped (the rules engine's `toMessage` normalises it)
+// and returns a function that tears itself down. That is the entire contract,
+// so an integrator can write one in five lines for a feed nobody here has
+// heard of, and the three below cover almost everything else:
+//
+// pollSource any JSON endpoint, on an interval, with visibility backoff
+// sseSource any EventSource endpoint (server-sent events)
+// railSource the three.ws delivery rail: your terminal, CI, or an agent
+// POSTs, and the browser you are looking at says it out loud
+
+/**
+ * Poll a JSON endpoint and emit what it returns.
+ *
+ * Polling stops while the tab is hidden and resumes (with an immediate read) on
+ * return, because a poll nobody is looking at is a request nobody needed.
+ *
+ * @param {object} opts
+ * @param {string} opts.url endpoint returning an array, or an object with an array
+ * @param {number} [opts.intervalMs=30000]
+ * @param {(body:any)=>any[]} [opts.select] pull the array out of the response
+ * @param {(item:any)=>any} [opts.map] shape one item into a message
+ * @param {RequestInit} [opts.fetchOptions] credentials, headers, and the rest
+ * @param {typeof fetch} [opts.fetchImpl]
+ */
+export function pollSource({
+ url,
+ intervalMs = 30_000,
+ select = defaultSelect,
+ map = (x) => x,
+ fetchOptions = { credentials: 'include' },
+ fetchImpl = globalThis.fetch?.bind(globalThis),
+}) {
+ return {
+ name: `poll:${url}`,
+ start(emit) {
+ let timer = 0;
+ let stopped = false;
+
+ const tick = async () => {
+ if (stopped) return;
+ try {
+ const res = await fetchImpl(url, fetchOptions);
+ if (res.ok) {
+ const body = await res.json();
+ for (const item of select(body) || []) emit(map(item));
+ }
+ } catch {
+ /* a network blip is not an error worth surfacing to a human */
+ }
+ schedule();
+ };
+
+ const schedule = () => {
+ clearTimeout(timer);
+ if (stopped) return;
+ timer = setTimeout(tick, intervalMs);
+ };
+
+ const onVisibility = () => {
+ if (globalThis.document?.visibilityState === 'visible') tick();
+ else clearTimeout(timer);
+ };
+ globalThis.document?.addEventListener?.('visibilitychange', onVisibility);
+
+ tick();
+ return () => {
+ stopped = true;
+ clearTimeout(timer);
+ globalThis.document?.removeEventListener?.('visibilitychange', onVisibility);
+ };
+ },
+ };
+}
+
+function defaultSelect(body) {
+ if (Array.isArray(body)) return body;
+ for (const key of ['messages', 'items', 'notifications', 'events', 'data']) {
+ if (Array.isArray(body?.[key])) return body[key];
+ }
+ return [];
+}
+
+/**
+ * Subscribe to a server-sent-events endpoint.
+ * @param {object} opts
+ * @param {string} opts.url
+ * @param {string[]} [opts.events=['message']] event names to listen for
+ * @param {boolean} [opts.withCredentials=true]
+ * @param {(data:any)=>any} [opts.map]
+ * @param {typeof EventSource} [opts.EventSourceImpl]
+ */
+export function sseSource({
+ url,
+ events = ['message'],
+ withCredentials = true,
+ map = (x) => x,
+ EventSourceImpl = globalThis.EventSource,
+}) {
+ return {
+ name: `sse:${url}`,
+ start(emit) {
+ if (!EventSourceImpl) return () => {};
+ const es = new EventSourceImpl(url, { withCredentials });
+ const handler = (e) => {
+ let payload = e.data;
+ try {
+ payload = JSON.parse(e.data);
+ } catch {
+ /* a plain string line is a valid message */
+ }
+ emit(map(payload));
+ };
+ for (const name of events) es.addEventListener(name, handler);
+ return () => {
+ for (const name of events) es.removeEventListener(name, handler);
+ es.close();
+ };
+ },
+ };
+}
+
+/**
+ * The three.ws delivery rail.
+ *
+ * Anything that can make an HTTPS request (a deploy script, a CI job, a cron,
+ * an AI agent holding an API key) POSTs to /api/herald/announce, and this
+ * source hands it to the avatar in the browser the human is actually looking
+ * at. The stream is per-account and session-authenticated: nobody can address
+ * your avatar but you and the keys you issued.
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.origin='https://three.ws'] rail origin
+ * @param {typeof EventSource} [opts.EventSourceImpl]
+ */
+export function railSource({ origin = 'https://three.ws', EventSourceImpl } = {}) {
+ const base = String(origin || '').replace(/\/$/, '');
+ const source = sseSource({
+ url: `${base}/api/herald/stream`,
+ events: ['announce'],
+ EventSourceImpl,
+ });
+ return { ...source, name: 'rail' };
+}
+
+/**
+ * A source fed by hand. `herald.announce()` uses one of these internally; it is
+ * exported because bridging an in-page event bus is a two-liner with it.
+ */
+export function manualSource() {
+ let push = null;
+ const pending = [];
+ return {
+ name: 'manual',
+ start(emit) {
+ push = emit;
+ while (pending.length) emit(pending.shift());
+ return () => {
+ push = null;
+ };
+ },
+ /** Feed a message in. Safe before start(): it is queued, not lost. */
+ send(message) {
+ if (push) push(message);
+ else pending.push(message);
+ },
+ };
+}
diff --git a/herald-sdk/src/voice.js b/herald-sdk/src/voice.js
new file mode 100644
index 000000000..8f2f1ef73
--- /dev/null
+++ b/herald-sdk/src/voice.js
@@ -0,0 +1,125 @@
+// Voice: the line, spoken out loud.
+//
+// Two lanes, in this order:
+// 1. A real TTS endpoint (three.ws serves one at /api/tts/speak; point it
+// anywhere that returns audio bytes for `{ text, voice, format }`). This
+// is the good one: a real voice, the same one across every browser.
+// 2. The browser's own speechSynthesis, when no endpoint is configured or
+// the endpoint is unreachable. It is robotic and inconsistent across
+// platforms, which is exactly why it is the fallback and not the default.
+//
+// Autoplay policy is not negotiable and not worth fighting: audio is attempted
+// only after a real user gesture has been seen on the page. Before that, and
+// whenever playback is refused, the caller still has the text on screen. No
+// silent failure, no fake audio, no "click here to enable sound" nag.
+
+/**
+ * @param {object} [opts]
+ * @param {string|null} [opts.endpoint='/api/tts/speak'] POST target returning audio
+ * @param {string} [opts.voice='nova'] voice id passed to the endpoint
+ * @param {'endpoint'|'browser'|'auto'} [opts.lane='auto']
+ * @param {boolean} [opts.requireGesture=true]
+ */
+export function createVoice({
+ endpoint = '/api/tts/speak',
+ voice = 'nova',
+ lane = 'auto',
+ requireGesture = true,
+} = {}) {
+ let gestureSeen = !requireGesture;
+ let audio = null;
+ let controller = null;
+ let objectUrl = null;
+
+ if (requireGesture && typeof globalThis.document !== 'undefined') {
+ const mark = () => {
+ gestureSeen = true;
+ };
+ globalThis.document.addEventListener('pointerdown', mark, { capture: true, once: true });
+ globalThis.document.addEventListener('keydown', mark, { capture: true, once: true });
+ }
+
+ function cancel() {
+ controller?.abort();
+ controller = null;
+ if (audio) {
+ audio.pause();
+ audio.onended = null;
+ audio.onerror = null;
+ audio.src = '';
+ audio = null;
+ }
+ if (objectUrl) {
+ URL.revokeObjectURL(objectUrl);
+ objectUrl = null;
+ }
+ try {
+ globalThis.speechSynthesis?.cancel();
+ } catch {
+ /* no synthesis in this environment */
+ }
+ }
+
+ async function speakViaEndpoint(text) {
+ if (!endpoint || typeof fetch !== 'function') return false;
+ controller = new AbortController();
+ let blob;
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ text, voice, format: 'mp3' }),
+ signal: controller.signal,
+ });
+ if (!res.ok) return false;
+ blob = await res.blob();
+ } catch {
+ return false;
+ }
+ if (!blob?.size) return false;
+ objectUrl = URL.createObjectURL(blob);
+ audio = new Audio(objectUrl);
+ try {
+ await audio.play();
+ return true;
+ } catch {
+ cancel();
+ return false;
+ }
+ }
+
+ function speakViaBrowser(text) {
+ const synth = globalThis.speechSynthesis;
+ if (!synth || typeof globalThis.SpeechSynthesisUtterance !== 'function') return false;
+ try {
+ const utterance = new globalThis.SpeechSynthesisUtterance(text);
+ utterance.rate = 1.02;
+ synth.speak(utterance);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ /**
+ * Say it. Resolves true when audio actually started.
+ * @param {string} text
+ */
+ async function speak(text) {
+ if (!text || !gestureSeen) return false;
+ cancel();
+ if (lane !== 'browser' && (await speakViaEndpoint(text))) return true;
+ if (lane === 'endpoint') return false;
+ return speakViaBrowser(text);
+ }
+
+ return {
+ speak,
+ cancel,
+ /** True once the page has seen a gesture, so audio is allowed at all. */
+ get unlocked() {
+ return gestureSeen;
+ },
+ };
+}
diff --git a/src/herald-embed.js b/src/herald-embed.js
new file mode 100644
index 000000000..af88eeb8b
--- /dev/null
+++ b/src/herald-embed.js
@@ -0,0 +1,66 @@
+// The CDN build of @three-ws/herald, served at the stable path /herald.js.
+//
+// Two ways to use it, both from one file:
+//
+// import { createHerald } from 'https://three.ws/herald.js'; // as a module
+// <script src="https://three.ws/herald.js"></script> // as a global
+//
+// The module path is the real one. The global (`window.threeHerald`) exists so
+// a page with no build step, or a CMS that only lets you paste a script tag,
+// still gets the whole feature: the loader creates a herald with sane defaults
+// on first use, so `threeHerald.announce('...')` works with nothing else.
+//
+// Vite emits this entry to /herald.js unhashed (see vite.config.js) and
+// vercel.json serves it with permissive CORS, so it can be imported from any
+// origin exactly like the <agent-3d> bundle.
+
+import { createHerald } from '../herald-sdk/src/index.js';
+
+export {
+ createHerald,
+ createAvatarPresenter,
+ createCardPresenter,
+ createVoice,
+ pollSource,
+ sseSource,
+ railSource,
+ manualSource,
+ decide,
+ planBatch,
+ resolveRules,
+ scoreMessage,
+ dwellMsFor,
+ toMessage,
+ withinQuietHours,
+ DEFAULT_RULES,
+ DROP_REASONS,
+ HOLD_REASONS,
+ VERSION,
+} from '../herald-sdk/src/index.js';
+
+export default createHerald;
+
+// Lazily-built default instance for the script-tag path. Building it on first
+// use rather than on load means a page that imports the module and configures
+// its own herald never pays for a second one.
+let ambient = null;
+function ensureAmbient() {
+ if (!ambient) ambient = createHerald({ voice: 'auto' });
+ return ambient;
+}
+
+if (typeof window !== 'undefined' && !window.threeHerald) {
+ window.threeHerald = {
+ createHerald,
+ /** Announce through the ambient instance, creating it on first call. */
+ announce: (message) => ensureAmbient().announce(message),
+ mute: (ms) => ensureAmbient().mute(ms),
+ unmute: () => ensureAmbient().unmute(),
+ stats: () => ensureAmbient().stats(),
+ rule: (scorer) => ensureAmbient().rule(scorer),
+ source: (source) => ensureAmbient().source(source),
+ get instance() {
+ return ensureAmbient();
+ },
+ };
+}
diff --git a/tests/herald-rail.test.js b/tests/herald-rail.test.js
new file mode 100644
index 000000000..07e062ba8
--- /dev/null
+++ b/tests/herald-rail.test.js
@@ -0,0 +1,113 @@
+// Unit tests for the herald rail's shared record shape (api/_lib/herald.js).
+//
+// The wire format is the contract between a machine that writes a line and the
+// browser that says it out loud, so the parts that matter are the ones that
+// stop a hostile or careless integration from turning a spoken sentence into
+// something else: URL scheme filtering, length caps, and importance clamping.
+
+import { describe, it, expect } from 'vitest';
+import {
+ QUEUE_CAP,
+ QUEUE_TTL_SECONDS,
+ TEXT_MAX,
+ cleanText,
+ normalizeAnnouncement,
+ parseRecord,
+ queueKey,
+ safeUrl,
+} from '../api/_lib/herald.js';
+
+const CLOCK = () => Date.parse('2026-08-28T12:00:00.000Z');
+const ID = () => 'fixed-id';
+
+describe('queueKey', () => {
+ it('scopes the queue to one user', () => {
+ expect(queueKey('u1')).toBe('herald:u1:queue');
+ expect(queueKey('u1')).not.toBe(queueKey('u2'));
+ });
+});
+
+describe('safeUrl', () => {
+ it('allows same-origin paths and absolute http(s)', () => {
+ expect(safeUrl('/dashboard')).toBe('/dashboard');
+ expect(safeUrl('https://three.ws/x')).toBe('https://three.ws/x');
+ expect(safeUrl(' /wallet ')).toBe('/wallet');
+ });
+
+ it('rejects every scheme that could execute or redirect off-site', () => {
+ expect(safeUrl('javascript:alert(1)')).toBe(null);
+ expect(safeUrl('data:text/html,<script>')).toBe(null);
+ expect(safeUrl('//evil.example.com')).toBe(null);
+ expect(safeUrl('vbscript:x')).toBe(null);
+ expect(safeUrl('')).toBe(null);
+ expect(safeUrl(null)).toBe(null);
+ });
+});
+
+describe('cleanText', () => {
+ it('collapses whitespace and caps the length', () => {
+ expect(cleanText(' hello world \n new line ')).toBe('hello world new line');
+ expect(cleanText('x'.repeat(500)).length).toBe(TEXT_MAX);
+ expect(cleanText(undefined)).toBe('');
+ });
+});
+
+describe('normalizeAnnouncement', () => {
+ it('builds the wire record with sane defaults', () => {
+ const a = normalizeAnnouncement({ text: 'Deploy is green' }, CLOCK, ID);
+ expect(a).toMatchObject({
+ id: 'fixed-id',
+ text: 'Deploy is green',
+ importance: 70,
+ tone: 'alert',
+ at: CLOCK(),
+ });
+ expect(a.url).toBeUndefined();
+ });
+
+ it('clamps importance and drops an unsafe url', () => {
+ const a = normalizeAnnouncement(
+ { text: 'x', importance: 5000, url: 'javascript:alert(1)' },
+ CLOCK,
+ ID,
+ );
+ expect(a.importance).toBe(100);
+ expect(a.url).toBeUndefined();
+ });
+
+ it('keeps a caller dedupe key and arbitrary meta', () => {
+ const a = normalizeAnnouncement(
+ { text: 'build', key: 'ci:main', meta: { run: 42 } },
+ CLOCK,
+ ID,
+ );
+ expect(a.key).toBe('ci:main');
+ expect(a.meta).toEqual({ run: 42 });
+ });
+
+ it('mints a distinct id per call by default', () => {
+ const a = normalizeAnnouncement({ text: 'one' });
+ const b = normalizeAnnouncement({ text: 'one' });
+ expect(a.id).not.toBe(b.id);
+ });
+});
+
+describe('parseRecord', () => {
+ it('accepts both shapes Redis can hand back', () => {
+ expect(parseRecord('{"text":"hi"}')).toEqual({ text: 'hi' });
+ expect(parseRecord({ text: 'hi' })).toEqual({ text: 'hi' });
+ });
+
+ it('skips anything unusable instead of throwing', () => {
+ expect(parseRecord('not json')).toBe(null);
+ expect(parseRecord(42)).toBe(null);
+ expect(parseRecord(null)).toBe(null);
+ });
+});
+
+describe('queue policy', () => {
+ it('is a live channel, not an archive', () => {
+ expect(QUEUE_TTL_SECONDS).toBeLessThanOrEqual(600);
+ expect(QUEUE_CAP).toBeLessThanOrEqual(50);
+ });
+});
diff --git a/tests/herald-rules.test.js b/tests/herald-rules.test.js
new file mode 100644
index 000000000..37966fe5f
--- /dev/null
+++ b/tests/herald-rules.test.js
@@ -0,0 +1,258 @@
+// Unit tests for the @three-ws/herald rules engine (herald-sdk/src/rules.js).
+//
+// This is the file that decides whether a human gets interrupted, so it is
+// tested the way an interrupt budget deserves: every drop reason, every hold
+// reason, the wrap-around quiet-hours window, the batch collapse, and the
+// sloppy input a real feed hands over.
+
+import { describe, it, expect } from 'vitest';
+import {
+ DEFAULT_RULES,
+ DROP_REASONS,
+ HOLD_REASONS,
+ clampImportance,
+ decide,
+ dedupeKeyFor,
+ dwellMsFor,
+ planBatch,
+ pruneSeen,
+ resolveRules,
+ scoreMessage,
+ toMessage,
+ withinQuietHours,
+} from '../herald-sdk/src/rules.js';
+
+const NOW = Date.parse('2026-08-28T12:00:00.000Z');
+
+function ctx(over = {}) {
+ return {
+ rules: resolveRules(over.rules),
+ now: NOW,
+ hour: 12,
+ seen: new Map(),
+ recent: [],
+ focused: true,
+ busy: false,
+ muted: false,
+ scorers: [],
+ ...over,
+ // `rules` must stay resolved even when the caller passed a partial.
+ ...(over.rules ? { rules: resolveRules(over.rules) } : {}),
+ };
+}
+
+const msg = (over = {}) => ({ id: 'm1', text: 'Deploy is green', at: NOW, ...over });
+
+describe('resolveRules', () => {
+ it('fills every default and lets a caller override one', () => {
+ expect(resolveRules().minImportance).toBe(DEFAULT_RULES.minImportance);
+ const r = resolveRules({ minImportance: 90 });
+ expect(r.minImportance).toBe(90);
+ expect(r.rateWindowMs).toBe(DEFAULT_RULES.rateWindowMs);
+ });
+});
+
+describe('clampImportance', () => {
+ it('clamps to 0-100 and falls back on junk', () => {
+ expect(clampImportance(120)).toBe(100);
+ expect(clampImportance(-5)).toBe(0);
+ expect(clampImportance('72')).toBe(72);
+ expect(clampImportance('nope', 33)).toBe(33);
+ expect(clampImportance(undefined)).toBe(DEFAULT_RULES.minImportance);
+ });
+});
+
+describe('scoreMessage', () => {
+ it('takes the highest opinion, ignoring abstainers', () => {
+ const score = scoreMessage(msg({ importance: 40 }), [
+ () => undefined,
+ (m) => (m.text.includes('Deploy') ? 85 : undefined),
+ () => 10,
+ ]);
+ expect(score).toBe(85);
+ });
+
+ it('survives a scorer that throws', () => {
+ const score = scoreMessage(msg({ importance: 51 }), [
+ () => {
+ throw new Error('bad rule');
+ },
+ ]);
+ expect(score).toBe(51);
+ });
+});
+
+describe('dedupeKeyFor', () => {
+ it('prefers an explicit key, then the id, then the text', () => {
+ expect(dedupeKeyFor({ key: 'k', id: 'i', text: 't' })).toBe('k');
+ expect(dedupeKeyFor({ id: 'i', text: 't' })).toBe('i');
+ expect(dedupeKeyFor({ text: 't' })).toBe('t');
+ });
+});
+
+describe('withinQuietHours', () => {
+ it('handles a same-day window', () => {
+ expect(withinQuietHours(13, [9, 17])).toBe(true);
+ expect(withinQuietHours(8, [9, 17])).toBe(false);
+ expect(withinQuietHours(17, [9, 17])).toBe(false);
+ });
+
+ it('handles a window that wraps past midnight', () => {
+ expect(withinQuietHours(23, [22, 7])).toBe(true);
+ expect(withinQuietHours(3, [22, 7])).toBe(true);
+ expect(withinQuietHours(7, [22, 7])).toBe(false);
+ expect(withinQuietHours(12, [22, 7])).toBe(false);
+ });
+
+ it('is off when unset or degenerate', () => {
+ expect(withinQuietHours(3, null)).toBe(false);
+ expect(withinQuietHours(3, [5, 5])).toBe(false);
+ });
+});
+
+describe('decide', () => {
+ it('delivers a fresh, important, unseen message', () => {
+ expect(decide(msg({ importance: 80 }), ctx()).action).toBe('deliver');
+ });
+
+ it('drops an empty line', () => {
+ const v = decide({ text: ' ' }, ctx());
+ expect(v).toMatchObject({ action: 'drop', reason: DROP_REASONS.EMPTY });
+ });
+
+ it('drops a duplicate inside the dedupe TTL and lets it through after', () => {
+ const seen = new Map([['m1', NOW - 1000]]);
+ expect(decide(msg({ importance: 80 }), ctx({ seen })).reason).toBe(DROP_REASONS.DUPLICATE);
+ const old = new Map([['m1', NOW - DEFAULT_RULES.dedupeTtlMs - 1]]);
+ expect(decide(msg({ importance: 80 }), ctx({ seen: old })).action).toBe('deliver');
+ });
+
+ it('drops history', () => {
+ const stale = msg({ importance: 90, at: NOW - DEFAULT_RULES.freshnessMs - 1 });
+ expect(decide(stale, ctx()).reason).toBe(DROP_REASONS.STALE);
+ });
+
+ it('treats a message with no timestamp as now, never as history', () => {
+ const undated = { id: 'x', text: 'Manual line', importance: 80 };
+ expect(decide(undated, ctx()).action).toBe('deliver');
+ });
+
+ it('drops anything under the interrupt floor', () => {
+ expect(decide(msg({ importance: 10 }), ctx()).reason).toBe(DROP_REASONS.BELOW_FLOOR);
+ });
+
+ it('drops everything while muted', () => {
+ expect(decide(msg({ importance: 100 }), ctx({ muted: true })).reason).toBe(DROP_REASONS.MUTED);
+ });
+
+ it('holds while another delivery is on screen', () => {
+ expect(decide(msg({ importance: 80 }), ctx({ busy: true }))).toMatchObject({
+ action: 'hold',
+ reason: HOLD_REASONS.BUSY,
+ });
+ });
+
+ it('holds for a background tab, unless focusOnly is off', () => {
+ expect(decide(msg({ importance: 80 }), ctx({ focused: false })).reason).toBe(
+ HOLD_REASONS.UNFOCUSED,
+ );
+ expect(
+ decide(msg({ importance: 80 }), ctx({ focused: false, rules: { focusOnly: false } })).action,
+ ).toBe('deliver');
+ });
+
+ it('holds once the rate window is full, and only counts what is inside it', () => {
+ const full = Array.from({ length: DEFAULT_RULES.maxPerWindow }, (_, i) => NOW - i * 1000);
+ expect(decide(msg({ importance: 80 }), ctx({ recent: full })).reason).toBe(
+ HOLD_REASONS.RATE_LIMITED,
+ );
+ const expired = full.map((t) => t - DEFAULT_RULES.rateWindowMs - 1);
+ expect(decide(msg({ importance: 80 }), ctx({ recent: expired })).action).toBe('deliver');
+ });
+
+ it('holds through quiet hours but lets a true emergency through', () => {
+ const night = ctx({ hour: 2, rules: { quietHours: [22, 7] } });
+ expect(decide(msg({ importance: 80 }), night).reason).toBe(HOLD_REASONS.QUIET_HOURS);
+ expect(decide(msg({ importance: 95 }), night).action).toBe('deliver');
+ });
+
+ it('reports the score it judged with, whatever the outcome', () => {
+ const v = decide(msg({ importance: 12 }), ctx({ scorers: [() => 99] }));
+ expect(v.importance).toBe(99);
+ expect(v.action).toBe('deliver');
+ });
+});
+
+describe('planBatch', () => {
+ const many = [
+ { text: 'a', importance: 60, at: 1 },
+ { text: 'b', importance: 95, at: 2 },
+ { text: 'c', importance: 80, at: 3 },
+ { text: 'd', importance: 70, at: 4 },
+ ];
+
+ it('says the most important few and collapses the rest into one line', () => {
+ const plan = planBatch(many, 2);
+ expect(plan.deliver.map((m) => m.text)).toEqual(['b', 'c']);
+ expect(plan.collapsed).toHaveLength(2);
+ expect(plan.summary).toBe('2 more messages waiting');
+ });
+
+ it('has no summary when everything fits', () => {
+ expect(planBatch(many, 10).summary).toBe(null);
+ });
+
+ it('uses the singular for exactly one collapsed message', () => {
+ expect(planBatch(many, 3).summary).toBe('1 more message waiting');
+ });
+
+ it('never divides by a nonsense batch size', () => {
+ expect(planBatch(many, 0).deliver).toHaveLength(1);
+ });
+});
+
+describe('dwellMsFor', () => {
+ it('scales with length and stays inside its bounds', () => {
+ expect(dwellMsFor('hi')).toBeGreaterThanOrEqual(4200);
+ expect(dwellMsFor('x'.repeat(10_000))).toBe(14_000);
+ expect(dwellMsFor('a short line')).toBeLessThan(dwellMsFor('a considerably longer line'));
+ });
+});
+
+describe('pruneSeen', () => {
+ it('forgets expired keys and caps the rest', () => {
+ const seen = new Map([
+ ['old', NOW - 10_000],
+ ['fresh', NOW],
+ ]);
+ pruneSeen(seen, NOW, 5_000);
+ expect([...seen.keys()]).toEqual(['fresh']);
+
+ const big = new Map(Array.from({ length: 10 }, (_, i) => [`k${i}`, NOW]));
+ pruneSeen(big, NOW, 60_000, 4);
+ expect(big.size).toBe(4);
+ });
+});
+
+describe('toMessage', () => {
+ it('accepts a bare string', () => {
+ expect(toMessage('hello')).toMatchObject({ text: 'hello' });
+ });
+
+ it('maps the field names real feeds actually use', () => {
+ const m = toMessage({
+ id: 7,
+ body: 'Something happened',
+ priority: 88,
+ link: '/x',
+ created_at: '2026-08-28T12:00:00.000Z',
+ });
+ expect(m).toMatchObject({ id: '7', text: 'Something happened', importance: 88, url: '/x' });
+ expect(m.at).toBe(NOW);
+ });
+
+ it('rejects anything with no line in it', () => {
+ expect(toMessage(null)).toBe(null);
+ expect(toMessage({ id: 'x' })).toBe(null);
+ });
+});
diff --git a/tests/herald-runtime.test.js b/tests/herald-runtime.test.js
new file mode 100644
index 000000000..a48e89af7
--- /dev/null
+++ b/tests/herald-runtime.test.js
@@ -0,0 +1,213 @@
+// Runtime tests for createHerald (herald-sdk/src/index.js): the orchestration
+// around the rules engine. Presenters are injected, the clock is injected, and
+// timers are faked, so these assert real behaviour (what reached a human, in
+// what order, and what got held) with no DOM and no waiting.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { createHerald } from '../herald-sdk/src/index.js';
+
+function fakePresenter(name, { shows = true } = {}) {
+ const shown = [];
+ return {
+ name,
+ shown,
+ async ready() {
+ return shows;
+ },
+ async present(message, opts) {
+ shown.push({ text: message.text, importance: message.importance, opts });
+ return shows;
+ },
+ stop() {},
+ };
+}
+
+function harness(over = {}) {
+ let clock = Date.parse('2026-08-28T12:00:00.000Z');
+ const card = fakePresenter('card');
+ const avatar = fakePresenter('avatar');
+ const delivered = [];
+ const dropped = [];
+ const herald = createHerald({
+ presenters: { avatar, card },
+ now: () => clock,
+ onDeliver: (m) => delivered.push(m.text),
+ onDrop: (m, reason) => dropped.push([m?.text ?? null, reason]),
+ ...over,
+ });
+ return {
+ herald,
+ card,
+ avatar,
+ delivered,
+ dropped,
+ tick: (ms) => {
+ clock += ms;
+ },
+ get clock() {
+ return clock;
+ },
+ };
+}
+
+// Let every queued microtask (presenter awaits) settle.
+const settle = async () => {
+ for (let i = 0; i < 6; i++) await Promise.resolve();
+};
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+describe('delivery', () => {
+ it('prefers the avatar when one can be rendered', async () => {
+ const h = harness();
+ h.herald.announce({ text: 'Deploy is green', importance: 80 });
+ await settle();
+ expect(h.avatar.shown.map((s) => s.text)).toEqual(['Deploy is green']);
+ expect(h.card.shown).toHaveLength(0);
+ expect(h.herald.stats().delivered).toBe(1);
+ });
+
+ it('falls back to the card when the avatar cannot render', async () => {
+ const avatar = fakePresenter('avatar', { shows: false });
+ const h = harness({ presenters: { avatar, card: fakePresenter('card') } });
+ h.herald.announce({ text: 'No GPU here', importance: 80 });
+ await settle();
+ expect(h.herald.stats().delivered).toBe(1);
+ });
+
+ it('passes a dwell scaled to the line and an Open action for a url', async () => {
+ const h = harness();
+ h.herald.announce({ text: 'Payment received', importance: 80, url: '/wallet' });
+ await settle();
+ const { opts } = h.avatar.shown[0];
+ expect(opts.dwellMs).toBeGreaterThan(4000);
+ expect(opts.actions[0]).toMatchObject({ label: 'Open', href: '/wallet' });
+ });
+
+ it('counts a presenter that throws as dropped, and keeps working after', async () => {
+ const avatar = fakePresenter('avatar');
+ avatar.present = async () => {
+ throw new Error('webgl lost');
+ };
+ const h = harness({ presenters: { avatar, card: fakePresenter('card') } });
+ h.herald.announce({ text: 'first', importance: 80 });
+ await settle();
+ expect(h.herald.stats().dropped).toBe(1);
+ h.herald.announce({ text: 'second', importance: 80, id: 'two' });
+ await settle();
+ expect(h.herald.stats().received).toBe(2);
+ });
+});
+
+describe('the interrupt budget', () => {
+ it('says a message once, however many times a source repeats it', async () => {
+ const h = harness();
+ for (let i = 0; i < 3; i++) h.herald.announce({ id: 'same', text: 'Same thing', importance: 80 });
+ await settle();
+ expect(h.avatar.shown).toHaveLength(1);
+ expect(h.dropped).toContainEqual(['Same thing', 'duplicate']);
+ });
+
+ it('drops what does not clear the floor and reports why', async () => {
+ const h = harness({ rules: { minImportance: 70 } });
+ h.herald.announce({ text: 'FYI', importance: 20 });
+ await settle();
+ expect(h.avatar.shown).toHaveLength(0);
+ expect(h.herald.stats().drops.at(-1)).toMatchObject({ reason: 'below-importance-floor' });
+ });
+
+ it('holds a burst past the batch size and collapses it into one summary', async () => {
+ const h = harness({ rules: { maxPerWindow: 1, batchSize: 2 } });
+ for (const i of [1, 2, 3, 4]) {
+ h.herald.announce({ id: `b${i}`, text: `alert ${i}`, importance: 70 + i });
+ }
+ await settle();
+ // One got through; the rest are rate-limited into the held queue.
+ expect(h.avatar.shown).toHaveLength(1);
+ expect(h.herald.stats().holding).toBe(3);
+
+ // Let the rate window drain, then run the sweep.
+ h.tick(70_000);
+ await vi.advanceTimersByTimeAsync(6_000);
+ await settle();
+ const lines = h.avatar.shown.map((s) => s.text);
+ expect(lines).toContain('alert 4'); // highest importance first
+ expect(lines.some((l) => /more message/.test(l))).toBe(true);
+ });
+
+ it('mutes and unmutes on demand', async () => {
+ const h = harness();
+ h.herald.mute();
+ h.herald.announce({ text: 'ignored', importance: 100 });
+ await settle();
+ expect(h.avatar.shown).toHaveLength(0);
+ expect(h.herald.muted).toBe(true);
+
+ h.herald.unmute();
+ h.herald.announce({ text: 'heard', importance: 100 });
+ await settle();
+ expect(h.avatar.shown.map((s) => s.text)).toEqual(['heard']);
+ });
+
+ it('expires a timed mute', async () => {
+ const h = harness();
+ h.herald.mute(60_000);
+ h.herald.announce({ text: 'during', importance: 100 });
+ await settle();
+ expect(h.avatar.shown).toHaveLength(0);
+ h.tick(61_000);
+ h.herald.announce({ text: 'after', importance: 100 });
+ await settle();
+ expect(h.avatar.shown.map((s) => s.text)).toEqual(['after']);
+ });
+});
+
+describe('scorers', () => {
+ it('lifts a message over the floor by who it is from', async () => {
+ const h = harness({ rules: { minImportance: 80 } });
+ h.herald.rule((m) => (m.from === 'oncall' ? 100 : undefined));
+ h.herald.announce({ text: 'page', importance: 10, from: 'oncall' });
+ h.herald.announce({ text: 'noise', importance: 10, from: 'newsletter' });
+ await settle();
+ expect(h.avatar.shown.map((s) => s.text)).toEqual(['page']);
+ });
+});
+
+describe('sources', () => {
+ it('reads a source and normalises whatever shape it emits', async () => {
+ const h = harness();
+ const source = {
+ name: 'test',
+ start(emit) {
+ emit({ id: 's1', body: 'From a feed', priority: 90, link: '/x' });
+ emit('a bare string that is important enough by default');
+ return () => {};
+ },
+ };
+ h.herald.source(source);
+ await settle();
+ expect(h.herald.stats().received).toBe(2);
+ expect(h.avatar.shown[0].text).toBe('From a feed');
+ });
+
+ it('stops every source when the herald stops', async () => {
+ const h = harness();
+ const stopped = vi.fn();
+ h.herald.source({ name: 'x', start: () => stopped });
+ h.herald.stop();
+ expect(stopped).toHaveBeenCalled();
+ });
+});
+
+describe('stats', () => {
+ it('reports what happened, with the last drops and their reasons', async () => {
+ const h = harness();
+ h.herald.announce({ text: 'kept', importance: 90 });
+ h.herald.announce({ text: '', importance: 90 });
+ await settle();
+ const stats = h.herald.stats();
+ expect(stats).toMatchObject({ received: 1, delivered: 1, dropped: 1 });
+ expect(stats.drops.at(-1).reason).toBe('empty');
+ });
+});