Skip to content

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

feat(companion): let the companion read a checkout page before you pay on it

nirholasc8fc03c038cd
diff --git a/api/companion/checkout.js b/api/companion/checkout.js
new file mode 100644
index 000000000..c98d94e8a
--- /dev/null
+++ b/api/companion/checkout.js
@@ -0,0 +1,149 @@
+// POST /api/companion/checkout - read a payment screen and say what it costs.
+//
+// The caller is the checkout companion browser extension
+// (extensions/checkout-companion). It sends a REDACTED extract of a checkout
+// page and gets back a short list of plain findings plus one line for the
+// avatar to say out loud.
+//
+// What this endpoint deliberately is not:
+//
+// - It is not a store. Nothing about the page is written to the database.
+// A checkout page is the most sensitive screen a person visits, and the
+// safest place to put a record of one is nowhere. The response is computed
+// and forgotten; only the aggregate spend counter the LLM chain already
+// keeps survives the request.
+// - It is not a legal opinion. api/_lib/companion/checkout.js strips any
+// model output that renders one, and the arithmetic findings state a
+// difference between two numbers, never a judgment about it.
+// - It is not a blocker. It has no way to stop a payment and never claims to.
+// The person reads it and decides.
+//
+// Auth is a session OR the companion bridge token, matching /api/companion/
+// ingest. The bridge token exists because the extension can hold a credential
+// but cannot rely on a first-party cookie surviving in every browser it runs
+// in, and rotating that one token in the UI cuts off every device at once.
+//
+// Body: {
+// url: string (required) the checkout page, used for its host only
+// title: string (optional) the page title
+// text: string (required) visible page text, already redacted client-side
+// currency: string (optional) ISO code, defaults to USD
+// amounts: [{ value: integer minor units, role, context, currency }]
+// quoted: { value: integer minor units } | null what they were shown earlier
+// }
+
+import { z } from 'zod';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { getRequestUser } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { loadUserProviderKeys } from '../_lib/provider-keys.js';
+import { userForIngestToken } from '../_lib/companion/store.js';
+import { analyzeCheckout } from '../_lib/companion/checkout.js';
+import { llmComplete, llmConfigured } from '../_lib/llm.js';
+
+const AMOUNT_ROLES = [
+ 'total',
+ 'subtotal',
+ 'line',
+ 'fee',
+ 'surcharge',
+ 'handling',
+ 'processing',
+ 'service',
+ 'tax',
+ 'shipping',
+ 'discount',
+ 'unknown',
+];
+
+const amount = z.object({
+ // Integer minor units only. The content script parses "$49.99" next to the
+ // DOM node that gave it the currency; a float arriving here would mean the
+ // parse happened somewhere that could not know the currency's exponent.
+ value: z.number().int().min(-100_000_000).max(100_000_000),
+ currency: z.string().length(3).optional(),
+ role: z.enum(AMOUNT_ROLES).default('unknown'),
+ context: z.string().max(120).optional(),
+});
+
+const body = z.object({
+ url: z.string().url().max(2048),
+ title: z.string().max(300).optional(),
+ text: z.string().min(1).max(60_000),
+ currency: z.string().length(3).optional(),
+ amounts: z.array(amount).max(60).default([]),
+ quoted: z.object({ value: z.number().int(), currency: z.string().length(3).optional() }).nullable().optional(),
+});
+
+async function anthropicKeyFor(userId) {
+ try {
+ const [row] = await sql`select provider_keys from users where id = ${userId}`;
+ const keys = await loadUserProviderKeys(row?.provider_keys);
+ return keys.anthropic || null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Resolve the caller from a session or the companion bridge token.
+ * Returns the user row, or null when neither credential is present or valid.
+ */
+async function callerFor(req, res) {
+ const auth = req.headers.authorization || '';
+ const bearer = auth.startsWith('Bearer ') ? auth.slice(7).trim() : null;
+ if (bearer) {
+ const user = await userForIngestToken(bearer);
+ if (user) return user;
+ }
+ return getRequestUser(req, res);
+}
+
+export default wrap(async function handler(req, res) {
+ // The extension calls from its own origin, which is not a three.ws page, so
+ // the browser sends `Origin: chrome-extension://<id>` and this must answer
+ // it. `*` is right here precisely because the endpoint is credentialed by an
+ // Authorization header rather than a cookie for that caller, and it writes
+ // nothing: there is no state for a hostile page to change by calling it.
+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;
+ if (method(req, res, ['POST'])) return;
+
+ const user = await callerFor(req, res);
+ if (!user) {
+ return error(res, 401, 'unauthorized', 'sign in to three.ws or send your companion bridge token');
+ }
+
+ const limit = await limits.companionCheckout(user.id);
+ if (!limit.success) return rateLimited(res, limit);
+
+ const input = parse(body, await readJson(req));
+
+ const key = await anthropicKeyFor(user.id);
+ const configured = llmConfigured({ anthropicKey: key });
+
+ const result = await analyzeCheckout(input, {
+ // The reading pass is optional by construction. When no provider is
+ // reachable `analyzeCheckout` reports reading_status and still returns
+ // every arithmetic finding, so a page whose total is $12.50 above the
+ // quoted price is caught with no model in the loop at all.
+ complete: configured
+ ? async ({ system, user: prompt }) => {
+ const { text } = await llmComplete({
+ system,
+ user: prompt,
+ maxTokens: 700,
+ anthropicKey: key,
+ timeoutMs: 20_000,
+ track: { userId: user.id, tool: 'companion_checkout' },
+ });
+ return text;
+ }
+ : null,
+ });
+
+ // no-store: the response describes a payment screen. It has no business in
+ // a CDN, a proxy, or the browser's disk cache.
+ return json(res, 200, result, { 'cache-control': 'no-store' });
+});
diff --git a/docs/companion.md b/docs/companion.md
new file mode 100644
index 000000000..5c6c72599
--- /dev/null
+++ b/docs/companion.md
@@ -0,0 +1,335 @@
+# The Companion
+
+**A 3D character that tells you the things worth interrupting you for, in person.**
+
+Your phone buzzes forty times a day. Two of those mattered. Every notification
+system ever built has optimised the buzz; none of them has ever taken
+responsibility for the judgement. The Companion is the other half of the
+problem: it reads what comes in, decides what a person would actually want a tap
+on the shoulder for, and then a character walks over and says it out loud, in
+the body and the voice of whoever it came from.
+
+Set it up at **[three.ws/companion](https://three.ws/companion)**.
+
+- It runs on **your own keys**. A Telegram bot you created, an iCal URL you can
+ revoke, an app password scoped to mail, or nothing at all but a token your
+ phone posts to.
+- It has **a bar**, and you set it. Everything under the bar is kept in a feed
+ instead of being spoken. Quiet hours are absolute.
+- Anyone you give a face to **arrives in that face**. A message from Sarah is
+ delivered by Sarah's avatar, in the voice you picked for her.
+- It shows up **where you are**: on three.ws, as a push on your phone, and on
+ your desktop as a character that lives there.
+
+---
+
+## Five minutes to your first delivery
+
+1. Open [three.ws/companion](https://three.ws/companion) and copy your **bridge
+ token** from the "Phone and Mac" card.
+2. Press **Send a test**. A character appears and says it. That is the whole
+ delivery path, proven, before you connect anything real.
+3. Connect a source: paste a Telegram bot token, a calendar URL, or IMAP
+ details. Each one is verified against the real provider before it is saved,
+ so a typo fails in front of you instead of at 3am.
+4. Add a **contact**: the handle or address of someone who matters, a name, an
+ avatar, a voice. Now their messages arrive as them.
+5. Set your **threshold** and **quiet hours**.
+
+---
+
+## Where messages come from
+
+### The bridge (your phone, your Mac, anything that can POST)
+
+The universal lane. One endpoint, one token, no integration:
+
+```bash
+curl -X POST https://three.ws/api/companion/ingest \
+ -H "Authorization: Bearer cmp_YOUR_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{"title":"Sarah is at the door","sender":"Sarah","app":"Messages","priority":"high"}'
+```
+
+| Field | Required | Meaning |
+|---|---|---|
+| `title` | yes | One line: what happened. |
+| `body` | no | The longer text. |
+| `sender` | no | Display name, matched against your contacts. |
+| `sender_id` | no | Handle, address, or number. Matched first, and more precisely. |
+| `app` | no | Where it came from, e.g. `Messages`, `Slack`. |
+| `url` | no | Somewhere to open; becomes a button. |
+| `id` | no | Your own id, which makes retries idempotent. |
+| `priority` | no | `high` / `normal` / `low`: what the sending device already knew. |
+| `occurred_at` | no | ISO timestamp, if it is not "now". |
+
+Ready-made bridges live in
+[`docs/companion/bridges/`](https://github.com/nirholas/three.ws/tree/main/docs/companion/bridges):
+
+- **[`notify.sh`](https://github.com/nirholas/three.ws/blob/main/docs/companion/bridges/notify.sh)** -
+ one curl, no dependencies. Put it at the end of a build, a backup, a cron job:
+ `make release || ./notify.sh "Release build failed" --priority high`.
+- **[`gmail-apps-script.gs`](https://github.com/nirholas/three.ws/blob/main/docs/companion/bridges/gmail-apps-script.gs)** -
+ runs inside your own Google account on a 5-minute trigger. three.ws never sees
+ your mailbox or your credentials, and `REDACT_BODY = true` sends only sender
+ and subject.
+- **[`macos-mail-rule.applescript`](https://github.com/nirholas/three.ws/blob/main/docs/companion/bridges/macos-mail-rule.applescript)** -
+ an Apple Mail rule. Point it at a VIP sender, or at everything and let the
+ triage do the filtering.
+- **Android**: MacroDroid or Tasker have a real notification-listener trigger.
+ Trigger: *Notification Received*. Action: *HTTP Request* → POST the JSON above,
+ mapping the notification's app, title and text into `app`, `sender`, `title`.
+ That is the closest thing to full phone mirroring that exists without writing
+ an app.
+- **iOS**: Shortcuts automations (time of day, arriving somewhere, an app
+ opening, an NFC tag, a focus change) can post the same JSON with the *Get
+ Contents of URL* action, and a Share Sheet shortcut lets you forward anything
+ you are looking at by hand. iOS does not expose a general "any notification"
+ trigger to Shortcuts, so full mirroring needs the calendar and email lanes, or
+ a third-party forwarder app, rather than a Shortcut.
+- **Anything else**: Zapier, n8n, Make, a webhook from your own service. The
+ body above is the whole contract.
+
+### Telegram
+
+Create a bot with [@BotFather](https://t.me/BotFather) (`/newbot`), paste the
+token, then message that bot or add it to a group. Telegram gives no read access
+to a human account's chats and no OAuth for one, so a bot you own is the real
+supported path: it costs nothing, it can only see what you add it to, and
+revoking the token ends the connection with nothing to clean up.
+
+### Calendar
+
+Paste the private iCal URL your calendar already publishes:
+
+- **Google Calendar** → Settings for my calendars → *Secret address in iCal format*
+- **Apple / iCloud** → share the calendar → copy the `webcal://` link (pasted as-is; it is converted)
+- **Outlook / Microsoft 365** → *Publish a calendar* → ICS
+- Any CalDAV server, Fastmail, Proton, Zoho: all publish one.
+
+Events are announced as they approach, once each, inside a window you choose (10
+minutes to 2 hours). Recurring series are expanded correctly, cancelled entries
+are skipped, and a moved instance is announced at its new time.
+
+### Email
+
+IMAP with an **app password**, never your account password. Gmail, iCloud,
+Fastmail, Proton Bridge and Outlook all issue one per app and let you revoke it
+independently.
+
+- The mailbox is opened **read-only**: your unread state is never touched.
+- Only headers and a short text preview are read.
+- The first check records where the mailbox is *now*, so connecting an inbox with
+ 40,000 messages does not announce 40,000 of them.
+
+Prefer that your mail never leaves your machine at all? See
+[local privacy mode](#local-privacy-mode-triage-on-your-own-machine).
+
+---
+
+## How it decides
+
+Every message is scored 0 to 100. Two passes, and the first always runs:
+
+**1. The rules.** Deterministic, instant, no key, no cost. They read:
+
+| Signal | Effect |
+|---|---|
+| From a saved contact | +18, plus that contact's own priority (-100 to +100) |
+| Looks like a one-time code or a login alert | +40 (the most perishable message there is) |
+| Urgent language ("asap", "deadline", "final notice") | +22 |
+| Asks you directly ("call me", "I'm outside", "where are you") | +18 |
+| Money, invoices, declined payments, fraud | +14 |
+| Flights, deliveries, cancellations, appointments | +12 |
+| Ends in a question | +6 |
+| Reads like marketing, or came from `noreply@` | -28 / -20 |
+| A calendar event starting within 5 / 15 / 60 minutes | +32 / +24 / +12 |
+| Priority the sending device already assigned | ±20 |
+
+Each lane starts from a different baseline, because a calendar entry is on your
+own calendar and a stranger's email is not.
+
+**2. A language model, if one is available.** It can move the score and rewrite
+the spoken line into something a person would actually say. It runs on **your own
+Anthropic key** when you have stored one in your dashboard (BYOK), and on the
+platform's free lanes otherwise. If it is over quota, wrong, or absent, the
+deterministic verdict stands: nothing is ever lost to a model being unavailable.
+
+The message text is treated as untrusted data at every step. It is passed to the
+model inside a delimiter, the model is told it may not follow instructions found
+there, and only a number and two short strings are read back. Nothing a message
+says can make the companion do anything.
+
+Above your threshold and outside quiet hours, it is **spoken**. Below it, it is
+**kept**, with the score and the reason, in the feed on
+[/companion](https://three.ws/companion).
+
+---
+
+## Who gets a face
+
+A contact maps an identity (`@sarah`, `[email protected]`, `+14155550100`) to:
+
+- a **display name**, used instead of a raw handle,
+- an **avatar** (any of yours, or one you make from a selfie at
+ [/create-selfie](https://three.ws/create-selfie)),
+- a **voice** from the [Voice Lab](https://three.ws/voice) catalogue,
+- a **priority** that is added to every message from that person.
+
+Identities are normalised, so the same person resolves whether they wrote from
+Telegram, email, or your phone.
+
+When a contact's message is delivered, the walking companion **swaps into their
+body for the length of the message and swaps back afterwards**: your own
+companion stays yours, and the message still arrives as them.
+
+---
+
+## Where it shows up
+
+### On three.ws
+
+Any page. The corner companion turns to you, waves, and speaks
+(`src/notification-herald.js`). Muting it for a browser, or turning the whole
+category off account-wide, both live in
+[/dashboard/settings](https://three.ws/dashboard/settings) under **Companion
+deliveries**.
+
+### On your phone
+
+Web Push, from the same delivery. Turn it on from the settings card on
+[/companion](https://three.ws/companion). On iOS, add three.ws to your home
+screen first: that is what makes push available.
+
+### On your desktop
+
+[`apps/desktop`](https://github.com/nirholas/three.ws/tree/main/apps/desktop) is
+a small Electron app: a transparent, click-through, always-on-top character that
+strolls across the bottom of your screen, and walks over to deliver.
+
+```bash
+cd apps/desktop && npm install && npm start
+```
+
+It signs in with the same bridge token, holds no other credential, and is
+click-through everywhere except the character and its bubble.
+
+### Anywhere you write code
+
+```js
+import { createCompanionClient, createCompanionStage } from '@three-ws/companion';
+
+const client = createCompanionClient({ token: 'cmp_…' });
+createCompanionStage({ client }).listen();
+```
+
+Full SDK reference:
+[`packages/companion-sdk`](https://github.com/nirholas/three.ws/tree/main/packages/companion-sdk).
+
+---
+
+## Let an agent interrupt you
+
+An agent that finds something genuinely urgent should not write it into a log
+nobody reads. With the companion's MCP server it becomes a character standing in
+front of the person who needed to know:
+
+```jsonc
+{
+ "mcpServers": {
+ "companion": {
+ "command": "npx",
+ "args": ["-y", "@three-ws/companion", "mcp"],
+ "env": { "COMPANION_TOKEN": "cmp_…" }
+ }
+ }
+}
+```
+
+Tools: `deliver_message`, `list_deliveries`, `score_message`. The agent does not
+get to decide whether you are interrupted: its message goes through the same
+triage, the same threshold, and the same quiet hours as everything else.
+
+---
+
+## Local privacy mode: triage on your own machine
+
+```bash
+npm install -g @three-ws/companion imapflow
+companion login --token cmp_…
+companion watch-imap --host imap.fastmail.com --user [email protected] --redact
+```
+
+This connects to your inbox **locally**, scores every new message with exactly
+the rules above on your own hardware (`@three-ws/companion/triage` is the same
+module the server runs), and posts only what clears the bar, with the body
+redacted. The service never sees the mailbox, the password, or the messages that
+did not matter.
+
+---
+
+## The API
+
+Everything the page does, you can do. Session cookie or bridge token.
+
+| Endpoint | Method | What it does |
+|---|---|---|
+| `/api/companion/ingest` | POST | Hand it a message (bridge token). Returns the triage verdict. |
+| `/api/companion/stream` | GET | Live deliveries as Server-Sent Events. |
+| `/api/companion/events` | GET | The feed, with scores and reasons. |
+| `/api/companion/events/:id` | PATCH | Mark delivered or dismissed. |
+| `/api/companion/sources` | GET, POST | List or connect a source (verified before saving). |
+| `/api/companion/sources/:id` | PATCH, DELETE, POST | Rename, pause, disconnect, or check now. |
+| `/api/companion/contacts` | GET, POST | The people who get a face. |
+| `/api/companion/contacts/:id` | DELETE | Forget one. |
+| `/api/companion/settings` | GET, PATCH, POST | Threshold, quiet hours, default body and voice; POST rotates the bridge token. |
+| `/api/companion/poll` | POST | Poll every connected source now. |
+
+A delivery on the stream carries everything a body needs to perform it:
+
+```jsonc
+{
+ "id": "…",
+ "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",
+ "voice": "nova",
+ "source_kind": "telegram",
+ "created_at": "2026-08-28T12:04:11.221Z"
+}
+```
+
+---
+
+## What is stored, and what is not
+
+- **Credentials** (bot token, IMAP password, calendar URL) are encrypted with
+ AES-256-GCM before they touch the database, and the UI only ever shows you
+ enough to recognise which account is connected.
+- **Messages** are stored as the title, a short preview, the score, and the
+ reason, so the feed can explain itself. Email bodies are truncated to a
+ preview and never fetched in full.
+- **The bridge token** is the one credential a device needs. Rotating it at
+ [/companion](https://three.ws/companion) revokes every device at once.
+- Disconnecting a source **deletes its stored credential**.
+
+## Troubleshooting
+
+| What you see | What it means |
+|---|---|
+| A source says **needs attention** | The provider's own error is shown on the card: an expired bot token, an ICS URL that returns HTML, an IMAP login the server refused. Fix it and press **Check now**. |
+| Telegram connected, nothing arrives | The bot only sees what you add it to. Message the bot directly, or add it to the group, and press **Check now**. |
+| Calendar connected, nothing arrives | Events are only announced as they approach. Widen the lookahead, or wait for the next one. |
+| Everything is **held**, nothing spoken | Your threshold is above what those messages scored. The feed shows each score and reason; lower the bar, or give the sender a contact card with a priority. |
+| Nothing is spoken at night | That is quiet hours doing its job. |
+| The desktop app says **Not signed in** | Paste the bridge token in the tray menu, or run `companion login`. |
+| `companion doctor` | Prints the token in use, whether the API is reachable, and the health of every connected source. |
+
+## Related
+
+- [`packages/companion-sdk`](https://github.com/nirholas/three.ws/tree/main/packages/companion-sdk) - client, triage rules, CLI, MCP server.
+- [`apps/desktop`](https://github.com/nirholas/three.ws/tree/main/apps/desktop) - the desktop companion.
+- [Walk embed API](https://three.ws/docs/walk-embed-api) - the postMessage contract the bodies are driven with.
+- [Notifications](https://three.ws/notifications) - every delivery, and everything else, in one inbox.
diff --git a/docs/companion/bridges/gmail-apps-script.gs b/docs/companion/bridges/gmail-apps-script.gs
new file mode 100644
index 000000000..b10af8080
--- /dev/null
+++ b/docs/companion/bridges/gmail-apps-script.gs
@@ -0,0 +1,100 @@
+/**
+ * Gmail -> three.ws Companion
+ * ---------------------------
+ * Forwards new mail matching a search into your companion, which triages it and
+ * decides whether it is worth interrupting you for. Runs inside YOUR Google
+ * account, so three.ws never sees your mailbox or your credentials.
+ *
+ * Setup, about two minutes:
+ * 1. script.google.com -> New project -> paste this file.
+ * 2. Project Settings -> Script Properties, add:
+ * COMPANION_TOKEN your bridge token from https://three.ws/companion
+ * (Optional: COMPANION_URL to point at a different server, and
+ * COMPANION_QUERY to change what is watched.)
+ * 3. Run `forwardToCompanion` once and approve the permissions it asks for.
+ * 4. Triggers (the clock icon) -> Add Trigger -> forwardToCompanion,
+ * Time-driven, Minutes timer, every 5 minutes.
+ *
+ * What leaves your account: the sender, the subject, and the first 800
+ * characters of the body. Set REDACT_BODY to true below and only the sender and
+ * subject are sent.
+ */
+
+var DEFAULT_URL = 'https://three.ws/api/companion/ingest';
+var DEFAULT_QUERY = 'is:unread -category:promotions -category:social -category:updates newer_than:1d';
+var MAX_MESSAGES = 25;
+var REDACT_BODY = false;
+
+function forwardToCompanion() {
+ var props = PropertiesService.getScriptProperties();
+ var token = props.getProperty('COMPANION_TOKEN');
+ if (!token) throw new Error('Set COMPANION_TOKEN in Project Settings -> Script Properties.');
+
+ var endpoint = props.getProperty('COMPANION_URL') || DEFAULT_URL;
+ var query = props.getProperty('COMPANION_QUERY') || DEFAULT_QUERY;
+ // Everything already seen is remembered as a timestamp, so a message is
+ // forwarded exactly once even though the search keeps matching it.
+ var seenUntil = Number(props.getProperty('COMPANION_SEEN_UNTIL') || 0);
+ var newest = seenUntil;
+
+ var threads = GmailApp.search(query, 0, MAX_MESSAGES);
+ for (var t = 0; t < threads.length; t++) {
+ var messages = threads[t].getMessages();
+ for (var m = 0; m < messages.length; m++) {
+ var message = messages[m];
+ var stamp = message.getDate().getTime();
+ if (stamp <= seenUntil) continue;
+ newest = Math.max(newest, stamp);
+
+ var from = message.getFrom(); // "Sarah K <[email protected]>"
+ var address = (from.match(/<([^>]+)>/) || [null, from])[1];
+ var name = from.replace(/<[^>]*>/, '').replace(/"/g, '').trim() || address;
+
+ var payload = {
+ title: message.getSubject() || '(no subject)',
+ sender: name,
+ sender_id: address,
+ app: 'Gmail',
+ id: 'gmail:' + message.getId(),
+ occurred_at: message.getDate().toISOString(),
+ url: 'https://mail.google.com/mail/u/0/#inbox/' + threads[t].getId()
+ };
+ if (!REDACT_BODY) payload.body = String(message.getPlainBody() || '').slice(0, 800);
+
+ var response = UrlFetchApp.fetch(endpoint, {
+ method: 'post',
+ contentType: 'application/json',
+ headers: { Authorization: 'Bearer ' + token },
+ payload: JSON.stringify(payload),
+ muteHttpExceptions: true
+ });
+
+ if (response.getResponseCode() >= 400) {
+ // Logged rather than thrown: one rejected message must not stop the
+ // rest of the batch, and the trigger runs again in five minutes.
+ console.warn('companion rejected a message: ' + response.getResponseCode() + ' ' + response.getContentText());
+ }
+ }
+ }
+
+ props.setProperty('COMPANION_SEEN_UNTIL', String(newest));
+}
+
+/** Run once by hand to check the token and the endpoint. */
+function testCompanion() {
+ var props = PropertiesService.getScriptProperties();
+ var response = UrlFetchApp.fetch(props.getProperty('COMPANION_URL') || DEFAULT_URL, {
+ method: 'post',
+ contentType: 'application/json',
+ headers: { Authorization: 'Bearer ' + props.getProperty('COMPANION_TOKEN') },
+ payload: JSON.stringify({
+ title: 'Gmail bridge is connected',
+ body: 'This came from your own Apps Script project.',
+ sender: 'Gmail',
+ app: 'Gmail',
+ priority: 'high'
+ }),
+ muteHttpExceptions: true
+ });
+ console.log(response.getResponseCode() + ' ' + response.getContentText());
+}
diff --git a/docs/companion/bridges/macos-mail-rule.applescript b/docs/companion/bridges/macos-mail-rule.applescript
new file mode 100644
index 000000000..c732c3e0d
--- /dev/null
+++ b/docs/companion/bridges/macos-mail-rule.applescript
@@ -0,0 +1,110 @@
+(*
+ Apple Mail -> three.ws Companion
+ --------------------------------
+ A Mail rule that hands every message it matches to your companion, which
+ decides whether it is worth interrupting you for. Everything runs on your
+ Mac; the only thing that leaves it is the sender, the subject, and the
+ preview you allow below.
+
+ Setup:
+ 1. Save this file as ~/Library/Application Scripts/com.apple.mail/companion.scpt
+ (open it in Script Editor, then File -> Save, format "Script").
+ 2. Put your bridge token from https://three.ws/companion into the
+ `token` line below, or leave it empty to read it from
+ ~/.config/three-ws/companion.json, which `companion login` writes.
+ 3. Mail -> Settings -> Rules -> Add Rule.
+ Condition: whatever you actually want to hear about (a VIP sender, a
+ mailbox, "from anyone" if you trust the triage to filter for you).
+ Action: Run AppleScript -> companion.scpt.
+
+ The rule fires on incoming mail only, so nothing is replayed when you rebuild
+ your mailboxes.
+*)
+
+property endpoint : "https://three.ws/api/companion/ingest"
+property token : "" -- paste cmp_… here, or leave empty to read the CLI's config
+property previewCharacters : 400 -- set to 0 to send subject and sender only
+
+on companionToken()
+ if token is not "" then return token
+ try
+ set configPath to (POSIX path of (path to home folder)) & ".config/three-ws/companion.json"
+ set raw to do shell script "cat " & quoted form of configPath
+ -- The config is small and flat; pull the token without a JSON library.
+ set AppleScript's text item delimiters to "\"token\""
+ set tail to text item 2 of raw
+ set AppleScript's text item delimiters to "\""
+ set found to text item 2 of tail
+ set AppleScript's text item delimiters to ""
+ return found
+ on error
+ return ""
+ end try
+end companionToken
+
+-- JSON is quoted for a shell command, so both layers of escaping matter.
+on jsonEscape(theText)
+ set out to ""
+ repeat with i from 1 to count of characters of theText
+ set c to character i of theText
+ if c is "\"" then
+ set out to out & "\\\""
+ else if c is "\\" then
+ set out to out & "\\\\"
+ else if c is return or c is linefeed then
+ set out to out & "\\n"
+ else if c is tab then
+ set out to out & "\\t"
+ else
+ set out to out & c
+ end if
+ end repeat
+ return out
+end jsonEscape
+
+on truncate(theText, theLimit)
+ if theLimit is 0 then return ""
+ if (count of characters of theText) > theLimit then
+ return text 1 thru theLimit of theText
+ end if
+ return theText
+end truncate
+
+using terms from application "Mail"
+ on perform mail action with messages theMessages for rule theRule
+ set theToken to companionToken()
+ if theToken is "" then return
+
+ tell application "Mail"
+ repeat with eachMessage in theMessages
+ try
+ set theSubject to subject of eachMessage
+ set theSenderName to extract name from sender of eachMessage
+ set theSenderAddress to extract address from sender of eachMessage
+ set theId to message id of eachMessage
+ set theBody to ""
+ if previewCharacters > 0 then
+ set theBody to my truncate(content of eachMessage, previewCharacters)
+ end if
+
+ set payload to "{" & ¬
+ "\"title\":\"" & my jsonEscape(theSubject) & "\"," & ¬
+ "\"body\":\"" & my jsonEscape(theBody) & "\"," & ¬
+ "\"sender\":\"" & my jsonEscape(theSenderName) & "\"," & ¬
+ "\"sender_id\":\"" & my jsonEscape(theSenderAddress) & "\"," & ¬
+ "\"app\":\"Mail\"," & ¬
+ "\"id\":\"apple-mail:" & my jsonEscape(theId) & "\"" & ¬
+ "}"
+
+ do shell script "/usr/bin/curl -sS -m 10 -X POST " & quoted form of endpoint & ¬
+ " -H " & quoted form of ("Authorization: Bearer " & theToken) & ¬
+ " -H 'Content-Type: application/json'" & ¬
+ " --data-binary " & quoted form of payload & " >/dev/null"
+ on error errorMessage
+ -- One bad message must never stop the rule from handling the rest.
+ log "companion bridge: " & errorMessage
+ end try
+ end repeat
+ end tell
+ end perform mail action with messages
+end using terms from
diff --git a/docs/companion/bridges/notify.sh b/docs/companion/bridges/notify.sh
new file mode 100755
index 000000000..7359192e1
--- /dev/null
+++ b/docs/companion/bridges/notify.sh
@@ -0,0 +1,76 @@
+#!/usr/bin/env bash
+# notify.sh - hand anything on a machine to your three.ws companion.
+#
+# The smallest possible bridge: one curl, no dependencies, works on any Unix,
+# in CI, in a cron job, at the end of a long build, from a Raspberry Pi.
+#
+# ./notify.sh "Backup finished" "1.2 TB in 41 minutes"
+# ./notify.sh "Deploy failed" "$(tail -5 build.log)" --priority high
+# make release || ./notify.sh "Release build failed" --priority high
+#
+# Token, in order of precedence:
+# $COMPANION_TOKEN
+# ~/.config/three-ws/companion.json (written by `companion login`)
+#
+# Exit codes: 0 delivered or stored, 1 usage error, 2 rejected by the server.
+
+set -euo pipefail
+
+ENDPOINT="${COMPANION_API_BASE:-https://three.ws}/api/companion/ingest"
+CONFIG="${XDG_CONFIG_HOME:-$HOME/.config}/three-ws/companion.json"
+SENDER="${COMPANION_SENDER:-$(hostname)}"
+PRIORITY="normal"
+
+title="${1:-}"
+body="${2:-}"
+shift $(( $# > 2 ? 2 : $# )) || true
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --priority) PRIORITY="${2:-normal}"; shift 2 ;;
+ --from) SENDER="${2:-$SENDER}"; shift 2 ;;
+ --url) URL="${2:-}"; shift 2 ;;
+ *) shift ;;
+ esac
+done
+
+if [ -z "$title" ]; then
+ echo "usage: notify.sh <title> [body] [--priority high|normal|low] [--from name] [--url link]" >&2
+ exit 1
+fi
+
+token="${COMPANION_TOKEN:-}"
+if [ -z "$token" ] && [ -f "$CONFIG" ]; then
+ # Small, flat config; no jq dependency for something this simple.
+ token="$(sed -n 's/.*"token"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$CONFIG" | head -1)"
+fi
+
+if [ -z "$token" ]; then
+ echo "No bridge token. Set COMPANION_TOKEN, or run: npx @three-ws/companion login --token cmp_..." >&2
+ exit 1
+fi
+
+# JSON-escape without assuming python or jq is installed.
+escape() {
+ printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | awk 'BEGIN{ORS=""} {print (NR>1 ? "\\n" : "") $0}'
+}
+
+payload="{\"title\":\"$(escape "$title")\",\"sender\":\"$(escape "$SENDER")\",\"app\":\"shell\",\"priority\":\"$PRIORITY\""
+[ -n "$body" ] && payload="$payload,\"body\":\"$(escape "$body")\""
+[ -n "${URL:-}" ] && payload="$payload,\"url\":\"$(escape "$URL")\""
+payload="$payload}"
+
+response="$(curl -sS -m 15 -w '\n%{http_code}' -X POST "$ENDPOINT" \
+ -H "Authorization: Bearer $token" \
+ -H 'Content-Type: application/json' \
+ --data-binary "$payload")"
+
+status="$(printf '%s' "$response" | tail -1)"
+body_out="$(printf '%s' "$response" | sed '$d')"
+
+if [ "$status" -ge 400 ]; then
+ echo "companion rejected it ($status): $body_out" >&2
+ exit 2
+fi
+
+echo "$body_out"
diff --git a/tests/companion-checkout.test.js b/tests/companion-checkout.test.js
new file mode 100644
index 000000000..730da78ea
--- /dev/null
+++ b/tests/companion-checkout.test.js
@@ -0,0 +1,305 @@
+// The checkout companion's two guarantees, held to by test rather than by hope.
+//
+// 1. Nothing that identifies a person or their card leaves the browser.
+// 2. Every number in a finding was computed here, never read off a model.
+//
+// Both are properties of api/_lib/companion/checkout.js, which is pure, so they
+// are checkable without a network, a key, or a browser. A regression in either
+// is a privacy incident or a false accusation rendered over a real merchant's
+// payment page, which is why the money-math cases below are exact rather than
+// approximate.
+
+import { describe, it, expect } from 'vitest';
+import {
+ redactPageText,
+ deterministicFindings,
+ sanitizeModelFindings,
+ mergeFindings,
+ spokenSummary,
+ formatAmount,
+ analyzeCheckout,
+ buildAnalysisPrompt,
+} from '../api/_lib/companion/checkout.js';
+
+describe('redactPageText', () => {
+ it('removes a card number and keeps only the last four', () => {
+ // 4242 4242 4242 4242 is Stripe's documented test number and passes Luhn.
+ const out = redactPageText('Paying with 4242 4242 4242 4242 today');
+ expect(out.text).not.toContain('4242 4242 4242 4242');
+ expect(out.text).toContain('[card ending 4242]');
+ expect(out.counts.card).toBe(1);
+ });
+
+ it('leaves a long number that is not a card alone', () => {
+ // Order ids are exactly the context a finding needs, and they fail Luhn.
+ const out = redactPageText('Order 1234567890123456 confirmed');
+ expect(out.text).toContain('1234567890123456');
+ expect(out.counts.card).toBe(0);
+ });
+
+ it('removes emails, phones, security codes and bank accounts', () => {
+ const out = redactPageText(
+ 'Receipt to [email protected], call (415) 555-0132, CVV: 123, IBAN GB29 NWBK 6016 1331 9268 19',
+ );
+ expect(out.text).not.toContain('[email protected]');
+ expect(out.text).not.toContain('555-0132');
+ expect(out.text).not.toContain('123456');
+ expect(out.text).not.toMatch(/CVV: 123/);
+ expect(out.counts.email).toBe(1);
+ expect(out.counts.phone).toBe(1);
+ expect(out.counts.cvv).toBe(1);
+ expect(out.counts.iban).toBe(1);
+ expect(out.redactionCount).toBe(4);
+ });
+
+ it('reports zero redactions for an ordinary page', () => {
+ const out = redactPageText('Total $49.99. Ships in two days.');
+ expect(out.redactionCount).toBe(0);
+ expect(out.text).toBe('Total $49.99. Ships in two days.');
+ });
+});
+
+describe('deterministicFindings: the arithmetic', () => {
+ it('catches a total higher than the price the person was quoted', () => {
+ const findings = deterministicFindings({
+ currency: 'USD',
+ quoted: { value: 4999 },
+ amounts: [{ value: 6249, role: 'total' }],
+ text: '',
+ });
+ const hit = findings.find((f) => f.id === 'total_above_quoted');
+ expect(hit).toBeDefined();
+ expect(hit.amount).toBe(1250);
+ expect(hit.severity).toBe('flag');
+ expect(hit.detail).toContain('$12.50');
+ });
+
+ it('stays silent when the total matches what was quoted', () => {
+ const findings = deterministicFindings({
+ quoted: { value: 4999 },
+ amounts: [{ value: 4999, role: 'total' }],
+ text: '',
+ });
+ expect(findings.find((f) => f.id === 'total_above_quoted')).toBeUndefined();
+ });
+
+ it('flags money in the total that no line item explains', () => {
+ const findings = deterministicFindings({
+ amounts: [
+ { value: 4999, role: 'line' },
+ { value: 500, role: 'shipping' },
+ { value: 6249, role: 'total' },
+ ],
+ text: '',
+ });
+ const hit = findings.find((f) => f.id === 'unexplained_addition');
+ expect(hit.amount).toBe(750);
+ expect(hit.detail).toContain('$7.50');
+ });
+
+ it('treats a one-cent gap as rounding, not a dark pattern', () => {
+ const findings = deterministicFindings({
+ amounts: [
+ { value: 3333, role: 'line' },
+ { value: 3333, role: 'line' },
+ { value: 3333, role: 'line' },
+ { value: 10000, role: 'total' },
+ ],
+ text: '',
+ });
+ expect(findings.find((f) => f.id === 'unexplained_addition')).toBeUndefined();
+ });
+
+ it('names the fees and adds them up', () => {
+ const findings = deterministicFindings({
+ amounts: [
+ { value: 250, role: 'fee', context: 'Service fee' },
+ { value: 199, role: 'processing', context: 'Processing' },
+ ],
+ text: '',
+ });
+ const hit = findings.find((f) => f.id === 'fees_present');
+ expect(hit.amount).toBe(449);
+ expect(hit.detail).toContain('Service fee');
+ });
+
+ it('reports a discount as information rather than a warning', () => {
+ const findings = deterministicFindings({
+ amounts: [
+ { value: 5000, role: 'line' },
+ { value: 4000, role: 'total' },
+ ],
+ text: '',
+ });
+ const hit = findings.find((f) => f.id === 'total_below_lines');
+ expect(hit.severity).toBe('info');
+ });
+});
+
+describe('deterministicFindings: the language', () => {
+ it('flags a charge that repeats', () => {
+ const findings = deterministicFindings({
+ amounts: [],
+ text: 'Your plan auto-renews every month until cancelled.',
+ });
+ expect(findings.find((f) => f.id === 'recurring')).toBeDefined();
+ });
+
+ it('flags a trial that turns into a paid plan', () => {
+ const findings = deterministicFindings({
+ amounts: [],
+ text: 'Start your free trial. After the trial you will be billed.',
+ });
+ const hit = findings.find((f) => f.id === 'trial_converts');
+ expect(hit.severity).toBe('flag');
+ expect(hit.evidence).toContain('trial');
+ });
+
+ it('says nothing about an ordinary one-off purchase', () => {
+ const findings = deterministicFindings({
+ amounts: [{ value: 4999, role: 'total' }],
+ quoted: { value: 4999 },
+ text: 'One pair of running shoes. Ships in two days. Free returns.',
+ });
+ expect(findings).toEqual([]);
+ });
+});
+
+describe('sanitizeModelFindings: what the model is not allowed to say', () => {
+ it('drops a finding that calls the charge illegal', () => {
+ const out = sanitizeModelFindings({
+ findings: [
+ { severity: 'flag', title: 'This is illegal', detail: 'The merchant is breaking the law.' },
+ ],
+ });
+ expect(out).toEqual([]);
+ });
+
+ it('drops a finding that invents an amount', () => {
+ // Arithmetic is never the model's job; a number here is unverified.
+ const out = sanitizeModelFindings({
+ findings: [{ severity: 'flag', title: 'Hidden fee', detail: 'They add $12.50 at the end.' }],
+ });
+ expect(out).toEqual([]);
+ });
+
+ it('keeps a plain reading of a cancellation clause', () => {
+ const out = sanitizeModelFindings({
+ findings: [
+ {
+ severity: 'notice',
+ title: 'Cancelling needs 30 days of notice',
+ detail: 'The terms say the plan must be cancelled a full period before it renews.',
+ evidence: 'cancel at least 30 days before renewal',
+ },
+ ],
+ });
+ expect(out).toHaveLength(1);
+ expect(out[0].source).toBe('reading');
+ });
+
+ it('parses JSON out of a model reply wrapped in prose', () => {
+ const out = sanitizeModelFindings(
+ 'Here you go:\n{"findings":[{"severity":"info","title":"Ships from overseas","detail":"Delivery is quoted from an overseas warehouse."}]}\nHope that helps.',
+ );
+ expect(out).toHaveLength(1);
+ });
+
+ it('returns nothing for unparseable output instead of throwing', () => {
+ expect(sanitizeModelFindings('the model said no')).toEqual([]);
+ expect(sanitizeModelFindings({ findings: 'nope' })).toEqual([]);
+ });
+});
+
+describe('ordering and the spoken line', () => {
+ it('puts computed money above read prose at the same severity', () => {
+ const merged = mergeFindings(
+ [{ id: 'a', severity: 'flag', title: 'Total is higher', source: 'arithmetic' }],
+ [{ id: 'b', severity: 'flag', title: 'It repeats', source: 'reading' }],
+ );
+ expect(merged[0].source).toBe('arithmetic');
+ });
+
+ it('sorts a flag above a notice', () => {
+ const merged = mergeFindings(
+ [{ id: 'n', severity: 'notice', title: 'Refund policy', source: 'phrase' }],
+ [{ id: 'f', severity: 'flag', title: 'It repeats', source: 'reading' }],
+ );
+ expect(merged[0].severity).toBe('flag');
+ });
+
+ it('speaks the exact difference when there is one', () => {
+ const line = spokenSummary([
+ { severity: 'flag', source: 'arithmetic', id: 'total_above_quoted', amount: 1250, title: 'x' },
+ ]);
+ expect(line).toContain('$12.50');
+ });
+
+ it('stays quiet when nothing is worth interrupting for', () => {
+ expect(spokenSummary([{ severity: 'notice', title: 'Refund policy', source: 'phrase' }])).toBeNull();
+ expect(spokenSummary([])).toBeNull();
+ });
+});
+
+describe('formatAmount', () => {
+ it('renders minor units for a two-decimal currency', () => {
+ expect(formatAmount(1250, 'USD')).toBe('$12.50');
+ expect(formatAmount(5, 'USD')).toBe('$0.05');
+ expect(formatAmount(100000, 'EUR')).toBe('€1000.00');
+ });
+
+ it('renders a zero-decimal currency without cents', () => {
+ expect(formatAmount(1250, 'JPY')).toBe('¥1250');
+ });
+});
+
+describe('analyzeCheckout', () => {
+ const extract = {
+ url: 'https://shop.example/checkout',
+ title: 'Checkout',
+ currency: 'USD',
+ quoted: { value: 4999 },
+ amounts: [{ value: 6249, role: 'total' }],
+ text: 'Total due today. Your plan auto-renews every month. Card 4242 4242 4242 4242.',
+ };
+
+ it('redacts before the model ever sees the page', async () => {
+ let seen = null;
+ await analyzeCheckout(extract, {
+ complete: async ({ user }) => {
+ seen = user;
+ return '{"findings":[]}';
+ },
+ });
+ expect(seen).not.toContain('4242 4242 4242 4242');
+ expect(seen).toContain('[card ending 4242]');
+ });
+
+ it('still reports the arithmetic when the model is unreachable', async () => {
+ const out = await analyzeCheckout(extract, {
+ complete: async () => {
+ throw new Error('llm down');
+ },
+ });
+ expect(out.reading_status).toBe('unavailable');
+ expect(out.findings.find((f) => f.id === 'total_above_quoted')).toBeDefined();
+ expect(out.spoken).toContain('$12.50');
+ });
+
+ it('reports how many redactions it made', async () => {
+ const out = await analyzeCheckout(extract, { complete: null });
+ expect(out.redactions).toBe(1);
+ expect(out.redaction_counts.card).toBe(1);
+ expect(out.reading_status).toBe('skipped');
+ });
+
+ it('never puts the page URL path into the prompt, only the host', () => {
+ const prompt = buildAnalysisPrompt({
+ url: 'https://shop.example/checkout/order/[email protected]',
+ text: 'hello',
+ });
+ expect(prompt).toContain('shop.example');
+ expect(prompt).not.toContain('abc123');
+ expect(prompt).not.toContain('[email protected]');
+ });
+});