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.

docs(companion): document the checkout companion, and cover brownout and knock tools

nirholas8f3939f72f2d
diff --git a/docs/checkout-companion.md b/docs/checkout-companion.md
new file mode 100644
index 000000000..4123c7fc5
--- /dev/null
+++ b/docs/checkout-companion.md
@@ -0,0 +1,209 @@
+# Checkout companion
+
+Your agent reads the payment page before you pay.
+
+Checkout dark patterns are not hidden. They are unread. The fee added on the
+last step, the "free trial" that becomes an annual charge, the cancellation
+notice period buried in a terms block: all of it is rendered on the screen the
+person is looking at, and none of it gets read, because reading it is tedious
+and the button is right there. This is the one moment where an agent that can
+read a page faster than you is worth more than an agent that can do anything
+else.
+
+The [companion](./companion.md) already delivers messages in person. This is the
+same companion at the moment money moves.
+
+## What it reports
+
+On a checkout page, and only there, the panel says:
+
+| Finding | Example |
+| --- | --- |
+| The total is above the price you were shown | "You saw $49.99 earlier and this page charges $62.49, a difference of $12.50." |
+| Money the page did not itemise | "The listed amounts come to $54.99 but the total is $62.49. $7.50 is not itemised on this page." |
+| Fees, named and summed | "$4.49 of this is fees. Service fee: $2.50. Processing: $1.99." |
+| The charge repeats | Auto-renewal, "billed monthly", "per year" |
+| A trial converts | "Start your free trial. After the trial you will be billed." |
+| The price changes on renewal | Introductory rates, "first year only", "renews at" |
+| Conditions on cancelling | Notice periods, non-refundable terms |
+| Something may be pre-selected | "uncheck this box", "already added" |
+
+If any of those is a red flag the panel opens itself and optionally says one
+line out loud. Otherwise it stays one collapsed line. Most checkouts are
+ordinary and it is quiet on them.
+
+## The two passes, and why they are separate
+
+This is the load-bearing design decision, and every future change has to keep
+it. The analysis runs in two passes with a hard line between them:
+
+**Arithmetic is decided in code.** Whether the line items add up to the total is
+integer minor-unit maths in
+[`api/_lib/companion/checkout.js`](../api/_lib/companion/checkout.js). Every
+number in every finding was computed there. A language model never performs,
+corrects, or infers an amount.
+
+The reason is asymmetry of harm. A model that hallucinates a $12.50 fee onto a
+legitimate merchant's checkout is worse than no feature at all, and a model that
+misses a real one because it did mental arithmetic is the same failure wearing a
+different hat. Arithmetic is the part computers have been reliable at for
+seventy years; handing it to a probabilistic system is a choice nobody should
+make on a payment screen.
+
+**Prose is read by a model.** What a cancellation clause actually says is a
+reading task, and that is what models are good at. The model is given the
+redacted page text and returns findings with no amounts in them.
+
+Two guarantees enforce the line:
+
+- `SYSTEM_PROMPT` forbids arithmetic and legal verdicts.
+- `sanitizeModelFindings()` **drops** any finding containing a currency amount
+ or the words illegal, unlawful, non-compliant, fraudulent, scam, and their
+ family. A prompt is a request; a filter is a guarantee.
+
+A finding is dropped rather than softened, because softening leaves a mangled
+sentence on a payment screen with our avatar's face on it, while dropping loses
+one line from a list that is allowed to be empty.
+
+**When the model is unreachable the feature still works.** `reading_status`
+comes back `unavailable` and every arithmetic finding still stands. The
+highest-value finding in the whole product ("this total is $12.50 more than you
+were quoted") needs no model at all.
+
+## What it never does
+
+- **It never renders a legal verdict.** It does not say a charge is illegal,
+ non-compliant, fraudulent, or a scam. It says what the page says and where the
+ numbers disagree. We cannot know the former, the user cannot verify it, and a
+ false accusation over a legitimate merchant's checkout is a liability we would
+ deserve.
+- **It never blocks a payment.** It has no mechanism to and never claims to.
+- **It never advises whether to buy.** It reports; the person decides.
+
+## Privacy
+
+The extension **never reads an input**. Not the value, not the placeholder, not
+a `contenteditable`, not an iframe. `collectText()` and `collectAmounts()` in
+[`extract.js`](../extensions/checkout-companion/extract.js) refuse those nodes
+structurally rather than filtering their contents afterwards, because a filter
+is a list of the cases someone thought of. Card number, CVV, billing address and
+email all live in inputs, so none of them can be read, so none of them can be
+sent.
+
+Redaction then runs in the browser over the visible text anyway (a confirmation
+step that prints your card's last four is real), stripping Luhn-validated card
+numbers, IBANs, security codes, emails, phone numbers, government ids and long
+opaque tokens. The panel reports the redaction count so the claim is checkable.
+
+Only the **hostname** is sent, never the path or query string.
+
+**Nothing about the page is stored.** `POST /api/companion/checkout` writes no
+row. Findings are computed and returned in the same request. The one piece of
+cross-page memory is a single remembered amount per site, kept in the browser
+for one hour, capped at twenty sites, which is what makes the "total versus the
+price you were shown" comparison possible without any surveillance at all.
+
+Full disclosures:
+[PRIVACY.md](../extensions/checkout-companion/PRIVACY.md),
+[PERMISSIONS.md](../extensions/checkout-companion/PERMISSIONS.md).
+
+## API
+
+### `POST /api/companion/checkout`
+
+Auth: a three.ws session, or `Authorization: Bearer <companion bridge token>`
+(the same token as [`/api/companion/ingest`](./companion.md), rotatable from
+`/companion`). Rate limit: 40 per 10 minutes per account.
+
+Request:
+
+```json
+{
+ "url": "https://shop.example/checkout",
+ "title": "Checkout",
+ "currency": "USD",
+ "text": "Order summary. Subtotal $49.99. Service fee $7.50. Order total $62.49. Your plan auto-renews every month.",
+ "amounts": [
+ { "value": 4999, "role": "subtotal", "context": "Subtotal" },
+ { "value": 750, "role": "service", "context": "Service fee" },
+ { "value": 6249, "role": "total", "context": "Order total" }
+ ],
+ "quoted": { "value": 4999 }
+}
+```
+
+`value` is **integer minor units** (cents). The parse from `"$49.99"` to `4999`
+happens in the content script, next to the DOM node that supplied the currency;
+a float arriving here would mean the parse happened somewhere that could not
+know the currency's exponent. `role` is one of `total`, `subtotal`, `line`,
+`fee`, `surcharge`, `handling`, `processing`, `service`, `tax`, `shipping`,
+`discount`, `unknown`.
+
+Response:
+
+```json
+{
+ "findings": [
+ {
+ "id": "total_above_quoted",
+ "severity": "flag",
+ "title": "The total is higher than the price you were shown",
+ "detail": "You saw $49.99 earlier and this page charges $62.49, a difference of $12.50.",
+ "amount": 1250,
+ "currency": "USD",
+ "source": "arithmetic"
+ }
+ ],
+ "spoken": "Heads up: this total is $12.50 more than the price you were shown.",
+ "currency": "USD",
+ "reading_status": "ok",
+ "redactions": 0,
+ "redaction_counts": { "card": 0, "iban": 0, "email": 0, "phone": 0, "cvv": 0, "government_id": 0, "token": 0 }
+}
+```
+
+`severity` is `flag` (opens the panel), `notice`, or `info`. `source` is
+`arithmetic` (computed here), `phrase` (a pattern matched in the page text), or
+`reading` (a model read the prose). Findings sort by severity, then arithmetic
+before prose, because a number you can check against your own screen in two
+seconds beats a paraphrase.
+
+`reading_status` is `ok`, `unavailable` (no model reachable; arithmetic findings
+still returned), or `skipped` (no provider configured, or too little text).
+
+## Installing the extension
+
+Sources: [`extensions/checkout-companion/`](../extensions/checkout-companion).
+
+1. `chrome://extensions` → **Developer mode** → **Load unpacked** → select that
+ directory.
+2. Sign in to three.ws in the same browser, or paste a bridge token from
+ [`/companion`](https://three.ws/companion) into the options page.
+
+### Other browsers
+
+The sources are plain MV3 and load unmodified in Firefox
+(`about:debugging` → **Load Temporary Add-on**) and in Safari via
+`xcrun safari-web-extension-converter`.
+
+**On iOS specifically:** a Safari Web Extension is the only way this can exist.
+iOS has no equivalent of Android's `SYSTEM_ALERT_WINDOW`, so no App Store app
+can draw a floating panel over other apps, and there is no third-party API for
+reading another app's screen contents. An extension inside Safari can read the
+page Safari is showing, which covers web checkouts (where the subscription dark
+patterns overwhelmingly live) and nothing else. That boundary is a platform
+fact, not a roadmap item. See [iOS](./ios-app.md).
+
+## Tests
+
+- [`tests/companion-checkout.test.js`](../tests/companion-checkout.test.js):
+ redaction, the arithmetic, and what the model is not allowed to say.
+- [`tests/checkout-extract.test.js`](../tests/checkout-extract.test.js): money
+ parsing across locales, and the no-inputs rule held against a real DOM.
+
+## Related
+
+- [Companion](./companion.md): the message lanes and the avatar delivery channel
+- [Notifications](./notifications.md): the per-category channel matrix
+- [`extensions/walk-avatar/`](../extensions/walk-avatar): the same rig, walking
+ your avatar across any site
diff --git a/packages/brownout/test/brownout.test.js b/packages/brownout/test/brownout.test.js
new file mode 100644
index 000000000..59a0446ce
--- /dev/null
+++ b/packages/brownout/test/brownout.test.js
@@ -0,0 +1,147 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ parseProvenance,
+ isStale,
+ failedSources,
+ describeProvenance,
+ chaosDirective,
+ chaosHeaders,
+ withChaos,
+ chaosOutcome,
+ assertDegraded,
+ BrownoutAssertionError,
+} from '../src/index.js';
+
+const resWith = (headers, status = 200) => new Response('{}', { status, headers });
+
+const DEGRADED = {
+ 'x-brownout': 'v=1;tier=stale;sources=3;ok=1;failed=2;ms=512;degraded=1',
+ 'x-brownout-trace': 'birdeye;o=429;t=412, tokens-xyz;o=timeout;t=8000, dex;o=ok;t=88',
+ 'x-brownout-chaos-status': 'applied;faults=1',
+};
+
+test('parseProvenance reads the summary and the trace', () => {
+ const p = parseProvenance(resWith(DEGRADED));
+ assert.equal(p.tier, 'stale');
+ assert.equal(p.degraded, true);
+ assert.equal(p.ok, 1);
+ assert.equal(p.failed, 2);
+ assert.equal(p.ms, 512);
+ assert.deepEqual(p.trace[0], { name: 'birdeye', outcome: '429', ms: 412 });
+ assert.equal(p.trace.length, 3);
+});
+
+test('parseProvenance accepts a Response, a Headers, or a plain object', () => {
+ const fromHeaders = parseProvenance(new Headers(DEGRADED));
+ const fromObject = parseProvenance({ 'X-Brownout': DEGRADED['x-brownout'] });
+ assert.equal(fromHeaders.tier, 'stale');
+ assert.equal(fromObject.tier, 'stale');
+});
+
+test('parseProvenance returns null when no upstream was touched', () => {
+ assert.equal(parseProvenance(resWith({})), null);
+ assert.equal(parseProvenance(null), null);
+});
+
+test('parseProvenance refuses an unknown tier rather than passing it through', () => {
+ const p = parseProvenance(resWith({ 'x-brownout': 'v=1;tier=invented;ok=1' }));
+ assert.equal(p.tier, null);
+});
+
+test('isStale separates "caption this number" from "something failed over"', () => {
+ // degraded is true for both; only stale and fallback mean the number is old.
+ assert.equal(isStale(parseProvenance(resWith({ 'x-brownout': 'v=1;tier=stale;degraded=1' }))), true);
+ assert.equal(isStale(parseProvenance(resWith({ 'x-brownout': 'v=1;tier=fallback;degraded=1' }))), true);
+ assert.equal(isStale(parseProvenance(resWith({ 'x-brownout': 'v=1;tier=live;degraded=1' }))), false);
+ assert.equal(isStale(parseProvenance(resWith({ 'x-brownout': 'v=1;tier=cache' }))), false);
+ assert.equal(isStale(null), false);
+});
+
+test('failedSources lists only what did not answer, in order', () => {
+ const failed = failedSources(parseProvenance(resWith(DEGRADED)));
+ assert.deepEqual(failed.map((f) => f.name), ['birdeye', 'tokens-xyz']);
+});
+
+test('describeProvenance renders a log line', () => {
+ const line = describeProvenance(parseProvenance(resWith(DEGRADED)));
+ assert.match(line, /tier=stale/);
+ assert.match(line, /2 sources failed/);
+ assert.match(line, /birdeye\(429\)/);
+ assert.equal(describeProvenance(null), 'no upstream was touched');
+});
+
+test('chaosDirective renders the wire format', () => {
+ assert.equal(chaosDirective({ birdeye: 'http:429', dex: 'timeout' }), 'birdeye=http:429, dex=timeout');
+});
+
+test('chaosHeaders refuses to build a directive without a token', () => {
+ assert.throws(() => chaosHeaders({ birdeye: 'timeout' }, ''), /chaos token is required/);
+});
+
+test('withChaos injects the headers and preserves the caller\'s own', async () => {
+ let seen;
+ const fetchImpl = async (url, init) => {
+ seen = init.headers;
+ return resWith({});
+ };
+ const broken = withChaos({ birdeye: 'http:429' }, { token: 'tok', fetch: fetchImpl });
+ await broken('https://example.test/x', { headers: { accept: 'application/json' } });
+ assert.equal(seen.get('x-brownout-chaos'), 'birdeye=http:429');
+ assert.equal(seen.get('x-brownout-chaos-token'), 'tok');
+ assert.equal(seen.get('accept'), 'application/json');
+});
+
+test('chaosOutcome distinguishes applied from refused', () => {
+ assert.deepEqual(chaosOutcome(resWith({ 'x-brownout-chaos-status': 'applied;faults=2' })), {
+ applied: true,
+ reason: null,
+ faults: 2,
+ });
+ assert.deepEqual(chaosOutcome(resWith({ 'x-brownout-chaos-status': 'refused;reason=money_path' })), {
+ applied: false,
+ reason: 'money_path',
+ faults: 0,
+ });
+ assert.equal(chaosOutcome(resWith({})).applied, false);
+});
+
+test('assertDegraded passes a response that degraded as expected', () => {
+ const prov = assertDegraded(resWith(DEGRADED), {
+ status: 200,
+ tier: ['stale', 'fallback'],
+ degraded: true,
+ exercised: ['birdeye'],
+ });
+ assert.equal(prov.tier, 'stale');
+});
+
+test('assertDegraded refuses when the upstream under test never failed', () => {
+ // The single most important behaviour: a warm cache answered, nothing was
+ // tested, and a green assertion here would be worse than no test at all.
+ const warm = resWith({
+ 'x-brownout': 'v=1;tier=cache;sources=1;ok=1;failed=0',
+ 'x-brownout-chaos-status': 'applied;faults=1',
+ });
+ assert.throws(() => assertDegraded(warm, { exercised: ['birdeye'] }), BrownoutAssertionError);
+ assert.throws(() => assertDegraded(warm, { exercised: ['birdeye'] }), /never failed during this request/);
+});
+
+test('assertDegraded refuses when the server declined the directive', () => {
+ const refused = resWith({ 'x-brownout-chaos-status': 'refused;reason=bad_token', 'x-brownout': 'v=1;tier=live' });
+ assert.throws(() => assertDegraded(refused, { exercised: ['birdeye'] }), /did not apply the fault \(bad_token\)/);
+});
+
+test('assertDegraded matches a sub-scoped source from the provider name', () => {
+ const scoped = resWith({
+ 'x-brownout': 'v=1;tier=stale;ok=1;failed=1;degraded=1',
+ 'x-brownout-trace': 'birdeye:txs;o=429;t=1',
+ 'x-brownout-chaos-status': 'applied;faults=1',
+ });
+ assert.doesNotThrow(() => assertDegraded(scoped, { exercised: ['birdeye'] }));
+});
+
+test('assertDegraded reports a wrong status and a wrong tier', () => {
+ assert.throws(() => assertDegraded(resWith(DEGRADED, 200), { status: 503 }), /status 200, expected 503/);
+ assert.throws(() => assertDegraded(resWith(DEGRADED), { tier: 'live' }), /tier stale, expected live/);
+});
diff --git a/packages/knock-mcp/src/tools/act.js b/packages/knock-mcp/src/tools/act.js
new file mode 100644
index 000000000..9be4fb7aa
--- /dev/null
+++ b/packages/knock-mcp/src/tools/act.js
@@ -0,0 +1,34 @@
+// `knock_act` — answer, dismiss, or block one knock. Authenticated write.
+
+import { z } from 'zod';
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'knock_act',
+ title: 'Act on a knock',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Act on one knock in your own inbox: mark it read, dismiss it, or reply to it. A reply is delivered ' +
+ 'back through the receipt link the sender already holds, so answering never hands out your email or ' +
+ 'any other address. Set block to stop hearing from that sender: they are matched on the wallet that ' +
+ 'paid when there was one, and they see the same answer a shut door gives, so they cannot tell it was ' +
+ 'them. Acting on a knock also settles its companion delivery, so your avatar will not walk on later ' +
+ 'to announce something you have already dealt with. Requires THREE_WS_API_KEY.',
+ inputSchema: {
+ knock_id: z.string().min(1).describe('The knock id from knock_inbox.'),
+ status: z.enum(['read', 'replied', 'dismissed']).optional().describe('The new status. Use replied together with reply.'),
+ reply: z.string().max(2000).optional().describe('What to write back. The sender reads it through their receipt link.'),
+ block: z.boolean().optional().describe('Never hear from this sender again.'),
+ },
+ async handler({ knock_id: knockId, status, reply, block }) {
+ const body = {};
+ if (status) body.status = status;
+ if (reply) {
+ body.reply = reply;
+ body.status = status || 'replied';
+ }
+ if (block) body.block = true;
+ const data = await apiRequest(`/api/knock/inbox/${encodeURIComponent(knockId)}`, { method: 'PATCH', auth: true, body });
+ return { ok: true, knock: data.knock };
+ },
+};
diff --git a/packages/knock-mcp/src/tools/directory.js b/packages/knock-mcp/src/tools/directory.js
new file mode 100644
index 000000000..8c9c0dfb2
--- /dev/null
+++ b/packages/knock-mcp/src/tools/directory.js
@@ -0,0 +1,19 @@
+// `knock_directory` — everyone reachable right now. Read-only, no credential.
+
+import { z } from 'zod';
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'knock_directory',
+ title: 'Browse open doors',
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
+ description:
+ 'List every open, listed door on three.ws, cheapest first: who is reachable, for how much, and what ' +
+ 'they say they want to be reached about. This is how an agent discovers which humans it can pay to ' +
+ 'talk to. Costs nothing and needs no credential. Read-only.',
+ inputSchema: { limit: z.number().int().min(1).max(100).optional().describe('How many doors to return. Default 60.') },
+ async handler({ limit }) {
+ const data = await apiRequest('/api/knock/directory', { query: { limit } });
+ return { ok: true, count: data.count, doors: data.doors };
+ },
+};
diff --git a/packages/knock-mcp/src/tools/inbox.js b/packages/knock-mcp/src/tools/inbox.js
new file mode 100644
index 000000000..9843d6840
--- /dev/null
+++ b/packages/knock-mcp/src/tools/inbox.js
@@ -0,0 +1,24 @@
+// `knock_inbox` — the knocks YOUR door has taken. Authenticated, read-only.
+
+import { z } from 'zod';
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'knock_inbox',
+ title: 'Read your knocks',
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Read the knocks your own door has taken, newest first, each with what the sender paid for it. Use ' +
+ 'this to triage: the amount is the sender\'s own statement of how much reaching you was worth. Also ' +
+ 'returns totals (waiting, all time, earned). Requires THREE_WS_API_KEY for the account that owns the ' +
+ 'door; it can never read anyone else\'s. Read-only.',
+ inputSchema: {
+ limit: z.number().int().min(1).max(50).optional().describe('Page size. Default 30.'),
+ status: z.enum(['pending', 'read', 'replied', 'dismissed']).optional().describe('Filter to one status.'),
+ before: z.string().optional().describe('ISO timestamp cursor for paging.'),
+ },
+ async handler({ limit, status, before }) {
+ const data = await apiRequest('/api/knock/inbox', { auth: true, query: { limit, status, before } });
+ return { ok: true, totals: data.totals, has_more: data.has_more, knocks: data.knocks };
+ },
+};
diff --git a/packages/knock-mcp/src/tools/quote.js b/packages/knock-mcp/src/tools/quote.js
new file mode 100644
index 000000000..172222e87
--- /dev/null
+++ b/packages/knock-mcp/src/tools/quote.js
@@ -0,0 +1,21 @@
+// `knock_quote` — what it costs to reach one person. Read-only, no credential.
+
+import { z } from 'zod';
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'knock_quote',
+ title: 'Quote a door',
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Read one person\'s public door on three.ws: the price of a single message to them, which chains ' +
+ 'they take it on, how long the message may be, what they say they want to hear about, and the exact ' +
+ 'endpoint to use. Costs nothing and needs no credential. ALWAYS call this before knock_send on a ' +
+ 'priced door: the owner can change their price at any time, and the quote you show a human before ' +
+ 'they approve a payment must be the live one. Read-only.',
+ inputSchema: { handle: z.string().min(1).max(40).describe('The recipient\'s three.ws username, with or without the @.') },
+ async handler({ handle }) {
+ const data = await apiRequest('/api/knock/door', { query: { handle: String(handle).replace(/^@+/, '') } });
+ return { ok: true, door: data.door };
+ },
+};
diff --git a/packages/knock-mcp/src/tools/receipt.js b/packages/knock-mcp/src/tools/receipt.js
new file mode 100644
index 000000000..5260b6f4c
--- /dev/null
+++ b/packages/knock-mcp/src/tools/receipt.js
@@ -0,0 +1,20 @@
+// `knock_receipt` — what became of a knock you sent. Read-only, no credential.
+
+import { z } from 'zod';
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'knock_receipt',
+ title: 'Read a knock receipt',
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Read the state of a knock you sent, using the receipt_url it returned. Statuses: pending (not opened), ' +
+ 'read (opened, no answer written), replied (they wrote back, and the reply is included), dismissed ' +
+ '(read and closed). The receipt carries its own proof, so this needs no account and reveals nothing ' +
+ 'about the recipient beyond the reply they chose to write. Read-only.',
+ inputSchema: { receipt_url: z.string().min(10).describe('The receipt_url a knock returned.') },
+ async handler({ receipt_url: receiptUrl }) {
+ const data = await apiRequest(String(receiptUrl));
+ return { ok: true, knock: data.knock };
+ },
+};
diff --git a/packages/knock-mcp/src/tools/send.js b/packages/knock-mcp/src/tools/send.js
new file mode 100644
index 000000000..b783dad35
--- /dev/null
+++ b/packages/knock-mcp/src/tools/send.js
@@ -0,0 +1,75 @@
+// `knock_send` — get one message through to a person.
+//
+// This tool deliberately CANNOT spend. A free door is sent immediately, because
+// nothing moves. A priced door returns the exact recipient, amount, token and
+// chain, plus the endpoint, and stops: paying is an act that belongs to the
+// wallet the human controls, not to an MCP server holding a key in an env var.
+// The agent shows those facts, the human approves, and the payment happens in
+// their own x402 client (@three-ws/knock, or any other).
+
+import { z } from 'zod';
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'knock_send',
+ title: 'Knock on a door',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Send exactly one message to a person through their three.ws door. The message lands in their inbox ' +
+ 'AND their 3D companion walks on screen wherever they are on the site and delivers it out loud, ' +
+ 'naming you and what you paid. On a FREE door this sends immediately. On a PRICED door this tool ' +
+ 'does not pay and cannot pay: it returns `payment_required` together with the recipient, the amount, ' +
+ 'the token, the chain and the endpoint, so a human can approve the spend and pay from their own ' +
+ 'wallet (npx @three-ws/knock, or any x402 client). Pass `request_id` to make retries safe: the same ' +
+ 'id never knocks, or charges, twice. Refusals (shut door, daily cap, message too long) happen before ' +
+ 'any payment, so a rejected knock is never a paid one.',
+ inputSchema: {
+ to: z.string().min(1).max(40).describe('Recipient username, with or without the @.'),
+ from: z.string().min(1).max(64).describe('Who is knocking. Shown to them and spoken out loud.'),
+ message: z.string().min(8).max(2000).describe('The message. Shown in full, never read aloud.'),
+ subject: z.string().max(120).optional().describe('One line their companion says out loud. Make it the reason you are knocking.'),
+ url: z.string().max(400).optional().describe('An http(s) link about you.'),
+ request_id: z.string().max(80).optional().describe('Idempotency key. A retry returns the first knock instead of knocking twice.'),
+ },
+ async handler({ to, from, message, subject, url, request_id: requestId }) {
+ const handle = String(to).replace(/^@+/, '');
+ const { door } = await apiRequest('/api/knock/door', { query: { handle } });
+
+ if (!door.free) {
+ return {
+ ok: false,
+ error: 'payment_required',
+ message: `${door.display_name} charges ${door.price} to be reached. This server does not hold a wallet, so a human has to approve and pay.`,
+ confirm: {
+ recipient: `${door.display_name} (@${door.handle})`,
+ amount: door.price,
+ token: door.currency,
+ chains: door.networks,
+ endpoint: door.endpoint,
+ settles_to: 'the recipient directly, not to three.ws',
+ },
+ how_to_pay: `npx @three-ws/knock send ${door.handle} "<message>" --from "${from}" --payer ./payer.mjs`,
+ };
+ }
+
+ const body = {
+ to: handle,
+ from,
+ message,
+ sender_kind: 'agent',
+ ...(subject ? { subject } : {}),
+ ...(url ? { url } : {}),
+ ...(requestId ? { request_id: requestId } : {}),
+ };
+ const data = await apiRequest('/api/knock/send', { method: 'POST', body });
+ return {
+ ok: true,
+ knock_id: data.knock_id,
+ delivered_to: data.delivered_to,
+ duplicate: data.duplicate,
+ paid: data.paid,
+ receipt_url: data.receipt_url,
+ next: 'Poll receipt_url with knock_receipt to see whether they replied.',
+ };
+ },
+};