tuxevil-rotator 3.8.0 → 3.10.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/CHANGELOG.md +44 -7
- package/README.md +5 -1
- package/package.json +3 -2
- package/plugins/opencode-discovery.d.ts +65 -0
- package/plugins/opencode-discovery.js +174 -0
- package/src/audio-transcription.ts +1265 -117
- package/src/auto-routing.ts +251 -39
- package/src/cli.ts +130 -0
- package/src/compat/model-specs.ts +59 -58
- package/src/compat/schema-sanitizer.ts +11 -3
- package/src/compat.ts +5 -5
- package/src/config-defaults.ts +1 -0
- package/src/index.ts +39 -1
- package/src/install-agent.ts +453 -0
- package/src/install-opencode.ts +201 -0
- package/src/key-auth.ts +69 -5
- package/src/onboarding.ts +17 -2
- package/src/providers/google-antigravity/dynamic-catalog.ts +1 -1
- package/src/providers/google-antigravity/translators.ts +16 -0
- package/src/providers/openai-codex/catalog.ts +8 -6
- package/src/providers/openai-codex/compat.ts +1 -1
- package/src/proxy.ts +38 -5
- package/src/response-headers.ts +1 -1
- package/src/rotator.ts +52 -7
- package/src/static/dashboard.js +10 -1
- package/src/telemetry.ts +32 -2
- package/src/types.ts +23 -6
- package/src/validators.ts +3 -0
- package/tools/telemetry-receiver/README.md +3 -1
- package/tools/telemetry-receiver/receiver.js +36 -0
|
@@ -108,7 +108,7 @@ export function sanitizeClaudeViaGeminiSchema(schema: unknown): unknown {
|
|
|
108
108
|
"patternProperties", "unevaluatedProperties", "unevaluatedItems",
|
|
109
109
|
"contentEncoding", "contentMediaType",
|
|
110
110
|
// Gemini's protobuf layer rejects these regardless of target model
|
|
111
|
-
"exclusiveMinimum", "exclusiveMaximum", "propertyNames", "deprecated",
|
|
111
|
+
"exclusiveMinimum", "exclusiveMaximum", "propertyNames", "uniqueItems", "deprecated",
|
|
112
112
|
]);
|
|
113
113
|
|
|
114
114
|
const out: Record<string, unknown> = {};
|
|
@@ -280,5 +280,13 @@ export function sanitizeClaudeViaGeminiSchema(schema: unknown): unknown {
|
|
|
280
280
|
|
|
281
281
|
out[key] = isRecord(value) ? sanitizeClaudeViaGeminiSchema(value) : value;
|
|
282
282
|
}
|
|
283
|
-
|
|
284
|
-
|
|
283
|
+
// Gemini's Schema proto accepts only strings in enum, even for Claude-bound
|
|
284
|
+
// requests. Preserve the primitive type and drop unsupported enum values.
|
|
285
|
+
if (Array.isArray(out.enum) && !out.enum.every((value) => typeof value === "string")) {
|
|
286
|
+
if (!out.type && out.enum.length > 0 && out.enum.every((value) => typeof value === "boolean")) {
|
|
287
|
+
out.type = "boolean";
|
|
288
|
+
}
|
|
289
|
+
delete out.enum;
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
package/src/compat.ts
CHANGED
|
@@ -204,7 +204,7 @@ async function resolveAutoModel(
|
|
|
204
204
|
): Promise<{
|
|
205
205
|
model: string;
|
|
206
206
|
providerId: string;
|
|
207
|
-
mode: "typesafe" | "deterministic";
|
|
207
|
+
mode: "typesafe" | "deterministic" | "shadow";
|
|
208
208
|
confidence?: number;
|
|
209
209
|
reason: string;
|
|
210
210
|
} | null> {
|
|
@@ -2567,16 +2567,16 @@ const MODEL_CATALOG = [
|
|
|
2567
2567
|
tools: true,
|
|
2568
2568
|
},
|
|
2569
2569
|
{
|
|
2570
|
-
id: "
|
|
2571
|
-
family: "
|
|
2570
|
+
id: "gemini-3.5-flash-lite",
|
|
2571
|
+
family: "gemini-3.5-flash",
|
|
2572
2572
|
ctx: 1048576,
|
|
2573
2573
|
quotaPool: "gemini",
|
|
2574
2574
|
multimodal: true,
|
|
2575
|
-
tools:
|
|
2575
|
+
tools: true,
|
|
2576
2576
|
},
|
|
2577
2577
|
{
|
|
2578
2578
|
id: "whisper-1",
|
|
2579
|
-
family: "
|
|
2579
|
+
family: "gemini-3.8-flash",
|
|
2580
2580
|
ctx: 1048576,
|
|
2581
2581
|
quotaPool: "gemini",
|
|
2582
2582
|
multimodal: true,
|
package/src/config-defaults.ts
CHANGED
|
@@ -66,6 +66,7 @@ export function applyConfigDefaults(config: Config): Config {
|
|
|
66
66
|
baseURL: config.typesafeRouting.baseURL,
|
|
67
67
|
timeoutMs: config.typesafeRouting.timeoutMs ?? 3_000,
|
|
68
68
|
minConfidence: config.typesafeRouting.minConfidence ?? 0.45,
|
|
69
|
+
shadowMode: config.typesafeRouting.shadowMode ?? false,
|
|
69
70
|
maxCandidates: config.typesafeRouting.maxCandidates ?? 32,
|
|
70
71
|
shortlistSize: config.typesafeRouting.shortlistSize ?? 12,
|
|
71
72
|
maxExcerptChars: config.typesafeRouting.maxExcerptChars ?? 12_000,
|
package/src/index.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import type { Config } from "./types.js";
|
|
5
5
|
import { AccountRotator } from "./rotator.js";
|
|
6
6
|
import { startProxy } from "./proxy.js";
|
|
7
|
+
import { closeAllAudioWebSockets } from "./audio-transcription.js";
|
|
7
8
|
import { getConfigDir } from "./paths.js";
|
|
8
9
|
import { TelemetryReporter, setActiveReporter } from "./telemetry.js";
|
|
9
10
|
import { loadConfig as loadConfigFromStore, importLegacyOllamaRotatorAccounts } from "./account-store.js";
|
|
@@ -47,6 +48,8 @@ function loadConfig(): Config {
|
|
|
47
48
|
}
|
|
48
49
|
|
|
49
50
|
const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
|
|
51
|
+
const SHUTDOWN_SERVER_CLOSE_TIMEOUT_MS = 3_000;
|
|
52
|
+
const SHUTDOWN_FORCE_EXIT_MS = 10_000;
|
|
50
53
|
|
|
51
54
|
/**
|
|
52
55
|
* Show a one-time, non-intrusive star reminder after 24h since first install.
|
|
@@ -242,10 +245,44 @@ export async function main(): Promise<void> {
|
|
|
242
245
|
setActiveReporter(telemetry);
|
|
243
246
|
void telemetry.start();
|
|
244
247
|
|
|
248
|
+
let server: ReturnType<typeof startProxy> | null = null;
|
|
249
|
+
let shuttingDown = false;
|
|
250
|
+
|
|
245
251
|
// ── Graceful shutdown ──
|
|
246
252
|
const shutdown = async (): Promise<void> => {
|
|
253
|
+
// npm/tsx wrappers can deliver the same Ctrl+C twice; a forced exit here would skip the flushes.
|
|
254
|
+
if (shuttingDown) {
|
|
255
|
+
console.log("Shutdown already in progress");
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
shuttingDown = true;
|
|
247
259
|
console.log("\nShutting down...");
|
|
260
|
+
// Last resort if a flush hangs; cleared before the normal exit so it can never fire later.
|
|
261
|
+
const forceExitTimer = setTimeout(() => {
|
|
262
|
+
console.error(`Shutdown did not finish within ${SHUTDOWN_FORCE_EXIT_MS}ms; forcing exit`);
|
|
263
|
+
process.exit(1);
|
|
264
|
+
}, SHUTDOWN_FORCE_EXIT_MS);
|
|
265
|
+
forceExitTimer.unref();
|
|
248
266
|
stopRetentionCleanup();
|
|
267
|
+
closeAllAudioWebSockets();
|
|
268
|
+
const currentServer = server;
|
|
269
|
+
if (currentServer) {
|
|
270
|
+
// Bounded: a peer that never finishes closing must not keep the flushes below from running.
|
|
271
|
+
await new Promise<void>((resolve) => {
|
|
272
|
+
const closeTimer = setTimeout(() => {
|
|
273
|
+
console.warn(
|
|
274
|
+
`Proxy server did not close within ${SHUTDOWN_SERVER_CLOSE_TIMEOUT_MS}ms; continuing shutdown`,
|
|
275
|
+
);
|
|
276
|
+
resolve();
|
|
277
|
+
}, SHUTDOWN_SERVER_CLOSE_TIMEOUT_MS);
|
|
278
|
+
closeTimer.unref();
|
|
279
|
+
currentServer.close(() => {
|
|
280
|
+
clearTimeout(closeTimer);
|
|
281
|
+
resolve();
|
|
282
|
+
});
|
|
283
|
+
(currentServer as any).closeAllConnections?.();
|
|
284
|
+
});
|
|
285
|
+
}
|
|
249
286
|
await flushSpendLogs();
|
|
250
287
|
await flushResponsesStore();
|
|
251
288
|
await rotator.flushPendingStateSave();
|
|
@@ -256,12 +293,13 @@ export async function main(): Promise<void> {
|
|
|
256
293
|
await closeProxyDispatchers();
|
|
257
294
|
const { closeDb } = await import("./db-store.js");
|
|
258
295
|
await closeDb();
|
|
296
|
+
clearTimeout(forceExitTimer);
|
|
259
297
|
process.exit(0);
|
|
260
298
|
};
|
|
261
299
|
process.on("SIGINT", () => void shutdown());
|
|
262
300
|
process.on("SIGTERM", () => void shutdown());
|
|
263
301
|
|
|
264
|
-
startProxy(rotator, config.proxyPort, config.bindHost || "0.0.0.0");
|
|
302
|
+
server = startProxy(rotator, config.proxyPort, config.bindHost || "0.0.0.0");
|
|
265
303
|
}
|
|
266
304
|
|
|
267
305
|
// Direct execution
|
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
import { execSync } from "node:child_process";
|
|
2
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
3
|
+
import { resolve, dirname } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
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";
|
|
10
|
+
|
|
11
|
+
export interface AgentInstallOptions {
|
|
12
|
+
targets?: Array<SupportedAgent | "auto" | "all">;
|
|
13
|
+
host?: string;
|
|
14
|
+
user?: string;
|
|
15
|
+
port?: number;
|
|
16
|
+
sshKey?: string;
|
|
17
|
+
rotatorUrl?: string;
|
|
18
|
+
providerId?: string;
|
|
19
|
+
providerName?: string;
|
|
20
|
+
apiKey?: string;
|
|
21
|
+
dryRun?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Builds the composite shell script that detects and configures all requested agents.
|
|
26
|
+
*/
|
|
27
|
+
export function buildCompositeInstallerScript(
|
|
28
|
+
opencodePluginContent: string,
|
|
29
|
+
options: {
|
|
30
|
+
targets: Array<SupportedAgent | "auto" | "all">;
|
|
31
|
+
rotatorUrl: string;
|
|
32
|
+
providerId: string;
|
|
33
|
+
providerName: string;
|
|
34
|
+
apiKey?: string;
|
|
35
|
+
}
|
|
36
|
+
): string {
|
|
37
|
+
const pluginBase64 = Buffer.from(opencodePluginContent, "utf8").toString("base64");
|
|
38
|
+
const rotatorUrl = options.rotatorUrl.replace(/\/+$/, "");
|
|
39
|
+
const providerId = options.providerId || "tuxevil-rotator";
|
|
40
|
+
const providerName = options.providerName || "Tuxevil Rotator";
|
|
41
|
+
const apiKey = options.apiKey || "no-key";
|
|
42
|
+
const targets = options.targets && options.targets.length > 0 ? options.targets : ["auto"];
|
|
43
|
+
const shouldAuto = targets.includes("auto") || targets.includes("all");
|
|
44
|
+
|
|
45
|
+
return `#!/usr/bin/env bash
|
|
46
|
+
set -e
|
|
47
|
+
|
|
48
|
+
ROTATOR_URL="${rotatorUrl}"
|
|
49
|
+
PROVIDER_ID="${providerId}"
|
|
50
|
+
PROVIDER_NAME="${providerName}"
|
|
51
|
+
API_KEY="${apiKey}"
|
|
52
|
+
|
|
53
|
+
echo "=========================================================="
|
|
54
|
+
echo "==> Tuxevil Rotator Agent Installer"
|
|
55
|
+
echo "==> Rotator URL: $ROTATOR_URL"
|
|
56
|
+
echo "==> Provider ID: $PROVIDER_ID"
|
|
57
|
+
echo "=========================================================="
|
|
58
|
+
|
|
59
|
+
# Helper to check if agent should be installed
|
|
60
|
+
should_install() {
|
|
61
|
+
local agent="$1"
|
|
62
|
+
local check_dir="$2"
|
|
63
|
+
if [ "${targets.includes("all") ? "1" : "0"}" = "1" ]; then
|
|
64
|
+
return 0
|
|
65
|
+
fi
|
|
66
|
+
if [ "${shouldAuto ? "1" : "0"}" = "1" ]; then
|
|
67
|
+
if [ -d "$check_dir" ]; then
|
|
68
|
+
return 0
|
|
69
|
+
else
|
|
70
|
+
return 1
|
|
71
|
+
fi
|
|
72
|
+
fi
|
|
73
|
+
case ",${targets.join(",")}," in
|
|
74
|
+
*,$agent,*) return 0 ;;
|
|
75
|
+
*) return 1 ;;
|
|
76
|
+
esac
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
# -------------------------------------------------------------
|
|
80
|
+
# 1. OpenCode Configuration
|
|
81
|
+
# -------------------------------------------------------------
|
|
82
|
+
OPENCODE_DIR="$HOME/.config/opencode"
|
|
83
|
+
if should_install "opencode" "$OPENCODE_DIR"; then
|
|
84
|
+
echo ""
|
|
85
|
+
echo "==> [OpenCode] Configuring in $OPENCODE_DIR..."
|
|
86
|
+
mkdir -p "$OPENCODE_DIR/plugins"
|
|
87
|
+
echo "${pluginBase64}" | base64 -d > "$OPENCODE_DIR/plugins/opencode-discovery.js"
|
|
88
|
+
|
|
89
|
+
node -e '
|
|
90
|
+
const fs = require("fs");
|
|
91
|
+
const path = require("path");
|
|
92
|
+
|
|
93
|
+
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");
|
|
95
|
+
const providerID = process.argv[1];
|
|
96
|
+
const providerName = process.argv[2];
|
|
97
|
+
const baseURL = process.argv[3];
|
|
98
|
+
const apiKey = process.argv[4];
|
|
99
|
+
|
|
100
|
+
let config = {};
|
|
101
|
+
if (fs.existsSync(configFile)) {
|
|
102
|
+
try {
|
|
103
|
+
config = JSON.parse(fs.readFileSync(configFile, "utf8"));
|
|
104
|
+
} catch (e) {
|
|
105
|
+
console.warn("Warning: Backing up invalid opencode.json");
|
|
106
|
+
fs.copyFileSync(configFile, configFile + ".bak." + Date.now());
|
|
107
|
+
config = {};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
config.$schema = config.$schema || "https://opencode.ai/config.json";
|
|
112
|
+
config.plugin = Array.isArray(config.plugin) ? config.plugin : [];
|
|
113
|
+
|
|
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;
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
config.plugin.push([
|
|
122
|
+
pluginPath,
|
|
123
|
+
{ baseURL, providerID, providerName }
|
|
124
|
+
]);
|
|
125
|
+
|
|
126
|
+
config.provider = config.provider || {};
|
|
127
|
+
config.provider[providerID] = config.provider[providerID] || {
|
|
128
|
+
npm: "@ai-sdk/openai-compatible",
|
|
129
|
+
name: providerName,
|
|
130
|
+
options: { baseURL }
|
|
131
|
+
};
|
|
132
|
+
config.provider[providerID].npm = "@ai-sdk/openai-compatible";
|
|
133
|
+
config.provider[providerID].name = providerName;
|
|
134
|
+
config.provider[providerID].options = config.provider[providerID].options || {};
|
|
135
|
+
config.provider[providerID].options.baseURL = baseURL;
|
|
136
|
+
|
|
137
|
+
if (apiKey && apiKey !== "no-key") {
|
|
138
|
+
config.provider[providerID].options.apiKey = apiKey;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
fs.writeFileSync(configFile, JSON.stringify(config, null, 2) + "\\n", "utf8");
|
|
142
|
+
console.log("==> [OpenCode] Configured successfully.");
|
|
143
|
+
' "$PROVIDER_ID" "$PROVIDER_NAME" "$ROTATOR_URL" "$API_KEY"
|
|
144
|
+
else
|
|
145
|
+
echo "==> [OpenCode] Skipped (not selected or directory not found)."
|
|
146
|
+
fi
|
|
147
|
+
|
|
148
|
+
# -------------------------------------------------------------
|
|
149
|
+
# 2. Hermes Configuration
|
|
150
|
+
# -------------------------------------------------------------
|
|
151
|
+
HERMES_DIR="$HOME/.hermes"
|
|
152
|
+
if should_install "hermes" "$HERMES_DIR"; then
|
|
153
|
+
echo ""
|
|
154
|
+
echo "==> [Hermes] Configuring in $HERMES_DIR..."
|
|
155
|
+
mkdir -p "$HERMES_DIR"
|
|
156
|
+
|
|
157
|
+
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
|
+
|
|
165
|
+
try:
|
|
166
|
+
import yaml
|
|
167
|
+
has_yaml = True
|
|
168
|
+
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.")
|
|
207
|
+
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.")
|
|
225
|
+
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"
|
|
230
|
+
else
|
|
231
|
+
echo "==> [Hermes] Skipped (not selected or directory not found)."
|
|
232
|
+
fi
|
|
233
|
+
|
|
234
|
+
# -------------------------------------------------------------
|
|
235
|
+
# 3. Pi Agent Configuration
|
|
236
|
+
# -------------------------------------------------------------
|
|
237
|
+
PI_DIR="$HOME/.pi/agent"
|
|
238
|
+
if should_install "pi" "$PI_DIR"; then
|
|
239
|
+
echo ""
|
|
240
|
+
echo "==> [Pi Agent] Configuring in $PI_DIR..."
|
|
241
|
+
mkdir -p "$PI_DIR"
|
|
242
|
+
|
|
243
|
+
node -e '
|
|
244
|
+
const fs = require("fs");
|
|
245
|
+
const path = require("path");
|
|
246
|
+
const http = require("http");
|
|
247
|
+
const https = require("https");
|
|
248
|
+
|
|
249
|
+
const modelsFile = path.join(process.env.HOME, ".pi/agent/models.json");
|
|
250
|
+
const providerID = process.argv[1];
|
|
251
|
+
const baseURL = process.argv[2];
|
|
252
|
+
const apiKey = process.argv[3];
|
|
253
|
+
|
|
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
|
+
async function main() {
|
|
280
|
+
let modelsData = { providers: {} };
|
|
281
|
+
if (fs.existsSync(modelsFile)) {
|
|
282
|
+
try {
|
|
283
|
+
modelsData = JSON.parse(fs.readFileSync(modelsFile, "utf8"));
|
|
284
|
+
} catch (e) {
|
|
285
|
+
console.warn("Warning: Backing up corrupted models.json");
|
|
286
|
+
fs.copyFileSync(modelsFile, modelsFile + ".bak." + Date.now());
|
|
287
|
+
modelsData = { providers: {} };
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
modelsData.providers = modelsData.providers || {};
|
|
291
|
+
|
|
292
|
+
const rawModels = await fetchModels(baseURL);
|
|
293
|
+
let mappedModels = [];
|
|
294
|
+
|
|
295
|
+
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
|
+
}));
|
|
304
|
+
console.log("==> [Pi Agent] Discovered " + mappedModels.length + " live models from rotator.");
|
|
305
|
+
} else {
|
|
306
|
+
// Fallback baseline if rotator is not immediately reachable
|
|
307
|
+
mappedModels = [
|
|
308
|
+
{ id: "gemini-3.8-flash-high", name: "Gemini 3.8 Flash High", input: ["text", "image"], contextWindow: 1048576, maxTokens: 65536, reasoning: true },
|
|
309
|
+
{ id: "gemini-3-flash", name: "Gemini 3 Flash", input: ["text", "image"], contextWindow: 1048576, maxTokens: 65536, reasoning: true },
|
|
310
|
+
{ id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", input: ["text", "image"], contextWindow: 1000000, maxTokens: 64000 }
|
|
311
|
+
];
|
|
312
|
+
console.log("==> [Pi Agent] Rotator unreachable during install; populated standard baseline models.");
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
modelsData.providers[providerID] = {
|
|
316
|
+
baseUrl: baseURL,
|
|
317
|
+
api: "openai-completions",
|
|
318
|
+
apiKey: apiKey,
|
|
319
|
+
models: mappedModels
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
fs.writeFileSync(modelsFile, JSON.stringify(modelsData, null, 2) + "\\n", "utf8");
|
|
323
|
+
console.log("==> [Pi Agent] Configured successfully in " + modelsFile);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
main();
|
|
327
|
+
' "$PROVIDER_ID" "$ROTATOR_URL" "$API_KEY"
|
|
328
|
+
else
|
|
329
|
+
echo "==> [Pi Agent] Skipped (not selected or directory not found)."
|
|
330
|
+
fi
|
|
331
|
+
|
|
332
|
+
# -------------------------------------------------------------
|
|
333
|
+
# 4. Codex CLI Configuration
|
|
334
|
+
# -------------------------------------------------------------
|
|
335
|
+
CODEX_DIR="$HOME/.codex"
|
|
336
|
+
if should_install "codex" "$CODEX_DIR"; then
|
|
337
|
+
echo ""
|
|
338
|
+
echo "==> [Codex CLI] Configuring in $CODEX_DIR..."
|
|
339
|
+
mkdir -p "$CODEX_DIR"
|
|
340
|
+
|
|
341
|
+
python3 -c '
|
|
342
|
+
import os, sys, re
|
|
343
|
+
|
|
344
|
+
config_file = os.path.expanduser("~/.codex/config.toml")
|
|
345
|
+
provider_id = sys.argv[1]
|
|
346
|
+
provider_name = sys.argv[2]
|
|
347
|
+
rotator_url = sys.argv[3]
|
|
348
|
+
|
|
349
|
+
content = ""
|
|
350
|
+
if os.path.exists(config_file):
|
|
351
|
+
with open(config_file, "r", encoding="utf-8") as f:
|
|
352
|
+
content = f.read()
|
|
353
|
+
|
|
354
|
+
section_header = f"[model_providers.{provider_id}]"
|
|
355
|
+
block = f"""
|
|
356
|
+
[model_providers.{provider_id}]
|
|
357
|
+
name = "{provider_name}"
|
|
358
|
+
base_url = "{rotator_url}"
|
|
359
|
+
wire_api = "responses"
|
|
360
|
+
"""
|
|
361
|
+
|
|
362
|
+
if section_header in content:
|
|
363
|
+
pattern = rf"\\[model_providers\\.{re.escape(provider_id)}\\][^\\[]*"
|
|
364
|
+
content = re.sub(pattern, block.strip() + "\\n\\n", content, flags=re.DOTALL)
|
|
365
|
+
print(f"==> [Codex CLI] Updated existing {section_header} in config.toml.")
|
|
366
|
+
else:
|
|
367
|
+
content = content.rstrip() + "\\n" + block
|
|
368
|
+
print(f"==> [Codex CLI] Added {section_header} to config.toml.")
|
|
369
|
+
|
|
370
|
+
with open(config_file, "w", encoding="utf-8") as f:
|
|
371
|
+
f.write(content)
|
|
372
|
+
' "$PROVIDER_ID" "$PROVIDER_NAME" "$ROTATOR_URL"
|
|
373
|
+
else
|
|
374
|
+
echo "==> [Codex CLI] Skipped (not selected or directory not found)."
|
|
375
|
+
fi
|
|
376
|
+
|
|
377
|
+
echo ""
|
|
378
|
+
echo "==> All target agents processed successfully!"
|
|
379
|
+
`;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Installs configuration for one or more agents locally or over SSH.
|
|
384
|
+
*/
|
|
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}`);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const opencodePluginContent = readFileSync(OPENCODE_PLUGIN_SOURCE_PATH, "utf8");
|
|
391
|
+
const rotatorUrl = (
|
|
392
|
+
options.rotatorUrl ||
|
|
393
|
+
process.env.TUXEVIL_ROTATOR_BASE_URL ||
|
|
394
|
+
process.env.ROTATOR_URL ||
|
|
395
|
+
"http://127.0.0.1:51200/v1"
|
|
396
|
+
).replace(/\/+$/, "");
|
|
397
|
+
|
|
398
|
+
const providerId = options.providerId || "tuxevil-rotator";
|
|
399
|
+
const providerName = options.providerName || "Tuxevil Rotator";
|
|
400
|
+
const targets: Array<SupportedAgent | "auto" | "all"> = options.targets && options.targets.length > 0 ? options.targets : ["auto"];
|
|
401
|
+
|
|
402
|
+
const script = buildCompositeInstallerScript(opencodePluginContent, {
|
|
403
|
+
targets,
|
|
404
|
+
rotatorUrl,
|
|
405
|
+
providerId,
|
|
406
|
+
providerName,
|
|
407
|
+
apiKey: options.apiKey,
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
if (options.dryRun) {
|
|
411
|
+
console.log("=== Dry Run Mode: Composite Script that would be executed ===");
|
|
412
|
+
console.log(script);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// 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}...`);
|
|
419
|
+
execSync("bash -s", {
|
|
420
|
+
input: script,
|
|
421
|
+
stdio: ["pipe", "inherit", "inherit"],
|
|
422
|
+
});
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// Remote installation via SSH
|
|
427
|
+
const sshTarget = options.user ? `${options.user}@${options.host}` : options.host;
|
|
428
|
+
const sshArgs: string[] = [
|
|
429
|
+
"-o", "BatchMode=yes",
|
|
430
|
+
"-o", "ConnectTimeout=10",
|
|
431
|
+
"-o", "StrictHostKeyChecking=accept-new",
|
|
432
|
+
];
|
|
433
|
+
|
|
434
|
+
if (options.port) {
|
|
435
|
+
sshArgs.push("-p", String(options.port));
|
|
436
|
+
}
|
|
437
|
+
if (options.sshKey) {
|
|
438
|
+
sshArgs.push("-i", options.sshKey);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const sshCmd = `ssh ${sshArgs.join(" ")} ${sshTarget} "bash -s"`;
|
|
442
|
+
|
|
443
|
+
console.log(`==> Installing agent configuration remotely on ${sshTarget} (Rotator: ${rotatorUrl})...`);
|
|
444
|
+
try {
|
|
445
|
+
execSync(sshCmd, {
|
|
446
|
+
input: script,
|
|
447
|
+
stdio: ["pipe", "inherit", "inherit"],
|
|
448
|
+
});
|
|
449
|
+
} catch (err: unknown) {
|
|
450
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
451
|
+
throw new Error(`SSH installation failed on ${sshTarget}: ${errorMsg}`, { cause: err });
|
|
452
|
+
}
|
|
453
|
+
}
|