Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions packages/kilo-gateway/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
".": "./src/index.ts",
"./autocomplete": "./src/autocomplete.ts",
"./fim": "./src/fim.ts",
"./edit": "./src/edit.ts",
"./tui": "./src/tui.ts"
},
"files": [
Expand Down
20 changes: 20 additions & 0 deletions packages/kilo-gateway/src/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ export interface AutocompleteModelDef {
readonly directProvider?: DirectAutocompleteProviderID
/** FIM request temperature. */
readonly temperature: number
/**
* Which gateway endpoint this model targets. Defaults to "fim" if omitted
* (back-compat with existing entries). Models with `kind: "edit"` route
* through `/kilo/edit` and use Mercury's Next Edit pipeline.
*/
readonly kind?: "fim" | "edit"
}

const models: AutocompleteModelDef[] = [
Expand Down Expand Up @@ -59,6 +65,20 @@ const models: AutocompleteModelDef[] = [
directProvider: "inception",
temperature: 0,
},
{
// Same wire-level model as `mercury-edit-2`, but routed through the
// Mercury Next Edit endpoint instead of FIM. Picked by users who want
// multi-line next-edit predictions with the jump-to-edit UX.
id: "inception/mercury-next-edit",
modelID: "mercury-next-edit",
label: "Mercury Next Edit",
providerID: "inception",
provider: "Inception",
requestModel: "mercury-edit-2",
directProvider: "inception",
temperature: 0,
kind: "edit",
},
]

export const AUTOCOMPLETE_MODELS: readonly AutocompleteModelDef[] = models
Expand Down
32 changes: 32 additions & 0 deletions packages/kilo-gateway/src/edit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { getAutocompleteModel, type DirectAutocompleteProviderID } from "./autocomplete.js"

/**
* Env var(s) consulted as a fallback for BYOK keys when the provider hasn't
* been authenticated via the gateway's Auth store. Mirrors `DIRECT_FIM_ENV`.
*/
export const DIRECT_EDIT_ENV: Record<DirectAutocompleteProviderID, string[]> = {
mistral: ["MISTRAL_API_KEY"],
inception: ["INCEPTION_API_KEY"],
}

export type EditTarget =
| { provider: "inception"; model: string; url: string }
| { provider: "kilo"; model: string; url: string }

const INCEPTION_EDIT_URL = "https://api.inceptionlabs.ai/v1/edit/completions"

/**
* Pick the upstream edit endpoint for a (provider, model) pair. Only Inception
* is wired up today — Mercury is the only model family with a documented
* /v1/edit/completions endpoint. Mistral does not expose a comparable surface.
*/
export function resolveEditTarget(provider?: string, model?: string): EditTarget {
const info = getAutocompleteModel(provider, model)
if (info.directProvider === "inception") {
return { provider: "inception", model: info.requestModel, url: INCEPTION_EDIT_URL }
}
// Kilo Gateway does not currently proxy an edit endpoint; callers should
// fall back to FIM. We still return a kilo target so the handler can surface
// a 400 rather than silently routing somewhere unexpected.
return { provider: "kilo", model: info.requestModel, url: "" }
}
113 changes: 113 additions & 0 deletions packages/kilo-gateway/src/server/edit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { DIRECT_EDIT_ENV, resolveEditTarget, type EditTarget } from "../edit.js"
import type { AuthStore } from "./handlers.js"

type Auth = Pick<AuthStore, "get">

const EDIT_TIMEOUT_MS = 30_000
const MAX_TOKENS_DEFAULT = 512

async function getProviderKey(Auth: Auth, provider: "inception" | "mistral"): Promise<string | undefined> {
const auth = await Auth.get(provider)
if (auth?.type === "api") return auth.key
return DIRECT_EDIT_ENV[provider].map((key) => process.env[key]).find(Boolean)
}

/**
* Extract the rewritten code from Mercury's reply. Mercury always wraps the
* editable region in a triple-backtick fence, sometimes with a language tag
* and sometimes with `<|code_to_edit|>` markers inside. Mirrors the parser the
* VSCode side used to run; doing it gateway-side keeps the Mercury contract
* in one place.
*/
function extractFencedBody(message: string): string {
if (!message) return ""
const fenceOpen = message.indexOf("```")
if (fenceOpen === -1) return message

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

WARNING: extractFencedBody returns the raw message when no code fence is found, but the old parseMercuryEditReply (still present in editCompletionParser.ts) returned null for the same case.

If Mercury responds without a triple-backtick fence — e.g. a rate-limit prose message, a refusal, or an unexpected format — the full response text will propagate to parseSuccess as replacement, pass the replacement.length === 0 guard, and be inserted directly into the user's document as code.

Consider returning "" instead so the gateway's response schema sends content: "", which parseSuccess already treats as a no-op (replacement.length === 0 → return null):

Suggested change
if (fenceOpen === -1) return message
if (fenceOpen === -1) return ""

const afterFenceOpen = message.indexOf("\n", fenceOpen + 3)
if (afterFenceOpen === -1) return ""
const fenceClose = message.lastIndexOf("```")
if (fenceClose <= afterFenceOpen) return ""
let body = message.slice(afterFenceOpen + 1, fenceClose)
if (body.endsWith("\n")) body = body.slice(0, -1)
body = body.replace(/^<\|code_to_edit\|>\n?/, "")
body = body.replace(/\n?<\|\/code_to_edit\|>$/, "")
return body
}

interface UpstreamResponse {
choices?: Array<{ message?: { content?: string } }>
usage?: { prompt_tokens?: number; completion_tokens?: number }
}

export function createEditHandler(Auth: Auth) {
return async (c: any) => {
const { content, provider, model, maxTokens } = c.req.valid("json")
const target = resolveEditTarget(provider, model)

if (target.provider !== "inception") {
return c.json({ error: "Next Edit currently requires the Inception provider (mercury-edit-2)." }, 400 as any)
}

const token = await getProviderKey(Auth, target.provider)
if (!token) {
return c.json({ error: `Missing ${target.provider} provider API key` }, 401 as any)
}

const signal = AbortSignal.any([c.req.raw.signal, AbortSignal.timeout(EDIT_TIMEOUT_MS)])
console.info(`[EDIT] request provider=${target.provider} model=${target.model} url=${target.url} chars=${content.length}`)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

WARNING: console.info fires on every NES edit request via the gateway server's stdout. This is the same class of issue previously noted for fim.ts. Gateway logs should use a structured logger or be gated on a debug flag — unconditional console.info will appear in server logs on every keystroke trigger. Consider removing or replacing with the nesLog/debug-gated pattern used on the VSCode side.


let response: Response
try {
response = await fetch(target.url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
signal,
body: JSON.stringify({
model: target.model,
max_tokens: maxTokens ?? MAX_TOKENS_DEFAULT,
// Mercury rejects role:"system" on this endpoint — must be a single
// user message. See the integration's constants.ts for context.
messages: [{ role: "user", content }],
}),
})
} catch (err) {
if (err instanceof DOMException && err.name === "TimeoutError") {
return c.json({ error: "Edit request timed out" }, 504 as any)
}
if (signal.aborted) return c.json({ error: "Edit request canceled" }, 499 as any)
throw err
}

if (!response.ok) {
const text = await safeText(response)
return c.json({ error: `Edit request failed: ${response.status} ${text}` }, response.status as any)
}

const json = (await response.json()) as UpstreamResponse
const replyContent = json.choices?.[0]?.message?.content ?? ""
const body = extractFencedBody(replyContent)
return c.json({
content: body,
usage: json.usage
? {
prompt_tokens: json.usage.prompt_tokens,
completion_tokens: json.usage.completion_tokens,
}
: undefined,
})
}
}

async function safeText(res: Response): Promise<string> {
try {
return await res.text()
} catch {
return "<unreadable>"
}
}

// Re-export the target type for tests + the opencode handler
export type { EditTarget }
42 changes: 42 additions & 0 deletions packages/kilo-gateway/src/server/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { KILO_API_BASE, HEADER_FEATURE, HEADER_ORGANIZATIONID } from "../api/con
import { buildKiloHeaders } from "../headers.js"
import type { ImportDeps, DrizzleDb } from "../cloud-sessions.js"
import { fetchCloudSession, fetchCloudSessionForImport, importSessionToDb } from "../cloud-sessions.js"
import { createEditHandler } from "./edit.js"
import { createFimHandler } from "./fim.js"
import {
GatewayError,
Expand Down Expand Up @@ -112,6 +113,16 @@ export function createKiloRoutes(deps: KiloRoutesDeps) {
currentOrgId: z.string().nullable(),
})

const EditCompletionResponse = z.object({
content: z.string(),
usage: z
.object({
prompt_tokens: z.number().optional(),
completion_tokens: z.number().optional(),
})
.optional(),
})

const FimStreamChunk = z.object({
choices: z
.array(
Expand Down Expand Up @@ -325,6 +336,37 @@ export function createKiloRoutes(deps: KiloRoutesDeps) {
),
createFimHandler(Auth),
)
.post(
"/edit",
describeRoute({
summary: "Next Edit completion",
description:
"Proxy a Mercury-style Next Edit request. The user supplies the already-templated " +
"sentinel-tagged prompt in `content`; the gateway forwards to the upstream edit endpoint.",
operationId: "kilo.edit",
responses: {
200: {
description: "Next Edit completion",
content: {
"application/json": {
schema: resolver(EditCompletionResponse),
},
},
},
...errors(400, 401),
},
}),
validator(
"json",
z.object({
content: z.string(),
provider: z.string().optional(),
model: z.string().optional(),
maxTokens: z.number().optional(),
}),
),
createEditHandler(Auth),
)
.post(
"/audio/transcriptions",
describeRoute({
Expand Down
Loading