/** * Prompt template storage and variable substitution. */ import { loadJson, saveJson } from '../../lib/storage.ts' import type { PromptContext, PromptTemplate } from './types.ts' const TEMPLATES_KEY = 'factory:signals:templates:v1' type TemplateStore = { version: 1 templates: Record } function emptyStore(): TemplateStore { return { version: 1, templates: {} } } export const BUILTIN_TEMPLATES: Record = { 'default-board-card': { id: 'default-board-card', name: 'Default board card', template: '{{title}}\n\nSource: {{source}} ({{sourceId}})\nProject: {{projectId}}\nSeverity: {{severity}}\nLabels: {{labels}}\n\n{{body}}', variables: ['title', 'body', 'source', 'sourceId', 'projectId', 'severity', 'labels'], }, 'default-grok-wake': { id: 'default-grok-wake', name: 'Default Grok Bot wake', template: 'The Kody factory signals system routed an inbound signal to you.\n\n' + 'Signal: {{title}}\n' + 'Source: {{source}} ({{sourceId}})\n' + 'Project: {{projectId}}\n' + 'Severity: {{severity}}\n' + 'Signal id: {{signalId}}\n\n' + '{{body}}', variables: ['title', 'body', 'source', 'sourceId', 'projectId', 'severity', 'signalId'], }, } export async function getTemplate(id: string): Promise { if (BUILTIN_TEMPLATES[id]) return BUILTIN_TEMPLATES[id] const store = await loadJson(TEMPLATES_KEY, emptyStore()) return store.templates[id] ?? null } export async function listTemplates(): Promise { const store = await loadJson(TEMPLATES_KEY, emptyStore()) return [...Object.values(BUILTIN_TEMPLATES), ...Object.values(store.templates)] } export async function saveTemplate(template: PromptTemplate): Promise { const store = await loadJson(TEMPLATES_KEY, emptyStore()) store.templates[template.id] = template await saveJson(TEMPLATES_KEY, store) } export async function deleteTemplate(id: string): Promise { if (BUILTIN_TEMPLATES[id]) throw new Error('Cannot delete a built-in template') const store = await loadJson(TEMPLATES_KEY, emptyStore()) delete store.templates[id] await saveJson(TEMPLATES_KEY, store) } export function renderTemplate(template: string, ctx: PromptContext): string { return template.replace(/\{\{(\w+)\}\}/g, (_, key: string) => { if (key === 'labels') return ctx.labels.join(', ') return String((ctx as Record)[key] ?? '') }) }