diff --git a/README.md b/README.md index 57e3338..50d0dda 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ model, sandbox tools, and Supermemory. Telegram supports photos and documents up to 20 MB, including generated files. Zalo supports text and incoming photos. The agent can install npm packages and -run scripts in an isolated sandbox. Voice, image generation, reminders, and +run scripts in an isolated sandbox. Voice, image generation, and cross-posting are not configured. ## Development @@ -35,6 +35,18 @@ Private chats require an allowed user ID; groups require an allowed chat ID. Empty allowlists disable access. Set the corresponding `TELEGRAM_ALLOWED_*` or `ZALO_ALLOWED_*` variables from `.env.example`. +Allowed users can create one-time and recurring text reminders, list them, change +their timing, pause/resume them, or cancel them through chat. Times default to +`Asia/Ho_Chi_Minh`. Reminders return to the originating chat/topic, and users manage +only their own reminders. Removed users/chats cannot receive reminders. Delivery +retries can repeat a message. Reminders send saved text; they do not run agent tasks. +Eve's experimental Vercel Schedules provider persists reminders in production +using Vercel OIDC. Preview and self-hosted scheduling are unsupported. Under +`pnpm dev`, a process-local Croner scheduler fires reminders in their configured +timezone. Reminders are lost on restart or worker reload, including when using +`--resume`. Dev delivery failures pause the reminder and log an error; cron jitter +is unsupported in dev. + **Telegram:** enable Threaded Mode and user-created threads in BotFather. For groups, enable Allow Groups, disable Group Privacy, and enable group Topics. Private messages without a thread ID are ignored; resend affected opening diff --git a/agent/instructions.md b/agent/instructions.md index 0315ae7..53f7972 100644 --- a/agent/instructions.md +++ b/agent/instructions.md @@ -37,5 +37,21 @@ Memory is shared among all trusted users of this bot; it is not private to one u Use its tools when the user asks to search, correct, or forget personal memory; report changes only after the tool confirms them. Do not claim that unrecorded facts or older chats are available. -Voice transcription, image generation, reminders, and external account access are +Use the reminders schedule tools to create, list, update, pause, resume, or delete +one-time and recurring text reminders. Reminders return to the chat/topic where +they are created; each user manages their own reminders. They send saved text, +not a future agent task. Do not promise scheduled research or other future actions. +Default to Asia/Ho_Chi_Minh unless the user specifies another timezone. Use an +explicit timezone for recurring cron schedules and one-time dates. For one-time +dates, use local YYYY-MM-DDTHH:mm without an offset in the requested timezone; +for relative requests, use a delay in minutes. Delays round up to minute precision +and may arrive up to 59 seconds later than the requested delay. +Ask for clarification when the time or recurrence is ambiguous. List reminders +before changing an ambiguous one and use the unique name from the tool receipt. +Payload replacement captures the current chat/topic as the new destination; +timing-only changes preserve the destination. Only confirm creation or changes +after the tool succeeds, and state the resolved time, timezone, and recurrence. +Check the returned state: a completed or inactive schedule is not a pending +reminder. Explain the result instead of claiming it will fire. +Voice transcription, image generation, and external account access are not configured. Explain this briefly if asked for one of these actions. diff --git a/agent/schedules/reminders.test.ts b/agent/schedules/reminders.test.ts new file mode 100644 index 0000000..1622b4f --- /dev/null +++ b/agent/schedules/reminders.test.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { ScheduleScopeContext } from "eve/experimental/schedules"; +import reminders from "./reminders.ts"; + +test("chat reminder mutations never park on an approval prompt that Zalo cannot display", async () => { + for (const operation of ["create", "update", "enable", "disable", "invoke", "delete"] as const) { + const approval = reminders.approval?.[operation]; + assert.ok(approval, `${operation} must override Eve's interactive approval default`); + const result = typeof approval === "function" ? await approval({} as never) : await approval.request({} as never); + assert.equal(result, "not-applicable", operation); + } +}); + +test("collection isolates owners, captures trusted destinations, and denies non-chat management", async () => { + const previous = process.env.TELEGRAM_ALLOWED_USER_IDS; + process.env.TELEGRAM_ALLOWED_USER_IDS = "123,456"; + try { + function caller(id: string): ScheduleScopeContext & { operation: "create"; name: string } { + const auth = { authenticator: "telegram-webhook", issuer: "telegram", principalType: "user", + principalId: `telegram:${id}`, attributes: { user_id: id, chat_id: id, chat_type: "private", message_thread_id: "7" } }; + return { abortSignal: new AbortController().signal, operation: "create", name: "drink-water", + channel: { kind: "channel:telegram" }, session: { id: "test", auth: { current: auth, initiator: auth } } }; + } + const first = caller("123"), second = caller("456"); + const firstScope = await reminders.scope!(first); + assert.ok(firstScope); + assert.notDeepEqual(firstScope, await reminders.scope!(second)); + const input = reminders.inputSchema; + // Normalization strips a destination injected into the model tool input. + const validated = await input["~standard"].validate({ text: "Drink water", destination: { chatId: "456" } }); + if (validated.issues) assert.fail("valid reminder was rejected"); + const prepared = await reminders.preparePayload!(validated.value, first); + assert.equal(prepared.destination.chatId, "123"); + assert.deepEqual(prepared, await reminders.preparePayload!(validated.value, first)); + assert.equal(await reminders.scope!({ ...first, channel: { kind: "channel:eve" } }), null); + process.env.TELEGRAM_ALLOWED_USER_IDS = "456"; + assert.equal(await reminders.scope!({ ...first, operation: "delete" }), null); + const auth = first.session.auth.current!; + assert.equal(await reminders.auth({ payload: prepared, + principal: { type: auth.principalType, principalId: auth.principalId, authenticator: auth.authenticator, issuer: auth.issuer }, + occurrence: { collection: "reminders", name: "drink-water", scheduleId: "s1", executionId: "e1", scheduledAt: "2026-10-14T03:00:00Z" } }), null); + } finally { + if (previous === undefined) delete process.env.TELEGRAM_ALLOWED_USER_IDS; + else process.env.TELEGRAM_ALLOWED_USER_IDS = previous; + } +}); diff --git a/agent/schedules/reminders.ts b/agent/schedules/reminders.ts new file mode 100644 index 0000000..6eaec60 --- /dev/null +++ b/agent/schedules/reminders.ts @@ -0,0 +1,22 @@ +import { byPrincipal, defineDynamicSchedules } from "eve/experimental/schedules"; +import { never } from "eve/tools/approval"; +import { devScheduleProvider } from "../../lib/dev-schedules.ts"; +import { captureReminderDestination, deliverReminder, reminderInputSchema, resolveReminderAuth } from "../../lib/reminders.ts"; + +export default defineDynamicSchedules({ + description: "Create and manage personal text reminders in this Telegram or Zalo chat. Supports delays, one-time dates and recurring cron schedules. Default timezone: Asia/Ho_Chi_Minh. Payload text is sent directly when due; it does not execute an agent task. Use the returned unique name for updates or cancellation.", + inputSchema: reminderInputSchema, + provider: process.env.EVE_DEV === "1" ? devScheduleProvider() : undefined, + // The user's chat request authorizes this bounded action. Zalo has no approval UI. + approval: { create: never(), update: never(), enable: never(), disable: never(), invoke: never(), delete: never() }, + scope(context) { + try { captureReminderDestination(context); } + catch { return null; } + return byPrincipal(context); + }, + preparePayload(input, context) { + return { ...input, destination: captureReminderDestination(context) }; + }, + auth({ principal, payload }) { return resolveReminderAuth(principal, payload); }, + async run({ payload }) { await deliverReminder(payload); }, +}); diff --git a/lib/dev-schedules.test.ts b/lib/dev-schedules.test.ts new file mode 100644 index 0000000..dd5fc43 --- /dev/null +++ b/lib/dev-schedules.test.ts @@ -0,0 +1,100 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { randomUUID } from "node:crypto"; +import type { ScheduleDelivery, ScheduleProviderContext } from "eve/experimental/schedules"; +import { createDevScheduleProvider } from "./dev-schedules.ts"; + +const settle = () => new Promise((resolve) => setImmediate(resolve)); +function context(deliver: (event: ScheduleDelivery) => Promise, namespace = "user1"): ScheduleProviderContext { + return { collection: "reminders", namespace, operationId: randomUUID(), + abortSignal: new AbortController().signal, target: { key: "bubby", deliver } }; +} + +test("UTC delay-style dates fire automatically on a Vietnam host and become completed", async (t) => { + const previous = process.env.TZ; + process.env.TZ = "Asia/Ho_Chi_Minh"; + t.after(() => { if (previous === undefined) delete process.env.TZ; else process.env.TZ = previous; }); + t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: new Date("2026-10-14T13:29:11Z") }); + const provider = createDevScheduleProvider(); + const sent: ScheduleDelivery[] = []; + const ctx = () => context(async (event) => { sent.push(event); }); + const created = await provider.create(ctx(), { name: "water", payload: { text: "Drink water" }, + expression: { type: "single", at: "2026-10-14T13:31", timezone: "UTC" } }); + assert.equal(created.state, "active"); + t.mock.timers.tick(108_999); + await settle(); + assert.equal(sent.length, 0); + t.mock.timers.tick(1); + await settle(); + assert.equal(sent.length, 1); + assert.deepEqual(sent[0].payload, { text: "Drink water" }); + assert.equal(sent[0].occurrence.scheduledAt, "2026-10-14T13:31:00.000Z"); + assert.equal((await provider.get(ctx(), "water"))?.state, "completed"); + t.mock.timers.tick(60_000); + await settle(); + assert.equal(sent.length, 1); + await provider.delete(ctx(), "water"); +}); + +test("recurring local time, pause/resume, timing updates and deletion control real timer callbacks", async (t) => { + t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: new Date("2026-10-14T01:59:00Z") }); + const provider = createDevScheduleProvider(); + const sent: ScheduleDelivery[] = []; + const ctx = () => context(async (event) => { sent.push(event); }); + await provider.create(ctx(), { name: "daily", payload: "original", + expression: { type: "cron", cron: "0 9 * * *", timezone: "Asia/Ho_Chi_Minh" } }); + t.mock.timers.tick(60_000); + await settle(); + assert.equal(sent.length, 1); + assert.equal((await provider.get(ctx(), "daily"))?.state, "active"); + await provider.disable(ctx(), "daily"); + t.mock.timers.tick(24 * 3600_000); + await settle(); + assert.equal(sent.length, 1); + await provider.update(ctx(), "daily", { expression: { type: "cron", cron: "* * * * *", timezone: "UTC" }, payload: "updated" }); + t.mock.timers.tick(60_000); + await settle(); + assert.equal(sent.length, 1); + await provider.enable(ctx(), "daily"); + t.mock.timers.tick(60_000); + await settle(); + assert.equal(sent.length, 2); + assert.equal(sent[1].payload, "updated"); + assert.notEqual(sent[0].occurrence.executionId, sent[1].occurrence.executionId); + await provider.delete(ctx(), "daily"); + t.mock.timers.tick(60_000); + await settle(); + assert.equal(sent.length, 2); +}); + +test("scope isolation, creation retries and invalid or past dates cannot falsely acknowledge delivery", async (t) => { + t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: new Date("2026-10-14T02:00:00Z") }); + const provider = createDevScheduleProvider(); + const ctx = context(async () => {}); + const input = { name: "water", payload: "hello", expression: { type: "single" as const, at: "2026-10-14T09:01", timezone: "Asia/Ho_Chi_Minh" } }; + const first = await provider.create(ctx, input); + assert.deepEqual(await provider.create(ctx, input), first); + const other = context(async () => {}, "user2"); + assert.equal(await provider.get(other, "water"), null); + assert.deepEqual((await provider.list(other, {})).data, []); + await assert.rejects(provider.disable(other, "water"), /not found/); + await assert.rejects(provider.create(context(async () => {}), { ...input, name: "past", + expression: { type: "single", at: "2026-10-14T08:59", timezone: "Asia/Ho_Chi_Minh" } }), /future occurrence/); + await assert.rejects(provider.update(context(async () => {}), "water", { expression: { type: "cron", cron: "invalid" } })); + assert.deepEqual((await provider.get(ctx, "water"))?.expression, input.expression); + await provider.delete(context(async () => {}), "water"); +}); + +test("failed delivery pauses the reminder and logs a safe error", async (t) => { + t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: new Date("2026-10-14T02:00:00Z") }); + const log = t.mock.method(console, "error", () => {}); + const provider = createDevScheduleProvider(); + const ctx = () => context(async () => { throw new Error("secret credential-bearing URL"); }); + await provider.create(ctx(), { name: "failed", payload: "hello", expression: { type: "single", at: "2026-10-14T02:01", timezone: "UTC" } }); + t.mock.timers.tick(60_000); + await settle(); + assert.equal((await provider.get(ctx(), "failed"))?.state, "inactive"); + assert.equal(log.mock.callCount(), 1); + assert.doesNotMatch(String(log.mock.calls[0].arguments[0]), /secret credential/); + await provider.delete(ctx(), "failed"); +}); diff --git a/lib/dev-schedules.ts b/lib/dev-schedules.ts new file mode 100644 index 0000000..90d32ed --- /dev/null +++ b/lib/dev-schedules.ts @@ -0,0 +1,145 @@ +import { randomUUID } from "node:crypto"; +import { Cron } from "croner"; +import type { ScheduleProvider, ScheduleProviderContext } from "eve/experimental/schedules"; +import type { ScheduleExpression, ScheduleRecord } from "eve/experimental/schedules"; + +type Entry = { record: ScheduleRecord; payload: unknown; context: ScheduleProviderContext; job: Cron }; + +/** Process-local scheduling for standalone eve dev (the bundled test provider has no timers). */ +export function createDevScheduleProvider(): ScheduleProvider { + const entries = new Map(); + const operations = new Map(); + const prefix = (ctx: ScheduleProviderContext) => JSON.stringify([ctx.collection, ctx.namespace]); + const key = (ctx: ScheduleProviderContext, name: string) => `${prefix(ctx)}:${name}`; + function requireEntry(ctx: ScheduleProviderContext, name: string): Entry { + const entry = entries.get(key(ctx, name)); + if (!entry) throw new Error("Reminder not found in this user's schedules."); + return entry; + } + function once(ctx: ScheduleProviderContext, action: () => T): T { + const id = `${prefix(ctx)}:${ctx.operationId}`; + if (operations.has(id)) return operations.get(id) as T; + const result = action(); + operations.set(id, result); + // Bound the process-local retry receipts independently of active schedules. + if (operations.size > 1000) operations.delete(operations.keys().next().value!); + return result; + } + function projection(entry: Entry): ScheduleRecord { + return structuredClone(entry.record); + } + async function dispatch(entry: Entry, executionId: string, scheduledAt: string) { + if (!entry.context.target.deliver) throw new Error("Dev scheduler has no delivery callback."); + await entry.context.target.deliver({ payload: entry.payload, occurrence: { + executionId, scheduledAt, name: entry.record.name, scheduleId: entry.record.scheduleId, + } }); + } + function makeJob(expression: ScheduleExpression, entry: () => Entry): Cron { + if (expression.type === "cron" && expression.jitter !== undefined) { + throw new Error("Dev reminders do not support jitter; omit it from the schedule."); + } + const job = new Cron(expression.type === "single" ? expression.at : expression.cron, { + timezone: expression.timezone ?? "UTC", paused: true, unref: true, protect: true, + }, async () => { + const current = entry(); + if (current.record.state !== "active") return; + try { + await dispatch(current, randomUUID(), new Date().toISOString()); + if (current.record.expression.type === "single") { + current.record = { ...current.record, state: "completed", updatedAt: Date.now() }; + } + } catch { + // Preserve the failed reminder for inspection and explicit retry. Do not expose API credentials. + current.job.pause(); + current.record = { ...current.record, state: "inactive", updatedAt: Date.now() }; + console.error(`[bubby:reminders] Dev delivery failed for ${current.record.name}; reminder paused.`); + } + }); + if (!job.nextRun()) { + job.stop(); + throw new Error("Reminder must have a future occurrence. Check its date and timezone."); + } + return job; + } + return { + kind: "bubby-dev", + async create(ctx, input) { + return once(ctx, () => { + if (entries.has(key(ctx, input.name))) throw new Error("Reminder name already exists."); + let entry: Entry; + const job = makeJob(input.expression, () => entry); + entry = { payload: input.payload, context: ctx, job, record: { + name: input.name, scheduleId: `dev_${randomUUID()}`, expression: structuredClone(input.expression), + state: "active", createdAt: Date.now(), updatedAt: Date.now(), + } }; + entries.set(key(ctx, input.name), entry); + job.resume(); + return projection(entry); + }); + }, + async get(ctx, name) { + const entry = entries.get(key(ctx, name)); + return entry ? projection(entry) : null; + }, + async list(ctx, query) { + const offset = Number(query.cursor ?? 0), limit = query.limit ?? 20; + if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) { + throw new Error("Invalid reminder pagination."); + } + const all = [...entries].filter(([id]) => id.startsWith(`${prefix(ctx)}:`)) + .map(([, entry]) => projection(entry)).sort((a, b) => a.name.localeCompare(b.name)); + return { data: all.slice(offset, offset + limit), cursor: offset + limit < all.length ? String(offset + limit) : null }; + }, + async update(ctx, name, patch) { + return once(ctx, () => { + const entry = requireEntry(ctx, name); + if (patch.expression) { + const job = makeJob(patch.expression, () => entry); + entry.job.stop(); + entry.job = job; + entry.record = { ...entry.record, expression: structuredClone(patch.expression) }; + if (entry.record.state === "active") job.resume(); + } + if (patch.payload !== undefined) entry.payload = patch.payload; + entry.context = ctx; + entry.record = { ...entry.record, updatedAt: Date.now() }; + return projection(entry); + }); + }, + async enable(ctx, name) { + return once(ctx, () => { + const entry = requireEntry(ctx, name); + if (!entry.job.nextRun()) throw new Error("Reminder has no future occurrence; reschedule it first."); + entry.record = { ...entry.record, state: "active", updatedAt: Date.now() }; + entry.context = ctx; + entry.job.resume(); + return projection(entry); + }); + }, + async disable(ctx, name) { + return once(ctx, () => { + const entry = requireEntry(ctx, name); + entry.job.pause(); + entry.record = { ...entry.record, state: "inactive", updatedAt: Date.now() }; + return projection(entry); + }); + }, + async invoke(ctx, name) { + await once(ctx, () => dispatch(requireEntry(ctx, name), `manual_${ctx.operationId}`, new Date().toISOString())); + }, + async delete(ctx, name) { + return once(ctx, () => { + const entry = entries.get(key(ctx, name)); + entry?.job.stop(); + return entries.delete(key(ctx, name)); + }); + }, + }; +} + +// Authored modules may be evaluated more than once in the dev worker. Share both records and timers. +const providerKey = Symbol.for("bubby.dev-reminders.provider.v1"); +export function devScheduleProvider(): ScheduleProvider { + const shared = globalThis as typeof globalThis & { [providerKey]?: ScheduleProvider }; + return shared[providerKey] ??= createDevScheduleProvider(); +} diff --git a/lib/reminders.test.ts b/lib/reminders.test.ts new file mode 100644 index 0000000..b1619fe --- /dev/null +++ b/lib/reminders.test.ts @@ -0,0 +1,100 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { SchedulePrincipalReference, ScheduleScopeContext } from "eve/experimental/schedules"; +import { defaultTelegramAuth } from "eve/channels/telegram"; +import { zaloAuth } from "./zalo-inbound.ts"; +import { captureReminderDestination, deliverReminder, reminderInputSchema, resolveReminderAuth } from "./reminders.ts"; + +const env = { TELEGRAM_ALLOWED_USER_IDS: "123", TELEGRAM_ALLOWED_CHAT_IDS: "-10042", + TELEGRAM_BOT_TOKEN: "test-secret", ZALO_ALLOWED_USER_IDS: "u1", ZALO_ALLOWED_CHAT_IDS: "g1", + ZALO_BOT_TOKEN: "zalo-secret" }; +function telegram(group = false, thread: number | undefined = 7): ScheduleScopeContext { + const auth = defaultTelegramAuth({ chat: { id: group ? "-10042" : "123", type: group ? "supergroup" : "private" }, + from: { id: "123", isBot: false }, messageId: "10", messageThreadId: thread }); + return { abortSignal: new AbortController().signal, channel: { kind: "channel:telegram" }, + session: { id: "test", auth: { current: auth, initiator: auth } } }; +} +function zalo(group = false): ScheduleScopeContext { + const auth = zaloAuth({ from: { id: "u1", is_bot: false }, + chat: { id: group ? "g1" : "private-chat", chat_type: group ? "GROUP" : "PRIVATE" }, message_id: "m1" }); + return { abortSignal: new AbortController().signal, channel: { kind: "channel:zalo" }, + session: { id: "test", auth: { current: auth, initiator: auth } } }; +} +function principal(context: ScheduleScopeContext): SchedulePrincipalReference { + const auth = context.session.auth.current!; + return { type: auth.principalType, authenticator: auth.authenticator, principalId: auth.principalId, issuer: auth.issuer }; +} + +test("capture uses real webhook identities and preserves Telegram topics and Zalo destinations", () => { + for (const context of [telegram(), telegram(true), zalo(), zalo(true)]) { + const destination = captureReminderDestination(context, env); + assert.equal(destination.chatId, context.session.auth.current!.attributes.chat_id); + assert.ok(resolveReminderAuth(principal(context), { text: "hello", destination }, env)); + } + assert.deepEqual(captureReminderDestination(telegram(true), env), { + channel: "telegram", chatId: "-10042", chatType: "supergroup", userId: "123", messageThreadId: 7, + }); + const general = telegram(true); + delete (general.session.auth.current!.attributes as Record).message_thread_id; + assert.equal("messageThreadId" in captureReminderDestination(general, env), false); +}); + +test("deny unallowed users, groups, non-webhook callers and inconsistent identities", () => { + for (const context of [telegram(), telegram(true), zalo(), zalo(true)]) { + assert.throws(() => captureReminderDestination(context, {}), /no longer allowed/); + } + const context = telegram(); + assert.throws(() => captureReminderDestination({ ...context, channel: { kind: "channel:eve" } }, env), /Telegram or Zalo/); + const auth = context.session.auth.current!; + for (const changed of [{ ...auth, principalType: "service" }, { ...auth, principalId: "telegram:999" }, + { ...auth, issuer: "other" }, { ...auth, attributes: { ...auth.attributes, message_thread_id: "invalid" } }]) { + assert.throws(() => captureReminderDestination({ ...context, + session: { ...context.session, auth: { current: changed, initiator: changed } } }, env)); + } +}); + +test("dispatch rechecks allowlists and creator identity rather than trusting stored grants", () => { + for (const context of [telegram(), telegram(true), zalo(), zalo(true)]) { + const payload = { text: "hello", destination: captureReminderDestination(context, env) }; + assert.equal(resolveReminderAuth(principal(context), payload, {}), null); + assert.equal(resolveReminderAuth({ ...principal(context), principalId: "another-user" }, payload, env), null); + assert.equal(resolveReminderAuth({ ...principal(context), authenticator: "other" }, payload, env), null); + assert.equal(resolveReminderAuth({ ...principal(context), subject: "delegated" }, payload, env), null); + } +}); + +test("model payload cannot select a destination and reminder text is bounded", () => { + assert.deepEqual(reminderInputSchema.parse({ text: " hello ", destination: { chatId: "victim" } }), { text: "hello" }); + for (const text of [" ", "x".repeat(1801)]) assert.equal(reminderInputSchema.safeParse({ text }).success, false); +}); + +test("delivery sends saved text to the exact Telegram topic or Zalo chat without a model call", async () => { + for (const context of [telegram(), telegram(true), zalo(), zalo(true)]) { + const payload = { text: "Time to drink water", destination: captureReminderDestination(context, env) }; + const requests: { url: string; body: Record }[] = []; + await deliverReminder(payload, env, async (url, init) => { + requests.push({ url: String(url), body: JSON.parse(String(init?.body)) }); + return Response.json({ ok: true }); + }); + assert.equal(requests.length, 1); + assert.equal(requests[0].body.chat_id, payload.destination.chatId); + assert.equal(requests[0].body.text, payload.text); + if (payload.destination.channel === "telegram") assert.equal(requests[0].body.message_thread_id, 7); + else assert.equal(requests[0].url, "https://bot-api.zaloplatforms.com/botzalo-secret/sendMessage"); + } +}); + +test("delivery rejects revoked destinations and reports API failures without exposing credentials", async () => { + for (const context of [telegram(), zalo()]) { + const payload = { text: "hello", destination: captureReminderDestination(context, env) }; + await assert.rejects(deliverReminder(payload, {}, async () => { assert.fail("must not send"); }), /no longer allowed/); + for (const response of [new Response("failed", { status: 500 }), Response.json({ ok: false }), Response.json({})]) { + await assert.rejects(deliverReminder(payload, env, async () => response), (error: Error) => { + assert.doesNotMatch(error.message, /test-secret|zalo-secret/); + return true; + }); + } + await assert.rejects(deliverReminder(payload, env, async () => { throw new Error("url with test-secret zalo-secret"); }), + (error: Error) => { assert.doesNotMatch(error.message, /test-secret|zalo-secret/); return true; }); + } +}); diff --git a/lib/reminders.ts b/lib/reminders.ts new file mode 100644 index 0000000..0f3e8f5 --- /dev/null +++ b/lib/reminders.ts @@ -0,0 +1,105 @@ +import type { SessionAuthContext } from "eve/context"; +import type { SchedulePrincipalReference, ScheduleScopeContext } from "eve/experimental/schedules"; +import { z } from "zod"; +import { includesId } from "./telegram-access.ts"; +import { zaloApi } from "./zalo-api.ts"; + +const destinationSchema = z.discriminatedUnion("channel", [ + z.object({ channel: z.literal("telegram"), chatId: z.string().regex(/^-?\d+$/), + chatType: z.enum(["private", "group", "supergroup"]), userId: z.string().regex(/^\d+$/), + messageThreadId: z.number().int().positive().optional() }), + z.object({ channel: z.literal("zalo"), chatId: z.string().min(1), + chatType: z.enum(["PRIVATE", "GROUP"]), userId: z.string().min(1) }), +]); +export const reminderInputSchema = z.object({ + text: z.string().trim().min(1).max(1800).describe("Exact reminder text to send when due, in the user's language. No code or agent task is executed."), +}); +export const reminderPayloadSchema = reminderInputSchema.extend({ destination: destinationSchema }); +export type ReminderPayload = z.infer; +type Destination = ReminderPayload["destination"]; +type ReminderEnv = { + TELEGRAM_ALLOWED_USER_IDS?: string; TELEGRAM_ALLOWED_CHAT_IDS?: string; TELEGRAM_BOT_TOKEN?: string; + ZALO_ALLOWED_USER_IDS?: string; ZALO_ALLOWED_CHAT_IDS?: string; ZALO_BOT_TOKEN?: string; +}; + +function destinationAuth(destination: Destination): SessionAuthContext { + const telegram = destination.channel === "telegram"; + const channel = destination.channel; + const group = telegram ? destination.chatType !== "private" : destination.chatType === "GROUP"; + return { + authenticator: `${channel}-webhook`, principalType: "user", + issuer: group ? `${channel}:${destination.chatId}` : channel, + principalId: group ? `${channel}:${destination.chatId}:${destination.userId}` : `${channel}:${destination.userId}`, + attributes: { chat_id: destination.chatId, chat_type: destination.chatType, user_id: destination.userId, + ...(telegram && destination.messageThreadId !== undefined + ? { message_thread_id: String(destination.messageThreadId) } : {}) }, + }; +} + +function allowed(destination: Destination, env: ReminderEnv): boolean { + if (destination.channel === "telegram") { + return destination.chatType === "private" + ? destination.chatId === destination.userId && includesId(env.TELEGRAM_ALLOWED_USER_IDS, destination.userId) + : includesId(env.TELEGRAM_ALLOWED_CHAT_IDS, destination.chatId); + } + return destination.chatType === "PRIVATE" + ? includesId(env.ZALO_ALLOWED_USER_IDS, destination.userId) + : includesId(env.ZALO_ALLOWED_CHAT_IDS, destination.chatId); +} + +/** Capture only verified webhook attributes, never model-supplied chat IDs. */ +export function captureReminderDestination(context: ScheduleScopeContext, env: ReminderEnv = process.env): Destination { + const auth = context.session.auth.current; + if (!auth || auth.principalType !== "user" || context.session.schedule) { + throw new Error("Reminders require an allowed user's Telegram or Zalo conversation."); + } + const channel = auth.authenticator === "telegram-webhook" ? "telegram" + : auth.authenticator === "zalo-webhook" ? "zalo" : null; + if (!channel || context.channel.kind !== `channel:${channel}`) { + throw new Error("Create and manage reminders from Telegram or Zalo."); + } + const attrs = auth.attributes; + const destination = destinationSchema.parse({ channel, chatId: attrs.chat_id, + chatType: attrs.chat_type, userId: attrs.user_id, + ...(channel === "telegram" && attrs.message_thread_id !== undefined + ? { messageThreadId: Number(attrs.message_thread_id) } : {}) }); + const expected = destinationAuth(destination); + if (auth.principalId !== expected.principalId || auth.issuer !== expected.issuer || !allowed(destination, env)) { + throw new Error("This user or chat is no longer allowed to use reminders."); + } + return destination; +} + +/** Re-resolve the creator against today's allowlists before every occurrence. */ +export function resolveReminderAuth(principal: SchedulePrincipalReference, payload: ReminderPayload, + env: ReminderEnv = process.env): SessionAuthContext | null { + const parsed = reminderPayloadSchema.safeParse(payload); + if (!parsed.success || !allowed(parsed.data.destination, env)) return null; + const auth = destinationAuth(parsed.data.destination); + return principal.type === auth.principalType && principal.authenticator === auth.authenticator + && principal.principalId === auth.principalId && principal.issuer === auth.issuer && principal.subject === undefined + ? auth : null; +} + +/** Deliver saved text directly; provider retries can repeat a message. */ +export async function deliverReminder(payload: ReminderPayload, env: ReminderEnv = process.env, + request: typeof fetch = fetch): Promise { + const { destination, text } = reminderPayloadSchema.parse(payload); + if (!allowed(destination, env)) throw new Error("Reminder destination is no longer allowed."); + if (destination.channel === "zalo") { + await zaloApi("sendMessage", { chat_id: destination.chatId, text }, env, request); + return; + } + if (!env.TELEGRAM_BOT_TOKEN) throw new Error("Telegram reminders require TELEGRAM_BOT_TOKEN."); + let response: Response; + try { + response = await request(`https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/sendMessage`, { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ chat_id: destination.chatId, text, message_thread_id: destination.messageThreadId }), + signal: AbortSignal.timeout(35_000), + }); + } catch { throw new Error("Telegram reminder request failed."); } + if (!response.ok) throw new Error(`Telegram reminder failed: HTTP ${response.status}`); + const result = z.object({ ok: z.literal(true) }).safeParse(await response.json().catch(() => null)); + if (!result.success) throw new Error("Telegram did not confirm reminder delivery."); +} diff --git a/package.json b/package.json index 9e13b70..531d06a 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,7 @@ "@supermemory/eve": "^0.1.3", "@vercel/connect": "^2.2.0", "ai": "^7.0.137", + "croner": "^10.0.1", "eve": "0.77.0", "microsandbox": "^0.5.5", "zod": "4.5.4" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index eaf568b..0ade5bf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -25,6 +25,9 @@ importers: ai: specifier: ^7.0.137 version: 7.0.137(zod@4.5.4) + croner: + specifier: ^10.0.1 + version: 10.0.1 eve: specifier: 0.77.0 version: 0.77.0(patch_hash=ndixs3aaz472mjebe3noo6mm2m)(ai@7.0.137)(just-bash@3.6.0)(microsandbox@0.5.5) @@ -603,6 +606,11 @@ packages: engines: {node: ^14.18.0 || >=16.10.0} dev: false + /croner@10.0.1: + resolution: {integrity: sha512-ixNtAJndqh173VQ4KodSdJEI6nuioBWI0V1ITNKhZZsO0pEMoDxz539T4FTTbSZ/xIOSuDnzxLVRqBVSvPNE2g==} + engines: {node: '>=18.0'} + dev: false + /cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'}