opencode-aifs-provider 0.0.0-stage → 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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -2
  3. package/package.json +25 -4
  4. package/src/index.ts +200 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sven Weber
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # opencode-aifs-provider
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenCode V2 plugin that auto-discovers **AIFS LLM Serving** models at runtime from the provider's `/models` endpoint, so users no longer hand-maintain a `models` block in `opencode.json(c)`.
4
+
5
+ > **Compatibility**: Tested against AIFS LLM Serving (OpenAI-compatible `/models` endpoint). Other AIFS pillars (SmartChat, RAG, Fine Tuning) are not covered by this plugin.
6
+
7
+ ## Why
8
+
9
+ AIFS (AI Foundation Services, T-Systems) exposes an OpenAI-compatible LLM endpoint but is not indexed on models.dev. OpenCode V2 cannot auto-discover models from a generic `openai-compatible` provider's `/models` endpoint — it relies on explicit `models` entries in config. This plugin closes that gap by calling the AIFS API at startup and registering the discovered models through OpenCode's provider transform API.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install -g opencode-aifs-provider
15
+ ```
16
+
17
+ ## Configure
18
+
19
+ Add to `~/.config/opencode/opencode.json(c)`:
20
+
21
+ ```jsonc
22
+ {
23
+ "$schema": "https://opencode.ai/config.json",
24
+ "plugins": ["opencode-aifs-provider"],
25
+ "providers": {
26
+ "aifs": {
27
+ "name": "AIFS",
28
+ "package": "aisdk:@ai-sdk/openai-compatible",
29
+ "settings": {
30
+ "baseURL": "{env:AIFS_BASE_URL}",
31
+ "apiKey": "{env:AIFS_API_KEY}"
32
+ }
33
+ }
34
+ }
35
+ }
36
+ ```
37
+
38
+ No `models` block under `providers.aifs` — the plugin fills it at runtime.
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
+
55
+ ## Environment
56
+
57
+ | Variable | Required | Notes |
58
+ |---|---|---|
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.
63
+
64
+ ## Plugin options
65
+
66
+ Pass options via the object form in the `plugins` array:
67
+
68
+ ```jsonc
69
+ { "plugins": [{ "package": "opencode-aifs-provider", "options": { "providerIDs": ["aifs"] } }] }
70
+ ```
71
+
72
+ | Option | Default | Purpose |
73
+ |---|---|---|
74
+ | `providerIDs` | `["aifs"]` | Register models under these provider IDs. Each must match a key under `providers` in your config. |
75
+
76
+ ## Behavior
77
+
78
+ - Fetches `${baseURL}/models` with Bearer auth at plugin load, once per provider ID in `providerIDs`.
79
+ - OpenCode supports chat models that emit text output (`model_type === "LLM"` and `output_modalities` includes `"text"`). Models not matching this are ignored.
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`).
81
+ - Calls `ctx.provider.transform(editor => editor.models.set(providerID, models))`.
82
+ - On fetch failure: logs and skips — does not crash OpenCode.
83
+
84
+ ## License
85
+
86
+ MIT
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "opencode-aifs-provider",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "OpenCode V2 plugin that auto-discovers AIFS LLM Serving models at runtime from the /models endpoint.",
5
+ "license": "MIT",
6
+ "author": "Sven Weber",
7
+ "keywords": [
8
+ "opencode",
9
+ "aifs",
10
+ "t-systems",
11
+ "openai-compatible",
12
+ "llm"
13
+ ],
14
+ "type": "module",
15
+ "exports": {
16
+ ".": "./src/index.ts"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "engines": {
22
+ "opencode": "^2.0.0"
23
+ },
24
+ "dependencies": {
25
+ "@opencode/plugin": "^2.2.0"
26
+ }
27
+ }
package/src/index.ts ADDED
@@ -0,0 +1,200 @@
1
+ import { Plugin, Model, Provider } from "@opencode/plugin"
2
+
3
+ /**
4
+ * AIFS /v2/models response shape (OpenAI-compatible with meta_data nesting).
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).
7
+ */
8
+ interface AifsModelMeta {
9
+ display_name: string
10
+ model_type: string
11
+ source_type: string
12
+ max_sequence_length: number
13
+ max_output_length: number
14
+ deployment_region: string
15
+ deployment_country: string
16
+ location: string
17
+ input_modalities: string[]
18
+ output_modalities: string[]
19
+ model_lifecycle_stage: string
20
+ license: string
21
+ is_externally_hosted: boolean
22
+ end_of_life_date: string | null
23
+ }
24
+
25
+ interface AifsModel {
26
+ id: string
27
+ meta_data: AifsModelMeta
28
+ }
29
+
30
+ interface AifsResponse {
31
+ data: AifsModel[]
32
+ }
33
+
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. */
44
+ interface AifsPluginOptions {
45
+ providerIDs?: string[]
46
+ }
47
+
48
+ /**
49
+ * Keep only chat-relevant models: LLMs that emit text output.
50
+ * Embeddings, OCR, decision, and image-generation models are skipped —
51
+ * they are not useful for OpenCode agents.
52
+ */
53
+ function isChatModel(m: AifsModel): boolean {
54
+ return (
55
+ m.meta_data?.model_type === "LLM" &&
56
+ (m.meta_data.output_modalities ?? []).some((o) => o.toLowerCase() === "text")
57
+ )
58
+ }
59
+
60
+ function toModelInfo(providerID: Provider.ID, m: AifsModel): Model.Info {
61
+ const id = Model.ID.make(m.id)
62
+ const base = Model.Info.default(providerID, id)
63
+ const stage = (m.meta_data.model_lifecycle_stage ?? "").toLowerCase()
64
+ const status: Model.Info["status"] = stage === "experimental" ? "beta" : "active"
65
+
66
+ return {
67
+ ...base,
68
+ name: m.meta_data.display_name || m.id,
69
+ type: "chat",
70
+ status,
71
+ // capabilities.tools defaults to true (Capabilities.default); AIFS /v2/models
72
+ // does not report tool-calling support. v2 of this plugin will fetch the
73
+ // `toolCalling` field from the public pricing page and override here.
74
+ capabilities: {
75
+ ...base.capabilities,
76
+ input: (m.meta_data.input_modalities ?? []).map((s) => s.toLowerCase()),
77
+ output: (m.meta_data.output_modalities ?? []).map((s) => s.toLowerCase()),
78
+ },
79
+ limit: {
80
+ context: m.meta_data.max_sequence_length ?? base.limit.context,
81
+ output: m.meta_data.max_output_length ?? base.limit.output,
82
+ },
83
+ }
84
+ }
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
+
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.
167
+ id: "aifs",
168
+ setup(ctx) {
169
+ const opts = (ctx.options ?? {}) as AifsPluginOptions
170
+ const providerIDs = (opts.providerIDs ?? ["aifs"]).map((id) => Provider.ID.make(id))
171
+
172
+ if (providerIDs.length === 0) {
173
+ console.error("[opencode-aifs-provider] providerIDs is empty; nothing to do.")
174
+ return
175
+ }
176
+
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)
182
+
183
+ // No cleanup needed; the deferred registration is one-shot.
184
+ },
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
+ }