@@ -18,10 +18,10 @@ import {
1818
1919 import { getContextWindow, resolveModel } from "../llm-api/providers.ts";
2020 import { type CoreMessage, runTurn } from "../llm-api/turn.ts";
21-import type { Message, ToolDef } from "../llm-api/types.ts";
21+import type { ToolDef } from "../llm-api/types.ts";
2222 import { connectMcpServer } from "../mcp/client.ts";
23+
2324 import {
24- addPromptHistory,
2525 deleteLastTurn,
2626 getConfigDir,
2727 getMaxTurnIndex,
@@ -29,6 +29,7 @@ import {
2929 saveMessages,
3030 setPreferredModel,
3131 } from "../session/db.ts";
32+
3233 import {
3334 type ActiveSession,
3435 newSession,
@@ -105,47 +106,6 @@ Guidelines:
105106 return prompt;
106107 }
107108
108-// ─── DB messages → raw ModelMessages (for session resume) ────────────────────
109-// On resume, the DB stores text-only messages. Tool-call/result parts are
110-// intentionally not reconstructed because the complex output/input shapes are
111-// opaque. Any tool-role entries are kept as plain text and treated as assistant
112-// messages for resume context.
113-function isTextPart(part: unknown): part is { type: "text"; text: string } {
114- return (
115- typeof part === "object" &&
116- part !== null &&
117- (part as { type?: unknown }).type === "text" &&
118- typeof (part as { text?: unknown }).text === "string"
119- );
120-}
121-
122-function resumeRole(role: Message["role"]): "user" | "assistant" {
123- // Tool-role entries are stored as plain text; treat them as assistant
124- // messages when rebuilding context for the model.
125- return role === "user" ? "user" : "assistant";
126-}
127-
128-function dbMessagesToCore(messages: Message[]): CoreMessage[] {
129- return messages.map((m): CoreMessage => {
130- const role = resumeRole(m.role);
131- if (typeof m.content === "string") {
132- return { role, content: m.content };
133- }
134- if (Array.isArray(m.content)) {
135- // Filter to text-only parts to avoid feeding malformed tool parts
136- const textParts = m.content.filter(isTextPart);
137- if (textParts.length > 0) {
138- return {
139- role,
140- content: textParts,
141- };
142- }
143- return { role, content: "" };
144- }
145- return { role, content: String(m.content) };
146- });
147-}
148-
149109 // ─── Shell passthrough (! prefix) ─────────────────────────────────────────────
150110
151111 async function runShellPassthrough(
@@ -204,16 +164,16 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
204164 let turnIndex = getMaxTurnIndex(session.id) + 1;
205165
206166 // Raw AI SDK ModelMessage history — fed directly to streamText each turn.
207- // This is kept separate from session.messages (which is DB-persisted text)
208- // to avoid lossy round-trips through our internal Message type.
209- const coreHistory: CoreMessage[] = dbMessagesToCore(session.messages);
167+ // This is kept separate from session.messages (DB-persisted CoreMessages)
168+ // so we can trim or rebuild without mutating the in-memory DB copy.
169+ const coreHistory: CoreMessage[] = [...session.messages];
210170
211171 // Subagent runner (recursive) — depth prevents infinite recursion
212172 const runSubagent = async (
213173 prompt: string,
214174 depth = 0,
215175 ): Promise<{ result: string; inputTokens: number; outputTokens: number }> => {
216- const subMessages: Message[] = [{ role: "user", content: prompt }];
176+ const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
217177 const subTools = buildToolSet({
218178 cwd,
219179 depth,
@@ -231,7 +191,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
231191
232192 const events = runTurn({
233193 model: subLlm,
234- messages: dbMessagesToCore(subMessages),
194+ messages: subMessages,
235195 tools: subTools,
236196 systemPrompt,
237197 });
@@ -394,13 +354,13 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
394354 const out = await runShellPassthrough(input.command, cwd);
395355 if (out) {
396356 const thisTurn = turnIndex++;
397- const msg: Message = {
357+ const msg: CoreMessage = {
398358 role: "user",
399359 content: `Shell output of \`${input.command}\`:\n\`\`\`\n${out}\n\`\`\``,
400360 };
401361 session.messages.push(msg);
402362 saveMessages(session.id, [msg], thisTurn);
403- coreHistory.push({ role: "user", content: String(msg.content) });
363+ coreHistory.push(msg);
404364 }
405365 continue;
406366 }
@@ -419,17 +379,13 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
419379 // Capture turn index for this turn (user + response share the same index)
420380 const thisTurn = turnIndex++;
421381
422- const userMsg: Message = { role: "user", content: resolvedText };
423- session.messages.push(userMsg);
424- saveMessages(session.id, [userMsg], thisTurn);
425-
426- // Also push into coreHistory as a raw ModelMessage.
427- // In plan mode, append the system-message suffix so the model knows it
428- // should only read/explore — not execute write operations.
429382 const coreContent = planMode
430383 ? `${resolvedText}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
431384 : resolvedText;
432- coreHistory.push({ role: "user", content: coreContent });
385+ const userMsg: CoreMessage = { role: "user", content: coreContent };
386+ session.messages.push(userMsg);
387+ saveMessages(session.id, [userMsg], thisTurn);
388+ coreHistory.push(userMsg);
433389
434390 const llm = resolveModel(currentModel);
435391 const systemPrompt = buildSystemPrompt(cwd);
@@ -456,26 +412,8 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
456412 // so subsequent turns have the correct input/output fields.
457413 if (newMessages.length > 0) {
458414 coreHistory.push(...newMessages);
459- // For DB persistence, store a simplified version (text only is enough
460- // for session resume context — tool call parts are not reconstructed).
461- const dbMsgs: Message[] = newMessages.map((m) => {
462- const role = m.role as Message["role"];
463- const content = m.content;
464- if (typeof content === "string") {
465- return { role, content };
466- }
467- if (Array.isArray(content)) {
468- // Collapse to text content only for DB storage
469- const text = content
470- .filter(isTextPart)
471- .map((p) => p.text)
472- .join("");
473- return { role, content: text };
474- }
475- return { role, content: String(content) };
476- });
477- session.messages.push(...dbMsgs);
478- saveMessages(session.id, dbMsgs, thisTurn);
415+ session.messages.push(...newMessages);
416+ saveMessages(session.id, newMessages, thisTurn);
479417 }
480418
481419 totalIn += inputTokens;