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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(companion): publish the triage rules so every body makes the same call
nirholas9a6336457f7a
diff --git a/api/_lib/companion/poll.js b/api/_lib/companion/poll.jsindex 149ed35ac..e9750d091 100644--- a/api/_lib/companion/poll.js+++ b/api/_lib/companion/poll.js@@ -11,6 +11,7 @@import { sql } from '../db.js';import { insertNotification } from '../notify.js';import { loadUserProviderKeys } from '../provider-keys.js';+import { inQuietHours } from '@three-ws/companion/triage';import { triage } from './triage.js';import {getSettings,@@ -34,28 +35,10 @@ export function laneFor(kind) {return LANES[kind] || null;}-/**- * Is it the middle of the user's night?- * Quiet hours are evaluated in the user's own timezone, and a window that wraps- * midnight (22 to 7) is the normal case rather than the exception.- */-export function inQuietHours(settings, now = new Date()) {- if (settings.quiet_start === null || settings.quiet_start === undefined) return false;- if (settings.quiet_end === null || settings.quiet_end === undefined) return false;- let hour;- try {- hour = Number(new Intl.DateTimeFormat('en-US', {- hour: 'numeric',- hour12: false,- timeZone: settings.timezone || 'UTC',- }).format(now));- } catch {- hour = now.getUTCHours();- }- const { quiet_start: start, quiet_end: end } = settings;- if (start === end) return true;- return start < end ? hour >= start && hour < end : hour >= start || hour < end;-}+// Quiet hours are evaluated in the user's own timezone, and a window that wraps+// midnight (22 to 7) is the normal case. Re-exported from the rules package so+// the server, the CLI, and any third-party body agree on when to stay silent.+export { inQuietHours };async function anthropicKeyFor(userId) {try {diff --git a/api/_lib/companion/triage.js b/api/_lib/companion/triage.jsindex 682384779..2f8747146 100644--- a/api/_lib/companion/triage.js+++ b/api/_lib/companion/triage.js@@ -2,10 +2,13 @@// line the companion says out loud when it is.//// Two stages, and the first one always runs:-// 1. A deterministic scorer (below). It reads the sender, the lane, the-// contact card, and the language of the message. It needs no key, costs-// nothing, and is what keeps the feature working for a signed-in user who-// has connected nothing but the phone bridge.+// 1. The deterministic scorer. It lives in the published SDK+// (@three-ws/companion/triage, packages/companion-sdk) rather than here,+// on purpose: the server, the CLI's local privacy mode, and anybody+// building their own body must make the SAME judgement, and two copies of+// a rule set drift within a month. It needs no key, costs nothing, and is+// what keeps the feature working for someone who has connected nothing but+// the phone bridge.// 2. An LLM pass that can move the score and rewrite the spoken line in the// companion's voice. It runs on the user's OWN key when they have stored// one (BYOK, api/_lib/provider-keys.js) and on the platform free chain@@ -16,105 +19,10 @@// only the numeric score and two short strings are read back out. Nothing the// model returns can trigger an action.+import { scoreByRules, defaultLine, shorten, clampScore } from '@three-ws/companion/triage';import { llmComplete, llmConfigured } from '../llm.js';-const URGENT = /\b(urgent|asap|emergency|immediately|right now|deadline|overdue|final notice|action required|time sensitive)\b/i;-const PERSONAL = /\b(call me|text me|ring me|where are you|are you (there|around|free)|need you|help|i'?m outside|on my way|pick me up)\b/i;-const MONEY = /\b(payment|invoice|refund|charge|declined|fraud|unauthorized|wire|transfer|past due|receipt)\b/i;-const SECURITY = /\b(verification code|security code|one[- ]time|2fa|otp|password reset|sign[- ]?in attempt|suspicious login)\b/i;-const LOGISTICS = /\b(flight|gate|delayed|cancell?ed|reschedul|boarding|delivery|arriving|appointment)\b/i;-const BULK = /\b(unsubscribe|newsletter|promotion|sale ends|% off|limited time offer|no[- ]reply|noreply|marketing|webinar|survey)\b/i;--// Lane baselines. A calendar event is on the user's own calendar, so it starts-// higher than a stranger's email, which starts near the floor.-const BASELINE = { telegram: 42, email: 30, calendar: 55, bridge: 45 };--function clamp(n) {- return Math.max(0, Math.min(100, Math.round(n)));-}--function minutesUntil(when) {- if (!when) return null;- const ts = when instanceof Date ? when.getTime() : Date.parse(when);- if (Number.isNaN(ts)) return null;- return (ts - Date.now()) / 60000;-}--// Trim any message to something a person can hear in one breath.-export function shorten(text, max = 220) {- const flat = String(text || '').replace(/\s+/g, ' ').trim();- if (flat.length <= max) return flat;- const cut = flat.slice(0, max);- const stop = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf(', '), cut.lastIndexOf(' '));- return `${cut.slice(0, stop > 60 ? stop : max).trim()}…`;-}--/**- * Deterministic importance pass.- * @returns {{ importance:number, reason:string, line:string }}- */-export function scoreByRules(event, contact = null) {- const text = `${event.title || ''} ${event.body || ''}`;- const reasons = [];- let score = BASELINE[event.source_kind] ?? 40;-- if (contact) {- score += 18 + (contact.priority_boost || 0);- reasons.push(`from ${contact.display_name}, a saved contact`);- }- // +40, not +30: this module's own scale calls 70-100 "interrupt the person- // now", and a one-time code is the canonical interrupt, someone is sitting- // at a sign-in screen waiting for it. At +30 a code arriving by email (the- // lowest baseline, 30) landed on 60, one band below the line, which is the- // one message you must never merely "glance at". A marketing mail that says- // "one-time offer" still floors out, because BULK and the unattended-address- // penalties subtract more than this adds.- if (SECURITY.test(text)) { score += 40; reasons.push('looks like a security or login code'); }- if (URGENT.test(text)) { score += 22; reasons.push('says it is urgent'); }- if (PERSONAL.test(text)) { score += 18; reasons.push('asks you for something directly'); }- if (MONEY.test(text)) { score += 14; reasons.push('concerns money or a payment'); }- if (LOGISTICS.test(text)) { score += 12; reasons.push('affects travel or a delivery'); }- if (/\?\s*$/.test((event.body || event.title || '').trim())) { score += 6; reasons.push('ends in a question'); }- if (BULK.test(text)) { score -= 28; reasons.push('reads like a bulk or marketing message'); }- if (/^(no[- ]?reply|do[- ]?not[- ]?reply|notifications?|updates?|info|newsletter)@/i.test(event.sender_id || '')) {- score -= 20;- reasons.push('sent from an unattended address');- }-- // A calendar entry matters in proportion to how soon it starts.- const mins = minutesUntil(event.occurs_at);- if (event.source_kind === 'calendar' && mins !== null) {- if (mins <= 5) { score += 32; reasons.push('starts in minutes'); }- else if (mins <= 15) { score += 24; reasons.push('starts within the quarter hour'); }- else if (mins <= 60) { score += 12; reasons.push('starts within the hour'); }- }-- // The phone bridge can carry the OS-level priority the sending device knew.- if (event.priority_hint === 'high') { score += 20; reasons.push('the device marked it high priority'); }- if (event.priority_hint === 'low') { score -= 20; reasons.push('the device marked it low priority'); }-- return {- importance: clamp(score),- reason: reasons.length ? reasons.join('; ') : 'no urgency signals in the message',- line: defaultLine(event, contact),- };-}--// The spoken fallback: plain, specific, and never longer than a sentence or two.-export function defaultLine(event, contact = null) {- const who = contact?.display_name || event.sender || 'Someone';- const body = shorten(event.body || event.title, 180);- if (event.source_kind === 'calendar') {- const mins = minutesUntil(event.occurs_at);- const when = mins === null ? 'coming up'- : mins <= 1 ? 'starting now'- : mins < 60 ? `in ${Math.round(mins)} minutes`- : `at ${new Date(event.occurs_at).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}`;- return `Heads up, ${event.title} is ${when}.${event.body ? ` ${shorten(event.body, 120)}` : ''}`;- }- if (event.source_kind === 'email') return `${who} emailed you: ${event.title}. ${body}`;- return `${who} says: ${body}`;-}+export { scoreByRules, defaultLine, shorten };const SYSTEM = ['You triage a person\'s incoming messages for a 3D assistant that will speak the result out loud.',@@ -131,11 +39,15 @@ function parseVerdict(text) {const match = String(text || '').match(/\{[\s\S]*\}/);if (!match) return null;let parsed;- try { parsed = JSON.parse(match[0]); } catch { return null; }+ try {+ parsed = JSON.parse(match[0]);+ } catch {+ return null;+ }const importance = Number(parsed.importance);if (!Number.isFinite(importance)) return null;return {- importance: clamp(importance),+ importance: clampScore(importance),reason: shorten(parsed.reason || '', 90),line: shorten(parsed.line || '', 220),};@@ -151,7 +63,9 @@ function parseVerdict(text) {*/export async function triage(event, contact = null, { anthropicKey = null, userId = null } = {}) {const rules = scoreByRules(event, contact);- if (!llmConfigured({ anthropicKey })) return { ...rules, engine: 'rules' };+ if (!llmConfigured({ anthropicKey })) {+ return { importance: rules.importance, reason: rules.reason, line: rules.line, engine: 'rules' };+ }const context = [`lane: ${event.source_kind}`,@@ -171,19 +85,21 @@ export async function triage(event, contact = null, { anthropicKey = null, userItrack: userId ? { userId, tool: 'companion_triage' } : null,});const verdict = parseVerdict(text);- if (!verdict) return { ...rules, engine: 'rules' };+ if (!verdict) {+ return { importance: rules.importance, reason: rules.reason, line: rules.line, engine: 'rules' };+ }// The model moves the score but does not own it: a saved contact's boost// and the calendar clock are facts, so the final score never drops below// what those facts alone justify by more than a small margin.const floor = contact ? Math.max(0, rules.importance - 15) : 0;return {- importance: clamp(Math.max(verdict.importance, floor)),+ importance: clampScore(Math.max(verdict.importance, floor)),reason: verdict.reason || rules.reason,line: verdict.line || rules.line,engine: anthropicKey ? 'byok' : `platform:${provider || 'llm'}`,};} catch {// Over quota, no key, upstream down: the deterministic verdict stands.- return { ...rules, engine: 'rules' };+ return { importance: rules.importance, reason: rules.reason, line: rules.line, engine: 'rules' };}}diff --git a/api/companion/stream.js b/api/companion/stream.jsnew file mode 100644index 000000000..c693f7e72--- /dev/null+++ b/api/companion/stream.js@@ -0,0 +1,188 @@+// GET /api/companion/stream - live deliveries, as Server-Sent Events.+//+// This is the socket the bodies listen on: the /companion stage, the desktop+// companion (apps/desktop), a browser extension, or anything built with+// @three-ws/companion. A delivery reaches every connected body within a poll+// tick of being triaged, so the character on your desktop turns around and+// speaks at the same moment the phone buzzes.+//+// Auth, two ways, because the clients are different animals:+// • a session cookie, for the page and any first-party surface;+// • the bridge token (Authorization: Bearer), for the desktop app, a CLI, a+// Raspberry Pi in the hallway. One credential per user, rotatable from+// /companion, and the same one the ingest endpoint accepts.+//+// Only events at or above the user's own threshold are streamed: the feed on+// the page is where quiet ones live. `?since=<iso>` replays anything delivered+// after that instant (bounded), which is how a laptop that was asleep catches+// up without repeating a week of messages.+//+// Cost shape: one poll loop per connection, but the query is a single indexed+// read of one user's own rows, and the cadence ramps from 2s to 15s while the+// user's world is quiet, so an idle desktop app costs about four reads a minute.++import { sql } from '../_lib/db.js';+import { cors, method } from '../_lib/http.js';+import { getSessionUser, extractBearer } from '../_lib/auth.js';+import { userForIngestToken, getSettings } from '../_lib/companion/store.js';++export const maxDuration = 300;++const HEARTBEAT_MS = 15_000;+const POLL_MS_MIN = 2_000;+const POLL_MS_MAX = 15_000;+const IDLE_RAMP_AFTER = 5;+const MAX_ROWS_PER_TICK = 20;+// A client that has been away replays at most this far back, so a machine that+// slept for a week wakes to what is still relevant rather than to a monologue.+const MAX_REPLAY_MS = 6 * 60 * 60 * 1000;++const SSE_HEADERS = {+ 'Content-Type': 'text/event-stream; charset=utf-8',+ 'Cache-Control': 'no-cache, no-transform',+ Connection: 'keep-alive',+ // Cloud Run and the CDN in front of it buffer by default; without this the+ // frames are held until the function returns, which defeats the stream.+ 'X-Accel-Buffering': 'no',+};++async function resolveViewer(req) {+ const bearer = extractBearer(req);+ if (bearer) {+ const settings = await userForIngestToken(bearer);+ if (settings) return { userId: settings.user_id, settings, via: 'bridge_token' };+ return null;+ }+ const user = await getSessionUser(req);+ if (!user) return null;+ return { userId: user.id, settings: await getSettings(user.id), via: 'session' };+}++function pollDelay(idleTicks) {+ if (idleTicks <= IDLE_RAMP_AFTER) return POLL_MS_MIN;+ return Math.min(Math.round(POLL_MS_MIN * Math.pow(1.5, idleTicks - IDLE_RAMP_AFTER)), POLL_MS_MAX);+}++export default async function handleCompanionStream(req, res) {+ const isHead = (req.method || 'GET').toUpperCase() === 'HEAD';+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;+ if (isHead) {+ res.writeHead(200, SSE_HEADERS);+ res.end();+ return;+ }++ const viewer = await resolveViewer(req);+ if (!viewer) {+ res.writeHead(401, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ error: 'unauthorized', message: 'sign in, or send your bridge token as a Bearer header' }));+ return;+ }++ const params = new URL(req.url, 'http://x').searchParams;+ const sinceRaw = params.get('since');+ const floor = new Date(Date.now() - MAX_REPLAY_MS);+ let cursor = sinceRaw && !Number.isNaN(Date.parse(sinceRaw))+ ? new Date(Math.max(Date.parse(sinceRaw), floor.getTime()))+ : new Date();+ let cursorId = '';++ res.writeHead(200, SSE_HEADERS);++ let closed = false;+ const send = (event, data) => {+ if (closed || res.writableEnded) return;+ res.write(`event: ${event}\n`);+ res.write(`data: ${JSON.stringify(data)}\n\n`);+ };++ send('hello', {+ ts: Date.now(),+ via: viewer.via,+ threshold: viewer.settings.threshold,+ enabled: viewer.settings.enabled,+ default_avatar_glb_url: viewer.settings.avatar_glb_url,+ default_voice: viewer.settings.voice,+ });++ let idleTicks = 0;+ let timer = null;++ const tick = async () => {+ if (closed) return;+ try {+ const rows = await sql`+ select e.id, e.source_kind, e.sender, e.sender_id, e.title, e.body, e.url,+ e.importance, e.reason, e.spoken_line, e.occurs_at, e.created_at,+ c.display_name as contact_name, c.avatar_glb_url as contact_avatar_glb_url,+ c.avatar_image_url as contact_avatar_image_url, c.voice as contact_voice+ from companion_events e+ left join companion_contacts c on c.id = e.contact_id+ where e.user_id = ${viewer.userId}+ and e.dismissed_at is null+ and e.importance >= ${viewer.settings.threshold}+ and (e.created_at, e.id::text) > (${cursor.toISOString()}::timestamptz, ${cursorId})+ order by e.created_at asc, e.id::text asc+ limit ${MAX_ROWS_PER_TICK}+ `;+ if (rows.length) {+ idleTicks = 0;+ const last = rows[rows.length - 1];+ cursor = last.created_at instanceof Date ? last.created_at : new Date(last.created_at);+ cursorId = String(last.id);+ for (const row of rows) {+ send('delivery', {+ ...row,+ // What to perform with, resolved server-side so every client+ // (page, desktop, extension) stages the same body and voice.+ avatar_glb_url: row.contact_avatar_glb_url || viewer.settings.avatar_glb_url || null,+ voice: row.contact_voice || viewer.settings.voice || null,+ speaker: row.contact_name || row.sender || 'Your companion',+ });+ }+ } else {+ idleTicks += 1;+ }+ } catch (err) {+ // A transient DB error must not kill a long-lived connection: report it+ // on the stream and keep polling. The client decides whether to care.+ send('warning', { message: String(err?.message || err).slice(0, 200) });+ }+ if (!closed) timer = setTimeout(tick, pollDelay(idleTicks));+ };++ timer = setTimeout(tick, 250);++ const startMs = Date.now();+ const heartbeat = setInterval(() => {+ if (closed || res.writableEnded) return;+ // Retire before the platform's hard timeout, telling the client to come+ // straight back. EventSource honours `retry:` on its own.+ if (Date.now() - startMs > 275_000) {+ res.write('retry: 1000\n\n');+ cleanup();+ return;+ }+ res.write(':hb\n\n');+ }, HEARTBEAT_MS);++ function cleanup() {+ if (closed) return;+ closed = true;+ clearTimeout(timer);+ clearInterval(heartbeat);+ if (!res.writableEnded) {+ try {+ res.end();+ } catch {+ /* socket already torn down */+ }+ }+ }++ req.on('close', cleanup);+ req.on('error', cleanup);+ res.on('close', cleanup);+ res.on('error', cleanup);+}diff --git a/packages/companion-sdk/LICENSE b/packages/companion-sdk/LICENSEnew file mode 100644index 000000000..dff21b7f4--- /dev/null+++ b/packages/companion-sdk/LICENSE@@ -0,0 +1,20 @@+Copyright 2026 nirholas++All rights reserved.++This software is proprietary and may not be used, copied, modified, distributed,+translated, or made available to any third party without the express written+permission of the copyright owner.++No rights are granted by implication, estoppel, or otherwise. Use of this+software is subject to the terms of a separate license agreement with the+copyright owner.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.++IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/packages/companion-sdk/README.md b/packages/companion-sdk/README.mdnew file mode 100644index 000000000..5e6aaba51--- /dev/null+++ b/packages/companion-sdk/README.md@@ -0,0 +1,280 @@+# @three-ws/companion++**Give a person's notifications a body.**++Software has spent thirty years getting better at buzzing. It has not got any+better at telling you which buzz mattered. This package is the other half: a+harness that decides what is worth interrupting a human for, and a 3D character+that walks over and says it out loud, in the voice and the body of whoever it+came from.++```js+import { createCompanionClient } from '@three-ws/companion';++const companion = createCompanionClient({ token: process.env.COMPANION_TOKEN });++await companion.send({+ title: 'Production deploy failed on main',+ sender: 'CI',+ priority: 'high',+ url: 'https://github.com/acme/api/actions/runs/1234',+});+// → the character on their desktop turns around and says it.+```++It ships four things that compose:++| | What it is |+|---|---|+| **Client** | `createCompanionClient()` - push messages in, stream triaged deliveries out (auto-reconnecting SSE, works in Node, browsers, and Electron). |+| **Triage** | `scoreByRules()` / `decide()` - the same interrupt-or-not judgement the hosted service makes, locally, with no key and no network. |+| **Stage** | `createCompanionStage()` - drops a 3D body into any page and has it deliver, with a real voice. |+| **CLI** | `companion send / stream / watch-imap / mcp / doctor` - including an MCP server, so any agent can interrupt a human in person. |++Install:++```bash+npm install @three-ws/companion+```++Get a bridge token at **[three.ws/companion](https://three.ws/companion)**. It is+the only credential anything here needs, it is per person, and rotating it on+that page disconnects every device at once.++---++## 1. Send something worth hearing++Anything that can make an HTTP request can hand the companion a message: a CI+job, a home server, a trading bot, a Raspberry Pi in the hallway, an agent.++```js+const result = await companion.send({+ title: 'Sarah is at the door', // required+ body: 'She says the gate code did not work',+ sender: 'Sarah', // matched against the person's contacts+ sender_id: '+14155550100', // matched first, and more precisely+ app: 'Messages',+ url: 'https://…', // optional, becomes an Open button+ priority: 'high', // what the sending device already knew+ id: 'doorbell-2026-08-28T12:04', // optional, makes retries idempotent+});++result.event.importance; // 92+result.event.reason; // "from Sarah, a saved contact; asks you for something directly"+result.event.line; // "Sarah is at the door and says the gate code did not work."+result.event.delivered; // true - it cleared their bar and was spoken+```++Nothing you send is guaranteed to be spoken, and that is the point: the person+sets the bar, their quiet hours are respected, and everything below it is kept+in their feed instead of shouted at them.++## 2. Listen for deliveries++```js+const stop = companion.stream({+ onOpen: (hello) => console.log('threshold is', hello.threshold),+ onDelivery: (delivery) => {+ console.log(`${delivery.speaker}: ${delivery.spoken_line}`);+ companion.markDelivered(delivery.id); // so no other device repeats it+ },+ onError: (err) => console.warn(err.message),+});++// later+stop();+```++A delivery carries everything a body needs to perform it:++```jsonc+{+ "id": "…",+ "source_kind": "telegram",+ "speaker": "Sarah",+ "spoken_line": "Sarah says she is downstairs and cannot find your door.",+ "importance": 88,+ "reason": "from Sarah, a saved contact; asks you for something directly",+ "avatar_glb_url": "https://three.ws/api/avatars/…/glb", // her own body+ "voice": "nova", // her own voice+ "url": null,+ "created_at": "2026-08-28T12:04:11.221Z"+}+```++The stream reconnects on its own and resumes from the last delivery it saw, so a+laptop that slept wakes up and catches what it missed (bounded server side to+the last few hours, because a monologue is not a delivery).++## 3. Put a body on a page++```js+import { createCompanionClient, createCompanionStage } from '@three-ws/companion';++const client = createCompanionClient({ token });+const stage = createCompanionStage({ client, corner: 'bottom-right' });+stage.listen();+```++That is the whole integration. The stage loads the published `<agent-3d>` web+component from three.ws, shows a speech bubble, speaks the line through the+platform voice lanes (falling back to the browser's own speech synthesis), and+swaps to the sender's avatar for the length of the delivery.++Drive it yourself if you would rather:++```js+stage.deliver({+ speaker: 'CI',+ spoken_line: 'The deploy finished. Everything is green.',+ avatar_glb_url: 'https://example.com/robot.glb',+});+```++Inside a page that is already signed in to three.ws, omit the token entirely and+the browser's session cookie is used instead.++## 4. Judge a message locally, with no key++The triage rules are the same code the server runs. Import them when you want+the judgement without sending anything anywhere:++```js+import { decide } from '@three-ws/companion/triage';++const verdict = decide(+ { source_kind: 'email', sender_id: '[email protected]', title: 'Your verification code is 220913' },+ { threshold: 60, settings: { quiet_start: 22, quiet_end: 7, timezone: 'Europe/Berlin' } },+);++verdict.importance; // 70+verdict.signals; // ['security_code']+verdict.speak; // true, unless it is the middle of their night+verdict.line; // what the companion would say+```++Signals it reads today: a saved contact (and their priority), one-time codes,+urgent language, direct requests, money, travel and delivery, a trailing+question, bulk/marketing wording, unattended senders, how close a calendar event+is, and whatever priority the sending device already assigned.++This is what makes a **local privacy mode** possible: score on your own machine,+and send only the one line that earned an interruption.++## 5. The command line++```bash+npx @three-ws/companion login --token cmp_…++companion send "Backup finished" --from "home-server" --priority low+companion stream --say # tail deliveries, speak them (macOS)+companion list --limit 10+companion check # poll every connected source now+companion score "Your code is 1234" --lane email+companion doctor # token, reachability, per-source health+```++### Local IMAP mode: your mail password never leaves the machine++```bash+npm install imapflow+companion watch-imap --host imap.fastmail.com --user [email protected] --redact+```++This connects to your inbox **locally**, scores every new message with the rules+above on your own hardware, and posts only what clears the bar, with the body+redacted if you ask. The hosted service never sees the mailbox, the password, or+the messages that did not matter.++### MCP: let an agent interrupt a human, in person++```bash+companion mcp # stdio MCP server+```++```jsonc+// claude_desktop_config.json / any MCP client+{+ "mcpServers": {+ "companion": {+ "command": "npx",+ "args": ["-y", "@three-ws/companion", "mcp"],+ "env": { "COMPANION_TOKEN": "cmp_…" }+ }+ }+}+```++Tools: `deliver_message` (walk on screen and say it out loud), `list_deliveries`+(what the human has heard recently), and `score_message` (ask how urgent+something would be judged before deciding to send it). An agent that finds+something genuinely urgent stops writing into a log nobody reads and becomes a+character standing in front of the person who needed to know.++Needs `@modelcontextprotocol/sdk` installed alongside this package.++---++## API++### `createCompanionClient(options)`++| Option | Default | Meaning |+|---|---|---|+| `apiBase` | `https://three.ws` | Where the API lives. |+| `token` | none | Bridge token. Omit in a signed-in first-party page. |+| `fetch` | platform | Override, for tests or a proxy. |+| `retryMs` | `3000` | Stream reconnect delay. |++Returns `{ send, list, markDelivered, dismiss, contacts, checkNow, stream }`.+Every method rejects with a `CompanionError` carrying `.status` and `.code`.++### `createCompanionStage(options)`++| Option | Default | Meaning |+|---|---|---|+| `client` | none | Needed for `.listen()`. |+| `apiBase` | `https://three.ws` | Origin for the 3D element and the voice lanes. |+| `corner` | `bottom-right` | Which corner it lives in. |+| `defaultAvatarUrl` | platform default | Body used when a sender has none. |+| `voice` | `true` | Speak the line as well as showing it. |+| `onOpen` | opens a tab | Handler for the delivery's Open button. |++Returns `{ deliver, listen, hide, destroy, element }`.++### `@three-ws/companion/triage`++`scoreByRules(event, contact?, { now })`, `decide(event, { contact, threshold, settings, now })`,+`inQuietHours(settings, now)`, `defaultLine(event, contact)`, `shorten(text, max)`,+`minutesUntil(when, now)`, `clampScore(n)`, `LANE_BASELINE`.++### `@three-ws/companion/config`++`resolveCredentials()`, `readConfig()`, `writeConfig(patch)`, `configPath()` -+the small 0600 JSON file the CLI and the desktop app share, so signing in once+signs in everything on that machine.++---++## Where the messages come from++You can send everything yourself, or connect a source at+[three.ws/companion](https://three.ws/companion) and let the platform poll it:++- **Telegram** - a bot you create with @BotFather, relaying the chats you add it to.+- **Calendar** - the private iCal URL Google, Apple, Outlook and CalDAV all publish.+- **Email** - IMAP with an app password, headers and a short preview only.+- **The bridge** - this package, an iOS Shortcut, an Android profile, a Mail rule, an Apps Script, a webhook.++Full recipes: [three.ws/docs/companion](https://three.ws/docs/companion).++## Related++- [`three.ws/companion`](https://three.ws/companion) - the control room: sources, contacts, threshold, quiet hours.+- [`@three-ws/walk`](https://www.npmjs.com/package/@three-ws/walk) - the walking avatar this uses as a body.+- [`apps/desktop`](https://github.com/nirholas/three.ws/tree/main/apps/desktop) - the companion that lives on your desktop.++## License++Apache-2.0diff --git a/packages/companion-sdk/package.json b/packages/companion-sdk/package.jsonnew file mode 100644index 000000000..9807be3b7--- /dev/null+++ b/packages/companion-sdk/package.json@@ -0,0 +1,66 @@+{+ "name": "@three-ws/companion",+ "version": "0.1.0",+ "description": "Give a person's notifications a body. A BYOK harness that triages what actually matters out of Telegram, a calendar, an inbox, or a phone, and hands it to a 3D character that says it out loud: browser client, Node client, a CLI, and an MCP server so any agent can interrupt a human in person.",+ "keywords": [+ "three.ws",+ "companion",+ "3d-avatar",+ "notifications",+ "triage",+ "assistant",+ "byok",+ "sse",+ "mcp",+ "desktop-pet"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws/companion",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/companion-sdk"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "private": true,+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "exports": {+ ".": "./src/index.js",+ "./triage": "./src/triage-rules.js",+ "./stage": "./src/stage.js",+ "./package.json": "./package.json",+ "./config": "./src/config.js",+ "./client": "./src/client.js"+ },+ "bin": {+ "companion": "./src/cli.mjs"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "engines": {+ "node": ">=18"+ },+ "scripts": {+ "test": "vitest run tests"+ },+ "peerDependencies": {+ "@modelcontextprotocol/sdk": ">=1.0.0",+ "imapflow": ">=1.0.0"+ },+ "peerDependenciesMeta": {+ "@modelcontextprotocol/sdk": {+ "optional": true+ },+ "imapflow": {+ "optional": true+ }+ }+}diff --git a/packages/companion-sdk/src/cli.mjs b/packages/companion-sdk/src/cli.mjsnew file mode 100755index 000000000..5c1e49ea0--- /dev/null+++ b/packages/companion-sdk/src/cli.mjs@@ -0,0 +1,464 @@+#!/usr/bin/env node+// companion - the command line for a person's 3D companion.+//+// companion login --token cmp_... store the bridge token on this machine+// companion send "Build finished" --from CI --priority high+// companion stream --say tail live deliveries, speak them on macOS+// companion watch-imap --host imap.gmail.com --user [email protected]+// companion mcp expose the companion to an agent over MCP+// companion doctor check the token, the API, and the lanes+//+// Design notes worth knowing:+//+// • `watch-imap` is the privacy mode. The mail password never leaves the+// machine: this process connects to the inbox locally, scores each message+// with the same rules the server uses (@three-ws/companion/triage), and+// posts only what clears the bar, with the body redacted if you ask. It+// needs `imapflow` installed alongside this package.+// • `mcp` turns "interrupt a human" into a tool any agent can call. An agent+// that finds something genuinely urgent can now walk on stage in a 3D body+// and say it, rather than writing into a log nobody reads.++import { createCompanionClient } from './client.js';+import { decide, scoreByRules } from './triage-rules.js';+import { resolveCredentials, writeConfig, configPath } from './config.js';+import { spawn } from 'node:child_process';++const HELP = `companion - your 3D companion, from the command line++Usage+ companion login --token <cmp_...> [--api <url>]+ companion send <title> [--body <text>] [--from <name>] [--id <handle>]+ [--app <name>] [--url <link>] [--priority high|normal|low]+ companion stream [--say] [--since <iso>] [--json]+ companion list [--limit 20] [--min <score>]+ companion check+ companion watch-imap --host <host> --user <address> [--pass <app password>]+ [--port 993] [--folder INBOX] [--interval 60]+ [--min <score>] [--redact]+ companion score <title> [--body <text>] [--from <name>] [--lane email]+ companion mcp+ companion doctor++Credentials+ Bridge token from https://three.ws/companion, in order of precedence:+ --token, $COMPANION_TOKEN, ${configPath()}++Every command exits non-zero on failure, so it composes in scripts and CI.`;++function parseArgs(argv) {+ const args = { _: [] };+ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i];+ if (arg.startsWith('--')) {+ const key = arg.slice(2);+ const next = argv[i + 1];+ if (next === undefined || next.startsWith('--')) args[key] = true;+ else {+ args[key] = next;+ i += 1;+ }+ } else args._.push(arg);+ }+ return args;+}++function die(message, code = 1) {+ process.stderr.write(`${message}\n`);+ process.exit(code);+}++function clientFrom(args) {+ const { token, apiBase } = resolveCredentials({ token: args.token, apiBase: args.api });+ if (!token) {+ die('No bridge token. Run `companion login --token cmp_...` (get one at https://three.ws/companion).');+ }+ return { client: createCompanionClient({ apiBase, token }), token, apiBase };+}++// macOS ships a real speech synthesiser; on other platforms the line is printed+// and nothing pretends to have spoken it.+function sayOnMac(text) {+ if (process.platform !== 'darwin') return false;+ try {+ spawn('say', [text], { stdio: 'ignore', detached: true }).unref();+ return true;+ } catch {+ return false;+ }+}++async function cmdLogin(args) {+ const token = args.token === true ? null : args.token;+ if (!token) die('Pass the token: companion login --token cmp_...');+ const apiBase = args.api && args.api !== true ? args.api : undefined;+ const client = createCompanionClient({ token, ...(apiBase ? { apiBase } : {}) });+ // Prove the token before storing it, so a typo fails here and not at 3am.+ const probe = await client.list({ limit: 1 }).catch((err) => {+ die(`That token was refused: ${err.message}`);+ });+ writeConfig({ token, ...(apiBase ? { apiBase } : {}), threshold: probe?.threshold ?? 60 });+ process.stdout.write(`Saved to ${configPath()}. Threshold is ${probe?.threshold ?? 60}.\n`);+}++async function cmdSend(args) {+ const title = args._[1];+ if (!title) die('What should it say? companion send "Build finished"');+ const { client } = clientFrom(args);+ const result = await client.send({+ title,+ ...(args.body && args.body !== true ? { body: args.body } : {}),+ ...(args.from && args.from !== true ? { sender: args.from } : {}),+ ...(args.id && args.id !== true ? { sender_id: args.id } : {}),+ ...(args.app && args.app !== true ? { app: args.app } : {}),+ ...(args.url && args.url !== true ? { url: args.url } : {}),+ ...(args.priority && args.priority !== true ? { priority: args.priority } : {}),+ });+ if (result.duplicate) {+ process.stdout.write('Already delivered that one.\n');+ return;+ }+ const event = result.event;+ process.stdout.write(+ `${event.delivered ? 'Delivered' : 'Stored (below your bar)'} · score ${event.importance}\n`+ + ` ${event.line}\n why: ${event.reason}\n`,+ );+}++async function cmdStream(args) {+ const { client } = clientFrom(args);+ const speak = Boolean(args.say);+ const asJson = Boolean(args.json);+ process.stderr.write('Listening for deliveries. Ctrl-C to stop.\n');+ const stop = client.stream({+ since: args.since && args.since !== true ? args.since : null,+ onOpen: (hello) => {+ if (!asJson) process.stderr.write(`Connected (threshold ${hello?.threshold ?? '?'}).\n`);+ },+ onDelivery: (delivery) => {+ if (asJson) {+ process.stdout.write(`${JSON.stringify(delivery)}\n`);+ } else {+ const when = new Date(delivery.created_at).toLocaleTimeString();+ process.stdout.write(`[${when}] ${delivery.speaker}: ${delivery.spoken_line}\n`);+ }+ if (speak) sayOnMac(delivery.spoken_line || delivery.title);+ client.markDelivered(delivery.id).catch(() => {});+ },+ onError: (err) => process.stderr.write(`stream: ${err.message}\n`),+ });+ process.on('SIGINT', () => {+ stop();+ process.exit(0);+ });+ // Hold the process open for the stream.+ await new Promise(() => {});+}++async function cmdList(args) {+ const { client } = clientFrom(args);+ const limit = Number(args.limit) || 20;+ const min = Number(args.min) || 0;+ const data = await client.list({ limit, minImportance: min });+ if (!data.events.length) {+ process.stdout.write('Nothing yet.\n');+ return;+ }+ for (const event of data.events) {+ const flag = event.delivered_at ? 'spoken' : 'held ';+ process.stdout.write(+ `${String(event.importance).padStart(3)} ${flag} ${new Date(event.created_at).toLocaleString()} `+ + `${event.contact_name || event.sender || 'unknown'}: ${event.spoken_line || event.title}\n`,+ );+ }+}++async function cmdCheck(args) {+ const { client } = clientFrom(args);+ const result = await client.checkNow();+ if (!result.sources.length) {+ process.stdout.write('No sources connected. Connect one at https://three.ws/companion\n');+ return;+ }+ for (const source of result.sources) {+ process.stdout.write(`${source.ok ? 'ok ' : 'FAIL'} ${source.kind.padEnd(9)} ${source.label} ${source.ok ? `${source.ingested} new` : source.error}\n`);+ }+}++async function cmdScore(args) {+ const title = args._[1];+ if (!title) die('companion score "Your verification code is 123456" --lane email');+ const verdict = scoreByRules({+ source_kind: args.lane && args.lane !== true ? args.lane : 'bridge',+ title,+ body: args.body && args.body !== true ? args.body : '',+ sender: args.from && args.from !== true ? args.from : undefined,+ sender_id: args.id && args.id !== true ? args.id : undefined,+ });+ process.stdout.write(`${verdict.importance}\n ${verdict.line}\n why: ${verdict.reason}\n signals: ${verdict.signals.join(', ') || 'none'}\n`);+}++// ── Local IMAP watcher (privacy mode) ────────────────────────────────────────++async function cmdWatchImap(args) {+ let ImapFlow;+ try {+ ({ ImapFlow } = await import('imapflow'));+ } catch {+ die('This command needs imapflow: npm install imapflow');+ }+ const host = args.host && args.host !== true ? args.host : null;+ const user = args.user && args.user !== true ? args.user : null;+ const pass = (args.pass && args.pass !== true ? args.pass : null) || process.env.COMPANION_IMAP_PASS;+ if (!host || !user || !pass) {+ die('Need --host, --user, and --pass (or $COMPANION_IMAP_PASS).');+ }+ const { client } = clientFrom(args);+ const { threshold } = resolveCredentials({ token: args.token, apiBase: args.api });+ const min = Number(args.min) || threshold || 60;+ const redact = Boolean(args.redact);+ const intervalMs = Math.max(15, Number(args.interval) || 60) * 1000;+ const folder = args.folder && args.folder !== true ? args.folder : 'INBOX';++ process.stderr.write(+ `Watching ${user} on ${host}${redact ? ' (bodies redacted)' : ''}.\n`+ + `Scoring locally; only messages at ${min} or above leave this machine.\n`,+ );++ let lastUid = 0;+ let validity = '';++ const pass_ = pass;+ async function tick() {+ const imap = new ImapFlow({+ host,+ port: Number(args.port) || 993,+ secure: args.insecure ? false : true,+ auth: { user, pass: pass_ },+ logger: false,+ });+ try {+ await imap.connect();+ const lock = await imap.getMailboxLock(folder, { readOnly: true });+ try {+ const currentValidity = String(imap.mailbox.uidValidity || '');+ if (!lastUid || (validity && validity !== currentValidity)) {+ lastUid = Math.max(0, (imap.mailbox.uidNext || 1) - 1);+ validity = currentValidity;+ return;+ }+ validity = currentValidity;+ for await (const message of imap.fetch({ uid: `${lastUid + 1}:*` }, { uid: true, envelope: true }, { uid: true })) {+ if (message.uid <= lastUid) continue;+ lastUid = Math.max(lastUid, message.uid);+ const from = message.envelope?.from?.[0] || {};+ const event = {+ source_kind: 'email',+ title: message.envelope?.subject || '(no subject)',+ sender: from.name || from.address || 'Email',+ sender_id: from.address || null,+ };+ const verdict = decide(event, { threshold: min });+ const mark = verdict.speak ? 'send' : 'keep';+ process.stdout.write(`${String(verdict.importance).padStart(3)} ${mark} ${event.sender}: ${event.title}\n`);+ if (!verdict.speak) continue;+ await client.send({+ title: event.title,+ sender: event.sender,+ sender_id: event.sender_id || undefined,+ app: 'Email',+ id: `local-imap:${validity}:${message.uid}`,+ body: redact ? undefined : verdict.line,+ priority: verdict.importance >= 80 ? 'high' : 'normal',+ }).catch((err) => process.stderr.write(`send failed: ${err.message}\n`));+ }+ } finally {+ lock.release();+ }+ } catch (err) {+ process.stderr.write(`imap: ${err.message}\n`);+ } finally {+ await imap.logout().catch(() => imap.close?.());+ }+ }++ await tick();+ setInterval(tick, intervalMs);+ await new Promise(() => {});+}++// ── MCP: let an agent interrupt a human, in person ───────────────────────────++async function cmdMcp(args) {+ let Server;+ let StdioServerTransport;+ let schemas;+ try {+ ({ Server } = await import('@modelcontextprotocol/sdk/server/index.js'));+ ({ StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js'));+ schemas = await import('@modelcontextprotocol/sdk/types.js');+ } catch {+ die('This command needs the MCP SDK: npm install @modelcontextprotocol/sdk');+ }+ const { client } = clientFrom(args);++ const server = new Server(+ { name: 'three-ws-companion', version: '0.1.0' },+ { capabilities: { tools: {} } },+ );++ const tools = [+ {+ name: 'deliver_message',+ description:+ 'Interrupt the human in person: a 3D companion walks on screen and says this out loud, on whatever device they are at. '+ + 'Use it only for something the person would genuinely want to be interrupted for; everything else is stored quietly. '+ + 'Returns the triage score, the reason, and whether it was actually spoken.',+ inputSchema: {+ type: 'object',+ properties: {+ title: { type: 'string', description: 'One line, what happened.' },+ body: { type: 'string', description: 'Optional detail.' },+ sender: { type: 'string', description: 'Who it is from, as the person would recognise them.' },+ url: { type: 'string', description: 'Optional link to open.' },+ priority: { type: 'string', enum: ['high', 'normal', 'low'] },+ },+ required: ['title'],+ },+ },+ {+ name: 'list_deliveries',+ description: 'What the companion has heard recently, with scores and whether each one was spoken.',+ inputSchema: {+ type: 'object',+ properties: {+ limit: { type: 'number', description: 'How many, 1 to 50.' },+ min_importance: { type: 'number', description: 'Only at or above this score.' },+ },+ },+ },+ {+ name: 'score_message',+ description: 'Ask, without sending anything, how urgent a message would be judged and what the companion would say.',+ inputSchema: {+ type: 'object',+ properties: {+ title: { type: 'string' },+ body: { type: 'string' },+ sender: { type: 'string' },+ lane: { type: 'string', description: 'telegram | email | calendar | bridge' },+ },+ required: ['title'],+ },+ },+ ];++ server.setRequestHandler(schemas.ListToolsRequestSchema, async () => ({ tools }));++ server.setRequestHandler(schemas.CallToolRequestSchema, async (request) => {+ const { name, arguments: input = {} } = request.params;+ try {+ if (name === 'deliver_message') {+ const result = await client.send({+ title: input.title,+ body: input.body,+ sender: input.sender || 'An agent',+ app: 'Agent',+ url: input.url,+ priority: input.priority || 'normal',+ });+ const event = result.event;+ return {+ content: [{+ type: 'text',+ text: result.duplicate+ ? 'Already delivered that exact message.'+ : `${event.delivered ? 'Spoken out loud' : 'Stored quietly (below the human\'s bar)'} · score ${event.importance}. Line: "${event.line}". Why: ${event.reason}`,+ }],+ };+ }+ if (name === 'list_deliveries') {+ const data = await client.list({+ limit: Math.min(50, Math.max(1, Number(input.limit) || 10)),+ minImportance: Number(input.min_importance) || 0,+ });+ return {+ content: [{+ type: 'text',+ text: data.events.length+ ? data.events.map((e) => `${e.importance} ${e.delivered_at ? '(spoken)' : '(held)'} ${e.contact_name || e.sender}: ${e.spoken_line || e.title}`).join('\n')+ : 'Nothing yet.',+ }],+ };+ }+ if (name === 'score_message') {+ const verdict = scoreByRules({+ source_kind: input.lane || 'bridge',+ title: input.title,+ body: input.body,+ sender: input.sender,+ });+ return {+ content: [{+ type: 'text',+ text: `score ${verdict.importance}\nline: ${verdict.line}\nwhy: ${verdict.reason}\nsignals: ${verdict.signals.join(', ') || 'none'}`,+ }],+ };+ }+ return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };+ } catch (err) {+ return { content: [{ type: 'text', text: `Failed: ${err.message}` }], isError: true };+ }+ });++ await server.connect(new StdioServerTransport());+}++async function cmdDoctor(args) {+ const { token, apiBase } = resolveCredentials({ token: args.token, apiBase: args.api });+ process.stdout.write(`config ${configPath()}\n`);+ process.stdout.write(`api ${apiBase}\n`);+ process.stdout.write(`token ${token ? `${token.slice(0, 8)}…${token.slice(-4)}` : 'MISSING'}\n`);+ if (!token) die('\nRun `companion login --token cmp_...` first. Get one at https://three.ws/companion');+ const client = createCompanionClient({ apiBase, token });+ try {+ const data = await client.list({ limit: 1 });+ process.stdout.write(`threshold ${data.threshold}\nreachable yes\n`);+ } catch (err) {+ die(`reachable no (${err.message})`);+ }+ try {+ const sources = await client.checkNow();+ for (const source of sources.sources) {+ process.stdout.write(`source ${source.kind.padEnd(9)} ${source.ok ? 'ok' : `error: ${source.error}`}\n`);+ }+ if (!sources.sources.length) process.stdout.write('source none connected\n');+ } catch (err) {+ process.stdout.write(`source could not check (${err.message})\n`);+ }+}++const COMMANDS = {+ login: cmdLogin,+ send: cmdSend,+ stream: cmdStream,+ list: cmdList,+ check: cmdCheck,+ score: cmdScore,+ 'watch-imap': cmdWatchImap,+ mcp: cmdMcp,+ doctor: cmdDoctor,+};++const args = parseArgs(process.argv.slice(2));+const command = args._[0];++if (!command || args.help || command === 'help') {+ process.stdout.write(`${HELP}\n`);+ process.exit(command ? 0 : 1);+}++const handler = COMMANDS[command];+if (!handler) die(`Unknown command: ${command}\n\n${HELP}`);++handler(args).catch((err) => die(`${err?.message || err}`));diff --git a/packages/companion-sdk/src/client.js b/packages/companion-sdk/src/client.jsnew file mode 100644index 000000000..f62844a7b--- /dev/null+++ b/packages/companion-sdk/src/client.js@@ -0,0 +1,264 @@+// The companion client: push a message in, listen for deliveries out.+//+// Isomorphic on purpose. In a browser it uses the platform `fetch` and+// `EventSource`; in Node 18+ it uses the built-in `fetch` and its own SSE+// reader over the response body (Node has no EventSource), so the same object+// works in a page, in an Electron renderer, in a CLI, and in a worker.+//+// import { createCompanionClient } from '@three-ws/companion';+//+// const companion = createCompanionClient({ token: process.env.COMPANION_TOKEN });+//+// await companion.send({ title: 'Build finished', sender: 'CI', priority: 'high' });+//+// const stop = companion.stream({+// onDelivery: (d) => console.log(`${d.speaker}: ${d.spoken_line}`),+// });+//+// The token is the bridge token from three.ws/companion. It can post messages+// and receive that user's deliveries, and rotating it on that page revokes+// every device at once. A browser page that already has a signed-in session can+// omit it entirely and pass `credentials: 'include'` behaviour by default.++const DEFAULT_API_BASE = 'https://three.ws';++class CompanionError extends Error {+ constructor(message, { status = 0, code = null } = {}) {+ super(message);+ this.name = 'CompanionError';+ this.status = status;+ this.code = code;+ }+}++export { CompanionError };++/**+ * @param {object} [options]+ * @param {string} [options.apiBase='https://three.ws'] where the API lives.+ * @param {string} [options.token] bridge token. Omit inside a signed-in page.+ * @param {typeof fetch} [options.fetch] override (tests, proxies, Electron).+ * @param {number} [options.retryMs=3000] reconnect delay for the stream.+ */+export function createCompanionClient({+ apiBase = DEFAULT_API_BASE,+ token = null,+ fetch: fetchImpl = null,+ retryMs = 3000,+} = {}) {+ const base = String(apiBase).replace(/\/+$/, '');+ const doFetch = fetchImpl || (typeof fetch === 'function' ? fetch.bind(globalThis) : null);+ if (!doFetch) {+ throw new CompanionError('no fetch implementation: pass one, or run on Node 18+ / a modern browser');+ }++ function headers(extra = {}) {+ return {+ accept: 'application/json',+ ...(token ? { authorization: `Bearer ${token}` } : {}),+ ...extra,+ };+ }++ async function call(path, { method = 'GET', body = null } = {}) {+ const res = await doFetch(`${base}${path}`, {+ method,+ credentials: token ? 'omit' : 'include',+ headers: headers(body ? { 'content-type': 'application/json' } : {}),+ ...(body ? { body: JSON.stringify(body) } : {}),+ });+ const text = await res.text();+ let data = null;+ if (text) {+ try {+ data = JSON.parse(text);+ } catch {+ data = null;+ }+ }+ if (!res.ok) {+ throw new CompanionError(data?.message || data?.error || `request failed (${res.status})`, {+ status: res.status,+ code: data?.code || null,+ });+ }+ return data;+ }++ return {+ /**+ * Hand the companion something to consider. Returns the triage verdict:+ * what it scored, why, the line it would say, and whether it spoke.+ *+ * @param {{ title:string, body?:string, sender?:string, sender_id?:string,+ * app?:string, url?:string, id?:string,+ * priority?:'high'|'normal'|'low', occurred_at?:string }} event+ */+ send(event) {+ if (!event?.title) throw new CompanionError('an event needs a title');+ return call('/api/companion/ingest', { method: 'POST', body: event });+ },++ /** Recent deliveries, newest first. */+ list({ limit = 30, before = null, minImportance = 0 } = {}) {+ const params = new URLSearchParams({ limit: String(limit) });+ if (before) params.set('before', before);+ if (minImportance) params.set('min_importance', String(minImportance));+ return call(`/api/companion/events?${params}`);+ },++ /** Say that a body has performed this one, so no other body repeats it. */+ markDelivered(id) {+ return call(`/api/companion/events/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body: { delivered: true },+ });+ },++ dismiss(id) {+ return call(`/api/companion/events/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body: { dismissed: true },+ });+ },++ /** The people this companion knows, with the body and voice each one uses. */+ contacts() {+ return call('/api/companion/contacts');+ },++ /** Poll every connected source right now. */+ checkNow() {+ return call('/api/companion/poll', { method: 'POST' });+ },++ /**+ * Subscribe to live deliveries. Returns a stop function.+ *+ * Reconnects on its own with the last delivery's timestamp, so a laptop+ * that slept wakes up and catches whatever it missed (bounded server side+ * to the last few hours, because a monologue is not a delivery).+ *+ * @param {object} handlers+ * @param {(delivery:object) => void} handlers.onDelivery+ * @param {(hello:object) => void} [handlers.onOpen]+ * @param {(err:Error) => void} [handlers.onError]+ */+ stream({ onDelivery, onOpen, onError, since = null } = {}) {+ if (typeof onDelivery !== 'function') throw new CompanionError('stream() needs an onDelivery handler');+ let stopped = false;+ let cleanup = () => {};+ let cursor = since;++ const useEventSource = !token && typeof EventSource === 'function';++ const connect = async () => {+ if (stopped) return;+ const url = `${base}/api/companion/stream${cursor ? `?since=${encodeURIComponent(cursor)}` : ''}`;++ if (useEventSource) {+ // Same-origin page with a session: the browser's own EventSource+ // handles reconnection and cookie auth for us.+ const source = new EventSource(url, { withCredentials: true });+ cleanup = () => source.close();+ source.addEventListener('hello', (e) => onOpen?.(safeParse(e.data)));+ source.addEventListener('delivery', (e) => {+ const delivery = safeParse(e.data);+ if (!delivery) return;+ cursor = delivery.created_at || cursor;+ onDelivery(delivery);+ });+ source.onerror = () => onError?.(new CompanionError('stream interrupted'));+ return;+ }++ // Token auth (desktop app, CLI, server): EventSource cannot send an+ // Authorization header, so the SSE frames are read off the body.+ const controller = new AbortController();+ cleanup = () => controller.abort();+ try {+ const res = await doFetch(url, { headers: headers({ accept: 'text/event-stream' }), signal: controller.signal });+ if (!res.ok || !res.body) {+ throw new CompanionError(`stream refused (${res.status})`, { status: res.status });+ }+ for await (const frame of readSse(res.body)) {+ if (stopped) break;+ if (frame.event === 'hello') onOpen?.(safeParse(frame.data));+ else if (frame.event === 'delivery') {+ const delivery = safeParse(frame.data);+ if (!delivery) continue;+ cursor = delivery.created_at || cursor;+ onDelivery(delivery);+ } else if (frame.event === 'warning') {+ onError?.(new CompanionError(safeParse(frame.data)?.message || 'stream warning'));+ }+ }+ } catch (err) {+ if (!stopped && err?.name !== 'AbortError') onError?.(err);+ }+ // The server retires a connection every few minutes on purpose;+ // coming straight back is the normal path, not an error path.+ if (!stopped) setTimeout(connect, retryMs);+ };++ connect();+ return () => {+ stopped = true;+ cleanup();+ };+ },+ };+}++function safeParse(raw) {+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++/**+ * Minimal Server-Sent Events reader over a fetch body stream. Yields+ * { event, data } per frame and ignores comments (heartbeats) and retry lines.+ * Exported for anyone writing their own transport on top of the stream.+ */+export async function* readSse(stream) {+ const decoder = new TextDecoder();+ let buffer = '';+ const reader = stream.getReader ? stream.getReader() : null;++ const chunks = reader+ ? (async function* () {+ while (true) {+ const { value, done } = await reader.read();+ if (done) return;+ yield value;+ }+ })()+ : stream; // Node streams are async-iterable already.++ for await (const chunk of chunks) {+ buffer += decoder.decode(chunk, { stream: true });+ let index = buffer.indexOf('\n\n');+ while (index !== -1) {+ const raw = buffer.slice(0, index);+ buffer = buffer.slice(index + 2);+ const frame = parseFrame(raw);+ if (frame) yield frame;+ index = buffer.indexOf('\n\n');+ }+ }+}++function parseFrame(raw) {+ let event = 'message';+ const data = [];+ for (const line of raw.split('\n')) {+ if (!line || line.startsWith(':')) continue;+ if (line.startsWith('event:')) event = line.slice(6).trim();+ else if (line.startsWith('data:')) data.push(line.slice(5).trim());+ }+ if (!data.length) return null;+ return { event, data: data.join('\n') };+}diff --git a/packages/companion-sdk/src/config.js b/packages/companion-sdk/src/config.jsnew file mode 100644index 000000000..9255743f2--- /dev/null+++ b/packages/companion-sdk/src/config.js@@ -0,0 +1,58 @@+// Where a machine keeps its companion credentials.+//+// One small JSON file per user account on the machine, so the CLI, the desktop+// companion (apps/desktop), and anything else built on this package all read+// the same token instead of each inventing their own env var. It is written+// with 0600 permissions because it holds a bearer token.+//+// Resolution order, most explicit first:+// 1. an argument passed in code,+// 2. COMPANION_TOKEN / THREEWS_COMPANION_TOKEN in the environment,+// 3. the config file below.++import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync } from 'node:fs';+import { homedir } from 'node:os';+import { join, dirname } from 'node:path';++export const DEFAULT_API_BASE = 'https://three.ws';++export function configPath() {+ if (process.env.COMPANION_CONFIG) return process.env.COMPANION_CONFIG;+ const base = process.env.XDG_CONFIG_HOME+ || (process.platform === 'darwin' ? join(homedir(), 'Library', 'Application Support') : join(homedir(), '.config'));+ return join(base, 'three-ws', 'companion.json');+}++export function readConfig() {+ const path = configPath();+ if (!existsSync(path)) return {};+ try {+ return JSON.parse(readFileSync(path, 'utf8')) || {};+ } catch {+ // A corrupted file must not brick the CLI: treat it as absent, and the+ // next `companion login` overwrites it cleanly.+ return {};+ }+}++export function writeConfig(patch) {+ const path = configPath();+ mkdirSync(dirname(path), { recursive: true });+ const next = { ...readConfig(), ...patch, updated_at: new Date().toISOString() };+ writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ try {+ chmodSync(path, 0o600);+ } catch {+ /* filesystems without POSIX modes (Windows) ignore this */+ }+ return next;+}++export function resolveCredentials({ token = null, apiBase = null } = {}) {+ const stored = readConfig();+ return {+ token: token || process.env.COMPANION_TOKEN || process.env.THREEWS_COMPANION_TOKEN || stored.token || null,+ apiBase: apiBase || process.env.COMPANION_API_BASE || stored.apiBase || DEFAULT_API_BASE,+ threshold: Number(process.env.COMPANION_THRESHOLD || stored.threshold || 60),+ };+}diff --git a/packages/companion-sdk/src/index.js b/packages/companion-sdk/src/index.jsnew file mode 100644index 000000000..c3008d96f--- /dev/null+++ b/packages/companion-sdk/src/index.js@@ -0,0 +1,41 @@+// @three-ws/companion - give a person's notifications a body.+//+// Three things live here, and they compose:+//+// 1. `createCompanionClient()` talks to the hosted companion: push a message+// in, listen for triaged deliveries out (SSE, reconnecting).+// 2. `scoreByRules()` / `decide()` make the same interrupt-or-not judgement+// the server makes, locally, with no key and no network. That is what lets+// a machine triage its own mail and send only the one line worth hearing.+// 3. `createCompanionStage()` puts a 3D body on a page and has it say the+// line out loud, in the sender's own avatar when they have one.+//+// Quick start (Node or browser):+//+// import { createCompanionClient } from '@three-ws/companion';+// const companion = createCompanionClient({ token: process.env.COMPANION_TOKEN });+// await companion.send({ title: 'Deploy finished', sender: 'CI', priority: 'high' });+//+// Quick start (a page that should show it):+//+// import { createCompanionClient, createCompanionStage } from '@three-ws/companion';+// createCompanionStage({ client: createCompanionClient({ token }) }).listen();+//+// The token comes from https://three.ws/companion. It is per person, it can be+// rotated there at any time, and it is the only credential any of this needs.++export { createCompanionClient, CompanionError, readSse } from './client.js';+export { createCompanionStage, holdMsFor } from './stage.js';+export {+ scoreByRules,+ defaultLine,+ decide,+ inQuietHours,+ shorten,+ minutesUntil,+ clampScore,+ LANE_BASELINE,+ DEFAULT_BASELINE,+} from './triage-rules.js';++export const VERSION = '0.1.0';diff --git a/packages/companion-sdk/src/stage.js b/packages/companion-sdk/src/stage.jsnew file mode 100644index 000000000..6a9a33ba1--- /dev/null+++ b/packages/companion-sdk/src/stage.js@@ -0,0 +1,246 @@+// A body for the companion, in any web page.+//+// import { createCompanionClient, createCompanionStage } from '@three-ws/companion';+//+// const client = createCompanionClient({ token });+// const stage = createCompanionStage({ client, corner: 'bottom-right' });+// stage.listen(); // deliveries now arrive in person, with a voice+//+// What it puts on the page: one <agent-3d> element (the published three.ws web+// component, loaded on demand from the same origin the API lives on) and one+// speech bubble. When a delivery arrives the stage swaps to whatever body that+// message should be delivered by (the sender's own avatar when the user gave+// them one), speaks the line, holds it long enough to read, and gets out.+//+// Everything degrades rather than disappears: a page with no WebGL still shows+// the bubble, a browser that blocks autoplay still shows the text, and a device+// with no hosted voice available falls back to the browser's own speech.++const STYLE_ID = 'three-ws-companion-stage-style';+const ELEMENT_SRC = '/agent-3d/latest/agent-3d.js';+const DEFAULT_AVATAR = '/avatars/michelle.glb';++const CSS = `+.twsc-stage{position:fixed;z-index:2147483000;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none;transition:opacity .35s ease,transform .35s ease;opacity:0;transform:translateY(12px)}+.twsc-stage[data-visible="1"]{opacity:1;transform:translateY(0)}+.twsc-stage[data-corner="bottom-right"]{right:18px;bottom:18px;align-items:flex-end}+.twsc-stage[data-corner="bottom-left"]{left:18px;bottom:18px;align-items:flex-start}+.twsc-stage[data-corner="top-right"]{right:18px;top:18px;align-items:flex-end}+.twsc-stage[data-corner="top-left"]{left:18px;top:18px;align-items:flex-start}+.twsc-bubble{pointer-events:auto;max-width:340px;background:rgba(18,18,20,.94);color:#f2f4f8;border:1px solid rgba(255,255,255,.14);border-radius:16px;padding:14px 16px;font:500 14px/1.5 Inter,system-ui,sans-serif;box-shadow:0 18px 50px rgba(0,0,0,.45);backdrop-filter:blur(10px)}+.twsc-who{font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:rgba(242,244,248,.55);margin-bottom:5px}+.twsc-actions{display:flex;gap:8px;margin-top:12px;flex-wrap:wrap}+.twsc-btn{pointer-events:auto;font:600 12px/1 Inter,system-ui,sans-serif;color:inherit;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);border-radius:8px;padding:7px 11px;cursor:pointer;transition:background .15s,border-color .15s}+.twsc-btn:hover{background:rgba(255,255,255,.14);border-color:rgba(255,255,255,.3)}+.twsc-btn:focus-visible{outline:2px solid #3b82f6;outline-offset:2px}+.twsc-body{pointer-events:auto;width:220px;height:280px;display:block}+@media (prefers-reduced-motion:reduce){.twsc-stage{transition:none}}+@media (prefers-color-scheme:light){.twsc-bubble{background:rgba(255,255,255,.96);color:#14161a;border-color:rgba(0,0,0,.1);box-shadow:0 18px 50px rgba(0,0,0,.18)}.twsc-who{color:rgba(20,22,26,.55)}.twsc-btn{background:rgba(0,0,0,.05);border-color:rgba(0,0,0,.12)}}+`;++function injectStyle(doc) {+ if (doc.getElementById(STYLE_ID)) return;+ const style = doc.createElement('style');+ style.id = STYLE_ID;+ style.textContent = CSS;+ doc.head.appendChild(style);+}++function loadElement(doc, apiBase) {+ if (customElements.get('agent-3d')) return Promise.resolve(true);+ const src = `${apiBase}${ELEMENT_SRC}`;+ if (!doc.querySelector(`script[src="${src}"]`)) {+ const script = doc.createElement('script');+ script.type = 'module';+ script.src = src;+ doc.head.appendChild(script);+ }+ return customElements.whenDefined('agent-3d').then(() => true).catch(() => false);+}++/** How long a line stays up, scaled to its length. */+export function holdMsFor(text, { base = 5200, perChar = 55, max = 14_000 } = {}) {+ return Math.min(max, base + String(text || '').length * perChar);+}++/**+ * @param {object} options+ * @param {object} [options.client] a createCompanionClient() instance, for listen().+ * @param {string} [options.apiBase='https://three.ws'] origin for the element and voice.+ * @param {'bottom-right'|'bottom-left'|'top-right'|'top-left'} [options.corner]+ * @param {string} [options.defaultAvatarUrl] body used when a sender has none.+ * @param {boolean} [options.voice=true] speak the line as well as showing it.+ * @param {Document} [options.document]+ * @param {(delivery:object) => void} [options.onOpen] clicked "Open".+ */+export function createCompanionStage({+ client = null,+ apiBase = 'https://three.ws',+ corner = 'bottom-right',+ defaultAvatarUrl = null,+ voice = true,+ document: doc = typeof document !== 'undefined' ? document : null,+ onOpen = null,+} = {}) {+ if (!doc) throw new Error('createCompanionStage needs a document (browser or Electron renderer)');+ const base = String(apiBase).replace(/\/+$/, '');++ injectStyle(doc);++ const root = doc.createElement('div');+ root.className = 'twsc-stage';+ root.dataset.corner = corner;+ root.setAttribute('role', 'status');+ root.setAttribute('aria-live', 'polite');++ const bubble = doc.createElement('div');+ bubble.className = 'twsc-bubble';+ bubble.hidden = true;++ const body = doc.createElement('agent-3d');+ body.className = 'twsc-body';+ body.setAttribute('background', 'transparent');+ body.setAttribute('src', defaultAvatarUrl || `${base}${DEFAULT_AVATAR}`);++ root.append(bubble, body);+ doc.body.appendChild(root);+ loadElement(doc, base);++ let audio = null;+ let hideTimer = null;+ let stopStream = null;+ const queue = [];+ let performing = false;++ function stopAudio() {+ if (audio) {+ audio.pause();+ audio.src = '';+ audio = null;+ }+ try {+ window.speechSynthesis?.cancel();+ } catch {+ /* no speech synthesis here */+ }+ }++ async function say(text, voiceId) {+ if (!voice) return 'muted';+ try {+ const res = await fetch(`${base}/api/tts/speak`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ text, voice: voiceId || 'alloy', format: 'mp3' }),+ });+ if (!res.ok) throw new Error(`tts ${res.status}`);+ const blob = await res.blob();+ if (!blob.size) throw new Error('empty clip');+ audio = new Audio(URL.createObjectURL(blob));+ await audio.play();+ return 'tts';+ } catch {+ try {+ if (!window.speechSynthesis) return 'silent';+ window.speechSynthesis.speak(new SpeechSynthesisUtterance(text));+ return 'browser';+ } catch {+ return 'silent';+ }+ }+ }++ function show(delivery) {+ const line = delivery.spoken_line || delivery.title || '';+ bubble.innerHTML = '';+ const who = doc.createElement('div');+ who.className = 'twsc-who';+ who.textContent = delivery.speaker || delivery.sender || 'Your companion';+ const text = doc.createElement('div');+ text.textContent = line;+ bubble.append(who, text);++ const actions = doc.createElement('div');+ actions.className = 'twsc-actions';+ if (delivery.url) {+ const open = doc.createElement('button');+ open.type = 'button';+ open.className = 'twsc-btn';+ open.textContent = 'Open';+ open.addEventListener('click', () => (onOpen ? onOpen(delivery) : window.open(delivery.url, '_blank', 'noopener')));+ actions.appendChild(open);+ }+ const dismiss = doc.createElement('button');+ dismiss.type = 'button';+ dismiss.className = 'twsc-btn';+ dismiss.textContent = 'Got it';+ dismiss.addEventListener('click', () => hide());+ actions.appendChild(dismiss);+ bubble.appendChild(actions);++ bubble.hidden = false;+ root.dataset.visible = '1';+ if (delivery.avatar_glb_url) body.setAttribute('src', delivery.avatar_glb_url);+ }++ function hide() {+ clearTimeout(hideTimer);+ stopAudio();+ root.dataset.visible = '0';+ hideTimer = setTimeout(() => {+ bubble.hidden = true;+ if (defaultAvatarUrl) body.setAttribute('src', defaultAvatarUrl);+ }, 400);+ }++ async function performNext() {+ if (performing) return;+ const delivery = queue.shift();+ if (!delivery) return;+ performing = true;+ show(delivery);+ const line = delivery.spoken_line || delivery.title || '';+ await say(line, delivery.voice);+ await new Promise((resolve) => {+ hideTimer = setTimeout(resolve, holdMsFor(line));+ });+ hide();+ performing = false;+ if (queue.length) setTimeout(performNext, 700);+ }++ return {+ element: root,++ /** Perform one delivery now (or queue it behind the current one). */+ deliver(delivery) {+ queue.push(delivery);+ performNext();+ return this;+ },++ /** Subscribe to the live stream and perform everything that arrives. */+ listen({ onError = null } = {}) {+ if (!client) throw new Error('createCompanionStage({ client }) is required to listen()');+ stopStream = client.stream({+ onDelivery: (delivery) => {+ this.deliver(delivery);+ client.markDelivered(delivery.id).catch(() => {});+ },+ onError,+ });+ return this;+ },++ hide,++ /** Remove the stage and stop everything it owns. */+ destroy() {+ stopStream?.();+ clearTimeout(hideTimer);+ stopAudio();+ root.remove();+ },+ };+}diff --git a/packages/companion-sdk/src/triage-rules.js b/packages/companion-sdk/src/triage-rules.jsnew file mode 100644index 000000000..d15ce6fdd--- /dev/null+++ b/packages/companion-sdk/src/triage-rules.js@@ -0,0 +1,193 @@+// The deterministic triage pass: is this worth interrupting a human for?+//+// This module is the single implementation of that judgement anywhere in the+// three.ws companion system. The server imports it (api/_lib/companion/+// triage.js) before it decides whether to speak; the CLI imports it to score+// messages on your own machine so a mail password never has to leave it; and+// anybody building their own body for the companion can import it to make the+// same call locally.+//+// It deliberately needs no model and no key. An LLM pass can refine the score+// and rewrite the line (that is what the hosted service does with your own+// Anthropic key when you have stored one), but everything here works offline,+// costs nothing, and is the floor the refinement is measured against.+//+// Scores are 0 to 100:+// 0-39 it can wait+// 40-69 worth a glance+// 70-100 interrupt the person now++const URGENT = /\b(urgent|asap|emergency|immediately|right now|deadline|overdue|final notice|action required|time sensitive)\b/i;+const PERSONAL = /\b(call me|text me|ring me|where are you|are you (there|around|free)|need you|help|i'?m outside|on my way|pick me up)\b/i;+const MONEY = /\b(payment|invoice|refund|charge|declined|fraud|unauthorized|wire|transfer|past due|receipt)\b/i;+const SECURITY = /\b(verification code|security code|one[- ]time|2fa|otp|password reset|sign[- ]?in attempt|suspicious login)\b/i;+const LOGISTICS = /\b(flight|gate|delayed|cancell?ed|reschedul|boarding|delivery|arriving|appointment)\b/i;+const BULK = /\b(unsubscribe|newsletter|promotion|sale ends|% off|limited time offer|no[- ]reply|noreply|marketing|webinar|survey)\b/i;+const UNATTENDED = /^(no[- ]?reply|do[- ]?not[- ]?reply|notifications?|updates?|info|newsletter)@/i;++/**+ * Where each lane starts before any signal is read. A calendar entry is on the+ * person's own calendar, so it opens higher than a stranger's email, which+ * opens near the floor.+ */+export const LANE_BASELINE = {+ telegram: 42,+ email: 30,+ calendar: 55,+ bridge: 45,+ sms: 45,+ slack: 38,+ discord: 34,+ webhook: 40,+};++export const DEFAULT_BASELINE = 40;++export function clampScore(n) {+ return Math.max(0, Math.min(100, Math.round(Number(n) || 0)));+}++/** Trim any message to something a person can hear in one breath. */+export function shorten(text, max = 220) {+ const flat = String(text || '').replace(/\s+/g, ' ').trim();+ if (flat.length <= max) return flat;+ const cut = flat.slice(0, max);+ const stop = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf(', '), cut.lastIndexOf(' '));+ return `${cut.slice(0, stop > 60 ? stop : max).trim()}…`;+}++export function minutesUntil(when, now = Date.now()) {+ if (!when) return null;+ const ts = when instanceof Date ? when.getTime() : Date.parse(when);+ if (Number.isNaN(ts)) return null;+ return (ts - now) / 60000;+}++/**+ * The line the companion says when no model rewrote it. Plain, specific, and+ * never longer than a sentence or two.+ *+ * @param {CompanionEvent} event+ * @param {CompanionContact|null} contact+ */+export function defaultLine(event, contact = null, now = Date.now()) {+ const who = contact?.display_name || event.sender || 'Someone';+ const body = shorten(event.body || event.title, 180);+ if (event.source_kind === 'calendar') {+ const mins = minutesUntil(event.occurs_at, now);+ const when = mins === null+ ? 'coming up'+ : mins <= 1+ ? 'starting now'+ : mins < 60+ ? `in ${Math.round(mins)} minutes`+ : `at ${new Date(event.occurs_at).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}`;+ return `Heads up, ${event.title} is ${when}.${event.body ? ` ${shorten(event.body, 120)}` : ''}`;+ }+ if (event.source_kind === 'email') return `${who} emailed you: ${event.title}. ${body}`;+ return `${who} says: ${body}`;+}++/**+ * Score one message.+ *+ * @typedef {object} CompanionEvent+ * @property {string} source_kind telegram | email | calendar | bridge | ...+ * @property {string} [sender] display name+ * @property {string} [sender_id] handle, address, or number+ * @property {string} title+ * @property {string} [body]+ * @property {string} [occurs_at] ISO, for things that start at a time+ * @property {'high'|'normal'|'low'} [priority_hint] what the sending device knew+ *+ * @typedef {object} CompanionContact+ * @property {string} display_name+ * @property {number} [priority_boost] -100 to 100+ *+ * @param {CompanionEvent} event+ * @param {CompanionContact|null} contact+ * @param {{ now?: number }} [opts]+ * @returns {{ importance:number, reason:string, line:string, signals:string[] }}+ */+export function scoreByRules(event, contact = null, { now = Date.now() } = {}) {+ const text = `${event.title || ''} ${event.body || ''}`;+ const signals = [];+ const reasons = [];+ let score = LANE_BASELINE[event.source_kind] ?? DEFAULT_BASELINE;++ const add = (points, signal, reason) => {+ score += points;+ signals.push(signal);+ reasons.push(reason);+ };++ if (contact) add(18 + (contact.priority_boost || 0), 'known_contact', `from ${contact.display_name}, a saved contact`);+ // A one-time code is the most perishable message a person receives: it is+ // worth interrupting for even from a sender nobody has ever saved, and it+ // expires while it sits unread. It is the single largest signal here on+ // purpose, enough to clear the default bar from the lowest lane baseline.+ if (SECURITY.test(text)) add(40, 'security_code', 'looks like a security or login code');+ if (URGENT.test(text)) add(22, 'urgent_language', 'says it is urgent');+ if (PERSONAL.test(text)) add(18, 'direct_request', 'asks you for something directly');+ if (MONEY.test(text)) add(14, 'money', 'concerns money or a payment');+ if (LOGISTICS.test(text)) add(12, 'logistics', 'affects travel or a delivery');+ if (/\?\s*$/.test((event.body || event.title || '').trim())) add(6, 'question', 'ends in a question');+ if (BULK.test(text)) add(-28, 'bulk', 'reads like a bulk or marketing message');+ if (UNATTENDED.test(event.sender_id || '')) add(-20, 'unattended_sender', 'sent from an unattended address');++ const mins = minutesUntil(event.occurs_at, now);+ if (event.source_kind === 'calendar' && mins !== null) {+ if (mins <= 5) add(32, 'starts_now', 'starts in minutes');+ else if (mins <= 15) add(24, 'starts_soon', 'starts within the quarter hour');+ else if (mins <= 60) add(12, 'starts_this_hour', 'starts within the hour');+ }++ if (event.priority_hint === 'high') add(20, 'device_high', 'the device marked it high priority');+ if (event.priority_hint === 'low') add(-20, 'device_low', 'the device marked it low priority');++ return {+ importance: clampScore(score),+ reason: reasons.length ? reasons.join('; ') : 'no urgency signals in the message',+ line: defaultLine(event, contact, now),+ signals,+ };+}++/**+ * Is it the middle of this person's night? Quiet hours are evaluated in their+ * own timezone, and a window that wraps midnight (22 to 7) is the normal case.+ *+ * @param {{ quiet_start:number|null, quiet_end:number|null, timezone?:string }} settings+ * @param {Date} [now]+ */+export function inQuietHours(settings, now = new Date()) {+ const start = settings?.quiet_start;+ const end = settings?.quiet_end;+ if (start === null || start === undefined || end === null || end === undefined) return false;+ let hour;+ try {+ hour = Number(new Intl.DateTimeFormat('en-US', {+ hour: 'numeric',+ hour12: false,+ timeZone: settings.timezone || 'UTC',+ }).format(now));+ } catch {+ hour = now.getUTCHours();+ }+ if (start === end) return true;+ return start < end ? hour >= start && hour < end : hour >= start || hour < end;+}++/**+ * The whole local decision in one call: score it, and say whether this person+ * would want to be interrupted right now.+ */+export function decide(event, { contact = null, threshold = 60, settings = null, now = Date.now() } = {}) {+ const verdict = scoreByRules(event, contact, { now });+ const quiet = settings ? inQuietHours(settings, new Date(now)) : false;+ return {+ ...verdict,+ quiet,+ speak: verdict.importance >= threshold && !quiet,+ };+}diff --git a/packages/companion-sdk/tests/client.test.js b/packages/companion-sdk/tests/client.test.jsnew file mode 100644index 000000000..1a9ad7aaa--- /dev/null+++ b/packages/companion-sdk/tests/client.test.js@@ -0,0 +1,110 @@+import { describe, it, expect, vi } from 'vitest';+import { createCompanionClient, readSse, CompanionError } from '../src/client.js';++function jsonResponse(body, { status = 200 } = {}) {+ return {+ ok: status >= 200 && status < 300,+ status,+ text: async () => JSON.stringify(body),+ };+}++function sseResponse(frames) {+ const encoder = new TextEncoder();+ const chunks = frames.map((frame) => encoder.encode(frame));+ let index = 0;+ return {+ ok: true,+ status: 200,+ body: {+ getReader: () => ({+ read: async () => (index < chunks.length+ ? { value: chunks[index++], done: false }+ : { value: undefined, done: true }),+ }),+ },+ };+}++describe('createCompanionClient', () => {+ it('sends a message with the bridge token as a bearer', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonResponse({ accepted: true, event: { importance: 88 } }));+ const client = createCompanionClient({ token: 'cmp_test', fetch: fetchImpl, apiBase: 'https://example.test' });+ const result = await client.send({ title: 'Build finished' });++ expect(result.event.importance).toBe(88);+ const [url, init] = fetchImpl.mock.calls[0];+ expect(url).toBe('https://example.test/api/companion/ingest');+ expect(init.headers.authorization).toBe('Bearer cmp_test');+ expect(JSON.parse(init.body)).toEqual({ title: 'Build finished' });+ });++ it('refuses an event with no title before it reaches the network', () => {+ const client = createCompanionClient({ token: 't', fetch: vi.fn() });+ expect(() => client.send({ body: 'no title' })).toThrow(CompanionError);+ });++ it('surfaces the server error message and status', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(+ jsonResponse({ code: 'unauthorized', message: 'unknown bridge token' }, { status: 401 }),+ );+ const client = createCompanionClient({ token: 'bad', fetch: fetchImpl });+ await expect(client.send({ title: 'hi' })).rejects.toMatchObject({+ status: 401,+ code: 'unauthorized',+ message: 'unknown bridge token',+ });+ });++ it('builds the list query from its options', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonResponse({ events: [] }));+ const client = createCompanionClient({ token: 't', fetch: fetchImpl, apiBase: 'https://example.test' });+ await client.list({ limit: 5, minImportance: 70 });+ expect(fetchImpl.mock.calls[0][0]).toBe('https://example.test/api/companion/events?limit=5&min_importance=70');+ });++ it('streams deliveries over a token-authenticated fetch', async () => {+ const frames = [+ 'event: hello\ndata: {"threshold":60}\n\n',+ 'event: delivery\ndata: {"id":"e1","spoken_line":"Sarah is at the door","created_at":"2026-08-28T12:00:00.000Z"}\n\n',+ ':hb\n\n',+ ];+ const fetchImpl = vi.fn().mockImplementation(async (url) => {+ if (String(url).includes('/api/companion/stream')) return sseResponse(frames);+ return jsonResponse({ ok: true });+ });+ const client = createCompanionClient({ token: 't', fetch: fetchImpl, retryMs: 10_000 });++ const seen = [];+ let opened = null;+ const stop = client.stream({+ onDelivery: (d) => seen.push(d),+ onOpen: (hello) => { opened = hello; },+ });+ await vi.waitFor(() => expect(seen).toHaveLength(1));+ stop();++ expect(opened).toEqual({ threshold: 60 });+ expect(seen[0].spoken_line).toBe('Sarah is at the door');+ expect(fetchImpl.mock.calls[0][1].headers.accept).toBe('text/event-stream');+ });+});++describe('readSse', () => {+ it('reassembles frames split across chunk boundaries', async () => {+ const encoder = new TextEncoder();+ const pieces = ['event: deliv', 'ery\ndata: {"id"', ':"e2"}\n\nevent: hello\ndata: {}\n\n'].map((p) => encoder.encode(p));+ let index = 0;+ const stream = {+ getReader: () => ({+ read: async () => (index < pieces.length ? { value: pieces[index++], done: false } : { done: true }),+ }),+ };+ const frames = [];+ for await (const frame of readSse(stream)) frames.push(frame);+ expect(frames).toEqual([+ { event: 'delivery', data: '{"id":"e2"}' },+ { event: 'hello', data: '{}' },+ ]);+ });+});diff --git a/packages/companion-sdk/tests/triage-rules.test.js b/packages/companion-sdk/tests/triage-rules.test.jsnew file mode 100644index 000000000..2245531be--- /dev/null+++ b/packages/companion-sdk/tests/triage-rules.test.js@@ -0,0 +1,94 @@+import { describe, it, expect } from 'vitest';+import { scoreByRules, decide, inQuietHours, shorten, LANE_BASELINE } from '../src/triage-rules.js';++const NOW = Date.parse('2026-08-28T12:00:00.000Z');+const inMinutes = (n) => new Date(NOW + n * 60_000).toISOString();++describe('scoreByRules', () => {+ it('reports which signals fired, not just a number', () => {+ const verdict = scoreByRules({+ source_kind: 'telegram',+ sender: 'Sarah',+ title: 'can you call me, it is urgent',+ });+ expect(verdict.signals).toContain('urgent_language');+ expect(verdict.signals).toContain('direct_request');+ expect(verdict.importance).toBeGreaterThan(LANE_BASELINE.telegram);+ });++ it('interrupts for a one-time code from an unknown sender', () => {+ const verdict = scoreByRules({+ source_kind: 'email',+ sender_id: '[email protected]',+ title: 'Your verification code is 220913',+ });+ expect(verdict.importance).toBeGreaterThanOrEqual(70);+ });++ it('keeps marketing below the floor even when it shouts', () => {+ const verdict = scoreByRules({+ source_kind: 'email',+ sender_id: '[email protected]',+ title: 'URGENT: limited time offer, sale ends tonight',+ body: 'Unsubscribe at any time.',+ });+ expect(verdict.importance).toBeLessThan(40);+ });++ it('gives an unknown lane the default baseline rather than NaN', () => {+ const verdict = scoreByRules({ source_kind: 'carrier-pigeon', title: 'hello' });+ expect(verdict.importance).toBe(40);+ });++ it('ranks a meeting by how close it is', () => {+ const soon = scoreByRules({ source_kind: 'calendar', title: 'Standup', occurs_at: inMinutes(3) }, null, { now: NOW });+ const hour = scoreByRules({ source_kind: 'calendar', title: 'Standup', occurs_at: inMinutes(45) }, null, { now: NOW });+ const tomorrow = scoreByRules({ source_kind: 'calendar', title: 'Standup', occurs_at: inMinutes(1500) }, null, { now: NOW });+ expect(soon.importance).toBeGreaterThan(hour.importance);+ expect(hour.importance).toBeGreaterThan(tomorrow.importance);+ });+});++describe('decide', () => {+ const settings = { quiet_start: 22, quiet_end: 7, timezone: 'UTC' };++ it('speaks when the score clears the threshold', () => {+ const verdict = decide({ source_kind: 'bridge', title: 'Sarah is at the door', priority_hint: 'high' }, { threshold: 60, now: NOW });+ expect(verdict.speak).toBe(true);+ expect(verdict.quiet).toBe(false);+ });++ it('stays silent during quiet hours no matter how loud the message is', () => {+ const verdict = decide(+ { source_kind: 'bridge', title: 'URGENT: emergency, call me now', priority_hint: 'high' },+ { threshold: 60, settings, now: Date.parse('2026-08-28T03:00:00.000Z') },+ );+ expect(verdict.importance).toBeGreaterThan(60);+ expect(verdict.quiet).toBe(true);+ expect(verdict.speak).toBe(false);+ });++ it('respects a raised bar', () => {+ const event = { source_kind: 'email', sender: 'A colleague', title: 'quick question about the deck' };+ expect(decide(event, { threshold: 20, now: NOW }).speak).toBe(true);+ expect(decide(event, { threshold: 90, now: NOW }).speak).toBe(false);+ });+});++describe('inQuietHours', () => {+ it('handles a window inside one day', () => {+ const settings = { quiet_start: 9, quiet_end: 17, timezone: 'UTC' };+ expect(inQuietHours(settings, new Date('2026-08-28T12:00:00Z'))).toBe(true);+ expect(inQuietHours(settings, new Date('2026-08-28T18:00:00Z'))).toBe(false);+ });++ it('treats an identical start and end as always quiet', () => {+ expect(inQuietHours({ quiet_start: 5, quiet_end: 5, timezone: 'UTC' }, new Date('2026-08-28T18:00:00Z'))).toBe(true);+ });+});++describe('shorten', () => {+ it('never returns more than the cap', () => {+ expect(shorten('a'.repeat(500), 100).length).toBeLessThanOrEqual(101);+ });+});diff --git a/src/feedback-companion.js b/src/feedback-companion.jsindex 8cb84e97d..600ac1fc8 100644--- a/src/feedback-companion.js+++ b/src/feedback-companion.js@@ -41,109 +41,45 @@ const DECLINED_KEY = '3dagent:feedback-declined';const OFFERED_KEY = '3dagent:feedback-offered';const STYLE_ID = 'walk-companion-feedback-style';-const MAX_ERRORS = 5;-const MAX_FAILURES = 5;// Long enough that the visitor still knows what they were doing, short enough// that the error they see offered is the one they just caused.const OFFER_WINDOW_MS = 20_000;// ── Context capture ─────────────────────────────────────────────────────────-// Installed once at module load so an error that happens before the companion-// finishes mounting is still captured. Two bounded ring buffers, no timers, no-// network: this costs nothing until something goes wrong.--const errors = [];-const failures = [];-const listeners = new Set();--function push(list, entry, max) {- if (!entry) return;- // Identical repeats are noise (a render loop can throw the same line a- // thousand times); count them instead of filling the buffer.- const last = list[list.length - 1];- if (last && last.text === entry) {- last.count += 1;- return;- }- list.push({ text: entry, count: 1, at: Date.now() });- if (list.length > max) list.shift();- for (const fn of listeners) {- try {- fn();- } catch {- /* a listener must never break capture */- }- }-}--function describeError(value) {- if (!value) return null;- if (value instanceof Error) {- const where = value.stack?.split('\n')[1]?.trim().replace(/^at\s+/, '');- return `${value.name}: ${value.message}${where ? ` (${where})` : ''}`;- }- const text = typeof value === 'string' ? value : String(value?.message || value);- return text && text !== '[object Object]' ? text : null;-}--function serialize(list) {- return list.map((e) => (e.count > 1 ? `${e.text} (x${e.count})` : e.text));-}--let captureInstalled = false;--function installCapture() {- if (captureInstalled || typeof window === 'undefined') return;- captureInstalled = true;+// The capture layer is @three-ws/witness (packages/witness), a standalone,+// framework-agnostic recorder published for any site to use. It keeps a bounded+// SEMANTIC trace: the sequence of intents plus the failures, with a stable+// selector synthesized for every element touched and no typed value ever held.+//+// That trace is the difference between a report and a reproduction. It compiles+// into a Playwright spec (GET /api/feedback/repro) that is red until the bug is+// fixed, so a sentence a visitor typed arrives as a runnable regression test.+//+// It starts at module load, before the companion finishes mounting, so a page+// that breaks during boot is still recorded.- window.addEventListener('error', (event) => {- // Resource errors (a 404 image) bubble here with no `error` object and are- // far less interesting than a real exception, so they are recorded by the- // file that failed rather than an empty message.- if (event.target && event.target !== window && event.target.tagName) {- const src = event.target.currentSrc || event.target.src || event.target.href;- if (src) push(failures, `failed to load ${new URL(src, location.href).pathname}`, MAX_FAILURES);- return;- }- const where = event.filename ? ` (${event.filename.split('/').pop()}:${event.lineno})` : '';- push(errors, `${describeError(event.error) || event.message}${where}`, MAX_ERRORS);- }, true);+import { witness } from '../packages/witness/src/index.js';+import { failuresIn, narrate } from '../packages/witness/src/compile.js';- window.addEventListener('unhandledrejection', (event) => {- push(errors, `Unhandled rejection: ${describeError(event.reason) || 'unknown'}`, MAX_ERRORS);- });+const recorder = witness.start({+ // Our own report endpoint is excluded: a failing report must never become+ // the next report's evidence.+ ignore: (path) => path.startsWith('/api/feedback/'),+});- // Wrap fetch to notice failed calls. The wrapper returns the original promise- // untouched in every path, so a bug here can never change what the page sees.- const nativeFetch = window.fetch;- if (typeof nativeFetch === 'function') {- window.fetch = function patchedFetch(input, init) {- const started = nativeFetch.apply(this, arguments);- try {- const method = (init?.method || input?.method || 'GET').toUpperCase();- const url = typeof input === 'string' ? input : input?.url || '';- const path = url ? new URL(url, location.href).pathname : '';- // Our own report endpoint is excluded: a failing report must not- // become the next report's evidence.- if (path && !path.startsWith('/api/feedback/')) {- started.then(- (res) => {- if (res && !res.ok) push(failures, `${method} ${path} -> ${res.status}`, MAX_FAILURES);- },- (err) => {- push(failures, `${method} ${path} -> ${describeError(err) || 'network error'}`, MAX_FAILURES);- },- );- }- } catch {- /* never let instrumentation break a request */- }- return started;- };- }+/** The failures the recorder saw, in the shape the report API already stores. */+export function capturedSignals() {+ const found = failuresIn(witness.trace());+ return {+ errors: [...found.errors].slice(-5),+ failures: [...found.network, ...found.resources].slice(-5),+ };}-installCapture();+/** The steps a person would read, straight from the same trace the spec compiles from. */+export function capturedSteps() {+ return narrate(witness.trace());+}// ── Environment facts ───────────────────────────────────────────────────────@@ -191,21 +127,21 @@ function writeFlag(key, value) {}async function collectContext() {+ const signals = capturedSignals();return {route: location.pathname + location.search,page_title: document.title || null,build_sha: await buildSha(),viewport: `${window.innerWidth}x${window.innerHeight}@${window.devicePixelRatio || 1}`,locale: navigator.language || null,- console_errors: serialize(errors),- failed_requests: serialize(failures),+ console_errors: signals.errors,+ failed_requests: signals.failures,+ // The whole recorded session. The server bounds every field again and the+ // compiler turns it into a runnable spec.+ trace: witness.trace(),};}-export function capturedSignals() {- return { errors: serialize(errors), failures: serialize(failures) };-}-// ── Transport ───────────────────────────────────────────────────────────────export async function sendReport(body, { transport = 'text' } = {}) {@@ -279,6 +215,12 @@ function ensureStyles() {.fb-note{margin:10px 0 0;font-size:12px;color:rgba(232,235,242,.55)}.fb-note[data-tone="error"]{color:#ff9b9b}.fb-note[data-tone="ok"]{color:#8fe0a8}+.fb-steps-toggle{background:none;border:none;padding:0;font:inherit;font-size:12px;color:#9fc0ff;cursor:pointer;text-decoration:underline;text-underline-offset:2px}+.fb-steps-toggle:hover{color:#c2d6ff}+.fb-steps-toggle:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px;border-radius:3px}+.fb-steps{margin:8px 0 0;padding:0 0 0 18px;max-height:132px;overflow-y:auto;font-size:11.5px;line-height:1.5;color:rgba(232,235,242,.62)}+.fb-steps li{margin:1px 0}+.fb-privacy{display:block;margin-top:8px;font-size:11px;color:rgba(232,235,242,.45)}.fb-done{padding:6px 0 2px;text-align:center}.fb-done p{margin:0 0 4px;font-size:14px}.fb-done small{color:rgba(232,235,242,.55)}@@ -286,6 +228,10 @@ function ensureStyles() {document.head.appendChild(style);}+function escapeHtml(value) {+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}+function speechRecognizer() {const Ctor = window.SpeechRecognition || window.webkitSpeechRecognition;if (!Ctor) return null;@@ -369,11 +315,27 @@ export function installFeedback({ getInstance, getHostEl } = {}) {if (!ctx) return;const signals = capturedSignals();const sha = await buildSha();+ const steps = capturedSteps();const bits = [`<b>Page</b> <code>${location.pathname}</code>`];if (sha) bits.push(`<b>Build</b> <code>${sha}</code>`);if (signals.errors.length) bits.push(`<b>${signals.errors.length}</b> console error${signals.errors.length > 1 ? 's' : ''}`);if (signals.failures.length) bits.push(`<b>${signals.failures.length}</b> failed request${signals.failures.length > 1 ? 's' : ''}`);- ctx.innerHTML = `Attached automatically: ${bits.join(' · ')}`;+ // Naming the step count is what makes the recorder feel like help rather+ // than surveillance: the visitor can see exactly how much was kept, and+ // open it to read every line before they send.+ const stepLine = steps.length+ ? `<button type="button" class="fb-steps-toggle" aria-expanded="false">${steps.length} recorded step${steps.length > 1 ? 's' : ''}</button>`+ : '';+ ctx.innerHTML = `Attached automatically: ${bits.join(' · ')}${stepLine ? ` · ${stepLine}` : ''}+ <ol class="fb-steps" hidden>${steps.map((line) => `<li>${escapeHtml(line)}</li>`).join('')}</ol>+ <span class="fb-privacy">Nothing you typed into a field is recorded, only how much.</span>`;+ const toggle = ctx.querySelector('.fb-steps-toggle');+ const listEl = ctx.querySelector('.fb-steps');+ toggle?.addEventListener('click', () => {+ const open = toggle.getAttribute('aria-expanded') === 'true';+ toggle.setAttribute('aria-expanded', String(!open));+ listEl.hidden = open;+ });}function stopDictation() {@@ -475,13 +437,17 @@ export function installFeedback({ getInstance, getHostEl } = {}) {sendBtn.textContent = 'Sending...';stopDictation();try {- await sendReport(body, { transport: micBtn?.dataset.wasUsed === '1' ? 'voice' : 'text' });+ const result = await sendReport(body, { transport: micBtn?.dataset.wasUsed === '1' ? 'voice' : 'text' });clearDraft();input.value = '';panel.querySelector('.fb-body').innerHTML = `<div class="fb-done"><p>Got it. That is on the list.</p>- <small>Every report is read by a person before anything changes.</small>+ <small>${+ result?.replayable+ ? 'Your steps came with it, so we can replay exactly what you hit.'+ : 'Every report is read by a person before anything changes.'+ }</small></div>`;const inst = resolveInst();@@ -573,8 +539,7 @@ export function installFeedback({ getInstance, getHostEl } = {}) {const route = location.pathname;if (readFlag(DECLINED_KEY).includes(route)) return;if (readFlag(OFFERED_KEY).includes(route)) return;- const fresh = [...errors, ...failures].some((e) => Date.now() - e.at < OFFER_WINDOW_MS);- if (!fresh) return;+ if (!witness.hasFailure({ withinMs: OFFER_WINDOW_MS })) return;const inst = resolveInst();if (!inst?.say) return;@@ -607,18 +572,18 @@ export function installFeedback({ getInstance, getHostEl } = {}) {if (!shown) writeFlag(OFFERED_KEY, readFlag(OFFERED_KEY).filter((r) => r !== route));}- const onSignal = () => {+ // The recorder tells us the moment a failure lands. Debounced, because a+ // burst of errors from one broken render is one thing to ask about.+ const unsubscribe = witness.onFailure(() => {clearTimeout(offerTimer);- // Debounced: a burst of errors from one broken render is one offer.offerTimer = setTimeout(maybeOffer, 1200);- };- listeners.add(onSignal);+ });return {open,close,uninstall() {- listeners.delete(onSignal);+ unsubscribe();clearInterval(hostWatch);clearTimeout(offerTimer);panel?.remove();diff --git a/tests/companion-calendar.test.js b/tests/companion-calendar.test.jsnew file mode 100644index 000000000..9a96ed982--- /dev/null+++ b/tests/companion-calendar.test.js@@ -0,0 +1,110 @@+// The calendar lane's announcement rules (api/_lib/companion/lanes/calendar.js).+//+// The lane fetches an ICS feed over the network, but the decision of WHAT to+// announce and WHEN is pure, so it is tested here against real iCalendar text:+// one-off events, a daily series, a cancelled entry, a moved instance, and the+// stable external id that stops the companion announcing the same standup twice.++import { describe, it, expect } from 'vitest';+import { eventsFromIcs, normalizeIcsUrl } from '../api/_lib/companion/lanes/calendar.js';++const NOW = Date.parse('2026-08-28T12:00:00.000Z');++function ics(...blocks) {+ return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//three.ws//companion tests//EN', ...blocks, 'END:VCALENDAR'].join('\n');+}++const soonEvent = [+ 'BEGIN:VEVENT',+ 'UID:design-review-1',+ 'DTSTAMP:20260828T100000Z',+ 'DTSTART:20260828T121500Z',+ 'DTEND:20260828T124500Z',+ 'SUMMARY:Design review',+ 'LOCATION:Studio',+ 'DESCRIPTION:Bring the deck',+ 'ORGANIZER;CN=Sarah:mailto:[email protected]',+ 'END:VEVENT',+].join('\n');++const laterEvent = [+ 'BEGIN:VEVENT',+ 'UID:tomorrow-1',+ 'DTSTAMP:20260828T100000Z',+ 'DTSTART:20260829T090000Z',+ 'DTEND:20260829T093000Z',+ 'SUMMARY:Not today',+ 'END:VEVENT',+].join('\n');++const cancelledEvent = [+ 'BEGIN:VEVENT',+ 'UID:cancelled-1',+ 'DTSTAMP:20260828T100000Z',+ 'DTSTART:20260828T122000Z',+ 'DTEND:20260828T125000Z',+ 'STATUS:CANCELLED',+ 'SUMMARY:Called off',+ 'END:VEVENT',+].join('\n');++const dailySeries = [+ 'BEGIN:VEVENT',+ 'UID:standup-1',+ 'DTSTAMP:20260801T100000Z',+ 'DTSTART:20260801T122500Z',+ 'DTEND:20260801T123500Z',+ 'RRULE:FREQ=DAILY;COUNT=200',+ 'SUMMARY:Standup',+ 'END:VEVENT',+].join('\n');++describe('eventsFromIcs', () => {+ it('announces what starts inside the window and nothing else', () => {+ const items = eventsFromIcs(ics(soonEvent, laterEvent), { now: NOW, lookaheadMinutes: 30 });+ expect(items.map((i) => i.title)).toEqual(['Design review']);+ const [item] = items;+ expect(item.occurs_at).toBe('2026-08-28T12:15:00.000Z');+ expect(item.sender).toBe('Sarah');+ expect(item.identity_candidates).toEqual(['Sarah']);+ expect(item.body).toContain('Location: Studio');+ expect(item.body).toContain('30 minutes');+ });++ it('skips a cancelled entry', () => {+ const items = eventsFromIcs(ics(cancelledEvent), { now: NOW, lookaheadMinutes: 60 });+ expect(items).toHaveLength(0);+ });++ it('expands a recurring series at today\'s occurrence, keeping the time of day', () => {+ const items = eventsFromIcs(ics(dailySeries), { now: NOW, lookaheadMinutes: 45 });+ expect(items).toHaveLength(1);+ expect(items[0].title).toBe('Standup');+ expect(items[0].occurs_at).toBe('2026-08-28T12:25:00.000Z');+ });++ it('gives every occurrence a stable id, so a re-poll never repeats one', () => {+ const first = eventsFromIcs(ics(dailySeries), { now: NOW, lookaheadMinutes: 45 });+ const second = eventsFromIcs(ics(dailySeries), { now: NOW + 60_000, lookaheadMinutes: 45 });+ expect(first[0].external_id).toBe(second[0].external_id);+ expect(first[0].external_id).toBe('cal:standup-1:2026-08-28T12:25:00.000Z');+ });++ it('still announces something that started seconds ago, but not minutes ago', () => {+ const justStarted = eventsFromIcs(ics(soonEvent), { now: Date.parse('2026-08-28T12:16:00.000Z'), lookaheadMinutes: 30 });+ const longGone = eventsFromIcs(ics(soonEvent), { now: Date.parse('2026-08-28T12:40:00.000Z'), lookaheadMinutes: 30 });+ expect(justStarted).toHaveLength(1);+ expect(longGone).toHaveLength(0);+ });++ it('reads an empty calendar without complaining', () => {+ expect(eventsFromIcs(ics(), { now: NOW })).toEqual([]);+ });+});++describe('normalizeIcsUrl', () => {+ it('turns the webcal scheme Apple hands out into a fetchable https URL', () => {+ expect(normalizeIcsUrl('webcal://p1.icloud.com/published/2/abc')).toBe('https://p1.icloud.com/published/2/abc');+ expect(normalizeIcsUrl(' https://calendar.google.com/basic.ics ')).toBe('https://calendar.google.com/basic.ics');+ });+});