import type { Message, Tool } from '../types.js'; import { buildBaseSystemPrompt } from './system.js'; /** Keep exactly one persistent system message at history[0]. */ export function upsertStableSystemMessage( history: Message[], content: string, ): Message { const previous = history.find( (message) => message.role === 'system' && message._ephemeral !== true, ); for (let index = history.length - 1; index >= 0; index--) { const message = history[index]; if (message?.role === 'system' && message._ephemeral !== true) { history.splice(index, 1); } } const stable: Message = { ...(previous ?? { role: 'system' }), content }; delete (stable as { _ephemeral?: true })._ephemeral; history.unshift(stable); return stable; } export async function refreshStableSystemPrompt( history: Message[], cwd: string, tools: Tool[], ): Promise { return upsertStableSystemMessage( history, await buildBaseSystemPrompt(cwd, tools), ); }