diff --git a/README.md b/README.md index d56301a..471afbf 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

BELL

-[BELL](https://www.browserbase.com/blog/bell-personal-assistant-stack) is a reference architecture and sample app for running your own personal assistant. It combines browser automation, messaging, personal memory, and payments. +[BELL](https://www.browserbase.com/blog/bell-personal-assistant-stack) is a reference architecture and sample app for running your own personal assistant. It combines browser automation, messaging, personal memory, scheduled reminders, and payments. - Browserbase: Browser + Stagehand - Eve by Vercel: Agent Framework @@ -38,7 +38,7 @@ pnpm dev | Integration | What it does | Guide | | --- | --- | --- | | Browserbase + Stagehand | Browser sessions, automation, saved Contexts, and human handoff | [Browser runtime](docs/browser-runtime.md) | -| Eve by Vercel | Agent configuration, tools, conversation state, and channels | [Eve in Bell](docs/repository.md#eve-by-vercel) | +| Eve by Vercel | Agent configuration, tools, conversation state, channels, and schedules | [Eve in Bell](docs/repository.md#eve-by-vercel) · [Reminders](docs/reminders.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) | | Linq | iMessage and SMS through a signed webhook and sender allowlist | [Messaging setup](docs/linq.md) | diff --git a/agent/channels/linq.ts b/agent/channels/linq.ts index db40b4c..531a8e6 100644 --- a/agent/channels/linq.ts +++ b/agent/channels/linq.ts @@ -1,4 +1,4 @@ -import { linqBrowserEvents, requiredEnvironmentValue } from "../lib/linq"; +import { linqBrowserEvents, localTimezone, requiredEnvironmentValue } from "../lib/linq"; import { defaultLinqAuth, linqChannel, type LinqChannelConfig } from "eve/channels/linq"; import { z } from "zod"; @@ -40,12 +40,15 @@ export default linqChannel({ if (!isAllowedBellMessage(message)) return null; const auth = defaultLinqAuth(message); const incoming = inboundMessage.parse(message.raw); + const timezone = localTimezone(); 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: { ...auth, attributes: { ...auth.attributes, bell_timezone: timezone, bell_watch_chat: incoming.chat.id, bell_watch_sender: incoming.sender_handle.handle, bell_watch_line: incoming.chat.owner_handle.handle } }, 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. " - + "For a human-only step, send the human_handoff tool's link and wait for a reply.", + + "For a human-only step, send the human_handoff tool's link and wait for a reply. " + + `The default local timezone is ${timezone}; current time is ${new Date().toISOString()}. ` + + "Use the user's saved timezone preference when available, otherwise this default. Do not ask for their timezone.", ], }; }, diff --git a/agent/connections/notion.ts b/agent/connections/notion.ts index 88bd707..c490167 100644 --- a/agent/connections/notion.ts +++ b/agent/connections/notion.ts @@ -11,19 +11,23 @@ export default defineDynamic({ if (auth?.principalType !== "user" || !["bell:operator", "linq"].includes(auth.issuer ?? "")) return null; const principal = { type: "user" as const, id: auth.principalId, issuer: auth.issuer }; const owner = notionOwner(principal); + const scheduled = ctx.session.schedule !== undefined; + const readTools = [ + "notion-search", "notion-fetch", "notion-memory-search", "notion-get-self", + "notion-get-tool-access", "notion-query-data-sources", "notion-get-async-task", + ]; return defineMcpClientConnection({ url: notionEndpoint, instanceKey: owner, description: "Notion: the user's personal preferences, routines, plans, decisions, and notes across conversations. Search before relying on remembered information.", protocolVersionDiscovery: false, auth: notionAuth, - tools: { allow: [ - "notion-search", "notion-fetch", "notion-memory-search", "notion-get-self", - "notion-get-tool-access", "notion-query-data-sources", + tools: { allow: scheduled ? readTools : [...readTools, "notion-create-pages", "notion-update-page", "notion-create-database", "notion-update-data-source", - "notion-get-async-task", "notion-delete-pages", + "notion-delete-pages", ] }, approval: async ({ toolName }) => { + if (scheduled && /__notion-(?:create|update|delete)-/.test(toolName)) return "denied"; if (toolName.startsWith("notion__") && (await safeNotion(() => getNotionOAuth().status(principal))).status !== "connected") return "denied"; return /__(?:notion-create-database|notion-update-data-source|notion-delete-pages)$/.test(toolName) diff --git a/agent/instructions.md b/agent/instructions.md index e50278b..d868c6a 100644 --- a/agent/instructions.md +++ b/agent/instructions.md @@ -64,6 +64,28 @@ 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. +The morning schedule asks Bell for an 8:30 AM Notion update in existing private Linq chats +whose sender is allowlisted and has Notion connected. +Reply directly in the Linq chat, just as you would answer an incoming message. +Use `schedule__reminders__create` for user-requested reminders and recurring tasks. +For a reminder, notify the user; do not perform the action being reminded about. +The schedule tools manage these user-created tasks; they do not change the fixed morning job. +Do not create recurring messages just because Notion contains a deadline or routine. + +Resolve timing from the user's explicit choice or saved Notion timezone preference, +otherwise the channel's local timezone. Do not ask for a timezone or infer one from a +phone number. Use delay for relative reminders, single for one-time dates, and cron with +expression.timezone for recurring local times. Include the resolved timezone in the task. +Use the generated list/get/update/enable/disable/delete tools to manage reminders. Follow +pagination, use returned names, and check existing schedules before retrying creation. +Confirm changes only after the tool succeeds. Changing a Notion note does not change a schedule. + +During a scheduled run, do the task and reply without asking questions or starting OAuth. +Use the creator's existing Notion connection and the notion-memory skill for fresh briefings. +Scheduled Notion access is read-only. Do not save memories, make purchases, or create new +commitments during these runs. Report access failures accurately. If a successful briefing +check finds nothing useful, call no_reply. Always deliver an explicit reminder when it is due. + For an explicit request to keep watching 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 diff --git a/agent/lib/linq.ts b/agent/lib/linq.ts index 9462924..2e8b8d3 100644 --- a/agent/lib/linq.ts +++ b/agent/lib/linq.ts @@ -17,3 +17,7 @@ export function requiredEnvironmentValue(name: string): string { if (!value) throw new Error(`${name} is required for the Linq channel.`); return value; } + +export function localTimezone(): string { + return Intl.DateTimeFormat().resolvedOptions().timeZone; +} diff --git a/agent/schedules/morning.ts b/agent/schedules/morning.ts new file mode 100644 index 0000000..31cdbcf --- /dev/null +++ b/agent/schedules/morning.ts @@ -0,0 +1,37 @@ +import { defineSchedule } from "eve/schedules"; +import linq from "../channels/linq"; +import { localTimezone } from "../lib/linq"; +import { privateLinqRecipients } from "../../server/linq"; +import { notionEnabled } from "../../server/notion/config"; +import { getNotionOAuth } from "../../server/notion/oauth"; + +export default defineSchedule({ + cron: "*/15 * * * *", + async run({ to }) { + if (!notionEnabled()) return; + const timezone = localTimezone(); + const now = new Date(); + const parts = new Intl.DateTimeFormat("en-GB", { + timeZone: timezone, hour: "2-digit", minute: "2-digit", hourCycle: "h23", + }).formatToParts(now); + const hour = Number(parts.find(part => part.type === "hour")?.value); + const minute = Number(parts.find(part => part.type === "minute")?.value); + if (hour !== 8 || minute < 30 || minute >= 45) return; + + for (const { destination, principalId, subject } of await privateLinqRecipients()) { + if ((await getNotionOAuth().status({ type: "user", issuer: "linq", id: principalId })).status !== "connected") continue; + const chat = destination.chat; + await to(linq, { adapterName: "linq", threadId: `linq:${chat}` }).send( + "Give the user a short morning update. Use notion-memory to check their current priorities, " + + "unfinished plans, and upcoming deadlines. Reply directly in this chat with useful source links. " + + `It is ${now.toISOString()}; the local timezone is ${timezone}. ` + + "If there is nothing useful to share, call no_reply.", + { auth: { + principalType: "user", authenticator: "linq-message", issuer: "linq", principalId, + subject, + attributes: { bell_timezone: timezone, bell_watch_chat: chat, bell_watch_sender: destination.sender, bell_watch_line: destination.line }, + } }, + ); + } + }, +}); diff --git a/agent/schedules/reminders.ts b/agent/schedules/reminders.ts new file mode 100644 index 0000000..f1982f9 --- /dev/null +++ b/agent/schedules/reminders.ts @@ -0,0 +1,45 @@ +import { defineDynamicSchedules } from "eve/experimental/schedules"; +import { z } from "zod"; +import linq from "../channels/linq"; +import { localTimezone } from "../lib/linq"; +import { allowed, destinationSchema } from "../../server/monitors/config"; + +const inputSchema = z.object({ task: z.string().trim().min(1).max(2_000) }).strict(); +const savedSchema = inputSchema.extend({ destination: destinationSchema, timezone: z.string().optional() }).strict(); + +export default defineDynamicSchedules({ + description: "Schedule one-time reminders or recurring tasks in your private Linq chat, requested by the user. " + + "Use their local timezone from context or a saved preference without asking. Set expression.timezone for wall-clock times. " + + "List existing schedules before retrying creation or making changes.", + inputSchema, + preparePayload(payload, { session }) { + const auth = session.auth.current; + if (auth?.principalType !== "user" || auth.authenticator !== "linq-message" || auth.issuer !== "linq") + throw new Error("Create reminders from your private Linq chat."); + const destination = destinationSchema.parse({ + chat: auth.attributes.bell_watch_chat, + sender: auth.attributes.bell_watch_sender, + line: auth.attributes.bell_watch_line, + }); + if (!allowed(destination)) throw new Error("This Linq sender or receiving line is no longer allowed."); + return { ...payload, destination, timezone: typeof auth.attributes.bell_timezone === "string" ? auth.attributes.bell_timezone : localTimezone() }; + }, + auth({ principal, payload }) { + const saved = savedSchema.safeParse(payload); + if (!saved.success || principal.type !== "user" || principal.authenticator !== "linq-message" + || principal.issuer !== "linq" || !allowed(saved.data.destination)) return null; + const { destination } = saved.data; + return { + principalType: principal.type, authenticator: principal.authenticator, + issuer: principal.issuer, principalId: principal.principalId, subject: principal.subject, + attributes: { bell_timezone: saved.data.timezone ?? localTimezone(), bell_watch_chat: destination.chat, bell_watch_sender: destination.sender, bell_watch_line: destination.line }, + }; + }, + async run({ payload, occurrence, to }) { + const { task, destination, timezone } = savedSchema.parse(payload); + await to(linq, { adapterName: "linq", threadId: `linq:${destination.chat}` }).send( + `Do this scheduled task now: ${task}\nScheduled for: ${occurrence.scheduledAt}. ` + + `Local timezone: ${timezone ?? localTimezone()}. Respect a timezone specified in the task.`, + ); + }, +}); diff --git a/agent/skills/notion-memory/SKILL.md b/agent/skills/notion-memory/SKILL.md index a8a98fd..e74bbc3 100644 --- a/agent/skills/notion-memory/SKILL.md +++ b/agent/skills/notion-memory/SKILL.md @@ -148,3 +148,17 @@ Report a Notion save failure separately from the outcome of the user's original Share the verified Notion link when useful. Confirm reminders, monitors, and background tasks through the tool that schedules them. + +## Scheduled briefings + +For a scheduled briefing, read the approved guide and current sources using the existing +memory lookup flow. Summarize useful unfinished priorities, plans, and approaching deadlines +with source links. Honor exclusions and skip completed or cancelled items. Reply directly +in the chat; if a successful check finds nothing useful, call `no_reply`. A failed read is +not an empty task list. Do not run setup, request authorization, save memories, or mark +anything complete. Use the schedule's local timezone to interpret dates. + +The fixed morning job reuses the existing private Linq chat and its connected Notion account. +Create additional schedules only when the user asks, through `schedule__reminders__create`. +A saved deadline alone is not a reminder, and editing or forgetting a note does not cancel +one. Verify schedule changes through its tools. diff --git a/agent/tools/no_reply.ts b/agent/tools/no_reply.ts new file mode 100644 index 0000000..4e18ed0 --- /dev/null +++ b/agent/tools/no_reply.ts @@ -0,0 +1,3 @@ +import { noReply } from "eve/tools/no_reply"; + +export default noReply(); diff --git a/docs/linq.md b/docs/linq.md index bf05f3c..4661fa7 100644 --- a/docs/linq.md +++ b/docs/linq.md @@ -99,6 +99,14 @@ hosted extension and live verification requirements are met. The staged personal single-step sign-in only; OTP and passkeys are not implemented. Do not send passwords or OTPs as chat messages. +## Scheduled updates + +Bell uses this same channel for [morning Notion updates and user-requested reminders](reminders.md). +The 8:30 AM morning job finds the existing private chat through Linq's API, checks the sender +allowlist, and reuses that sender's Notion connection. There are no separate recipient settings. +Dynamic reminders capture the verified chat when created and recheck access when due. +Both run the existing Bell agent and deliver its reply to Linq. A web Notion grant is separate. + ## Verification boundary `pnpm test` sends signed HTTP requests through the installed Eve/Linq adapter and checks dispatch diff --git a/docs/notion.md b/docs/notion.md index 5d5c7a3..d034ed0 100644 --- a/docs/notion.md +++ b/docs/notion.md @@ -103,7 +103,12 @@ and memory instructions. If a write fails, Bell reports the unsaved record separ the original task outcome and does not repeat the action. Memory is saved during conversations. There is no background account sync or guaranteed -logging after a process crash, and a saved deadline is not a scheduled reminder. +logging after a process crash. Once Notion is connected in a private Linq chat, the +[morning update](reminders.md) reads fresh plans and deadlines at 8:30 AM in Bell's local +timezone and sends its reply to that existing chat. Additional reminders and recurring +checks are created when the user asks. A saved deadline alone schedules nothing. +Briefings use the Notion account connected in that Linq chat and cannot change notes or mark +plans complete. Editing a note does not change or cancel a schedule. ## Verify diff --git a/docs/reminders.md b/docs/reminders.md new file mode 100644 index 0000000..901e38d --- /dev/null +++ b/docs/reminders.md @@ -0,0 +1,77 @@ +# Scheduled reminders and morning updates + +Bell can check Notion and reply through Linq without waiting for a message. The fixed +morning job uses Eve's `defineSchedule`. User-requested reminders and recurring tasks use +`defineDynamicSchedules` from `eve/experimental/schedules`. + +## Configure schedules + +Complete [Linq setup](linq.md) with Bell's receiving line and your personal sender allowlist. +For morning updates, connect [Notion](notion.md) in that private Linq chat. No additional +Bell environment variables, credentials, or database migration are needed. + +The morning job finds existing private chats through Linq's API and uses each participant's +Linq identity to check their existing Notion connection. It skips groups, archived chats, +other receiving lines, senders outside the allowlist, and disconnected Notion accounts. +It does not create chats or send an update to a new recipient. + +Bell uses the machine's local timezone without asking the user. Linq does not expose the +phone's device timezone, so a deployed host must use the intended local timezone. An +explicit choice or saved Notion timezone preference takes precedence for user-created tasks. + +Bell pins Eve 0.79.1. Fixed cron expressions use UTC on Vercel, so the morning handler checks +every 15 minutes and starts Bell only in the local 8:30 AM slot, before 8:45. This follows +daylight saving changes. Vercel Cron needs a plan that supports this frequency; Hobby +supports daily jobs only. Built Eve servers can also run the fixed job with their schedule +runner active. Plain `pnpm dev` does not fire fixed schedules automatically. + +Dynamic schedules use Vercel Schedules and Queues and require the experimental organization +feature flag in this Eve version. For local dynamic delivery, use `vercel dev` with +[local Schedules support](https://vercel.com/docs/schedules/local-development). + +## Use from your phone + +Once Notion is connected in your private chat, Bell's morning run checks current plans, +unfinished priorities, and approaching deadlines at 8:30 AM. Bell replies in the existing +chat with useful source links. It uses `no_reply` when a successful check finds nothing +to share. + +Text Bell for additional reminders: + +- "Remind me to buy milk in ten minutes." +- "Every evening at 7 PM, check Notion for tomorrow's travel plans." +- "Move my travel briefing to 6 PM." +- "Cancel my travel briefing." + +Eve provides the management tools, approvals, and creator isolation. Bell captures the +verified destination when the user creates a reminder and rechecks the sender allowlist +when it runs. The existing Bell agent handles the task and delivers its reply through Linq. +Explicit reminders do not require Notion. + +## Persistence and recovery + +Morning runs read existing chats from Linq and reuse the sender's Notion grant. They do not +depend on the conversation staying open. Web and Linq Notion grants remain separate. +Scheduled Notion access is read-only; Bell cannot change notes or mark tasks complete. + +Dynamic records persist through Vercel Schedules. Under plain `pnpm dev`, they are +process-local and disappear on restart. Editing a Notion note does not change or cancel +a reminder. Dynamic management tools control user-created reminders; the fixed morning +job is controlled in code and hosting configuration. + +Eve 0.79.1 can repeat a dynamic notification after a delivery retry. Cancellation stops +future occurrences and cannot recall a running task or sent message. + +## Verify + +`pnpm check` covers chat discovery, sender access, local timing, native reminder management, +and Notion read-only access. Provider HTTP and model execution are mocked; tests send no texts. + +For a live check, connect Notion in your private Linq chat and verify the morning update +arrives there. Ask for a reminder in a few minutes, then change or cancel a recurring one. +This needs the existing provider credentials and an active scheduler. Automated tests do +not establish live phone delivery. + +See Eve's [fixed schedules](https://eve.dev/docs/schedules) and +[dynamic schedules](https://eve.dev/docs/experimental/dynamic-schedules) guides. Their latest +examples may use options introduced after Bell's pinned version. diff --git a/docs/repository.md b/docs/repository.md index 9de11b7..8c97d92 100644 --- a/docs/repository.md +++ b/docs/repository.md @@ -28,7 +28,7 @@ lifecycle; channel callbacks also handle terminal-session cleanup. Restart Bell | Integration | Implementation | Guide | | --- | --- | --- | | Browserbase + Stagehand | [Browser runtime](../agent/lib/browser-runtime.ts), [session management](../server/browser/browser-session.ts) | [Browser configuration](browser-runtime.md) | -| Eve by Vercel | [Agent](../agent/agent.ts), [channels](../agent/channels/), [hooks](../agent/hooks/) | [Eve in Bell](#eve-by-vercel) | +| Eve by Vercel | [Agent](../agent/agent.ts), [channels](../agent/channels/), [hooks](../agent/hooks/), [schedules](../agent/schedules/) | [Eve in Bell](#eve-by-vercel) · [Reminders](reminders.md) | | Notion | [MCP connection](../agent/connections/notion.ts), [OAuth](../server/notion/), [personal memory Skill](../agent/skills/notion-memory/SKILL.md) | [Memory setup](notion.md) | | Linq | [Channel and sender policy](../agent/channels/linq.ts) | [Messaging setup](linq.md) | | Link by Stripe | [Eve extension and tools](../agent/extensions/link/), [authorization](../agent/lib/link-auth.ts), [server implementation](../server/link/) | [Sandbox and wallet setup](link.md) | diff --git a/server/linq.ts b/server/linq.ts new file mode 100644 index 0000000..4e04585 --- /dev/null +++ b/server/linq.ts @@ -0,0 +1,43 @@ +import { z } from "zod"; +import { allowed } from "./monitors/config"; +import { request } from "./monitors/provider"; + +const handleSchema = z.object({ + id: z.string().min(1), handle: z.string(), is_me: z.boolean().optional(), + left_at: z.string().nullish(), status: z.string().optional(), +}); +const chatsSchema = z.object({ + chats: z.array(z.object({ + id: z.string().min(1), is_group: z.boolean(), is_archived: z.boolean().optional(), + handles: z.array(handleSchema), + })), + next_cursor: z.string().nullish(), +}); + +export async function privateLinqRecipients() { + const key = process.env.LINQ_API_KEY?.trim(); + const line = process.env.BELL_LINQ_PHONE_NUMBER?.trim(); + if (!key || !line || !process.env.BELL_LINQ_ALLOWED_SENDERS?.trim()) return []; + const recipients = []; + const seen = new Set(); + const cursors = new Set(); + const params = new URLSearchParams({ from: line, limit: "100" }); + for (;;) { + const page = chatsSchema.parse(await request(`https://api.linqapp.com/api/partner/v3/chats?${params}`, key, "GET", undefined, true)); + for (const chat of page.chats) { + if (chat.is_group || chat.is_archived) continue; + const handles = chat.handles.filter(handle => !handle.left_at && (!handle.status || handle.status === "active")); + if (handles.length !== 2 || !handles.some(handle => handle.is_me && handle.handle === line)) continue; + const sender = handles.find(handle => handle.is_me === false); + if (!sender || seen.has(sender.id)) continue; + const destination = { chat: chat.id, sender: sender.handle, line }; + if (!allowed(destination)) continue; + seen.add(sender.id); + recipients.push({ destination, principalId: `linq:${sender.id}`, subject: sender.id }); + } + if (!page.next_cursor) return recipients; + if (cursors.has(page.next_cursor)) throw new Error("Linq chat pagination did not advance."); + cursors.add(page.next_cursor); + params.set("cursor", page.next_cursor); + } +} diff --git a/tests/linq.test.ts b/tests/linq.test.ts index affba1e..431dce5 100644 --- a/tests/linq.test.ts +++ b/tests/linq.test.ts @@ -2,6 +2,7 @@ import { createHmac, randomUUID } from "node:crypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import linq from "../agent/channels/linq"; +import { localTimezone } from "../agent/lib/linq"; import { ContextContainer, contextStorage } from "../node_modules/eve/dist/src/context/container.js"; import { SessionKey } from "../node_modules/eve/dist/src/context/keys.js"; import type { ChannelAdapter } from "../node_modules/eve/dist/src/channel/adapter.js"; @@ -84,6 +85,21 @@ async function deliver(event: ReturnType, options: { tamper?: bo } describe("Bell's signed Linq webhook", () => { + it("supplies the local timezone to the agent without a user question", async () => { + vi.stubEnv("TZ", "America/Los_Angeles"); + const event = message(); + const { dispatch } = await deliver(event); + expect(dispatch).toHaveBeenCalledWith(event.data.parts[0].value, expect.objectContaining({ + context: [expect.stringContaining("The default local timezone is America/Los_Angeles")], + auth: expect.objectContaining({ attributes: expect.objectContaining({ bell_timezone: "America/Los_Angeles" }) }), + })); + }); + + it("uses the machine's local timezone from the process environment", () => { + vi.stubEnv("TZ", "Pacific/Auckland"); + expect(localTimezone()).toBe("Pacific/Auckland"); + }); + it("dispatches a verified direct message to Bell with sender auth and chat state", async () => { const event = message(); const { response, from, dispatch } = await deliver(event); diff --git a/tests/morning.test.ts b/tests/morning.test.ts new file mode 100644 index 0000000..86a003c --- /dev/null +++ b/tests/morning.test.ts @@ -0,0 +1,129 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import linq from "../agent/channels/linq"; +import * as notionOAuth from "../server/notion/oauth"; + +const line = "+12025550100"; +const sender = "+12025550123"; +function chat(id = "private-chat", senderId = "sender-id", phone = sender) { + return { id, is_group: false, is_archived: false, handles: [ + { id: "line-id", handle: line, is_me: true, status: "active", left_at: null }, + { id: senderId, handle: phone, is_me: false, status: "active", left_at: null }, + ] }; +} +const connected = vi.fn(async () => ({ status: "connected" })); + +beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-11-18T03:00:00Z")); + vi.stubEnv("TZ", "Asia/Kolkata"); + vi.stubEnv("NOTION_ENABLED", "true"); + vi.stubEnv("LINQ_API_KEY", "synthetic-key"); + vi.stubEnv("BELL_LINQ_PHONE_NUMBER", line); + vi.stubEnv("BELL_LINQ_ALLOWED_SENDERS", sender); + connected.mockReset().mockResolvedValue({ status: "connected" }); + vi.spyOn(notionOAuth, "getNotionOAuth").mockReturnValue({ status: connected } as never); + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ chats: [chat()], next_cursor: null }))); +}); +afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.useRealTimers(); }); + +async function run() { + const morning = (await import("../agent/schedules/morning")).default; + const send = vi.fn(async () => ({} as never)); + const to = vi.fn(() => ({ send })); + await morning.run!({ to, waitUntil: () => {}, appAuth: {} as never }); + return { to, send }; +} + +describe("Fixed morning schedule", () => { + it.each([ + ["Asia/Kolkata", "2026-11-18T03:00:00Z"], + ["Asia/Kathmandu", "2026-11-18T02:45:00Z"], + ["America/New_York", "2026-07-18T12:30:00Z"], + ["America/New_York", "2026-11-18T13:30:00Z"], + ["Pacific/Auckland", "2026-11-17T19:30:00Z"], + ])("delivers at local 8:30 in %s at %s", async (timezone, at) => { + vi.stubEnv("TZ", timezone); + vi.setSystemTime(new Date(at)); + expect((await run()).send).toHaveBeenCalledOnce(); + }); + + it("allows cron startup delay within the 8:30 slot", async () => { + vi.setSystemTime(new Date("2026-11-18T03:12:00Z")); + expect((await run()).send).toHaveBeenCalledOnce(); + }); + + it.each(["02:59:00", "03:15:00", "04:00:00"])("does not contact Linq outside the morning slot at %s UTC", async time => { + vi.setSystemTime(new Date(`2026-11-18T${time}Z`)); + expect((await run()).send).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + }); + + it("reuses the existing private chat and its connected Notion identity", async () => { + const { to, send } = await run(); + const [url, options] = vi.mocked(fetch).mock.calls[0]; + expect(new URL(String(url)).searchParams.get("from")).toBe(line); + expect(options?.headers).toMatchObject({ Authorization: "Bearer synthetic-key" }); + expect(connected).toHaveBeenCalledWith({ type: "user", issuer: "linq", id: "linq:sender-id" }); + expect(to).toHaveBeenCalledWith(linq, { adapterName: "linq", threadId: "linq:private-chat" }); + expect(send).toHaveBeenCalledWith(expect.stringContaining("Give the user a short morning update"), { + auth: expect.objectContaining({ + principalType: "user", issuer: "linq", principalId: "linq:sender-id", subject: "sender-id", + attributes: expect.objectContaining({ bell_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, bell_watch_chat: "private-chat", bell_watch_sender: sender }), + }), + }); + }); + + it.each([ + ["group", (value: ReturnType) => { value.is_group = true; }], + ["archived", (value: ReturnType) => { value.is_archived = true; }], + ["wrong line", (value: ReturnType) => { value.handles[0].handle = "+12025550999"; }], + ["unlisted sender", (value: ReturnType) => { value.handles[1].handle = "+12025550999"; }], + ["removed participant", (value: ReturnType) => { value.handles[1].status = "removed"; }], + ["extra participant", (value: ReturnType) => { value.handles.push({ ...value.handles[1], id: "third" }); }], + ])("skips a %s chat", async (_name, change) => { + const value = chat(); + change(value); + vi.mocked(fetch).mockResolvedValue(Response.json({ chats: [value], next_cursor: null })); + expect((await run()).send).not.toHaveBeenCalled(); + expect(connected).not.toHaveBeenCalled(); + }); + + it("follows chat pagination and sends once per Linq identity", async () => { + vi.mocked(fetch) + .mockResolvedValueOnce(Response.json({ chats: [], next_cursor: "next-page" })) + .mockResolvedValueOnce(Response.json({ chats: [chat(), chat("other-chat")], next_cursor: null })); + expect((await run()).send).toHaveBeenCalledOnce(); + expect(new URL(String(vi.mocked(fetch).mock.calls[1][0])).searchParams.get("cursor")).toBe("next-page"); + }); + + it("uses each allowed sender's own chat and Notion identity", async () => { + vi.stubEnv("BELL_LINQ_ALLOWED_SENDERS", `${sender},+12025550456`); + vi.mocked(fetch).mockResolvedValue(Response.json({ chats: [chat(), chat("second-chat", "second-sender", "+12025550456")] })); + const { send, to } = await run(); + expect(send).toHaveBeenCalledTimes(2); + expect(to).toHaveBeenNthCalledWith(2, linq, { adapterName: "linq", threadId: "linq:second-chat" }); + expect(connected).toHaveBeenNthCalledWith(2, { type: "user", issuer: "linq", id: "linq:second-sender" }); + }); + + it("does not create a chat when none exists", async () => { + vi.mocked(fetch).mockResolvedValue(Response.json({ chats: [], next_cursor: null })); + expect((await run()).send).not.toHaveBeenCalled(); + }); + + it("skips disconnected Notion accounts", async () => { + connected.mockResolvedValue({ status: "disconnected" }); + expect((await run()).send).not.toHaveBeenCalled(); + }); + + it("does not contact Linq when Notion is disabled", async () => { + vi.stubEnv("NOTION_ENABLED", "false"); + expect((await run()).send).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + }); + + it.each(["LINQ_API_KEY", "BELL_LINQ_PHONE_NUMBER", "BELL_LINQ_ALLOWED_SENDERS"])("skips delivery when existing %s setup is missing", async name => { + vi.stubEnv(name, ""); + expect((await run()).send).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/notion.test.ts b/tests/notion.test.ts index 7b52079..c4bf8a8 100644 --- a/tests/notion.test.ts +++ b/tests/notion.test.ts @@ -318,3 +318,28 @@ it("validates the personal Notion connection through Eve's runtime resolver", as expect(resolved).toMatchObject({ connectionName: "notion", url: "https://mcp.notion.com/mcp" }); } }); + +it("keeps scheduled Notion sessions read-only, including forced write calls", async () => { + vi.stubEnv("NOTION_ENABLED", "true"); + const definition = (await import("../agent/connections/notion")).default; + const connection = await definition.events["turn.started"]!({}, { + session: { id: "scheduled", schedule: { definition: "reminders" }, auth: { current: { + principalType: "user", principalId: "operator", issuer: "bell:operator", authenticator: "http-basic", attributes: {}, + } } }, channel: {}, + } as never); + if (!connection || !("url" in connection) || typeof connection.approval !== "function") throw new Error("Expected a scheduled Notion connection"); + const filter = connection.tools; + if (!filter || !("allow" in filter)) throw new Error("Expected a read-tool allowlist"); + expect(filter.allow).toContain("notion-fetch"); + expect(filter.allow).toContain("notion-get-async-task"); + expect(filter.allow).not.toContain("notion-update-page"); + const f = fixture(); + await authorize(f); + const oauthModule = await import("../server/notion/oauth"); + const service = vi.spyOn(oauthModule, "getNotionOAuth").mockReturnValue(f.oauth); + try { + expect(await connection.approval({ toolName: "notion__notion-fetch" } as never)).toBe("not-applicable"); + expect(await connection.approval({ toolName: "notion__notion-update-page" } as never)).toBe("denied"); + expect(await connection.approval({ toolName: "notion__notion-create-pages" } as never)).toBe("denied"); + } finally { service.mockRestore(); } +}); diff --git a/tests/reminders.test.ts b/tests/reminders.test.ts new file mode 100644 index 0000000..1e639fb --- /dev/null +++ b/tests/reminders.test.ts @@ -0,0 +1,75 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { ScheduleScopeContext } from "eve/experimental/schedules"; +import { inMemoryScheduleProvider } from "eve/experimental/schedules/testing"; +import reminders from "../agent/schedules/reminders"; +import linq from "../agent/channels/linq"; +import { createScheduleCollectionClient } from "../node_modules/eve/dist/src/runtime/schedules/collection-client.js"; + +const destination = { chat: "private-chat", sender: "+12025550123", line: "+12025550100" }; +const principal = { type: "user", authenticator: "linq-message", issuer: "linq", principalId: "linq:sender", subject: "sender" }; +const auth = { + principalType: principal.type, ...principal, + attributes: { bell_watch_chat: destination.chat, bell_watch_sender: destination.sender, bell_watch_line: destination.line }, +}; +const context: ScheduleScopeContext = { + session: { id: "creating-session", auth: { current: auth, initiator: auth } }, + channel: { kind: "chat-sdk" }, abortSignal: new AbortController().signal, +}; +const occurrence = { collection: "reminders", name: "morning", scheduleId: "schedule-id", executionId: "execution-id", scheduledAt: "2026-11-18T03:00:00Z" }; + +beforeEach(() => { + vi.stubEnv("TZ", "America/New_York"); + vi.stubEnv("BELL_LINQ_PHONE_NUMBER", destination.line); + vi.stubEnv("BELL_LINQ_ALLOWED_SENDERS", destination.sender); +}); +afterEach(() => vi.unstubAllEnvs()); + +describe("Native Eve schedules", () => { + it("captures the verified chat instead of accepting model-supplied recipients", async () => { + const saved = await reminders.preparePayload!({ task: "Read my Notion priorities" }, { ...context, operation: "create", name: "morning" }); + expect(saved).toEqual({ task: "Read my Notion priorities", destination, timezone: "America/New_York" }); + expect((await reminders.inputSchema["~standard"].validate({ task: "Hello", destination })).issues).toBeDefined(); + }); + + it("rejects creation outside a private Linq identity", async () => { + expect(() => reminders.preparePayload!({ task: "Hello" }, { + ...context, operation: "create", name: "test", session: { ...context.session, auth: { current: null, initiator: null } }, + })).toThrow("private Linq"); + }); + + it("rechecks the creator and current sender allowlist before a run", async () => { + const payload = { task: "Hello", destination, timezone: "America/New_York" }; + expect(await reminders.auth({ principal, payload, occurrence })).toMatchObject({ principalId: principal.principalId }); + expect(await reminders.auth({ principal: { ...principal, issuer: "other" }, payload, occurrence })).toBeNull(); + vi.stubEnv("BELL_LINQ_ALLOWED_SENDERS", ""); + expect(await reminders.auth({ principal, payload, occurrence })).toBeNull(); + }); + + it("hands the task to the existing Linq channel as a fresh scheduled run", async () => { + const send = vi.fn(async () => ({} as never)); + const to = vi.fn(() => ({ send })); + await reminders.run({ payload: { task: "Read fresh Notion plans", destination, timezone: "America/New_York" }, occurrence, auth, to, waitUntil: () => {} }); + expect(to).toHaveBeenCalledWith(linq, { adapterName: "linq", threadId: `linq:${destination.chat}` }); + expect(send).toHaveBeenCalledWith(expect.stringContaining("Read fresh Notion plans")); + expect(send).toHaveBeenCalledWith(expect.stringContaining(occurrence.scheduledAt)); + }); + + it.each(["0 7 * * *", "30 8 * * *", "0 9 * * *"])("uses Eve's CRUD and per-user scope for daily %s schedules", async cron => { + const definition = { ...reminders, provider: inMemoryScheduleProvider() }; + const client = createScheduleCollectionClient(definition, { ...context, application: "bell-test", collection: "reminders" }); + const record = await client.create({ name: "morning", expression: { type: "cron", cron, timezone: "Asia/Kolkata" }, payload: { task: "Read Notion plans in Asia/Kolkata" } }); + expect(record.expression).toEqual({ type: "cron", cron, timezone: "Asia/Kolkata" }); + expect((await client.list()).data).toHaveLength(1); + const other = createScheduleCollectionClient(definition, { + ...context, application: "bell-test", collection: "reminders", + session: { ...context.session, auth: { current: { ...auth, principalId: "linq:other" }, initiator: auth } }, + }); + expect((await other.list()).data).toHaveLength(0); + expect(await other.delete(record.name)).toBe(false); + expect((await client.disable(record.name)).state).toBe("inactive"); + expect((await client.enable(record.name)).state).toBe("active"); + await client.update(record.name, { expression: { type: "cron", cron: "0 10 * * *", timezone: "Asia/Kolkata" } }); + expect((await client.get(record.name))?.expression).toMatchObject({ cron: "0 10 * * *" }); + expect(await client.delete(record.name)).toBe(true); + }); +}); diff --git a/tests/schedule-delivery.test.ts b/tests/schedule-delivery.test.ts new file mode 100644 index 0000000..cb59ad3 --- /dev/null +++ b/tests/schedule-delivery.test.ts @@ -0,0 +1,79 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import linq from "../agent/channels/linq"; +import morning from "../agent/schedules/morning"; +import reminders from "../agent/schedules/reminders"; +import * as notionOAuth from "../server/notion/oauth"; +import { ScheduleDispatcher } from "../node_modules/eve/dist/src/channel/schedule.js"; +import type { ChannelAdapter } from "../node_modules/eve/dist/src/channel/adapter.js"; +import type { RunInput } from "../node_modules/eve/dist/src/channel/types.js"; +import { ContextContainer, contextStorage } from "../node_modules/eve/dist/src/context/container.js"; +import { SessionKey } from "../node_modules/eve/dist/src/context/keys.js"; + +const { adapter } = linq as unknown as { adapter: ChannelAdapter }; + +beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-11-18T03:00:00Z")); + vi.stubEnv("TZ", "Asia/Kolkata"); + vi.stubEnv("NOTION_ENABLED", "true"); + vi.spyOn(notionOAuth, "getNotionOAuth").mockReturnValue({ status: async () => ({ status: "connected" }) } as never); + vi.stubEnv("BELL_LINQ_PHONE_NUMBER", "+12025550100"); + vi.stubEnv("BELL_LINQ_ALLOWED_SENDERS", "+12025550123"); + vi.stubEnv("LINQ_API_KEY", "synthetic-test-key"); + vi.stubEnv("LINQ_WEBHOOK_SECRET", "synthetic-signing-secret"); + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => { + const url = input instanceof Request ? input.url : String(input); + if (url.startsWith("https://api.linqapp.com/api/partner/v3/chats?")) + return Response.json({ chats: [{ id: "private-chat", is_group: false, handles: [ + { id: "line", handle: "+12025550100", is_me: true }, + { id: "sender-id", handle: "+12025550123", is_me: false }, + ] }], next_cursor: null }); + if (url !== "https://api.linqapp.com/api/partner/v3/chats/private-chat/messages") + throw new Error(`Unexpected provider request: ${url}`); + return Response.json({ chat_id: "private-chat", message: { id: "reply-id" } }); + })); +}); +afterEach(() => { vi.useRealTimers(); vi.unstubAllEnvs(); vi.unstubAllGlobals(); }); + +it.each(["morning", "reminders"])("delivers %s through Eve's dispatcher and the real Linq adapter", async kind => { + const createSession = vi.fn<(input: RunInput) => Promise<{ sessionId: string }>>() + .mockResolvedValue({ sessionId: "scheduled-session" }); + const dispatcher = new ScheduleDispatcher({ + runtime: { + createSession, + dispatchContinuation: async () => ({ status: "session_not_active" }), + } as never, + channels: [{ name: "linq", definition: linq, receive: linq.receive, adapter }] as never, + }); + if (kind === "morning") { + await dispatcher.trigger({ scheduleId: "morning", run: morning.run }); + } else { + await dispatcher.triggerCollection({ + collectionId: "reminders", definition: reminders, + occurrence: { collection: "reminders", name: "milk", scheduleId: "schedule-id", executionId: "execution-id", scheduledAt: new Date().toISOString() }, + payload: { + eve: { application: "bell-test", collection: "reminders", version: 3 }, + envelope: { + version: 3, scope: "test-user", + principal: { type: "user", authenticator: "linq-message", issuer: "linq", principalId: "linq:sender-id", subject: "sender-id" }, + payload: { task: "Remind the user to buy milk", timezone: "Asia/Kolkata", destination: { + chat: "private-chat", sender: "+12025550123", line: "+12025550100", + } }, + }, + }, + }); + } + expect(createSession).toHaveBeenCalledOnce(); + const input = createSession.mock.calls[0][0]; + expect(input.auth).toMatchObject({ principalType: "user", issuer: "linq", principalId: "linq:sender-id" }); + expect(input.adapter.state?.thread).toMatchObject({ id: "linq:private-chat" }); + const context = new ContextContainer(); + context.set(SessionKey, { sessionId: "scheduled-session" } as never); + await contextStorage.run(context, async () => { + const adapterContext = adapter.createAdapterContext!({ + state: input.adapter.state!, ctx: context, session: { id: "scheduled-session" }, + } as never); + await adapter["message.completed"]!({ message: "Bell's scheduled reply", finishReason: "stop" } as never, adapterContext); + }); + expect(fetch).toHaveBeenCalledTimes(kind === "morning" ? 2 : 1); +});