workbuddy-cli 0.0.0-stage → 1.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 +21 -0
- package/README.md +200 -2
- package/bin/workbuddy.mjs +1152 -0
- package/package.json +38 -4
|
@@ -0,0 +1,1152 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import net from 'node:net';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
const PROTOCOL_VERSION = 1;
|
|
10
|
+
const DEFAULT_ENDPOINT = 'https://www.workbuddy.cn';
|
|
11
|
+
const AUTH_PREFIX = '/v2/plugin';
|
|
12
|
+
const AUTH_PLATFORM = 'workbuddy';
|
|
13
|
+
const AUTH_DIR = path.join(os.homedir(), '.workbuddy-cli');
|
|
14
|
+
const AUTH_FILE = path.join(AUTH_DIR, 'auth.json');
|
|
15
|
+
const LOGIN_POLL_INTERVAL_MS = 1500;
|
|
16
|
+
const LOGIN_TIMEOUT_MS = 300000;
|
|
17
|
+
const LOGIN_TOKEN_PENDING_CODE = 11217;
|
|
18
|
+
const LOGIN_ACCOUNT_PENDING_CODE = 12151;
|
|
19
|
+
|
|
20
|
+
const MODEL_ALIASES = {
|
|
21
|
+
// 模式
|
|
22
|
+
'auto': 'auto',
|
|
23
|
+
'fast': 'fast-model',
|
|
24
|
+
'balanced': 'balanced-model',
|
|
25
|
+
'deep': 'deep-model',
|
|
26
|
+
|
|
27
|
+
// 腾讯混元 (Hunyuan)
|
|
28
|
+
'hy4': 'hy4',
|
|
29
|
+
'hy4free': 'hy4free',
|
|
30
|
+
'hy4std': 'hy4std',
|
|
31
|
+
'hy4-preview': 'hy4-preview',
|
|
32
|
+
'hy3': 'hy3',
|
|
33
|
+
'hy3-free': 'hy3',
|
|
34
|
+
'hy3-std': 'hy3-x',
|
|
35
|
+
'hy3-preview': 'hy3-preview',
|
|
36
|
+
'hunyuan': 'hy4',
|
|
37
|
+
'hunyuan-chat': 'hunyuan-chat',
|
|
38
|
+
|
|
39
|
+
// DeepSeek 系列
|
|
40
|
+
'ds': 'deepseek-v3-2-volc',
|
|
41
|
+
'deepseek': 'deepseek-v3-2-volc',
|
|
42
|
+
'deepseek-v3': 'deepseek-v3-2-volc',
|
|
43
|
+
'deepseek-v4': 'deepseek-v4.1-flash',
|
|
44
|
+
'deepseek-v4.1': 'deepseek-v4.1-flash',
|
|
45
|
+
'deepseek-v4-flash': 'deepseek-v4-flash',
|
|
46
|
+
'deepseek-v4-pro': 'deepseek-v4-pro',
|
|
47
|
+
|
|
48
|
+
// 智谱 GLM 系列
|
|
49
|
+
'glm': 'glm-5.3',
|
|
50
|
+
'glm-5.3': 'glm-5.3',
|
|
51
|
+
'glm-flash': 'glm-5.3-flash',
|
|
52
|
+
'glm-5.3-flash': 'glm-5.3-flash',
|
|
53
|
+
'glm-5.3-flashx': 'glm-5.3-flashx',
|
|
54
|
+
'glm-5.2': 'glm-5.2',
|
|
55
|
+
'glm-5v': 'glm-5v-turbo',
|
|
56
|
+
'glm-5v-turbo': 'glm-5v-turbo',
|
|
57
|
+
|
|
58
|
+
// 月之暗面 Kimi 系列
|
|
59
|
+
'kimi': 'kimi-k2.5',
|
|
60
|
+
'kimi-k2.5': 'kimi-k2.5',
|
|
61
|
+
'kimi-k2.6': 'kimi-k2.6',
|
|
62
|
+
'kimi-k2.7': 'kimi-k2.7',
|
|
63
|
+
'kimi-k2.8': 'kimi-k2.8-preview',
|
|
64
|
+
'kimi-k3': 'kimi-k3-1',
|
|
65
|
+
'kimi-k3-1': 'kimi-k3-1',
|
|
66
|
+
'kimi-k3-2': 'kimi-k3-2',
|
|
67
|
+
'kimi-pro': 'kimi-k3.1-pro',
|
|
68
|
+
'kimi-k3.1-pro': 'kimi-k3.1-pro',
|
|
69
|
+
|
|
70
|
+
// MiniMax 系列
|
|
71
|
+
'minimax': 'minimax-m2.7',
|
|
72
|
+
'minimax-m2.7': 'minimax-m2.7',
|
|
73
|
+
'minimax-m3': 'minimax-m3-pay',
|
|
74
|
+
'minimax-flash': 'minimax-m3.1-flash',
|
|
75
|
+
'minimax-m3.1-flash': 'minimax-m3.1-flash',
|
|
76
|
+
|
|
77
|
+
// 小米 / 阶跃星辰 / 其他
|
|
78
|
+
'mimo': 'mimo-v2.6-pro',
|
|
79
|
+
'mimo-v2.6-pro': 'mimo-v2.6-pro',
|
|
80
|
+
'step': 'step-5-preview',
|
|
81
|
+
'step-5-preview': 'step-5-preview',
|
|
82
|
+
'space-bunny': 'space-bunny',
|
|
83
|
+
'wb-lite': 'wb-lite'
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
function showModels() {
|
|
87
|
+
console.log(`WorkBuddy 完整模型清单(经实测 200 OK 确认可用):
|
|
88
|
+
|
|
89
|
+
1. 智能调度模式:
|
|
90
|
+
auto 自动调度
|
|
91
|
+
fast-model (简写: fast) 快速响应
|
|
92
|
+
balanced-model (简写: balanced) 均衡模式
|
|
93
|
+
deep-model (简写: deep) 极致推理/深度模式
|
|
94
|
+
|
|
95
|
+
2. 腾讯混元 (Hunyuan):
|
|
96
|
+
hy4 (或 hy4free) 混元 4.0 [免费] (客户端默认)
|
|
97
|
+
hy4std 混元 4.0 标准版 [付费包额度]
|
|
98
|
+
hy4-preview 混元 4.0 尝鲜内测版
|
|
99
|
+
hy4-preview-ctrl 混元 4.0 对照组
|
|
100
|
+
hy4-preview-exp 混元 4.0 实验组
|
|
101
|
+
hy4preview-exp1 / exp2 混元 4.0 实验组 1/2
|
|
102
|
+
hy3 (或 hy3-free) 混元 3.0 [免费]
|
|
103
|
+
hy3-x (或 hy3-std) 混元 3.0 标准版 [付费包额度]
|
|
104
|
+
hy3-b / hy3-c / hy3-preview 混元 3.0 衍生版本
|
|
105
|
+
hunyuan-chat 混元 Turbos
|
|
106
|
+
|
|
107
|
+
3. DeepSeek 系列:
|
|
108
|
+
deepseek-v3-2-volc (简写: deepseek, ds) DeepSeek-V3.2 (火山/腾讯聚合,默认模型)
|
|
109
|
+
deepseek-v4.1-flash (简写: deepseek-v4) DeepSeek-V4.1-Flash (极速旗舰)
|
|
110
|
+
deepseek-v4-flash DeepSeek-V4-Flash
|
|
111
|
+
deepseek-v4-pro DeepSeek-V4-Pro (高阶专业版)
|
|
112
|
+
|
|
113
|
+
4. 智谱 GLM 系列:
|
|
114
|
+
glm-5.3 (简写: glm) GLM-5.3 最新旗舰
|
|
115
|
+
glm-5.3-flash (简写: glm-flash) GLM-5.3-Flash
|
|
116
|
+
glm-5.3-flashx GLM-5.3-FlashX
|
|
117
|
+
glm-5.2 GLM-5.2
|
|
118
|
+
glm-5v-turbo (简写: glm-5v) GLM-5v-Turbo 视觉多模态
|
|
119
|
+
|
|
120
|
+
5. 月之暗面 Kimi 系列:
|
|
121
|
+
kimi-k3.1-pro (简写: kimi-pro) Kimi-K3.1-Pro 最新旗舰
|
|
122
|
+
kimi-k3-1 / kimi-k3-2 Kimi-K3 / K3-v2
|
|
123
|
+
kimi-k2.8-preview Kimi-K2.8-Preview
|
|
124
|
+
kimi-k2.7 Kimi-K2.7-Code 代码专精
|
|
125
|
+
kimi-k2.6 Kimi-K2.6
|
|
126
|
+
kimi-k2.5 (简写: kimi) Kimi-K2.5
|
|
127
|
+
|
|
128
|
+
6. MiniMax 系列:
|
|
129
|
+
minimax-m3.1-flash (简写: minimax-flash) MiniMax-M3.1-Flash 极速版
|
|
130
|
+
minimax-m3-pay (简写: minimax-m3) MiniMax-M3
|
|
131
|
+
minimax-m2.7 (简写: minimax) MiniMax-M2.7
|
|
132
|
+
|
|
133
|
+
7. 其他合作厂商与特色模型:
|
|
134
|
+
mimo-v2.6-pro (简写: mimo) 小米 Xiaomi MiMo-V2.6-Pro
|
|
135
|
+
step-5-preview (简写: step) 阶跃星辰 Step-5-Preview
|
|
136
|
+
space-bunny Space-Bunny
|
|
137
|
+
wb-lite WorkBuddy Lite
|
|
138
|
+
|
|
139
|
+
8. 内置代码辅助模型 (直接可调):
|
|
140
|
+
codewise-rewrite 代码重构专精
|
|
141
|
+
codewise-jump 符号定义跳转辅助
|
|
142
|
+
codewise-nes-a4-027-aide IDE 代码补全辅助
|
|
143
|
+
|
|
144
|
+
注:
|
|
145
|
+
- 腾讯内网专属模型(如 GPT-5 / GPT-6 / Claude-5 / Gemini-3 等海外模型)需处于腾讯内部 IOA 办公网环境方可访问,非 IOA 环境会返回 400 'is only available on IOA'。
|
|
146
|
+
- 生图模型 (hunyuan-image-v3.0) 与生视频模型 (kling-video-v3, minimax-video-h3) 为多模态生成专用接口,不走普通文本流式对话。
|
|
147
|
+
`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function showHelp() {
|
|
151
|
+
console.log(`Usage: workbuddy [command] [options] [prompt]
|
|
152
|
+
|
|
153
|
+
Interact with WorkBuddy directly (after login) or via local desktop WBIPC.
|
|
154
|
+
|
|
155
|
+
Commands:
|
|
156
|
+
login Log in via browser (no desktop app needed afterwards)
|
|
157
|
+
logout Revoke session and remove local CLI credentials
|
|
158
|
+
status, whoami Show current CLI auth and desktop WBIPC status
|
|
159
|
+
models Scan available models from server (falls back to static list)
|
|
160
|
+
|
|
161
|
+
Arguments:
|
|
162
|
+
prompt Your prompt / question
|
|
163
|
+
|
|
164
|
+
Options:
|
|
165
|
+
-p, --print Print response and exit (default behavior)
|
|
166
|
+
-m, --model <model> Model name or alias (e.g. hy4, deepseek, glm, default: deepseek-v3-2-volc)
|
|
167
|
+
-l, --models Scan/list available models and aliases
|
|
168
|
+
--all Include specialized/image models when listing models
|
|
169
|
+
--static Show built-in static model list without querying server
|
|
170
|
+
--json Output response as JSON
|
|
171
|
+
-s, --system <prompt> System prompt
|
|
172
|
+
--no-browser Print login URL instead of opening browser automatically
|
|
173
|
+
-h, --help Show this help message
|
|
174
|
+
|
|
175
|
+
Examples:
|
|
176
|
+
workbuddy login
|
|
177
|
+
workbuddy models
|
|
178
|
+
workbuddy "用Python写一个快速排序"
|
|
179
|
+
workbuddy -m hy4 "帮我写一封商务邮件"
|
|
180
|
+
cat document.txt | workbuddy -p "总结主要内容"
|
|
181
|
+
workbuddy --model glm "写一首五言绝句"
|
|
182
|
+
workbuddy logout
|
|
183
|
+
`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function parseArgs(args) {
|
|
187
|
+
let command = 'chat';
|
|
188
|
+
let prompt = '';
|
|
189
|
+
let model = 'deepseek-v3-2-volc';
|
|
190
|
+
let asJson = false;
|
|
191
|
+
let systemPrompt = '';
|
|
192
|
+
let noBrowser = false;
|
|
193
|
+
let includeAllModels = false;
|
|
194
|
+
let staticModels = false;
|
|
195
|
+
|
|
196
|
+
const first = args[0];
|
|
197
|
+
if (first === 'login' || first === '--login') {
|
|
198
|
+
command = 'login';
|
|
199
|
+
args = args.slice(1);
|
|
200
|
+
} else if (first === 'logout' || first === '--logout') {
|
|
201
|
+
command = 'logout';
|
|
202
|
+
args = args.slice(1);
|
|
203
|
+
} else if (first === 'status' || first === 'whoami' || first === '--status') {
|
|
204
|
+
command = 'status';
|
|
205
|
+
args = args.slice(1);
|
|
206
|
+
} else if (first === 'models') {
|
|
207
|
+
command = 'models';
|
|
208
|
+
args = args.slice(1);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
for (let i = 0; i < args.length; i++) {
|
|
212
|
+
const arg = args[i];
|
|
213
|
+
if (arg === '-h' || arg === '--help') {
|
|
214
|
+
showHelp();
|
|
215
|
+
process.exit(0);
|
|
216
|
+
} else if (arg === '-l' || arg === '--models') {
|
|
217
|
+
command = 'models';
|
|
218
|
+
} else if (arg === '-p' || arg === '--print') {
|
|
219
|
+
// default
|
|
220
|
+
} else if (arg === '--json') {
|
|
221
|
+
asJson = true;
|
|
222
|
+
} else if (arg === '--no-browser') {
|
|
223
|
+
noBrowser = true;
|
|
224
|
+
} else if (arg === '--all') {
|
|
225
|
+
includeAllModels = true;
|
|
226
|
+
} else if (arg === '--static') {
|
|
227
|
+
staticModels = true;
|
|
228
|
+
} else if (arg === '-m' || arg === '--model') {
|
|
229
|
+
model = args[++i];
|
|
230
|
+
} else if (arg.startsWith('--model=')) {
|
|
231
|
+
model = arg.slice(8);
|
|
232
|
+
} else if (arg === '-s' || arg === '--system') {
|
|
233
|
+
systemPrompt = args[++i];
|
|
234
|
+
} else if (arg.startsWith('--system=')) {
|
|
235
|
+
systemPrompt = arg.slice(9);
|
|
236
|
+
} else if (!arg.startsWith('-')) {
|
|
237
|
+
prompt = prompt ? `${prompt} ${arg}` : arg;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Resolve alias
|
|
242
|
+
if (model && MODEL_ALIASES[model.toLowerCase()]) {
|
|
243
|
+
model = MODEL_ALIASES[model.toLowerCase()];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return { command, prompt, model, asJson, systemPrompt, noBrowser, includeAllModels, staticModels };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function encodeTranscript(role, t) {
|
|
250
|
+
const domain = role === 'server' ? 'wbipc-s' : 'wbipc-c';
|
|
251
|
+
const parts = [domain, String(t.protocol), t.endpoint, t.clientNonce, t.serverNonce];
|
|
252
|
+
const chunks = [];
|
|
253
|
+
for (const part of parts) {
|
|
254
|
+
const buf = Buffer.from(part, 'utf8');
|
|
255
|
+
const len = Buffer.alloc(4);
|
|
256
|
+
len.writeUInt32BE(buf.length, 0);
|
|
257
|
+
chunks.push(len, buf);
|
|
258
|
+
}
|
|
259
|
+
return Buffer.concat(chunks);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function computeProof(ticket, role, transcript) {
|
|
263
|
+
return crypto.createHmac('sha256', Buffer.from(ticket, 'utf8'))
|
|
264
|
+
.update(encodeTranscript(role, transcript))
|
|
265
|
+
.digest('base64url');
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function ticketIdOf(ticket) {
|
|
269
|
+
return crypto.createHash('sha256').update(ticket, 'utf8').digest('hex').slice(0, 16);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function sleep(ms) {
|
|
273
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function readCliSession() {
|
|
277
|
+
if (!fs.existsSync(AUTH_FILE)) return null;
|
|
278
|
+
try {
|
|
279
|
+
return JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8'));
|
|
280
|
+
} catch {
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function writeCliSession(session) {
|
|
286
|
+
fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });
|
|
287
|
+
fs.writeFileSync(AUTH_FILE, JSON.stringify(session, null, 2) + '\n', { mode: 0o600 });
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function removeCliSession() {
|
|
291
|
+
if (fs.existsSync(AUTH_FILE)) {
|
|
292
|
+
fs.unlinkSync(AUTH_FILE);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function normalizeToken(raw, fallbackDomain = 'www.workbuddy.cn') {
|
|
297
|
+
const now = Date.now();
|
|
298
|
+
const expiresAt = raw.expiresAt || (raw.expiresIn ? now + raw.expiresIn * 1000 : undefined);
|
|
299
|
+
const refreshExpiresAt = raw.refreshExpiresAt || (raw.refreshExpiresIn ? now + raw.refreshExpiresIn * 1000 : undefined);
|
|
300
|
+
return {
|
|
301
|
+
accessToken: raw.accessToken,
|
|
302
|
+
refreshToken: raw.refreshToken,
|
|
303
|
+
tokenType: raw.tokenType,
|
|
304
|
+
domain: raw.domain || fallbackDomain,
|
|
305
|
+
expiresAt,
|
|
306
|
+
refreshExpiresAt,
|
|
307
|
+
lastRefreshTime: now
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function buildDomainHeader(endpoint, auth) {
|
|
312
|
+
try {
|
|
313
|
+
return auth?.domain || new URL(endpoint).host;
|
|
314
|
+
} catch {
|
|
315
|
+
return 'www.workbuddy.cn';
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function buildEnterpriseHeaders(endpoint, auth, account) {
|
|
320
|
+
const headers = {
|
|
321
|
+
'X-Domain': buildDomainHeader(endpoint, auth)
|
|
322
|
+
};
|
|
323
|
+
const enterpriseId = account?.enterpriseId;
|
|
324
|
+
if (enterpriseId) {
|
|
325
|
+
headers['X-Enterprise-Id'] = enterpriseId;
|
|
326
|
+
headers['X-Tenant-Id'] = enterpriseId;
|
|
327
|
+
}
|
|
328
|
+
return headers;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function openExternalUrl(url) {
|
|
332
|
+
return new Promise(resolve => {
|
|
333
|
+
const platform = process.platform;
|
|
334
|
+
let cmd;
|
|
335
|
+
let args;
|
|
336
|
+
if (platform === 'darwin') {
|
|
337
|
+
cmd = 'open';
|
|
338
|
+
args = [url];
|
|
339
|
+
} else if (platform === 'win32') {
|
|
340
|
+
cmd = 'cmd';
|
|
341
|
+
args = ['/c', 'start', '', url];
|
|
342
|
+
} else {
|
|
343
|
+
cmd = 'xdg-open';
|
|
344
|
+
args = [url];
|
|
345
|
+
}
|
|
346
|
+
try {
|
|
347
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
348
|
+
child.on('error', () => resolve(false));
|
|
349
|
+
child.unref();
|
|
350
|
+
resolve(true);
|
|
351
|
+
} catch {
|
|
352
|
+
resolve(false);
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function fetchJson(url, options = {}) {
|
|
358
|
+
const controller = new AbortController();
|
|
359
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 15000);
|
|
360
|
+
try {
|
|
361
|
+
const res = await fetch(url, {
|
|
362
|
+
...options,
|
|
363
|
+
signal: controller.signal
|
|
364
|
+
});
|
|
365
|
+
const text = await res.text();
|
|
366
|
+
let json = null;
|
|
367
|
+
try {
|
|
368
|
+
json = JSON.parse(text);
|
|
369
|
+
} catch {}
|
|
370
|
+
return { status: res.status, ok: res.ok, json, text };
|
|
371
|
+
} finally {
|
|
372
|
+
clearTimeout(timer);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async function loginWorkBuddy(options = {}) {
|
|
377
|
+
const endpoint = DEFAULT_ENDPOINT;
|
|
378
|
+
const noAuthHeaders = {
|
|
379
|
+
'Content-Type': 'application/json',
|
|
380
|
+
'X-Domain': buildDomainHeader(endpoint),
|
|
381
|
+
'X-No-Authorization': 'true',
|
|
382
|
+
'X-No-User-Id': 'true',
|
|
383
|
+
'X-No-Enterprise-Id': 'true',
|
|
384
|
+
'X-No-Department-Info': 'true'
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const stateRes = await fetchJson(`${endpoint}${AUTH_PREFIX}/auth/state?platform=${AUTH_PLATFORM}`, {
|
|
388
|
+
method: 'POST',
|
|
389
|
+
headers: noAuthHeaders,
|
|
390
|
+
body: '{}'
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
if (!stateRes.ok || !stateRes.json?.data?.state || !stateRes.json?.data?.authUrl) {
|
|
394
|
+
throw new Error(`获取登录链接失败 (HTTP ${stateRes.status}): ${stateRes.json?.msg || stateRes.text}`);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const { state, authUrl } = stateRes.json.data;
|
|
398
|
+
console.error(`请在浏览器中完成 WorkBuddy 登录:\n${authUrl}\n`);
|
|
399
|
+
if (!options.noBrowser) {
|
|
400
|
+
const opened = await openExternalUrl(authUrl);
|
|
401
|
+
if (!opened) {
|
|
402
|
+
console.error('未能自动打开浏览器,请手动复制上方链接到浏览器打开。');
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
console.error('等待登录完成...');
|
|
406
|
+
|
|
407
|
+
const deadline = Date.now() + LOGIN_TIMEOUT_MS;
|
|
408
|
+
let tokenData = null;
|
|
409
|
+
|
|
410
|
+
while (Date.now() < deadline) {
|
|
411
|
+
await sleep(LOGIN_POLL_INTERVAL_MS);
|
|
412
|
+
const tokenRes = await fetchJson(
|
|
413
|
+
`${endpoint}${AUTH_PREFIX}/auth/token?state=${encodeURIComponent(state)}`,
|
|
414
|
+
{ headers: noAuthHeaders }
|
|
415
|
+
);
|
|
416
|
+
const body = tokenRes.json;
|
|
417
|
+
if (body?.data?.accessToken) {
|
|
418
|
+
tokenData = normalizeToken(body.data, buildDomainHeader(endpoint));
|
|
419
|
+
break;
|
|
420
|
+
}
|
|
421
|
+
if (body?.code === LOGIN_TOKEN_PENDING_CODE) {
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
throw new Error(`登录轮询失败 (HTTP ${tokenRes.status}): ${body?.msg || tokenRes.text}`);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
if (!tokenData) {
|
|
428
|
+
throw new Error('登录超时(5 分钟内未完成登录)');
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
let account = null;
|
|
432
|
+
const authHeaders = {
|
|
433
|
+
...buildEnterpriseHeaders(endpoint, tokenData),
|
|
434
|
+
'Authorization': `Bearer ${tokenData.accessToken}`,
|
|
435
|
+
'X-No-User-Id': 'true',
|
|
436
|
+
'X-No-Enterprise-Id': 'true',
|
|
437
|
+
'X-No-Department-Info': 'true'
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
const accountDeadline = Math.min(deadline, Date.now() + 30000);
|
|
441
|
+
while (Date.now() < accountDeadline) {
|
|
442
|
+
const accRes = await fetchJson(
|
|
443
|
+
`${endpoint}${AUTH_PREFIX}/login/account?state=${encodeURIComponent(state)}`,
|
|
444
|
+
{ headers: authHeaders }
|
|
445
|
+
);
|
|
446
|
+
if (accRes.json?.data) {
|
|
447
|
+
account = accRes.json.data;
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
450
|
+
if (accRes.json?.code === LOGIN_ACCOUNT_PENDING_CODE) {
|
|
451
|
+
await sleep(1000);
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
if (!account) {
|
|
458
|
+
const listRes = await fetchJson(`${endpoint}${AUTH_PREFIX}/accounts`, {
|
|
459
|
+
headers: {
|
|
460
|
+
...buildEnterpriseHeaders(endpoint, tokenData),
|
|
461
|
+
'Authorization': `Bearer ${tokenData.accessToken}`
|
|
462
|
+
}
|
|
463
|
+
});
|
|
464
|
+
const accounts = listRes.json?.data?.accounts;
|
|
465
|
+
if (Array.isArray(accounts) && accounts.length > 0) {
|
|
466
|
+
account = accounts.find(a => a.lastLogin) || accounts[0];
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const session = {
|
|
471
|
+
endpoint,
|
|
472
|
+
auth: tokenData,
|
|
473
|
+
account: account ? {
|
|
474
|
+
uid: account.uid,
|
|
475
|
+
nickname: account.nickname || account.name || account.username,
|
|
476
|
+
enterpriseId: account.enterpriseId,
|
|
477
|
+
type: account.type
|
|
478
|
+
} : null,
|
|
479
|
+
updatedAt: Date.now()
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
writeCliSession(session);
|
|
483
|
+
return session;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
async function refreshCliSession(session) {
|
|
487
|
+
const endpoint = session.endpoint || DEFAULT_ENDPOINT;
|
|
488
|
+
const refreshToken = session.auth?.refreshToken;
|
|
489
|
+
if (!refreshToken) {
|
|
490
|
+
throw new Error('当前凭据缺少 refreshToken,请重新运行 "workbuddy login"');
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const res = await fetchJson(`${endpoint}${AUTH_PREFIX}/auth/token/refresh`, {
|
|
494
|
+
method: 'POST',
|
|
495
|
+
headers: {
|
|
496
|
+
...buildEnterpriseHeaders(endpoint, session.auth, session.account),
|
|
497
|
+
'X-Refresh-Token': refreshToken,
|
|
498
|
+
'X-Auth-Refresh-Source': 'plugin'
|
|
499
|
+
},
|
|
500
|
+
body: '{}'
|
|
501
|
+
});
|
|
502
|
+
|
|
503
|
+
if (!res.ok || !res.json?.data?.accessToken) {
|
|
504
|
+
throw new Error(`刷新登录态失败 (HTTP ${res.status}): ${res.json?.msg || res.text},请重新运行 "workbuddy login"`);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
const updated = {
|
|
508
|
+
...session,
|
|
509
|
+
auth: normalizeToken(res.json.data, session.auth?.domain || buildDomainHeader(endpoint)),
|
|
510
|
+
updatedAt: Date.now()
|
|
511
|
+
};
|
|
512
|
+
writeCliSession(updated);
|
|
513
|
+
return updated;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async function logoutWorkBuddy() {
|
|
517
|
+
const session = readCliSession();
|
|
518
|
+
if (!session) {
|
|
519
|
+
return { hadSession: false, serverRevoked: false };
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
let serverRevoked = false;
|
|
523
|
+
const endpoint = session.endpoint || DEFAULT_ENDPOINT;
|
|
524
|
+
const refreshToken = session.auth?.refreshToken;
|
|
525
|
+
|
|
526
|
+
if (refreshToken) {
|
|
527
|
+
try {
|
|
528
|
+
const res = await fetchJson(`${endpoint}${AUTH_PREFIX}/auth/logout`, {
|
|
529
|
+
method: 'POST',
|
|
530
|
+
headers: {
|
|
531
|
+
...buildEnterpriseHeaders(endpoint, session.auth, session.account),
|
|
532
|
+
'X-Refresh-Token': refreshToken,
|
|
533
|
+
'X-Auth-Refresh-Source': 'plugin',
|
|
534
|
+
'X-No-Authorization': 'true'
|
|
535
|
+
},
|
|
536
|
+
body: '{}'
|
|
537
|
+
});
|
|
538
|
+
serverRevoked = res.ok;
|
|
539
|
+
} catch {
|
|
540
|
+
serverRevoked = false;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
removeCliSession();
|
|
545
|
+
return { hadSession: true, serverRevoked };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function parseSseCompletion(raw) {
|
|
549
|
+
let fullText = '';
|
|
550
|
+
let reasoning = '';
|
|
551
|
+
|
|
552
|
+
for (const line of raw.split('\n')) {
|
|
553
|
+
if (line.startsWith('data: ')) {
|
|
554
|
+
const dataStr = line.slice(6).trim();
|
|
555
|
+
if (dataStr === '[DONE]') continue;
|
|
556
|
+
try {
|
|
557
|
+
const parsed = JSON.parse(dataStr);
|
|
558
|
+
const delta = parsed.choices?.[0]?.delta;
|
|
559
|
+
if (delta?.content) fullText += delta.content;
|
|
560
|
+
if (delta?.reasoning_content) reasoning += delta.reasoning_content;
|
|
561
|
+
} catch {}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
return { text: fullText, reasoning };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
async function fetchDirectApi(session, method, apiPath, body) {
|
|
569
|
+
let activeSession = session;
|
|
570
|
+
if (
|
|
571
|
+
activeSession.auth?.refreshToken &&
|
|
572
|
+
activeSession.auth?.expiresAt &&
|
|
573
|
+
Date.now() >= activeSession.auth.expiresAt - 60000
|
|
574
|
+
) {
|
|
575
|
+
activeSession = await refreshCliSession(activeSession);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const sendOnce = async s => {
|
|
579
|
+
const endpoint = (s.endpoint || DEFAULT_ENDPOINT).replace(/\/+$/, '');
|
|
580
|
+
const headers = {
|
|
581
|
+
'Accept': 'application/json',
|
|
582
|
+
'Authorization': `Bearer ${s.auth.accessToken}`
|
|
583
|
+
};
|
|
584
|
+
if (s.account?.uid) {
|
|
585
|
+
headers['X-User-Id'] = s.account.uid;
|
|
586
|
+
}
|
|
587
|
+
if (s.account?.enterpriseId) {
|
|
588
|
+
headers['X-Enterprise-Id'] = s.account.enterpriseId;
|
|
589
|
+
headers['X-Tenant-Id'] = s.account.enterpriseId;
|
|
590
|
+
}
|
|
591
|
+
const init = { method, headers };
|
|
592
|
+
if (body !== undefined && method !== 'GET' && method !== 'HEAD') {
|
|
593
|
+
headers['Content-Type'] = 'application/json';
|
|
594
|
+
init.body = JSON.stringify(body);
|
|
595
|
+
}
|
|
596
|
+
return fetchJson(`${endpoint}${apiPath}`, init);
|
|
597
|
+
};
|
|
598
|
+
|
|
599
|
+
let res = await sendOnce(activeSession);
|
|
600
|
+
if (res.status === 401 && activeSession.auth?.refreshToken) {
|
|
601
|
+
activeSession = await refreshCliSession(activeSession);
|
|
602
|
+
res = await sendOnce(activeSession);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
if (!res.ok) {
|
|
606
|
+
throw new Error(`HTTP ${res.status}: ${res.json?.msg || res.json?.message || res.text}`);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
return res.json?.data ?? res.json;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async function fetchIpcApi(method, apiPath, body) {
|
|
613
|
+
const discoveryFile = path.join(os.homedir(), '.workbuddy', 'wbipc', 'endpoint.json');
|
|
614
|
+
if (!fs.existsSync(discoveryFile)) {
|
|
615
|
+
throw new Error('WorkBuddy 桌面端未运行');
|
|
616
|
+
}
|
|
617
|
+
const discovery = JSON.parse(fs.readFileSync(discoveryFile, 'utf8'));
|
|
618
|
+
|
|
619
|
+
return new Promise((resolve, reject) => {
|
|
620
|
+
const socket = net.connect({ path: discovery.endpoint });
|
|
621
|
+
let buffer = Buffer.alloc(0);
|
|
622
|
+
const clientNonce = crypto.randomBytes(16).toString('base64url');
|
|
623
|
+
const send = frame => socket.write(JSON.stringify(frame) + '\n');
|
|
624
|
+
|
|
625
|
+
const timeoutTimer = setTimeout(() => {
|
|
626
|
+
socket.destroy();
|
|
627
|
+
reject(new Error('WBIPC 请求超时 (15s)'));
|
|
628
|
+
}, 15000);
|
|
629
|
+
|
|
630
|
+
socket.on('connect', () => {
|
|
631
|
+
send({
|
|
632
|
+
type: 'session_hello',
|
|
633
|
+
protocol_min: PROTOCOL_VERSION,
|
|
634
|
+
protocol_max: PROTOCOL_VERSION,
|
|
635
|
+
client_nonce: clientNonce,
|
|
636
|
+
ticket_id: ticketIdOf(discovery.ticket),
|
|
637
|
+
client: { kind: 'cli', id: 'workbuddy-cli' }
|
|
638
|
+
});
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
socket.on('data', chunk => {
|
|
642
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
643
|
+
for (;;) {
|
|
644
|
+
const nl = buffer.indexOf(0x0a);
|
|
645
|
+
if (nl < 0) break;
|
|
646
|
+
const line = buffer.subarray(0, nl);
|
|
647
|
+
buffer = buffer.subarray(nl + 1);
|
|
648
|
+
if (line.length === 0) continue;
|
|
649
|
+
|
|
650
|
+
let f;
|
|
651
|
+
try {
|
|
652
|
+
f = JSON.parse(line.toString('utf8'));
|
|
653
|
+
} catch {
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
if (f.type === 'session_challenge') {
|
|
658
|
+
send({
|
|
659
|
+
type: 'session_prove',
|
|
660
|
+
client_proof: computeProof(discovery.ticket, 'client', {
|
|
661
|
+
protocol: PROTOCOL_VERSION,
|
|
662
|
+
endpoint: discovery.endpoint,
|
|
663
|
+
clientNonce,
|
|
664
|
+
serverNonce: f.server_nonce
|
|
665
|
+
})
|
|
666
|
+
});
|
|
667
|
+
} else if (f.type === 'session_hello_ack') {
|
|
668
|
+
send({ jsonrpc: '2.0', id: 1, method: 'broker/GetPipe', params: { pipe: 'wb.request' } });
|
|
669
|
+
} else if (f.id === 1) {
|
|
670
|
+
if (f.error) {
|
|
671
|
+
clearTimeout(timeoutTimer);
|
|
672
|
+
socket.end();
|
|
673
|
+
return reject(new Error(`GetPipe 错误: ${f.error.message}`));
|
|
674
|
+
}
|
|
675
|
+
const channel = f.result?.channel;
|
|
676
|
+
const params = {
|
|
677
|
+
method,
|
|
678
|
+
path: apiPath,
|
|
679
|
+
headers: { 'accept': 'application/json' }
|
|
680
|
+
};
|
|
681
|
+
if (body !== undefined && method !== 'GET' && method !== 'HEAD') {
|
|
682
|
+
params.headers['content-type'] = 'application/json';
|
|
683
|
+
params.body_b64 = Buffer.from(JSON.stringify(body)).toString('base64');
|
|
684
|
+
}
|
|
685
|
+
send({ jsonrpc: '2.0', id: 2, method: `${channel}/http.fetch`, mode: 'call', params });
|
|
686
|
+
} else if (f.id === 2) {
|
|
687
|
+
clearTimeout(timeoutTimer);
|
|
688
|
+
socket.end();
|
|
689
|
+
if (f.error) return reject(new Error(f.error.message));
|
|
690
|
+
const raw = f.result?.body_b64 ? Buffer.from(f.result.body_b64, 'base64').toString('utf8') : '';
|
|
691
|
+
let parsed = null;
|
|
692
|
+
try { parsed = JSON.parse(raw); } catch {}
|
|
693
|
+
if (f.result?.status && f.result.status >= 400) {
|
|
694
|
+
return reject(new Error(`HTTP ${f.result.status}: ${parsed?.msg || parsed?.message || raw}`));
|
|
695
|
+
}
|
|
696
|
+
resolve(parsed?.data ?? parsed);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
socket.on('error', err => {
|
|
702
|
+
clearTimeout(timeoutTimer);
|
|
703
|
+
reject(new Error(`连接 WorkBuddy 套接字失败: ${err.message}`));
|
|
704
|
+
});
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
async function scanAvailableModels(options = {}) {
|
|
709
|
+
const cliSession = readCliSession();
|
|
710
|
+
const discoveryFile = path.join(os.homedir(), '.workbuddy', 'wbipc', 'endpoint.json');
|
|
711
|
+
const hasIpc = fs.existsSync(discoveryFile);
|
|
712
|
+
|
|
713
|
+
if (!cliSession?.auth?.accessToken && !hasIpc) {
|
|
714
|
+
return { source: 'static', models: null, reason: '未登录且桌面端未运行' };
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
const enterpriseId = cliSession?.account?.enterpriseId;
|
|
718
|
+
const candidatePaths = enterpriseId
|
|
719
|
+
? [`/v2/enterprises/${encodeURIComponent(enterpriseId)}/models`, '/v2/enterprises/personal/models']
|
|
720
|
+
: ['/v2/enterprises/personal/models'];
|
|
721
|
+
|
|
722
|
+
let payload = null;
|
|
723
|
+
let lastErr = null;
|
|
724
|
+
for (const apiPath of candidatePaths) {
|
|
725
|
+
try {
|
|
726
|
+
payload = cliSession?.auth?.accessToken
|
|
727
|
+
? await fetchDirectApi(cliSession, 'GET', apiPath)
|
|
728
|
+
: await fetchIpcApi('GET', apiPath);
|
|
729
|
+
if (payload) break;
|
|
730
|
+
} catch (err) {
|
|
731
|
+
lastErr = err;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
if (!payload) {
|
|
736
|
+
throw lastErr || new Error('获取模型列表失败');
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
const rawList = Array.isArray(payload.models) ? payload.models : Array.isArray(payload) ? payload : [];
|
|
740
|
+
const excludedTags = new Set(['text-to-image']);
|
|
741
|
+
const models = options.includeAll
|
|
742
|
+
? rawList
|
|
743
|
+
: rawList.filter(m => {
|
|
744
|
+
if (!m || typeof m.id !== 'string' || !m.id) return false;
|
|
745
|
+
const tags = Array.isArray(m.tags) ? m.tags.map(String) : [];
|
|
746
|
+
return !tags.some(t => excludedTags.has(t));
|
|
747
|
+
});
|
|
748
|
+
|
|
749
|
+
return { source: cliSession?.auth?.accessToken ? 'remote-direct' : 'remote-ipc', models };
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function buildReverseAliasMap() {
|
|
753
|
+
const map = new Map();
|
|
754
|
+
for (const [alias, target] of Object.entries(MODEL_ALIASES)) {
|
|
755
|
+
if (alias === target) continue;
|
|
756
|
+
if (!map.has(target)) map.set(target, []);
|
|
757
|
+
map.get(target).push(alias);
|
|
758
|
+
}
|
|
759
|
+
return map;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
function printScannedModels(models, source) {
|
|
763
|
+
const aliasMap = buildReverseAliasMap();
|
|
764
|
+
console.log(`WorkBuddy 可用模型列表 (来源: ${source}, 共 ${models.length} 个):\n`);
|
|
765
|
+
for (const m of models) {
|
|
766
|
+
const aliases = aliasMap.get(m.id);
|
|
767
|
+
const aliasText = aliases?.length ? ` (简写: ${aliases.join(', ')})` : '';
|
|
768
|
+
const credits = m.credits ? ` [${m.credits}]` : '';
|
|
769
|
+
const caps = [];
|
|
770
|
+
if (m.supportsReasoning) caps.push('推理');
|
|
771
|
+
if (m.supportsImages) caps.push('视觉');
|
|
772
|
+
if (m.supportsToolCall) caps.push('工具');
|
|
773
|
+
if (Array.isArray(m.tags) && m.tags.length) caps.push(m.tags.join(','));
|
|
774
|
+
const capText = caps.length ? ` (${caps.join(' / ')})` : '';
|
|
775
|
+
const title = m.name && m.name !== m.id ? ` — ${m.name}` : '';
|
|
776
|
+
console.log(` ${m.id}${aliasText}${title}${credits}${capText}`);
|
|
777
|
+
const desc = m.descriptionZh || m.descriptionEn;
|
|
778
|
+
if (desc) {
|
|
779
|
+
console.log(` ${desc}`);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
console.log(`\n提示: 使用 workbuddy -m <model_id> "..." 即可直接调用任意新模型,无需等待 CLI 更新。`);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
async function callWorkBuddyDirect(session, userPrompt, options = {}) {
|
|
786
|
+
let activeSession = session;
|
|
787
|
+
if (
|
|
788
|
+
activeSession.auth?.refreshToken &&
|
|
789
|
+
activeSession.auth?.expiresAt &&
|
|
790
|
+
Date.now() >= activeSession.auth.expiresAt - 60000
|
|
791
|
+
) {
|
|
792
|
+
activeSession = await refreshCliSession(activeSession);
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const { model = 'deepseek-v3-2-volc', systemPrompt } = options;
|
|
796
|
+
const messages = [];
|
|
797
|
+
if (systemPrompt) {
|
|
798
|
+
messages.push({ role: 'system', content: systemPrompt });
|
|
799
|
+
}
|
|
800
|
+
messages.push({ role: 'user', content: userPrompt });
|
|
801
|
+
|
|
802
|
+
const payload = {
|
|
803
|
+
model,
|
|
804
|
+
messages,
|
|
805
|
+
stream: true
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
const sendRequest = async s => {
|
|
809
|
+
const endpoint = (s.endpoint || DEFAULT_ENDPOINT).replace(/\/+$/, '');
|
|
810
|
+
const headers = {
|
|
811
|
+
'Content-Type': 'application/json',
|
|
812
|
+
'Accept': 'text/event-stream',
|
|
813
|
+
'Authorization': `Bearer ${s.auth.accessToken}`
|
|
814
|
+
};
|
|
815
|
+
if (s.account?.uid) {
|
|
816
|
+
headers['X-User-Id'] = s.account.uid;
|
|
817
|
+
}
|
|
818
|
+
if (s.account?.enterpriseId) {
|
|
819
|
+
headers['X-Enterprise-Id'] = s.account.enterpriseId;
|
|
820
|
+
headers['X-Tenant-Id'] = s.account.enterpriseId;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
const controller = new AbortController();
|
|
824
|
+
const timer = setTimeout(() => controller.abort(), 60000);
|
|
825
|
+
try {
|
|
826
|
+
const res = await fetch(`${endpoint}/v2/chat/completions`, {
|
|
827
|
+
method: 'POST',
|
|
828
|
+
headers,
|
|
829
|
+
body: JSON.stringify(payload),
|
|
830
|
+
signal: controller.signal
|
|
831
|
+
});
|
|
832
|
+
const raw = await res.text();
|
|
833
|
+
return { status: res.status, raw };
|
|
834
|
+
} catch (err) {
|
|
835
|
+
if (err?.name === 'AbortError') {
|
|
836
|
+
throw new Error('请求超时 (60s)');
|
|
837
|
+
}
|
|
838
|
+
throw err;
|
|
839
|
+
} finally {
|
|
840
|
+
clearTimeout(timer);
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
|
|
844
|
+
let res = await sendRequest(activeSession);
|
|
845
|
+
if (res.status === 401 && activeSession.auth?.refreshToken) {
|
|
846
|
+
activeSession = await refreshCliSession(activeSession);
|
|
847
|
+
res = await sendRequest(activeSession);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
if (res.status >= 400) {
|
|
851
|
+
let errorText = `HTTP ${res.status}`;
|
|
852
|
+
try {
|
|
853
|
+
const errJson = JSON.parse(res.raw);
|
|
854
|
+
errorText += `: ${errJson.msg || errJson.message || res.raw}`;
|
|
855
|
+
} catch {
|
|
856
|
+
if (res.raw) errorText += `: ${res.raw}`;
|
|
857
|
+
}
|
|
858
|
+
throw new Error(errorText);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
return parseSseCompletion(res.raw);
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
async function callWorkBuddy(userPrompt, options = {}) {
|
|
865
|
+
const cliSession = readCliSession();
|
|
866
|
+
if (cliSession?.auth?.accessToken) {
|
|
867
|
+
return callWorkBuddyDirect(cliSession, userPrompt, options);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
const discoveryFile = path.join(os.homedir(), '.workbuddy', 'wbipc', 'endpoint.json');
|
|
871
|
+
if (!fs.existsSync(discoveryFile)) {
|
|
872
|
+
throw new Error('未登录且 WorkBuddy 桌面端未运行。请先运行 "workbuddy login" 登录,或启动 WorkBuddy 桌面端。');
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
let discovery;
|
|
876
|
+
try {
|
|
877
|
+
discovery = JSON.parse(fs.readFileSync(discoveryFile, 'utf8'));
|
|
878
|
+
} catch (err) {
|
|
879
|
+
throw new Error(`读取 WBIPC endpoint.json 失败: ${err.message}`);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
const { model = 'deepseek-v3-2-volc', systemPrompt } = options;
|
|
883
|
+
|
|
884
|
+
return new Promise((resolve, reject) => {
|
|
885
|
+
const socket = net.connect({ path: discovery.endpoint });
|
|
886
|
+
let buffer = Buffer.alloc(0);
|
|
887
|
+
const clientNonce = crypto.randomBytes(16).toString('base64url');
|
|
888
|
+
const send = frame => socket.write(JSON.stringify(frame) + '\n');
|
|
889
|
+
|
|
890
|
+
let timeoutTimer = setTimeout(() => {
|
|
891
|
+
socket.destroy();
|
|
892
|
+
reject(new Error('请求超时 (60s)'));
|
|
893
|
+
}, 60000);
|
|
894
|
+
|
|
895
|
+
socket.on('connect', () => {
|
|
896
|
+
send({
|
|
897
|
+
type: 'session_hello',
|
|
898
|
+
protocol_min: PROTOCOL_VERSION,
|
|
899
|
+
protocol_max: PROTOCOL_VERSION,
|
|
900
|
+
client_nonce: clientNonce,
|
|
901
|
+
ticket_id: ticketIdOf(discovery.ticket),
|
|
902
|
+
client: { kind: 'cli', id: 'workbuddy-cli' }
|
|
903
|
+
});
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
socket.on('data', chunk => {
|
|
907
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
908
|
+
for (;;) {
|
|
909
|
+
const nl = buffer.indexOf(0x0a);
|
|
910
|
+
if (nl < 0) break;
|
|
911
|
+
const line = buffer.subarray(0, nl);
|
|
912
|
+
buffer = buffer.subarray(nl + 1);
|
|
913
|
+
if (line.length === 0) continue;
|
|
914
|
+
|
|
915
|
+
let f;
|
|
916
|
+
try {
|
|
917
|
+
f = JSON.parse(line.toString('utf8'));
|
|
918
|
+
} catch {
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
if (f.type === 'session_challenge') {
|
|
923
|
+
const transcript = {
|
|
924
|
+
protocol: PROTOCOL_VERSION,
|
|
925
|
+
endpoint: discovery.endpoint,
|
|
926
|
+
clientNonce,
|
|
927
|
+
serverNonce: f.server_nonce
|
|
928
|
+
};
|
|
929
|
+
send({
|
|
930
|
+
type: 'session_prove',
|
|
931
|
+
client_proof: computeProof(discovery.ticket, 'client', transcript)
|
|
932
|
+
});
|
|
933
|
+
} else if (f.type === 'session_hello_ack') {
|
|
934
|
+
send({ jsonrpc: '2.0', id: 1, method: 'broker/GetPipe', params: { pipe: 'wb.request' } });
|
|
935
|
+
} else if (f.id === 1) {
|
|
936
|
+
if (f.error) {
|
|
937
|
+
clearTimeout(timeoutTimer);
|
|
938
|
+
socket.end();
|
|
939
|
+
return reject(new Error(`GetPipe 错误: ${f.error.message}`));
|
|
940
|
+
}
|
|
941
|
+
const channel = f.result?.channel;
|
|
942
|
+
const messages = [];
|
|
943
|
+
if (systemPrompt) {
|
|
944
|
+
messages.push({ role: 'system', content: systemPrompt });
|
|
945
|
+
}
|
|
946
|
+
messages.push({ role: 'user', content: userPrompt });
|
|
947
|
+
|
|
948
|
+
const payload = {
|
|
949
|
+
model,
|
|
950
|
+
messages,
|
|
951
|
+
stream: true
|
|
952
|
+
};
|
|
953
|
+
|
|
954
|
+
send({
|
|
955
|
+
jsonrpc: '2.0',
|
|
956
|
+
id: 2,
|
|
957
|
+
method: `${channel}/http.fetch`,
|
|
958
|
+
mode: 'call',
|
|
959
|
+
params: {
|
|
960
|
+
method: 'POST',
|
|
961
|
+
path: '/v2/chat/completions',
|
|
962
|
+
headers: {
|
|
963
|
+
'content-type': 'application/json',
|
|
964
|
+
'accept': 'text/event-stream'
|
|
965
|
+
},
|
|
966
|
+
body_b64: Buffer.from(JSON.stringify(payload)).toString('base64')
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
} else if (f.id === 2) {
|
|
970
|
+
clearTimeout(timeoutTimer);
|
|
971
|
+
socket.end();
|
|
972
|
+
|
|
973
|
+
if (f.error) {
|
|
974
|
+
return reject(new Error(f.error.message));
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
if (f.result?.status && f.result.status >= 400) {
|
|
978
|
+
let errorText = `HTTP ${f.result.status}`;
|
|
979
|
+
if (f.result.body_b64) {
|
|
980
|
+
try {
|
|
981
|
+
const bodyStr = Buffer.from(f.result.body_b64, 'base64').toString('utf8');
|
|
982
|
+
const errJson = JSON.parse(bodyStr);
|
|
983
|
+
errorText += `: ${errJson.msg || errJson.message || bodyStr}`;
|
|
984
|
+
} catch {}
|
|
985
|
+
}
|
|
986
|
+
return reject(new Error(errorText));
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
if (!f.result || !f.result.body_b64) {
|
|
990
|
+
return resolve({ text: '', reasoning: '' });
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
const raw = Buffer.from(f.result.body_b64, 'base64').toString('utf8');
|
|
994
|
+
resolve(parseSseCompletion(raw));
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
|
|
999
|
+
socket.on('error', err => {
|
|
1000
|
+
clearTimeout(timeoutTimer);
|
|
1001
|
+
reject(new Error(`连接 WorkBuddy 套接字失败: ${err.message}`));
|
|
1002
|
+
});
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
function getStatusInfo() {
|
|
1007
|
+
const cliSession = readCliSession();
|
|
1008
|
+
const discoveryFile = path.join(os.homedir(), '.workbuddy', 'wbipc', 'endpoint.json');
|
|
1009
|
+
const desktopRunning = fs.existsSync(discoveryFile);
|
|
1010
|
+
return {
|
|
1011
|
+
cliLoggedIn: Boolean(cliSession?.auth?.accessToken),
|
|
1012
|
+
authFile: AUTH_FILE,
|
|
1013
|
+
endpoint: cliSession?.endpoint || DEFAULT_ENDPOINT,
|
|
1014
|
+
account: cliSession?.account || null,
|
|
1015
|
+
expiresAt: cliSession?.auth?.expiresAt ? new Date(cliSession.auth.expiresAt).toISOString() : null,
|
|
1016
|
+
desktopWbicpRunning: desktopRunning
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
async function main() {
|
|
1021
|
+
const args = parseArgs(process.argv.slice(2));
|
|
1022
|
+
|
|
1023
|
+
if (args.command === 'login') {
|
|
1024
|
+
try {
|
|
1025
|
+
const session = await loginWorkBuddy({ noBrowser: args.noBrowser });
|
|
1026
|
+
if (args.asJson) {
|
|
1027
|
+
console.log(JSON.stringify({ ok: true, account: session.account, authFile: AUTH_FILE }, null, 2));
|
|
1028
|
+
} else {
|
|
1029
|
+
const who = session.account?.nickname || session.account?.uid || 'Unknown';
|
|
1030
|
+
console.log(`登录成功!当前账号: ${who}`);
|
|
1031
|
+
console.log(`凭据已保存至: ${AUTH_FILE}(后续无需再开启 WorkBuddy 客户端)`);
|
|
1032
|
+
}
|
|
1033
|
+
} catch (err) {
|
|
1034
|
+
if (args.asJson) {
|
|
1035
|
+
console.error(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
1036
|
+
} else {
|
|
1037
|
+
console.error(`Error: ${err.message}`);
|
|
1038
|
+
}
|
|
1039
|
+
process.exit(1);
|
|
1040
|
+
}
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
if (args.command === 'logout') {
|
|
1045
|
+
const result = await logoutWorkBuddy();
|
|
1046
|
+
if (args.asJson) {
|
|
1047
|
+
console.log(JSON.stringify({ ok: true, ...result }, null, 2));
|
|
1048
|
+
} else if (!result.hadSession) {
|
|
1049
|
+
console.log('当前未登录 CLI 会话。');
|
|
1050
|
+
} else {
|
|
1051
|
+
console.log('已退出登录并清理本地 CLI 凭据。');
|
|
1052
|
+
}
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
if (args.command === 'status') {
|
|
1057
|
+
const info = getStatusInfo();
|
|
1058
|
+
if (args.asJson) {
|
|
1059
|
+
console.log(JSON.stringify({ ok: true, data: info }, null, 2));
|
|
1060
|
+
} else {
|
|
1061
|
+
console.log(`CLI 独立登录: ${info.cliLoggedIn ? '已登录' : '未登录'}`);
|
|
1062
|
+
if (info.cliLoggedIn) {
|
|
1063
|
+
const who = info.account?.nickname || info.account?.uid || '(未知用户)';
|
|
1064
|
+
console.log(`当前账号: ${who}`);
|
|
1065
|
+
if (info.expiresAt) console.log(`Token 过期时间: ${info.expiresAt}`);
|
|
1066
|
+
console.log(`凭据文件: ${info.authFile}`);
|
|
1067
|
+
}
|
|
1068
|
+
console.log(`桌面端 WBIPC: ${info.desktopWbicpRunning ? '运行中' : '未运行'}`);
|
|
1069
|
+
}
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
if (args.command === 'models') {
|
|
1074
|
+
if (args.staticModels) {
|
|
1075
|
+
if (args.asJson) {
|
|
1076
|
+
console.log(JSON.stringify({ ok: true, source: 'static', aliases: MODEL_ALIASES }, null, 2));
|
|
1077
|
+
} else {
|
|
1078
|
+
showModels();
|
|
1079
|
+
}
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
try {
|
|
1084
|
+
const result = await scanAvailableModels({ includeAll: args.includeAllModels });
|
|
1085
|
+
if (!result.models) {
|
|
1086
|
+
if (args.asJson) {
|
|
1087
|
+
console.log(JSON.stringify({ ok: true, source: 'static', note: result.reason, aliases: MODEL_ALIASES }, null, 2));
|
|
1088
|
+
} else {
|
|
1089
|
+
console.error(`提示: ${result.reason},以下为内置静态模型清单;运行 "workbuddy login" 后可实时扫描服务端最新模型。\n`);
|
|
1090
|
+
showModels();
|
|
1091
|
+
}
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
if (args.asJson) {
|
|
1096
|
+
console.log(JSON.stringify({ ok: true, source: result.source, count: result.models.length, models: result.models }, null, 2));
|
|
1097
|
+
} else {
|
|
1098
|
+
printScannedModels(result.models, result.source);
|
|
1099
|
+
}
|
|
1100
|
+
} catch (err) {
|
|
1101
|
+
if (args.asJson) {
|
|
1102
|
+
console.error(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
1103
|
+
} else {
|
|
1104
|
+
console.error(`扫描服务端模型失败 (${err.message}),回退到内置清单:\n`);
|
|
1105
|
+
showModels();
|
|
1106
|
+
}
|
|
1107
|
+
process.exit(1);
|
|
1108
|
+
}
|
|
1109
|
+
return;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
let userPrompt = args.prompt;
|
|
1113
|
+
|
|
1114
|
+
// 如果没有从命令行参数提供 prompt,检查 stdin 是否有输入(例如管道传参)
|
|
1115
|
+
if (!userPrompt && !process.stdin.isTTY) {
|
|
1116
|
+
const chunks = [];
|
|
1117
|
+
for await (const chunk of process.stdin) {
|
|
1118
|
+
chunks.push(chunk);
|
|
1119
|
+
}
|
|
1120
|
+
userPrompt = Buffer.concat(chunks).toString('utf8').trim();
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
if (!userPrompt) {
|
|
1124
|
+
showHelp();
|
|
1125
|
+
process.exit(1);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
try {
|
|
1129
|
+
const result = await callWorkBuddy(userPrompt, {
|
|
1130
|
+
model: args.model,
|
|
1131
|
+
systemPrompt: args.systemPrompt
|
|
1132
|
+
});
|
|
1133
|
+
|
|
1134
|
+
if (args.asJson) {
|
|
1135
|
+
console.log(JSON.stringify({ ok: true, data: result }, null, 2));
|
|
1136
|
+
} else {
|
|
1137
|
+
if (result.reasoning && process.env.WORKBUDDY_SHOW_REASONING === '1') {
|
|
1138
|
+
console.error(`[思考过程]\n${result.reasoning}\n`);
|
|
1139
|
+
}
|
|
1140
|
+
console.log(result.text);
|
|
1141
|
+
}
|
|
1142
|
+
} catch (err) {
|
|
1143
|
+
if (args.asJson) {
|
|
1144
|
+
console.error(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
1145
|
+
} else {
|
|
1146
|
+
console.error(`Error: ${err.message}`);
|
|
1147
|
+
}
|
|
1148
|
+
process.exit(1);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
main();
|