opencode-aifs-provider 0.1.0 → 0.2.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.
Files changed (3) hide show
  1. package/README.md +23 -8
  2. package/package.json +11 -10
  3. package/src/index.ts +118 -45
package/README.md CHANGED
@@ -37,30 +37,45 @@ Add to `~/.config/opencode/opencode.json(c)`:
37
37
 
38
38
  No `models` block under `providers.aifs` — the plugin fills it at runtime.
39
39
 
40
+ If you maintain multiple AIFS provider entries (e.g. one per project API key), list them all under `providerIDs` and load the plugin once:
41
+
42
+ ```jsonc
43
+ {
44
+ "$schema": "https://opencode.ai/config.json",
45
+ "plugins": [{ "package": "opencode-aifs-provider", "options": { "providerIDs": ["aifs", "aifs-project-x"] } }],
46
+ "providers": {
47
+ "aifs": { "name": "AIFS", "package": "aisdk:@ai-sdk/openai-compatible", "settings": { "baseURL": "{env:AIFS_BASE_URL}", "apiKey": "{env:AIFS_API_KEY}" } },
48
+ "aifs-project-x": { "name": "AIFS (project X)", "package": "aisdk:@ai-sdk/openai-compatible", "settings": { "baseURL": "{env:AIFS_BASE_URL}", "apiKey": "{env:AIFS_API_KEY_PROJECT_X}" } }
49
+ }
50
+ }
51
+ ```
52
+
53
+ The plugin iterates `providerIDs`, reads `baseURL` and `apiKey` from each provider entry's `settings` (the host resolves `{env:...}` placeholders before exposing them), fetches `/models` per entry, and registers the discovered models under the matching provider ID.
54
+
40
55
  ## Environment
41
56
 
42
57
  | Variable | Required | Notes |
43
58
  |---|---|---|
44
- | `AIFS_BASE_URL` | yes | Must include the API version, e.g. `https://llm-server.llmhub.t-systems.net/v2` |
45
- | `AIFS_API_KEY` | yes | AIFS API key with model-list scope |
59
+ | `AIFS_BASE_URL` | yes | Must include the API version, e.g. `https://llm-server.llmhub.t-systems.net/v2`. Referenced by the provider entry's `settings.baseURL` via `{env:...}`. |
60
+ | `AIFS_API_KEY` | yes | AIFS API key with model-list scope. Referenced by the provider entry's `settings.apiKey` via `{env:...}`. |
61
+
62
+ Credentials are read from the provider entry, not the plugin options — so the env vars are only required because the provider entry references them.
46
63
 
47
64
  ## Plugin options
48
65
 
49
- Pass options via the object form in the `plugins` array when you need to override defaults:
66
+ Pass options via the object form in the `plugins` array:
50
67
 
51
68
  ```jsonc
52
- { "plugins": [{ "package": "opencode-aifs-provider", "options": { "providerID": "aifs" } }] }
69
+ { "plugins": [{ "package": "opencode-aifs-provider", "options": { "providerIDs": ["aifs"] } }] }
53
70
  ```
54
71
 
55
72
  | Option | Default | Purpose |
56
73
  |---|---|---|
57
- | `providerID` | `"aifs"` | Register models under this provider ID. Must match the key under `providers` in your config. |
58
- | `baseURL` | `process.env.AIFS_BASE_URL` | Override the AIFS base URL |
59
- | `apiKey` | `process.env.AIFS_API_KEY` | Override the AIFS API key |
74
+ | `providerIDs` | `["aifs"]` | Register models under these provider IDs. Each must match a key under `providers` in your config. |
60
75
 
61
76
  ## Behavior
62
77
 
63
- - Fetches `${baseURL}/models` with Bearer auth at plugin load.
78
+ - Fetches `${baseURL}/models` with Bearer auth at plugin load, once per provider ID in `providerIDs`.
64
79
  - OpenCode supports chat models that emit text output (`model_type === "LLM"` and `output_modalities` includes `"text"`). Models not matching this are ignored.
65
80
  - Maps AIFS metadata to OpenCode `Model.Info`: `id`, `name` (`display_name`), `limit.context`/`output` (`max_sequence_length`/`max_output_length`), `capabilities.input`/`output` (modalities, lowercased), `status` (`Stable`→`active`, `Experimental`→`beta`).
66
81
  - Calls `ctx.provider.transform(editor => editor.models.set(providerID, models))`.
package/package.json CHANGED
@@ -1,26 +1,27 @@
1
1
  {
2
2
  "name": "opencode-aifs-provider",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "OpenCode V2 plugin that auto-discovers AIFS LLM Serving models at runtime from the /models endpoint.",
5
5
  "license": "MIT",
6
6
  "author": "Sven Weber",
7
- "keywords": ["opencode", "aifs", "t-systems", "openai-compatible", "llm"],
7
+ "keywords": [
8
+ "opencode",
9
+ "aifs",
10
+ "t-systems",
11
+ "openai-compatible",
12
+ "llm"
13
+ ],
8
14
  "type": "module",
9
15
  "exports": {
10
16
  ".": "./src/index.ts"
11
17
  },
12
- "files": ["src"],
18
+ "files": [
19
+ "src"
20
+ ],
13
21
  "engines": {
14
22
  "opencode": "^2.0.0"
15
23
  },
16
24
  "dependencies": {
17
25
  "@opencode/plugin": "^2.2.0"
18
- },
19
- "devDependencies": {
20
- "typescript": "^5.6.0",
21
- "@types/node": "^22.0.0"
22
- },
23
- "scripts": {
24
- "typecheck": "tsc --noEmit"
25
26
  }
26
27
  }
package/src/index.ts CHANGED
@@ -2,7 +2,8 @@ import { Plugin, Model, Provider } from "@opencode/plugin"
2
2
 
3
3
  /**
4
4
  * AIFS /v2/models response shape (OpenAI-compatible with meta_data nesting).
5
- * The helper fetches ${AIFS_BASE_URL}/models with Bearer auth.
5
+ * The helper fetches ${baseURL}/models with Bearer auth, where baseURL and
6
+ * apiKey come from the provider entry's settings (resolved by the host).
6
7
  */
7
8
  interface AifsModelMeta {
8
9
  display_name: string
@@ -30,17 +31,20 @@ interface AifsResponse {
30
31
  data: AifsModel[]
31
32
  }
32
33
 
33
- /** Plugin options. Set `providerID` to register models under a different provider
34
- * (used for the `aifs2` test sandbox without touching the live `aifs` block). */
34
+ /** Plugin options.
35
+ *
36
+ * `providerIDs` registers models under one or more provider IDs. Use an array
37
+ * when you maintain multiple AIFS provider entries (e.g. one per project API
38
+ * key) — the plugin loads once and iterates, instead of being loaded N times.
39
+ *
40
+ * Credentials (`baseURL`, `apiKey`) are read from each provider entry's
41
+ * `settings` in opencode.json(c); they are not accepted as plugin options.
42
+ * The host resolves `{env:VAR}` placeholders before exposing settings, so
43
+ * values are plain strings by the time the plugin reads them. */
35
44
  interface AifsPluginOptions {
36
- providerID?: string
37
- baseURL?: string
38
- apiKey?: string
45
+ providerIDs?: string[]
39
46
  }
40
47
 
41
- /** OpenAI-compatible adapter package used by the provider block in opencode.json(c). */
42
- const ADAPTER = "aisdk:@ai-sdk/openai-compatible"
43
-
44
48
  /**
45
49
  * Keep only chat-relevant models: LLMs that emit text output.
46
50
  * Embeddings, OCR, decision, and image-generation models are skipped —
@@ -79,49 +83,118 @@ function toModelInfo(providerID: Provider.ID, m: AifsModel): Model.Info {
79
83
  }
80
84
  }
81
85
 
86
+ /**
87
+ * Config-defined providers are not available during plugin `setup` — the host
88
+ * activates them after all plugins load. Poll the transform editor until the
89
+ * provider entry appears and exposes resolved `baseURL`/`apiKey` in its
90
+ * settings, or until `timeoutMs` elapses. The host resolves `{env:...}`
91
+ * placeholders before exposing settings, so values are plain strings.
92
+ *
93
+ * Returns the resolved credentials, or undefined on timeout.
94
+ */
95
+ async function waitForProviderSettings(
96
+ ctx: Plugin.Context,
97
+ providerID: Provider.ID,
98
+ timeoutMs = 10000,
99
+ ): Promise<{ baseURL: string; apiKey: string } | undefined> {
100
+ const deadline = Date.now() + timeoutMs
101
+ while (Date.now() < deadline) {
102
+ let settings: Record<string, unknown> = {}
103
+ await ctx.provider.transform((editor) => {
104
+ const record = editor.get(providerID)
105
+ settings = (record?.provider?.settings ?? {}) as Record<string, unknown>
106
+ })
107
+
108
+ const baseURL = typeof settings.baseURL === "string" ? settings.baseURL : undefined
109
+ const apiKey = typeof settings.apiKey === "string" ? settings.apiKey : undefined
110
+ if (baseURL && apiKey) return { baseURL, apiKey }
111
+
112
+ await new Promise((r) => setTimeout(r, 100))
113
+ }
114
+ return undefined
115
+ }
116
+
117
+ /** Fetch /models for one provider, map to Model.Info, register via transform.
118
+ * Returns the number of models registered, or undefined on failure (so the
119
+ * caller can skip the entry in its summary). Errors are logged and isolated:
120
+ * one provider's failure does not abort the others. */
121
+ async function registerForProvider(
122
+ ctx: Plugin.Context,
123
+ providerID: Provider.ID,
124
+ ): Promise<number | undefined> {
125
+ const creds = await waitForProviderSettings(ctx, providerID)
126
+ if (!creds) {
127
+ console.error(
128
+ `[opencode-aifs-provider] Provider "${providerID}" not found or missing baseURL/apiKey in its settings within 10s. ` +
129
+ `Set them in the providers entry (e.g. "baseURL": "{env:AIFS_BASE_URL}").`,
130
+ )
131
+ return undefined
132
+ }
133
+
134
+ const url = `${creds.baseURL.replace(/\/+$/, "")}/models`
135
+
136
+ let res: Response
137
+ try {
138
+ res = await fetch(url, { headers: { Authorization: `Bearer ${creds.apiKey}` } })
139
+ } catch (err) {
140
+ console.error(`[opencode-aifs-provider] Failed to reach ${url} for provider "${providerID}":`, err)
141
+ return undefined
142
+ }
143
+ if (!res.ok) {
144
+ console.error(`[opencode-aifs-provider] ${url} (provider "${providerID}") returned ${res.status} ${res.statusText}`)
145
+ return undefined
146
+ }
147
+
148
+ const json = (await res.json()) as AifsResponse
149
+ if (!Array.isArray(json.data)) {
150
+ console.error(`[opencode-aifs-provider] Response from ${url} (provider "${providerID}") missing 'data' array`)
151
+ return undefined
152
+ }
153
+
154
+ const models: Model.Info[] = json.data.filter(isChatModel).map((m) => toModelInfo(providerID, m))
155
+
156
+ await ctx.provider.transform((editor) => {
157
+ editor.models.set(providerID, models)
158
+ })
159
+
160
+ return models.length
161
+ }
162
+
82
163
  export default Plugin.define({
164
+ // Dev identity: distinct from the published plugin's id ("aifs") so the two
165
+ // instances can coexist in the merged config without a registry collision.
166
+ // prepare-pub.mjs rewrites this back to "aifs" in dist/src/index.ts.
83
167
  id: "aifs",
84
- async setup(ctx) {
168
+ setup(ctx) {
85
169
  const opts = (ctx.options ?? {}) as AifsPluginOptions
86
- const providerID = Provider.ID.make(opts.providerID ?? "aifs")
87
- const baseURL = opts.baseURL ?? process.env.AIFS_BASE_URL
88
- const apiKey = opts.apiKey ?? process.env.AIFS_API_KEY
89
-
90
- if (!baseURL || !apiKey) {
91
- console.error(
92
- "[opencode-aifs-provider] AIFS_BASE_URL and AIFS_API_KEY must be set (env or plugin options).",
93
- )
94
- return
95
- }
96
-
97
- const url = `${baseURL.replace(/\/+$/, "")}/models`
98
-
99
- let res: Response
100
- try {
101
- res = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } })
102
- } catch (err) {
103
- console.error(`[opencode-aifs-provider] Failed to reach ${url}:`, err)
104
- return
105
- }
106
- if (!res.ok) {
107
- console.error(`[opencode-aifs-provider] ${url} returned ${res.status} ${res.statusText}`)
108
- return
109
- }
170
+ const providerIDs = (opts.providerIDs ?? ["aifs"]).map((id) => Provider.ID.make(id))
110
171
 
111
- const json = (await res.json()) as AifsResponse
112
- if (!Array.isArray(json.data)) {
113
- console.error("[opencode-aifs-provider] Response missing 'data' array")
172
+ if (providerIDs.length === 0) {
173
+ console.error("[opencode-aifs-provider] providerIDs is empty; nothing to do.")
114
174
  return
115
175
  }
116
176
 
117
- const models: Model.Info[] = json.data.filter(isChatModel).map((m) => toModelInfo(providerID, m))
177
+ // Config-defined providers are NOT available during plugin setup — the host
178
+ // activates them after all plugins load. Fire-and-forget the registration;
179
+ // waitForProviderSettings polls the editor until the provider entry appears
180
+ // (up to 10s), so setup returns immediately and the host can finish booting.
181
+ setTimeout(() => { void registerAllProviders(ctx, providerIDs) }, 0)
118
182
 
119
- console.log(
120
- `[opencode-aifs-provider] Discovered ${models.length} chat models for provider "${opts.providerID ?? "aifs"}"`,
121
- )
122
-
123
- await ctx.provider.transform((editor) => {
124
- editor.models.set(providerID, models)
125
- })
183
+ // No cleanup needed; the deferred registration is one-shot.
126
184
  },
127
185
  })
186
+
187
+ async function registerAllProviders(ctx: Plugin.Context, providerIDs: Provider.ID[]): Promise<void> {
188
+ const summary: { providerID: Provider.ID; count: number }[] = []
189
+
190
+ for (const providerID of providerIDs) {
191
+ const result = await registerForProvider(ctx, providerID)
192
+ if (result !== undefined) summary.push({ providerID, count: result })
193
+ }
194
+
195
+ const total = summary.reduce((acc, s) => acc + s.count, 0)
196
+ const perProvider = summary.map((s) => `${s.providerID}: ${s.count}`).join(", ")
197
+ console.error(
198
+ `[opencode-aifs-provider] Discovered ${total} chat models across ${summary.length} provider(s) (${perProvider})`,
199
+ )
200
+ }