Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): bot_schedule — bots can schedule their own future runs
Salman Qureshi4b801719806c
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 771fd90f..0a1080a2 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -12,6 +12,7 @@ import { BotJournal } from './journal.js';import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from './queue.js';import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';import { createBotSendTool } from './tools/bot-send.js';+import { createBotScheduleTool, type BotScheduler } from './tools/bot-schedule.js';import { runBotTurn, isTransientFailure, type BotTurnMail } from './bot-turn.js';import { synthesizeSkill, MIN_TOOLS_FOR_SYNTHESIS } from './skill-synthesis.js';import { logger } from '../utils/logger.js';@@ -58,6 +59,14 @@ export interface BotManagerDeps {const MAX_TRANSIENT_ATTEMPTS = 3;const MAILBOX_CAPACITY = 100;+/** Structural subset of the main Scheduler the bot runtime needs. */+type BotSchedulerLike = {+ addDelayedTask(m: { id: string; description: string; prompt: string; delaySeconds?: number; executeAt?: string; botId?: string; createdAt: string }): void;+ addPersistedTask(m: { id: string; cron: string; description: string; prompt: string; botId?: string; createdAt: string }): void;+ persistSchedules(): void;+ getManifests(): Array<{ id: string; botId?: string }>;+};+/*** Owns the bot fleet: per-bot job queues, isolated turn runtimes, mailboxes,* run journals, and live statuses. Bots never touch Agent.processQueue —@@ -83,12 +92,21 @@ export class BotManager {this.alert = cb;}+ /** Wire the main Scheduler so bots can self-schedule (bot_schedule tool). */+ setScheduler(scheduler: BotSchedulerLike): void {+ this.scheduler = scheduler;+ // Runtime-created toolsets gain the tool on next invalidation; simplest+ // is to refresh all bot runtimes so every bot sees the new tool.+ for (const botId of [...this.registries.keys()]) this.invalidateRuntime(botId);+ }+private async alertOwner(botId: string, message: string): Promise<void> {if (!this.alert) return;await this.alert(message).catch((e) => logger.warn({ e, botId }, 'Bot alert send failed'));}private queues: Map<string, BotJob[]> = new Map();+ private scheduler?: BotSchedulerLike;private mailboxes: Map<string, BotTurnMail[]> = new Map();private running: Map<string, Set<string>> = new Map(); // botId → running job idsprivate aborts: Map<string, AbortController> = new Map(); // job key → controller@@ -448,12 +466,18 @@ export class BotManager {userMemory: this.userMemoryFor(botId, manifest),config: this.config,});- const tools: Record<string, Tool> = { ...registry.getTools() };- // bot_send is added per bot, scoped to its configured roster.+ // Filter FIRST (strips interactive/global-mutation tools and applies the+ // manifest allow/deny), THEN add the bot-specific tools — otherwise the+ // filter would strip them again.+ const filtered = filterBotTools({ ...registry.getTools() }, manifest) as Record<string, Tool>;if ((manifest.comms?.canMessage ?? []).length > 0) {- tools.bot_send = createBotSendTool(this, botId, manifest.comms?.canMessage ?? []);+ filtered.bot_send = createBotSendTool(this, botId, manifest.comms?.canMessage ?? []);+ }+ // bot_schedule: bots can schedule their own future runs (durable,+ // capped) when the main scheduler is wired.+ if (this.scheduler) {+ filtered.bot_schedule = createBotScheduleTool(this.scheduler, botId);}- const filtered = filterBotTools(tools, manifest);this.registries.set(botId, { registry, tools: filtered });return { registry, tools: filtered };}diff --git a/src/bots/bot-schedule.test.ts b/src/bots/bot-schedule.test.tsnew file mode 100644index 00000000..a9229d86--- /dev/null+++ b/src/bots/bot-schedule.test.ts@@ -0,0 +1,81 @@+import { describe, it, expect, beforeEach } from 'vitest';+import { createBotScheduleTool, type BotScheduler } from './tools/bot-schedule.js';++function makeScheduler(): BotScheduler & { manifests: any[] } {+ const manifests: any[] = [];+ return {+ manifests,+ addDelayedTask(m: any) { manifests.push({ type: 'delayed', ...m }); },+ addPersistedTask(m: any) { manifests.push({ type: 'persisted', ...m }); },+ persistSchedules() { void 0; },+ getManifests() { return manifests; },+ } as any;+}++describe('bot_schedule (bot self-scheduling)', () => {+ let scheduler: ReturnType<typeof makeScheduler>;+ let tool: any;++ beforeEach(() => {+ scheduler = makeScheduler();+ tool = createBotScheduleTool(scheduler, 'publisher');+ });++ it('schedules a one-shot delayed run that survives restart (executeAt persisted)', async () => {+ const reply = await tool.execute({ prompt: 'post the follow-up thread', delayMinutes: 60 });+ expect(reply).toContain('60 min');+ expect(scheduler.manifests).toHaveLength(1);+ const m = scheduler.manifests[0];+ expect(m.type).toBe('delayed');+ expect(m.botId).toBe('publisher');+ expect(m.delaySeconds).toBe(3600);+ expect(m.executeAt).toBeTruthy();+ expect(m.id).toMatch(/^bot:publisher:self-/);+ });++ it('schedules recurring routines by name and replaces on re-schedule', async () => {+ const first = await tool.execute({ prompt: 'weekly scan', cron: '0 9 * * 1', name: 'Weekly Scan' });+ expect(first).toContain('routine');+ const m = scheduler.manifests[0];+ expect(m.type).toBe('persisted');+ expect(m.cron).toBe('0 9 * * 1');+ expect(m.id).toBe('bot:publisher:routine-weekly-scan');+ expect(m.botId).toBe('publisher');+ });++ it('rejects invalid cron and requires a name for cron', async () => {+ expect(await tool.execute({ prompt: 'x', cron: 'every morning', name: 'n' })).toContain('not a 5-field cron');+ expect(await tool.execute({ prompt: 'x', cron: '0 9 * * 1' })).toContain('need a name');+ });++ it('rejects ambiguous input: both one-shot and cron', async () => {+ const reply = await tool.execute({ prompt: 'x', delayMinutes: 30, cron: '0 9 * * 1', name: 'n' });+ expect(reply).toContain('exactly one');+ });++ it('caps pending one-shots at 10 per bot (runaway-loop guard)', async () => {+ for (let i = 0; i < 10; i++) {+ const reply = await tool.execute({ prompt: `task ${i}`, delayMinutes: i + 1 });+ expect(reply).toContain('Scheduled');+ }+ const reply = await tool.execute({ prompt: 'task 11', delayMinutes: 5 });+ expect(reply).toContain('pending self-scheduled runs');+ expect(scheduler.manifests).toHaveLength(10);+ });++ it('rejects delays beyond the 30-day horizon and invalid ISO timestamps', async () => {+ expect(await tool.execute({ prompt: 'x', delayMinutes: 50000 })).toContain('day horizon');+ expect(await tool.execute({ prompt: 'x', executeAt: 'not-a-date' })).toContain('not a valid ISO');+ const tooFar = new Date(Date.now() + 40 * 24 * 3600 * 1000).toISOString();+ expect(await tool.execute({ prompt: 'x', executeAt: tooFar })).toContain('day horizon');+ });++ it('the cap counts only this bot\'s one-shots', async () => {+ for (let i = 0; i < 10; i++) {+ await tool.execute({ prompt: `t${i}`, delayMinutes: 5 });+ }+ const otherTool = createBotScheduleTool(scheduler, 'other-bot');+ const reply = await (otherTool as any).execute({ prompt: 'other', delayMinutes: 5 });+ expect(reply).toContain('Scheduled');+ });+});\ No newline at end of filediff --git a/src/bots/tools/bot-schedule.ts b/src/bots/tools/bot-schedule.tsnew file mode 100644index 00000000..36f22abf--- /dev/null+++ b/src/bots/tools/bot-schedule.ts@@ -0,0 +1,118 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';+import { randomUUID } from 'node:crypto';+import { logger } from '../../utils/logger.js';++export interface BotScheduler {+ addDelayedTask(manifest: {+ id: string;+ description: string;+ prompt: string;+ delaySeconds?: number;+ executeAt?: string;+ botId?: string;+ createdAt: string;+ }): void;+ addPersistedTask(manifest: {+ id: string;+ cron: string;+ description: string;+ prompt: string;+ botId?: string;+ createdAt: string;+ }): void;+ persistSchedules(): void;+ /** All live manifests, used for the per-bot self-schedule cap. */+ getManifests(): Array<{ id: string; botId?: string }>;+}++const SELF_PREFIX = 'self-';+const ROUTINE_PREFIX = 'routine-';+const MAX_DELAY_MINUTES = 60 * 24 * 30; // 30 days+const MAX_PENDING_SELF_SCHEDULES = 10;++/**+ * bot_schedule — a bot schedules its OWN future run (durable, persisted with+ * the fleet's schedules): one-shot delayed runs ("post again in an hour") or+ * self-created recurring routines. Guardrails keep runaway loops bounded:+ * prompts are capped, delays are capped, and a bot can have at most+ * MAX_PENDING_SELF_SCHEDULES pending one-shots.+ */+export function createBotScheduleTool(scheduler: BotScheduler, botId: string) {+ return tool({+ description:+ 'Schedule work for yourself in the future. Use when a task needs a follow-up later (e.g. "post the follow-up in one hour") ' ++ 'or a recurring routine. One-shot: delayMinutes (or executeAt ISO date). Recurring: cron (5 fields). ' ++ 'The scheduled run starts fresh with your persona and tools; results are delivered like any other run.',+ inputSchema: zodSchema(z.object({+ prompt: z.string().min(1).max(4000).describe('What you should do on the future run — self-contained, include all needed context'),+ delayMinutes: z.number().min(1).max(MAX_DELAY_MINUTES).optional().describe('One-shot: run again after this many minutes (1..43200)'),+ executeAt: z.string().optional().describe('One-shot alternative: ISO timestamp to run at'),+ cron: z.string().optional().describe('Recurring: 5-field cron expression, e.g. "0 9 * * 1"'),+ name: z.string().max(40).optional().describe('Label for recurring routines (required with cron)'),+ })),+ execute: async ({ prompt, delayMinutes, executeAt, cron, name }: {+ prompt: string; delayMinutes?: number; executeAt?: string; cron?: string; name?: string;+ }) => {+ const hasDelay = delayMinutes !== undefined || executeAt !== undefined;+ if (hasDelay === Boolean(cron)) {+ return 'Error: choose exactly one — delayMinutes/executeAt for a one-shot, or cron for a recurring routine.';+ }++ if (cron) {+ if (!name) return 'Error: cron schedules need a name (used to update/replace the routine later).';+ if (cron.trim().split(/\s+/).length !== 5) {+ return `Error: "${cron}" is not a 5-field cron expression.`;+ }+ const id = `bot:${botId}:${ROUTINE_PREFIX}${name.toLowerCase().replace(/[^a-z0-9-]+/g, '-')}`;+ scheduler.addPersistedTask({+ id,+ cron,+ description: name,+ prompt,+ botId,+ createdAt: new Date().toISOString(),+ });+ scheduler.persistSchedules();+ logger.info({ botId, id, cron }, 'Bot self-scheduled a recurring routine');+ return `Scheduled: routine "${name}" (${cron}) — fires through the cron lane; results land in your chat like any other run. Manage via /bots.`;+ }++ // One-shot with a pending cap — this is the runaway-loop guard.+ const pending = scheduler.getManifests().filter(m => m.botId === botId && m.id.includes(`:${SELF_PREFIX}`)).length;+ if (pending >= MAX_PENDING_SELF_SCHEDULES) {+ return `Error: you already have ${MAX_PENDING_SELF_SCHEDULES} pending self-scheduled runs — complete or let them fire before adding more.`;+ }++ let delaySeconds: number;+ if (executeAt) {+ const at = new Date(executeAt);+ if (Number.isNaN(at.getTime())) return `Error: "${executeAt}" is not a valid ISO timestamp.`;+ delaySeconds = Math.max(1, Math.ceil((at.getTime() - Date.now()) / 1000));+ if (delaySeconds > MAX_DELAY_MINUTES * 60) {+ return `Error: scheduled time is beyond the ${MAX_DELAY_MINUTES / 60 / 24}-day horizon.`;+ }+ } else {+ if ((delayMinutes as number) > MAX_DELAY_MINUTES) {+ return `Error: delayMinutes exceeds the ${MAX_DELAY_MINUTES / 60 / 24}-day horizon.`;+ }+ delaySeconds = Math.round((delayMinutes as number) * 60);+ }++ const id = `bot:${botId}:${SELF_PREFIX}${randomUUID().slice(0, 8)}`;+ const executeAtIso = new Date(Date.now() + delaySeconds * 1000).toISOString();+ scheduler.addDelayedTask({+ id,+ description: 'bot self-schedule',+ prompt,+ delaySeconds,+ executeAt: executeAtIso,+ botId,+ createdAt: new Date().toISOString(),+ });+ scheduler.persistSchedules();+ logger.info({ botId, id, executeAtIso }, 'Bot self-scheduled a one-shot run');+ return `Scheduled: this run will fire in ${Math.round(delaySeconds / 60)} min (at ${executeAtIso}). It survives restarts; prompt: "${prompt.slice(0, 80)}"`;+ },+ });+}\ No newline at end of filediff --git a/src/index.ts b/src/index.tsindex ddb3ce30..0dea2ce5 100644--- a/src/index.ts+++ b/src/index.ts@@ -2486,6 +2486,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {return new UserMemoryStore(config, `bot:${manifest.id}`);},});+ botManager.setScheduler(scheduler);botManager.registerRoutines(scheduler);agent.setBotManager(botManager);setWebBotManager(botManager);