Skip to content
5 changes: 5 additions & 0 deletions .changeset/jetbrains-custom-provider-env-var-models.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kilocode/kilo-jetbrains": patch
---

Use the configured API key environment variable (or an already-saved key) when selecting models for a custom OpenAI-compatible provider, instead of requiring the key to be retyped every time. Also allow removing custom providers that authenticate through an environment variable, and stop a cleared environment variable from lingering in the saved configuration.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import ai.kilocode.rpc.dto.ProviderOAuthAuthorizeDto
import ai.kilocode.rpc.dto.ProviderOAuthCallbackDto
import ai.kilocode.rpc.dto.ProviderOAuthReadyDto
import ai.kilocode.rpc.dto.ProviderSettingsDto
import com.intellij.util.EnvironmentUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
Expand Down Expand Up @@ -111,7 +112,7 @@ internal class KiloBackendProviderSettingsManager(
if (input.providerId == "kilo") {
return ProviderActionResultDto(current, error = "Kilo Gateway cannot be disconnected from provider settings.")
}
if (provider?.source == "env") {
if (provider?.source == "env" && cfg == null) {
return ProviderActionResultDto(current, error = "Provider is configured by environment variables.")
}
val configured = input.providerId in current.connected || provider?.key != null || provider?.source == "config" || cfg != null
Expand All @@ -124,7 +125,7 @@ internal class KiloBackendProviderSettingsManager(
dispose()
return ProviderActionResultDto(state(input.directory))
}
if (provider?.source == "config") {
if (cfg != null || provider?.source == "config") {
val scope = cfg?.scope ?: "global"
val ids = disabledFor(current, scope) + input.providerId
patch(input.directory, scope, KiloCliDataParser.buildDisabledProviderPatch(ids))
Expand All @@ -149,7 +150,19 @@ internal class KiloBackendProviderSettingsManager(
suspend fun saveCustom(input: CustomProviderSaveDto): ProviderActionResultDto {
val err = validate(input)
if (err != null) return ProviderActionResultDto(state(input.directory), error = err)
patch(KiloCliDataParser.buildCustomProviderPatch(input))
// The config schema only allows nulling a whole provider entry (to delete it), not an
// individual field inside one, so a previously-set env var can only be cleared by deleting
// the entry before the patch below recreates it. Only do this when there is an existing env
// var to clear: deleting drops any fields the recreate patch doesn't set (e.g. a
// hand-authored whitelist/blacklist), and a failure between the two patches would otherwise
// leave the entry missing until the next successful save.
val cfg = if (input.envVar.isNullOrBlank()) state(input.directory).config[input.id] else null
val stale = cfg?.takeIf { it.env.isNotEmpty() }
if (stale != null) patch(KiloCliDataParser.buildCustomProviderDeletePatch(input.id))
// The dialog never edits headers, so the delete above would otherwise drop hand-authored
// ones: carry them into the recreate patch when the save itself doesn't set any.
val save = if (stale != null && input.headers.isEmpty()) input.copy(headers = stale.headers) else input
patch(KiloCliDataParser.buildCustomProviderPatch(save))
if (input.envVar.isNullOrBlank()) {
val key = input.apiKey?.takeIf { it.isNotBlank() }
if (key != null) put("/auth/${enc(input.id)}", KiloCliDataParser.buildProviderAuthJson(key, emptyMap()))
Expand All @@ -160,12 +173,18 @@ internal class KiloBackendProviderSettingsManager(
return ProviderActionResultDto(state(input.directory))
}

suspend fun fetch(input: CustomModelFetchDto): CustomModelFetchResultDto {
suspend fun fetch(input: CustomModelFetchDto, env: Map<String, String> = EnvironmentUtil.getEnvironmentMap()): CustomModelFetchResultDto {
val name = input.env?.trim()?.takeIf { it.isNotBlank() }
val resolved = name?.let { env[it]?.takeIf(String::isNotBlank) }
val stored = if (input.apiKey.isNullOrBlank() && resolved == null) storedKey(input) else null
val key = input.apiKey?.takeIf { it.isNotBlank() } ?: resolved ?: stored
val envMissing = name != null && resolved == null
val url = input.baseUrl.trim().trimEnd('/') + "/models"
LOG.debug { "custom provider model fetch: env=$name resolved=${resolved != null} stored=${stored != null}" }
return try {
val request = Request.Builder().url(url).get().apply {
input.apiKey?.takeIf { it.isNotBlank() }?.let { header("Authorization", "Bearer $it") }
input.headers.forEach { (key, value) -> header(key, value) }
key?.let { header("Authorization", "Bearer $it") }
input.headers.forEach { (headerKey, value) -> header(headerKey, value) }
}.build()
val raw = withContext(Dispatchers.IO) {
FETCH.newCall(request).execute().use { response ->
Expand All @@ -174,13 +193,18 @@ internal class KiloBackendProviderSettingsManager(
body
}
}
CustomModelFetchResultDto(KiloCliDataParser.parseModelIds(raw))
CustomModelFetchResultDto(KiloCliDataParser.parseModelIds(raw), envMissing = envMissing)
} catch (e: Exception) {
LOG.warn("Custom provider model fetch failed: ${e.message}", e)
CustomModelFetchResultDto(error = e.message)
CustomModelFetchResultDto(error = e.message, envMissing = envMissing)
}
}

private suspend fun storedKey(input: CustomModelFetchDto): String? {
val id = input.providerId?.trim()?.takeIf { it.isNotBlank() } ?: return null
return state(input.directory).providers.firstOrNull { it.id == id }?.key?.takeIf(String::isNotBlank)
}

private suspend fun <T> load(resource: String, errors: MutableList<LoadErrorDto>, block: suspend () -> T): T? {
val start = System.currentTimeMillis()
LOG.debug { "provider settings $resource: start" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import ai.kilocode.backend.testing.FakeCliServer
import ai.kilocode.backend.testing.MockCliServer
import ai.kilocode.backend.testing.TestLog
import ai.kilocode.rpc.dto.CustomModelDto
import ai.kilocode.rpc.dto.CustomModelFetchDto
import ai.kilocode.rpc.dto.CustomProviderSaveDto
import ai.kilocode.rpc.dto.ProviderConnectDto
import ai.kilocode.rpc.dto.ProviderDisconnectDto
import ai.kilocode.rpc.dto.ProviderEnableDto
import kotlinx.coroutines.async
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
Expand Down Expand Up @@ -265,6 +268,285 @@ class KiloBackendProviderSettingsManagerTest {
assertEquals(1, mock.requestCount("/global/dispose"))
}

@Test
fun `saving custom provider with blank env var clears existing env from config`() = runBlocking {
// The config schema only allows nulling a whole provider entry, not a single field inside
// one, so clearing "env" requires deleting and recreating the entry. This exercises that
// two-step flow through MockCliServer's own JSON-merge-patch simulation of the real config
// endpoint, rather than asserting on a single "env":null patch body the real CLI would 400 on.
mock.config = """{
"provider":{
"my-openai":{"name":"My OpenAI","npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434"},"env":["OLD_VAR"]}
}
}""".trimIndent()
mock.providers = """{
"all":[{"id":"my-openai","name":"My OpenAI","source":"config","models":{"gpt-4o":{"id":"gpt-4o","name":"gpt-4o"}}}],
"default":{},
"connected":[],
"failed":[]
}""".trimIndent()
val manager = manager()

mock.resetCounts()
val result = manager.saveCustom(
CustomProviderSaveDto(
"/test",
"my-openai",
"My OpenAI",
"https://api.example.com/v1",
apiKey = "sk-test",
envVar = null,
models = listOf(CustomModelDto("gpt-4o", "gpt-4o")),
),
)

assertNull(result.error)
assertContains(mock.lastConfigPatchBody.orEmpty(), "\"my-openai\"")
assertFalse(mock.lastConfigPatchBody.orEmpty().contains("\"env\""))
assertContains(mock.lastAuthPutBody.orEmpty(), "\"key\":\"sk-test\"")
val state = manager.state("/test")
assertEquals(emptyList<String>(), state.config["my-openai"]?.env.orEmpty())
}

@Test
fun `clearing an env var keeps hand-authored headers on the provider entry`() = runBlocking {
// Deleting the entry to clear "env" also drops every other key on it. The dialog has no
// headers field, so headers only ever come from a hand-edited kilo.json and must survive
// the recreate patch instead of being silently wiped by an unrelated env var change.
mock.config = """{
"provider":{
"my-openai":{"name":"My OpenAI","npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434"},"env":["OLD_VAR"],"headers":{"X-Custom":"abc-123"}}
}
}""".trimIndent()
mock.providers = """{
"all":[{"id":"my-openai","name":"My OpenAI","source":"config","models":{"gpt-4o":{"id":"gpt-4o","name":"gpt-4o"}}}],
"default":{},
"connected":[],
"failed":[]
}""".trimIndent()
val manager = manager()

mock.resetCounts()
val result = manager.saveCustom(
CustomProviderSaveDto(
"/test",
"my-openai",
"My OpenAI",
"https://api.example.com/v1",
apiKey = "sk-test",
envVar = null,
models = listOf(CustomModelDto("gpt-4o", "gpt-4o")),
),
)

assertNull(result.error)
val state = manager.state("/test")
assertEquals(emptyList<String>(), state.config["my-openai"]?.env.orEmpty())
assertEquals(mapOf("X-Custom" to "abc-123"), state.config["my-openai"]?.headers)
}

@Test
fun `saving custom provider without an existing env var does not delete the entry first`() = runBlocking {
// Deleting first is only needed to clear a previously-set env var. Doing it unconditionally
// would risk wiping fields the save patch doesn't set (e.g. a hand-authored
// whitelist/blacklist) on every ordinary save, and would leave the provider entry missing
// if the recreate patch failed, so this must stay a no-op when there is nothing to clear.
mock.config = """{
"provider":{
"my-openai":{"name":"My OpenAI","npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434"}}
}
}""".trimIndent()
mock.providers = """{
"all":[{"id":"my-openai","name":"My OpenAI","source":"config","models":{"gpt-4o":{"id":"gpt-4o","name":"gpt-4o"}}}],
"default":{},
"connected":[],
"failed":[]
}""".trimIndent()
val manager = manager()

mock.resetCounts()
val result = manager.saveCustom(
CustomProviderSaveDto(
"/test",
"my-openai",
"My OpenAI",
"https://api.example.com/v1",
apiKey = "sk-test",
envVar = null,
models = listOf(CustomModelDto("gpt-4o", "gpt-4o")),
),
)

assertNull(result.error)
assertContains(mock.lastAuthPutBody.orEmpty(), "\"key\":\"sk-test\"")
// Exactly one GET (the pre-check) + one PATCH (the recreate) + one GET (the trailing
// reload) hit /global/config; a fourth request would mean a delete patch also fired.
assertEquals(3, mock.requestCount("/global/config"))
}

@Test
fun `disconnecting env backed openai compatible custom provider deletes config and auth`() = runBlocking {
mock.config = """{
"provider":{
"local-openai":{"name":"Local OpenAI","npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434"},"env":["API_KEY"]}
}
}""".trimIndent()
mock.providers = """{
"all":[{"id":"local-openai","name":"Local OpenAI","source":"env","key":"sk-env","models":{}}],
"default":{},
"connected":["local-openai"],
"failed":[]
}""".trimIndent()
val manager = manager()

mock.resetCounts()
val result = manager.disconnect(ProviderDisconnectDto("/test", "local-openai"))

assertNull(result.error)
assertContains(mock.lastConfigPatchBody.orEmpty(), "\"local-openai\":null")
assertEquals("/auth/local-openai", mock.lastAuthDeletePath)
}

@Test
fun `disconnecting env only catalog provider still returns configured by environment error`() = runBlocking {
mock.providers = """{
"all":[{"id":"anthropic","name":"Anthropic","source":"env","key":"sk-env","models":{}}],
"default":{},
"connected":["anthropic"],
"failed":[]
}""".trimIndent()
val manager = manager()

mock.resetCounts()
val result = manager.disconnect(ProviderDisconnectDto("/test", "anthropic"))

assertEquals("Provider is configured by environment variables.", result.error)
assertNull(mock.lastConfigPatchBody)
}

@Test
fun `fetch uses env var value for authorization when no key is typed`() = runBlocking {
val server = MockWebServer()
server.enqueue(MockResponse().setBody("""{"data":[{"id":"gpt-4o"}]}"""))
server.start()
val manager = manager()

try {
val result = manager.fetch(
CustomModelFetchDto(baseUrl = server.url("/v1").toString(), directory = "/test", env = "API_KEY"),
env = mapOf("API_KEY" to "sk-env"),
)

assertEquals(listOf("gpt-4o"), result.models)
assertNull(result.error)
assertFalse(result.envMissing)
assertEquals("Bearer sk-env", server.takeRequest().getHeader("Authorization"))
} finally {
server.shutdown()
}
}

@Test
fun `fetch falls back to stored provider key when key and env are absent`() = runBlocking {
mock.providers = """{
"all":[{"id":"my-openai","name":"My OpenAI","source":"api","key":"sk-stored","models":{}}],
"default":{},
"connected":["my-openai"],
"failed":[]
}""".trimIndent()
val server = MockWebServer()
server.enqueue(MockResponse().setBody("""{"data":[{"id":"gpt-4o"}]}"""))
server.start()
val manager = manager()

try {
val result = manager.fetch(
CustomModelFetchDto(baseUrl = server.url("/v1").toString(), directory = "/test", providerId = "my-openai"),
env = emptyMap(),
)

assertEquals(listOf("gpt-4o"), result.models)
assertEquals("Bearer sk-stored", server.takeRequest().getHeader("Authorization"))
} finally {
server.shutdown()
}
}

@Test
fun `fetch marks env missing and sends request without authorization when env var is unset`() = runBlocking {
val server = MockWebServer()
server.enqueue(MockResponse().setBody("""{"data":[{"id":"local-model"}]}"""))
server.start()
val manager = manager()

try {
val result = manager.fetch(
CustomModelFetchDto(baseUrl = server.url("/v1").toString(), directory = "/test", env = "MISSING_KEY"),
env = emptyMap(),
)

assertEquals(listOf("local-model"), result.models)
assertTrue(result.envMissing)
assertNull(server.takeRequest().getHeader("Authorization"))
} finally {
server.shutdown()
}
}

@Test
fun `fetch forwards custom headers to the models request`() = runBlocking {
val server = MockWebServer()
server.enqueue(MockResponse().setBody("""{"data":[]}"""))
server.start()
val manager = manager()

try {
manager.fetch(
CustomModelFetchDto(
baseUrl = server.url("/v1").toString(),
directory = "/test",
headers = mapOf("X-Custom" to "abc-123"),
),
env = emptyMap(),
)

assertEquals("abc-123", server.takeRequest().getHeader("X-Custom"))
} finally {
server.shutdown()
}
}

@Test
fun `fetch prefers typed api key over env var and stored key`() = runBlocking {
mock.providers = """{
"all":[{"id":"my-openai","name":"My OpenAI","source":"api","key":"sk-stored","models":{}}],
"default":{},
"connected":["my-openai"],
"failed":[]
}""".trimIndent()
val server = MockWebServer()
server.enqueue(MockResponse().setBody("""{"data":[]}"""))
server.start()
val manager = manager()

try {
manager.fetch(
CustomModelFetchDto(
baseUrl = server.url("/v1").toString(),
directory = "/test",
providerId = "my-openai",
apiKey = "sk-typed",
env = "API_KEY",
),
env = mapOf("API_KEY" to "sk-env"),
)

assertEquals("Bearer sk-typed", server.takeRequest().getHeader("Authorization"))
} finally {
server.shutdown()
}
}

@Test
fun `disconnecting kilo gateway returns error without logout`() = runBlocking {
mock.providers = """{
Expand Down
Loading
Loading