workbuddy-cli 0.0.0-stage → 1.2.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 +226 -2
- package/README.zh-CN.md +227 -0
- package/bin/acp-server.mjs +739 -0
- package/bin/sessions.mjs +92 -0
- package/bin/workbuddy.mjs +1537 -0
- package/package.json +38 -4
|
@@ -0,0 +1,1537 @@
|
|
|
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
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { runAcpServer } from './acp-server.mjs';
|
|
10
|
+
import {
|
|
11
|
+
authFilePath,
|
|
12
|
+
cliHome,
|
|
13
|
+
createSessionId,
|
|
14
|
+
latestSession,
|
|
15
|
+
listSessions,
|
|
16
|
+
loadSession,
|
|
17
|
+
saveSession
|
|
18
|
+
} from './sessions.mjs';
|
|
19
|
+
|
|
20
|
+
const PROTOCOL_VERSION = 1;
|
|
21
|
+
const DEFAULT_ENDPOINT = 'https://www.workbuddy.cn';
|
|
22
|
+
const AUTH_PREFIX = '/v2/plugin';
|
|
23
|
+
const AUTH_PLATFORM = 'workbuddy';
|
|
24
|
+
const DEFAULT_MODEL = 'deepseek-v3-2-volc';
|
|
25
|
+
const AUTH_DIR = cliHome();
|
|
26
|
+
const AUTH_FILE = authFilePath();
|
|
27
|
+
const LOGIN_POLL_INTERVAL_MS = 1500;
|
|
28
|
+
const LOGIN_TIMEOUT_MS = 300000;
|
|
29
|
+
const LOGIN_TOKEN_PENDING_CODE = 11217;
|
|
30
|
+
const LOGIN_ACCOUNT_PENDING_CODE = 12151;
|
|
31
|
+
|
|
32
|
+
const MODEL_ALIASES = {
|
|
33
|
+
// 模式
|
|
34
|
+
'auto': 'auto',
|
|
35
|
+
'fast': 'fast-model',
|
|
36
|
+
'balanced': 'balanced-model',
|
|
37
|
+
'deep': 'deep-model',
|
|
38
|
+
|
|
39
|
+
// 腾讯混元 (Hunyuan)
|
|
40
|
+
'hy4': 'hy4',
|
|
41
|
+
'hy4free': 'hy4free',
|
|
42
|
+
'hy4std': 'hy4std',
|
|
43
|
+
'hy4-preview': 'hy4-preview',
|
|
44
|
+
'hy3': 'hy3',
|
|
45
|
+
'hy3-free': 'hy3',
|
|
46
|
+
'hy3-std': 'hy3-x',
|
|
47
|
+
'hy3-preview': 'hy3-preview',
|
|
48
|
+
'hunyuan': 'hy4',
|
|
49
|
+
'hunyuan-chat': 'hunyuan-chat',
|
|
50
|
+
|
|
51
|
+
// DeepSeek 系列
|
|
52
|
+
'ds': 'deepseek-v3-2-volc',
|
|
53
|
+
'deepseek': 'deepseek-v3-2-volc',
|
|
54
|
+
'deepseek-v3': 'deepseek-v3-2-volc',
|
|
55
|
+
'deepseek-v4': 'deepseek-v4.1-flash',
|
|
56
|
+
'deepseek-v4.1': 'deepseek-v4.1-flash',
|
|
57
|
+
'deepseek-v4-flash': 'deepseek-v4-flash',
|
|
58
|
+
'deepseek-v4-pro': 'deepseek-v4-pro',
|
|
59
|
+
|
|
60
|
+
// 智谱 GLM 系列
|
|
61
|
+
'glm': 'glm-5.3',
|
|
62
|
+
'glm-5.3': 'glm-5.3',
|
|
63
|
+
'glm-flash': 'glm-5.3-flash',
|
|
64
|
+
'glm-5.3-flash': 'glm-5.3-flash',
|
|
65
|
+
'glm-5.3-flashx': 'glm-5.3-flashx',
|
|
66
|
+
'glm-5.2': 'glm-5.2',
|
|
67
|
+
'glm-5v': 'glm-5v-turbo',
|
|
68
|
+
'glm-5v-turbo': 'glm-5v-turbo',
|
|
69
|
+
|
|
70
|
+
// 月之暗面 Kimi 系列
|
|
71
|
+
'kimi': 'kimi-k2.5',
|
|
72
|
+
'kimi-k2.5': 'kimi-k2.5',
|
|
73
|
+
'kimi-k2.6': 'kimi-k2.6',
|
|
74
|
+
'kimi-k2.7': 'kimi-k2.7',
|
|
75
|
+
'kimi-k2.8': 'kimi-k2.8-preview',
|
|
76
|
+
'kimi-k3': 'kimi-k3-1',
|
|
77
|
+
'kimi-k3-1': 'kimi-k3-1',
|
|
78
|
+
'kimi-k3-2': 'kimi-k3-2',
|
|
79
|
+
'kimi-pro': 'kimi-k3.1-pro',
|
|
80
|
+
'kimi-k3.1-pro': 'kimi-k3.1-pro',
|
|
81
|
+
|
|
82
|
+
// MiniMax 系列
|
|
83
|
+
'minimax': 'minimax-m2.7',
|
|
84
|
+
'minimax-m2.7': 'minimax-m2.7',
|
|
85
|
+
'minimax-m3': 'minimax-m3-pay',
|
|
86
|
+
'minimax-flash': 'minimax-m3.1-flash',
|
|
87
|
+
'minimax-m3.1-flash': 'minimax-m3.1-flash',
|
|
88
|
+
|
|
89
|
+
// 小米 / 阶跃星辰 / 其他
|
|
90
|
+
'mimo': 'mimo-v2.6-pro',
|
|
91
|
+
'mimo-v2.6-pro': 'mimo-v2.6-pro',
|
|
92
|
+
'step': 'step-5-preview',
|
|
93
|
+
'step-5-preview': 'step-5-preview',
|
|
94
|
+
'space-bunny': 'space-bunny',
|
|
95
|
+
'wb-lite': 'wb-lite'
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const ACP_MODELS = [
|
|
99
|
+
['deepseek-v3-2-volc', 'DeepSeek V3.2'],
|
|
100
|
+
['deepseek-v4.1-flash', 'DeepSeek V4.1 Flash'],
|
|
101
|
+
['deepseek-v4-pro', 'DeepSeek V4 Pro'],
|
|
102
|
+
['hy4', '混元 4.0'],
|
|
103
|
+
['glm-5.3', 'GLM-5.3'],
|
|
104
|
+
['kimi-k3.1-pro', 'Kimi K3.1 Pro'],
|
|
105
|
+
['kimi-k2.5', 'Kimi K2.5'],
|
|
106
|
+
['minimax-m3.1-flash', 'MiniMax M3.1 Flash'],
|
|
107
|
+
['auto', 'Auto'],
|
|
108
|
+
['fast-model', 'Fast'],
|
|
109
|
+
['balanced-model', 'Balanced'],
|
|
110
|
+
['deep-model', 'Deep']
|
|
111
|
+
];
|
|
112
|
+
|
|
113
|
+
function acpModels() {
|
|
114
|
+
return ACP_MODELS.map(([modelId, name]) => ({ modelId, name }));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function printSessions(asJson) {
|
|
118
|
+
const sessions = listSessions();
|
|
119
|
+
if (asJson) {
|
|
120
|
+
console.log(JSON.stringify({
|
|
121
|
+
ok: true,
|
|
122
|
+
sessions: sessions.map(session => ({
|
|
123
|
+
id: session.id,
|
|
124
|
+
title: session.title || '',
|
|
125
|
+
cwd: session.cwd,
|
|
126
|
+
model: session.model,
|
|
127
|
+
updatedAt: session.updatedAt,
|
|
128
|
+
messages: Array.isArray(session.messages) ? session.messages.length : 0
|
|
129
|
+
}))
|
|
130
|
+
}, null, 2));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (!sessions.length) {
|
|
134
|
+
console.log('还没有保存的会话。直接提问一次后,可用 workbuddy -c 继续。');
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
console.log('已保存的会话(最近在前):\n');
|
|
138
|
+
for (const session of sessions.slice(0, 30)) {
|
|
139
|
+
const when = session.updatedAt ? new Date(session.updatedAt).toISOString().replace('T', ' ').slice(0, 16) : '-';
|
|
140
|
+
console.log(` ${session.id} ${when} ${session.model || ''}`);
|
|
141
|
+
console.log(` ${session.title || '(无标题)'} ${session.cwd || ''}`);
|
|
142
|
+
}
|
|
143
|
+
console.log('\n继续当前目录最近一条:workbuddy -c "..."');
|
|
144
|
+
console.log('按 id 继续:workbuddy resume <id> "..."');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function showModels() {
|
|
148
|
+
console.log(`WorkBuddy 完整模型清单(经实测 200 OK 确认可用):
|
|
149
|
+
|
|
150
|
+
1. 智能调度模式:
|
|
151
|
+
auto 自动调度
|
|
152
|
+
fast-model (简写: fast) 快速响应
|
|
153
|
+
balanced-model (简写: balanced) 均衡模式
|
|
154
|
+
deep-model (简写: deep) 极致推理/深度模式
|
|
155
|
+
|
|
156
|
+
2. 腾讯混元 (Hunyuan):
|
|
157
|
+
hy4 (或 hy4free) 混元 4.0 [免费] (客户端默认)
|
|
158
|
+
hy4std 混元 4.0 标准版 [付费包额度]
|
|
159
|
+
hy4-preview 混元 4.0 尝鲜内测版
|
|
160
|
+
hy4-preview-ctrl 混元 4.0 对照组
|
|
161
|
+
hy4-preview-exp 混元 4.0 实验组
|
|
162
|
+
hy4preview-exp1 / exp2 混元 4.0 实验组 1/2
|
|
163
|
+
hy3 (或 hy3-free) 混元 3.0 [免费]
|
|
164
|
+
hy3-x (或 hy3-std) 混元 3.0 标准版 [付费包额度]
|
|
165
|
+
hy3-b / hy3-c / hy3-preview 混元 3.0 衍生版本
|
|
166
|
+
hunyuan-chat 混元 Turbos
|
|
167
|
+
|
|
168
|
+
3. DeepSeek 系列:
|
|
169
|
+
deepseek-v3-2-volc (简写: deepseek, ds) DeepSeek-V3.2 (火山/腾讯聚合,默认模型)
|
|
170
|
+
deepseek-v4.1-flash (简写: deepseek-v4) DeepSeek-V4.1-Flash (极速旗舰)
|
|
171
|
+
deepseek-v4-flash DeepSeek-V4-Flash
|
|
172
|
+
deepseek-v4-pro DeepSeek-V4-Pro (高阶专业版)
|
|
173
|
+
|
|
174
|
+
4. 智谱 GLM 系列:
|
|
175
|
+
glm-5.3 (简写: glm) GLM-5.3 最新旗舰
|
|
176
|
+
glm-5.3-flash (简写: glm-flash) GLM-5.3-Flash
|
|
177
|
+
glm-5.3-flashx GLM-5.3-FlashX
|
|
178
|
+
glm-5.2 GLM-5.2
|
|
179
|
+
glm-5v-turbo (简写: glm-5v) GLM-5v-Turbo 视觉多模态
|
|
180
|
+
|
|
181
|
+
5. 月之暗面 Kimi 系列:
|
|
182
|
+
kimi-k3.1-pro (简写: kimi-pro) Kimi-K3.1-Pro 最新旗舰
|
|
183
|
+
kimi-k3-1 / kimi-k3-2 Kimi-K3 / K3-v2
|
|
184
|
+
kimi-k2.8-preview Kimi-K2.8-Preview
|
|
185
|
+
kimi-k2.7 Kimi-K2.7-Code 代码专精
|
|
186
|
+
kimi-k2.6 Kimi-K2.6
|
|
187
|
+
kimi-k2.5 (简写: kimi) Kimi-K2.5
|
|
188
|
+
|
|
189
|
+
6. MiniMax 系列:
|
|
190
|
+
minimax-m3.1-flash (简写: minimax-flash) MiniMax-M3.1-Flash 极速版
|
|
191
|
+
minimax-m3-pay (简写: minimax-m3) MiniMax-M3
|
|
192
|
+
minimax-m2.7 (简写: minimax) MiniMax-M2.7
|
|
193
|
+
|
|
194
|
+
7. 其他合作厂商与特色模型:
|
|
195
|
+
mimo-v2.6-pro (简写: mimo) 小米 Xiaomi MiMo-V2.6-Pro
|
|
196
|
+
step-5-preview (简写: step) 阶跃星辰 Step-5-Preview
|
|
197
|
+
space-bunny Space-Bunny
|
|
198
|
+
wb-lite WorkBuddy Lite
|
|
199
|
+
|
|
200
|
+
8. 内置代码辅助模型 (直接可调):
|
|
201
|
+
codewise-rewrite 代码重构专精
|
|
202
|
+
codewise-jump 符号定义跳转辅助
|
|
203
|
+
codewise-nes-a4-027-aide IDE 代码补全辅助
|
|
204
|
+
|
|
205
|
+
注:
|
|
206
|
+
- 腾讯内网专属模型(如 GPT-5 / GPT-6 / Claude-5 / Gemini-3 等海外模型)需处于腾讯内部 IOA 办公网环境方可访问,非 IOA 环境会返回 400 'is only available on IOA'。
|
|
207
|
+
- 生图模型 (hunyuan-image-v3.0) 与生视频模型 (kling-video-v3, minimax-video-h3) 为多模态生成专用接口,不走普通文本流式对话。
|
|
208
|
+
`);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function showHelp() {
|
|
212
|
+
console.log(`Usage: workbuddy [command] [options] [prompt]
|
|
213
|
+
|
|
214
|
+
Interact with WorkBuddy directly (after login) or via local desktop WBIPC.
|
|
215
|
+
|
|
216
|
+
Commands:
|
|
217
|
+
login Log in via browser (no desktop app needed afterwards)
|
|
218
|
+
logout Revoke session and remove local CLI credentials
|
|
219
|
+
status, whoami Show current CLI auth and desktop WBIPC status
|
|
220
|
+
models Scan available models from server (falls back to static list)
|
|
221
|
+
sessions List saved CLI conversations
|
|
222
|
+
continue [prompt] Continue the most recent conversation in this directory
|
|
223
|
+
resume [id] [prompt] Resume a conversation by id (or a unique prefix)
|
|
224
|
+
acp Speak Agent Client Protocol on stdin/stdout (for T3 Code)
|
|
225
|
+
|
|
226
|
+
Arguments:
|
|
227
|
+
prompt Your prompt / question
|
|
228
|
+
|
|
229
|
+
Options:
|
|
230
|
+
-p, --print Print response and exit (default behavior)
|
|
231
|
+
-c, --continue Continue the most recent conversation in this directory
|
|
232
|
+
-r, --resume [id] Resume a conversation by id, or list conversations when omitted
|
|
233
|
+
--session-id <id> Pin the session id for a new conversation
|
|
234
|
+
-m, --model <model> Model name or alias (e.g. hy4, deepseek, glm, default: deepseek-v3-2-volc)
|
|
235
|
+
-l, --models Scan/list available models and aliases
|
|
236
|
+
--all Include specialized/image models when listing models
|
|
237
|
+
--static Show built-in static model list without querying server
|
|
238
|
+
--json Output response as JSON
|
|
239
|
+
-s, --system <prompt> System prompt
|
|
240
|
+
--no-browser Print login URL instead of opening browser automatically
|
|
241
|
+
-h, --help Show this help message
|
|
242
|
+
|
|
243
|
+
Examples:
|
|
244
|
+
workbuddy login
|
|
245
|
+
workbuddy models
|
|
246
|
+
workbuddy "用Python写一个快速排序"
|
|
247
|
+
workbuddy -c "把刚才的例子改成迭代版本"
|
|
248
|
+
workbuddy resume wb_abc123 "再补上测试"
|
|
249
|
+
workbuddy sessions
|
|
250
|
+
workbuddy -m hy4 "帮我写一封商务邮件"
|
|
251
|
+
cat document.txt | workbuddy -p "总结主要内容"
|
|
252
|
+
workbuddy acp
|
|
253
|
+
workbuddy logout
|
|
254
|
+
`);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function parseArgs(args) {
|
|
258
|
+
let command = 'chat';
|
|
259
|
+
let prompt = '';
|
|
260
|
+
let model = DEFAULT_MODEL;
|
|
261
|
+
let modelExplicit = false;
|
|
262
|
+
let asJson = false;
|
|
263
|
+
let systemPrompt = '';
|
|
264
|
+
let systemExplicit = false;
|
|
265
|
+
let noBrowser = false;
|
|
266
|
+
let includeAllModels = false;
|
|
267
|
+
let staticModels = false;
|
|
268
|
+
let continueSession = false;
|
|
269
|
+
let resumeId = undefined;
|
|
270
|
+
let expectResumeId = false;
|
|
271
|
+
let sessionId = '';
|
|
272
|
+
|
|
273
|
+
const first = args[0];
|
|
274
|
+
if (first === 'login' || first === '--login') {
|
|
275
|
+
command = 'login';
|
|
276
|
+
args = args.slice(1);
|
|
277
|
+
} else if (first === 'logout' || first === '--logout') {
|
|
278
|
+
command = 'logout';
|
|
279
|
+
args = args.slice(1);
|
|
280
|
+
} else if (first === 'status' || first === 'whoami' || first === '--status') {
|
|
281
|
+
command = 'status';
|
|
282
|
+
args = args.slice(1);
|
|
283
|
+
} else if (first === 'models') {
|
|
284
|
+
command = 'models';
|
|
285
|
+
args = args.slice(1);
|
|
286
|
+
} else if (first === 'sessions') {
|
|
287
|
+
command = 'sessions';
|
|
288
|
+
args = args.slice(1);
|
|
289
|
+
} else if (first === 'acp') {
|
|
290
|
+
command = 'acp';
|
|
291
|
+
args = args.slice(1);
|
|
292
|
+
} else if (first === 'continue') {
|
|
293
|
+
command = 'chat';
|
|
294
|
+
continueSession = true;
|
|
295
|
+
args = args.slice(1);
|
|
296
|
+
} else if (first === 'resume') {
|
|
297
|
+
command = 'chat';
|
|
298
|
+
expectResumeId = true;
|
|
299
|
+
args = args.slice(1);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
for (let i = 0; i < args.length; i++) {
|
|
303
|
+
const arg = args[i];
|
|
304
|
+
if (arg === '-h' || arg === '--help') {
|
|
305
|
+
showHelp();
|
|
306
|
+
process.exit(0);
|
|
307
|
+
} else if (arg === '-l' || arg === '--models') {
|
|
308
|
+
command = 'models';
|
|
309
|
+
} else if (arg === '-p' || arg === '--print') {
|
|
310
|
+
// default
|
|
311
|
+
} else if (arg === '--json') {
|
|
312
|
+
asJson = true;
|
|
313
|
+
} else if (arg === '--no-browser') {
|
|
314
|
+
noBrowser = true;
|
|
315
|
+
} else if (arg === '--all') {
|
|
316
|
+
includeAllModels = true;
|
|
317
|
+
} else if (arg === '--static') {
|
|
318
|
+
staticModels = true;
|
|
319
|
+
} else if (arg === '-c' || arg === '--continue') {
|
|
320
|
+
continueSession = true;
|
|
321
|
+
} else if (arg === '-r' || arg === '--resume') {
|
|
322
|
+
const next = args[i + 1];
|
|
323
|
+
if (next && !next.startsWith('-')) {
|
|
324
|
+
resumeId = next;
|
|
325
|
+
i += 1;
|
|
326
|
+
} else {
|
|
327
|
+
resumeId = '';
|
|
328
|
+
}
|
|
329
|
+
} else if (arg.startsWith('--resume=')) {
|
|
330
|
+
resumeId = arg.slice('--resume='.length);
|
|
331
|
+
} else if (arg === '--session-id') {
|
|
332
|
+
sessionId = args[++i] || '';
|
|
333
|
+
} else if (arg.startsWith('--session-id=')) {
|
|
334
|
+
sessionId = arg.slice('--session-id='.length);
|
|
335
|
+
} else if (arg === '-m' || arg === '--model') {
|
|
336
|
+
model = args[++i];
|
|
337
|
+
modelExplicit = true;
|
|
338
|
+
} else if (arg.startsWith('--model=')) {
|
|
339
|
+
model = arg.slice(8);
|
|
340
|
+
modelExplicit = true;
|
|
341
|
+
} else if (arg === '-s' || arg === '--system') {
|
|
342
|
+
systemPrompt = args[++i];
|
|
343
|
+
systemExplicit = true;
|
|
344
|
+
} else if (arg.startsWith('--system=')) {
|
|
345
|
+
systemPrompt = arg.slice(9);
|
|
346
|
+
systemExplicit = true;
|
|
347
|
+
} else if (!arg.startsWith('-')) {
|
|
348
|
+
if (expectResumeId && resumeId === undefined) {
|
|
349
|
+
resumeId = arg;
|
|
350
|
+
expectResumeId = false;
|
|
351
|
+
} else {
|
|
352
|
+
prompt = prompt ? `${prompt} ${arg}` : arg;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Resolve alias
|
|
358
|
+
if (model && MODEL_ALIASES[model.toLowerCase()]) {
|
|
359
|
+
model = MODEL_ALIASES[model.toLowerCase()];
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (resumeId === undefined && expectResumeId) resumeId = '';
|
|
363
|
+
|
|
364
|
+
return {
|
|
365
|
+
command,
|
|
366
|
+
prompt,
|
|
367
|
+
model,
|
|
368
|
+
modelExplicit,
|
|
369
|
+
asJson,
|
|
370
|
+
systemPrompt,
|
|
371
|
+
systemExplicit,
|
|
372
|
+
noBrowser,
|
|
373
|
+
includeAllModels,
|
|
374
|
+
staticModels,
|
|
375
|
+
continueSession,
|
|
376
|
+
resumeId,
|
|
377
|
+
sessionId
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function encodeTranscript(role, t) {
|
|
382
|
+
const domain = role === 'server' ? 'wbipc-s' : 'wbipc-c';
|
|
383
|
+
const parts = [domain, String(t.protocol), t.endpoint, t.clientNonce, t.serverNonce];
|
|
384
|
+
const chunks = [];
|
|
385
|
+
for (const part of parts) {
|
|
386
|
+
const buf = Buffer.from(part, 'utf8');
|
|
387
|
+
const len = Buffer.alloc(4);
|
|
388
|
+
len.writeUInt32BE(buf.length, 0);
|
|
389
|
+
chunks.push(len, buf);
|
|
390
|
+
}
|
|
391
|
+
return Buffer.concat(chunks);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function computeProof(ticket, role, transcript) {
|
|
395
|
+
return crypto.createHmac('sha256', Buffer.from(ticket, 'utf8'))
|
|
396
|
+
.update(encodeTranscript(role, transcript))
|
|
397
|
+
.digest('base64url');
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function ticketIdOf(ticket) {
|
|
401
|
+
return crypto.createHash('sha256').update(ticket, 'utf8').digest('hex').slice(0, 16);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function sleep(ms) {
|
|
405
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function readCliSession() {
|
|
409
|
+
if (!fs.existsSync(AUTH_FILE)) return null;
|
|
410
|
+
try {
|
|
411
|
+
return JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8'));
|
|
412
|
+
} catch {
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function writeCliSession(session) {
|
|
418
|
+
fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });
|
|
419
|
+
fs.writeFileSync(AUTH_FILE, JSON.stringify(session, null, 2) + '\n', { mode: 0o600 });
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function removeCliSession() {
|
|
423
|
+
if (fs.existsSync(AUTH_FILE)) {
|
|
424
|
+
fs.unlinkSync(AUTH_FILE);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function normalizeToken(raw, fallbackDomain = 'www.workbuddy.cn') {
|
|
429
|
+
const now = Date.now();
|
|
430
|
+
const expiresAt = raw.expiresAt || (raw.expiresIn ? now + raw.expiresIn * 1000 : undefined);
|
|
431
|
+
const refreshExpiresAt = raw.refreshExpiresAt || (raw.refreshExpiresIn ? now + raw.refreshExpiresIn * 1000 : undefined);
|
|
432
|
+
return {
|
|
433
|
+
accessToken: raw.accessToken,
|
|
434
|
+
refreshToken: raw.refreshToken,
|
|
435
|
+
tokenType: raw.tokenType,
|
|
436
|
+
domain: raw.domain || fallbackDomain,
|
|
437
|
+
expiresAt,
|
|
438
|
+
refreshExpiresAt,
|
|
439
|
+
lastRefreshTime: now
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function buildDomainHeader(endpoint, auth) {
|
|
444
|
+
try {
|
|
445
|
+
return auth?.domain || new URL(endpoint).host;
|
|
446
|
+
} catch {
|
|
447
|
+
return 'www.workbuddy.cn';
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function buildEnterpriseHeaders(endpoint, auth, account) {
|
|
452
|
+
const headers = {
|
|
453
|
+
'X-Domain': buildDomainHeader(endpoint, auth)
|
|
454
|
+
};
|
|
455
|
+
const enterpriseId = account?.enterpriseId;
|
|
456
|
+
if (enterpriseId) {
|
|
457
|
+
headers['X-Enterprise-Id'] = enterpriseId;
|
|
458
|
+
headers['X-Tenant-Id'] = enterpriseId;
|
|
459
|
+
}
|
|
460
|
+
return headers;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function openExternalUrl(url) {
|
|
464
|
+
return new Promise(resolve => {
|
|
465
|
+
const platform = process.platform;
|
|
466
|
+
let cmd;
|
|
467
|
+
let args;
|
|
468
|
+
if (platform === 'darwin') {
|
|
469
|
+
cmd = 'open';
|
|
470
|
+
args = [url];
|
|
471
|
+
} else if (platform === 'win32') {
|
|
472
|
+
cmd = 'cmd';
|
|
473
|
+
args = ['/c', 'start', '', url];
|
|
474
|
+
} else {
|
|
475
|
+
cmd = 'xdg-open';
|
|
476
|
+
args = [url];
|
|
477
|
+
}
|
|
478
|
+
try {
|
|
479
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
480
|
+
child.on('error', () => resolve(false));
|
|
481
|
+
child.unref();
|
|
482
|
+
resolve(true);
|
|
483
|
+
} catch {
|
|
484
|
+
resolve(false);
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async function fetchJson(url, options = {}) {
|
|
490
|
+
const controller = new AbortController();
|
|
491
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 15000);
|
|
492
|
+
try {
|
|
493
|
+
const res = await fetch(url, {
|
|
494
|
+
...options,
|
|
495
|
+
signal: controller.signal
|
|
496
|
+
});
|
|
497
|
+
const text = await res.text();
|
|
498
|
+
let json = null;
|
|
499
|
+
try {
|
|
500
|
+
json = JSON.parse(text);
|
|
501
|
+
} catch {}
|
|
502
|
+
return { status: res.status, ok: res.ok, json, text };
|
|
503
|
+
} finally {
|
|
504
|
+
clearTimeout(timer);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
async function loginWorkBuddy(options = {}) {
|
|
509
|
+
const endpoint = DEFAULT_ENDPOINT;
|
|
510
|
+
const noAuthHeaders = {
|
|
511
|
+
'Content-Type': 'application/json',
|
|
512
|
+
'X-Domain': buildDomainHeader(endpoint),
|
|
513
|
+
'X-No-Authorization': 'true',
|
|
514
|
+
'X-No-User-Id': 'true',
|
|
515
|
+
'X-No-Enterprise-Id': 'true',
|
|
516
|
+
'X-No-Department-Info': 'true'
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
const stateRes = await fetchJson(`${endpoint}${AUTH_PREFIX}/auth/state?platform=${AUTH_PLATFORM}`, {
|
|
520
|
+
method: 'POST',
|
|
521
|
+
headers: noAuthHeaders,
|
|
522
|
+
body: '{}'
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
if (!stateRes.ok || !stateRes.json?.data?.state || !stateRes.json?.data?.authUrl) {
|
|
526
|
+
throw new Error(`获取登录链接失败 (HTTP ${stateRes.status}): ${stateRes.json?.msg || stateRes.text}`);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
const { state, authUrl } = stateRes.json.data;
|
|
530
|
+
console.error(`请在浏览器中完成 WorkBuddy 登录:\n${authUrl}\n`);
|
|
531
|
+
if (!options.noBrowser) {
|
|
532
|
+
const opened = await openExternalUrl(authUrl);
|
|
533
|
+
if (!opened) {
|
|
534
|
+
console.error('未能自动打开浏览器,请手动复制上方链接到浏览器打开。');
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
console.error('等待登录完成...');
|
|
538
|
+
|
|
539
|
+
const deadline = Date.now() + LOGIN_TIMEOUT_MS;
|
|
540
|
+
let tokenData = null;
|
|
541
|
+
|
|
542
|
+
while (Date.now() < deadline) {
|
|
543
|
+
await sleep(LOGIN_POLL_INTERVAL_MS);
|
|
544
|
+
const tokenRes = await fetchJson(
|
|
545
|
+
`${endpoint}${AUTH_PREFIX}/auth/token?state=${encodeURIComponent(state)}`,
|
|
546
|
+
{ headers: noAuthHeaders }
|
|
547
|
+
);
|
|
548
|
+
const body = tokenRes.json;
|
|
549
|
+
if (body?.data?.accessToken) {
|
|
550
|
+
tokenData = normalizeToken(body.data, buildDomainHeader(endpoint));
|
|
551
|
+
break;
|
|
552
|
+
}
|
|
553
|
+
if (body?.code === LOGIN_TOKEN_PENDING_CODE) {
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
throw new Error(`登录轮询失败 (HTTP ${tokenRes.status}): ${body?.msg || tokenRes.text}`);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
if (!tokenData) {
|
|
560
|
+
throw new Error('登录超时(5 分钟内未完成登录)');
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
let account = null;
|
|
564
|
+
const authHeaders = {
|
|
565
|
+
...buildEnterpriseHeaders(endpoint, tokenData),
|
|
566
|
+
'Authorization': `Bearer ${tokenData.accessToken}`,
|
|
567
|
+
'X-No-User-Id': 'true',
|
|
568
|
+
'X-No-Enterprise-Id': 'true',
|
|
569
|
+
'X-No-Department-Info': 'true'
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
const accountDeadline = Math.min(deadline, Date.now() + 30000);
|
|
573
|
+
while (Date.now() < accountDeadline) {
|
|
574
|
+
const accRes = await fetchJson(
|
|
575
|
+
`${endpoint}${AUTH_PREFIX}/login/account?state=${encodeURIComponent(state)}`,
|
|
576
|
+
{ headers: authHeaders }
|
|
577
|
+
);
|
|
578
|
+
if (accRes.json?.data) {
|
|
579
|
+
account = accRes.json.data;
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
if (accRes.json?.code === LOGIN_ACCOUNT_PENDING_CODE) {
|
|
583
|
+
await sleep(1000);
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
break;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
if (!account) {
|
|
590
|
+
const listRes = await fetchJson(`${endpoint}${AUTH_PREFIX}/accounts`, {
|
|
591
|
+
headers: {
|
|
592
|
+
...buildEnterpriseHeaders(endpoint, tokenData),
|
|
593
|
+
'Authorization': `Bearer ${tokenData.accessToken}`
|
|
594
|
+
}
|
|
595
|
+
});
|
|
596
|
+
const accounts = listRes.json?.data?.accounts;
|
|
597
|
+
if (Array.isArray(accounts) && accounts.length > 0) {
|
|
598
|
+
account = accounts.find(a => a.lastLogin) || accounts[0];
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const session = {
|
|
603
|
+
endpoint,
|
|
604
|
+
auth: tokenData,
|
|
605
|
+
account: account ? {
|
|
606
|
+
uid: account.uid,
|
|
607
|
+
nickname: account.nickname || account.name || account.username,
|
|
608
|
+
enterpriseId: account.enterpriseId,
|
|
609
|
+
type: account.type
|
|
610
|
+
} : null,
|
|
611
|
+
updatedAt: Date.now()
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
writeCliSession(session);
|
|
615
|
+
return session;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
async function refreshCliSession(session) {
|
|
619
|
+
const endpoint = session.endpoint || DEFAULT_ENDPOINT;
|
|
620
|
+
const refreshToken = session.auth?.refreshToken;
|
|
621
|
+
if (!refreshToken) {
|
|
622
|
+
throw new Error('当前凭据缺少 refreshToken,请重新运行 "workbuddy login"');
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const res = await fetchJson(`${endpoint}${AUTH_PREFIX}/auth/token/refresh`, {
|
|
626
|
+
method: 'POST',
|
|
627
|
+
headers: {
|
|
628
|
+
...buildEnterpriseHeaders(endpoint, session.auth, session.account),
|
|
629
|
+
'X-Refresh-Token': refreshToken,
|
|
630
|
+
'X-Auth-Refresh-Source': 'plugin'
|
|
631
|
+
},
|
|
632
|
+
body: '{}'
|
|
633
|
+
});
|
|
634
|
+
|
|
635
|
+
if (!res.ok || !res.json?.data?.accessToken) {
|
|
636
|
+
throw new Error(`刷新登录态失败 (HTTP ${res.status}): ${res.json?.msg || res.text},请重新运行 "workbuddy login"`);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
const updated = {
|
|
640
|
+
...session,
|
|
641
|
+
auth: normalizeToken(res.json.data, session.auth?.domain || buildDomainHeader(endpoint)),
|
|
642
|
+
updatedAt: Date.now()
|
|
643
|
+
};
|
|
644
|
+
writeCliSession(updated);
|
|
645
|
+
return updated;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
async function logoutWorkBuddy() {
|
|
649
|
+
const session = readCliSession();
|
|
650
|
+
if (!session) {
|
|
651
|
+
return { hadSession: false, serverRevoked: false };
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
let serverRevoked = false;
|
|
655
|
+
const endpoint = session.endpoint || DEFAULT_ENDPOINT;
|
|
656
|
+
const refreshToken = session.auth?.refreshToken;
|
|
657
|
+
|
|
658
|
+
if (refreshToken) {
|
|
659
|
+
try {
|
|
660
|
+
const res = await fetchJson(`${endpoint}${AUTH_PREFIX}/auth/logout`, {
|
|
661
|
+
method: 'POST',
|
|
662
|
+
headers: {
|
|
663
|
+
...buildEnterpriseHeaders(endpoint, session.auth, session.account),
|
|
664
|
+
'X-Refresh-Token': refreshToken,
|
|
665
|
+
'X-Auth-Refresh-Source': 'plugin',
|
|
666
|
+
'X-No-Authorization': 'true'
|
|
667
|
+
},
|
|
668
|
+
body: '{}'
|
|
669
|
+
});
|
|
670
|
+
serverRevoked = res.ok;
|
|
671
|
+
} catch {
|
|
672
|
+
serverRevoked = false;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
removeCliSession();
|
|
677
|
+
return { hadSession: true, serverRevoked };
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function createSseAccumulator(onDelta, onReasoning) {
|
|
681
|
+
let text = '';
|
|
682
|
+
let reasoning = '';
|
|
683
|
+
let raw = '';
|
|
684
|
+
const toolCalls = new Map();
|
|
685
|
+
|
|
686
|
+
const absorbMessage = message => {
|
|
687
|
+
if (!message) return;
|
|
688
|
+
if (message.content) {
|
|
689
|
+
text += message.content;
|
|
690
|
+
onDelta?.(message.content);
|
|
691
|
+
}
|
|
692
|
+
if (message.reasoning_content) {
|
|
693
|
+
reasoning += message.reasoning_content;
|
|
694
|
+
onReasoning?.(message.reasoning_content);
|
|
695
|
+
}
|
|
696
|
+
for (const call of message.tool_calls || []) {
|
|
697
|
+
const idx = call.index ?? toolCalls.size;
|
|
698
|
+
toolCalls.set(idx, {
|
|
699
|
+
id: call.id || `call_${idx}`,
|
|
700
|
+
name: call.function?.name || '',
|
|
701
|
+
arguments: call.function?.arguments || ''
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
|
|
706
|
+
return {
|
|
707
|
+
pushLine(line) {
|
|
708
|
+
raw += `${line}\n`;
|
|
709
|
+
const trimmed = line.trim();
|
|
710
|
+
if (!trimmed.startsWith('data:')) return;
|
|
711
|
+
const dataStr = trimmed.slice(5).trim();
|
|
712
|
+
if (!dataStr || dataStr === '[DONE]') return;
|
|
713
|
+
let parsed;
|
|
714
|
+
try {
|
|
715
|
+
parsed = JSON.parse(dataStr);
|
|
716
|
+
} catch {
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
if (parsed.error) {
|
|
720
|
+
const message = parsed.error.message || parsed.error.msg || JSON.stringify(parsed.error);
|
|
721
|
+
throw new Error(message);
|
|
722
|
+
}
|
|
723
|
+
const choice = parsed.choices?.[0];
|
|
724
|
+
const delta = choice?.delta;
|
|
725
|
+
if (delta?.content) {
|
|
726
|
+
text += delta.content;
|
|
727
|
+
onDelta?.(delta.content);
|
|
728
|
+
}
|
|
729
|
+
if (delta?.reasoning_content) {
|
|
730
|
+
reasoning += delta.reasoning_content;
|
|
731
|
+
onReasoning?.(delta.reasoning_content);
|
|
732
|
+
}
|
|
733
|
+
for (const call of delta?.tool_calls || []) {
|
|
734
|
+
const idx = call.index ?? 0;
|
|
735
|
+
const current = toolCalls.get(idx) || { id: '', name: '', arguments: '' };
|
|
736
|
+
if (call.id) current.id = call.id;
|
|
737
|
+
if (call.function?.name) current.name += call.function.name;
|
|
738
|
+
if (call.function?.arguments) current.arguments += call.function.arguments;
|
|
739
|
+
toolCalls.set(idx, current);
|
|
740
|
+
}
|
|
741
|
+
if (!delta && choice?.message) absorbMessage(choice.message);
|
|
742
|
+
},
|
|
743
|
+
finish() {
|
|
744
|
+
if (!text && toolCalls.size === 0) {
|
|
745
|
+
const body = raw.trim();
|
|
746
|
+
if (body.startsWith('{')) {
|
|
747
|
+
try {
|
|
748
|
+
const parsed = JSON.parse(body);
|
|
749
|
+
absorbMessage(parsed.choices?.[0]?.message);
|
|
750
|
+
} catch {}
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
return {
|
|
754
|
+
text,
|
|
755
|
+
reasoning,
|
|
756
|
+
toolCalls: [...toolCalls.values()].filter(call => call.name).map((call, index) => ({
|
|
757
|
+
...call,
|
|
758
|
+
id: call.id || `call_${index}`
|
|
759
|
+
}))
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function parseSseCompletion(raw) {
|
|
766
|
+
const acc = createSseAccumulator();
|
|
767
|
+
for (const line of String(raw || '').split(/\n/)) acc.pushLine(line);
|
|
768
|
+
return acc.finish();
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
async function readSseResponse(res, onDelta, onReasoning) {
|
|
772
|
+
if (!onDelta && !onReasoning) return parseSseCompletion(await res.text());
|
|
773
|
+
const acc = createSseAccumulator(onDelta, onReasoning);
|
|
774
|
+
if (!res.body?.getReader) return parseSseCompletion(await res.text());
|
|
775
|
+
const reader = res.body.getReader();
|
|
776
|
+
const decoder = new TextDecoder();
|
|
777
|
+
let buf = '';
|
|
778
|
+
while (true) {
|
|
779
|
+
const { done, value } = await reader.read();
|
|
780
|
+
if (done) break;
|
|
781
|
+
buf += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');
|
|
782
|
+
const lines = buf.split('\n');
|
|
783
|
+
buf = lines.pop() ?? '';
|
|
784
|
+
for (const line of lines) acc.pushLine(line);
|
|
785
|
+
}
|
|
786
|
+
if (buf) acc.pushLine(buf);
|
|
787
|
+
return acc.finish();
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function mockComplete({ messages, signal, onDelta }) {
|
|
791
|
+
const lastUser = [...messages].reverse().find(message => message.role === 'user');
|
|
792
|
+
const userText = typeof lastUser?.content === 'string' ? lastUser.content : '';
|
|
793
|
+
const hasToolResult = messages.some(message => message.role === 'tool');
|
|
794
|
+
if (!hasToolResult && userText.includes('TOOL')) {
|
|
795
|
+
return Promise.resolve({
|
|
796
|
+
text: '',
|
|
797
|
+
reasoning: '',
|
|
798
|
+
toolCalls: [{ id: 'call_mock', name: 'read_file', arguments: JSON.stringify({ path: 'README.md' }) }]
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
if (userText.includes('SLOW')) {
|
|
802
|
+
return new Promise((resolve, reject) => {
|
|
803
|
+
const timer = setTimeout(() => resolve({ text: 'mock:slow-finished', reasoning: '', toolCalls: [] }), 30000);
|
|
804
|
+
const abort = () => {
|
|
805
|
+
clearTimeout(timer);
|
|
806
|
+
const err = new Error('aborted');
|
|
807
|
+
err.name = 'AbortError';
|
|
808
|
+
reject(err);
|
|
809
|
+
};
|
|
810
|
+
if (signal?.aborted) abort();
|
|
811
|
+
else signal?.addEventListener('abort', abort, { once: true });
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
const text = hasToolResult ? 'mock-after-tool' : `mock:${userText.slice(0, 200)}`;
|
|
815
|
+
onDelta?.(text);
|
|
816
|
+
return Promise.resolve({ text, reasoning: '', toolCalls: [] });
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
async function fetchDirectApi(session, method, apiPath, body) {
|
|
820
|
+
let activeSession = session;
|
|
821
|
+
if (
|
|
822
|
+
activeSession.auth?.refreshToken &&
|
|
823
|
+
activeSession.auth?.expiresAt &&
|
|
824
|
+
Date.now() >= activeSession.auth.expiresAt - 60000
|
|
825
|
+
) {
|
|
826
|
+
activeSession = await refreshCliSession(activeSession);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
const sendOnce = async s => {
|
|
830
|
+
const endpoint = (s.endpoint || DEFAULT_ENDPOINT).replace(/\/+$/, '');
|
|
831
|
+
const headers = {
|
|
832
|
+
'Accept': 'application/json',
|
|
833
|
+
'Authorization': `Bearer ${s.auth.accessToken}`
|
|
834
|
+
};
|
|
835
|
+
if (s.account?.uid) {
|
|
836
|
+
headers['X-User-Id'] = s.account.uid;
|
|
837
|
+
}
|
|
838
|
+
if (s.account?.enterpriseId) {
|
|
839
|
+
headers['X-Enterprise-Id'] = s.account.enterpriseId;
|
|
840
|
+
headers['X-Tenant-Id'] = s.account.enterpriseId;
|
|
841
|
+
}
|
|
842
|
+
const init = { method, headers };
|
|
843
|
+
if (body !== undefined && method !== 'GET' && method !== 'HEAD') {
|
|
844
|
+
headers['Content-Type'] = 'application/json';
|
|
845
|
+
init.body = JSON.stringify(body);
|
|
846
|
+
}
|
|
847
|
+
return fetchJson(`${endpoint}${apiPath}`, init);
|
|
848
|
+
};
|
|
849
|
+
|
|
850
|
+
let res = await sendOnce(activeSession);
|
|
851
|
+
if (res.status === 401 && activeSession.auth?.refreshToken) {
|
|
852
|
+
activeSession = await refreshCliSession(activeSession);
|
|
853
|
+
res = await sendOnce(activeSession);
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
if (!res.ok) {
|
|
857
|
+
throw new Error(`HTTP ${res.status}: ${res.json?.msg || res.json?.message || res.text}`);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
return res.json?.data ?? res.json;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
async function fetchIpcApi(method, apiPath, body) {
|
|
864
|
+
const discoveryFile = path.join(os.homedir(), '.workbuddy', 'wbipc', 'endpoint.json');
|
|
865
|
+
if (!fs.existsSync(discoveryFile)) {
|
|
866
|
+
throw new Error('WorkBuddy 桌面端未运行');
|
|
867
|
+
}
|
|
868
|
+
const discovery = JSON.parse(fs.readFileSync(discoveryFile, 'utf8'));
|
|
869
|
+
|
|
870
|
+
return new Promise((resolve, reject) => {
|
|
871
|
+
const socket = net.connect({ path: discovery.endpoint });
|
|
872
|
+
let buffer = Buffer.alloc(0);
|
|
873
|
+
const clientNonce = crypto.randomBytes(16).toString('base64url');
|
|
874
|
+
const send = frame => socket.write(JSON.stringify(frame) + '\n');
|
|
875
|
+
|
|
876
|
+
const timeoutTimer = setTimeout(() => {
|
|
877
|
+
socket.destroy();
|
|
878
|
+
reject(new Error('WBIPC 请求超时 (15s)'));
|
|
879
|
+
}, 15000);
|
|
880
|
+
|
|
881
|
+
socket.on('connect', () => {
|
|
882
|
+
send({
|
|
883
|
+
type: 'session_hello',
|
|
884
|
+
protocol_min: PROTOCOL_VERSION,
|
|
885
|
+
protocol_max: PROTOCOL_VERSION,
|
|
886
|
+
client_nonce: clientNonce,
|
|
887
|
+
ticket_id: ticketIdOf(discovery.ticket),
|
|
888
|
+
client: { kind: 'cli', id: 'workbuddy-cli' }
|
|
889
|
+
});
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
socket.on('data', chunk => {
|
|
893
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
894
|
+
for (;;) {
|
|
895
|
+
const nl = buffer.indexOf(0x0a);
|
|
896
|
+
if (nl < 0) break;
|
|
897
|
+
const line = buffer.subarray(0, nl);
|
|
898
|
+
buffer = buffer.subarray(nl + 1);
|
|
899
|
+
if (line.length === 0) continue;
|
|
900
|
+
|
|
901
|
+
let f;
|
|
902
|
+
try {
|
|
903
|
+
f = JSON.parse(line.toString('utf8'));
|
|
904
|
+
} catch {
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
if (f.type === 'session_challenge') {
|
|
909
|
+
send({
|
|
910
|
+
type: 'session_prove',
|
|
911
|
+
client_proof: computeProof(discovery.ticket, 'client', {
|
|
912
|
+
protocol: PROTOCOL_VERSION,
|
|
913
|
+
endpoint: discovery.endpoint,
|
|
914
|
+
clientNonce,
|
|
915
|
+
serverNonce: f.server_nonce
|
|
916
|
+
})
|
|
917
|
+
});
|
|
918
|
+
} else if (f.type === 'session_hello_ack') {
|
|
919
|
+
send({ jsonrpc: '2.0', id: 1, method: 'broker/GetPipe', params: { pipe: 'wb.request' } });
|
|
920
|
+
} else if (f.id === 1) {
|
|
921
|
+
if (f.error) {
|
|
922
|
+
clearTimeout(timeoutTimer);
|
|
923
|
+
socket.end();
|
|
924
|
+
return reject(new Error(`GetPipe 错误: ${f.error.message}`));
|
|
925
|
+
}
|
|
926
|
+
const channel = f.result?.channel;
|
|
927
|
+
const params = {
|
|
928
|
+
method,
|
|
929
|
+
path: apiPath,
|
|
930
|
+
headers: { 'accept': 'application/json' }
|
|
931
|
+
};
|
|
932
|
+
if (body !== undefined && method !== 'GET' && method !== 'HEAD') {
|
|
933
|
+
params.headers['content-type'] = 'application/json';
|
|
934
|
+
params.body_b64 = Buffer.from(JSON.stringify(body)).toString('base64');
|
|
935
|
+
}
|
|
936
|
+
send({ jsonrpc: '2.0', id: 2, method: `${channel}/http.fetch`, mode: 'call', params });
|
|
937
|
+
} else if (f.id === 2) {
|
|
938
|
+
clearTimeout(timeoutTimer);
|
|
939
|
+
socket.end();
|
|
940
|
+
if (f.error) return reject(new Error(f.error.message));
|
|
941
|
+
const raw = f.result?.body_b64 ? Buffer.from(f.result.body_b64, 'base64').toString('utf8') : '';
|
|
942
|
+
let parsed = null;
|
|
943
|
+
try { parsed = JSON.parse(raw); } catch {}
|
|
944
|
+
if (f.result?.status && f.result.status >= 400) {
|
|
945
|
+
return reject(new Error(`HTTP ${f.result.status}: ${parsed?.msg || parsed?.message || raw}`));
|
|
946
|
+
}
|
|
947
|
+
resolve(parsed?.data ?? parsed);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
});
|
|
951
|
+
|
|
952
|
+
socket.on('error', err => {
|
|
953
|
+
clearTimeout(timeoutTimer);
|
|
954
|
+
reject(new Error(`连接 WorkBuddy 套接字失败: ${err.message}`));
|
|
955
|
+
});
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
async function scanAvailableModels(options = {}) {
|
|
960
|
+
const cliSession = readCliSession();
|
|
961
|
+
const discoveryFile = path.join(os.homedir(), '.workbuddy', 'wbipc', 'endpoint.json');
|
|
962
|
+
const hasIpc = fs.existsSync(discoveryFile);
|
|
963
|
+
|
|
964
|
+
if (!cliSession?.auth?.accessToken && !hasIpc) {
|
|
965
|
+
return { source: 'static', models: null, reason: '未登录且桌面端未运行' };
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
const enterpriseId = cliSession?.account?.enterpriseId;
|
|
969
|
+
const candidatePaths = enterpriseId
|
|
970
|
+
? [`/v2/enterprises/${encodeURIComponent(enterpriseId)}/models`, '/v2/enterprises/personal/models']
|
|
971
|
+
: ['/v2/enterprises/personal/models'];
|
|
972
|
+
|
|
973
|
+
let payload = null;
|
|
974
|
+
let lastErr = null;
|
|
975
|
+
for (const apiPath of candidatePaths) {
|
|
976
|
+
try {
|
|
977
|
+
payload = cliSession?.auth?.accessToken
|
|
978
|
+
? await fetchDirectApi(cliSession, 'GET', apiPath)
|
|
979
|
+
: await fetchIpcApi('GET', apiPath);
|
|
980
|
+
if (payload) break;
|
|
981
|
+
} catch (err) {
|
|
982
|
+
lastErr = err;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
if (!payload) {
|
|
987
|
+
throw lastErr || new Error('获取模型列表失败');
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
const rawList = Array.isArray(payload.models) ? payload.models : Array.isArray(payload) ? payload : [];
|
|
991
|
+
const excludedTags = new Set(['text-to-image']);
|
|
992
|
+
const models = options.includeAll
|
|
993
|
+
? rawList
|
|
994
|
+
: rawList.filter(m => {
|
|
995
|
+
if (!m || typeof m.id !== 'string' || !m.id) return false;
|
|
996
|
+
const tags = Array.isArray(m.tags) ? m.tags.map(String) : [];
|
|
997
|
+
return !tags.some(t => excludedTags.has(t));
|
|
998
|
+
});
|
|
999
|
+
|
|
1000
|
+
return { source: cliSession?.auth?.accessToken ? 'remote-direct' : 'remote-ipc', models };
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
function buildReverseAliasMap() {
|
|
1004
|
+
const map = new Map();
|
|
1005
|
+
for (const [alias, target] of Object.entries(MODEL_ALIASES)) {
|
|
1006
|
+
if (alias === target) continue;
|
|
1007
|
+
if (!map.has(target)) map.set(target, []);
|
|
1008
|
+
map.get(target).push(alias);
|
|
1009
|
+
}
|
|
1010
|
+
return map;
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
function printScannedModels(models, source) {
|
|
1014
|
+
const aliasMap = buildReverseAliasMap();
|
|
1015
|
+
console.log(`WorkBuddy 可用模型列表 (来源: ${source}, 共 ${models.length} 个):\n`);
|
|
1016
|
+
for (const m of models) {
|
|
1017
|
+
const aliases = aliasMap.get(m.id);
|
|
1018
|
+
const aliasText = aliases?.length ? ` (简写: ${aliases.join(', ')})` : '';
|
|
1019
|
+
const credits = m.credits ? ` [${m.credits}]` : '';
|
|
1020
|
+
const caps = [];
|
|
1021
|
+
if (m.supportsReasoning) caps.push('推理');
|
|
1022
|
+
if (m.supportsImages) caps.push('视觉');
|
|
1023
|
+
if (m.supportsToolCall) caps.push('工具');
|
|
1024
|
+
if (Array.isArray(m.tags) && m.tags.length) caps.push(m.tags.join(','));
|
|
1025
|
+
const capText = caps.length ? ` (${caps.join(' / ')})` : '';
|
|
1026
|
+
const title = m.name && m.name !== m.id ? ` — ${m.name}` : '';
|
|
1027
|
+
console.log(` ${m.id}${aliasText}${title}${credits}${capText}`);
|
|
1028
|
+
const desc = m.descriptionZh || m.descriptionEn;
|
|
1029
|
+
if (desc) {
|
|
1030
|
+
console.log(` ${desc}`);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
console.log(`\n提示: 使用 workbuddy -m <model_id> "..." 即可直接调用任意新模型,无需等待 CLI 更新。`);
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
function chatPayload(userPrompt, options = {}) {
|
|
1037
|
+
const { model = DEFAULT_MODEL, systemPrompt, tools } = options;
|
|
1038
|
+
const messages = options.messages
|
|
1039
|
+
? options.messages.map(message => {
|
|
1040
|
+
const next = { role: message.role, content: message.content ?? '' };
|
|
1041
|
+
if (message.tool_calls) next.tool_calls = message.tool_calls;
|
|
1042
|
+
if (message.tool_call_id) next.tool_call_id = message.tool_call_id;
|
|
1043
|
+
if (message.name) next.name = message.name;
|
|
1044
|
+
return next;
|
|
1045
|
+
})
|
|
1046
|
+
: [];
|
|
1047
|
+
if (!options.messages) {
|
|
1048
|
+
if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });
|
|
1049
|
+
if (userPrompt) messages.push({ role: 'user', content: userPrompt });
|
|
1050
|
+
} else if (!tools?.length) {
|
|
1051
|
+
for (let i = 0; i < messages.length; i += 1) {
|
|
1052
|
+
if (messages[i].role === 'tool') {
|
|
1053
|
+
messages.splice(i, 1);
|
|
1054
|
+
i -= 1;
|
|
1055
|
+
continue;
|
|
1056
|
+
}
|
|
1057
|
+
if (messages[i].tool_calls) delete messages[i].tool_calls;
|
|
1058
|
+
if (!messages[i].content) {
|
|
1059
|
+
messages.splice(i, 1);
|
|
1060
|
+
i -= 1;
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
const payload = { model, messages, stream: true };
|
|
1065
|
+
if (tools?.length) payload.tools = tools;
|
|
1066
|
+
return payload;
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
function linkAbortSignals(external, timeoutMs) {
|
|
1070
|
+
const controller = new AbortController();
|
|
1071
|
+
const seconds = Math.round(timeoutMs / 1000);
|
|
1072
|
+
const timer = setTimeout(() => {
|
|
1073
|
+
const err = new Error(`请求超时 (${seconds}s)`);
|
|
1074
|
+
err.name = 'TimeoutError';
|
|
1075
|
+
controller.abort(err);
|
|
1076
|
+
}, timeoutMs);
|
|
1077
|
+
const onAbort = () => controller.abort(external.reason);
|
|
1078
|
+
if (external) {
|
|
1079
|
+
if (external.aborted) controller.abort(external.reason);
|
|
1080
|
+
else external.addEventListener('abort', onAbort, { once: true });
|
|
1081
|
+
}
|
|
1082
|
+
return {
|
|
1083
|
+
signal: controller.signal,
|
|
1084
|
+
close() {
|
|
1085
|
+
clearTimeout(timer);
|
|
1086
|
+
external?.removeEventListener('abort', onAbort);
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
async function callWorkBuddyDirect(session, userPrompt, options = {}) {
|
|
1092
|
+
let activeSession = session;
|
|
1093
|
+
if (
|
|
1094
|
+
activeSession.auth?.refreshToken &&
|
|
1095
|
+
activeSession.auth?.expiresAt &&
|
|
1096
|
+
Date.now() >= activeSession.auth.expiresAt - 60000
|
|
1097
|
+
) {
|
|
1098
|
+
activeSession = await refreshCliSession(activeSession);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
const payload = chatPayload(userPrompt, options);
|
|
1102
|
+
const timeoutMs = options.timeoutMs || 60000;
|
|
1103
|
+
|
|
1104
|
+
const sendRequest = async s => {
|
|
1105
|
+
const endpoint = (s.endpoint || DEFAULT_ENDPOINT).replace(/\/+$/, '');
|
|
1106
|
+
const headers = {
|
|
1107
|
+
'Content-Type': 'application/json',
|
|
1108
|
+
'Accept': 'text/event-stream',
|
|
1109
|
+
'Authorization': `Bearer ${s.auth.accessToken}`
|
|
1110
|
+
};
|
|
1111
|
+
if (s.account?.uid) {
|
|
1112
|
+
headers['X-User-Id'] = s.account.uid;
|
|
1113
|
+
}
|
|
1114
|
+
if (s.account?.enterpriseId) {
|
|
1115
|
+
headers['X-Enterprise-Id'] = s.account.enterpriseId;
|
|
1116
|
+
headers['X-Tenant-Id'] = s.account.enterpriseId;
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
const linked = linkAbortSignals(options.signal, timeoutMs);
|
|
1120
|
+
try {
|
|
1121
|
+
const res = await fetch(`${endpoint}/v2/chat/completions`, {
|
|
1122
|
+
method: 'POST',
|
|
1123
|
+
headers,
|
|
1124
|
+
body: JSON.stringify(payload),
|
|
1125
|
+
signal: linked.signal
|
|
1126
|
+
});
|
|
1127
|
+
if (!res.ok) {
|
|
1128
|
+
const raw = await res.text();
|
|
1129
|
+
return { status: res.status, raw, completion: null };
|
|
1130
|
+
}
|
|
1131
|
+
const completion = await readSseResponse(res, options.onDelta, options.onReasoning);
|
|
1132
|
+
return { status: res.status, raw: '', completion };
|
|
1133
|
+
} catch (err) {
|
|
1134
|
+
if (err?.name === 'AbortError' || err?.name === 'TimeoutError' || linked.signal.aborted) {
|
|
1135
|
+
if (options.signal?.aborted) {
|
|
1136
|
+
const aborted = new Error('cancelled');
|
|
1137
|
+
aborted.name = 'AbortError';
|
|
1138
|
+
throw aborted;
|
|
1139
|
+
}
|
|
1140
|
+
throw new Error(linked.signal.reason?.message || `请求超时 (${Math.round(timeoutMs / 1000)}s)`);
|
|
1141
|
+
}
|
|
1142
|
+
throw err;
|
|
1143
|
+
} finally {
|
|
1144
|
+
linked.close();
|
|
1145
|
+
}
|
|
1146
|
+
};
|
|
1147
|
+
|
|
1148
|
+
let res = await sendRequest(activeSession);
|
|
1149
|
+
if (res.status === 401 && activeSession.auth?.refreshToken) {
|
|
1150
|
+
activeSession = await refreshCliSession(activeSession);
|
|
1151
|
+
res = await sendRequest(activeSession);
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
if (res.status >= 400) {
|
|
1155
|
+
let errorText = `HTTP ${res.status}`;
|
|
1156
|
+
try {
|
|
1157
|
+
const errJson = JSON.parse(res.raw);
|
|
1158
|
+
errorText += `: ${errJson.msg || errJson.message || res.raw}`;
|
|
1159
|
+
} catch {
|
|
1160
|
+
if (res.raw) errorText += `: ${res.raw}`;
|
|
1161
|
+
}
|
|
1162
|
+
throw new Error(errorText);
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
return res.completion;
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
async function callWorkBuddy(userPrompt, options = {}) {
|
|
1169
|
+
if (process.env.WORKBUDDY_ACP_MOCK === '1') {
|
|
1170
|
+
return mockComplete({
|
|
1171
|
+
messages: options.messages || chatPayload(userPrompt, options).messages,
|
|
1172
|
+
signal: options.signal,
|
|
1173
|
+
onDelta: options.onDelta
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
const cliSession = readCliSession();
|
|
1178
|
+
if (cliSession?.auth?.accessToken) {
|
|
1179
|
+
return callWorkBuddyDirect(cliSession, userPrompt, options);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
const discoveryFile = path.join(os.homedir(), '.workbuddy', 'wbipc', 'endpoint.json');
|
|
1183
|
+
if (!fs.existsSync(discoveryFile)) {
|
|
1184
|
+
throw new Error('未登录且 WorkBuddy 桌面端未运行。请先运行 "workbuddy login" 登录,或启动 WorkBuddy 桌面端。');
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
let discovery;
|
|
1188
|
+
try {
|
|
1189
|
+
discovery = JSON.parse(fs.readFileSync(discoveryFile, 'utf8'));
|
|
1190
|
+
} catch (err) {
|
|
1191
|
+
throw new Error(`读取 WBIPC endpoint.json 失败: ${err.message}`);
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
const payload = chatPayload(userPrompt, options);
|
|
1195
|
+
const timeoutMs = options.timeoutMs || 60000;
|
|
1196
|
+
|
|
1197
|
+
return new Promise((resolve, reject) => {
|
|
1198
|
+
const socket = net.connect({ path: discovery.endpoint });
|
|
1199
|
+
let buffer = Buffer.alloc(0);
|
|
1200
|
+
const clientNonce = crypto.randomBytes(16).toString('base64url');
|
|
1201
|
+
const send = frame => socket.write(JSON.stringify(frame) + '\n');
|
|
1202
|
+
let settled = false;
|
|
1203
|
+
let timeoutTimer;
|
|
1204
|
+
const finish = (fn, value) => {
|
|
1205
|
+
if (settled) return;
|
|
1206
|
+
settled = true;
|
|
1207
|
+
clearTimeout(timeoutTimer);
|
|
1208
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
1209
|
+
fn(value);
|
|
1210
|
+
};
|
|
1211
|
+
const onAbort = () => {
|
|
1212
|
+
socket.destroy();
|
|
1213
|
+
const err = new Error('cancelled');
|
|
1214
|
+
err.name = 'AbortError';
|
|
1215
|
+
finish(reject, err);
|
|
1216
|
+
};
|
|
1217
|
+
if (options.signal?.aborted) {
|
|
1218
|
+
onAbort();
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
1222
|
+
|
|
1223
|
+
timeoutTimer = setTimeout(() => {
|
|
1224
|
+
socket.destroy();
|
|
1225
|
+
finish(reject, new Error(`请求超时 (${Math.round(timeoutMs / 1000)}s)`));
|
|
1226
|
+
}, timeoutMs);
|
|
1227
|
+
|
|
1228
|
+
socket.on('connect', () => {
|
|
1229
|
+
send({
|
|
1230
|
+
type: 'session_hello',
|
|
1231
|
+
protocol_min: PROTOCOL_VERSION,
|
|
1232
|
+
protocol_max: PROTOCOL_VERSION,
|
|
1233
|
+
client_nonce: clientNonce,
|
|
1234
|
+
ticket_id: ticketIdOf(discovery.ticket),
|
|
1235
|
+
client: { kind: 'cli', id: 'workbuddy-cli' }
|
|
1236
|
+
});
|
|
1237
|
+
});
|
|
1238
|
+
|
|
1239
|
+
socket.on('data', chunk => {
|
|
1240
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
1241
|
+
for (;;) {
|
|
1242
|
+
const nl = buffer.indexOf(0x0a);
|
|
1243
|
+
if (nl < 0) break;
|
|
1244
|
+
const line = buffer.subarray(0, nl);
|
|
1245
|
+
buffer = buffer.subarray(nl + 1);
|
|
1246
|
+
if (line.length === 0) continue;
|
|
1247
|
+
|
|
1248
|
+
let f;
|
|
1249
|
+
try {
|
|
1250
|
+
f = JSON.parse(line.toString('utf8'));
|
|
1251
|
+
} catch {
|
|
1252
|
+
continue;
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
if (f.type === 'session_challenge') {
|
|
1256
|
+
const transcript = {
|
|
1257
|
+
protocol: PROTOCOL_VERSION,
|
|
1258
|
+
endpoint: discovery.endpoint,
|
|
1259
|
+
clientNonce,
|
|
1260
|
+
serverNonce: f.server_nonce
|
|
1261
|
+
};
|
|
1262
|
+
send({
|
|
1263
|
+
type: 'session_prove',
|
|
1264
|
+
client_proof: computeProof(discovery.ticket, 'client', transcript)
|
|
1265
|
+
});
|
|
1266
|
+
} else if (f.type === 'session_hello_ack') {
|
|
1267
|
+
send({ jsonrpc: '2.0', id: 1, method: 'broker/GetPipe', params: { pipe: 'wb.request' } });
|
|
1268
|
+
} else if (f.id === 1) {
|
|
1269
|
+
if (f.error) {
|
|
1270
|
+
socket.end();
|
|
1271
|
+
return finish(reject, new Error(`GetPipe 错误: ${f.error.message}`));
|
|
1272
|
+
}
|
|
1273
|
+
const channel = f.result?.channel;
|
|
1274
|
+
send({
|
|
1275
|
+
jsonrpc: '2.0',
|
|
1276
|
+
id: 2,
|
|
1277
|
+
method: `${channel}/http.fetch`,
|
|
1278
|
+
mode: 'call',
|
|
1279
|
+
params: {
|
|
1280
|
+
method: 'POST',
|
|
1281
|
+
path: '/v2/chat/completions',
|
|
1282
|
+
headers: {
|
|
1283
|
+
'content-type': 'application/json',
|
|
1284
|
+
'accept': 'text/event-stream'
|
|
1285
|
+
},
|
|
1286
|
+
body_b64: Buffer.from(JSON.stringify(payload)).toString('base64')
|
|
1287
|
+
}
|
|
1288
|
+
});
|
|
1289
|
+
} else if (f.id === 2) {
|
|
1290
|
+
socket.end();
|
|
1291
|
+
|
|
1292
|
+
if (f.error) {
|
|
1293
|
+
return finish(reject, new Error(f.error.message));
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
if (f.result?.status && f.result.status >= 400) {
|
|
1297
|
+
let errorText = `HTTP ${f.result.status}`;
|
|
1298
|
+
if (f.result.body_b64) {
|
|
1299
|
+
try {
|
|
1300
|
+
const bodyStr = Buffer.from(f.result.body_b64, 'base64').toString('utf8');
|
|
1301
|
+
const errJson = JSON.parse(bodyStr);
|
|
1302
|
+
errorText += `: ${errJson.msg || errJson.message || bodyStr}`;
|
|
1303
|
+
} catch {}
|
|
1304
|
+
}
|
|
1305
|
+
return finish(reject, new Error(errorText));
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
if (!f.result || !f.result.body_b64) {
|
|
1309
|
+
return finish(resolve, { text: '', reasoning: '', toolCalls: [] });
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
const raw = Buffer.from(f.result.body_b64, 'base64').toString('utf8');
|
|
1313
|
+
const completion = parseSseCompletion(raw);
|
|
1314
|
+
if (completion.text) options.onDelta?.(completion.text);
|
|
1315
|
+
if (completion.reasoning) options.onReasoning?.(completion.reasoning);
|
|
1316
|
+
finish(resolve, completion);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
});
|
|
1320
|
+
|
|
1321
|
+
socket.on('error', err => {
|
|
1322
|
+
finish(reject, new Error(`连接 WorkBuddy 套接字失败: ${err.message}`));
|
|
1323
|
+
});
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
function getStatusInfo() {
|
|
1328
|
+
const cliSession = readCliSession();
|
|
1329
|
+
const discoveryFile = path.join(os.homedir(), '.workbuddy', 'wbipc', 'endpoint.json');
|
|
1330
|
+
const desktopRunning = fs.existsSync(discoveryFile);
|
|
1331
|
+
return {
|
|
1332
|
+
cliLoggedIn: Boolean(cliSession?.auth?.accessToken),
|
|
1333
|
+
authFile: AUTH_FILE,
|
|
1334
|
+
endpoint: cliSession?.endpoint || DEFAULT_ENDPOINT,
|
|
1335
|
+
account: cliSession?.account || null,
|
|
1336
|
+
expiresAt: cliSession?.auth?.expiresAt ? new Date(cliSession.auth.expiresAt).toISOString() : null,
|
|
1337
|
+
desktopWbicpRunning: desktopRunning
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
async function main() {
|
|
1342
|
+
const args = parseArgs(process.argv.slice(2));
|
|
1343
|
+
|
|
1344
|
+
if (args.command === 'login') {
|
|
1345
|
+
try {
|
|
1346
|
+
const session = await loginWorkBuddy({ noBrowser: args.noBrowser });
|
|
1347
|
+
if (args.asJson) {
|
|
1348
|
+
console.log(JSON.stringify({ ok: true, account: session.account, authFile: AUTH_FILE }, null, 2));
|
|
1349
|
+
} else {
|
|
1350
|
+
const who = session.account?.nickname || session.account?.uid || 'Unknown';
|
|
1351
|
+
console.log(`登录成功!当前账号: ${who}`);
|
|
1352
|
+
console.log(`凭据已保存至: ${AUTH_FILE}(后续无需再开启 WorkBuddy 客户端)`);
|
|
1353
|
+
}
|
|
1354
|
+
} catch (err) {
|
|
1355
|
+
if (args.asJson) {
|
|
1356
|
+
console.error(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
1357
|
+
} else {
|
|
1358
|
+
console.error(`Error: ${err.message}`);
|
|
1359
|
+
}
|
|
1360
|
+
process.exit(1);
|
|
1361
|
+
}
|
|
1362
|
+
return;
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
if (args.command === 'logout') {
|
|
1366
|
+
const result = await logoutWorkBuddy();
|
|
1367
|
+
if (args.asJson) {
|
|
1368
|
+
console.log(JSON.stringify({ ok: true, ...result }, null, 2));
|
|
1369
|
+
} else if (!result.hadSession) {
|
|
1370
|
+
console.log('当前未登录 CLI 会话。');
|
|
1371
|
+
} else {
|
|
1372
|
+
console.log('已退出登录并清理本地 CLI 凭据。');
|
|
1373
|
+
}
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
if (args.command === 'status') {
|
|
1378
|
+
const info = getStatusInfo();
|
|
1379
|
+
if (args.asJson) {
|
|
1380
|
+
console.log(JSON.stringify({ ok: true, data: info }, null, 2));
|
|
1381
|
+
} else {
|
|
1382
|
+
console.log(`CLI 独立登录: ${info.cliLoggedIn ? '已登录' : '未登录'}`);
|
|
1383
|
+
if (info.cliLoggedIn) {
|
|
1384
|
+
const who = info.account?.nickname || info.account?.uid || '(未知用户)';
|
|
1385
|
+
console.log(`当前账号: ${who}`);
|
|
1386
|
+
if (info.expiresAt) console.log(`Token 过期时间: ${info.expiresAt}`);
|
|
1387
|
+
console.log(`凭据文件: ${info.authFile}`);
|
|
1388
|
+
}
|
|
1389
|
+
console.log(`桌面端 WBIPC: ${info.desktopWbicpRunning ? '运行中' : '未运行'}`);
|
|
1390
|
+
}
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
if (args.command === 'models') {
|
|
1395
|
+
if (args.staticModels) {
|
|
1396
|
+
if (args.asJson) {
|
|
1397
|
+
console.log(JSON.stringify({ ok: true, source: 'static', aliases: MODEL_ALIASES }, null, 2));
|
|
1398
|
+
} else {
|
|
1399
|
+
showModels();
|
|
1400
|
+
}
|
|
1401
|
+
return;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
try {
|
|
1405
|
+
const result = await scanAvailableModels({ includeAll: args.includeAllModels });
|
|
1406
|
+
if (!result.models) {
|
|
1407
|
+
if (args.asJson) {
|
|
1408
|
+
console.log(JSON.stringify({ ok: true, source: 'static', note: result.reason, aliases: MODEL_ALIASES }, null, 2));
|
|
1409
|
+
} else {
|
|
1410
|
+
console.error(`提示: ${result.reason},以下为内置静态模型清单;运行 "workbuddy login" 后可实时扫描服务端最新模型。\n`);
|
|
1411
|
+
showModels();
|
|
1412
|
+
}
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
if (args.asJson) {
|
|
1417
|
+
console.log(JSON.stringify({ ok: true, source: result.source, count: result.models.length, models: result.models }, null, 2));
|
|
1418
|
+
} else {
|
|
1419
|
+
printScannedModels(result.models, result.source);
|
|
1420
|
+
}
|
|
1421
|
+
} catch (err) {
|
|
1422
|
+
if (args.asJson) {
|
|
1423
|
+
console.error(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
1424
|
+
} else {
|
|
1425
|
+
console.error(`扫描服务端模型失败 (${err.message}),回退到内置清单:\n`);
|
|
1426
|
+
showModels();
|
|
1427
|
+
}
|
|
1428
|
+
process.exit(1);
|
|
1429
|
+
}
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
if (args.command === 'acp') {
|
|
1434
|
+
const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
|
|
1435
|
+
let version = '1.2.0';
|
|
1436
|
+
try {
|
|
1437
|
+
version = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version || version;
|
|
1438
|
+
} catch {}
|
|
1439
|
+
await runAcpServer({
|
|
1440
|
+
version,
|
|
1441
|
+
defaultModel: args.modelExplicit ? args.model : DEFAULT_MODEL,
|
|
1442
|
+
models: acpModels(),
|
|
1443
|
+
isLoggedIn: () => process.env.WORKBUDDY_ACP_MOCK === '1' || Boolean(readCliSession()?.auth?.accessToken),
|
|
1444
|
+
logout: logoutWorkBuddy,
|
|
1445
|
+
completeChat: options => callWorkBuddy('', options)
|
|
1446
|
+
});
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
if (args.command === 'sessions' || (args.resumeId === '' && !args.prompt)) {
|
|
1451
|
+
printSessions(args.asJson);
|
|
1452
|
+
return;
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
let userPrompt = args.prompt;
|
|
1456
|
+
|
|
1457
|
+
// 如果没有从命令行参数提供 prompt,检查 stdin 是否有输入(例如管道传参)
|
|
1458
|
+
if (!userPrompt && !process.stdin.isTTY) {
|
|
1459
|
+
const chunks = [];
|
|
1460
|
+
for await (const chunk of process.stdin) {
|
|
1461
|
+
chunks.push(chunk);
|
|
1462
|
+
}
|
|
1463
|
+
userPrompt = Buffer.concat(chunks).toString('utf8').trim();
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
if (!userPrompt) {
|
|
1467
|
+
showHelp();
|
|
1468
|
+
process.exit(1);
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
let stored = null;
|
|
1472
|
+
try {
|
|
1473
|
+
if (args.resumeId) {
|
|
1474
|
+
stored = loadSession(args.resumeId);
|
|
1475
|
+
if (!stored) throw new Error(`找不到会话 ${args.resumeId}。运行 workbuddy sessions 查看已保存的对话。`);
|
|
1476
|
+
} else if (args.continueSession) {
|
|
1477
|
+
stored = latestSession(process.cwd());
|
|
1478
|
+
if (!stored) throw new Error('当前目录没有可继续的会话。先直接提问一次,或用 workbuddy resume <id>。');
|
|
1479
|
+
}
|
|
1480
|
+
} catch (err) {
|
|
1481
|
+
if (args.asJson) console.error(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
1482
|
+
else console.error(`Error: ${err.message}`);
|
|
1483
|
+
process.exit(1);
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
const messages = [...(stored?.messages || [])];
|
|
1487
|
+
if (args.systemExplicit) {
|
|
1488
|
+
const rest = messages.filter(message => message.role !== 'system');
|
|
1489
|
+
messages.length = 0;
|
|
1490
|
+
if (args.systemPrompt) messages.push({ role: 'system', content: args.systemPrompt });
|
|
1491
|
+
messages.push(...rest);
|
|
1492
|
+
}
|
|
1493
|
+
messages.push({ role: 'user', content: userPrompt });
|
|
1494
|
+
const model = args.modelExplicit ? args.model : (stored?.model || args.model);
|
|
1495
|
+
|
|
1496
|
+
try {
|
|
1497
|
+
const result = await callWorkBuddy(userPrompt, {
|
|
1498
|
+
model,
|
|
1499
|
+
messages,
|
|
1500
|
+
systemPrompt: args.systemPrompt
|
|
1501
|
+
});
|
|
1502
|
+
const saved = saveSession({
|
|
1503
|
+
id: stored?.id || args.sessionId || createSessionId(),
|
|
1504
|
+
cwd: stored?.cwd || process.cwd(),
|
|
1505
|
+
model,
|
|
1506
|
+
title: stored?.title || userPrompt.slice(0, 48),
|
|
1507
|
+
mode: stored?.mode || 'default',
|
|
1508
|
+
createdAt: stored?.createdAt || Date.now(),
|
|
1509
|
+
updatedAt: Date.now(),
|
|
1510
|
+
messages: [
|
|
1511
|
+
...messages,
|
|
1512
|
+
{ role: 'assistant', content: result.text || '' }
|
|
1513
|
+
]
|
|
1514
|
+
});
|
|
1515
|
+
|
|
1516
|
+
if (args.asJson) {
|
|
1517
|
+
console.log(JSON.stringify({ ok: true, data: { ...result, sessionId: saved.id } }, null, 2));
|
|
1518
|
+
} else {
|
|
1519
|
+
if (result.reasoning && process.env.WORKBUDDY_SHOW_REASONING === '1') {
|
|
1520
|
+
console.error(`[思考过程]\n${result.reasoning}\n`);
|
|
1521
|
+
}
|
|
1522
|
+
console.log(result.text);
|
|
1523
|
+
if (process.stderr.isTTY) {
|
|
1524
|
+
console.error(`会话 ${saved.id} 已保存。继续:workbuddy -c`);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
} catch (err) {
|
|
1528
|
+
if (args.asJson) {
|
|
1529
|
+
console.error(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
1530
|
+
} else {
|
|
1531
|
+
console.error(`Error: ${err.message}`);
|
|
1532
|
+
}
|
|
1533
|
+
process.exit(1);
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
main();
|