opencode-llamacpp-v2 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 renderxor
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,178 @@
1
- # Temporary Holding Version
1
+ # opencode-llamacpp-v2
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
+ Plugin llama.cpp router para OpenCode V2 (prototipo 0.1.0). Paquete npm: `opencode-llamacpp-v2`.
4
+
5
+ **Estado:** prototipo para OpenCode **V2** (API 2.3.2). La lógica del inventario ha pasado pruebas automáticas y la interacción con la API de plugins se ha probado con un *host simulado*. **No se ha probado aún con una instancia real de OpenCode ni con tu llama.cpp**.
6
+
7
+ ## Funcionalidad
8
+
9
+ - Añade la integración **llama.cpp** a `/connect`.
10
+ - Solicita una **URL** y después una **API key**. OpenCode guarda los datos en su sistema de credenciales; el plugin no escribe claves en archivos propios.
11
+ - Recupera los datos de la conexión activa mediante `ctx.integration.connection.active` y `resolve`.
12
+ - Consulta `GET /models` (ruta relativa a `/v1`, compatible con prefijos de proxy).
13
+ - Descubre los modelos sin cargarlos y obtiene `limit.context` de un `--ctx-size` explícito en `status.args`; si falta, lo lee de `status.preset`. `--fit` solo ajusta argumentos no fijados, así que no invalida un contexto explícito.
14
+ - Si no hay contexto explícito ni efectivo, aplica `fallbackContext` (131.072 por defecto) para mantener el modelo disponible.
15
+ - Omite los modelos en descarga, incompletos o con la última carga fallida.
16
+ - No usa `created` de `/models`: en el router ese campo es la hora de la petición, no la fecha de release del modelo.
17
+ - Da prioridad a `memory.effective.n_ctx` o `meta.n_ctx` para una instancia **cargada**, cuando se proporcionan.
18
+ - Traslada `architecture.input_modalities`, `architecture.output_modalities`, nombre y contexto al catálogo V2.
19
+ - Anuncia `capabilities.tools: true` para todos los modelos, porque llama.cpp soporta tool calling mediante `--jinja`; no se realiza una prueba real de ejecución.
20
+ - Publica `limit.output`, configurable (32.000 por defecto), sin superar el contexto ni `--n-predict` positivo si aparece.
21
+ - Actualiza al arrancar, al conectarse/cambiar de cuenta y mediante el comando `/llamacpp-refresh`. El intervalo periódico es optativo.
22
+ - `/llamacpp-refresh` muestra un aviso emergente en la TUI con el resultado: modelos actualizados, modelos omitidos o error.
23
+ - Mantiene el último inventario válido en un fallo temporal del servidor, para la misma conexión, y no muestra el inventario de una conexión anterior tras cambiar de cuenta.
24
+
25
+ No analiza plantillas Jinja ni crea variantes de razonamiento. No verifica ejecución real de tool calling. Si no hay `--ctx-size` explícito ni datos de una instancia cargada, aplica el fallback configurable en lugar de calcularlo. No divide el contexto por `--parallel`. No es un plugin para llama-swap.
26
+
27
+ ## Instalación desde npm
28
+
29
+ El paquete se publica como `opencode-llamacpp-v2`.
30
+
31
+ 1. Instala el plugin:
32
+
33
+ ```powershell
34
+ opencode plugin add opencode-llamacpp-v2@latest
35
+ ```
36
+
37
+ 2. Edita la entrada creada en `opencode.jsonc` para añadir las opciones:
38
+
39
+ ```jsonc
40
+ {
41
+ "plugins": [
42
+ {
43
+ "package": "opencode-llamacpp-v2@latest",
44
+ "options": {
45
+ "maxOutputTokens": 32000,
46
+ "fallbackContext": 131072
47
+ }
48
+ }
49
+ ]
50
+ }
51
+ ```
52
+
53
+ **Quita** el proveedor `providers["llama.cpp"]` de la configuración, porque ahora lo crea el plugin. **Desactiva el descubrimiento de llama.cpp en `opencode-models-discovery`**; si solo lo usabas para llama.cpp, puedes quitar ese plugin. No elimines otros proveedores ajenos al router.
54
+
55
+ 3. Reinicia OpenCode y abre `/connect` → `llama.cpp`.
56
+
57
+ 4. Introduce la dirección **`http://192.168.2.49:8080/v1`** y después la API key en el cuadro nativo. La URL puede introducirse con o sin `/v1`.
58
+
59
+ 5. Comprueba en el selector de modelos que aparecen los presets y que OpenCode muestra el contexto correcto. Ejecuta `/llamacpp-refresh` para forzar una nueva consulta tras editar presets.
60
+
61
+ Tras ejecutar `/llamacpp-refresh`, la TUI muestra un aviso emergente con el número de modelos actualizados y los omitidos. El resultado también queda en el log del servidor. El aviso requiere la parte TUI del plugin, que OpenCode carga automáticamente; en modo headless o servidor sin TUI no se muestra.
62
+
63
+ ## Instalación manual
64
+
65
+ 1. Copia el contenido del repositorio en:
66
+
67
+ `C:\Users\anexu\.config\opencode\extensions\opencode-llamacpp-v2`
68
+
69
+ El directorio debe contener `index.js`, `lib/router.js`, `rpc.js`, `tui.js` y `package.json`.
70
+
71
+ 2. Instala la dependencia V2 en un terminal de PowerShell conectado a Internet:
72
+
73
+ ```powershell
74
+ cd C:\Users\anexu\.config\opencode\extensions\opencode-llamacpp-v2
75
+ npm install --omit=dev
76
+ ```
77
+
78
+ Este prototipo utiliza `@opencode/plugin` **2.3.2**. Si utilizas otra versión de OpenCode V2, debe verificarse su compatibilidad antes de darla por supuesta.
79
+
80
+ 3. Haz copia de seguridad de tu `opencode.jsonc` y ajusta su array `plugins`:
81
+
82
+ ```jsonc
83
+ {
84
+ "plugins": [
85
+ {
86
+ "package": "./extensions/opencode-llamacpp-v2",
87
+ "options": {
88
+ "maxOutputTokens": 32000,
89
+ "fallbackContext": 131072
90
+ }
91
+ }
92
+ ]
93
+ }
94
+ ```
95
+
96
+ **Quita** el proveedor `providers["llama.cpp"]` de la configuración, porque ahora lo crea el plugin. **Desactiva el descubrimiento de llama.cpp en `opencode-models-discovery`**; si solo lo usabas para llama.cpp, puedes quitar ese plugin. No elimines otros proveedores ajenos al router.
97
+
98
+ 4. Reinicia OpenCode y abre `/connect` → `llama.cpp`.
99
+
100
+ 5. Introduce la dirección **`http://192.168.2.49:8080/v1`** y después la API key en el cuadro nativo. La URL puede introducirse con o sin `/v1`.
101
+
102
+ 6. Comprueba en el selector de modelos que aparecen los presets y que OpenCode muestra el contexto correcto. Ejecuta `/llamacpp-refresh` para forzar una nueva consulta tras editar presets.
103
+
104
+ Tras ejecutar `/llamacpp-refresh`, la TUI muestra un aviso emergente con el número de modelos actualizados y los omitidos. El resultado también queda en el log del servidor. El aviso requiere la parte TUI del plugin, que OpenCode carga automáticamente; en modo headless o servidor sin TUI no se muestra.
105
+
106
+ ## Opciones
107
+
108
+ Añade opciones a la entrada del plugin (en el objeto `options`):
109
+
110
+ | Campo | Predeterminado | Significado |
111
+ | --- | --- | --- |
112
+ | `maxOutputTokens` | `32000` | Tope de salida que OpenCode puede solicitar; ajustado también al contexto y a un `--n-predict` positivo. No es una capacidad máxima detectada del GGUF. |
113
+ | `fallbackContext` | `131072` | Contexto que se asigna cuando el modelo no declara `--ctx-size` ni ofrece un contexto efectivo. `0` desactiva el fallback y omite esos modelos. Es una suposición configurable: ajústala si algún modelo tiene menos contexto real. |
114
+ | `refreshIntervalSeconds` | `0` | `0` desactiva refresco periódico; un valor >=30 activa consultas periódicas. |
115
+
116
+ Ejemplo:
117
+
118
+ ```jsonc
119
+ "options": {
120
+ "maxOutputTokens": 65536,
121
+ "fallbackContext": 131072,
122
+ "refreshIntervalSeconds": 0
123
+ }
124
+ ```
125
+
126
+ El plugin anuncia `tools: true` para todos los modelos. OpenCode solo anuncia esa capacidad; la ejecución real de una herramienta depende de la plantilla y del modelo concretos.
127
+
128
+ ## Aviso en la TUI
129
+
130
+ `/llamacpp-refresh` usa un contrato RPC (`rpc.js`) y una parte TUI (`tui.js`). El servidor emite un evento `toast` con el resultado del refresco y la TUI lo convierte en un aviso mediante `ui.toast.show`. Si no hay TUI conectada, el evento no tiene suscriptor y el plugin sigue funcionando; el resultado queda en el log.
131
+
132
+ El aviso no se muestra en arranques, cambios de credencial ni refrescos periódicos: solo al ejecutar el comando manualmente.
133
+
134
+ ## Diagnóstico
135
+
136
+ El servidor debe devolver una respuesta con la estructura `{ "data": [...] }` para `GET /models`. En PowerShell:
137
+
138
+ ```powershell
139
+ $key = Read-Host "API key de llama.cpp"
140
+ $r = Invoke-RestMethod -Uri "http://192.168.2.49:8080/models" -Headers @{ Authorization = "Bearer $key" }
141
+ $r.data | Select-Object id, @{N="Ctx";E={$_.status.args -join ' '}} | Select-Object -First 5
142
+ ```
143
+
144
+ Un modelo sin un `--ctx-size` válido ni un contexto efectivo de una instancia cargada se publica con el `fallbackContext` configurado. Si `fallbackContext` es `0`, se omite intencionadamente. Los modelos en descarga, incompletos o con la última carga fallida se omiten siempre. Se usa `memory.effective.n_ctx` únicamente cuando el modelo esté cargado y se devuelva ese dato.
145
+
146
+ En caso de error de autenticación, fallo de conexión o error en el payload, el plugin registra un aviso `[opencode-llamacpp-v2]` en el log. El prototipo no tiene todavía panel de estado propio ni mecanismos de autorización avanzada.
147
+
148
+ ## Pruebas
149
+
150
+ En la carpeta del plugin:
151
+
152
+ ```powershell
153
+ npm test
154
+ ```
155
+
156
+ Las pruebas cubren la extracción del contexto con `--fit` activo o ausente, el fallback configurable, modelos no disponibles, variantes de los argumentos, límites de salida, modalidades, tools siempre anunciado, el contrato RPC/TUI del aviso y un **host OpenCode simulado**. No suponen una validación extremo a extremo en OpenCode real.
157
+
158
+ ## Fuentes oficiales consultadas
159
+
160
+ - OpenCode V2: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/server.mdx
161
+ - OpenCode TUI: https://opencode.ai/docs/build/plugins/cli/
162
+ - OpenCode RPC: https://opencode.ai/docs/build/plugins/rpc/
163
+ - OpenCode: https://github.com/anomalyco/opencode/blob/dev/packages/plugin/src/promise/integration.ts
164
+ - OpenCode: https://github.com/anomalyco/opencode/blob/dev/packages/plugin/src/promise/provider.ts
165
+ - OpenCode: https://github.com/anomalyco/opencode/blob/dev/packages/schema/src/model.ts
166
+ - llama.cpp: https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md
167
+
168
+ ## Limitaciones y precauciones
169
+
170
+ - En uso sobre red local, HTTP no cifra el tráfico: la API key viaja en la petición. Utiliza una LAN de confianza o HTTPS/proxy cuando el acceso no sea local y controlado.
171
+ - Cualquier cambio de API de OpenCode V2 puede requerir actualizar el plugin.
172
+ - Evita dos plugins que modifiquen el mismo proveedor y catálogo de modelos simultáneamente.
173
+ - El servidor llama.cpp puede rechazar o fallar al cargar un modelo aunque su preset declare `--ctx-size` fijo.
174
+ - El aviso de `/llamacpp-refresh` depende de la parte TUI y de una conexión TUI activa. En modo headless o servidor sin TUI, el resultado solo queda en el log.
175
+
176
+ ## Licencia
177
+
178
+ MIT © 2026 renderxor. Consulta `LICENSE`.
package/index.js ADDED
@@ -0,0 +1,238 @@
1
+ import { Plugin, Model, Provider, Integration } from '@opencode/plugin';
2
+ import { normalizeBaseURL, routerModelsURL, parseRouterCatalog, DEFAULT_CONTEXT } from './lib/router.js';
3
+ import { LlamacppRouter } from './rpc.js';
4
+
5
+ const PROVIDER_ID = 'llama.cpp';
6
+ const DEFAULT_OUTPUT = 32000;
7
+
8
+ function pluginOptions(options) {
9
+ const opts = options ?? {};
10
+ const limit = Number.isSafeInteger(opts.maxOutputTokens) && opts.maxOutputTokens > 0
11
+ ? opts.maxOutputTokens : DEFAULT_OUTPUT;
12
+ const interval = Number.isSafeInteger(opts.refreshIntervalSeconds) && opts.refreshIntervalSeconds >= 30
13
+ ? opts.refreshIntervalSeconds * 1000 : 0;
14
+ const fallbackContext = Number.isSafeInteger(opts.fallbackContext) && opts.fallbackContext >= 0
15
+ ? opts.fallbackContext : DEFAULT_CONTEXT;
16
+ return { outputTokens: limit, fallbackContext, interval };
17
+ }
18
+
19
+ function connectionKey(connection) {
20
+ if (!connection) return null;
21
+ return connection.type === 'credential' ? `credential:${connection.id}` : `env:${connection.name}`;
22
+ }
23
+
24
+ async function fetchCatalog(baseURL, apiKey, options) {
25
+ const signal = AbortSignal.timeout(15000);
26
+ const response = await fetch(routerModelsURL(baseURL), {
27
+ method: 'GET',
28
+ redirect: 'error',
29
+ headers: { Accept: 'application/json', ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}) },
30
+ signal,
31
+ });
32
+ if (!response.ok) {
33
+ const error = new Error(`GET /models: HTTP ${response.status}`);
34
+ error.status = response.status;
35
+ throw error;
36
+ }
37
+ return parseRouterCatalog(await response.json(), options);
38
+ }
39
+
40
+ function makeProvider(snapshot) {
41
+ const id = Provider.ID.make(PROVIDER_ID);
42
+ const models = snapshot.catalog.map(spec => {
43
+ const item = { ...Model.Info.default(id, Model.ID.make(spec.id)) };
44
+ item.name = spec.name;
45
+ item.limit = { context: spec.context, output: spec.output };
46
+ item.capabilities = { ...spec.capabilities };
47
+ item.variants = [];
48
+ if (spec.compatibility) item.compatibility = spec.compatibility;
49
+ return item;
50
+ });
51
+ return {
52
+ info: {
53
+ ...Provider.Info.empty(id),
54
+ integrationID: Integration.ID.make(PROVIDER_ID),
55
+ name: 'llama.cpp',
56
+ activation: 'enabled',
57
+ package: '@opencode/ai/providers/openai-compatible',
58
+ // Only in process memory; /connect owns persistent credentials.
59
+ settings: { baseURL: snapshot.baseURL, apiKey: snapshot.apiKey },
60
+ },
61
+ models,
62
+ sourceConnection: snapshot.connection,
63
+ };
64
+ }
65
+
66
+ export default Plugin.define({
67
+ id: 'opencode-llamacpp-v2',
68
+ async setup(ctx) {
69
+ const options = pluginOptions(ctx.options);
70
+ const state = { active: null, snapshot: null, signature: null };
71
+ let closing = false;
72
+
73
+ const integrationReg = await ctx.integration.transform(editor => {
74
+ editor.update(PROVIDER_ID, item => { item.name = 'llama.cpp'; });
75
+ editor.method.update({
76
+ integrationID: PROVIDER_ID,
77
+ method: {
78
+ type: 'key',
79
+ label: 'Conectar servidor llama.cpp',
80
+ form: [{
81
+ key: 'baseURL',
82
+ type: 'string',
83
+ title: 'URL del servidor (con /v1 o sin él)',
84
+ required: true,
85
+ format: 'uri',
86
+ placeholder: 'http://192.168.2.49:8080/v1',
87
+ }],
88
+ },
89
+ });
90
+ });
91
+
92
+ const providerReg = await ctx.provider.transform(editor => {
93
+ if (!state.snapshot) return;
94
+ // Isolated account-specific source: OpenCode hides it after a connection switch.
95
+ editor.add(makeProvider(state.snapshot));
96
+ });
97
+
98
+ const rpc = await ctx.rpc.register(LlamacppRouter, {});
99
+
100
+ async function notify(payload) {
101
+ try {
102
+ await rpc.events.emit('toast', payload);
103
+ } catch (error) {
104
+ console.warn(`[opencode-llamacpp-v2] No se pudo mostrar el aviso de la TUI: ${error instanceof Error ? error.message : String(error)}`);
105
+ }
106
+ }
107
+
108
+ async function refresh() {
109
+ if (closing) return { status: 'closing' };
110
+ const connection = await ctx.integration.connection.active(PROVIDER_ID);
111
+ const identity = connectionKey(connection);
112
+ if (identity !== state.active) {
113
+ state.active = identity;
114
+ state.snapshot = null;
115
+ state.signature = null;
116
+ await ctx.provider.reload(); // Remove the previous account's catalog immediately.
117
+ }
118
+ if (!connection) return { status: 'no-connection' };
119
+
120
+ const credential = await ctx.integration.connection.resolve(connection);
121
+ if (credential?.type !== 'key') throw new Error('La conexión debe usar una API key');
122
+ const meta = credential.metadata;
123
+ const urlInput = typeof meta?.baseURL === 'string' ? meta.baseURL : undefined;
124
+ if (!urlInput) throw new Error('Esta conexión no tiene URL; reconéctala mediante /connect');
125
+ const baseURL = normalizeBaseURL(urlInput);
126
+ let catalog;
127
+ try {
128
+ catalog = await fetchCatalog(baseURL, credential.key, options);
129
+ } catch (error) {
130
+ if (error?.status === 401 || error?.status === 403) {
131
+ try {
132
+ await ctx.integration.connection.status({
133
+ integrationID: PROVIDER_ID, connection,
134
+ status: { status: 'needs_auth', message: 'API key rechazada por llama.cpp' },
135
+ });
136
+ } catch { /* Connection status is optional for the catalog. */ }
137
+ }
138
+ throw error;
139
+ }
140
+ const { models, skipped } = catalog;
141
+ if (!models.length) throw new Error('No hay modelos de texto con contexto fijo verificable en /models');
142
+
143
+ // Prevent a slow response from overwriting a newly selected connection.
144
+ const stillActive = await ctx.integration.connection.active(PROVIDER_ID);
145
+ if (connectionKey(stillActive) !== identity || closing) return { status: 'stale' };
146
+
147
+ const signature = JSON.stringify({ identity, baseURL, models });
148
+ if (signature !== state.signature) {
149
+ state.snapshot = { connection, baseURL, apiKey: credential.key, catalog: models };
150
+ state.signature = signature;
151
+ await ctx.provider.reload();
152
+ }
153
+ try {
154
+ await ctx.integration.connection.status({
155
+ integrationID: PROVIDER_ID, connection, status: undefined,
156
+ });
157
+ } catch { /* Not fatal for catalog updates. */ }
158
+ console.info(`[opencode-llamacpp-v2] ${models.length} modelos registrados; ${skipped.length} omitidos`);
159
+ for (const message of skipped) console.warn(`[opencode-llamacpp-v2] ${message}`);
160
+ return { status: 'ok', models: models.length, skipped: skipped.length };
161
+ }
162
+
163
+ let queue = Promise.resolve();
164
+ function scheduleRefresh() {
165
+ const task = queue.then(refresh);
166
+ queue = task.catch(error => {
167
+ console.warn(`[opencode-llamacpp-v2] Error de actualización: ${error instanceof Error ? error.message : String(error)}`);
168
+ });
169
+ return task;
170
+ }
171
+
172
+ const commandReg = await ctx.command.transform(editor => {
173
+ editor.add({
174
+ name: 'llamacpp-refresh',
175
+ description: 'Actualizar modelos y contextos del servidor llama.cpp',
176
+ execute: async () => {
177
+ try {
178
+ const result = await scheduleRefresh();
179
+ if (result?.status === 'no-connection') {
180
+ await notify({
181
+ title: 'llama.cpp',
182
+ message: 'No hay una conexión activa; usa /connect → llama.cpp',
183
+ variant: 'warning',
184
+ duration: 5000,
185
+ });
186
+ return;
187
+ }
188
+ if (result?.status !== 'ok') return;
189
+ const omitted = result.skipped ? `; ${result.skipped} omitidos` : '';
190
+ await notify({
191
+ title: 'llama.cpp',
192
+ message: `Catálogo actualizado: ${result.models} modelos${omitted}`,
193
+ variant: result.skipped ? 'warning' : 'success',
194
+ duration: 4000,
195
+ });
196
+ } catch (error) {
197
+ await notify({
198
+ title: 'llama.cpp',
199
+ message: `Error al actualizar: ${error instanceof Error ? error.message : String(error)}`,
200
+ variant: 'error',
201
+ duration: 6000,
202
+ });
203
+ }
204
+ },
205
+ });
206
+ });
207
+
208
+ // Observe credentials created by /connect, and account selection changes.
209
+ const controller = new AbortController();
210
+ void (async () => {
211
+ try {
212
+ for await (const event of ctx.event.subscribe({
213
+ types: ['credential.updated', 'credential.switched'], signal: controller.signal,
214
+ })) {
215
+ if (closing) break;
216
+ const detail = event.properties ?? event.data;
217
+ if (detail?.integrationID && detail.integrationID !== PROVIDER_ID) continue;
218
+ await scheduleRefresh().catch(() => {});
219
+ }
220
+ } catch (error) {
221
+ if (!controller.signal.aborted)
222
+ console.warn(`[opencode-llamacpp-v2] Suscripción a eventos: ${String(error)}`);
223
+ }
224
+ })();
225
+
226
+ const timer = options.interval
227
+ ? setInterval(() => { void scheduleRefresh().catch(() => {}); }, options.interval)
228
+ : undefined;
229
+ await ctx.integration.reload();
230
+ await scheduleRefresh().catch(() => {});
231
+ return async () => {
232
+ closing = true;
233
+ controller.abort();
234
+ if (timer) clearInterval(timer);
235
+ await Promise.allSettled([integrationReg.dispose(), providerReg.dispose(), commandReg.dispose(), rpc.dispose()]);
236
+ };
237
+ },
238
+ });
package/lib/router.js ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Pure helpers for llama.cpp router discovery. No dependencies on OpenCode.
3
+ * The returned context is a configured context, never inferred from the GGUF's training length.
4
+ */
5
+
6
+ export const DEFAULT_CONTEXT = 131072;
7
+
8
+ /** @param {string} input */
9
+ export function normalizeBaseURL(input) {
10
+ const url = new URL(String(input).trim());
11
+ if (!['http:', 'https:'].includes(url.protocol)) throw new Error('La URL debe usar http o https');
12
+ if (url.username || url.password || url.search || url.hash) {
13
+ throw new Error('La URL no debe incluir usuario, contraseña, parámetros ni fragmento');
14
+ }
15
+ const cleanPath = url.pathname.replace(/\/+$/, '');
16
+ url.pathname = cleanPath.endsWith('/v1') ? cleanPath : cleanPath + '/v1';
17
+ return url.toString().replace(/\/+$/, '');
18
+ }
19
+
20
+ /** @param {string} baseURL */
21
+ export function routerModelsURL(baseURL) {
22
+ const url = new URL(baseURL);
23
+ // Strip only the final version suffix; preserve a reverse-proxy path prefix.
24
+ url.pathname = url.pathname.replace(/\/v1\/?$/, '') + '/models';
25
+ return url.toString();
26
+ }
27
+
28
+ /** @param {unknown[]} tokens @param {string[]} keys */
29
+ export function flagValue(tokens, keys) {
30
+ if (!Array.isArray(tokens)) return undefined;
31
+ let value;
32
+ for (let i = 0; i < tokens.length; i++) {
33
+ const s = tokens[i];
34
+ if (typeof s !== 'string') continue;
35
+ for (const key of keys) {
36
+ if (s === key && typeof tokens[i + 1] === 'string') value = tokens[i + 1];
37
+ if (s.startsWith(`${key}=`)) value = s.slice(key.length + 1);
38
+ }
39
+ }
40
+ return value;
41
+ }
42
+
43
+ /** @param {string} text @param {string} property */
44
+ function iniValue(text, property) {
45
+ if (typeof text !== 'string') return undefined;
46
+ const escaped = property.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
47
+ const re = new RegExp(`^\\s*${escaped}\\s*=\\s*(.+?)\\s*$`, 'gmi');
48
+ let match, result;
49
+ while ((match = re.exec(text))) {
50
+ result = match[1].split(/[;#]/)[0].trim();
51
+ }
52
+ return result;
53
+ }
54
+
55
+ /** @param {unknown} val */
56
+ function positiveInt(val) {
57
+ const n = Number(val);
58
+ return Number.isSafeInteger(n) && n > 0 ? n : undefined;
59
+ }
60
+
61
+ /**
62
+ * @param {Record<string,any>} model
63
+ * @returns {{context: number|null, source: string, reason?: string}}
64
+ */
65
+ export function configuredContext(model) {
66
+ const args = model?.status?.args;
67
+ const preset = model?.status?.preset;
68
+ const ctxArg = flagValue(args, ['--ctx-size', '-c', '-ctx']);
69
+ const context = positiveInt(ctxArg ?? iniValue(preset, 'ctx-size'));
70
+
71
+ // Effective contexts are authoritative only for currently loaded instances.
72
+ if (model?.status?.value === 'loaded') {
73
+ const effective = positiveInt(model?.memory?.effective?.n_ctx) ?? positiveInt(model?.meta?.n_ctx);
74
+ if (effective) return { context: effective, source: 'loaded-effective' };
75
+ }
76
+ // --fit only adjusts arguments that were left unset; an explicit context is fixed.
77
+ if (context) return { context, source: 'fixed-preset' };
78
+ return { context: null, source: 'unknown', reason: 'No hay --ctx-size válido' };
79
+ }
80
+
81
+ /** @param {unknown} input @param {string[]} fallback */
82
+ function modalities(input, fallback) {
83
+ if (!Array.isArray(input)) return fallback;
84
+ const allowed = new Set(['text', 'image', 'audio', 'video', 'pdf', 'decisions']);
85
+ const result = [...new Set(input.filter(x=>typeof x==='string').map(x=>x.trim().toLowerCase()).filter(x=>allowed.has(x)))];
86
+ return result.length ? result : fallback;
87
+ }
88
+
89
+ /**
90
+ * @param {Record<string,any>} model
91
+ * @param {{outputTokens?:number, fallbackContext?:number}} options
92
+ */
93
+ export function mapModel(model, options = {}) {
94
+ if (!model || typeof model.id !== 'string' || !model.id.trim() || model.id.includes('#')) {
95
+ return { error: 'Identificador de modelo inválido' };
96
+ }
97
+ const state = model?.status?.value;
98
+ if (state === 'downloading' || state === 'incomplete') {
99
+ return { error: `${model.id}: modelo no descargado` };
100
+ }
101
+ if (model?.status?.failed === true) {
102
+ return { error: `${model.id}: la última carga falló` };
103
+ }
104
+ const fallbackContext = Number.isSafeInteger(options.fallbackContext) && options.fallbackContext >= 0
105
+ ? options.fallbackContext : DEFAULT_CONTEXT;
106
+ const context = configuredContext(model);
107
+ const contextValue = context.context ?? fallbackContext;
108
+ if (!contextValue) return { error: `${model.id}: ${context.reason ?? 'contexto desconocido'}` };
109
+ const input = modalities(model.architecture?.input_modalities, ['text']);
110
+ const output = modalities(model.architecture?.output_modalities, ['text']);
111
+ // The generic chat route cannot serve decision-only or audio-only models.
112
+ if (!output.includes('text')) return { error: `${model.id}: no es un modelo de salida de texto` };
113
+ const requestedOutput = positiveInt(options.outputTokens) ?? 32000;
114
+ const nPredict = positiveInt(flagValue(model.status?.args, ['--n-predict', '-n']) ?? iniValue(model.status?.preset, 'n-predict'));
115
+ const outputLimit = Math.min(contextValue, requestedOutput, nPredict ?? Number.MAX_SAFE_INTEGER);
116
+ const name = (typeof model.name === 'string' && model.name.trim()) ? model.name.trim() : model.id;
117
+ const reasoningFormat = flagValue(model.status?.args, ['--reasoning-format']) ?? iniValue(model.status?.preset, 'reasoning-format');
118
+ return {
119
+ id: model.id,
120
+ name,
121
+ context: contextValue,
122
+ contextSource: context.context ? context.source : 'fallback',
123
+ output: outputLimit,
124
+ // llama.cpp supports tool calling for chat models through --jinja.
125
+ capabilities: { tools: true, input, output, temperature: true },
126
+ // No speculative reasoning flags/variants. Add compatibility only when explicitly set.
127
+ compatibility: ['deepseek', 'deepseek-legacy'].includes(reasoningFormat) ? { reasoningField: 'reasoning_content' } : undefined,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * @param {unknown} payload
133
+ * @param {{outputTokens?:number, fallbackContext?:number}} options
134
+ */
135
+ export function parseRouterCatalog(payload, options = {}) {
136
+ if (!payload || typeof payload !== 'object' || !Array.isArray(payload.data)) {
137
+ throw new Error('El servidor no devolvió un objeto JSON con data[]');
138
+ }
139
+ const models = [];
140
+ const skipped = [];
141
+ for (const raw of payload.data) {
142
+ const model = mapModel(raw, options);
143
+ if (model.error) skipped.push(model.error);
144
+ else models.push(model);
145
+ }
146
+ models.sort((a,b)=>a.id.localeCompare(b.id));
147
+ return { models, skipped };
148
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "opencode-llamacpp-v2",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Plugin llama.cpp router para OpenCode V2",
5
+ "author": "renderxor",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./rpc": "./rpc.js",
11
+ "./tui": "./tui.js"
12
+ },
13
+ "files": [
14
+ "index.js",
15
+ "rpc.js",
16
+ "tui.js",
17
+ "lib/",
18
+ "README.md"
19
+ ],
20
+ "keywords": [
21
+ "opencode",
22
+ "opencode-plugin",
23
+ "llama.cpp",
24
+ "llamacpp",
25
+ "router"
26
+ ],
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+http://192.168.3.17:3000/renderxor/opencode-llamacpp-v2.git"
30
+ },
31
+ "homepage": "http://192.168.3.17:3000/renderxor/opencode-llamacpp-v2",
32
+ "bugs": {
33
+ "url": "http://192.168.3.17:3000/renderxor/opencode-llamacpp-v2/issues"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "dependencies": {
39
+ "@opencode/plugin": "2.3.2"
40
+ },
41
+ "scripts": {
42
+ "test": "node --test test/*.test.js"
43
+ }
44
+ }
package/rpc.js ADDED
@@ -0,0 +1,21 @@
1
+ import { Rpc } from '@opencode/plugin/rpc';
2
+
3
+ export const LlamacppRouter = Rpc.define({
4
+ id: 'opencode-llamacpp-v2',
5
+ methods: {},
6
+ events: {
7
+ toast: {
8
+ schema: {
9
+ type: 'object',
10
+ properties: {
11
+ title: { type: 'string' },
12
+ message: { type: 'string' },
13
+ variant: { type: 'string', enum: ['info', 'success', 'warning', 'error'] },
14
+ duration: { type: 'number' },
15
+ },
16
+ required: ['message'],
17
+ additionalProperties: false,
18
+ },
19
+ },
20
+ },
21
+ });
package/tui.js ADDED
@@ -0,0 +1,31 @@
1
+ import { Plugin } from '@opencode/plugin/tui';
2
+ import { LlamacppRouter } from './rpc.js';
3
+
4
+ const VARIANTS = new Set(['info', 'success', 'warning', 'error']);
5
+
6
+ export default Plugin.define({
7
+ id: 'opencode-llamacpp-v2.tui',
8
+ setup(context) {
9
+ let unsubscribe = () => {};
10
+ const currentDirectory = context.location?.directory ?? context.data?.location?.default?.().directory;
11
+
12
+ try {
13
+ const router = context.client.rpc(LlamacppRouter);
14
+ unsubscribe = router.events.on('toast', event => {
15
+ if (currentDirectory && event?.location?.directory && event.location.directory !== currentDirectory) return;
16
+ const data = event?.data;
17
+ if (!data || typeof data.message !== 'string') return;
18
+ context.ui.toast.show({
19
+ title: typeof data.title === 'string' ? data.title : 'llama.cpp',
20
+ message: data.message,
21
+ variant: VARIANTS.has(data.variant) ? data.variant : 'info',
22
+ ...(typeof data.duration === 'number' && Number.isFinite(data.duration) ? { duration: data.duration } : {}),
23
+ });
24
+ });
25
+ } catch (error) {
26
+ console.warn(`[opencode-llamacpp-v2] No se pudo suscribir a los avisos de la TUI: ${error instanceof Error ? error.message : String(error)}`);
27
+ }
28
+
29
+ return () => { if (typeof unsubscribe === 'function') unsubscribe(); };
30
+ },
31
+ });