Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/runtime/src/__tests__/history-compact-summarizer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,10 +13,13 @@ import type { RuntimeEvent, RuntimeEventContent } from '@maka/core/runtime-event
import { decodeModelCallAttempt, type ModelCallAttempt } from '@maka/core/model-call-attempt';
import { ProviderRequestTracker } from '../provider-request-telemetry.js';
import type { HistoryCompactSummaryInput } from '../ai-sdk-compaction-contract.js';
import type { ModelMessage } from '../model-protocol.js';
import {
buildLlmHistorySummarizer,
replayPlanItemsToModelMessages,
type AiSdkGenerateTextLike,
} from '../history-compact-summarizer.js';
import { buildRuntimeEventModelReplayPlan } from '../model-history.js';
import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';

const ts = 1_700_000_000_000;
Expand All@@ -35,6 +38,24 @@ function ev(overrides: Partial<RuntimeEvent> & { content?: RuntimeEventContent }
} as RuntimeEvent;
}

function assertStrictOpenAiToolCallFollowed(messages: ModelMessage[]): void {
for (const [index, message] of messages.entries()) {
if (message.role !== 'assistant' || typeof message.content === 'string') continue;
const callIds = message.content
.filter((part) => part.type === 'tool-call')
.map((part) => part.toolCallId);
if (callIds.length === 0) continue;
const answered: string[] = [];
for (const following of messages.slice(index + 1)) {
if (following.role !== 'tool') break;
for (const part of following.content) {
if (part.type === 'tool-result') answered.push(part.toolCallId);
}
}
assert.deepEqual(answered, callIds);
}
}

function inputWith(events: RuntimeEvent[], abortSignal?: AbortSignal): HistoryCompactSummaryInput {
return {
sessionId: 'sess-1',
Expand DownExpand Up@@ -166,6 +187,99 @@ describe('buildLlmHistorySummarizer', () => {
expect(toolPart.output).toEqual({ type: 'json', value: { name: 'maka' } });
});

test('groups consecutive parallel tool calls into one assistant message', async () => {
const seen: ModelMessage[][] = [];
const summarize = buildLlmHistorySummarizer({
resolveModel: () => 'fake-model',
generateText: async (options) => {
seen.push(options.messages);
return { text: '## Goal\nX' };
},
});

const events: RuntimeEvent[] = [
ev({ role: 'user', author: 'user', content: { kind: 'text', text: 'read both files' } }),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
];

expect(await summarize(inputWith(events))).toBe('## Goal\nX');
const messages = seen[0]!;
const assistantCalls = messages.filter(
(message) =>
message.role === 'assistant' &&
typeof message.content !== 'string' &&
message.content.some((part) => part.type === 'tool-call'),
);
expect(assistantCalls).toHaveLength(1);
expect(assistantCalls[0]?.content).toEqual([
{ type: 'tool-call', toolCallId: 'fc-a', toolName: 'read', input: { path: 'a.ts' } },
{ type: 'tool-call', toolCallId: 'fc-b', toolName: 'read', input: { path: 'b.ts' } },
]);
expect(
messages
.filter((message) => message.role === 'tool')
.flatMap((message) =>
message.content.flatMap((part) => (part.type === 'tool-result' ? [part.toolCallId] : [])),
),
).toEqual(['fc-a', 'fc-b']);
assertStrictOpenAiToolCallFollowed(messages);

const plan = buildRuntimeEventModelReplayPlan(events);
expect(
replayPlanItemsToModelMessages(plan.items).filter((message) => message.role === 'assistant'),
).toHaveLength(1);
});

test('does not merge sequential tool-call rounds that already have answers between them', () => {
const messages = replayPlanItemsToModelMessages(
buildRuntimeEventModelReplayPlan([
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
]).items,
);
expect(messages.filter((message) => message.role === 'assistant')).toHaveLength(2);
assertStrictOpenAiToolCallFollowed(messages);
});

test('surfaces provider failures so the runtime can report the real compact reason', async () => {
const generateText: AiSdkGenerateTextLike = async () => {
throw new Error('model down');
Expand Down
36 changes: 26 additions & 10 deletions packages/runtime/src/history-compact-summarizer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,10 +130,13 @@ async function loadAiSdkTextModule(): Promise<AiSdkTextModule> {
}

type ReplayPlanItems = ReturnType<typeof buildRuntimeEventModelReplayPlan>['items'];
type ReplayToolCallItem = Extract<ReplayPlanItems[number], { kind: 'tool_call' }>;

export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMessage[] {
const out: ModelMessage[] = [];
for (const item of items) {
let index = 0;
while (index < items.length) {
const item = items[index]!;
if (item.kind === 'text') {
// Split on role so each push matches exactly one ModelMessage arm — no cast.
const textPart = { type: 'text' as const, text: item.content };
Expand All@@ -142,17 +145,27 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
} else {
out.push({ role: 'assistant', content: [textPart] });
}
index += 1;
} else if (item.kind === 'tool_call') {
// Consecutive tool_call items are one assistant step. Emitting each as
// its own assistant message leaves the previous tool_calls unanswered
// and is rejected by strict OpenAI-compatible providers.
const calls: ReplayToolCallItem[] = [item];
index += 1;
while (index < items.length) {
const next = items[index];
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;
Comment on lines +155 to +159

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Continue grouping across skipped thinking items.

If a thinking item occurs between tool calls in one tool step, Line 157 ends the group. Lines 183-185 then remove that boundary. The replay emits adjacent assistant tool-call messages, so the first call remains unanswered and strict providers can reject the request.

Skip thinking items while collecting calls. Add a regression case with tool_call, thinking, tool_call, and matching results.

Proposed fix
 while (index < items.length) {
const next = items[index];
+ if (next?.kind === 'thinking') {+ index += 1;+ continue;+ }
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;

As per path instructions, “Review the diff adversarially against the problem it claims to solve.”

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while(index<items.length){
constnext=items[index];
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;
while(index<items.length){
constnext=items[index];
if(next?.kind==='thinking'){
index+=1;
continue;
}
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;

Source: Path instructions

}
out.push({
role: 'assistant',
content: [
{
type: 'tool-call',
toolCallId: item.toolCallId,
toolName: item.toolName,
input: item.input,
},
],
content: calls.map((call) => ({
type: 'tool-call' as const,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
})),
});
} else if (item.kind === 'tool_result') {
out.push({
Expand All@@ -166,8 +179,11 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
},
],
});
index += 1;
} else {
// thinking entries are intentionally skipped for summarization
index += 1;
}
// thinking entries are intentionally skipped for summarization
}
return out;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/runtime/src/__tests__/history-compact-summarizer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,10 +13,13 @@ import type { RuntimeEvent, RuntimeEventContent } from '@maka/core/runtime-event
import { decodeModelCallAttempt, type ModelCallAttempt } from '@maka/core/model-call-attempt';
import { ProviderRequestTracker } from '../provider-request-telemetry.js';
import type { HistoryCompactSummaryInput } from '../ai-sdk-compaction-contract.js';
import type { ModelMessage } from '../model-protocol.js';
import {
buildLlmHistorySummarizer,
replayPlanItemsToModelMessages,
type AiSdkGenerateTextLike,
} from '../history-compact-summarizer.js';
import { buildRuntimeEventModelReplayPlan } from '../model-history.js';
import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';

const ts = 1_700_000_000_000;
Expand All@@ -35,6 +38,24 @@ function ev(overrides: Partial<RuntimeEvent> & { content?: RuntimeEventContent }
} as RuntimeEvent;
}

function assertStrictOpenAiToolCallFollowed(messages: ModelMessage[]): void {
for (const [index, message] of messages.entries()) {
if (message.role !== 'assistant' || typeof message.content === 'string') continue;
const callIds = message.content
.filter((part) => part.type === 'tool-call')
.map((part) => part.toolCallId);
if (callIds.length === 0) continue;
const answered: string[] = [];
for (const following of messages.slice(index + 1)) {
if (following.role !== 'tool') break;
for (const part of following.content) {
if (part.type === 'tool-result') answered.push(part.toolCallId);
}
}
assert.deepEqual(answered, callIds);
}
}

function inputWith(events: RuntimeEvent[], abortSignal?: AbortSignal): HistoryCompactSummaryInput {
return {
sessionId: 'sess-1',
Expand DownExpand Up@@ -166,6 +187,99 @@ describe('buildLlmHistorySummarizer', () => {
expect(toolPart.output).toEqual({ type: 'json', value: { name: 'maka' } });
});

test('groups consecutive parallel tool calls into one assistant message', async () => {
const seen: ModelMessage[][] = [];
const summarize = buildLlmHistorySummarizer({
resolveModel: () => 'fake-model',
generateText: async (options) => {
seen.push(options.messages);
return { text: '## Goal\nX' };
},
});

const events: RuntimeEvent[] = [
ev({ role: 'user', author: 'user', content: { kind: 'text', text: 'read both files' } }),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
];

expect(await summarize(inputWith(events))).toBe('## Goal\nX');
const messages = seen[0]!;
const assistantCalls = messages.filter(
(message) =>
message.role === 'assistant' &&
typeof message.content !== 'string' &&
message.content.some((part) => part.type === 'tool-call'),
);
expect(assistantCalls).toHaveLength(1);
expect(assistantCalls[0]?.content).toEqual([
{ type: 'tool-call', toolCallId: 'fc-a', toolName: 'read', input: { path: 'a.ts' } },
{ type: 'tool-call', toolCallId: 'fc-b', toolName: 'read', input: { path: 'b.ts' } },
]);
expect(
messages
.filter((message) => message.role === 'tool')
.flatMap((message) =>
message.content.flatMap((part) => (part.type === 'tool-result' ? [part.toolCallId] : [])),
),
).toEqual(['fc-a', 'fc-b']);
assertStrictOpenAiToolCallFollowed(messages);

const plan = buildRuntimeEventModelReplayPlan(events);
expect(
replayPlanItemsToModelMessages(plan.items).filter((message) => message.role === 'assistant'),
).toHaveLength(1);
});

test('does not merge sequential tool-call rounds that already have answers between them', () => {
const messages = replayPlanItemsToModelMessages(
buildRuntimeEventModelReplayPlan([
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
]).items,
);
expect(messages.filter((message) => message.role === 'assistant')).toHaveLength(2);
assertStrictOpenAiToolCallFollowed(messages);
});

test('surfaces provider failures so the runtime can report the real compact reason', async () => {
const generateText: AiSdkGenerateTextLike = async () => {
throw new Error('model down');
Expand Down
36 changes: 26 additions & 10 deletions packages/runtime/src/history-compact-summarizer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,10 +130,13 @@ async function loadAiSdkTextModule(): Promise<AiSdkTextModule> {
}

type ReplayPlanItems = ReturnType<typeof buildRuntimeEventModelReplayPlan>['items'];
type ReplayToolCallItem = Extract<ReplayPlanItems[number], { kind: 'tool_call' }>;

export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMessage[] {
const out: ModelMessage[] = [];
for (const item of items) {
let index = 0;
while (index < items.length) {
const item = items[index]!;
if (item.kind === 'text') {
// Split on role so each push matches exactly one ModelMessage arm — no cast.
const textPart = { type: 'text' as const, text: item.content };
Expand All@@ -142,17 +145,27 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
} else {
out.push({ role: 'assistant', content: [textPart] });
}
index += 1;
} else if (item.kind === 'tool_call') {
// Consecutive tool_call items are one assistant step. Emitting each as
// its own assistant message leaves the previous tool_calls unanswered
// and is rejected by strict OpenAI-compatible providers.
const calls: ReplayToolCallItem[] = [item];
index += 1;
while (index < items.length) {
const next = items[index];
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;
Comment on lines +155 to +159

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Continue grouping across skipped thinking items.

If a thinking item occurs between tool calls in one tool step, Line 157 ends the group. Lines 183-185 then remove that boundary. The replay emits adjacent assistant tool-call messages, so the first call remains unanswered and strict providers can reject the request.

Skip thinking items while collecting calls. Add a regression case with tool_call, thinking, tool_call, and matching results.

Proposed fix
 while (index < items.length) {
const next = items[index];
+ if (next?.kind === 'thinking') {+ index += 1;+ continue;+ }
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;

As per path instructions, “Review the diff adversarially against the problem it claims to solve.”

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while(index<items.length){
constnext=items[index];
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;
while(index<items.length){
constnext=items[index];
if(next?.kind==='thinking'){
index+=1;
continue;
}
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;

Source: Path instructions

}
out.push({
role: 'assistant',
content: [
{
type: 'tool-call',
toolCallId: item.toolCallId,
toolName: item.toolName,
input: item.input,
},
],
content: calls.map((call) => ({
type: 'tool-call' as const,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
})),
});
} else if (item.kind === 'tool_result') {
out.push({
Expand All@@ -166,8 +179,11 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
},
],
});
index += 1;
} else {
// thinking entries are intentionally skipped for summarization
index += 1;
}
// thinking entries are intentionally skipped for summarization
}
return out;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/runtime/src/__tests__/history-compact-summarizer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,10 +13,13 @@ import type { RuntimeEvent, RuntimeEventContent } from '@maka/core/runtime-event
import { decodeModelCallAttempt, type ModelCallAttempt } from '@maka/core/model-call-attempt';
import { ProviderRequestTracker } from '../provider-request-telemetry.js';
import type { HistoryCompactSummaryInput } from '../ai-sdk-compaction-contract.js';
import type { ModelMessage } from '../model-protocol.js';
import {
buildLlmHistorySummarizer,
replayPlanItemsToModelMessages,
type AiSdkGenerateTextLike,
} from '../history-compact-summarizer.js';
import { buildRuntimeEventModelReplayPlan } from '../model-history.js';
import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';

const ts = 1_700_000_000_000;
Expand All@@ -35,6 +38,24 @@ function ev(overrides: Partial<RuntimeEvent> & { content?: RuntimeEventContent }
} as RuntimeEvent;
}

function assertStrictOpenAiToolCallFollowed(messages: ModelMessage[]): void {
for (const [index, message] of messages.entries()) {
if (message.role !== 'assistant' || typeof message.content === 'string') continue;
const callIds = message.content
.filter((part) => part.type === 'tool-call')
.map((part) => part.toolCallId);
if (callIds.length === 0) continue;
const answered: string[] = [];
for (const following of messages.slice(index + 1)) {
if (following.role !== 'tool') break;
for (const part of following.content) {
if (part.type === 'tool-result') answered.push(part.toolCallId);
}
}
assert.deepEqual(answered, callIds);
}
}

function inputWith(events: RuntimeEvent[], abortSignal?: AbortSignal): HistoryCompactSummaryInput {
return {
sessionId: 'sess-1',
Expand DownExpand Up@@ -166,6 +187,99 @@ describe('buildLlmHistorySummarizer', () => {
expect(toolPart.output).toEqual({ type: 'json', value: { name: 'maka' } });
});

test('groups consecutive parallel tool calls into one assistant message', async () => {
const seen: ModelMessage[][] = [];
const summarize = buildLlmHistorySummarizer({
resolveModel: () => 'fake-model',
generateText: async (options) => {
seen.push(options.messages);
return { text: '## Goal\nX' };
},
});

const events: RuntimeEvent[] = [
ev({ role: 'user', author: 'user', content: { kind: 'text', text: 'read both files' } }),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
];

expect(await summarize(inputWith(events))).toBe('## Goal\nX');
const messages = seen[0]!;
const assistantCalls = messages.filter(
(message) =>
message.role === 'assistant' &&
typeof message.content !== 'string' &&
message.content.some((part) => part.type === 'tool-call'),
);
expect(assistantCalls).toHaveLength(1);
expect(assistantCalls[0]?.content).toEqual([
{ type: 'tool-call', toolCallId: 'fc-a', toolName: 'read', input: { path: 'a.ts' } },
{ type: 'tool-call', toolCallId: 'fc-b', toolName: 'read', input: { path: 'b.ts' } },
]);
expect(
messages
.filter((message) => message.role === 'tool')
.flatMap((message) =>
message.content.flatMap((part) => (part.type === 'tool-result' ? [part.toolCallId] : [])),
),
).toEqual(['fc-a', 'fc-b']);
assertStrictOpenAiToolCallFollowed(messages);

const plan = buildRuntimeEventModelReplayPlan(events);
expect(
replayPlanItemsToModelMessages(plan.items).filter((message) => message.role === 'assistant'),
).toHaveLength(1);
});

test('does not merge sequential tool-call rounds that already have answers between them', () => {
const messages = replayPlanItemsToModelMessages(
buildRuntimeEventModelReplayPlan([
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
]).items,
);
expect(messages.filter((message) => message.role === 'assistant')).toHaveLength(2);
assertStrictOpenAiToolCallFollowed(messages);
});

test('surfaces provider failures so the runtime can report the real compact reason', async () => {
const generateText: AiSdkGenerateTextLike = async () => {
throw new Error('model down');
Expand Down
36 changes: 26 additions & 10 deletions packages/runtime/src/history-compact-summarizer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,10 +130,13 @@ async function loadAiSdkTextModule(): Promise<AiSdkTextModule> {
}

type ReplayPlanItems = ReturnType<typeof buildRuntimeEventModelReplayPlan>['items'];
type ReplayToolCallItem = Extract<ReplayPlanItems[number], { kind: 'tool_call' }>;

export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMessage[] {
const out: ModelMessage[] = [];
for (const item of items) {
let index = 0;
while (index < items.length) {
const item = items[index]!;
if (item.kind === 'text') {
// Split on role so each push matches exactly one ModelMessage arm — no cast.
const textPart = { type: 'text' as const, text: item.content };
Expand All@@ -142,17 +145,27 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
} else {
out.push({ role: 'assistant', content: [textPart] });
}
index += 1;
} else if (item.kind === 'tool_call') {
// Consecutive tool_call items are one assistant step. Emitting each as
// its own assistant message leaves the previous tool_calls unanswered
// and is rejected by strict OpenAI-compatible providers.
const calls: ReplayToolCallItem[] = [item];
index += 1;
while (index < items.length) {
const next = items[index];
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;
Comment on lines +155 to +159

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Continue grouping across skipped thinking items.

If a thinking item occurs between tool calls in one tool step, Line 157 ends the group. Lines 183-185 then remove that boundary. The replay emits adjacent assistant tool-call messages, so the first call remains unanswered and strict providers can reject the request.

Skip thinking items while collecting calls. Add a regression case with tool_call, thinking, tool_call, and matching results.

Proposed fix
 while (index < items.length) {
const next = items[index];
+ if (next?.kind === 'thinking') {+ index += 1;+ continue;+ }
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;

As per path instructions, “Review the diff adversarially against the problem it claims to solve.”

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while(index<items.length){
constnext=items[index];
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;
while(index<items.length){
constnext=items[index];
if(next?.kind==='thinking'){
index+=1;
continue;
}
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;

Source: Path instructions

}
out.push({
role: 'assistant',
content: [
{
type: 'tool-call',
toolCallId: item.toolCallId,
toolName: item.toolName,
input: item.input,
},
],
content: calls.map((call) => ({
type: 'tool-call' as const,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
})),
});
} else if (item.kind === 'tool_result') {
out.push({
Expand All@@ -166,8 +179,11 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
},
],
});
index += 1;
} else {
// thinking entries are intentionally skipped for summarization
index += 1;
}
// thinking entries are intentionally skipped for summarization
}
return out;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/runtime/src/__tests__/history-compact-summarizer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,10 +13,13 @@ import type { RuntimeEvent, RuntimeEventContent } from '@maka/core/runtime-event
import { decodeModelCallAttempt, type ModelCallAttempt } from '@maka/core/model-call-attempt';
import { ProviderRequestTracker } from '../provider-request-telemetry.js';
import type { HistoryCompactSummaryInput } from '../ai-sdk-compaction-contract.js';
import type { ModelMessage } from '../model-protocol.js';
import {
buildLlmHistorySummarizer,
replayPlanItemsToModelMessages,
type AiSdkGenerateTextLike,
} from '../history-compact-summarizer.js';
import { buildRuntimeEventModelReplayPlan } from '../model-history.js';
import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';

const ts = 1_700_000_000_000;
Expand All@@ -35,6 +38,24 @@ function ev(overrides: Partial<RuntimeEvent> & { content?: RuntimeEventContent }
} as RuntimeEvent;
}

function assertStrictOpenAiToolCallFollowed(messages: ModelMessage[]): void {
for (const [index, message] of messages.entries()) {
if (message.role !== 'assistant' || typeof message.content === 'string') continue;
const callIds = message.content
.filter((part) => part.type === 'tool-call')
.map((part) => part.toolCallId);
if (callIds.length === 0) continue;
const answered: string[] = [];
for (const following of messages.slice(index + 1)) {
if (following.role !== 'tool') break;
for (const part of following.content) {
if (part.type === 'tool-result') answered.push(part.toolCallId);
}
}
assert.deepEqual(answered, callIds);
}
}

function inputWith(events: RuntimeEvent[], abortSignal?: AbortSignal): HistoryCompactSummaryInput {
return {
sessionId: 'sess-1',
Expand DownExpand Up@@ -166,6 +187,99 @@ describe('buildLlmHistorySummarizer', () => {
expect(toolPart.output).toEqual({ type: 'json', value: { name: 'maka' } });
});

test('groups consecutive parallel tool calls into one assistant message', async () => {
const seen: ModelMessage[][] = [];
const summarize = buildLlmHistorySummarizer({
resolveModel: () => 'fake-model',
generateText: async (options) => {
seen.push(options.messages);
return { text: '## Goal\nX' };
},
});

const events: RuntimeEvent[] = [
ev({ role: 'user', author: 'user', content: { kind: 'text', text: 'read both files' } }),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
];

expect(await summarize(inputWith(events))).toBe('## Goal\nX');
const messages = seen[0]!;
const assistantCalls = messages.filter(
(message) =>
message.role === 'assistant' &&
typeof message.content !== 'string' &&
message.content.some((part) => part.type === 'tool-call'),
);
expect(assistantCalls).toHaveLength(1);
expect(assistantCalls[0]?.content).toEqual([
{ type: 'tool-call', toolCallId: 'fc-a', toolName: 'read', input: { path: 'a.ts' } },
{ type: 'tool-call', toolCallId: 'fc-b', toolName: 'read', input: { path: 'b.ts' } },
]);
expect(
messages
.filter((message) => message.role === 'tool')
.flatMap((message) =>
message.content.flatMap((part) => (part.type === 'tool-result' ? [part.toolCallId] : [])),
),
).toEqual(['fc-a', 'fc-b']);
assertStrictOpenAiToolCallFollowed(messages);

const plan = buildRuntimeEventModelReplayPlan(events);
expect(
replayPlanItemsToModelMessages(plan.items).filter((message) => message.role === 'assistant'),
).toHaveLength(1);
});

test('does not merge sequential tool-call rounds that already have answers between them', () => {
const messages = replayPlanItemsToModelMessages(
buildRuntimeEventModelReplayPlan([
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
]).items,
);
expect(messages.filter((message) => message.role === 'assistant')).toHaveLength(2);
assertStrictOpenAiToolCallFollowed(messages);
});

test('surfaces provider failures so the runtime can report the real compact reason', async () => {
const generateText: AiSdkGenerateTextLike = async () => {
throw new Error('model down');
Expand Down
36 changes: 26 additions & 10 deletions packages/runtime/src/history-compact-summarizer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,10 +130,13 @@ async function loadAiSdkTextModule(): Promise<AiSdkTextModule> {
}

type ReplayPlanItems = ReturnType<typeof buildRuntimeEventModelReplayPlan>['items'];
type ReplayToolCallItem = Extract<ReplayPlanItems[number], { kind: 'tool_call' }>;

export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMessage[] {
const out: ModelMessage[] = [];
for (const item of items) {
let index = 0;
while (index < items.length) {
const item = items[index]!;
if (item.kind === 'text') {
// Split on role so each push matches exactly one ModelMessage arm — no cast.
const textPart = { type: 'text' as const, text: item.content };
Expand All@@ -142,17 +145,27 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
} else {
out.push({ role: 'assistant', content: [textPart] });
}
index += 1;
} else if (item.kind === 'tool_call') {
// Consecutive tool_call items are one assistant step. Emitting each as
// its own assistant message leaves the previous tool_calls unanswered
// and is rejected by strict OpenAI-compatible providers.
const calls: ReplayToolCallItem[] = [item];
index += 1;
while (index < items.length) {
const next = items[index];
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;
Comment on lines +155 to +159

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Continue grouping across skipped thinking items.

If a thinking item occurs between tool calls in one tool step, Line 157 ends the group. Lines 183-185 then remove that boundary. The replay emits adjacent assistant tool-call messages, so the first call remains unanswered and strict providers can reject the request.

Skip thinking items while collecting calls. Add a regression case with tool_call, thinking, tool_call, and matching results.

Proposed fix
 while (index < items.length) {
const next = items[index];
+ if (next?.kind === 'thinking') {+ index += 1;+ continue;+ }
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;

As per path instructions, “Review the diff adversarially against the problem it claims to solve.”

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while(index<items.length){
constnext=items[index];
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;
while(index<items.length){
constnext=items[index];
if(next?.kind==='thinking'){
index+=1;
continue;
}
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;

Source: Path instructions

}
out.push({
role: 'assistant',
content: [
{
type: 'tool-call',
toolCallId: item.toolCallId,
toolName: item.toolName,
input: item.input,
},
],
content: calls.map((call) => ({
type: 'tool-call' as const,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
})),
});
} else if (item.kind === 'tool_result') {
out.push({
Expand All@@ -166,8 +179,11 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
},
],
});
index += 1;
} else {
// thinking entries are intentionally skipped for summarization
index += 1;
}
// thinking entries are intentionally skipped for summarization
}
return out;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/runtime/src/__tests__/history-compact-summarizer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,10 +13,13 @@ import type { RuntimeEvent, RuntimeEventContent } from '@maka/core/runtime-event
import { decodeModelCallAttempt, type ModelCallAttempt } from '@maka/core/model-call-attempt';
import { ProviderRequestTracker } from '../provider-request-telemetry.js';
import type { HistoryCompactSummaryInput } from '../ai-sdk-compaction-contract.js';
import type { ModelMessage } from '../model-protocol.js';
import {
buildLlmHistorySummarizer,
replayPlanItemsToModelMessages,
type AiSdkGenerateTextLike,
} from '../history-compact-summarizer.js';
import { buildRuntimeEventModelReplayPlan } from '../model-history.js';
import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';

const ts = 1_700_000_000_000;
Expand All@@ -35,6 +38,24 @@ function ev(overrides: Partial<RuntimeEvent> & { content?: RuntimeEventContent }
} as RuntimeEvent;
}

function assertStrictOpenAiToolCallFollowed(messages: ModelMessage[]): void {
for (const [index, message] of messages.entries()) {
if (message.role !== 'assistant' || typeof message.content === 'string') continue;
const callIds = message.content
.filter((part) => part.type === 'tool-call')
.map((part) => part.toolCallId);
if (callIds.length === 0) continue;
const answered: string[] = [];
for (const following of messages.slice(index + 1)) {
if (following.role !== 'tool') break;
for (const part of following.content) {
if (part.type === 'tool-result') answered.push(part.toolCallId);
}
}
assert.deepEqual(answered, callIds);
}
}

function inputWith(events: RuntimeEvent[], abortSignal?: AbortSignal): HistoryCompactSummaryInput {
return {
sessionId: 'sess-1',
Expand DownExpand Up@@ -166,6 +187,99 @@ describe('buildLlmHistorySummarizer', () => {
expect(toolPart.output).toEqual({ type: 'json', value: { name: 'maka' } });
});

test('groups consecutive parallel tool calls into one assistant message', async () => {
const seen: ModelMessage[][] = [];
const summarize = buildLlmHistorySummarizer({
resolveModel: () => 'fake-model',
generateText: async (options) => {
seen.push(options.messages);
return { text: '## Goal\nX' };
},
});

const events: RuntimeEvent[] = [
ev({ role: 'user', author: 'user', content: { kind: 'text', text: 'read both files' } }),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
];

expect(await summarize(inputWith(events))).toBe('## Goal\nX');
const messages = seen[0]!;
const assistantCalls = messages.filter(
(message) =>
message.role === 'assistant' &&
typeof message.content !== 'string' &&
message.content.some((part) => part.type === 'tool-call'),
);
expect(assistantCalls).toHaveLength(1);
expect(assistantCalls[0]?.content).toEqual([
{ type: 'tool-call', toolCallId: 'fc-a', toolName: 'read', input: { path: 'a.ts' } },
{ type: 'tool-call', toolCallId: 'fc-b', toolName: 'read', input: { path: 'b.ts' } },
]);
expect(
messages
.filter((message) => message.role === 'tool')
.flatMap((message) =>
message.content.flatMap((part) => (part.type === 'tool-result' ? [part.toolCallId] : [])),
),
).toEqual(['fc-a', 'fc-b']);
assertStrictOpenAiToolCallFollowed(messages);

const plan = buildRuntimeEventModelReplayPlan(events);
expect(
replayPlanItemsToModelMessages(plan.items).filter((message) => message.role === 'assistant'),
).toHaveLength(1);
});

test('does not merge sequential tool-call rounds that already have answers between them', () => {
const messages = replayPlanItemsToModelMessages(
buildRuntimeEventModelReplayPlan([
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
]).items,
);
expect(messages.filter((message) => message.role === 'assistant')).toHaveLength(2);
assertStrictOpenAiToolCallFollowed(messages);
});

test('surfaces provider failures so the runtime can report the real compact reason', async () => {
const generateText: AiSdkGenerateTextLike = async () => {
throw new Error('model down');
Expand Down
36 changes: 26 additions & 10 deletions packages/runtime/src/history-compact-summarizer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,10 +130,13 @@ async function loadAiSdkTextModule(): Promise<AiSdkTextModule> {
}

type ReplayPlanItems = ReturnType<typeof buildRuntimeEventModelReplayPlan>['items'];
type ReplayToolCallItem = Extract<ReplayPlanItems[number], { kind: 'tool_call' }>;

export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMessage[] {
const out: ModelMessage[] = [];
for (const item of items) {
let index = 0;
while (index < items.length) {
const item = items[index]!;
if (item.kind === 'text') {
// Split on role so each push matches exactly one ModelMessage arm — no cast.
const textPart = { type: 'text' as const, text: item.content };
Expand All@@ -142,17 +145,27 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
} else {
out.push({ role: 'assistant', content: [textPart] });
}
index += 1;
} else if (item.kind === 'tool_call') {
// Consecutive tool_call items are one assistant step. Emitting each as
// its own assistant message leaves the previous tool_calls unanswered
// and is rejected by strict OpenAI-compatible providers.
const calls: ReplayToolCallItem[] = [item];
index += 1;
while (index < items.length) {
const next = items[index];
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;
Comment on lines +155 to +159

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Continue grouping across skipped thinking items.

If a thinking item occurs between tool calls in one tool step, Line 157 ends the group. Lines 183-185 then remove that boundary. The replay emits adjacent assistant tool-call messages, so the first call remains unanswered and strict providers can reject the request.

Skip thinking items while collecting calls. Add a regression case with tool_call, thinking, tool_call, and matching results.

Proposed fix
 while (index < items.length) {
const next = items[index];
+ if (next?.kind === 'thinking') {+ index += 1;+ continue;+ }
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;

As per path instructions, “Review the diff adversarially against the problem it claims to solve.”

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while(index<items.length){
constnext=items[index];
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;
while(index<items.length){
constnext=items[index];
if(next?.kind==='thinking'){
index+=1;
continue;
}
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;

Source: Path instructions

}
out.push({
role: 'assistant',
content: [
{
type: 'tool-call',
toolCallId: item.toolCallId,
toolName: item.toolName,
input: item.input,
},
],
content: calls.map((call) => ({
type: 'tool-call' as const,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
})),
});
} else if (item.kind === 'tool_result') {
out.push({
Expand All@@ -166,8 +179,11 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
},
],
});
index += 1;
} else {
// thinking entries are intentionally skipped for summarization
index += 1;
}
// thinking entries are intentionally skipped for summarization
}
return out;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/runtime/src/__tests__/history-compact-summarizer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,10 +13,13 @@ import type { RuntimeEvent, RuntimeEventContent } from '@maka/core/runtime-event
import { decodeModelCallAttempt, type ModelCallAttempt } from '@maka/core/model-call-attempt';
import { ProviderRequestTracker } from '../provider-request-telemetry.js';
import type { HistoryCompactSummaryInput } from '../ai-sdk-compaction-contract.js';
import type { ModelMessage } from '../model-protocol.js';
import {
buildLlmHistorySummarizer,
replayPlanItemsToModelMessages,
type AiSdkGenerateTextLike,
} from '../history-compact-summarizer.js';
import { buildRuntimeEventModelReplayPlan } from '../model-history.js';
import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';

const ts = 1_700_000_000_000;
Expand All@@ -35,6 +38,24 @@ function ev(overrides: Partial<RuntimeEvent> & { content?: RuntimeEventContent }
} as RuntimeEvent;
}

function assertStrictOpenAiToolCallFollowed(messages: ModelMessage[]): void {
for (const [index, message] of messages.entries()) {
if (message.role !== 'assistant' || typeof message.content === 'string') continue;
const callIds = message.content
.filter((part) => part.type === 'tool-call')
.map((part) => part.toolCallId);
if (callIds.length === 0) continue;
const answered: string[] = [];
for (const following of messages.slice(index + 1)) {
if (following.role !== 'tool') break;
for (const part of following.content) {
if (part.type === 'tool-result') answered.push(part.toolCallId);
}
}
assert.deepEqual(answered, callIds);
}
}

function inputWith(events: RuntimeEvent[], abortSignal?: AbortSignal): HistoryCompactSummaryInput {
return {
sessionId: 'sess-1',
Expand DownExpand Up@@ -166,6 +187,99 @@ describe('buildLlmHistorySummarizer', () => {
expect(toolPart.output).toEqual({ type: 'json', value: { name: 'maka' } });
});

test('groups consecutive parallel tool calls into one assistant message', async () => {
const seen: ModelMessage[][] = [];
const summarize = buildLlmHistorySummarizer({
resolveModel: () => 'fake-model',
generateText: async (options) => {
seen.push(options.messages);
return { text: '## Goal\nX' };
},
});

const events: RuntimeEvent[] = [
ev({ role: 'user', author: 'user', content: { kind: 'text', text: 'read both files' } }),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
];

expect(await summarize(inputWith(events))).toBe('## Goal\nX');
const messages = seen[0]!;
const assistantCalls = messages.filter(
(message) =>
message.role === 'assistant' &&
typeof message.content !== 'string' &&
message.content.some((part) => part.type === 'tool-call'),
);
expect(assistantCalls).toHaveLength(1);
expect(assistantCalls[0]?.content).toEqual([
{ type: 'tool-call', toolCallId: 'fc-a', toolName: 'read', input: { path: 'a.ts' } },
{ type: 'tool-call', toolCallId: 'fc-b', toolName: 'read', input: { path: 'b.ts' } },
]);
expect(
messages
.filter((message) => message.role === 'tool')
.flatMap((message) =>
message.content.flatMap((part) => (part.type === 'tool-result' ? [part.toolCallId] : [])),
),
).toEqual(['fc-a', 'fc-b']);
assertStrictOpenAiToolCallFollowed(messages);

const plan = buildRuntimeEventModelReplayPlan(events);
expect(
replayPlanItemsToModelMessages(plan.items).filter((message) => message.role === 'assistant'),
).toHaveLength(1);
});

test('does not merge sequential tool-call rounds that already have answers between them', () => {
const messages = replayPlanItemsToModelMessages(
buildRuntimeEventModelReplayPlan([
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
]).items,
);
expect(messages.filter((message) => message.role === 'assistant')).toHaveLength(2);
assertStrictOpenAiToolCallFollowed(messages);
});

test('surfaces provider failures so the runtime can report the real compact reason', async () => {
const generateText: AiSdkGenerateTextLike = async () => {
throw new Error('model down');
Expand Down
36 changes: 26 additions & 10 deletions packages/runtime/src/history-compact-summarizer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,10 +130,13 @@ async function loadAiSdkTextModule(): Promise<AiSdkTextModule> {
}

type ReplayPlanItems = ReturnType<typeof buildRuntimeEventModelReplayPlan>['items'];
type ReplayToolCallItem = Extract<ReplayPlanItems[number], { kind: 'tool_call' }>;

export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMessage[] {
const out: ModelMessage[] = [];
for (const item of items) {
let index = 0;
while (index < items.length) {
const item = items[index]!;
if (item.kind === 'text') {
// Split on role so each push matches exactly one ModelMessage arm — no cast.
const textPart = { type: 'text' as const, text: item.content };
Expand All@@ -142,17 +145,27 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
} else {
out.push({ role: 'assistant', content: [textPart] });
}
index += 1;
} else if (item.kind === 'tool_call') {
// Consecutive tool_call items are one assistant step. Emitting each as
// its own assistant message leaves the previous tool_calls unanswered
// and is rejected by strict OpenAI-compatible providers.
const calls: ReplayToolCallItem[] = [item];
index += 1;
while (index < items.length) {
const next = items[index];
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;
Comment on lines +155 to +159

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Continue grouping across skipped thinking items.

If a thinking item occurs between tool calls in one tool step, Line 157 ends the group. Lines 183-185 then remove that boundary. The replay emits adjacent assistant tool-call messages, so the first call remains unanswered and strict providers can reject the request.

Skip thinking items while collecting calls. Add a regression case with tool_call, thinking, tool_call, and matching results.

Proposed fix
 while (index < items.length) {
const next = items[index];
+ if (next?.kind === 'thinking') {+ index += 1;+ continue;+ }
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;

As per path instructions, “Review the diff adversarially against the problem it claims to solve.”

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while(index<items.length){
constnext=items[index];
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;
while(index<items.length){
constnext=items[index];
if(next?.kind==='thinking'){
index+=1;
continue;
}
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;

Source: Path instructions

}
out.push({
role: 'assistant',
content: [
{
type: 'tool-call',
toolCallId: item.toolCallId,
toolName: item.toolName,
input: item.input,
},
],
content: calls.map((call) => ({
type: 'tool-call' as const,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
})),
});
} else if (item.kind === 'tool_result') {
out.push({
Expand All@@ -166,8 +179,11 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
},
],
});
index += 1;
} else {
// thinking entries are intentionally skipped for summarization
index += 1;
}
// thinking entries are intentionally skipped for summarization
}
return out;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/runtime/src/__tests__/history-compact-summarizer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,10 +13,13 @@ import type { RuntimeEvent, RuntimeEventContent } from '@maka/core/runtime-event
import { decodeModelCallAttempt, type ModelCallAttempt } from '@maka/core/model-call-attempt';
import { ProviderRequestTracker } from '../provider-request-telemetry.js';
import type { HistoryCompactSummaryInput } from '../ai-sdk-compaction-contract.js';
import type { ModelMessage } from '../model-protocol.js';
import {
buildLlmHistorySummarizer,
replayPlanItemsToModelMessages,
type AiSdkGenerateTextLike,
} from '../history-compact-summarizer.js';
import { buildRuntimeEventModelReplayPlan } from '../model-history.js';
import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';

const ts = 1_700_000_000_000;
Expand All@@ -35,6 +38,24 @@ function ev(overrides: Partial<RuntimeEvent> & { content?: RuntimeEventContent }
} as RuntimeEvent;
}

function assertStrictOpenAiToolCallFollowed(messages: ModelMessage[]): void {
for (const [index, message] of messages.entries()) {
if (message.role !== 'assistant' || typeof message.content === 'string') continue;
const callIds = message.content
.filter((part) => part.type === 'tool-call')
.map((part) => part.toolCallId);
if (callIds.length === 0) continue;
const answered: string[] = [];
for (const following of messages.slice(index + 1)) {
if (following.role !== 'tool') break;
for (const part of following.content) {
if (part.type === 'tool-result') answered.push(part.toolCallId);
}
}
assert.deepEqual(answered, callIds);
}
}

function inputWith(events: RuntimeEvent[], abortSignal?: AbortSignal): HistoryCompactSummaryInput {
return {
sessionId: 'sess-1',
Expand DownExpand Up@@ -166,6 +187,99 @@ describe('buildLlmHistorySummarizer', () => {
expect(toolPart.output).toEqual({ type: 'json', value: { name: 'maka' } });
});

test('groups consecutive parallel tool calls into one assistant message', async () => {
const seen: ModelMessage[][] = [];
const summarize = buildLlmHistorySummarizer({
resolveModel: () => 'fake-model',
generateText: async (options) => {
seen.push(options.messages);
return { text: '## Goal\nX' };
},
});

const events: RuntimeEvent[] = [
ev({ role: 'user', author: 'user', content: { kind: 'text', text: 'read both files' } }),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
];

expect(await summarize(inputWith(events))).toBe('## Goal\nX');
const messages = seen[0]!;
const assistantCalls = messages.filter(
(message) =>
message.role === 'assistant' &&
typeof message.content !== 'string' &&
message.content.some((part) => part.type === 'tool-call'),
);
expect(assistantCalls).toHaveLength(1);
expect(assistantCalls[0]?.content).toEqual([
{ type: 'tool-call', toolCallId: 'fc-a', toolName: 'read', input: { path: 'a.ts' } },
{ type: 'tool-call', toolCallId: 'fc-b', toolName: 'read', input: { path: 'b.ts' } },
]);
expect(
messages
.filter((message) => message.role === 'tool')
.flatMap((message) =>
message.content.flatMap((part) => (part.type === 'tool-result' ? [part.toolCallId] : [])),
),
).toEqual(['fc-a', 'fc-b']);
assertStrictOpenAiToolCallFollowed(messages);

const plan = buildRuntimeEventModelReplayPlan(events);
expect(
replayPlanItemsToModelMessages(plan.items).filter((message) => message.role === 'assistant'),
).toHaveLength(1);
});

test('does not merge sequential tool-call rounds that already have answers between them', () => {
const messages = replayPlanItemsToModelMessages(
buildRuntimeEventModelReplayPlan([
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
]).items,
);
expect(messages.filter((message) => message.role === 'assistant')).toHaveLength(2);
assertStrictOpenAiToolCallFollowed(messages);
});

test('surfaces provider failures so the runtime can report the real compact reason', async () => {
const generateText: AiSdkGenerateTextLike = async () => {
throw new Error('model down');
Expand Down
36 changes: 26 additions & 10 deletions packages/runtime/src/history-compact-summarizer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,10 +130,13 @@ async function loadAiSdkTextModule(): Promise<AiSdkTextModule> {
}

type ReplayPlanItems = ReturnType<typeof buildRuntimeEventModelReplayPlan>['items'];
type ReplayToolCallItem = Extract<ReplayPlanItems[number], { kind: 'tool_call' }>;

export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMessage[] {
const out: ModelMessage[] = [];
for (const item of items) {
let index = 0;
while (index < items.length) {
const item = items[index]!;
if (item.kind === 'text') {
// Split on role so each push matches exactly one ModelMessage arm — no cast.
const textPart = { type: 'text' as const, text: item.content };
Expand All@@ -142,17 +145,27 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
} else {
out.push({ role: 'assistant', content: [textPart] });
}
index += 1;
} else if (item.kind === 'tool_call') {
// Consecutive tool_call items are one assistant step. Emitting each as
// its own assistant message leaves the previous tool_calls unanswered
// and is rejected by strict OpenAI-compatible providers.
const calls: ReplayToolCallItem[] = [item];
index += 1;
while (index < items.length) {
const next = items[index];
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;
Comment on lines +155 to +159

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Continue grouping across skipped thinking items.

If a thinking item occurs between tool calls in one tool step, Line 157 ends the group. Lines 183-185 then remove that boundary. The replay emits adjacent assistant tool-call messages, so the first call remains unanswered and strict providers can reject the request.

Skip thinking items while collecting calls. Add a regression case with tool_call, thinking, tool_call, and matching results.

Proposed fix
 while (index < items.length) {
const next = items[index];
+ if (next?.kind === 'thinking') {+ index += 1;+ continue;+ }
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;

As per path instructions, “Review the diff adversarially against the problem it claims to solve.”

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while(index<items.length){
constnext=items[index];
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;
while(index<items.length){
constnext=items[index];
if(next?.kind==='thinking'){
index+=1;
continue;
}
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;

Source: Path instructions

}
out.push({
role: 'assistant',
content: [
{
type: 'tool-call',
toolCallId: item.toolCallId,
toolName: item.toolName,
input: item.input,
},
],
content: calls.map((call) => ({
type: 'tool-call' as const,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
})),
});
} else if (item.kind === 'tool_result') {
out.push({
Expand All@@ -166,8 +179,11 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
},
],
});
index += 1;
} else {
// thinking entries are intentionally skipped for summarization
index += 1;
}
// thinking entries are intentionally skipped for summarization
}
return out;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/runtime/src/__tests__/history-compact-summarizer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,10 +13,13 @@ import type { RuntimeEvent, RuntimeEventContent } from '@maka/core/runtime-event
import { decodeModelCallAttempt, type ModelCallAttempt } from '@maka/core/model-call-attempt';
import { ProviderRequestTracker } from '../provider-request-telemetry.js';
import type { HistoryCompactSummaryInput } from '../ai-sdk-compaction-contract.js';
import type { ModelMessage } from '../model-protocol.js';
import {
buildLlmHistorySummarizer,
replayPlanItemsToModelMessages,
type AiSdkGenerateTextLike,
} from '../history-compact-summarizer.js';
import { buildRuntimeEventModelReplayPlan } from '../model-history.js';
import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';

const ts = 1_700_000_000_000;
Expand All@@ -35,6 +38,24 @@ function ev(overrides: Partial<RuntimeEvent> & { content?: RuntimeEventContent }
} as RuntimeEvent;
}

function assertStrictOpenAiToolCallFollowed(messages: ModelMessage[]): void {
for (const [index, message] of messages.entries()) {
if (message.role !== 'assistant' || typeof message.content === 'string') continue;
const callIds = message.content
.filter((part) => part.type === 'tool-call')
.map((part) => part.toolCallId);
if (callIds.length === 0) continue;
const answered: string[] = [];
for (const following of messages.slice(index + 1)) {
if (following.role !== 'tool') break;
for (const part of following.content) {
if (part.type === 'tool-result') answered.push(part.toolCallId);
}
}
assert.deepEqual(answered, callIds);
}
}

function inputWith(events: RuntimeEvent[], abortSignal?: AbortSignal): HistoryCompactSummaryInput {
return {
sessionId: 'sess-1',
Expand DownExpand Up@@ -166,6 +187,99 @@ describe('buildLlmHistorySummarizer', () => {
expect(toolPart.output).toEqual({ type: 'json', value: { name: 'maka' } });
});

test('groups consecutive parallel tool calls into one assistant message', async () => {
const seen: ModelMessage[][] = [];
const summarize = buildLlmHistorySummarizer({
resolveModel: () => 'fake-model',
generateText: async (options) => {
seen.push(options.messages);
return { text: '## Goal\nX' };
},
});

const events: RuntimeEvent[] = [
ev({ role: 'user', author: 'user', content: { kind: 'text', text: 'read both files' } }),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
refs: { stepId: 'step-1' },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
];

expect(await summarize(inputWith(events))).toBe('## Goal\nX');
const messages = seen[0]!;
const assistantCalls = messages.filter(
(message) =>
message.role === 'assistant' &&
typeof message.content !== 'string' &&
message.content.some((part) => part.type === 'tool-call'),
);
expect(assistantCalls).toHaveLength(1);
expect(assistantCalls[0]?.content).toEqual([
{ type: 'tool-call', toolCallId: 'fc-a', toolName: 'read', input: { path: 'a.ts' } },
{ type: 'tool-call', toolCallId: 'fc-b', toolName: 'read', input: { path: 'b.ts' } },
]);
expect(
messages
.filter((message) => message.role === 'tool')
.flatMap((message) =>
message.content.flatMap((part) => (part.type === 'tool-result' ? [part.toolCallId] : [])),
),
).toEqual(['fc-a', 'fc-b']);
assertStrictOpenAiToolCallFollowed(messages);

const plan = buildRuntimeEventModelReplayPlan(events);
expect(
replayPlanItemsToModelMessages(plan.items).filter((message) => message.role === 'assistant'),
).toHaveLength(1);
});

test('does not merge sequential tool-call rounds that already have answers between them', () => {
const messages = replayPlanItemsToModelMessages(
buildRuntimeEventModelReplayPlan([
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-a', name: 'read', args: { path: 'a.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-a', name: 'read', result: { ok: 'a' } },
}),
ev({
role: 'model',
author: 'agent',
content: { kind: 'function_call', id: 'fc-b', name: 'read', args: { path: 'b.ts' } },
}),
ev({
role: 'tool',
author: 'tool',
content: { kind: 'function_response', id: 'fc-b', name: 'read', result: { ok: 'b' } },
}),
]).items,
);
expect(messages.filter((message) => message.role === 'assistant')).toHaveLength(2);
assertStrictOpenAiToolCallFollowed(messages);
});

test('surfaces provider failures so the runtime can report the real compact reason', async () => {
const generateText: AiSdkGenerateTextLike = async () => {
throw new Error('model down');
Expand Down
36 changes: 26 additions & 10 deletions packages/runtime/src/history-compact-summarizer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,10 +130,13 @@ async function loadAiSdkTextModule(): Promise<AiSdkTextModule> {
}

type ReplayPlanItems = ReturnType<typeof buildRuntimeEventModelReplayPlan>['items'];
type ReplayToolCallItem = Extract<ReplayPlanItems[number], { kind: 'tool_call' }>;

export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMessage[] {
const out: ModelMessage[] = [];
for (const item of items) {
let index = 0;
while (index < items.length) {
const item = items[index]!;
if (item.kind === 'text') {
// Split on role so each push matches exactly one ModelMessage arm — no cast.
const textPart = { type: 'text' as const, text: item.content };
Expand All@@ -142,17 +145,27 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
} else {
out.push({ role: 'assistant', content: [textPart] });
}
index += 1;
} else if (item.kind === 'tool_call') {
// Consecutive tool_call items are one assistant step. Emitting each as
// its own assistant message leaves the previous tool_calls unanswered
// and is rejected by strict OpenAI-compatible providers.
const calls: ReplayToolCallItem[] = [item];
index += 1;
while (index < items.length) {
const next = items[index];
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;
Comment on lines +155 to +159

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Continue grouping across skipped thinking items.

If a thinking item occurs between tool calls in one tool step, Line 157 ends the group. Lines 183-185 then remove that boundary. The replay emits adjacent assistant tool-call messages, so the first call remains unanswered and strict providers can reject the request.

Skip thinking items while collecting calls. Add a regression case with tool_call, thinking, tool_call, and matching results.

Proposed fix
 while (index < items.length) {
const next = items[index];
+ if (next?.kind === 'thinking') {+ index += 1;+ continue;+ }
if (next?.kind !== 'tool_call') break;
calls.push(next);
index += 1;

As per path instructions, “Review the diff adversarially against the problem it claims to solve.”

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while(index<items.length){
constnext=items[index];
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;
while(index<items.length){
constnext=items[index];
if(next?.kind==='thinking'){
index+=1;
continue;
}
if(next?.kind!=='tool_call')break;
calls.push(next);
index+=1;

Source: Path instructions

}
out.push({
role: 'assistant',
content: [
{
type: 'tool-call',
toolCallId: item.toolCallId,
toolName: item.toolName,
input: item.input,
},
],
content: calls.map((call) => ({
type: 'tool-call' as const,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
})),
});
} else if (item.kind === 'tool_result') {
out.push({
Expand All@@ -166,8 +179,11 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
},
],
});
index += 1;
} else {
// thinking entries are intentionally skipped for summarization
index += 1;
}
// thinking entries are intentionally skipped for summarization
}
return out;
}
Loading