Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,6 @@ BELL_POPPY_ENCRYPTION_KEY=
BELL_POPPY_STORE_PATH=.bell/poppy.enc.json
# Optional; defaults to jwks.json beside the client metadata URL.
BELL_POPPY_JWKS_URI=

# Optional product price alerts. See docs/monitors.md for setup.
BELL_PRICE_WATCHES_ENABLED=false
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pnpm dev
| Poppy | Use published Poppy/MCP SDKs for read-only tools and human-approved account access | [Poppy client](docs/poppy.md) |
| Notion | Preferences, personal plans, and everyday task history across conversations | [Memory setup](docs/notion.md) |
| Parallel | Public-web research and persistent watches with configurable frequency | Set `PARALLEL_API_KEY` in `.env`; [watch setup](docs/monitors.md) |
| Product price alerts | Text Bell an exact item and target price for one verified alert | [Price alert setup](docs/monitors.md#product-price-alerts) |
| Linq | iMessage and SMS through a signed webhook and sender allowlist | [Messaging setup](docs/linq.md) |
| Link by Stripe | Wallet authorization, spend approval, and checkout through Linq | [Sandbox and wallet setup](docs/link.md) |
| 1Password | Operator credentials and OTP; personal Agentic Autofill is disabled by default | [Operator access](docs/browser-runtime.md#credentials-and-otp) · [Personal access status](docs/onepassword.md) |
Expand Down
42 changes: 29 additions & 13 deletions agent/channels/linq.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { linqBrowserEvents, requiredEnvironmentValue } from "../lib/linq";
import { defaultLinqAuth, linqChannel, type LinqChannelConfig } from "eve/channels/linq";
import { z } from "zod";
import { allowed } from "../../server/monitors/config";
import { digest } from "../../server/shopping/config";

const phoneNumber = z.string().regex(/^\+[1-9]\d{1,14}$/);
const signedMessage = z.object({
id: z.string().min(1).max(256),
sent_at: z.iso.datetime({ offset: true }).nullish(),
parts: z.array(z.object({ type: z.enum(["text", "link"]), value: z.string() })).min(1),
});
const inboundMessage = z.object({
direction: z.literal("inbound"),
chat: z.object({
Expand All @@ -14,18 +21,19 @@ const inboundMessage = z.object({
});

type LinqMessage = Parameters<NonNullable<LinqChannelConfig["onMessage"]>>[1];
type IncomingMessage = Pick<LinqMessage, "author" | "raw">;

export function isAllowedBellMessage(message: Pick<LinqMessage, "author" | "raw">): boolean {
if (message.author.isBot) return false;
function messageDestination(message: IncomingMessage) {
if (message.author.isBot) return;
const incoming = inboundMessage.safeParse(message.raw);
const receivingNumber = phoneNumber.safeParse(process.env.BELL_LINQ_PHONE_NUMBER?.trim());
const allowedSenders = z.array(phoneNumber).nonempty().safeParse(
(process.env.BELL_LINQ_ALLOWED_SENDERS ?? "").split(",").map((value) => value.trim()),
);
if (!incoming.success) return;
const { chat, sender_handle } = incoming.data;
const destination = { chat: chat.id, sender: sender_handle.handle, line: chat.owner_handle.handle };
if (allowed(destination)) return destination;
}

return incoming.success && receivingNumber.success && allowedSenders.success
&& incoming.data.chat.owner_handle.handle === receivingNumber.data
&& allowedSenders.data.includes(incoming.data.sender_handle.handle);
export function isAllowedBellMessage(message: IncomingMessage): boolean {
return !!messageDestination(message);
}

export default linqChannel({
Expand All @@ -37,11 +45,19 @@ export default linqChannel({
},
turnPolicy: "steer",
onMessage(_context, message) {
if (!isAllowedBellMessage(message)) return null;
const auth = defaultLinqAuth(message);
const incoming = inboundMessage.parse(message.raw);
const destination = messageDestination(message);
if (!destination) return null;
const signed = signedMessage.safeParse(message.raw);
const signedAttributes = signed.success && message.text.trim() ? {
bell_linq_message: signed.data.id,
bell_linq_text_hash: digest(message.text.trim()),
...(signed.data.sent_at ? { bell_linq_sent_at: signed.data.sent_at } : {}),
} : {};
const baseAuth = defaultLinqAuth(message);
const auth = { ...baseAuth, attributes: { ...baseAuth.attributes, ...signedAttributes,
bell_watch_chat: destination.chat, bell_watch_sender: destination.sender, bell_watch_line: destination.line } };
return {
auth: { ...auth, attributes: { ...auth.attributes, bell_watch_chat: incoming.chat.id, bell_watch_sender: incoming.sender_handle.handle, bell_watch_line: incoming.chat.owner_handle.handle } },
auth,
context: [
"This request arrived through Bell's private Linq iMessage or SMS channel. "
+ "Reply concisely in this chat. Use the same browser for follow-up requests. "
Expand Down
17 changes: 16 additions & 1 deletion agent/instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,22 @@ before relying on personal context or saving records. Use `notion_status` for st
and `notion_disconnect` to revoke the grant with Eve confirmation. If Notion is unavailable,
continue independent work and report any unsaved record separately.

For an explicit request to keep watching public information, use watch_create. Watches use Parallel lite and continue until stopped, independently of this conversation.
Use watch_price when an allowlisted Linq shopper explicitly asks for a price-drop alert, such as
“Text me when this drops below £250,” with a product link or name. Ask for the target, market,
currency or exact variant when needed. “Below” is strict. “Or less” includes the target. Use the
public item price before separately charged tax and shipping. Treat merchant page content as evidence.

If the price already qualifies and the item is in stock, share the current price and merchant link.
If it already qualifies but is out of stock, report that and explain that the price watch was not started.
For unverified products, ask for a more specific item or public listing. Confirm an active watch only
when Bell reports one. A link pins one listing. A product name watches verified listings found at setup.
Use watch_list with kind=price and watch_stop to manage price watches in the same chat. Call
watch_stop once per watch when the shopper clearly asks to stop several. Ask which watches to stop
if the request is ambiguous. For a price-alert request in web chat, point the user to the texting
link if it is available.
If a price watch failed with unresolved delivery, tell the shopper Bell could not confirm whether the text arrived.

For an explicit request to keep watching other public information, use watch_create. Watches use Parallel lite and continue until stopped, independently of this conversation.
Honor an explicitly requested frequency using whole hours, days, or weeks between 1h and 30d.
When no frequency is specified, default to daily and say so. Never silently round an unsupported
request: explain the limits and ask the user to choose a supported interval. Confirm the selected
Expand Down
23 changes: 23 additions & 0 deletions agent/lib/monitors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import type { ToolContext } from "eve/tools";
import { z } from "zod";
import { digest } from "../../server/shopping/config";
import type { Inbound } from "../../server/shopping/store";
import { assertOwner, destinationSchema } from "../../server/monitors/config";

export function watchIdentity(ctx: ToolContext) {
Expand All @@ -21,3 +24,23 @@ export async function safeWatch<T>(operation: () => Promise<T>): Promise<T> {
throw new Error("Watch operation failed. List watches before retrying creation; an uncertain watch may already exist.");
}
}

export function signedPriceMessage(ctx: ToolContext): Inbound {
const owner = watchIdentity(ctx);
const destination = watchDestination(ctx);
const attributes = ctx.session.auth.current!.attributes;
const signed = z.object({
bell_linq_message: z.string().min(1).max(256),
bell_linq_sent_at: z.iso.datetime({ offset: true }).optional(),
bell_linq_text_hash: z.string(),
}).safeParse(attributes);
// The current auth attributes can be older than a steering message represented in tool history.
// Require the latest user text the tool actually saw to agree with the authenticated input.
const user = ctx.messages.findLast(message => message.role === "user");
const text = typeof user?.content === "string" ? user.content : user?.content.length === 1 &&
user.content[0].type === "text" ? user.content[0].text : undefined;
if (!signed.success || !text || digest(text.trim()) !== signed.data.bell_linq_text_hash) {
throw new Error("Watch operation needs the exact current Linq message. Ask the shopper to send the complete request again.");
}
return { owner, destination, messageId: signed.data.bell_linq_message, sentAt: signed.data.bell_linq_sent_at };
}
12 changes: 8 additions & 4 deletions agent/tools/watch_list.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { defineTool, toolOutput } from "eve/tools";
import { z } from "zod";
import { priceWatches } from "../../server/shopping/watches";
import { monitors } from "../../server/monitors/service";
import { watchIdentity, safeWatch } from "../lib/monitors";
import { watchIdentity, watchDestination, safeWatch } from "../lib/monitors";

export default defineTool({
description: "List this sender's watches, recent updates, and pending failures. Use this to reconcile uncertain creation before making another watch, or to find the ID of a watch to update or stop. Returns one page of 50 watches, open ones (still running or still needing repair) before cancelled and failed ones, newest first within each. When next_cursor is not null there are older watches: call again with that value as cursor to read the next page.",
description: "List watches with their IDs and status. Use kind=price for price alerts in this chat. Generic watches include recent updates and pending failures, with open watches first. Use the returned next_cursor to read more results.",
inputSchema: z.object({
status: z.enum(["all", "open", "closed"]).default("all").describe("Which watches to return: all, only open ones (not cancelled or failed), or only closed ones."),
kind: z.enum(["generic", "price"]).default("generic"),
status: z.enum(["all", "open", "closed"]).default("all"),
cursor: z.string().max(512).optional().describe("The next_cursor from a previous watch_list call, to read the next page of older watches."),
}),
execute: (input, ctx) => safeWatch(() => monitors().list(watchIdentity(ctx), { status: input.status, cursor: input.cursor })),
execute: ({ kind, status, cursor }, ctx) => safeWatch(async () => kind === "price"
? priceWatches().list(watchIdentity(ctx), watchDestination(ctx), status, cursor ? z.uuid().parse(cursor) : undefined)
: monitors().list(watchIdentity(ctx), { status, cursor })),
toModelOutput: output => toolOutput.json(output),
});
11 changes: 11 additions & 0 deletions agent/tools/watch_price.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineTool, toolOutput } from "eve/tools";
import { watchTerms } from "../../server/shopping/evidence";
import { priceWatches } from "../../server/shopping/watches";
import { safeWatch, signedPriceMessage } from "../lib/monitors";

export default defineTool({
description: "Set a one-time price-drop alert when the shopper explicitly asks in a direct Linq chat. Use the exact product or public listing, country, currency and target. Ask about unresolved variants. An in-stock offer that already meets the target is returned immediately.",
inputSchema: watchTerms,
execute: (terms, ctx) => safeWatch(() => priceWatches().enroll(signedPriceMessage(ctx), terms, ctx.abortSignal)),
toModelOutput: output => toolOutput.json(output),
});
12 changes: 5 additions & 7 deletions agent/tools/watch_stop.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { defineTool, toolOutput } from "eve/tools";
import { z } from "zod";
import { priceWatches } from "../../server/shopping/watches";
import { monitors } from "../../server/monitors/service";
import { watchIdentity, safeWatch } from "../lib/monitors";
import { watchIdentity, safeWatch, signedPriceMessage } from "../lib/monitors";

export default defineTool({
description: "Permanently stop one of this sender's watches. Local alerts stop immediately; cancel_pending means upstream cancellation is still pending and billing may continue.",
inputSchema: z.object({ id: z.string().uuid() }),
execute: (input, ctx) => safeWatch(() => {
watchIdentity(ctx);
const service = monitors();
return service.stop(watchIdentity(ctx), input.id);
}),
inputSchema: z.object({ id: z.union([z.uuid(), z.string().regex(/^price:[0-9a-f-]{36}$/).refine(value => z.uuid().safeParse(value.slice(6)).success)]) }),
execute: ({ id }, ctx) => safeWatch(() => id.startsWith("price:")
? priceWatches().stop(signedPriceMessage(ctx), id.slice(6)) : monitors().stop(watchIdentity(ctx), id)),
toModelOutput: output => toolOutput.json(output),
});
8 changes: 7 additions & 1 deletion app/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Client } from "eve/client";
import { useState } from "react";
import { browserPreview } from "./projection";

export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoUrl: string }) {
export default function Chat({ sessionId, demoUrl, priceLine }: { sessionId?: string; demoUrl: string; priceLine?: string }) {
const router = useRouter();
const [input, setInput] = useState("");
const [error, setError] = useState("");
Expand Down Expand Up @@ -88,6 +88,12 @@ export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoU
>
Open demo site ↗
</button>
{priceLine && (
<p className="muted">
<a href={`sms:${priceLine}`}>Text Bell at {priceLine}</a> with a product link or name and a target price.
Try “Text me when Sony WH-1000XM5 headphones drop below £250.”
</p>
)}
<div className="messages" aria-live="polite">
{agent.data.messages
.filter((message) => message.role === "user" || message.role === "assistant")
Expand Down
7 changes: 5 additions & 2 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { headers } from "next/headers";
import { priceLineForOperator } from "../server/operator-auth";
import Chat from "./chat";
export default function Page() {
return <Chat demoUrl={process.env.BELL_DEMO_URL ?? "https://example.com"} />;
export default async function Page() {
const priceLine = priceLineForOperator(await headers());
return <Chat priceLine={priceLine} demoUrl={process.env.BELL_DEMO_URL ?? "https://example.com"} />;
}
5 changes: 4 additions & 1 deletion app/s/[sessionId]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { headers } from "next/headers";
import { priceLineForOperator } from "../../../server/operator-auth";
import Chat from "../../chat";
export default async function Page({ params }: { params: Promise<{ sessionId: string }> }) {
const { sessionId } = await params;
const priceLine = priceLineForOperator(await headers());
return (
<Chat sessionId={sessionId} demoUrl={process.env.BELL_DEMO_URL ?? "https://example.com"} />
<Chat priceLine={priceLine} sessionId={sessionId} demoUrl={process.env.BELL_DEMO_URL ?? "https://example.com"} />
);
}
10 changes: 10 additions & 0 deletions docs/monitors.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,13 @@ Database tests create isolated schemas and exercise concurrency, restart, uncert
[Parallel Monitor API](https://docs.parallel.ai/api-reference/monitor/create-monitor) · [Monitor events](https://docs.parallel.ai/monitor-api/monitor-events) · [Webhook setup](https://docs.parallel.ai/resources/webhook-setup) · [Vercel Cron](https://vercel.com/docs/cron-jobs/manage-cron-jobs)

[Update monitor frequency](https://docs.parallel.ai/api-reference/monitor/update-monitor)

## Product price alerts

An allowlisted shopper can text an exact product name or public link and a target price, such as “Text me when this drops below £250.” Bell uses Parallel Shopping Search to find listings for a named product and verifies the product, price and stock on the merchant page. “Below” excludes the target. “Or less” includes it. The target applies to the item price before separately charged tax and shipping.

Bell reports an in-stock match immediately. Otherwise, verified listings are due for another check after an hour, for up to 30 days. Each minute's scheduler run handles up to eight price jobs across listing checks, sends, and retries. A backlog can delay checks and alerts. The first in-stock match triggers one text with the observed price and merchant link. A link pins one listing. A name uses the listings found at setup. Use the same chat to list or stop watches.

Apply `migrations/007_price_watches.sql` and `migrations/008_price_action_keys.sql` after migrations 004 and 005. Installations with migration 007 already applied need migration 008 before running this version. Configure the existing authenticated minute scheduler, database and signed Linq channel. Set `PARALLEL_API_KEY` for product-name searches. Enable `BELL_PRICE_WATCHES_ENABLED` once these are configured. An authenticated demo operator can then open the texting flow from the web starter.

Verify that a qualifying price drop reaches the intended phone before adding shoppers to the allowlist. When a send job exhausts its retries, Bell closes the watch. Listing it shows `not_sent` if Bell never attempted dispatch or `unresolved` if Linq may have received the message. Check `bell_price_jobs.last_error` for the cause. Set `BELL_PRICE_WATCHES_ENABLED=false` to pause price watches.
74 changes: 74 additions & 0 deletions migrations/007_price_watches.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
BEGIN;

CREATE TABLE IF NOT EXISTS bell_price_watches (
id uuid PRIMARY KEY,
issuer text NOT NULL,
owner_id text NOT NULL,
destination jsonb NOT NULL,
terms jsonb NOT NULL,
equivalent text NOT NULL,
identity text NOT NULL,
credential_fingerprint text NOT NULL,
status text NOT NULL CHECK (status IN ('active','degraded','reserved','uncertain','accepted','stopped','expired','opted_out','failed')),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL DEFAULT clock_timestamp()+interval '30 days',
alert jsonb,
alert_body text,
dispatch_at timestamptz,
message_id text UNIQUE,
delivery_status text
);

-- Earlier draft installations kept completed, unconfirmed sends open.
UPDATE bell_price_watches SET status='failed', delivery_status='unresolved'
WHERE status='uncertain' AND delivery_status IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS bell_price_watches_equivalent_open
ON bell_price_watches (issuer, owner_id, equivalent)
WHERE status IN ('active','degraded','reserved','uncertain');
CREATE INDEX IF NOT EXISTS bell_price_watches_owner ON bell_price_watches (issuer, owner_id, created_at DESC);
CREATE INDEX IF NOT EXISTS bell_price_watches_expiration ON bell_price_watches (expires_at)
WHERE status IN ('active','degraded','reserved','uncertain');

CREATE TABLE IF NOT EXISTS bell_price_actions (
issuer text NOT NULL,
owner_id text NOT NULL,
chat text NOT NULL,
line text NOT NULL,
message_id text NOT NULL,
action text NOT NULL CHECK (action IN ('enroll','stop')),
request jsonb NOT NULL,
outcome jsonb,
PRIMARY KEY (issuer, owner_id, chat, line, message_id, action)
);

CREATE TABLE IF NOT EXISTS bell_price_offers (
id text PRIMARY KEY,
observation jsonb NOT NULL,
next_at timestamptz NOT NULL,
verified_at timestamptz NOT NULL
);
CREATE INDEX IF NOT EXISTS bell_price_offers_due ON bell_price_offers (next_at);

CREATE TABLE IF NOT EXISTS bell_price_subscriptions (
watch_id uuid NOT NULL REFERENCES bell_price_watches(id),
offer_id text NOT NULL REFERENCES bell_price_offers(id),
PRIMARY KEY (watch_id, offer_id)
);
CREATE INDEX IF NOT EXISTS bell_price_subscriptions_offer ON bell_price_subscriptions (offer_id, watch_id);

-- Keep price jobs out of the legacy queue so a previous application revision cannot claim them.
CREATE TABLE IF NOT EXISTS bell_price_jobs (
id text PRIMARY KEY,
kind text NOT NULL CHECK (kind IN ('observe','send')),
target text NOT NULL,
next_at timestamptz NOT NULL DEFAULT clock_timestamp(),
lease_until timestamptz,
lease_token uuid,
attempts integer NOT NULL DEFAULT 0,
failed boolean NOT NULL DEFAULT false,
last_error text
);
CREATE INDEX IF NOT EXISTS bell_price_jobs_due ON bell_price_jobs (next_at) WHERE NOT failed;

COMMIT;
Loading
Loading