Skip to content

Commit f5b25d8

Browse files
committed
refactor(agents): fold assistant string normalization into transcript ingest
1 parent b2c507c commit f5b25d8

9 files changed

Lines changed: 124 additions & 27 deletions

File tree

‎src/agents/cli-runner/session-history.test.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,11 @@ function requireRecord(value: unknown, label: string): Record<string, unknown> {
7575
return value as Record<string, unknown>;
7676
}
7777

78-
function expectMessageFields(value: unknown, expected: { role: string; content?: string }) {
78+
function expectMessageFields(value: unknown, expected: { role: string; content?: unknown }) {
7979
const message = requireRecord(value, "message");
8080
expect(message.role).toBe(expected.role);
8181
if ("content" in expected) {
82-
expect(message.content).toBe(expected.content);
82+
expect(message.content).toEqual(expected.content);
8383
}
8484
}
8585

@@ -256,7 +256,10 @@ describe("loadCliSessionHistoryMessages", () => {
256256
});
257257
expect(history).toHaveLength(2);
258258
expectMessageFields(history[0], { role: "user", content: "active root" });
259-
expectMessageFields(history[1], { role: "assistant", content: "active tail" });
259+
expectMessageFields(history[1], {
260+
role: "assistant",
261+
content: [{ type: "text", text: "active tail" }],
262+
});
260263
});
261264
} finally {
262265
fs.rmSync(stateDir, { recursive: true, force: true });
@@ -369,7 +372,10 @@ describe("loadCliSessionHistoryMessages", () => {
369372
content: "tail custom context",
370373
});
371374
expectBranchSummary(history[2], "tail branch context");
372-
expectMessageFields(history[3], { role: "assistant", content: "tail answer" });
375+
expectMessageFields(history[3], {
376+
role: "assistant",
377+
content: [{ type: "text", text: "tail answer" }],
378+
});
373379
});
374380
} finally {
375381
fs.rmSync(stateDir, { recursive: true, force: true });

‎src/agents/embedded-agent-runner/transcript-file-state.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ describe("readTranscriptFileState", () => {
192192
expect(state.getEntries().map((entry) => entry.id)).toEqual(["user-1", "assistant-string"]);
193193
expect(state.buildSessionContext().messages).toMatchObject([
194194
{ role: "user", content: "prompt" },
195-
{ role: "assistant", content: "legacy reply" },
195+
{ role: "assistant", content: [{ type: "text", text: "legacy reply" }] },
196196
]);
197197
});
198198

@@ -1185,7 +1185,7 @@ describe("readTranscriptFileState", () => {
11851185

11861186
expect(state.buildSessionContext().messages).toMatchObject([
11871187
{ role: "user", content: "rewritten question" },
1188-
{ role: "assistant", content: "answer" },
1188+
{ role: "assistant", content: [{ type: "text", text: "answer" }] },
11891189
]);
11901190
});
11911191

‎src/agents/sessions/session-manager.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ describe("SessionManager.open", () => {
5858
timestamp: "2026-05-27T00:00:02.000Z",
5959
message: { role: "assistant", content: "important answer" },
6060
};
61+
const normalizedAssistantEntry = {
62+
...assistantEntry,
63+
message: { role: "assistant", content: [{ type: "text", text: "important answer" }] },
64+
};
6165
const originalTranscript =
6266
[
6367
JSON.stringify(originalHeader).slice(0, 30),
@@ -71,8 +75,8 @@ describe("SessionManager.open", () => {
7175

7276
const sessionManager = SessionManager.open(sessionFile, dir, "/tmp/task-repo");
7377

74-
expect(sessionManager.getEntries()).toEqual([userEntry, assistantEntry]);
75-
expect(sessionManager.getChildren(userEntry.id)).toEqual([assistantEntry]);
78+
expect(sessionManager.getEntries()).toEqual([userEntry, normalizedAssistantEntry]);
79+
expect(sessionManager.getChildren(userEntry.id)).toEqual([normalizedAssistantEntry]);
7680
expect(await fs.readFile(sessionFile, "utf8")).toContain("important question");
7781
expect(await fs.readFile(sessionFile, "utf8")).toContain("important answer");
7882
await expect(fs.readFile(sessionFile, "utf8")).resolves.not.toBe(originalTranscript);
@@ -1432,6 +1436,10 @@ describe("SessionManager.open", () => {
14321436
timestamp: "2026-06-04T00:00:01.000Z",
14331437
message: { role: "assistant", content: "carried context" },
14341438
};
1439+
const normalizedAssistantEntry = {
1440+
...assistantEntry,
1441+
message: { role: "assistant", content: [{ type: "text", text: "carried context" }] },
1442+
};
14351443
await fs.writeFile(
14361444
sessionFile,
14371445
[
@@ -1456,7 +1464,7 @@ describe("SessionManager.open", () => {
14561464
.split("\n")
14571465
.map((line) => JSON.parse(line) as unknown);
14581466
expect(records).toContainEqual(metadata);
1459-
expect(sessionManager.getEntries()).toEqual([assistantEntry]);
1467+
expect(sessionManager.getEntries()).toEqual([normalizedAssistantEntry]);
14601468
});
14611469

14621470
it("bridges parent-linked opaque rows without exposing them as session entries", async () => {

‎src/agents/sessions/session-manager.tool-result-replay.test.ts‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,52 @@ async function writeSessionWithToolResultContent(
9898
await fs.writeFile(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`);
9999
}
100100

101+
async function writeSessionWithAssistantContent(
102+
sessionFile: string,
103+
content: unknown,
104+
): Promise<void> {
105+
const entries = [
106+
{
107+
type: "session",
108+
version: 3,
109+
id: "string-assistant-session",
110+
timestamp: "2026-07-01T00:00:00.000Z",
111+
cwd: "/tmp/tool-result-replay",
112+
},
113+
{
114+
type: "message",
115+
id: "user-1",
116+
parentId: null,
117+
timestamp: "2026-07-01T00:00:01.000Z",
118+
message: { role: "user", content: "say hello", timestamp: 1 },
119+
},
120+
{
121+
type: "message",
122+
id: "assistant-1",
123+
parentId: "user-1",
124+
timestamp: "2026-07-01T00:00:02.000Z",
125+
message: {
126+
role: "assistant",
127+
provider: "anthropic",
128+
api: "anthropic-messages",
129+
model: "claude-sonnet-4-6",
130+
stopReason: "stop",
131+
timestamp: 2,
132+
usage: {
133+
input: 0,
134+
output: 0,
135+
cacheRead: 0,
136+
cacheWrite: 0,
137+
totalTokens: 0,
138+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
139+
},
140+
content,
141+
},
142+
},
143+
];
144+
await fs.writeFile(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`);
145+
}
146+
101147
describe("SessionManager tool-result replay", () => {
102148
afterEach(async () => {
103149
await Promise.all(
@@ -120,6 +166,43 @@ describe("SessionManager tool-result replay", () => {
120166
expect(toolResult.content).toEqual([{ type: "text", text: "lookup result text" }]);
121167
});
122168

169+
it("replays string assistant JSONL content as Anthropic assistant text", async () => {
170+
const dir = await makeTempDir();
171+
const sessionFile = path.join(dir, "session.jsonl");
172+
await writeSessionWithAssistantContent(sessionFile, "assistant replay text");
173+
const context = SessionManager.open(
174+
sessionFile,
175+
dir,
176+
"/tmp/tool-result-replay",
177+
).buildSessionContext();
178+
const assistant = context.messages.find((message) => message.role === "assistant");
179+
if (!assistant || assistant.role !== "assistant") {
180+
throw new Error("assistant message missing");
181+
}
182+
expect(assistant.content).toEqual([{ type: "text", text: "assistant replay text" }]);
183+
184+
let capturedPayload: unknown;
185+
const stream = streamAnthropic(makeAnthropicModel(), toLlmContext(context), {
186+
apiKey: "sk-ant-provider",
187+
onPayload: (payload) => {
188+
capturedPayload = payload;
189+
throw new Error("stop before network");
190+
},
191+
});
192+
193+
await stream.result();
194+
195+
const payload = capturedPayload as {
196+
messages: Array<{
197+
role: string;
198+
content: string | Array<{ type?: unknown; text?: unknown }>;
199+
}>;
200+
};
201+
const assistantPayload = payload.messages.find((message) => message.role === "assistant");
202+
203+
expect(assistantPayload?.content).toEqual([{ type: "text", text: "assistant replay text" }]);
204+
});
205+
123206
it("replays string tool-result JSONL content as Anthropic tool text", async () => {
124207
const dir = await makeTempDir();
125208
const sessionFile = path.join(dir, "session.jsonl");

‎src/agents/sessions/session-manager.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -960,15 +960,15 @@ function normalizeLoadedFileEntry(entry: FileEntry): FileEntry {
960960
// Persisted JSONL is untrusted: shapes may predate the current Message type,
961961
// so normalize through a record view instead of the declared union.
962962
const message: Record<string, unknown> = entry.message;
963-
if (message.role !== "toolResult") {
964-
return entry;
965-
}
966-
// Replayed JSONL can carry string or single-record tool results while
967-
// downstream providers require block arrays. Without this, strings replay as
968-
// empty output and records hit non-array replay assumptions.
969-
if (typeof message.content === "string") {
963+
// Replayed JSONL can carry legacy string assistant/toolResult content while
964+
// downstream providers require block arrays. Single-record tool results need
965+
// the same ingress repair before replay reaches provider conversion.
966+
if (
967+
(message.role === "assistant" || message.role === "toolResult") &&
968+
typeof message.content === "string"
969+
) {
970970
message.content = [{ type: "text", text: message.content }];
971-
} else if (isJsonRecord(message.content)) {
971+
} else if (message.role === "toolResult" && isJsonRecord(message.content)) {
972972
message.content = [message.content];
973973
}
974974
return entry;

‎src/auto-reply/reply/session-fork.runtime.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,7 @@ describe("forkSessionFromParentRuntime", () => {
439439
expect(records.at(-1)).toMatchObject({ type: "message", parentId: "plugin-metadata" });
440440
expect(records.at(-1)).not.toHaveProperty("appendMode");
441441
expect(reopened.buildSessionContext().messages).toMatchObject([
442-
{ role: "assistant", content: "active root" },
442+
{ role: "assistant", content: [{ type: "text", text: "active root" }] },
443443
{ role: "user", content: "continued" },
444444
]);
445445
});

‎src/gateway/session-compaction-checkpoints.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -789,7 +789,7 @@ describe("session-compaction-checkpoints", () => {
789789
const messages = SessionManager.open(forked.sessionFile, dir).buildSessionContext().messages;
790790
expect(messages.map((message) => (message as { content?: unknown }).content)).toEqual([
791791
"legacy first",
792-
"legacy second",
792+
[{ type: "text", text: "legacy second" }],
793793
]);
794794
});
795795

‎src/gateway/session-utils.fs.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1788,7 +1788,7 @@ describe("readSessionMessages", () => {
17881788
})),
17891789
).toEqual([
17901790
{ role: "user", text: "hello" },
1791-
{ role: "assistant", text: "hi" },
1791+
{ role: "assistant", text: [{ type: "text", text: "hi" }] },
17921792
{ role: "user", text: [{ type: "text", text: "Blocked by HITL test hook." }] },
17931793
]);
17941794
expect(JSON.stringify(out)).not.toContain("[hitl:block] hello");

‎src/llm/providers/transform-messages.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,13 @@ export function transformMessages<TApi extends Api>(
117117
assistantMsg.api === model.api &&
118118
assistantMsg.model === model.id);
119119

120-
// Assistant content is typed as a block array, but transcript replay can
121-
// hand us a raw string (JSONL passthrough). Normalize it to an equivalent
122-
// single text block before transforming, matching the string->text block
123-
// handling already used in anthropic-payload-policy.ts.
124-
const contentBlocks = Array.isArray(assistantMsg.content)
125-
? assistantMsg.content
126-
: [{ type: "text" as const, text: assistantMsg.content as unknown as string }];
120+
// Public plugin-sdk/llm exports transformMessages; keep accepting legacy
121+
// assistant strings from external provider adapters even though session
122+
// JSONL replay normalizes them at ingest.
123+
const contentBlocks =
124+
typeof assistantMsg.content === "string"
125+
? [{ type: "text" as const, text: assistantMsg.content }]
126+
: assistantMsg.content;
127127

128128
const transformedContent = contentBlocks.flatMap((block) => {
129129
if (block.type === "thinking") {

0 commit comments

Comments
 (0)