Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): onboarding budget step + full lifecycle editing (budget/edit/delete)
Salman Qureshi930529edbd8e
diff --git a/src/bots/edit.test.ts b/src/bots/edit.test.tsnew file mode 100644index 00000000..6723d255--- /dev/null+++ b/src/bots/edit.test.ts@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest';+import { applyBotFieldPatch, EDITABLE_PATHS, type EditResult } from './edit.js';+import type { BotManifest } from './types.js';++function baseManifest(): BotManifest {+ return {+ id: 'researcher',+ name: 'Research',+ enabled: true,+ tools: { allow: [], deny: ['run_command'] },+ memory: { scope: 'own' },+ comms: { canMessage: [] },+ autonomy: { maxSteps: 25, dailyTokenBudget: 100_000 },+ };+}++describe('applyBotFieldPatch (/bots edit)', () => {+ it('edits nested config fields', () => {+ const m = baseManifest();+ expect(applyBotFieldPatch(m, 'name', 'Deep Research').ok).toBe(true);+ expect(m.name).toBe('Deep Research');+ expect(applyBotFieldPatch(m, 'model.provider', 'anthropic').ok).toBe(true);+ expect(m.model?.provider).toBe('anthropic');+ expect(applyBotFieldPatch(m, 'memory.scope', 'shared-read').ok).toBe(true);+ expect(m.memory?.scope).toBe('shared-read');+ expect(applyBotFieldPatch(m, 'autonomy.maxSteps', '40').ok).toBe(true);+ expect(m.autonomy?.maxSteps).toBe(40);+ });++ it('parses comma lists for bot links and tool lists', () => {+ const m = baseManifest();+ applyBotFieldPatch(m, 'comms.canMessage', 'Publisher, SOCIAL');+ expect(m.comms?.canMessage).toEqual(['publisher', 'social']);+ applyBotFieldPatch(m, 'tools.allow', 'fetch_url, read_file');+ expect(m.tools?.allow).toEqual(['fetch_url', 'read_file']);+ });++ it('dailyTokenBudget: numbers set a cap, "none" removes it (unlimited default)', () => {+ const m = baseManifest();+ const capped = applyBotFieldPatch(m, 'autonomy.dailyTokenBudget', '5000000') as Extract<EditResult, { ok: true }>;+ expect(m.autonomy?.dailyTokenBudget).toBe(5000000);+ expect(capped.display).toBe('5,000,000');+ const none = applyBotFieldPatch(m, 'autonomy.dailyTokenBudget', 'none') as Extract<EditResult, { ok: true }>;+ expect(m.autonomy?.dailyTokenBudget).toBeUndefined();+ expect('dailyTokenBudget' in (m.autonomy ?? {})).toBe(false);+ expect(none.display).toContain('unlimited');+ });++ it('rejects unknown fields and invalid values without mutating', () => {+ const m = baseManifest();+ expect(applyBotFieldPatch(m, 'id', 'new-id').ok).toBe(false);+ expect(applyBotFieldPatch(m, 'enabled', 'true').ok).toBe(false);+ expect(applyBotFieldPatch(m, 'autonomy.maxSteps', '0').ok).toBe(false);+ expect(applyBotFieldPatch(m, 'memory.scope', 'everything').ok).toBe(false);+ expect(applyBotFieldPatch(m, 'name', '').ok).toBe(false);+ // Nothing was mutated by the rejected edits+ expect(m.id).toBe('researcher');+ expect(m.memory?.scope).toBe('own');+ });++ it('editable paths exclude identity and enable (dedicated commands exist)', () => {+ expect(EDITABLE_PATHS).not.toContain('id');+ expect(EDITABLE_PATHS).not.toContain('enabled');+ });+});\ No newline at end of filediff --git a/src/bots/edit.ts b/src/bots/edit.tsnew file mode 100644index 00000000..f76c8adb--- /dev/null+++ b/src/bots/edit.ts@@ -0,0 +1,83 @@+import type { BotManifest } from './types.js';++/**+ * Editable dot-paths on a bot manifest (`/bots edit <id> <path> <value>`).+ * Deliberately excludes `id` (identity) and `enabled` (has its own+ * enable/disable commands with halt semantics).+ */+export const EDITABLE_PATHS = [+ 'name',+ 'description',+ 'model.provider',+ 'model.model',+ 'memory.scope', // none | own | shared-read+ 'memory.allowCrossBotRecall',// comma-separated bot ids+ 'comms.canMessage', // comma-separated bot ids+ 'tools.allow', // comma-separated tool names+ 'tools.deny', // comma-separated tool names+ 'autonomy.maxConcurrent',+ 'autonomy.maxSteps',+ 'autonomy.dailyTokenBudget', // number or "none" (unlimited, default)+] as const;++export type EditResult = { ok: true; value: unknown; display: string } | { ok: false; error: string };++/**+ * Parse and apply a dot-path field edit onto a manifest (in place).+ * Value parsing: integer → number, "true"/"false" → boolean, comma list →+ * string[], "none" on dailyTokenBudget → undefined (unlimited).+ */+export function applyBotFieldPatch(manifest: BotManifest, path: string, rawValue: string): EditResult {+ const value = rawValue.trim();+ if (!(EDITABLE_PATHS as readonly string[]).includes(path)) {+ return { ok: false, error: `Unknown field "${path}". Editable: ${EDITABLE_PATHS.join(', ')}` };+ }++ const segments = path.split('.');+ const last = segments[segments.length - 1];+ let parsed: unknown = value;++ if (last === 'dailyTokenBudget') {+ if (value.toLowerCase() === 'none' || value === '') {+ parsed = undefined; // budget disabled (the default)+ } else {+ const n = parseInt(value, 10);+ if (!Number.isFinite(n) || n <= 0) return { ok: false, error: 'dailyTokenBudget must be a positive integer or "none"' };+ parsed = n;+ }+ } else if (last === 'maxSteps' || last === 'maxConcurrent') {+ const n = parseInt(value, 10);+ if (!Number.isFinite(n) || n < 1) return { ok: false, error: `${last} must be a positive integer` };+ parsed = n;+ } else if (last === 'scope') {+ if (!['none', 'own', 'shared-read'].includes(value)) {+ return { ok: false, error: 'memory.scope must be one of: none, own, shared-read' };+ }+ } else if (['allowCrossBotRecall', 'canMessage', 'allow', 'deny'].includes(last)) {+ parsed = value.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);+ } else if (last === 'name') {+ if (!value) return { ok: false, error: 'name cannot be empty' };+ }++ // Walk/set the nested path.+ let target: any = manifest;+ for (const seg of segments.slice(0, -1)) {+ if (target[seg] === undefined || target[seg] === null) target[seg] = {};+ target = target[seg];+ }+ // Removing a value (dailyTokenBudget=none): delete the key entirely.+ if (parsed === undefined) {+ delete target[last];+ } else {+ target[last] = parsed;+ }+ return {+ ok: true,+ value: parsed,+ display: parsed === undefined+ ? 'none (unlimited)'+ : Array.isArray(parsed) ? parsed.join(', ')+ : typeof parsed === 'number' ? parsed.toLocaleString('en-US')+ : String(parsed),+ };+}\ No newline at end of filediff --git a/src/core/agent.ts b/src/core/agent.tsindex 91765c98..9071df70 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -25,6 +25,7 @@ import { SkillBatcher } from '../skills/batcher.js';import type { SkillLoader } from '../skills/loader.js';import { logger } from '../utils/logger.js';import { refinePersona } from '../bots/persona-template.js';+import { applyBotFieldPatch } from '../bots/edit.js';import { CLIChannel } from '../channels/cli.js';import { TelegramChannel } from '../channels/telegram.js';import { SignalChannel } from '../channels/signal.js';@@ -493,6 +494,8 @@ export class Agent {private botManager?: import('../bots/bot-manager.js').BotManager;/** Bot awaiting a persona from the next message (post-create setup flow). */private pendingPersonaFor: string | null = null;+ /** Bot awaiting a daily token budget answer (final onboarding step). */+ private pendingBudgetFor: string | null = null;readonly programmingMode: ProgrammingMode;readonly researchMode: ResearchMode;readonly saverMode: SaverMode;@@ -1122,12 +1125,54 @@ export class Agent {bm.invalidateRuntime(botId);this.pendingPersonaFor = null;const mode = finalPersona === raw ? 'as-is' : 'as a structured template';+ await channel.send(`✍️ Persona saved ${mode}.`, `bot:${botId}`).catch(() => {});++ // Final onboarding step: the daily token budget — optional and OFF by+ // default (no cap). "suggest" fills a generous number so heavy bots are+ // protected from runaway spend without ever being strangled.+ const suggested = this.config.bots?.suggestedDailyTokenBudget ?? 5_000_000;+ this.pendingBudgetFor = botId;await channel.send(- `✍️ Persona saved ${mode} — **${manifest.name}** is ready.\nTry: \`/bot ${botId} <task>\`, or just type here and it runs as a bot task.`,+ `Final setup step — **daily token budget** for **${manifest.name}** (tokens/day):\n` ++ `• \`suggest\` — recommended, generous: ${suggested.toLocaleString()}/day\n` ++ `• a number — set your own cap\n` ++ `• \`none\` (or \`skip\`) — no cap (default)\n` ++ `Editable anytime: \`/bots budget ${botId} <tokens|suggest|none>\`. Or just type your first task — the budget stays unset.`,`bot:${botId}`,).catch(() => {});}+ /** Apply the budget answer typed after the persona step (or a later task). */+ private async applyBudgetAnswer(bm: import('../bots/bot-manager.js').BotManager, botId: string, message: string, msg: ChannelMessage): Promise<boolean> {+ const value = message.trim().toLowerCase();+ const isBudgetCommand = /^\d+$/.test(value) || ['suggest', 'none', 'skip'].includes(value);+ if (!isBudgetCommand) {+ // Not a budget answer — treat as the user's first task; budget stays unset.+ this.pendingBudgetFor = null;+ return false;+ }+ this.pendingBudgetFor = null;+ const manifest = bm.store.get(botId);+ const suggested = this.config.bots?.suggestedDailyTokenBudget ?? 5_000_000;+ let applied: string;+ if (value === 'suggest') {+ bm.store.update(botId, m => { m.autonomy = { ...m.autonomy, dailyTokenBudget: suggested }; });+ applied = `${suggested.toLocaleString()}/day`;+ } else if (value === 'none' || value === 'skip') {+ bm.store.update(botId, m => { if (m.autonomy) delete m.autonomy.dailyTokenBudget; });+ applied = 'no cap (unlimited)';+ } else {+ const n = parseInt(value, 10);+ bm.store.update(botId, m => { m.autonomy = { ...m.autonomy, dailyTokenBudget: n }; });+ applied = `${n.toLocaleString()}/day`;+ }+ bm.invalidateRuntime(botId);+ const channel = this.channels.getChannelForMessage(msg);+ await channel?.send(`💰 Budget for **${manifest?.name ?? botId}**: ${applied}. When the cap is hit the bot pauses until the next day — never killed.`, `bot:${botId}`)+ .catch(() => {});+ return true;+ }+/** Enqueue a bot turn from any channel, with ack + reply-back routing. */private async dispatchToBot(botId: string, message: string, msg: ChannelMessage): Promise<void> {const bm = this.botManager;@@ -1135,6 +1180,17 @@ export class Agent {const channel = this.channels.getChannelForMessage(msg);if (!channel) return;+ // Budget step runs after the persona step: the next message answers it+ // if it looks like one; anything else is the user's first real task.+ if (this.pendingBudgetFor) {+ if (this.pendingBudgetFor !== botId) {+ this.pendingBudgetFor = null;+ } else {+ const handled = await this.applyBudgetAnswer(bm, botId, message, msg);+ if (handled) return;+ }+ }+// Post-create persona setup: the first message typed into the new bot's// chat becomes its persona instead of a task (send /skip to keep the// template). Any dispatch to a different bot cancels the pending setup.@@ -1319,6 +1375,87 @@ export class Agent {return;}+ if (action === 'budget') {+ const target = parts[1]?.toLowerCase();+ const value = (parts[2] ?? '').toLowerCase();+ if (!target || !value) {+ const suggested = this.config.bots?.suggestedDailyTokenBudget ?? 5_000_000;+ await channel.send(`Usage: \`/bots budget <id> <tokens|suggest|none>\` — suggest = ${suggested.toLocaleString()}/day, none = no cap (default).`, channelId);+ return;+ }+ try {+ bm.store.update(target, m => {+ if (value === 'none') { if (m.autonomy) delete m.autonomy.dailyTokenBudget; }+ else if (value === 'suggest') { m.autonomy = { ...m.autonomy, dailyTokenBudget: this.config.bots?.suggestedDailyTokenBudget ?? 5_000_000 }; }+ else {+ const n = parseInt(value, 10);+ if (!Number.isFinite(n) || n <= 0) throw new Error('budget must be a positive integer, "suggest", or "none"');+ m.autonomy = { ...m.autonomy, dailyTokenBudget: n };+ }+ });+ bm.invalidateRuntime(target);+ const m = bm.store.get(target);+ const applied = m?.autonomy?.dailyTokenBudget ? `${m.autonomy.dailyTokenBudget.toLocaleString()}/day` : 'none (unlimited)';+ await channel.send(`💰 Budget for **${target}**: ${applied}. Hit the cap → the bot pauses until the next day, never killed.`, channelId);+ } catch (err: any) {+ await channel.send(`Failed: ${err?.message}`, channelId);+ }+ return;+ }++ if (action === 'edit') {+ const target = parts[1]?.toLowerCase();+ const path = parts[2];+ const value = parts.slice(3).join(' ');+ if (!target || !path || !value) {+ await channel.send('Usage: `/bots edit <id> <field> <value>`\nEditable fields: name, description, model.provider, model.model, memory.scope, memory.allowCrossBotRecall, comms.canMessage, tools.allow, tools.deny, autonomy.maxConcurrent, autonomy.maxSteps, autonomy.dailyTokenBudget', channelId);+ return;+ }+ try {+ const manifest = bm.store.get(target);+ if (!manifest) throw new Error(`Bot "${target}" does not exist`);+ const result = applyBotFieldPatch(manifest, path, value);+ if (!result.ok) {+ await channel.send(`⚠ ${result.error}`, channelId);+ return;+ }+ bm.store.save(manifest);+ bm.invalidateRuntime(target);+ await channel.send(`✏️ **${target}**.${path} = ${result.display}`, channelId);+ } catch (err: any) {+ await channel.send(`Failed: ${err?.message}`, channelId);+ }+ return;+ }++ if (action === 'delete') {+ const target = parts[1]?.toLowerCase();+ const confirmed = parts[2]?.toLowerCase() === 'confirm';+ if (!target || !bm.store.exists(target)) {+ await channel.send('Usage: `/bots delete <id> confirm` — removes the profile dir, halts any running turn, and dead-letters pending jobs. This cannot be undone.', channelId);+ return;+ }+ if (!confirmed && typeof (channel as any).askToContinue === 'function') {+ const proceed = await (channel as any).askToContinue(`Delete bot **${target}** and its profile (persona, memory links, journal)? This cannot be undone.`);+ if (!proceed) {+ await channel.send('Deletion cancelled.', channelId);+ return;+ }+ } else if (!confirmed) {+ await channel.send(`Type \`/bots delete ${target} confirm\` to permanently delete.`, channelId);+ return;+ }+ try {+ await bm.halt(target);+ bm.store.delete(target);+ bm.invalidateRuntime(target);+ await channel.send(`🗑 Bot **${target}** deleted (running turn halted; its profile directory is gone).`, channelId);+ } catch (err: any) {+ await channel.send(`Failed: ${err?.message}`, channelId);+ }+ return;+ }+if (action === 'stop' || action === 'pause') {const target = parts[1]?.toLowerCase();if (!target) {@@ -1426,13 +1563,16 @@ export class Agent {'`/bots open <id>` — open a bot chat (transcript swaps to the bot thread)\n' +'`/bots create <id> "Name" "Description"` — onboard a bot\n' +'`/bot <id> <message>` — message a bot from any channel\n' +- '`/bots send <id> <message>` — message a bot\n' ++ '`/bots persona <id> <text>` — set/replace its character (with template conversion)\n' ++ '`/bots budget <id> <tokens|suggest|none>` — daily token budget (none = no cap, default)\n' ++ '`/bots edit <id> <field> <value>` — edit any config field anytime\n' +'`/bots journal <id>` — recent runs\n' +'`/bots inbox <id>` — pending bot-to-bot mail\n' +'`/bots dlq` — dead-lettered jobs\n' +'`/bots replay <botId> <jobId>` — re-run a dead-lettered job\n' +'`/bots storage` — disk usage\n' +- '`/bots enable|disable|stop <id>` — control',+ '`/bots enable|disable|stop <id>` — control (disable = pause, enable = resume)\n' ++ '`/bots delete <id> confirm` — permanently delete',channelId,);}diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 375c0461..f742e50f 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -132,6 +132,10 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC'/bots open ','/bots create ','/bots send ',+ '/bots persona ',+ '/bots budget ',+ '/bots edit ',+ '/bots delete ','/bots journal ','/bots inbox ','/bots storage',diff --git a/src/utils/config.ts b/src/utils/config.tsindex ba020b6e..03295233 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -206,6 +206,8 @@ export interface MercuryConfig {autoSkill?: {enabled?: boolean;};+ /** Suggested per-bot daily token budget offered during onboarding. */+ suggestedDailyTokenBudget?: number;retention: {transcriptRuns: number;journalRotateBytes: number;@@ -468,6 +470,7 @@ export function getDefaultConfig(): MercuryConfig {autoSkill: {enabled: getEnvBool('BOTS_AUTO_SKILL', false),},+ suggestedDailyTokenBudget: getEnvNum('BOTS_SUGGESTED_DAILY_TOKEN_BUDGET', 5_000_000),retention: {transcriptRuns: getEnvNum('BOTS_RETENTION_TRANSCRIPT_RUNS', 50),journalRotateBytes: getEnvNum('BOTS_JOURNAL_ROTATE_BYTES', 5 * 1024 * 1024),