tuxevil-rotator 4.2.1 → 4.3.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 (41) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +20 -6
  3. package/package.json +3 -3
  4. package/plugins/opencode-discovery/capabilities.d.mts +7 -0
  5. package/plugins/opencode-discovery/capabilities.mjs +54 -0
  6. package/plugins/opencode-discovery/index.d.mts +60 -0
  7. package/plugins/opencode-discovery/index.mjs +333 -0
  8. package/plugins/opencode-discovery/package.json +24 -0
  9. package/src/audio-transcription.ts +32 -6
  10. package/src/cli.ts +3 -3
  11. package/src/compat/model-specs.ts +4 -0
  12. package/src/compat.ts +34 -6
  13. package/src/dashboard-app.ts +1 -0
  14. package/src/install-agent.ts +252 -143
  15. package/src/install-opencode.ts +211 -43
  16. package/src/providers/google-antigravity/catalog.ts +45 -166
  17. package/src/providers/google-antigravity/dynamic-catalog.ts +107 -10
  18. package/src/providers/google-antigravity/forward.ts +4 -2
  19. package/src/providers/google-antigravity/index.ts +12 -4
  20. package/src/providers/google-antigravity/quota.ts +9 -7
  21. package/src/providers/ollama/forward.ts +10 -0
  22. package/src/providers/openai-codex/catalog.ts +157 -18
  23. package/src/proxy.ts +54 -5
  24. package/src/rotator.ts +32 -22
  25. package/src/types.ts +79 -67
  26. package/src/web/app.tsx +4 -0
  27. package/src/web/lib/audio-recorder.ts +159 -0
  28. package/src/web/lib/colors.ts +4 -0
  29. package/src/web/lib/playground-storage.ts +261 -0
  30. package/src/web/lib/playground.ts +448 -0
  31. package/src/web/nav.ts +1 -0
  32. package/src/web/pages/Playground.tsx +1111 -0
  33. package/src/web/pages/Transcription.tsx +428 -0
  34. package/src/web/state/api.ts +3 -0
  35. package/src/web/state/playground-client.ts +136 -0
  36. package/src/web/state/playground.ts +69 -0
  37. package/src/web/state/router.ts +2 -2
  38. package/src/web/state/transcription-client.ts +93 -0
  39. package/src/web/styles/app.css +45 -0
  40. package/tools/telemetry-receiver/receiver.js +59 -46
  41. package/plugins/opencode-discovery.js +0 -174
@@ -4,9 +4,18 @@ import { resolve, dirname } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
6
  const __dirname = dirname(fileURLToPath(import.meta.url));
7
- const OPENCODE_PLUGIN_SOURCE_PATH = resolve(__dirname, "../plugins/opencode-discovery.js");
8
-
9
- export type SupportedAgent = "opencode" | "hermes" | "pi" | "codex";
7
+ const OPENCODE_PLUGIN_SOURCE_DIR = resolve(
8
+ __dirname,
9
+ "../plugins/opencode-discovery",
10
+ );
11
+ const OPENCODE_PLUGIN_RUNTIME_FILES = [
12
+ "index.mjs",
13
+ "package.json",
14
+ "capabilities.mjs",
15
+ ];
16
+
17
+ export type SupportedAgent =
18
+ "opencode" | "hermes" | "pi" | "codex" | "openclaw";
10
19
 
11
20
  export interface AgentInstallOptions {
12
21
  targets?: Array<SupportedAgent | "auto" | "all">;
@@ -25,21 +34,48 @@ export interface AgentInstallOptions {
25
34
  * Builds the composite shell script that detects and configures all requested agents.
26
35
  */
27
36
  export function buildCompositeInstallerScript(
28
- opencodePluginContent: string,
37
+ opencodePluginFiles: Record<string, string>,
29
38
  options: {
30
39
  targets: Array<SupportedAgent | "auto" | "all">;
31
40
  rotatorUrl: string;
32
41
  providerId: string;
33
42
  providerName: string;
34
43
  apiKey?: string;
35
- }
44
+ },
36
45
  ): string {
37
- const pluginBase64 = Buffer.from(opencodePluginContent, "utf8").toString("base64");
46
+ if (
47
+ !OPENCODE_PLUGIN_RUNTIME_FILES.every((name) => name in opencodePluginFiles)
48
+ ) {
49
+ throw new Error(
50
+ `opencodePluginFiles must include all of: ${OPENCODE_PLUGIN_RUNTIME_FILES.join(", ")}`,
51
+ );
52
+ }
53
+
54
+ const pluginFileWriteLines = OPENCODE_PLUGIN_RUNTIME_FILES.map((name) => {
55
+ const base64 = Buffer.from(opencodePluginFiles[name], "utf8").toString(
56
+ "base64",
57
+ );
58
+ return `echo "${base64}" | base64 -d > "$OPENCODE_DIR/plugins/opencode-discovery/${name}"`;
59
+ }).join("\n");
38
60
  const rotatorUrl = options.rotatorUrl.replace(/\/+$/, "");
39
61
  const providerId = options.providerId || "tuxevil-rotator";
40
62
  const providerName = options.providerName || "Tuxevil Rotator";
41
63
  const apiKey = options.apiKey || "no-key";
42
- const targets = options.targets && options.targets.length > 0 ? options.targets : ["auto"];
64
+ const targets =
65
+ options.targets && options.targets.length > 0 ? options.targets : ["auto"];
66
+ const allowedTargets = new Set([
67
+ "opencode",
68
+ "hermes",
69
+ "pi",
70
+ "codex",
71
+ "openclaw",
72
+ "auto",
73
+ "all",
74
+ ]);
75
+ if (targets.some((target) => !allowedTargets.has(target)))
76
+ throw new Error(
77
+ "Unknown agent target. Use opencode, hermes, openclaw, pi, codex, auto or all.",
78
+ );
43
79
  const shouldAuto = targets.includes("auto") || targets.includes("all");
44
80
 
45
81
  return `#!/usr/bin/env bash
@@ -56,6 +92,20 @@ echo "==> Rotator URL: $ROTATOR_URL"
56
92
  echo "==> Provider ID: $PROVIDER_ID"
57
93
  echo "=========================================================="
58
94
 
95
+ # One catalog snapshot and shared capability mapper for every selected agent.
96
+ AGENT_WORK_DIR=$(mktemp -d)
97
+ trap 'rm -rf "$AGENT_WORK_DIR"' EXIT
98
+ printf %s "${Buffer.from(opencodePluginFiles["capabilities.mjs"], "utf8").toString("base64")}" | base64 -d > "$AGENT_WORK_DIR/capabilities.mjs"
99
+ node --input-type=module -e '
100
+ import fs from "node:fs";
101
+ import { pathToFileURL } from "node:url";
102
+ const { fetchModels } = await import(pathToFileURL(process.argv[1]).href);
103
+ let models = [];
104
+ try { models = await fetchModels(process.argv[2], process.argv[3]); }
105
+ catch { console.warn("==> Catalog unavailable; keeping existing model settings."); }
106
+ fs.writeFileSync(process.argv[4], JSON.stringify(models));
107
+ ' "$AGENT_WORK_DIR/capabilities.mjs" "$ROTATOR_URL" "$API_KEY" "$AGENT_WORK_DIR/models.json"
108
+
59
109
  # Helper to check if agent should be installed
60
110
  should_install() {
61
111
  local agent="$1"
@@ -83,15 +133,16 @@ OPENCODE_DIR="$HOME/.config/opencode"
83
133
  if should_install "opencode" "$OPENCODE_DIR"; then
84
134
  echo ""
85
135
  echo "==> [OpenCode] Configuring in $OPENCODE_DIR..."
86
- mkdir -p "$OPENCODE_DIR/plugins"
87
- echo "${pluginBase64}" | base64 -d > "$OPENCODE_DIR/plugins/opencode-discovery.js"
136
+ mkdir -p "$OPENCODE_DIR/plugins/opencode-discovery"
137
+ ${pluginFileWriteLines}
88
138
 
89
139
  node -e '
140
+ (async () => {
90
141
  const fs = require("fs");
91
142
  const path = require("path");
92
143
 
93
144
  const configFile = path.join(process.env.HOME, ".config/opencode/opencode.json");
94
- const pluginPath = path.join(process.env.HOME, ".config/opencode/plugins/opencode-discovery.js");
145
+ const pluginDir = path.join(process.env.HOME, ".config/opencode/plugins/opencode-discovery");
95
146
  const providerID = process.argv[1];
96
147
  const providerName = process.argv[2];
97
148
  const baseURL = process.argv[3];
@@ -109,19 +160,34 @@ if should_install "opencode" "$OPENCODE_DIR"; then
109
160
  }
110
161
 
111
162
  config.$schema = config.$schema || "https://opencode.ai/config.json";
112
- config.plugin = Array.isArray(config.plugin) ? config.plugin : [];
113
163
 
114
- // Remove existing discovery plugin
115
- config.plugin = config.plugin.filter(p => {
116
- if (typeof p === "string") return !p.includes("opencode-discovery.js");
117
- if (Array.isArray(p)) return !p[0].includes("opencode-discovery.js");
118
- return true;
164
+ const isDiscoveryEntry = (entry) => {
165
+ if (typeof entry === "string") return entry.includes("opencode-discovery");
166
+ if (Array.isArray(entry)) {
167
+ return typeof entry[0] === "string" && entry[0].includes("opencode-discovery");
168
+ }
169
+ if (entry && typeof entry === "object") {
170
+ return typeof entry.package === "string" && entry.package.includes("opencode-discovery");
171
+ }
172
+ return false;
173
+ };
174
+
175
+ // V2 plugin list: scrub prior discovery entries, then register the directory
176
+ config.plugins = Array.isArray(config.plugins) ? config.plugins.filter(p => !isDiscoveryEntry(p)) : [];
177
+ config.plugins.push({
178
+ package: pluginDir,
179
+ options: { baseURL, providerID, providerName }
119
180
  });
120
181
 
121
- config.plugin.push([
122
- pluginPath,
123
- { baseURL, providerID, providerName }
124
- ]);
182
+ // Legacy V1 key: scrub discovery entries, keep everything else untouched
183
+ if (Array.isArray(config.plugin)) {
184
+ const kept = config.plugin.filter(p => !isDiscoveryEntry(p));
185
+ if (kept.length > 0) {
186
+ config.plugin = kept;
187
+ } else {
188
+ delete config.plugin;
189
+ }
190
+ }
125
191
 
126
192
  config.provider = config.provider || {};
127
193
  config.provider[providerID] = config.provider[providerID] || {
@@ -138,9 +204,14 @@ if should_install "opencode" "$OPENCODE_DIR"; then
138
204
  config.provider[providerID].options.apiKey = apiKey;
139
205
  }
140
206
 
207
+ const { mergeOpenCodeModels } = await import(require("url").pathToFileURL(process.argv[6]).href);
208
+ const live = JSON.parse(fs.readFileSync(process.argv[5], "utf8"));
209
+ if (live.length) config.provider[providerID].models = mergeOpenCodeModels(config.provider[providerID].models, live);
210
+ if (fs.existsSync(configFile)) fs.copyFileSync(configFile, configFile + ".bak." + Date.now());
141
211
  fs.writeFileSync(configFile, JSON.stringify(config, null, 2) + "\\n", "utf8");
142
212
  console.log("==> [OpenCode] Configured successfully.");
143
- ' "$PROVIDER_ID" "$PROVIDER_NAME" "$ROTATOR_URL" "$API_KEY"
213
+ })().catch(error => { console.error(error.message); process.exitCode = 1; });
214
+ ' "$PROVIDER_ID" "$PROVIDER_NAME" "$ROTATOR_URL" "$API_KEY" "$AGENT_WORK_DIR/models.json" "$AGENT_WORK_DIR/capabilities.mjs"
144
215
  else
145
216
  echo "==> [OpenCode] Skipped (not selected or directory not found)."
146
217
  fi
@@ -148,85 +219,74 @@ fi
148
219
  # -------------------------------------------------------------
149
220
  # 2. Hermes Configuration
150
221
  # -------------------------------------------------------------
151
- HERMES_DIR="$HOME/.hermes"
222
+ HERMES_DIR="\${HERMES_HOME:-$HOME/.hermes}"
152
223
  if should_install "hermes" "$HERMES_DIR"; then
153
224
  echo ""
154
225
  echo "==> [Hermes] Configuring in $HERMES_DIR..."
155
226
  mkdir -p "$HERMES_DIR"
156
227
 
157
228
  python3 -c '
158
- import os, sys
159
-
160
- config_file = os.path.expanduser("~/.hermes/config.yaml")
161
- provider_id = sys.argv[1]
162
- rotator_url = sys.argv[2]
163
- api_key = sys.argv[3]
164
-
229
+ import os, sys, json, time, shutil
230
+ config_file = os.path.join(sys.argv[5], "config.yaml")
231
+ provider_id, rotator_url, api_key, models_file = sys.argv[1:5]
165
232
  try:
166
233
  import yaml
167
- has_yaml = True
168
234
  except ImportError:
169
- has_yaml = False
170
-
171
- if has_yaml:
172
- data = {}
173
- if os.path.exists(config_file):
174
- try:
175
- with open(config_file, "r", encoding="utf-8") as f:
176
- data = yaml.safe_load(f) or {}
177
- except Exception as e:
178
- print(f"Warning: could not parse {config_file}, preserving existing content")
179
- data = {}
180
-
181
- custom_providers = data.get("custom_providers", [])
182
- if not isinstance(custom_providers, list):
183
- custom_providers = []
184
-
185
- updated = False
186
- for p in custom_providers:
187
- if isinstance(p, dict) and p.get("name") in (provider_id, "tuxevil-rotator", "antigravity"):
188
- p["name"] = provider_id
189
- p["base_url"] = rotator_url
190
- p["api_key"] = api_key
191
- p["discover_models"] = True
192
- updated = True
193
- break
194
-
195
- if not updated:
196
- custom_providers.append({
197
- "name": provider_id,
198
- "base_url": rotator_url,
199
- "api_key": api_key,
200
- "discover_models": True
201
- })
202
-
203
- data["custom_providers"] = custom_providers
204
- with open(config_file, "w", encoding="utf-8") as f:
205
- yaml.safe_dump(data, f, sort_keys=False)
206
- print("==> [Hermes] Updated custom_providers with discover_models=True via PyYAML.")
235
+ yaml = None
236
+ content = open(config_file, encoding="utf-8").read() if os.path.exists(config_file) else ""
237
+ try:
238
+ data = (yaml.safe_load(content) if yaml else json.loads(content)) if content.strip() else {}
239
+ except Exception as error:
240
+ raise SystemExit("Cannot safely parse existing Hermes YAML; install PyYAML. Configuration was preserved.") from error
241
+ if not isinstance(data, dict):
242
+ raise SystemExit("Hermes configuration must be a mapping; configuration was preserved.")
243
+ custom = data.setdefault("custom_providers", [])
244
+ if not isinstance(custom, list):
245
+ raise SystemExit("Hermes custom_providers must be a list; configuration was preserved.")
246
+ modern = data.get("providers", {})
247
+ modern_entry = modern.get(provider_id) if isinstance(modern, dict) else None
248
+ entry = modern_entry if isinstance(modern_entry, dict) else next((p for p in custom if isinstance(p, dict) and p.get("name") == provider_id), None)
249
+ # Reuse an already connected legacy provider only when the endpoint matches.
250
+ if entry is None:
251
+ entry = next((p for p in custom if isinstance(p, dict) and p.get("name") in ("antigravity", "tuxevil-rotator") and str(p.get("base_url", "")).rstrip("/") == rotator_url), None)
252
+ if entry is None:
253
+ entry = {"name": provider_id}
254
+ custom.append(entry)
255
+ if entry is modern_entry:
256
+ entry["api"] = rotator_url
207
257
  else:
208
- # Minimal fallback block update if yaml library is not present
209
- entry = f"""
210
- custom_providers:
211
- - name: {provider_id}
212
- base_url: {rotator_url}
213
- api_key: {api_key}
214
- discover_models: true
215
- """
216
- if os.path.exists(config_file):
217
- with open(config_file, "r", encoding="utf-8") as f:
218
- content = f.read()
219
- if "discover_models" not in content and provider_id not in content:
220
- with open(config_file, "a", encoding="utf-8") as f:
221
- f.write(entry)
222
- print("==> [Hermes] Appended custom_providers entry.")
223
- else:
224
- print("==> [Hermes] Entry already present in config.yaml.")
258
+ entry["base_url"] = rotator_url
259
+ entry.setdefault("api_mode", "chat_completions")
260
+ entry.pop("discover_models", None)
261
+ if api_key != "no-key" or not (entry.get("api_key") or entry.get("key_env")):
262
+ entry["api_key"] = api_key
263
+ with open(models_file, encoding="utf-8") as f:
264
+ live = json.load(f)
265
+ models = entry.get("models", {})
266
+ if isinstance(models, list):
267
+ models = {name: {} for name in models if isinstance(name, str)}
268
+ if not isinstance(models, dict):
269
+ raise SystemExit("Hermes provider models must be a mapping or list; configuration was preserved.")
270
+ for model in live:
271
+ meta = model.get("meta", {})
272
+ prior = models.get(model["id"], {})
273
+ models[model["id"]] = {"context_length": meta.get("context_length", model.get("context_window", 128000)), **prior}
274
+ # A named-provider override enables native /reasoning controls without pinning
275
+ # an effort or changing defaults for any other provider.
276
+ if meta.get("provider") == "openai-codex" or meta.get("family") == "openai-codex":
277
+ overrides = data.setdefault("model_overrides", {}).setdefault("custom:" + entry.get("name", provider_id), {})
278
+ overrides.setdefault(model["id"], {}).setdefault("supports_reasoning", meta.get("reasoning", False))
279
+ if models:
280
+ entry["models"] = models
281
+ if content:
282
+ shutil.copy2(config_file, config_file + ".bak." + str(time.time_ns()))
283
+ with open(config_file, "w", encoding="utf-8") as f:
284
+ if yaml:
285
+ yaml.safe_dump(data, f, sort_keys=False)
225
286
  else:
226
- with open(config_file, "w", encoding="utf-8") as f:
227
- f.write(entry)
228
- print("==> [Hermes] Created config.yaml with custom_providers.")
229
- ' "$PROVIDER_ID" "$ROTATOR_URL" "$API_KEY"
287
+ json.dump(data, f, indent=2)
288
+ print("==> [Hermes] Connected; choose a Codex model and use /reasoning low|medium|high|xhigh|max as supported.")
289
+ ' "$PROVIDER_ID" "$ROTATOR_URL" "$API_KEY" "$AGENT_WORK_DIR/models.json" "$HERMES_DIR"
230
290
  else
231
291
  echo "==> [Hermes] Skipped (not selected or directory not found)."
232
292
  fi
@@ -243,39 +303,12 @@ if should_install "pi" "$PI_DIR"; then
243
303
  node -e '
244
304
  const fs = require("fs");
245
305
  const path = require("path");
246
- const http = require("http");
247
- const https = require("https");
248
306
 
249
307
  const modelsFile = path.join(process.env.HOME, ".pi/agent/models.json");
250
308
  const providerID = process.argv[1];
251
309
  const baseURL = process.argv[2];
252
310
  const apiKey = process.argv[3];
253
311
 
254
- async function fetchModels(url) {
255
- return new Promise((resolve) => {
256
- try {
257
- const parsed = new URL(url.replace(/\\/+$/, "") + "/models");
258
- const client = parsed.protocol === "https:" ? https : http;
259
- const req = client.get(parsed, { timeout: 3000 }, (res) => {
260
- let data = "";
261
- res.on("data", chunk => data += chunk);
262
- res.on("end", () => {
263
- try {
264
- const json = JSON.parse(data);
265
- resolve(Array.isArray(json?.data) ? json.data : []);
266
- } catch {
267
- resolve([]);
268
- }
269
- });
270
- });
271
- req.on("error", () => resolve([]));
272
- req.on("timeout", () => { req.destroy(); resolve([]); });
273
- } catch {
274
- resolve([]);
275
- }
276
- });
277
- }
278
-
279
312
  async function main() {
280
313
  let modelsData = { providers: {} };
281
314
  if (fs.existsSync(modelsFile)) {
@@ -289,18 +322,16 @@ if should_install "pi" "$PI_DIR"; then
289
322
  }
290
323
  modelsData.providers = modelsData.providers || {};
291
324
 
292
- const rawModels = await fetchModels(baseURL);
325
+ const rawModels = JSON.parse(fs.readFileSync(process.argv[4], "utf8"));
326
+ const { mapAgentModel } = await import(require("url").pathToFileURL(process.argv[5]).href);
293
327
  let mappedModels = [];
294
328
 
295
329
  if (rawModels.length > 0) {
296
- mappedModels = rawModels.map(m => ({
297
- id: m.id,
298
- name: m.name || m.id,
299
- reasoning: m.meta?.thinking ?? m.meta?.reasoning ?? false,
300
- input: m.meta?.multimodal ? ["text", "image"] : ["text"],
301
- contextWindow: m.meta?.context_length || m.context_window || 128000,
302
- maxTokens: m.meta?.max_output_tokens || 8192
303
- }));
330
+ mappedModels = rawModels.map(raw => {
331
+ const model = mapAgentModel(raw);
332
+ if (model.compat) model.compat = { supportsReasoningEffort: true };
333
+ return model;
334
+ });
304
335
  console.log("==> [Pi Agent] Discovered " + mappedModels.length + " live models from rotator.");
305
336
  } else {
306
337
  // Fallback baseline if rotator is not immediately reachable
@@ -312,10 +343,21 @@ if should_install "pi" "$PI_DIR"; then
312
343
  console.log("==> [Pi Agent] Rotator unreachable during install; populated standard baseline models.");
313
344
  }
314
345
 
346
+ const existing = modelsData.providers[providerID] || {};
347
+ if (!rawModels.length && existing.models?.length) mappedModels = existing.models;
348
+ else {
349
+ const merged = new Map((existing.models || []).map(model => [model.id, model]));
350
+ for (const model of mappedModels) {
351
+ const old = merged.get(model.id) || {};
352
+ merged.set(model.id, { ...model, ...old, ...(model.compat || old.compat ? { compat: { ...model.compat, ...old.compat } } : {}) });
353
+ }
354
+ mappedModels = [...merged.values()];
355
+ }
315
356
  modelsData.providers[providerID] = {
357
+ ...existing,
316
358
  baseUrl: baseURL,
317
359
  api: "openai-completions",
318
- apiKey: apiKey,
360
+ apiKey: apiKey !== "no-key" ? apiKey : existing.apiKey || apiKey,
319
361
  models: mappedModels
320
362
  };
321
363
 
@@ -323,8 +365,8 @@ if should_install "pi" "$PI_DIR"; then
323
365
  console.log("==> [Pi Agent] Configured successfully in " + modelsFile);
324
366
  }
325
367
 
326
- main();
327
- ' "$PROVIDER_ID" "$ROTATOR_URL" "$API_KEY"
368
+ main().catch(error => { console.error(error.message); process.exitCode = 1; });
369
+ ' "$PROVIDER_ID" "$ROTATOR_URL" "$API_KEY" "$AGENT_WORK_DIR/models.json" "$AGENT_WORK_DIR/capabilities.mjs"
328
370
  else
329
371
  echo "==> [Pi Agent] Skipped (not selected or directory not found)."
330
372
  fi
@@ -374,6 +416,47 @@ else
374
416
  echo "==> [Codex CLI] Skipped (not selected or directory not found)."
375
417
  fi
376
418
 
419
+ # -------------------------------------------------------------
420
+ # 5. OpenClaw Configuration
421
+ # -------------------------------------------------------------
422
+ OPENCLAW_DIR="\${OPENCLAW_STATE_DIR:-$HOME/.openclaw}"
423
+ if should_install "openclaw" "$OPENCLAW_DIR"; then
424
+ node -e '
425
+ const fs = require("fs"), path = require("path");
426
+ (async () => {
427
+ const configFile = process.env.OPENCLAW_CONFIG_PATH || path.join(process.argv[1], "openclaw.json");
428
+ const [providerID, baseURL, apiKey, modelsFile, helper] = process.argv.slice(2);
429
+ const { mapAgentModel } = await import(require("url").pathToFileURL(helper).href);
430
+ const live = JSON.parse(fs.readFileSync(modelsFile, "utf8"));
431
+ const content = fs.existsSync(configFile) ? fs.readFileSync(configFile, "utf8") : "";
432
+ let config;
433
+ try { config = content ? JSON.parse(content) : {}; }
434
+ catch { throw new Error("Cannot safely parse OpenClaw JSON; existing configuration was preserved."); }
435
+ config.models ||= {};
436
+ config.models.mode ||= "merge";
437
+ config.models.providers ||= {};
438
+ const prior = config.models.providers[providerID] || {};
439
+ const models = new Map((prior.models || []).map(model => [model.id, model]));
440
+ for (const raw of live) {
441
+ const generated = mapAgentModel(raw), old = models.get(raw.id) || {};
442
+ models.set(raw.id, { cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, ...generated, ...old,
443
+ ...(generated.compat || old.compat ? { compat: { ...generated.compat, ...old.compat } } : {}) });
444
+ }
445
+ config.models.providers[providerID] = { ...prior, baseUrl: baseURL,
446
+ api: prior.api && prior.api !== "openai" ? prior.api : "openai-completions",
447
+ apiKey: apiKey !== "no-key" ? apiKey : prior.apiKey || "no-key", models: [...models.values()] };
448
+ const allowlist = config.agents?.defaults?.models;
449
+ if (allowlist) for (const model of models.values()) allowlist[providerID + "/" + model.id] ||= {};
450
+ fs.mkdirSync(path.dirname(configFile), { recursive: true });
451
+ if (content) fs.copyFileSync(configFile, configFile + ".bak." + Date.now());
452
+ fs.writeFileSync(configFile, JSON.stringify(config, null, 2) + "\\n");
453
+ console.log("==> [OpenClaw] Connected; choose a Codex model and use /think high (or another advertised effort).");
454
+ })().catch(error => { console.error(error.message); process.exitCode = 1; });
455
+ ' "$OPENCLAW_DIR" "$PROVIDER_ID" "$ROTATOR_URL" "$API_KEY" "$AGENT_WORK_DIR/models.json" "$AGENT_WORK_DIR/capabilities.mjs"
456
+ else
457
+ echo "==> [OpenClaw] Skipped (not selected or directory not found)."
458
+ fi
459
+
377
460
  echo ""
378
461
  echo "==> All target agents processed successfully!"
379
462
  `;
@@ -382,12 +465,20 @@ echo "==> All target agents processed successfully!"
382
465
  /**
383
466
  * Installs configuration for one or more agents locally or over SSH.
384
467
  */
385
- export async function installAgents(options: AgentInstallOptions): Promise<void> {
386
- if (!existsSync(OPENCODE_PLUGIN_SOURCE_PATH)) {
387
- throw new Error(`OpenCode plugin file not found at ${OPENCODE_PLUGIN_SOURCE_PATH}`);
468
+ export async function installAgents(
469
+ options: AgentInstallOptions,
470
+ ): Promise<void> {
471
+ if (!existsSync(resolve(OPENCODE_PLUGIN_SOURCE_DIR, "index.mjs"))) {
472
+ throw new Error(
473
+ `OpenCode plugin directory missing index.mjs at ${OPENCODE_PLUGIN_SOURCE_DIR}`,
474
+ );
388
475
  }
389
476
 
390
- const opencodePluginContent = readFileSync(OPENCODE_PLUGIN_SOURCE_PATH, "utf8");
477
+ const opencodePluginFiles: Record<string, string> = {};
478
+ for (const name of OPENCODE_PLUGIN_RUNTIME_FILES) {
479
+ const filePath = resolve(OPENCODE_PLUGIN_SOURCE_DIR, name);
480
+ opencodePluginFiles[name] = readFileSync(filePath, "utf8");
481
+ }
391
482
  const rotatorUrl = (
392
483
  options.rotatorUrl ||
393
484
  process.env.TUXEVIL_ROTATOR_BASE_URL ||
@@ -397,9 +488,10 @@ export async function installAgents(options: AgentInstallOptions): Promise<void>
397
488
 
398
489
  const providerId = options.providerId || "tuxevil-rotator";
399
490
  const providerName = options.providerName || "Tuxevil Rotator";
400
- const targets: Array<SupportedAgent | "auto" | "all"> = options.targets && options.targets.length > 0 ? options.targets : ["auto"];
491
+ const targets: Array<SupportedAgent | "auto" | "all"> =
492
+ options.targets && options.targets.length > 0 ? options.targets : ["auto"];
401
493
 
402
- const script = buildCompositeInstallerScript(opencodePluginContent, {
494
+ const script = buildCompositeInstallerScript(opencodePluginFiles, {
403
495
  targets,
404
496
  rotatorUrl,
405
497
  providerId,
@@ -408,14 +500,22 @@ export async function installAgents(options: AgentInstallOptions): Promise<void>
408
500
  });
409
501
 
410
502
  if (options.dryRun) {
411
- console.log("=== Dry Run Mode: Composite Script that would be executed ===");
503
+ console.log(
504
+ "=== Dry Run Mode: Composite Script that would be executed ===",
505
+ );
412
506
  console.log(script);
413
507
  return;
414
508
  }
415
509
 
416
510
  // Local installation
417
- if (!options.host || options.host === "localhost" || options.host === "127.0.0.1") {
418
- console.log(`==> Installing agent configuration locally for rotator: ${rotatorUrl}...`);
511
+ if (
512
+ !options.host ||
513
+ options.host === "localhost" ||
514
+ options.host === "127.0.0.1"
515
+ ) {
516
+ console.log(
517
+ `==> Installing agent configuration locally for rotator: ${rotatorUrl}...`,
518
+ );
419
519
  execSync("bash -s", {
420
520
  input: script,
421
521
  stdio: ["pipe", "inherit", "inherit"],
@@ -424,11 +524,16 @@ export async function installAgents(options: AgentInstallOptions): Promise<void>
424
524
  }
425
525
 
426
526
  // Remote installation via SSH
427
- const sshTarget = options.user ? `${options.user}@${options.host}` : options.host;
527
+ const sshTarget = options.user
528
+ ? `${options.user}@${options.host}`
529
+ : options.host;
428
530
  const sshArgs: string[] = [
429
- "-o", "BatchMode=yes",
430
- "-o", "ConnectTimeout=10",
431
- "-o", "StrictHostKeyChecking=accept-new",
531
+ "-o",
532
+ "BatchMode=yes",
533
+ "-o",
534
+ "ConnectTimeout=10",
535
+ "-o",
536
+ "StrictHostKeyChecking=accept-new",
432
537
  ];
433
538
 
434
539
  if (options.port) {
@@ -440,7 +545,9 @@ export async function installAgents(options: AgentInstallOptions): Promise<void>
440
545
 
441
546
  const sshCmd = `ssh ${sshArgs.join(" ")} ${sshTarget} "bash -s"`;
442
547
 
443
- console.log(`==> Installing agent configuration remotely on ${sshTarget} (Rotator: ${rotatorUrl})...`);
548
+ console.log(
549
+ `==> Installing agent configuration remotely on ${sshTarget} (Rotator: ${rotatorUrl})...`,
550
+ );
444
551
  try {
445
552
  execSync(sshCmd, {
446
553
  input: script,
@@ -448,6 +555,8 @@ export async function installAgents(options: AgentInstallOptions): Promise<void>
448
555
  });
449
556
  } catch (err: unknown) {
450
557
  const errorMsg = err instanceof Error ? err.message : String(err);
451
- throw new Error(`SSH installation failed on ${sshTarget}: ${errorMsg}`, { cause: err });
558
+ throw new Error(`SSH installation failed on ${sshTarget}: ${errorMsg}`, {
559
+ cause: err,
560
+ });
452
561
  }
453
562
  }