opencode-plugin-litellm 1.8.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'
2
2
  import { readFileSync, mkdirSync, writeFileSync, renameSync, rmSync } from 'node:fs'
3
3
  import { homedir, tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
+ import type { ModelNaming } from './format-model-name'
5
6
 
6
7
  /**
7
8
  * Facts about a discovered model's upstream that OpenCode 2 turns into
@@ -98,19 +99,23 @@ function canonicalize(value: unknown): string {
98
99
  /**
99
100
  * Cache identity for a provider's model view. `providerId@baseURL`
100
101
  * alone isn't enough: `includeModels`/`excludeModels`,
101
- * `modelCapabilities` and `formatModelNames` are baked into cached
102
- * entries by discovery, so a config change must not reuse the old cache
103
- * — it would keep serving the previous adjusted view until a second
104
- * restart. A fingerprint is appended whenever adjustments exist
105
- * (pattern order ignored); default configs keep the plain key so
106
- * existing caches stay warm across plugin upgrades.
102
+ * `modelCapabilities` and the naming choices (`formatModelNames`,
103
+ * `modelNameTemplate`) are baked into cached entries by discovery, so a
104
+ * config change must not reuse the old cache — it would keep serving the
105
+ * previous adjusted view until a second restart. A fingerprint is appended
106
+ * whenever adjustments exist (pattern order ignored); default configs keep
107
+ * the plain key so existing caches stay warm across plugin upgrades.
108
+ *
109
+ * `providerName` only matters when a template is set: `{provider_name}`
110
+ * resolves to it, so renaming a provider must start a fresh discovery too.
111
+ * The provider id is already part of the base key.
107
112
  */
108
113
  export function buildCacheKey(
109
114
  providerId: string,
110
115
  baseURL: string,
111
116
  filters: { includeModels?: string[]; excludeModels?: string[] },
112
117
  capabilities: Record<string, Record<string, boolean>>,
113
- naming: { formatModelNames?: boolean } = {},
118
+ naming: ModelNaming = {},
114
119
  credential?: string,
115
120
  ): string {
116
121
  let base = `${providerId}@${baseURL}`
@@ -122,21 +127,31 @@ export function buildCacheKey(
122
127
  base += `@${createHash('sha256').update(credential).digest('hex').slice(0, 12)}`
123
128
  }
124
129
  const rawNames = naming.formatModelNames === false
130
+ const template = naming.modelNameTemplate
125
131
  const hasAdjustments =
126
132
  (filters.includeModels?.length ?? 0) > 0 ||
127
133
  (filters.excludeModels?.length ?? 0) > 0 ||
128
134
  Object.keys(capabilities).length > 0 ||
129
- rawNames
135
+ rawNames ||
136
+ template !== undefined
130
137
  if (!hasAdjustments) return base
138
+ // Omitted keys stay out of the hash entirely: `undefined` would serialize
139
+ // as the literal string "undefined" and change every existing cache key.
140
+ const namingFingerprint: Record<string, unknown> = {}
141
+ // Omitted (not `true`) when formatting is on, so keys for configs that
142
+ // never touch this option are unchanged.
143
+ if (rawNames) namingFingerprint.formatModelNames = false
144
+ if (template !== undefined) {
145
+ namingFingerprint.modelNameTemplate = template
146
+ namingFingerprint.providerName = naming.providerName
147
+ }
131
148
  const fingerprint = createHash('sha256')
132
149
  .update(
133
150
  canonicalize({
134
151
  includeModels: filters.includeModels ? [...filters.includeModels].sort() : undefined,
135
152
  excludeModels: filters.excludeModels ? [...filters.excludeModels].sort() : undefined,
136
153
  capabilities,
137
- // Omitted (not `true`) when formatting is on, so keys for
138
- // configs that never touch this option are unchanged.
139
- formatModelNames: rawNames ? false : undefined,
154
+ ...namingFingerprint,
140
155
  }),
141
156
  )
142
157
  .digest('hex')
@@ -1,11 +1,12 @@
1
1
  import { readFile } from 'node:fs/promises'
2
2
  import { homedir } from 'node:os'
3
3
  import { join } from 'node:path'
4
+ import type { SsoToken } from './sso'
4
5
 
5
6
  /**
6
7
  * Shape of an `api`-type entry in OpenCode's own credential store. OpenCode
7
- * also stores `oauth` and `wellknown` entries there, but LiteLLM proxies
8
- * only ever use a plain API key, so that's the only variant we care about.
8
+ * also stores `oauth` (a LiteLLM sign-in, see `getOpenCodeStoredSso`) and
9
+ * `wellknown` entries there.
9
10
  */
10
11
  interface OpenCodeApiAuthEntry {
11
12
  type: 'api'
@@ -33,22 +34,22 @@ function resolveAuthPath(): string {
33
34
  // (model discovery itself is cached per baseURL for the same reason).
34
35
  let cachedAuthFile: Promise<OpenCodeAuthFile | null> | null = null
35
36
 
36
- async function loadOpenCodeAuthFile(): Promise<OpenCodeAuthFile | null> {
37
- if (!cachedAuthFile) {
38
- cachedAuthFile = (async () => {
39
- try {
40
- const raw = await readFile(resolveAuthPath(), 'utf-8')
41
- const parsed: unknown = JSON.parse(raw)
42
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
43
- return parsed as OpenCodeAuthFile
44
- }
45
- } catch {
46
- // File doesn't exist, isn't readable, or isn't valid JSON — treat
47
- // as "no stored credentials" rather than failing plugin startup.
48
- }
49
- return null
50
- })()
37
+ async function readOpenCodeAuthFile(): Promise<OpenCodeAuthFile | null> {
38
+ try {
39
+ const raw = await readFile(resolveAuthPath(), 'utf-8')
40
+ const parsed: unknown = JSON.parse(raw)
41
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
42
+ return parsed as OpenCodeAuthFile
43
+ }
44
+ } catch {
45
+ // File doesn't exist, isn't readable, or isn't valid JSON — treat
46
+ // as "no stored credentials" rather than failing plugin startup.
51
47
  }
48
+ return null
49
+ }
50
+
51
+ async function loadOpenCodeAuthFile(): Promise<OpenCodeAuthFile | null> {
52
+ cachedAuthFile ??= readOpenCodeAuthFile()
52
53
  return cachedAuthFile
53
54
  }
54
55
 
@@ -77,7 +78,57 @@ export async function getOpenCodeStoredApiKey(providerId: string): Promise<strin
77
78
  return undefined
78
79
  }
79
80
 
80
- /** Test-only: force the next read to hit disk again. */
81
- export function __resetOpenCodeAuthCacheForTests(): void {
81
+ /**
82
+ * Force the next read to hit disk again. OpenCode 1 rebuilds its plugin
83
+ * instance after a login, and the new instance must see the new credential.
84
+ */
85
+ export function resetOpenCodeAuthCache(): void {
82
86
  cachedAuthFile = null
83
87
  }
88
+
89
+ /**
90
+ * An OpenCode 1 OAuth entry for a LiteLLM sign-in. OpenCode 1 keeps only these
91
+ * fields and drops the rest the next time it rewrites the file, so the
92
+ * sign-in's metadata travels as JSON in `accountId`.
93
+ */
94
+ export function toOpenCodeOAuthEntry(token: SsoToken): {
95
+ type: 'oauth'
96
+ access: string
97
+ refresh: string
98
+ expires: number
99
+ accountId: string
100
+ } {
101
+ const { access, refresh, expires, metadata } = token
102
+ return { type: 'oauth', access, refresh, expires, accountId: JSON.stringify(metadata) }
103
+ }
104
+
105
+ /**
106
+ * The LiteLLM sign-in OpenCode 1 stored for `providerId`, read from disk on
107
+ * every call: the plugin refreshes it in place, and so may another OpenCode
108
+ * process sharing the file.
109
+ */
110
+ export async function getOpenCodeStoredSso(providerId: string): Promise<SsoToken | undefined> {
111
+ const entry = (await readOpenCodeAuthFile())?.[providerId]
112
+ if (
113
+ entry?.type !== 'oauth' ||
114
+ typeof entry.access !== 'string' ||
115
+ typeof entry.refresh !== 'string' ||
116
+ typeof entry.expires !== 'number' ||
117
+ typeof entry.accountId !== 'string'
118
+ ) {
119
+ return undefined
120
+ }
121
+ try {
122
+ const metadata: unknown = JSON.parse(entry.accountId)
123
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return undefined
124
+ return {
125
+ access: entry.access,
126
+ refresh: entry.refresh,
127
+ expires: entry.expires,
128
+ metadata: metadata as Record<string, unknown>,
129
+ }
130
+ } catch {
131
+ // Not one of this plugin's sign-ins.
132
+ return undefined
133
+ }
134
+ }