import type { PluginEvent } from '../plugins/pluginApi.js'; import type { LoopEvent, Message } from '../types.js'; import { createPublicTextStream } from '../ui/publicText.js'; type LocalRow = Extract; /** A slash command can expand into a different model input, or never call the * model at all. Keep the UI transcript independent of that routing decision. */ export function commandRequest(input: string, userMessageId: string): LocalRow { return { role: 'system', _ephemeral: true, _uiProgress: true, id: `command:${userMessageId}`, timestamp: Date.now(), content: input, commandDisplay: { kind: 'request', userMessageId } }; } /** Some deterministic plugins emit only text + turn_done. Model turns and * workflows own their own drafts, echoes, and committed history. Never promote * their preview (including a replayed echo) into a second or invented answer. */ export function captureCommandReply(userMessageId: string) { const stream = createPublicTextStream(); const chunks: string[] = []; let standalone = true; let resultNumber = 0; const result = (content: string): LocalRow => ({ role: 'system', _ephemeral: true, _uiProgress: true, id: `command:${userMessageId}:result:${++resultNumber}`, timestamp: Date.now(), content, commandDisplay: { kind: 'result' }, }); return (event: LoopEvent | PluginEvent): LocalRow | undefined => { if (event.type === 'text' && event.commandResult === true && typeof event.delta === 'string') { standalone = false; chunks.length = 0; stream.reset(); const content = stream.append(event.delta) + stream.finish(); return content.trim() ? result(content) : undefined; } if (!standalone) return; switch (event.type) { case 'text': if (typeof event.delta === 'string') chunks.push(stream.append(event.delta)); return; case 'plugin_progress': case 'warning': return; case 'turn_done': { standalone = false; const content = chunks.join('') + stream.finish(); if (!content.trim() || event.completionStatus === 'no_answer') return; return result(content); } default: standalone = false; chunks.length = 0; stream.reset(); } }; } /** Display projection shared by hosts. Never mutate the model's actual input. */ export function transcriptRows(history: Message[]): Message[] { const ids = new Set(); const users = new Map>(); for (const m of history) { if (m.role === 'user' && m.id) users.set(m.id, m); if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request') ids.add(m.commandDisplay.userMessageId); } if (!ids.size) return history; return history.flatMap((m): Message[] => { if (m.role === 'user' && m.id && ids.has(m.id)) return []; if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request') { const requestId = m.commandDisplay.userMessageId; const original = users.get(requestId); return [{ ...original, role: 'user', content: m.content, timestamp: m.timestamp, id: requestId }]; } return [m]; }); }