-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclovapi-desktop.js
More file actions
290 lines (263 loc) · 8.65 KB
/
Copy pathclovapi-desktop.js
File metadata and controls
290 lines (263 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
const { runClovapiArgsAsync, runClovapiLongAsync, cancelClovapiLongRun } = require("./clovapi-exec");
const { spawn } = require("node:child_process");
const AUTH_PROVIDERS = new Set(["claude-code", "codex"]);
const AUTH_LOGIN_TIMEOUT = 3 * 60 * 1000;
// Must match subscriptionauth.AuthorizeURLLinePrefix in the Go core.
const AUTHORIZE_URL_PREFIX = "clovapi-authorize-url: ";
let outputHandler = () => {};
function setOutputHandler(handler) {
outputHandler = typeof handler === "function" ? handler : () => {};
}
function parseCliJSON(result) {
const text = String(result.stdout || "").trim();
if (!text) {
return { ok: false, error: result.stderr || "empty response from clovapi" };
}
try {
return JSON.parse(text);
} catch {
return { ok: false, error: "invalid JSON from clovapi" };
}
}
async function runAuthAsync(args, options = {}) {
const result = await runClovapiArgsAsync(["auth", ...args, "--json"], {
timeout: options.timeout ?? 30000,
input: options.input,
});
if (result.error && result.error.code === "ETIMEDOUT") {
return { ok: false, error: "clovapi auth timed out" };
}
if (!result.ok) {
const message = String(result.stderr || result.stdout || "clovapi auth failed").trim();
return { ok: false, error: message || "clovapi auth failed" };
}
return parseCliJSON(result);
}
async function runProfilesAsync(args, options = {}) {
const result = await runClovapiArgsAsync(["profiles", ...args, "--json"], {
timeout: options.timeout ?? 30000,
input: options.input,
});
if (result.error && result.error.code === "ETIMEDOUT") {
return { ok: false, error: "clovapi profiles timed out" };
}
if (!result.ok) {
const message = String(result.stderr || result.stdout || "clovapi profiles failed").trim();
return { ok: false, error: message || "clovapi profiles failed" };
}
return parseCliJSON(result);
}
async function runDesktopAsync(args, options = {}) {
const result = await runClovapiArgsAsync(["desktop", ...args], {
timeout: options.timeout ?? 30000,
input: options.input,
});
if (result.error && result.error.code === "ETIMEDOUT") {
return { ok: false, error: "clovapi desktop timed out" };
}
if (!result.ok) {
const message = String(result.stderr || result.stdout || "clovapi desktop failed").trim();
return { ok: false, error: message || "clovapi desktop failed" };
}
return parseCliJSON(result);
}
function loadProfiles() {
return runProfilesAsync(["load"]);
}
function loadProxyConfig() {
return runDesktopAsync(["proxy", "load"], { timeout: 10000 });
}
function saveProxyConfig(payload) {
return runDesktopAsync(["proxy", "save"], {
input: JSON.stringify(payload || {}),
timeout: 10000,
});
}
function saveProfiles(payload) {
return runProfilesAsync(["save"], {
input: JSON.stringify(payload || {}),
timeout: 15000,
});
}
function listVendorModels(vendorName, credentialRef = "") {
const args = ["list-models", "--vendor", String(vendorName || "")];
if (String(credentialRef || "").trim()) args.push("--credential-ref", String(credentialRef).trim());
return runProfilesAsync(args, {
timeout: 45000,
});
}
function listModels() {
return runProfilesAsync(["models"], { timeout: 15000 });
}
async function testBinding(payload) {
const provider = String(payload?.provider || payload?.provider_id || "").trim();
const model = String(payload?.model || payload?.model_id || "").trim();
const args = ["test"];
args.push("--provider", provider, "--model", model);
const port = Number(payload?.proxy?.port);
if (Number.isFinite(port) && port > 0) {
args.push("--port", String(port));
}
return runProfilesAsync(args, { timeout: 130000 });
}
function modelAdapters() {
return runProfilesAsync(["catalog"], { timeout: 10000 });
}
function vendorCatalog() {
return modelAdapters();
}
function whichCommand(command) {
const name = String(command || "").trim();
if (!name) return Promise.resolve({ ok: false, exists: false, path: "" });
const tool = process.platform === "win32" ? "where.exe" : "which";
return new Promise((resolve) => {
const child = spawn(tool, [name], {
windowsHide: true,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
const timer = setTimeout(() => {
child.kill();
resolve({ ok: false, exists: false, path: "", error: "which timed out" });
}, 10000);
child.stdout.on("data", (chunk) => {
stdout += String(chunk || "");
});
child.stderr.on("data", (chunk) => {
stderr += String(chunk || "");
});
child.on("error", (error) => {
clearTimeout(timer);
resolve({ ok: false, exists: false, path: "", error: error.message });
});
child.on("close", (code) => {
clearTimeout(timer);
const first = stdout.split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "";
resolve({
ok: code === 0,
exists: code === 0 && Boolean(first),
path: first,
error: code === 0 ? "" : String(stderr || stdout || "").trim(),
});
});
});
}
function mergeNoProxy(value) {
const bypass = ["127.0.0.1", "localhost", "::1"];
const parts = String(value || "")
.split(",")
.map((part) => part.trim())
.filter(Boolean);
for (const host of bypass) {
if (!parts.some((part) => part.toLowerCase() === host.toLowerCase())) parts.push(host);
}
return parts.join(",");
}
function authLoginEnv() {
const env = { ...process.env };
env.NO_PROXY = mergeNoProxy(env.NO_PROXY);
env.no_proxy = mergeNoProxy(env.no_proxy);
return env;
}
function authStatus() {
return runAuthAsync(["status"]);
}
function openAuthorizeURL(rawURL) {
const url = String(rawURL || "").trim();
if (!url) return;
try {
const { shell } = require("electron");
Promise.resolve(shell.openExternal(url)).catch(() => {});
} catch {
// electron shell unavailable (e.g. tests) — the URL is still streamed to the UI.
}
}
// authorizeURLOpener watches streamed stderr for the authorize URL line emitted
// by the core and opens it in the default browser. Opening the browser is the
// shell's responsibility, not the CLI's.
function authorizeURLOpener() {
let buffer = "";
let opened = false;
return (kind, chunk) => {
outputHandler(kind, chunk);
if (opened || kind !== "stderr") return;
buffer += String(chunk || "");
let idx;
while ((idx = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, idx);
buffer = buffer.slice(idx + 1);
const at = line.indexOf(AUTHORIZE_URL_PREFIX);
if (at < 0) continue;
const url = line.slice(at + AUTHORIZE_URL_PREFIX.length).trim();
if (url) {
opened = true;
openAuthorizeURL(url);
return;
}
}
};
}
async function authLogin(payload) {
const providerId = String(typeof payload === "string" ? payload : payload?.provider || "").trim();
const credentialRef = String(typeof payload === "string" ? "" : payload?.credentialRef || "").trim();
if (!AUTH_PROVIDERS.has(providerId)) {
return { ok: false, error: `未知订阅类型: ${providerId}` };
}
const args = ["auth", "login", "--provider", providerId, "--json"];
if (credentialRef) args.push("--credential-ref", credentialRef);
const result = await runClovapiLongAsync(args, {
cancelKey: providerId,
onOutput: authorizeURLOpener(),
timeout: AUTH_LOGIN_TIMEOUT,
env: authLoginEnv(),
});
if (result.cancelled) {
return { ok: false, cancelled: true, error: "已取消登录" };
}
if (!result.ok) {
const message = String(result.stderr || result.stdout || "登录失败").trim();
return { ok: false, error: message || "登录失败" };
}
return parseCliJSON(result);
}
function cancelAuthLogin(provider) {
const providerId = String(provider || "").trim();
const result = cancelClovapiLongRun(providerId);
if (!result.ok) {
return { ok: false, error: "该订阅未在登录中" };
}
return { ok: true };
}
function authLogout(provider) {
return runAuthAsync(["logout", "--provider", String(provider || "")], { timeout: 15000 });
}
function queryVendorUsage(vendorName, credentialRef = "") {
const args = ["usage", "--vendor", String(vendorName || "")];
if (String(credentialRef || "").trim()) args.push("--credential-ref", String(credentialRef).trim());
return runProfilesAsync(args, {
timeout: 20000,
});
}
module.exports = {
setOutputHandler,
runDesktopAsync,
runProfilesAsync,
loadProfiles,
loadProxyConfig,
saveProxyConfig,
saveProfiles,
listVendorModels,
listModels,
testBinding,
modelAdapters,
vendorCatalog,
whichCommand,
authStatus,
authLogin,
cancelAuthLogin,
authLogout,
queryVendorUsage,
mergeNoProxy,
authLoginEnv,
};