diff --git a/README.md b/README.md index 57984f4..c1b99e1 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) | | 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) | diff --git a/agent/agent.ts b/agent/agent.ts index 05bd7cc..a3e5770 100644 --- a/agent/agent.ts +++ b/agent/agent.ts @@ -1,8 +1,10 @@ import { openai } from "@ai-sdk/openai"; import { defineAgent } from "eve"; +import { scheduledToolApproval } from "./lib/scheduled-tools"; export default defineAgent({ model: openai.responses(process.env.BELL_MODEL ?? "gpt-5.6-sol"), + approval: scheduledToolApproval, build: { externalDependencies: [ "@1password/sdk", diff --git a/agent/channels/linq.ts b/agent/channels/linq.ts index c11db3e..00df5d0 100644 --- a/agent/channels/linq.ts +++ b/agent/channels/linq.ts @@ -1,4 +1,6 @@ -import { linqBrowserEvents, requiredEnvironmentValue } from "../lib/linq"; +import { linqBrowserEvents, localTimezone, requiredEnvironmentValue } from "../lib/linq"; +import type { Channel, InferChannelMetadata } from "eve/channels"; +import type { ChatSdkChannelState, ChatSdkReceiveTarget } from "eve/channels/chat-sdk"; import { defaultLinqAuth, linqChannel, type LinqChannelConfig } from "eve/channels/linq"; import { z } from "zod"; import { allowed } from "../../server/monitors/config"; @@ -36,7 +38,7 @@ export function isAllowedBellMessage(message: IncomingMessage): boolean { return !!messageDestination(message); } -export default linqChannel({ +const linq = linqChannel({ events: linqBrowserEvents, userName: "Bell", credentials: { @@ -53,16 +55,37 @@ export default linqChannel({ bell_linq_text_hash: digest(message.text.trim()), ...(signed.data.sent_at ? { bell_linq_sent_at: signed.data.sent_at } : {}), } : {}; + const timezone = localTimezone(); const baseAuth = defaultLinqAuth(message); - const auth = { ...baseAuth, attributes: { ...baseAuth.attributes, ...signedAttributes, + const auth = { ...baseAuth, attributes: { ...baseAuth.attributes, ...signedAttributes, bell_timezone: timezone, bell_watch_chat: destination.chat, bell_watch_sender: destination.sender, bell_watch_line: destination.line } }; return { 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. " - + "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.", ], }; }, }); + +type BellLinqTarget = ChatSdkReceiveTarget & { morningDate?: string }; +const receive = linq.receive; +if (!receive) throw new Error("The Eve Linq channel requires a receive handler."); + +const channel: Channel> = { + ...linq, + receive(input, ctx) { + const { morningDate } = input.target; + // Eve's address selects a session. The Linq adapter still posts to the real thread ID. + return receive(input, morningDate === undefined ? ctx : { + ...ctx, + from: address => ctx.from(`morning:${morningDate}:${address}`), + }); + }, +}; + +export default channel; diff --git a/agent/connections/notion.ts b/agent/connections/notion.ts index 88bd707..1393533 100644 --- a/agent/connections/notion.ts +++ b/agent/connections/notion.ts @@ -1,35 +1,32 @@ import { defineDynamic, defineMcpClientConnection } from "eve/connections"; import { notionAuth } from "../lib/notion-auth"; +import { notionReadTools } from "../lib/scheduled-tools"; import { notionEnabled, notionEndpoint, notionOwner, safeNotion } from "../../server/notion/config"; import { getNotionOAuth } from "../../server/notion/oauth"; -export default defineDynamic({ - events: { - "turn.started": (_event, ctx) => { - if (!notionEnabled()) return null; - const auth = ctx.session.auth.current; - 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); - 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", - "notion-create-pages", "notion-update-page", "notion-create-database", "notion-update-data-source", - "notion-get-async-task", "notion-delete-pages", - ] }, - approval: async ({ toolName }) => { - 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) - ? "user-approval" : "not-applicable"; - }, - }); +export default defineDynamic((ctx) => { + if (!notionEnabled()) return null; + const auth = ctx.session.auth.current; + 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; + 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: scheduled ? notionReadTools : [...notionReadTools, + "notion-create-pages", "notion-update-page", "notion-create-database", "notion-update-data-source", + "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) + ? "user-approval" : "not-applicable"; }, - }, + }); }); diff --git a/agent/extensions/link/lib/spend-requests.ts b/agent/extensions/link/lib/spend-requests.ts index 7286b10..448401e 100644 --- a/agent/extensions/link/lib/spend-requests.ts +++ b/agent/extensions/link/lib/spend-requests.ts @@ -34,6 +34,8 @@ const total = z.object({ amount: z.number(), }); +const expiration = z.union([z.number(), z.iso.datetime({ offset: true })]); + const metadata = z.object({ id: spendRequestId, status: z.string(), @@ -56,7 +58,7 @@ const metadata = z.object({ totals: z.array(total).optional(), approval_url: z.string().optional(), activity_url: z.string().optional(), - expires_at: z.number().optional(), + expires_at: expiration.optional(), recurring: z.object({ interval: z.string(), interval_count: z.number().optional(), @@ -83,7 +85,7 @@ const metadata = z.object({ display_message: z.string().optional(), action_url: z.string().nullable().optional(), resolution: z.string().optional(), - expires_at: z.number().nullable().optional(), + expires_at: expiration.nullable().optional(), }).optional(), }).optional(), }).nullable().optional(), diff --git a/agent/extensions/link/tools/checkout.ts b/agent/extensions/link/tools/checkout.ts index 27ef480..ec06587 100644 --- a/agent/extensions/link/tools/checkout.ts +++ b/agent/extensions/link/tools/checkout.ts @@ -11,6 +11,7 @@ export default defineTool({ description: "Submit an already-approved Link purchase in the existing browser. Supply exact CSS payment-field mappings and the approved amount/currency. Virtual-card values stay server-side. Shared Payment Tokens and Link Pay Tokens require a separate integration and are not accepted. Use only once per purchase; an uncertain outcome requires checking the merchant and Link before any retry. Human handoff remains available for 3DS.", inputSchema: checkoutInput, async execute(args, ctx) { + if (ctx.session.schedule !== undefined) throw new Error("Link checkout requires an interactive Linq conversation."); const input = checkoutInput.parse(args); linkPrincipal(ctx); ctx.abortSignal.throwIfAborted(); diff --git a/agent/extensions/link/tools/mpp_decode.ts b/agent/extensions/link/tools/mpp_decode.ts new file mode 100644 index 0000000..a908e44 --- /dev/null +++ b/agent/extensions/link/tools/mpp_decode.ts @@ -0,0 +1,2 @@ +import { disableTool } from "eve/tools"; +export default disableTool(); diff --git a/agent/extensions/link/tools/mpp_pay.ts b/agent/extensions/link/tools/mpp_pay.ts new file mode 100644 index 0000000..a908e44 --- /dev/null +++ b/agent/extensions/link/tools/mpp_pay.ts @@ -0,0 +1,2 @@ +import { disableTool } from "eve/tools"; +export default disableTool(); diff --git a/agent/extensions/link/tools/retrieve_approval_policy.ts b/agent/extensions/link/tools/retrieve_approval_policy.ts new file mode 100644 index 0000000..a908e44 --- /dev/null +++ b/agent/extensions/link/tools/retrieve_approval_policy.ts @@ -0,0 +1,2 @@ +import { disableTool } from "eve/tools"; +export default disableTool(); diff --git a/agent/hooks/browser-lifecycle.ts b/agent/hooks/browser-lifecycle.ts index a5bab4e..9dda121 100644 --- a/agent/hooks/browser-lifecycle.ts +++ b/agent/hooks/browser-lifecycle.ts @@ -4,8 +4,8 @@ import { saveBrowserRuntime } from "../lib/browser-runtime"; export default defineHook({ events: { - async "turn.completed"(_event, ctx) { - await saveBrowserRuntime(ctx.session.id); + async "turn.settled"(event, ctx) { + if (event.data.outcome === "completed") await saveBrowserRuntime(ctx.session.id); }, }, }); diff --git a/agent/hooks/task-state.ts b/agent/hooks/task-state.ts index b17dbfa..d86feee 100644 --- a/agent/hooks/task-state.ts +++ b/agent/hooks/task-state.ts @@ -1,36 +1,30 @@ -import { defineHook, type HookEvent } from "eve/hooks"; +import { defineHook, type HookContext, type HookEvent } from "eve/hooks"; import { closeBrowserRuntime, resumeBrowserAfterHumanInput } from "../lib/browser-runtime"; import { applyTaskEvent, taskState } from "../lib/task-state"; -const update = (event: HookEvent, ctx: { session: { id: string } }) => - taskState.update((current) => applyTaskEvent(current, event, ctx.session.id)); - -const cancel = async (event: HookEvent<"turn.cancelled">, ctx: { session: { id: string } }) => { - await closeBrowserRuntime(ctx.session.id); - update(event, ctx); -}; +const update = (event: HookEvent, ctx: HookContext) => + taskState.update((current) => applyTaskEvent(current, event, ctx.session.id, ctx.position, ctx.now.toISOString())); export default defineHook({ events: { "session.started": update, "turn.started": update, - "message.received": (event, ctx) => { + "delivery.consumed": (event, ctx) => { taskState.update((current) => { - const next = applyTaskEvent(current, event, ctx.session.id); - if (next !== current && current.status === "waiting_for_user") + const next = applyTaskEvent(current, event, ctx.session.id, ctx.position, ctx.now.toISOString()); + if (next !== current && current.status === "waiting_for_user" && event.data.parts.length > 0) resumeBrowserAfterHumanInput(ctx.session.id); return next; }); }, - "step.started": update, - "input.requested": update, - "input.resolved": update, - "turn.completed": update, - "turn.failed": update, - "turn.cancelled": cancel, - "session.waiting": update, - "session.failed": update, - "session.completed": update, + "model.started": update, + "interaction.opened": update, + "interaction.settled": update, + async "turn.settled"(event, ctx) { + if (event.data.outcome === "cancelled") await closeBrowserRuntime(ctx.session.id); + update(event, ctx); + }, + "session.ended": update, }, }); diff --git a/agent/instructions.md b/agent/instructions.md index a6fa621..b2f6e34 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. + 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 diff --git a/agent/lib/browser-runtime.ts b/agent/lib/browser-runtime.ts index 6f9839e..b5d204e 100644 --- a/agent/lib/browser-runtime.ts +++ b/agent/lib/browser-runtime.ts @@ -358,12 +358,8 @@ function scheduleIdleClose(sessionId: string, runtime: BrowserRuntime): void { } // Channel callbacks also run when Eve ends a session outside a turn. -// Global stream hooks do not run on that path in Eve 0.79.1. export const browserChannelEvents = { - async "session.completed"(_event: unknown, _channel: unknown, ctx: { session: { id: string } }) { + async "session.ended"(_event: unknown, ctx: { session: { id: string } }) { await closeBrowserRuntime(ctx.session.id); }, - async "session.failed"(event: { sessionId: string }) { - await closeBrowserRuntime(event.sessionId); - }, }; diff --git a/agent/lib/linq.ts b/agent/lib/linq.ts index 9462924..5e6a0e0 100644 --- a/agent/lib/linq.ts +++ b/agent/lib/linq.ts @@ -3,11 +3,11 @@ import { browserChannelEvents } from "./browser-runtime"; export const linqBrowserEvents: NonNullable = { ...browserChannelEvents, - async "session.failed"(event, channel) { + async "session.ended"(event, ctx) { try { - await browserChannelEvents["session.failed"](event); + await browserChannelEvents["session.ended"](event, ctx); } finally { - await channel.thread?.post("This session could not recover from an error. Start a new conversation to continue."); + if (event.data.outcome === "failed") await ctx.channel.thread?.post("This session could not recover from an error. Start a new conversation to continue."); } }, }; @@ -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/lib/scheduled-tools.ts b/agent/lib/scheduled-tools.ts new file mode 100644 index 0000000..4bd2a8d --- /dev/null +++ b/agent/lib/scheduled-tools.ts @@ -0,0 +1,17 @@ +import type { AgentDefinition } from "eve"; + +export const notionReadTools = [ + "notion-search", "notion-fetch", "notion-memory-search", "notion-get-self", + "notion-get-tool-access", "notion-query-data-sources", "notion-get-async-task", +]; + +const scheduledTools = new Set([ + ...notionReadTools.map(name => `notion__${name}`), + "no_reply", "notion_status", "web_search", "web_fetch", +]); + +export const scheduledToolApproval: NonNullable = ({ session, toolName }) => { + if (session.schedule && !scheduledTools.has(toolName)) { + return { type: "denied", reason: "Scheduled turns can only look up information and report it." }; + } +}; diff --git a/agent/lib/task-state.ts b/agent/lib/task-state.ts index f90ed56..fab1aec 100644 --- a/agent/lib/task-state.ts +++ b/agent/lib/task-state.ts @@ -1,4 +1,6 @@ import { defineState } from "eve/context"; +import type { FactPosition, InteractionRequest } from "eve/events"; +import type { HookEvent } from "eve/hooks"; import type { BrowserProxyLocation, BrowserState } from "../../server/browser/types.js"; @@ -74,15 +76,12 @@ export function initializeTask( } export function applyTaskEvent( record: DurableTaskRecord, - event: { - type: string; - data?: Record; - meta?: { id?: string; at?: string }; - }, + event: HookEvent, sessionId: string, + position?: FactPosition, + at = new Date().toISOString(), ): DurableTaskRecord { - const id = event.meta?.id, - at = event.meta?.at ?? new Date().toISOString(); + const id = position && `${position.line}:${position.index}`; let next = initializeTask(record, sessionId, at); if (id && next.processedEventIds.includes(id)) return next; next = { @@ -90,9 +89,9 @@ export function applyTaskEvent( processedEventIds: id ? [...next.processedEventIds, id].slice(-2_000) : next.processedEventIds, updatedAt: at, }; - if (event.type === "message.received") { + if (event.type === "delivery.consumed" && event.data.parts.length > 0) { if (next.title === "New task") { - const text = safeText(event.data?.message ?? event.data?.text); + const text = safeText(event.data.parts.flatMap((part) => part.kind === "text" ? [part.text] : []).join("\n")); if (text) next = { ...next, title: text.slice(0, 64) }; } // A reply after handoff permits a fresh observation of the existing page. @@ -111,25 +110,25 @@ export function applyTaskEvent( activeStep: "agent turn", waitReason: undefined, }; - else if (event.type === "step.started") + else if (event.type === "model.started") next = captchaBlocksGeneric(next) ? next : { ...next, status: "running", activeStep: "model step" }; - else if (event.type === "input.requested") + else if (event.type === "interaction.opened") next = { ...next, status: "waiting_for_user", activeStep: "waiting for user", - waitReason: classifyWait(event.data), + waitReason: classifyWait(event.data.request), }; - else if (event.type === "input.resolved") + else if (event.type === "interaction.settled") next = { ...next, status: "running", activeStep: "resuming", waitReason: undefined, }; - else if (event.type === "turn.completed" || event.type === "session.waiting") + else if (event.type === "turn.settled" && event.data.outcome === "completed") next = captchaBlocksGeneric(next) ? next : { @@ -138,16 +137,16 @@ export function applyTaskEvent( activeStep: undefined, waitReason: undefined, }; - else if (event.type === "turn.failed" || event.type === "session.failed") + else if ((event.type === "turn.settled" || event.type === "session.ended") && event.data.outcome === "failed") next = { ...next, status: "failed", activeStep: undefined }; - else if (event.type === "turn.cancelled") + else if (event.type === "turn.settled" && event.data.outcome === "cancelled") next = closeTaskBrowser({ ...next, status: "canceled", activeStep: undefined, waitReason: undefined, }); - else if (event.type === "session.completed") + else if (event.type === "session.ended") next = { ...next, status: "complete", activeStep: undefined }; return next; } @@ -337,11 +336,11 @@ export function closeTaskBrowser(record: DurableTaskRecord): DurableTaskRecord { updatedAt: new Date().toISOString(), }; } -function classifyWait(data?: Record): DurableTaskRecord["waitReason"] { - const value = JSON.stringify(data ?? {}).toLowerCase(); +function classifyWait(request: InteractionRequest): DurableTaskRecord["waitReason"] { + if (request.kind === "approval") return "approval"; + const value = request.prompt.toLowerCase(); if (value.includes("captcha")) return "captcha"; if (value.includes("otp") || value.includes("code")) return "otp"; - if (value.includes("approval")) return "approval"; return "other"; } export function safeText(value: unknown): string | undefined { diff --git a/agent/schedules/morning.ts b/agent/schedules/morning.ts new file mode 100644 index 0000000..c6f6856 --- /dev/null +++ b/agent/schedules/morning.ts @@ -0,0 +1,41 @@ +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"; + +const timezone = localTimezone(); +const calendarDate = new Intl.DateTimeFormat("en-CA", { + timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", +}); + +export default defineSchedule({ + cron: "30 8 * * *", + timezone, + async run({ to }) { + if (!notionEnabled()) return; + const now = new Date(); + const morningDate = calendarDate.format(now); + + for (const { destination, principalId, subject } of await privateLinqRecipients()) { + try { + 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}`, morningDate }).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.", + { idempotencyKey: `morning:${morningDate}:${chat}`, 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 }, + } }, + ); + } catch (error) { + console.error("Could not queue a Linq morning briefing.", error instanceof Error ? error.name : "Unknown error"); + } + } + }, +}); diff --git a/agent/schedules/reminders.ts b/agent/schedules/reminders.ts new file mode 100644 index 0000000..2e9dd20 --- /dev/null +++ b/agent/schedules/reminders.ts @@ -0,0 +1,45 @@ +import { defineDynamicSchedules } from "eve/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..0233878 --- /dev/null +++ b/agent/tools/no_reply.ts @@ -0,0 +1,4 @@ +import { noReply } from "eve/tools/no_reply"; +import { defineDynamic } from "eve/tools"; + +export default defineDynamic(({ session }) => session.schedule ? noReply : null); diff --git a/app/chat.tsx b/app/chat.tsx index 0e139f2..bf6aa6e 100644 --- a/app/chat.tsx +++ b/app/chat.tsx @@ -1,8 +1,9 @@ "use client"; import Image from "next/image"; import { useRouter } from "next/navigation"; +import { Client, ClientError, SessionNotActiveError } from "eve/client"; import { useEveAgent } from "eve/react"; -import { Client } from "eve/client"; +import { activeTurn, openInteractions, signInEnding } from "eve/events"; import { useState } from "react"; import { browserPreview } from "./projection"; @@ -19,16 +20,11 @@ export default function Chat({ sessionId, demoUrl, priceLine }: { sessionId?: st window.history.replaceState(null, "", `/s/${encodeURIComponent(session.sessionId)}`); }, }); - const busy = agent.status === "submitted" || agent.status === "streaming"; + const busy = agent.status === "busy"; const waiting = busy || agent.status === "resuming" || retiring; + const canStop = activeTurn(agent.view) !== undefined; const preview = browserPreview(agent.events); - const pending = agent.data.messages - .flatMap((message) => message.parts) - .flatMap((part) => { - if (part.type !== "dynamic-tool" || part.state !== "approval-requested") return []; - const request = part.toolMetadata?.eve?.inputRequest; - return request ? [request] : []; - }); + const pending = openInteractions(agent.view).filter(({ request }) => request.kind !== "sign-in"); async function send(text: string) { if (!text.trim() || waiting) return; setError(""); @@ -44,10 +40,15 @@ export default function Chat({ sessionId, demoUrl, priceLine }: { sessionId?: st setRetiring(true); setError(""); try { - const activeSessionId = agent.session?.sessionId ?? sessionId; - if (activeSessionId) - await new Client({ host: "" }).sessions.attach(activeSessionId).reset(); - agent.reset(); + try { + if (agent.session) await agent.end(); + else if (sessionId) await new Client({ baseUrl: "" }).sessions.attach(sessionId).end(); + } catch (error) { + const inactive = SessionNotActiveError.is(error) && !error.retryable; + const expired = ClientError.is(error) && error.code === "session_expired"; + if (!inactive && !expired) throw error; + } + agent.newSession(); setInput(""); router.push("/"); } catch { @@ -95,28 +96,30 @@ export default function Chat({ sessionId, demoUrl, priceLine }: { sessionId?: st

)}
- {agent.data.messages + {agent.messages .filter((message) => message.role === "user" || message.role === "assistant") .map((message) => (
{message.role === "user" ? "You" : "Bell"} - {message.parts.map((part, index) => - part.type === "text" ?

{part.text}

- : part.type === "authorization" ? ( -
- {part.state === "completed" ? ( -

{part.outcome === "authorized" ? `${part.displayName} connected.` : `${part.displayName} authorization ${part.outcome}.`}

- ) : ( - <> -

{part.description}

- {part.authorization?.url && ( - Connect {part.displayName} - )} - - )} -
- ) : null, - )} + {message.parts.map((part, index) => { + if (part.type === "text") return

{part.text}

; + const interaction = part.type === "interaction" ? part + : part.type === "tool" ? part.interaction : undefined; + if (!interaction || interaction.request.kind !== "sign-in") return null; + const { request, outcome } = interaction; + const name = request.signIn?.displayName ?? "Account"; + const url = request.link?.url ?? request.signIn?.url; + return ( +
+ {outcome ?

{name} {signInEnding(outcome)}.

: ( + <> +

{request.prompt}

+ {url && {request.link?.label ?? `Connect ${name}`}} + + )} +
+ ); + })}
))}
@@ -129,8 +132,8 @@ export default function Chat({ sessionId, demoUrl, priceLine }: { sessionId?: st {" "}

)} - {pending.map((request) => ( -
+ {pending.map(({ interactionId, request }) => ( +
{request.prompt} {request.options?.map((option) => ( )} @@ -183,7 +186,7 @@ export default function Chat({ sessionId, demoUrl, priceLine }: { sessionId?: st - {busy && ( + {canStop && (