Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): "convert to template" persona step before writing to disk

Salman Qureshi7b7a36a8bf80
diff --git a/src/bots/persona-template.test.ts b/src/bots/persona-template.test.ts
new file mode 100644
index 00000000..5db33ed9
--- /dev/null
+++ b/src/bots/persona-template.test.ts
@@ -0,0 +1,69 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { refinePersona } from './persona-template.js';
+
+const scriptedResponses: string[] = [];
+
+function stubProvider() {
+ return {
+ name: 'stub',
+ model: 'stub-model',
+ generateText: async () => ({
+ text: scriptedResponses.shift() ?? '',
+ inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub', provider: 'stub',
+ }),
+ streamText: async function* () { yield { text: '', done: true }; },
+ isAvailable: () => true,
+ getModelInstance: () => ({}),
+ getModel: () => 'stub-model',
+ } as any;
+}
+
+const goodTemplate = `# Research
+
+A focused deep-research specialist.
+
+## Character
+
+Curious but skeptical curator; verifies before recommending.
+
+## Standing instructions
+
+- Verify repos are active before recommending
+- Never recommend unverified sources
+- Prefer depth over volume
+
+## Output
+
+Lead with a one-line summary, then compact sections.
+`;
+
+describe('refinePersona (convert to template)', () => {
+ beforeEach(() => {
+ scriptedResponses.length = 0;
+ });
+
+ it('restructures free-form persona text into the template shape', async () => {
+ scriptedResponses.push(goodTemplate);
+ const result = await refinePersona(
+ 'I want a research bot that verifies repos are active before recommending, never recommends unverified stuff, and likes depth over volume. Skeptical tone.',
+ 'Research',
+ stubProvider(),
+ );
+ expect(result).toContain('# Research');
+ expect(result).toContain('## Standing instructions');
+ expect(result).toContain('verifies');
+ expect(result).toContain('## Output');
+ });
+
+ it('returns null for unusable output (missing sections, too short, code fences)', async () => {
+ scriptedResponses.push('Sure! Here is your persona.'); // no structure
+ expect(await refinePersona('raw', 'R', stubProvider())).toBeNull();
+ scriptedResponses.push('# R'); // too short
+ expect(await refinePersona('raw', 'R', stubProvider())).toBeNull();
+ });
+
+ it('is non-fatal when the provider throws — raw persona is kept instead', async () => {
+ const throwing = { ...stubProvider(), generateText: async () => { throw new Error('HTTP 500'); } } as any;
+ expect(await refinePersona('raw persona text', 'R', throwing)).toBeNull();
+ });
+});
\ No newline at end of file
diff --git a/src/bots/persona-template.ts b/src/bots/persona-template.ts
new file mode 100644
index 00000000..6f3b0f96
--- /dev/null
+++ b/src/bots/persona-template.ts
@@ -0,0 +1,59 @@
+import type { BaseProvider } from '../providers/base.js';
+import { logger } from '../utils/logger.js';
+
+export interface PersonaRefinement {
+ /** Refined persona (template format), or null when unusable. */
+ text: string | null;
+}
+
+/**
+ * "Convert to template" — turn a user's free-form persona text into the
+ * structured format that produces good bot behavior (Character / Standing
+ * instructions / Output, the same sections as the onboarding template).
+ *
+ * Hard rule: refinement only RESTRUCTURES. It may not add capabilities,
+ * permissions, or instructions the user didn't give — an LLM quietly
+ * widening a bot's mandate would be a silent privilege grant.
+ */
+export async function refinePersona(raw: string, botName: string, provider: BaseProvider): Promise<string | null> {
+ try {
+ const result = await provider.generateText(
+ `Convert this free-form bot persona into a structured persona file. Bot name: ${botName}.
+
+User's persona (preserve every explicit requirement, restructure only):
+"""
+${raw.slice(0, 4000)}
+"""
+
+Output ONLY markdown, in exactly this shape:
+
+# ${botName}
+
+<one-sentence identity summary>
+
+## Character
+
+<personality, voice, expertise boundaries>
+
+## Standing instructions
+
+- <each behavioral requirement as a bullet, including every rule the user wrote>
+
+## Output
+
+<output format expectations>
+
+Rules: never invent new capabilities, tools, or permissions; keep the bot's stated restrictions verbatim in meaning; 100-300 words; no preamble, no code fences.`,
+ 'You write precise bot persona files. Restructure only; never add or remove requirements.',
+ );
+ const text = (result.text ?? '').trim();
+ if (!text.startsWith('#') || text.length < 80 || text.length > 5000 || !text.includes('##')) {
+ logger.debug({ botName }, 'Persona refinement produced unusable output — keeping raw');
+ return null;
+ }
+ return text.endsWith('\n') ? text : text + '\n';
+ } catch (err: any) {
+ logger.warn({ botName, err: err?.message }, 'Persona refinement failed — keeping raw persona');
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 6a2f27ab..91765c98 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -24,6 +24,7 @@ import { BackgroundTaskManager } from './background-tasks.js';
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 { CLIChannel } from '../channels/cli.js';
import { TelegramChannel } from '../channels/telegram.js';
import { SignalChannel } from '../channels/signal.js';
@@ -1083,6 +1084,50 @@ export class Agent {
await channel.send('Agent is busy. Programming mode changes will be available after current task completes.', msg.channelId);
}
+ /**
+ * Persona finalization: before anything is written to persona.md, offer
+ * "Convert to template" (LLM-restructured, restructure-only) vs save
+ * as-is. TUI gets a real choice prompt; other channels default to
+ * template with graceful raw fallback on provider failure.
+ */
+ private async finalizePersona(bm: import('../bots/bot-manager.js').BotManager, botId: string, raw: string, msg: ChannelMessage): Promise<void> {
+ const channel = this.channels.getChannelForMessage(msg);
+ const manifest = bm.store.get(botId);
+ if (!channel || !manifest) return;
+ const channelType = msg.channelType as any;
+
+ let choice = 'template';
+ try {
+ choice = await this.presentChoice(
+ `Persona for **${manifest.name}** — how should it be saved?`,
+ ['Convert to template (recommended — structured, precise)', 'Save as-is'],
+ msg.channelId,
+ channelType,
+ );
+ } catch {
+ choice = 'template';
+ }
+
+ let finalPersona = raw;
+ if (choice.startsWith('Convert')) {
+ const refined = await refinePersona(raw, manifest.name, this.providers.getDefault());
+ if (refined) {
+ finalPersona = refined;
+ } else {
+ await channel.send('⚠ Template conversion unavailable (provider) — saving your text as-is. Edit `persona.md` anytime.', msg.channelId).catch(() => {});
+ }
+ }
+
+ bm.store.writePersona(botId, finalPersona.endsWith('\n') ? finalPersona : finalPersona + '\n');
+ bm.invalidateRuntime(botId);
+ this.pendingPersonaFor = null;
+ const mode = finalPersona === raw ? 'as-is' : 'as a structured template';
+ 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.`,
+ `bot:${botId}`,
+ ).catch(() => {});
+ }
+
/** 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;
@@ -1102,13 +1147,8 @@ export class Agent {
.catch(() => {});
return;
} else {
- bm.store.writePersona(botId, message.trim() + '\n');
- bm.invalidateRuntime(botId);
- this.pendingPersonaFor = null;
- await channel.send(
- `✍️ Persona set — **${bm.store.get(botId)?.name ?? botId}** is ready.\nTry: \`/bot ${botId} <task>\`, or just type here and it runs as a bot task.`,
- `bot:${botId}`,
- ).catch(() => {});
+ // Offer the "convert to template" step before anything hits disk.
+ await this.finalizePersona(bm, botId, message.trim(), msg);
return;
}
}
@@ -1244,10 +1284,7 @@ export class Agent {
await channel.send('Usage: `/bots persona <id> <full persona text in one message>` — or open the bot chat (`/bots open <id>`) and type `/persona <text>`.', channelId);
return;
}
- bm.store.writePersona(target, personaText + '\n');
- bm.invalidateRuntime(target);
- this.pendingPersonaFor = null;
- await channel.send(`✍️ Persona updated for **${target}** — the next run uses it.`, channelId);
+ await this.finalizePersona(bm, target, personaText, msg);
return;
}