Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .changeset/flatten-toolcall.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@moonshot-ai/kosong": minor
"@moonshot-ai/agent-core": minor
Comment thread
kermanx marked this conversation as resolved.
"@moonshot-ai/kimi-code": minor
---

Flatten tool call data by inlining tool names and arguments at the top level, and limit legacy record migration so it only rewrites matching tool call payloads.
4 changes: 2 additions & 2 deletions apps/kimi-code/src/tui/actions/replay-ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -520,12 +520,12 @@ function collectMessageContent(target: OpenAssistant, content: readonly ContentP

function toolCallFromMessage(rawToolCall: ToolCall): ToolCallBlockData | undefined {
const id = rawToolCall.id;
const name = rawToolCall.function.name;
const name = rawToolCall.name;
if (id.length === 0 || name.length === 0) return undefined;
return {
id,
name,
args: parseToolArguments(rawToolCall.function.arguments),
args: parseToolArguments(rawToolCall.arguments),
};
}

Expand Down
20 changes: 5 additions & 15 deletions apps/kimi-code/test/tui/replay-ops.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,14 +279,12 @@ describe('projectReplayRecords', () => {
{
type: 'function',
id: 'call_agent',
function: {
name: 'Agent',
name: 'Agent',
arguments: JSON.stringify({
description: 'Optimize summary',
subagent_type: 'coder',
run_in_background: true,
}),
},
},
],
}),
Expand Down Expand Up @@ -400,10 +398,8 @@ describe('projectReplayRecords', () => {
{
type: 'function',
id: 'tc_1',
function: {
name: 'Bash',
name: 'Bash',
arguments: '{"command":"pwd"}',
},
},
],
}),
Expand All @@ -427,10 +423,8 @@ describe('projectReplayRecords', () => {
{
type: 'function',
id: 'tc_1',
function: {
name: 'Bash',
name: 'Bash',
arguments: '{"command":"false"}',
},
},
],
}),
Expand Down Expand Up @@ -461,10 +455,8 @@ describe('projectReplayRecords', () => {
{
type: 'function',
id: 'call_resume_bash',
function: {
name: 'Bash',
name: 'Bash',
arguments: '{"command":"echo ok"}',
},
},
],
},
Expand Down Expand Up @@ -500,10 +492,8 @@ describe('projectReplayRecords', () => {
{
type: 'function',
id: 'tc_media',
function: {
name: 'ReadMediaFile',
name: 'ReadMediaFile',
arguments: '{"path":"/tmp/a.png"}',
},
},
],
}),
Expand Down
6 changes: 2 additions & 4 deletions apps/vis/server/src/lib/context-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,8 @@ export function buildAnnotatedMessages(
currentStep.tool_calls.push({
type: 'function',
id: r.data.tool_call_id,
function: {
name: r.data.tool_name,
arguments: r.data.args === undefined ? null : JSON.stringify(r.data.args),
},
name: r.data.tool_name,
arguments: r.data.args === undefined ? null : JSON.stringify(r.data.args),
});
break;
}
Expand Down
2 changes: 1 addition & 1 deletion apps/vis/server/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ export interface ContentPart {
export interface ToolCallEntry {
type: 'function';
id: string;
function: { name: string; arguments: string | null };
name: string; arguments: string | null;
}

export type MessageOrigin =
Expand Down
21 changes: 21 additions & 0 deletions apps/vis/server/src/lib/wire-replay.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { readFile } from 'node:fs/promises';

import {
migrateWireRecords,
type WireMigrationRecord,
} from '@moonshot-ai/agent-core/agent/records/migration';

import type {
ContentPartRecord,
NotificationRecord,
Expand Down Expand Up @@ -54,6 +59,22 @@ export async function replayWire(wirePath: string): Promise<ReplayWireResult> {
rawRecords.push({ seq, raw: parsed });
}

// Extract source version from metadata (if any) and apply wire migrations.
let sourceVersion: string | undefined;
for (const record of rawRecords) {
if (record.raw['type'] === 'metadata') {
const meta = record.raw as unknown as WireFileMetadata;
sourceVersion ??= meta.protocol_version;
Comment thread
kermanx marked this conversation as resolved.
}
}
const migrated = migrateWireRecords(
Comment thread
kermanx marked this conversation as resolved.
rawRecords.map((r) => r.raw as WireMigrationRecord),
sourceVersion,
);
Comment thread
kermanx marked this conversation as resolved.
for (const [i, rawRecord] of rawRecords.entries()) {
rawRecord.raw = migrated[i]!;
}

for (const [recordIndex, record] of rawRecords.entries()) {
const parsed = record.raw;
const seq = record.seq;
Expand Down
2 changes: 1 addition & 1 deletion apps/vis/server/test/context-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ describe('context-builder', () => {
| undefined;
expect(text?.text).toBe('hello!');
expect(m?.message.tool_calls).toHaveLength(1);
expect(m?.message.tool_calls[0]?.function.name).toBe('Bash');
expect(m?.message.tool_calls[0]?.name).toBe('Bash');
});

it('builds correct origin tagging on a synthetic session with system_reminder', async () => {
Expand Down
4 changes: 2 additions & 2 deletions apps/vis/web/src/components/context/MessageBubble.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ function ThinkBlock({ text }: { text: string }) {

function ToolCallCard({ call }: { call: ToolCallEntry }) {
const [open, setOpen] = useState(false);
const argsStr = call.function.arguments ?? '';
const argsStr = call.arguments ?? '';
return (
<div className="border border-border bg-surface-0">
<button
Expand All @@ -135,7 +135,7 @@ function ToolCallCard({ call }: { call: ToolCallEntry }) {
>
<span className="text-fg-3">{open ? '▾' : '▸'}</span>
<Pill tone="tools" variant="soft">call</Pill>
<span className="text-fg-0">{call.function.name}</span>
<span className="text-fg-0">{call.name}</span>
<span className="truncate text-fg-3">{truncate(argsStr, 80)}</span>
<span className="ml-auto text-fg-3 tabular text-[10px]">{call.id.slice(0, 10)}</span>
</button>
Expand Down
2 changes: 1 addition & 1 deletion apps/vis/web/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export interface ContentPart {
export interface ToolCallEntry {
type: 'function';
id: string;
function: { name: string; arguments: string | null };
name: string; arguments: string | null;
}

export interface AnnotatedMessage {
Expand Down
4 changes: 4 additions & 0 deletions packages/agent-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./agent/records/migration": {
"types": "./src/agent/records/migration/index.ts",
"default": "./src/agent/records/migration/index.ts"
},
"./session/store": {
"types": "./src/session/store/index.ts",
"default": "./src/session/store/index.ts"
Expand Down
4 changes: 2 additions & 2 deletions packages/agent-core/src/agent/compaction/render-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ function renderContentPartToText(part: Message['content'][number]): string {

function renderToolCallToText(toolCall: Message['toolCalls'][number]): string {
const lines = [
`- ${toolCall.id}: ${toolCall.function.name}`,
renderBlock('arguments', renderToolCallArguments(toolCall.function.arguments)),
`- ${toolCall.id}: ${toolCall.name}`,
renderBlock('arguments', renderToolCallArguments(toolCall.arguments)),
];

if (toolCall.extras !== undefined) {
Expand Down
6 changes: 2 additions & 4 deletions packages/agent-core/src/agent/context/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,8 @@ export class ContextMemory {
openStep.toolCalls.push({
type: 'function',
id: event.toolCallId,
function: {
name: event.name,
arguments: event.args === undefined ? null : JSON.stringify(event.args),
},
name: event.name,
arguments: event.args === undefined ? null : JSON.stringify(event.args),
});
this.pendingToolResultIds.add(event.toolCallId);
return;
Expand Down
4 changes: 2 additions & 2 deletions packages/agent-core/src/agent/permission/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export class PermissionManager {
async beforeToolCall(
context: ToolExecutionHookContext,
): Promise<PrepareToolExecutionResult | undefined> {
const name = context.toolCall.function.name;
const name = context.toolCall.name;
const args = context.args;

const mode = this.mode;
Expand Down Expand Up @@ -151,7 +151,7 @@ export class PermissionManager {
): Promise<PrepareToolExecutionResult | undefined> {
const { signal } = context;
const id = context.toolCall.id;
const name = context.toolCall.function.name;
const name = context.toolCall.name;
const args = context.args;
const display =
options.display ?? ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const AskUserQuestionAutoPermissionPolicy: PermissionPolicy = {
name: 'auto.ask-user-question',
evaluate({ mode, toolCallContext }) {
if (mode !== 'auto') return undefined;
if (toolCallContext.toolCall.function.name !== 'AskUserQuestion') return undefined;
if (toolCallContext.toolCall.name !== 'AskUserQuestion') return undefined;
return {
kind: 'result',
result: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function createDefaultGitCwdWritePolicy(): PermissionPolicy {
if (mode !== 'manual') return undefined;
if (matchedRule !== undefined) return undefined;

const toolName = toolCallContext.toolCall.function.name;
const toolName = toolCallContext.toolCall.name;
if (toolName !== 'Write' && toolName !== 'Edit') return undefined;

const kaos = agent.runtime.kaos;
Expand Down
6 changes: 3 additions & 3 deletions packages/agent-core/src/agent/permission/policies/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ interface ExitPlanModeExecutionMetadata {
export const EnterPlanModePermissionPolicy: PermissionPolicy = {
name: 'plan.enter-plan-mode',
evaluate({ toolCallContext }) {
if (toolCallContext.toolCall.function.name !== 'EnterPlanMode') return undefined;
if (toolCallContext.toolCall.name !== 'EnterPlanMode') return undefined;
return { kind: 'allow' };
},
};

export const ExitPlanModePermissionPolicy: PermissionPolicy = {
name: 'plan.exit-plan-mode',
async evaluate(context) {
if (context.toolCallContext.toolCall.function.name !== 'ExitPlanMode') return undefined;
if (context.toolCallContext.toolCall.name !== 'ExitPlanMode') return undefined;
if (context.mode === 'auto') return { kind: 'allow' };

const review = await resolveExitPlanModeReview(context);
Expand Down Expand Up @@ -82,7 +82,7 @@ export const PlanModeGuardPermissionPolicy: PermissionPolicy = {
evaluate({ agent, toolCallContext }) {
if (!agent.planMode.isActive) return undefined;

const name = toolCallContext.toolCall.function.name;
const name = toolCallContext.toolCall.name;
const args = toolCallContext.args;

if (name === 'Write' || name === 'Edit') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const YoloOutsideWorkspacePermissionPolicy: PermissionPolicy = {
evaluate({ agent, mode, toolCallContext }) {
if (mode !== 'yolo') return undefined;

const toolName = toolCallContext.toolCall.function.name;
const toolName = toolCallContext.toolCall.name;
const toolAccess = FILE_ACCESS_TOOLS[toolName];
if (toolAccess === undefined) return undefined;
const [operation, displayOperation] = toolAccess;
Expand Down
15 changes: 13 additions & 2 deletions packages/agent-core/src/agent/records/migration/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { migrateV1_0ToV1_1 } from './v1.1';

// Wire protocol versions currently support only the `number.number` format.
export const AGENT_WIRE_PROTOCOL_VERSION = '1.0';
export const AGENT_WIRE_PROTOCOL_VERSION = '1.1';

export interface WireMigrationRecord {
readonly type: string;
Expand All @@ -12,7 +14,7 @@ export interface WireMigration {
migrateRecord(record: WireMigrationRecord): WireMigrationRecord;
}

const MIGRATIONS: readonly WireMigration[] = [];
const MIGRATIONS: readonly WireMigration[] = [migrateV1_0ToV1_1];

export function resolveWireMigrations(readVersion: string): readonly WireMigration[] {
if (compareWireVersions(readVersion, AGENT_WIRE_PROTOCOL_VERSION) === 0) {
Expand Down Expand Up @@ -48,6 +50,15 @@ export function migrateWireRecord(
);
}

export function migrateWireRecords(
records: readonly WireMigrationRecord[],
readVersion: string | undefined,
): WireMigrationRecord[] {
const migrations =
readVersion === undefined ? MIGRATIONS : resolveWireMigrations(readVersion);
return records.map((record) => migrateWireRecord(record, migrations));
}

function findMigration(sourceVersion: string): WireMigration | undefined {
for (const migration of MIGRATIONS) {
if (migration.sourceVersion === sourceVersion) return migration;
Expand Down
63 changes: 63 additions & 0 deletions packages/agent-core/src/agent/records/migration/v1.1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import type { WireMigration, WireMigrationRecord } from './index';

/**
* Wire records before v1.1 used a nested `function` wrapper for each tool call:
* { function: { name: 'xxx', arguments: 'yyy' } }
* v1.1 flattens it to:
* { name: 'xxx', arguments: 'yyy' }
*/
interface LegacyToolCall {
type: 'function';
id: string;
function: {
name?: string;
arguments?: string | null;
};
}

function isLegacyToolCall(v: unknown): v is LegacyToolCall {
if (!isRecord(v)) return false;
return v['type'] === 'function' && typeof v['id'] === 'string' && isRecord(v['function']);
}

function migrateToolCall(v: LegacyToolCall): unknown {
const { function: fn, ...rest } = v;
return {
...rest,
name: fn.name,
arguments: fn.arguments,
Comment thread
kermanx marked this conversation as resolved.
};
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

export const migrateV1_0ToV1_1: WireMigration = {
sourceVersion: '1.0',
targetVersion: '1.1',
migrateRecord(record: WireMigrationRecord): WireMigrationRecord {
if (record.type !== 'context.append_message') return record;

const message = record['message'] as {
readonly toolCalls: readonly unknown[];
};

let changed = false;
const toolCalls = message.toolCalls.map((toolCall) => {
if (!isLegacyToolCall(toolCall)) return toolCall;
changed = true;
return migrateToolCall(toolCall);
});

if (!changed) return record;

return {
...record,
message: {
...message,
toolCalls,
},
};
},
};
Loading
Loading