Files
public/opencode/install-arka-provider.ps1
T
ixoblakp ed34998cb7 feat(opencode): support opencode 2.x + generation-aware installer
opencode 2.x changed the plugin API (a plugin must export { id, setup }), so
the 1.x plugin (plugins/arka-ai.ts) no longer loads there and the Arka-AI
provider disappeared ('failed to load plugin').

- install-arka-provider.sh / .ps1 now detect the generation (opencode --version:
  '1.x.y' vs 'opencode v2.x.y'; --gen / -Gen override):
    * 1.x -> install the plugin (dynamic catalog), as before;
    * 2.x -> write a static providers["Arka-AI"] block
      (package @opencode/ai/providers/openai-compatible, settings.baseURL,
      settings.apiKey, models from catalog.json) and disable any stale 1.x plugin.
- --refresh / -Refresh regenerates the 2.x model list (infers generation 2 from
  the installed config); 1.x still clears the cache.
- README + companion skill updated with the 1.x/2.x table, detection, and the
  providers schema.

Verified: gen detection, gen1 plugin write, gen2 providers write (117 models),
merge preserves unrelated keys, stale plugin disabled, refresh keeps the key.
2026-10-27 12:20:31 +03:00

399 lines
14 KiB
PowerShell

# install-arka-provider.ps1 — OpenCode Arka-AI provider for Windows (CLI and
# Desktop). Idempotent. Detects the opencode generation:
# * 1.x -> installs the provider plugin (plugins\arka-ai.ts)
# * 2.x -> writes providers["Arka-AI"] into opencode.jsonc (no plugin; 2.x
# changed the plugin API, so the 1.x plugin no longer loads there)
#
# One-liner (PowerShell):
# irm https://git.arka-ai.ru/arka/public/raw/branch/main/opencode/install-arka-provider.ps1 | iex
#
# With key + default model:
# iwr -useb URL -OutFile $env:TEMP\install-arka.ps1
# powershell -ExecutionPolicy Bypass -File $env:TEMP\install-arka.ps1 -Key $env:ARKA_API_KEY -SetDefault DeepSeek-V4-Pro
#
# Force a generation / refresh models:
# powershell -ExecutionPolicy Bypass -File install-arka-provider.ps1 -Gen 2
# powershell -ExecutionPolicy Bypass -File install-arka-provider.ps1 -Refresh
#
# cmd.exe:
# powershell -NoProfile -ExecutionPolicy Bypass -Command "irm URL | iex"
[CmdletBinding()]
param(
[string]$Key,
[string]$SetDefault,
[ValidateSet('1','2')][string]$Gen,
[switch]$Refresh
)
$ErrorActionPreference = 'Stop'
$CatalogUrl = 'https://git.arka-ai.ru/arka/public/raw/branch/main/opencode/catalog.json'
$ApiUrl = 'https://api.arka-ai.ru/v1'
if (-not $Key) { $Key = $env:ARKA_API_KEY }
function Get-ConfigDir {
if ($env:XDG_CONFIG_HOME) { return (Join-Path $env:XDG_CONFIG_HOME 'opencode') }
return (Join-Path $HOME '.config\opencode')
}
function Get-InstallDirs {
$dirs = New-Object System.Collections.Generic.List[string]
$canonical = Get-ConfigDir
[void]$dirs.Add($canonical)
if ($env:APPDATA) {
$legacy = Join-Path $env:APPDATA 'opencode'
if ((Test-Path $legacy) -and ($legacy -ne $canonical)) { [void]$dirs.Add($legacy) }
}
return $dirs
}
function Get-Gen {
if ($Gen) { return $Gen }
if ($env:OPENCODE_GEN) { return $env:OPENCODE_GEN }
try {
$v = (& opencode --version 2>$null | Select-Object -First 1)
if ($v -match '(\d+)') {
if ([int]$Matches[1] -ge 2) { return '2' } else { return '1' }
}
} catch {}
return ''
}
function Get-CatalogIds {
try {
$cat = Invoke-RestMethod -Uri $CatalogUrl -TimeoutSec 25
return @($cat.data | ForEach-Object { $_.id } | Where-Object { $_ })
} catch {
try {
$m = Invoke-RestMethod -Uri "$ApiUrl/models" -TimeoutSec 25
return @($m.data | ForEach-Object { $_.id } | Where-Object { $_ })
} catch { return @() }
}
}
$gen = Get-Gen
if (-not $gen) {
Write-Warning 'could not detect opencode version (opencode not on PATH?); defaulting to generation 2. Use -Gen 1 for opencode 1.x.'
$gen = '2'
}
Write-Host "==> opencode generation: $gen"
if (-not $Key -and -not $Refresh) {
$entered = Read-Host 'ARKA_API_KEY (leave blank to skip)'
if ($entered) { $Key = $entered }
}
# --- embedded 1.x plugin ------------------------------------------------
$plugin = @'
import { homedir } from "node:os"
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
import { join } from "node:path"
const PROVIDER_ID = "Arka-AI"
const API_URL = "https://api.arka-ai.ru/v1"
const CATALOG_URL =
"https://git.arka-ai.ru/arka/public/raw/branch/main/opencode/catalog.json"
const TTL_MS = 24 * 60 * 60 * 1000
function configDir(): string {
const xdg = process.env.XDG_CONFIG_HOME
if (xdg) return join(xdg, "opencode")
return join(homedir(), ".config", "opencode")
}
function cacheDir(): string {
const xdg = process.env.XDG_CACHE_HOME
if (xdg) return join(xdg, "opencode")
return join(homedir(), ".cache", "opencode")
}
const CACHE_FILE = join(cacheDir(), "arka-ai-models.json")
const KEY_FILE = join(configDir(), ".arka-api-key")
function readApiKey(): string | undefined {
const fromEnv = process.env.ARKA_API_KEY?.trim()
if (fromEnv) return fromEnv
try {
if (existsSync(KEY_FILE)) {
const fromFile = readFileSync(KEY_FILE, "utf8").trim()
if (fromFile) return fromFile
}
} catch {}
return undefined
}
const FORCED_MODELS = [
"DeepSeek-V4-Pro",
"deepseek-v4-flash-0731",
"qwen3.8-max",
"kimi-k3",
"MiniMax-M3",
"GLM-5.3",
]
const NON_CHAT = new RegExp(
[
"tts", "asr", "audio", "speech", "voice", "whisper", "sensevoice",
"image", "(^|[.-])img", "wan", "vidu", "video", "sora", "flux",
"diffus", "kolors", "cogview", "ocr", "embedding", "(^|[.-])embed",
"rerank", "clip", "moderation", "(^|[.-])filter", "detect", "classif",
"(^|[.-])location", "(^|[.-])search", "comfyui", "meme", "hello",
"(^|[.-])sam", "florence", "esrgan", "rmbg", "background", "poster",
"(^|[.-])face", "(^|[.-])lip", "translate", "(^|[.-])mt([2-]|$)",
"(^|[.-])bge", "(^|[.-])e5", "(^|[.-])jina", "(^|[.-])mpnet",
"spark-tts", "cosyvoice", "chattts", "indextts", "step-audio",
"fish-speech", "cosy", "mate-gguf", "tokenizer",
].join("|"),
"i",
)
type ModelMap = Record<string, { name: string }>
type Cache = { ts: number; models: ModelMap }
function loadCache(): Cache | null {
try {
if (existsSync(CACHE_FILE)) return JSON.parse(readFileSync(CACHE_FILE, "utf8"))
} catch {}
return null
}
function saveCache(models: ModelMap): void {
try {
mkdirSync(cacheDir(), { recursive: true })
writeFileSync(CACHE_FILE, JSON.stringify({ ts: Date.now(), models }))
} catch {}
}
async function fetchJson(
url: string,
headers: Record<string, string>,
timeoutMs: number,
): Promise<unknown> {
const ctrl = new AbortController()
const timer = setTimeout(() => ctrl.abort(), timeoutMs)
try {
const res = await fetch(url, { headers, signal: ctrl.signal })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return await res.json()
} finally {
clearTimeout(timer)
}
}
function idsFromPayload(json: unknown): string[] {
const data = (json as { data?: Array<{ id: string }> }).data
return (data ?? []).map((m) => m.id).filter(Boolean)
}
function toModelMap(ids: string[], filter: boolean): ModelMap {
const models: ModelMap = {}
for (const id of ids) {
if (!filter || FORCED_MODELS.includes(id) || !NON_CHAT.test(id)) {
models[id] = { name: id }
}
}
return models
}
async function resolveModels(): Promise<ModelMap | null> {
const cache = loadCache()
if (cache && Date.now() - cache.ts < TTL_MS) return cache.models
try {
const models = toModelMap(idsFromPayload(await fetchJson(CATALOG_URL, {}, 5000)), false)
if (Object.keys(models).length) {
saveCache(models)
return models
}
} catch {}
try {
const key = readApiKey()
const json = await fetchJson(
`${API_URL}/models`,
key ? { Authorization: `Bearer ${key}` } : {},
5000,
)
const models = toModelMap(idsFromPayload(json), true)
saveCache(models)
return models
} catch {
return cache?.models ?? null
}
}
export default async function ArkaAIProviderPlugin() {
const models = await resolveModels()
const apiKey = readApiKey()
return {
config: (cfg: any) => {
cfg.provider ??= {}
const prev = cfg.provider[PROVIDER_ID] ?? {}
cfg.provider[PROVIDER_ID] = {
name: "Arka-AI",
api: API_URL,
env: ["ARKA_API_KEY"],
...prev,
models: { ...(prev.models ?? {}), ...(models ?? {}) },
options: {
...(prev.options ?? {}),
...(apiKey ? { apiKey } : {}),
},
}
},
}
}
'@
$skill = @'
---
name: arka-provider
description: Manage the custom Arka-AI (arka-ai.ru) LLM provider in opencode config (1.x and 2.x). Use when the user needs to add, refresh, or fix the arka-ai.ru provider, sync its model catalog, change the Arka-AI default model, or when arka models are missing from /models.
---
# Arka-AI provider
arka-ai.ru is **not** in models.dev, so opencode ships no built-in config for it.
The mechanism depends on the opencode generation:
| opencode | provider lives in | models |
|----------|-------------------|--------|
| **1.x** | plugin `~/.config/opencode/plugins/arka-ai.ts` (injects via the `config` hook) | dynamic (public catalog, cached 24h) |
| **2.x** | static `providers["Arka-AI"]` block in `opencode.jsonc` | static list (refresh via the installer) |
`opencode --version` prints `1.x.y` on 1.x and `opencode v2.x.y` on 2.x. The
installer detects this. (2.x changed the plugin API: a 1.x plugin no longer
loads, so the static block is used and the stale plugin is disabled.)
- 1.x: key from `ARKA_API_KEY` env or `~/.config/opencode/.arka-api-key`.
- 2.x: `providers["Arka-AI"]` with `package @opencode/ai/providers/openai-compatible`,
`settings.baseURL https://api.arka-ai.ru/v1`, `settings.apiKey`, and a `models` map.
Refresh models: re-run the installer (`-Refresh` on Windows).
## Change default model
`"model": "Arka-AI/<model-id>"` in the config file (IDs exactly as in the catalog).
## Adjust filtering
`NON_CHAT` / `FORCED_MODELS` live in the 1.x plugin, the installer's 2.x
generator, and `scripts/sync-catalog.py` — keep them in lockstep.
## Probing plan coverage
The public catalog lists every platform model, not your plan's allow-list.
Out-of-plan calls return `400 … does not support using vendor "arka"`. The
allow-list lives only in the admin console.
'@
$dirs = Get-InstallDirs
foreach ($conf in $dirs) {
$pluginDir = Join-Path $conf 'plugins'
$skillDir = Join-Path $conf 'skills\arka-provider'
New-Item -ItemType Directory -Force -Path $pluginDir | Out-Null
New-Item -ItemType Directory -Force -Path $skillDir | Out-Null
[System.IO.File]::WriteAllText((Join-Path $skillDir 'SKILL.md'), $skill.TrimStart() + "`n")
Write-Host "==> skill $(Join-Path $skillDir 'SKILL.md')"
if ($Key) {
$keyFile = Join-Path $conf '.arka-api-key'
[System.IO.File]::WriteAllText($keyFile, $Key.Trim() + "`n")
Write-Host "==> key $keyFile"
}
if ($gen -eq '1' -and -not $Refresh) {
$pluginPath = Join-Path $pluginDir 'arka-ai.ts'
[System.IO.File]::WriteAllText($pluginPath, $plugin.TrimStart() + "`n")
Write-Host "==> plugin $pluginPath"
if ($SetDefault) {
$confFile = Join-Path $conf 'opencode.json'
$data = $null
if (Test-Path $confFile) { $data = Get-Content -Raw -Encoding UTF8 $confFile | ConvertFrom-Json }
if (-not $data) { $data = New-Object psobject }
$data | Add-Member -NotePropertyName '$schema' -NotePropertyValue 'https://opencode.ai/config.json' -Force
$data | Add-Member -NotePropertyName model -NotePropertyValue ("Arka-AI/" + $SetDefault) -Force
($data | ConvertTo-Json -Depth 40) + "`n" | Out-File -FilePath $confFile -Encoding utf8
Write-Host "==> default Arka-AI/$SetDefault in $confFile"
}
}
elseif ($gen -eq '2') {
# Disable a stale 1.x plugin so 2.x doesn't spam load errors.
$stale = Join-Path $pluginDir 'arka-ai.ts'
if (Test-Path $stale) {
Move-Item -Force $stale "$stale.disabled"
Write-Host "==> disabled stale 1.x plugin ($stale.disabled)"
}
$confFile = Join-Path $conf 'opencode.jsonc'
if (-not (Test-Path $confFile)) {
$alt = Join-Path $conf 'opencode.json'
if (Test-Path $alt) { $confFile = $alt }
}
$data = $null
if (Test-Path $confFile) {
$raw = Get-Content -Raw -Encoding UTF8 $confFile
$stripped = (($raw -split "`n") | Where-Object { $_ -notmatch '^\s*//' }) -join "`n"
try { $data = $stripped | ConvertFrom-Json } catch { $data = $null }
}
if (-not $data) { $data = New-Object psobject }
if (-not $data.PSObject.Properties['$schema']) {
$data | Add-Member -NotePropertyName '$schema' -NotePropertyValue 'https://opencode.ai/config.json' -Force
}
$providers = $data.providers
if (-not $providers) { $providers = New-Object psobject; $data | Add-Member -NotePropertyName providers -NotePropertyValue $providers -Force }
$prov = $providers.'Arka-AI'
if (-not $prov) { $prov = New-Object psobject; $providers | Add-Member -NotePropertyName 'Arka-AI' -NotePropertyValue $prov -Force }
$prov | Add-Member -NotePropertyName name -NotePropertyValue 'Arka-AI' -Force
$prov | Add-Member -NotePropertyName package -NotePropertyValue '@opencode/ai/providers/openai-compatible' -Force
$prov | Add-Member -NotePropertyName env -NotePropertyValue @('ARKA_API_KEY') -Force
$settings = New-Object psobject
$settings | Add-Member -NotePropertyName baseURL -NotePropertyValue $ApiUrl -Force
if ($Key) { $settings | Add-Member -NotePropertyName apiKey -NotePropertyValue $Key -Force }
$prov | Add-Member -NotePropertyName settings -NotePropertyValue $settings -Force
$ids = Get-CatalogIds
if ($ids.Count -gt 0) {
$models = [ordered]@{}
foreach ($id in $ids) { $models[$id] = @{ name = $id } }
$prov | Add-Member -NotePropertyName models -NotePropertyValue $models -Force
Write-Host "==> models $($ids.Count) chat models"
}
if ($SetDefault) {
$data | Add-Member -NotePropertyName model -NotePropertyValue ("Arka-AI/" + $SetDefault) -Force
}
($data | ConvertTo-Json -Depth 40) + "`n" | Out-File -FilePath $confFile -Encoding utf8
Write-Host "==> providers['Arka-AI'] in $confFile"
}
}
if ($Key) {
$env:ARKA_API_KEY = $Key
try {
[Environment]::SetEnvironmentVariable('ARKA_API_KEY', $Key, 'User')
Write-Host '==> User environment ARKA_API_KEY (CLI/Desktop pick it up after a full restart)'
} catch {
Write-Warning "could not set User environment variable: $_"
}
} elseif (-not $Refresh) {
Write-Warning 'no ARKA_API_KEY; Desktop will not be able to call models until you set it'
}
Write-Host ''
Write-Host "Done (opencode generation $gen)."
Write-Host 'Next:'
Write-Host ' 1. Fully quit OpenCode CLI *and* OpenCode Desktop (tray icon too), then start again.'
Write-Host ' 2. /models — provider Arka-AI should appear.'
if ($gen -eq '2') {
Write-Host ' 3. Refresh models later: re-run this installer with -Refresh.'
} else {
Write-Host ' 3. Refresh later: delete %USERPROFILE%\.cache\opencode\arka-ai-models.json and restart.'
}