Skip to content
Open
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
6 changes: 6 additions & 0 deletions packages/opencode/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,12 @@ export namespace Config {
options: z
.object({
apiKey: z.string().optional(),
apiKeyCommand: z
.array(z.string())
.optional()
.describe(
"Command to execute to get the API key dynamically. The command should output the API key to stdout. Example: ['my-auth-cli', 'get-token']",
),
baseURL: z.string().optional(),
enterpriseUrl: z.string().optional().describe("GitHub Enterprise URL for copilot authentication"),
setCacheKey: z.boolean().optional().describe("Enable promptCacheKey for this provider (default false)"),
Expand Down
30 changes: 30 additions & 0 deletions packages/opencode/src/provider/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,30 @@ export namespace Provider {
"@ai-sdk/github-copilot": createGitHubCopilotOpenAICompatible,
}

/**
* Executes an apiKeyCommand and returns the output as the API key.
* This allows dynamic API key retrieval from credential helpers or token services.
*/
async function resolveApiKeyCommand(command: string[]): Promise<string | undefined> {
if (!command || command.length === 0) return undefined
try {
const proc = Bun.spawn(command, {
stdout: "pipe",
stderr: "pipe",
})
const code = await proc.exited
if (code !== 0) {
log.warn("apiKeyCommand failed", { command, exitCode: code })
return undefined
}
const stdout = await new Response(proc.stdout).text()
return stdout.trim()
} catch (e) {
log.warn("apiKeyCommand execution error", { command, error: e })
return undefined
}
}

type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>) => Promise<any>
type CustomLoader = (provider: Info) => Promise<{
autoload: boolean
Expand Down Expand Up @@ -921,6 +945,12 @@ export namespace Provider {

if (!options["baseURL"]) options["baseURL"] = model.api.url
if (options["apiKey"] === undefined && provider.key) options["apiKey"] = provider.key
// If no apiKey yet, try apiKeyCommand
if (options["apiKey"] === undefined && options["apiKeyCommand"]) {
const key = await resolveApiKeyCommand(options["apiKeyCommand"])
if (key) options["apiKey"] = key
delete options["apiKeyCommand"] // Don't pass command to SDK
}
if (model.headers)
options["headers"] = {
...options["headers"],
Expand Down