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
26 changes: 20 additions & 6 deletions src/api/providers/openrouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,8 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH

addNativeToolCallsToParams(requestOptions, this.options, metadata)

// kilocode_change: logs removed

let stream
try {
stream = await this.client.chat.completions.create(
Expand All @@ -241,6 +243,7 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH

try {
let fullContent = ""
let fullReasoning = "" // kilocode_change: variable kept for structural integrity if needed, but unused logs removed

let isThinking = false

Expand Down Expand Up @@ -302,8 +305,8 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH
isThinking = false
}

newText = newText.replace(/<\/?think>/g, "")
newText = newText.replace(/<think>/g, "")
// newText = newText.replace(/<\/?think>/g, "")
// newText = newText.replace(/<think>/g, "")

yield {
type: "reasoning",
Expand All @@ -318,12 +321,24 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH
}
}

// kilocode_change start: Handle reasoning from API (both 'reasoning' and 'reasoning_content' keys)
// Some models send 'reasoning', others send 'reasoning_content'
if ("reasoning" in delta && delta.reasoning) {
const reasoningText = (delta.reasoning as string | undefined) || ""
yield {
type: "reasoning",
text: reasoningText,
}
}

if ("reasoning_content" in delta && delta.reasoning_content) {
const reasoningText = (delta.reasoning_content as string | undefined) || ""
yield {
type: "reasoning",
text: (delta.reasoning_content as string | undefined) || "",
text: reasoningText,
}
}
// kilocode_change end

// Handle native tool calls when toolStyle is "json"
yield* processNativeToolCallsFromDelta(delta, getActiveToolUseStyle(this.options))
Expand All @@ -333,6 +348,8 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH
// yield { type: "text", text: delta.content }
// }
}

// kilocode_change: logs removed
} catch (error) {
console.error("OpenRouter API Error:", error)
let errorMessage = makeOpenRouterErrorReadable(error)
Expand Down Expand Up @@ -556,9 +573,6 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH
// kilocode_change start
function makeOpenRouterErrorReadable(error: any) {
try {
// Add logging to help debug the issue
console.debug("makeOpenRouterErrorReadable called with error:", JSON.stringify(error, null, 2))

const metadata = error?.error?.metadata as { raw?: string; provider_name?: string } | undefined
const parsedJson = safeJsonParse(metadata?.raw)
const rawError = parsedJson as { error?: string & { message?: string }; detail?: string } | undefined
Expand Down
54 changes: 46 additions & 8 deletions src/api/transform/openai-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,36 @@ export function convertToOpenAiMessages(

for (const anthropicMessage of anthropicMessages) {
if (typeof anthropicMessage.content === "string") {
openAiMessages.push({ role: anthropicMessage.role, content: anthropicMessage.content })
// kilocode_change start: Preserve reasoning fields for assistant messages with string content
if (anthropicMessage.role === "assistant") {
const messageWithReasoning = anthropicMessage as typeof anthropicMessage & {
reasoning?: string
reasoning_content?: string
}
const assistantMsg: OpenAI.Chat.ChatCompletionAssistantMessageParam = {
role: "assistant",
content: anthropicMessage.content,
}
if (messageWithReasoning.reasoning) {
;(assistantMsg as any).reasoning = messageWithReasoning.reasoning
}
if (messageWithReasoning.reasoning_content) {
;(assistantMsg as any).reasoning_content = messageWithReasoning.reasoning_content
}
openAiMessages.push(assistantMsg)
} else {
openAiMessages.push({ role: anthropicMessage.role, content: anthropicMessage.content })
}
// kilocode_change end
} else {
// image_url.url is base64 encoded image data
// ensure it contains the content-type of the image: data:image/png;base64,
/*
{ role: "user", content: "" | { type: "text", text: string } | { type: "image_url", image_url: { url: string } } },
// content required unless tool_calls is present
{ role: "assistant", content?: "" | null, tool_calls?: [{ id: "", function: { name: "", arguments: "" }, type: "function" }] },
{ role: "tool", tool_call_id: "", content: ""}
*/
{ role: "user", content: "" | { type: "text", text: string } | { type: "image_url", image_url: { url: string } } },
// content required unless tool_calls is present
{ role: "assistant", content?: "" | null, tool_calls?: [{ id: "", function: { name: "", arguments: "" }, type: "function" }] },
{ role: "tool", tool_call_id: "", content: ""}
*/
if (anthropicMessage.role === "user") {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
Expand Down Expand Up @@ -139,12 +159,30 @@ export function convertToOpenAiMessages(
},
}))

openAiMessages.push({
// kilocode_change start: Preserve reasoning fields from the original message
// Some models (DeepSeek, OpenRouter, etc.) return reasoning/reasoning_content
// in their responses, and these should be passed through in subsequent API calls
const assistantMsg: OpenAI.Chat.ChatCompletionAssistantMessageParam = {
role: "assistant",
content,
// Cannot be an empty array. API expects an array with minimum length 1, and will respond with an error if it's empty
tool_calls: tool_calls.length > 0 ? tool_calls : undefined,
})
}

// Pass through reasoning fields if present on the source message
const messageWithReasoning = anthropicMessage as typeof anthropicMessage & {
reasoning?: string
reasoning_content?: string
}
if (messageWithReasoning.reasoning) {
;(assistantMsg as any).reasoning = messageWithReasoning.reasoning
}
if (messageWithReasoning.reasoning_content) {
;(assistantMsg as any).reasoning_content = messageWithReasoning.reasoning_content
}

openAiMessages.push(assistantMsg)
// kilocode_change end
}
}
}
Expand Down
7 changes: 6 additions & 1 deletion src/core/task-persistence/apiMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ import { fileExistsAtPath } from "../../utils/fs"
import { GlobalFileNames } from "../../shared/globalFileNames"
import { getTaskDirectoryPath } from "../../utils/storage"

export type ApiMessage = Anthropic.MessageParam & { ts?: number; isSummary?: boolean }
export type ApiMessage = Anthropic.MessageParam & {
ts?: number
isSummary?: boolean
reasoning?: string
reasoning_content?: string
}

export async function readApiMessages({
taskId,
Expand Down
34 changes: 24 additions & 10 deletions src/core/task/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2239,18 +2239,18 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
switch (chunk.type) {
case "reasoning": {
reasoningMessage += chunk.text
// Only apply formatting if the message contains sentence-ending punctuation followed by **
let formattedReasoning = reasoningMessage
if (reasoningMessage.includes("**")) {
// Add line breaks before **Title** patterns that appear after sentence endings
// This targets section headers like "...end of sentence.**Title Here**"
// Handles periods, exclamation marks, and question marks
formattedReasoning = reasoningMessage.replace(
/([.!?])\*\*([^*\n]+)\*\*/g,
"$1\n\n**$2**",
)
}
await this.say("reasoning", formattedReasoning, undefined, true)
if (formattedReasoning.includes("<think>")) {
formattedReasoning = formattedReasoning.replace(/<\/?think>/g, "")
formattedReasoning = formattedReasoning.replace(/<think>/g, "")
await this.say("reasoning", formattedReasoning, undefined, true)
}
break
}
case "usage":
Expand Down Expand Up @@ -2685,10 +2685,21 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
assistantMessageContent.push({ type: "text", text: assistantMessage })
}
assistantMessageContent.push(...assistantToolUses)
await this.addToApiConversationHistory({

const assistantHistoryMessage: Anthropic.MessageParam & {
reasoning?: string
reasoning_content?: string
} = {
role: "assistant",
content: assistantMessageContent,
})
}

// Add reasoning content if present
if (reasoningMessage) {
assistantHistoryMessage.reasoning = reasoningMessage
}

await this.addToApiConversationHistory(assistantHistoryMessage)
// kilocode_change end

TelemetryService.instance.captureConversationMessage(this.taskId, "assistant")
Expand Down Expand Up @@ -3138,9 +3149,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
}

const messagesSinceLastSummary = getMessagesSinceLastSummary(this.apiConversationHistory)
let cleanConversationHistory = maybeRemoveImageBlocks(messagesSinceLastSummary, this.api).map(
({ role, content }) => ({ role, content }),
)
let cleanConversationHistory = maybeRemoveImageBlocks(messagesSinceLastSummary, this.api).map((msg) => ({
role: msg.role,
content: msg.content,
// kilocode_change: preserve reasoning
...("reasoning" in msg ? { reasoning: (msg as any).reasoning } : {}),
}))

// kilocode_change start
// Fetch project properties for KiloCode provider tracking
Expand Down
8 changes: 7 additions & 1 deletion src/core/tools/readFileTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,12 +303,16 @@ export async function readFileTool(
const batchFiles = filesToApprove.map((fileResult) => {
const relPath = fileResult.path
const fullPath = path.isAbsolute(relPath) ? relPath : path.resolve(cline.cwd, relPath)
const offset = fileResult.offset
const limit = fileResult.limit
return {
path: getReadablePath(cline.cwd, relPath),
lineSnippet: "",
lineSnippet: offset !== undefined && limit !== undefined ? `#L${offset}-${offset + limit - 1}` : "",
isOutsideWorkspace: isPathOutsideWorkspace(fullPath),
key: relPath,
content: fullPath,
offset,
limit,
}
})

Expand Down Expand Up @@ -342,6 +346,8 @@ export async function readFileTool(
path: getReadablePath(cline.cwd, relPath),
isOutsideWorkspace,
content: fullPath,
offset: fileResult.offset || 0,
limit: fileResult.limit || MAX_READ_FILE_LINES,
} satisfies ClineSayTool)

// kilocode_change: Auto-approve - show in UI and immediately approve
Expand Down
4 changes: 4 additions & 0 deletions src/core/webview/webviewMessageHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1281,13 +1281,17 @@ export const webviewMessageHandler = async (
}
}

// Get the first changed line number from the diff anchor (1-indexed for VS Code)
const firstLineNumber = edit.diffAnchor ? edit.diffAnchor.start.line + 1 : undefined

return {
relPath: edit.relPath,
absolutePath: edit.absolutePath,
stat: {
additions: totalAdditions,
deletions: totalDeletions,
},
firstLineNumber,
}
})

Expand Down
2 changes: 1 addition & 1 deletion src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"displayName": "%extension.displayName%",
"description": "%extension.description%",
"publisher": "matterai",
"version": "5.3.4",
"version": "5.3.5",
"icon": "assets/icons/matterai-ic.png",
"galleryBanner": {
"color": "#FFFFFF",
Expand Down
4 changes: 4 additions & 0 deletions src/shared/ExtensionMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -516,12 +516,16 @@ export interface ClineSayTool {
endLine?: number
lineNumber?: number
query?: string
offset?: number
limit?: number
batchFiles?: Array<{
path: string
lineSnippet: string
isOutsideWorkspace?: boolean
key: string
content?: string
offset?: number
limit?: number
}>
batchDiffs?: Array<{
path: string
Expand Down
11 changes: 11 additions & 0 deletions webview-ui/src/components/chat/BatchDiffApproval.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { vscode } from "@/utils/vscode"
import React, { memo, useState } from "react"
import CodeAccordian from "../common/CodeAccordian"

Expand Down Expand Up @@ -37,6 +38,8 @@ export const BatchDiffApproval = memo(({ files = [], ts }: BatchDiffApprovalProp
{files.map((file) => {
// Combine all diffs into a single diff string for this file
const combinedDiff = file.diffs?.map((diff) => diff.content).join("\n\n") || file.content
// Get the first changed line from the diffs, or fallback to extracting from combined diff
const firstChangedLine = file.diffs?.find((d) => d.startLine)?.startLine

return (
<div key={`${file.path}-${ts}`}>
Expand All @@ -46,6 +49,14 @@ export const BatchDiffApproval = memo(({ files = [], ts }: BatchDiffApprovalProp
language="diff"
isExpanded={expandedFiles[file.path] || false}
onToggleExpand={() => handleToggleExpand(file.path)}
onJumpToFile={(line) =>
vscode.postMessage({
type: "openFile",
text: "./" + file.path,
values:
(line ?? firstChangedLine) ? { line: line ?? firstChangedLine } : undefined,
})
}
/>
</div>
)
Expand Down
Loading
Loading