Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
33eb706
fix(vscode): support direct autocomplete FIM providers
May 25, 2026
900b1fc
docs(vscode): clarify autocomplete FIM changeset
May 25, 2026
c09c5c4
refactor(vscode): route direct FIM through backend
May 25, 2026
d635a15
test(vscode): update autocomplete selector expectations
May 25, 2026
2bf49bd
refactor(gateway): extract FIM routing
May 25, 2026
25e89db
refactor(gateway): own autocomplete model catalog
May 25, 2026
afde386
fix(gateway): preserve legacy autocomplete model ids
May 25, 2026
4cd463d
refactor(gateway): split autocomplete provider and model
May 26, 2026
bfda8fe
fix(vscode): import browser-safe autocomplete catalog
May 26, 2026
08124be
Merge remote-tracking branch 'origin/main' into mark/direct-autocompl…
May 26, 2026
cc50d76
fix(kilo-docs): exclude FIM API endpoints from link check
May 26, 2026
cef6164
fix(vscode): use autocomplete provider for chat completions
May 26, 2026
19719ba
fix(gateway): use env keys for direct FIM providers
May 26, 2026
e5b2bb8
fix(gateway): preserve FIM gateway model passthrough
May 26, 2026
6fb50a8
fix(vscode): infer autocomplete provider from direct models
May 26, 2026
4ca226c
fix(gateway): cache working Mistral FIM endpoint
May 26, 2026
c073dac
refactor(gateway): clarify Mistral FIM endpoint helper
May 26, 2026
d02145a
refactor(gateway): simplify Mistral FIM endpoint cache
May 26, 2026
9b1407e
refactor(gateway): remove unshipped autocomplete aliases
May 26, 2026
5590b43
refactor(gateway): simplify autocomplete model lookup
May 26, 2026
762eb22
refactor(gateway): share autocomplete provider types
May 26, 2026
bbc57f6
Merge branch 'main' into mark/direct-autocomplete-fim-providers
May 26, 2026
923d955
fix: address autocomplete FIM review findings
May 26, 2026
80e39c2
Merge branch 'main' into mark/direct-autocomplete-fim-providers
May 26, 2026
be5b4f9
fix(vscode): never infer direct autocomplete provider from model name
May 26, 2026
80f8781
refactor(gateway): make FimTarget a discriminated union
May 26, 2026
21b5607
chore: trigger CI
May 26, 2026
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
5 changes: 5 additions & 0 deletions .changeset/direct-fim-providers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Add explicit Mistral and Inception autocomplete options that use connected provider API keys for FIM requests.
8 changes: 7 additions & 1 deletion packages/kilo-docs/source-links.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
# Source Code Links

<!-- Auto-generated by script/extract-source-links.ts — DO NOT EDIT -->
<!-- 86 unique URLs extracted from extension and CLI source -->
<!-- 89 unique URLs extracted from extension and CLI source -->

- <https://api.apertis.ai/v1>
<!-- packages/opencode/src/provider/model-cache.ts -->
<!-- packages/opencode/src/provider/models.ts -->
- <https://api.inceptionlabs.ai/v1/fim/completions>
<!-- packages/kilo-vscode/src/services/autocomplete/fim.ts -->
- <https://api.kilo.ai>
<!-- packages/opencode/src/cli/cmd/github.ts -->
- <https://api.mistral.ai/v1/fim/completions>
<!-- packages/kilo-vscode/src/services/autocomplete/fim.ts -->
- <https://app.kilo.ai>
<!-- packages/opencode/src/kilocode/kilo-commands.tsx -->
- <https://app.kilo.ai/claw>
Expand All @@ -32,6 +36,8 @@
<!-- packages/kilo-vscode/src/agent-manager/WorktreeManager.ts -->
- <https://cloudflare.com/cdn-cgi/trace>
<!-- packages/opencode/src/session/network.ts -->
- <https://codestral.mistral.ai/v1/fim/completions>
<!-- packages/kilo-vscode/src/services/autocomplete/fim.ts -->
- <https://cookbook.openai.com/examples/using_logprobs>
<!-- packages/opencode/src/provider/sdk/copilot/responses/openai-responses-language-model.ts -->
- <https://docs.github.com/en/actions/how-tos/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services>
Expand Down
10 changes: 7 additions & 3 deletions packages/kilo-vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -753,11 +753,15 @@
"type": "string",
"enum": [
"mistralai/codestral-2508",
"inception/mercury-edit-2"
"inception/mercury-edit-2",
"mistral/codestral-2508",
"inception-direct/mercury-edit-2"
],
"enumDescriptions": [
"Codestral by Mistral AI (default)",
"Mercury Edit 2 by Inception"
"Codestral via Kilo Gateway (default)",
"Mercury Edit 2 via Kilo Gateway",
"Codestral via your connected Mistral provider API key",
"Mercury Edit 2 via your connected Inception provider API key"
],
"description": "Model to use for inline autocomplete suggestions"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ export class AutocompleteServiceManager {
}

private getCurrentModelName(): string {
return this.inlineCompletionProvider.getModelId()
return getAutocompleteModel(this.inlineCompletionProvider.getModelId()).label
}

private getCurrentProviderName(): string {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,36 +65,14 @@ export class FimPromptBuilder {
signal?: AbortSignal,
): Promise<FimCompletionResult> {
const { formattedPrefix, prunedSuffix, autocompleteInput } = prompt
let perflog = ""
const logtime = (() => {
let timestamp = performance.now()
return (msg: string) => {
const baseline = timestamp
timestamp = performance.now()
perflog += `${msg}: ${timestamp - baseline}\n`
}
})()

logtime("snippets")

console.log("[FIM] formattedPrefix:", formattedPrefix)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

remvoed this because it spammed the logs


let response = ""
const onChunk = (text: string) => {
response += text
}
logtime("prep fim")
const usageInfo = await generateFim(connection, modelId, formattedPrefix, prunedSuffix, onChunk, signal)
logtime("fim network")
console.log("[FIM] response:", response)

const fillInAtCursorSuggestion = processSuggestion(response)

if (fillInAtCursorSuggestion.text) {
console.info("Final FIM suggestion:", fillInAtCursorSuggestion)
}
logtime("processSuggestion")
console.log(perflog + `lengths: ${formattedPrefix.length + prunedSuffix.length}\n`)
return {
suggestion: fillInAtCursorSuggestion,
cost: usageInfo.cost,
Expand Down
193 changes: 190 additions & 3 deletions packages/kilo-vscode/src/services/autocomplete/fim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,173 @@ import { ResponseMetaData } from "./types"
import type { KiloConnectionService } from "../cli-backend"
import { getAutocompleteModel } from "../../shared/autocomplete-models"

const FIM_MAX_TOKENS = 256
const MISTRAL_FIM_URL = "https://api.mistral.ai/v1/fim/completions"
const CODESTRAL_FIM_URL = "https://codestral.mistral.ai/v1/fim/completions"
const INCEPTION_FIM_URL = "https://api.inceptionlabs.ai/v1/fim/completions"

type FimProvider = "mistral" | "inception"

interface DirectFimTarget {
provider: FimProvider
model: string
urls: string[]
}

interface ProviderItem {
id: string
key?: string
options?: Record<string, unknown>
}

interface ProviderListResponse {
all: ProviderItem[]
}

interface DirectFimChunk {
choices?: Array<{
delta?: { content?: string }
text?: string
}>
usage?: {
prompt_tokens?: number
completion_tokens?: number
}
}

interface DirectFimOptions {
apiKey: string
target: DirectFimTarget
prefix: string
suffix: string
temperature: number
onChunk: (text: string) => void
signal?: AbortSignal
fetchImpl?: typeof fetch
}

export function getDirectFimTarget(model: string): DirectFimTarget | null {
const info = getAutocompleteModel(model)
if (info.directProvider === "mistral") {
return { provider: "mistral", model: info.requestModel, urls: [MISTRAL_FIM_URL, CODESTRAL_FIM_URL] }
}
if (info.directProvider === "inception") {
return { provider: "inception", model: info.requestModel, urls: [INCEPTION_FIM_URL] }
}
return null
}

async function resolveProviderKey(connectionService: KiloConnectionService, provider: FimProvider): Promise<string | null> {
const client = await connectionService.getClientAsync()
const result = await client.provider.list({}, { throwOnError: true })
const data = result.data as ProviderListResponse | undefined
const item = data?.all.find((p) => p.id === provider)
const key = item?.options?.apiKey
return item?.key ?? (typeof key === "string" ? key : null)
}

function extractDirectFimContent(chunk: DirectFimChunk): string {
const choice = chunk.choices?.[0]
return choice?.delta?.content ?? choice?.text ?? ""
}

function parseDirectFimEvent(data: string): DirectFimChunk | null {
if (data === "[DONE]") return null
return JSON.parse(data) as DirectFimChunk
}

function parseDirectFimLine(line: string): string | null {
const trimmed = line.trim()
if (!trimmed.startsWith("data:")) return null
return trimmed.slice("data:".length).trim()
}

function handleDirectFimLine(
line: string,
onChunk: (text: string) => void,
usage: { inputTokens: number; outputTokens: number },
) {
const data = parseDirectFimLine(line)
if (!data) return
const event = parseDirectFimEvent(data)
if (!event) return
const content = extractDirectFimContent(event)
if (content) onChunk(content)
usage.inputTokens = event.usage?.prompt_tokens ?? usage.inputTokens
usage.outputTokens = event.usage?.completion_tokens ?? usage.outputTokens
}

export async function generateDirectFim(options: DirectFimOptions): Promise<ResponseMetaData> {
const urls = [...options.target.urls]
const [url] = urls
if (!url) throw new Error("FIM request failed: 500 missing provider endpoint")
return generateDirectFimWithUrl(options, url, urls.slice(1))
}

async function generateDirectFimWithUrl(
options: DirectFimOptions,
url: string,
fallbacks: string[],
): Promise<ResponseMetaData> {
const fetchImpl = options.fetchImpl ?? fetch
console.info(`[FIM] request provider=${options.target.provider} model=${options.target.model} url=${url}`)
const res = await fetchImpl(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.apiKey}`,
},
body: JSON.stringify({
model: options.target.model,
prompt: options.prefix,
suffix: options.suffix,
max_tokens: FIM_MAX_TOKENS,
temperature: options.temperature,
stream: true,
}),
signal: options.signal,
})

if (!res.ok) {
const body = await res.text().catch(() => "")
const [next] = fallbacks
if (res.status === 401 && next) return generateDirectFimWithUrl(options, next, fallbacks.slice(1))
throw new Error(`FIM request failed: ${res.status} ${res.statusText}: ${body}`)
}

if (!res.body) throw new Error("FIM request failed: 500 empty response body")

const reader = res.body.getReader()
const decoder = new TextDecoder()
const usage = { inputTokens: 0, outputTokens: 0 }
let pending = ""

while (true) {
const chunk = await reader.read()
if (chunk.done) break
pending += decoder.decode(chunk.value, { stream: true })
const lines = pending.split("\n")
pending = lines.pop() ?? ""

for (const line of lines) {
handleDirectFimLine(line, options.onChunk, usage)
}
}

pending += decoder.decode()
handleDirectFimLine(pending, options.onChunk, usage)

reader.releaseLock()

return {
cost: 0,
inputTokens: usage.inputTokens,
outputTokens: usage.outputTokens,
cacheWriteTokens: 0,
cacheReadTokens: 0,
}
}

/**
* Generate a FIM (Fill-in-the-Middle) completion via the CLI backend.
* Uses the SDK's kilo.fim() SSE endpoint which handles auth and streaming.
Expand All @@ -17,6 +184,25 @@ export async function generateFim(
signal?: AbortSignal,
): Promise<ResponseMetaData> {
const client = await connectionService.getClientAsync()
const info = getAutocompleteModel(modelId)
const target = getDirectFimTarget(modelId)
const key = info.directProvider ? await resolveProviderKey(connectionService, info.directProvider).catch(() => null) : null

if (target && !key) {
throw new Error(`FIM request failed: 401 Missing ${target.provider} provider API key`)
}

if (target && key) {
return generateDirectFim({
apiKey: key,
target,
prefix,
suffix,
temperature: info.temperature,
onChunk,
signal,
})
}

let cost = 0
let inputTokens = 0
Expand All @@ -27,14 +213,15 @@ export async function generateFim(
// ends the stream. Without this, errors never reach ErrorBackoff.
let sseError: Error | undefined

const temp = getAutocompleteModel(modelId).temperature
const temp = info.temperature
console.info(`[FIM] request provider=kilo model=${info.requestModel} url=/kilo/fim`)

const { stream } = await client.kilo.fim(
{
prefix,
suffix,
model: modelId,
maxTokens: 256,
model: info.requestModel,
maxTokens: FIM_MAX_TOKENS,
temperature: temp,
},
{
Expand Down
42 changes: 38 additions & 4 deletions packages/kilo-vscode/src/shared/autocomplete-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,61 @@
*/

export interface AutocompleteModelDef {
/** Full model ID sent to the gateway, e.g. "mistralai/codestral-2508" */
/** Stable setting value. */
readonly id: string
/** Model ID displayed under the selector provider group. */
readonly modelID: string
/** Human-readable label shown in the settings dropdown */
readonly label: string
/** Provider ID used by the selector group. */
readonly providerID: string
/** Provider display name for status bar / telemetry */
readonly provider: string
/** Full model ID sent to the FIM API. */
readonly requestModel: string
/** Provider key to use for direct BYOK FIM. Empty means Kilo Gateway. */
readonly directProvider?: "mistral" | "inception"
/** FIM request temperature */
readonly temperature: number
}

const models: AutocompleteModelDef[] = [
{
id: "mistralai/codestral-2508",
label: "Codestral (Mistral AI)",
provider: "Mistral AI",
modelID: "mistralai/codestral-2508",
label: "Codestral",
providerID: "kilo",
provider: "Kilo Gateway",
requestModel: "mistralai/codestral-2508",
temperature: 0.2,
},
{
id: "inception/mercury-edit-2",
label: "Mercury Edit 2 (Inception)",
modelID: "inception/mercury-edit-2",
label: "Mercury Edit 2",
providerID: "kilo",
provider: "Kilo Gateway",
requestModel: "inception/mercury-edit-2",
temperature: 0,
},
{
id: "mistral/codestral-2508",
modelID: "codestral-2508",
label: "Codestral",
providerID: "mistral",
provider: "Mistral",
requestModel: "codestral-2508",
directProvider: "mistral",
temperature: 0.2,
},
{
id: "inception-direct/mercury-edit-2",
modelID: "mercury-edit-2",
label: "Mercury Edit 2",
providerID: "inception",
provider: "Inception",
requestModel: "mercury-edit-2",
directProvider: "inception",
temperature: 0,
},
]
Expand Down
Loading