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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
18 changes: 17 additions & 1 deletion agent/instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
47 changes: 47 additions & 0 deletions agent/schedules/reminders.test.ts
Original file line number Diff line number Diff line change
@@ -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;
}
});
22 changes: 22 additions & 0 deletions agent/schedules/reminders.ts
Original file line number Diff line number Diff line change
@@ -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); },
});
100 changes: 100 additions & 0 deletions lib/dev-schedules.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((resolve) => setImmediate(resolve));
function context(deliver: (event: ScheduleDelivery) => Promise<void>, 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");
});
145 changes: 145 additions & 0 deletions lib/dev-schedules.ts
Original file line number Diff line number Diff line change
@@ -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<string, Entry>();
const operations = new Map<string, unknown>();
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<T>(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();
}
Loading
Loading