workbuddy-cli 1.1.0 → 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/bin/workbuddy.mjs CHANGED
@@ -5,13 +5,25 @@ import fs from 'node:fs';
5
5
  import net from 'node:net';
6
6
  import os from 'node:os';
7
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';
8
19
 
9
20
  const PROTOCOL_VERSION = 1;
10
21
  const DEFAULT_ENDPOINT = 'https://www.workbuddy.cn';
11
22
  const AUTH_PREFIX = '/v2/plugin';
12
23
  const AUTH_PLATFORM = 'workbuddy';
13
- const AUTH_DIR = path.join(os.homedir(), '.workbuddy-cli');
14
- const AUTH_FILE = path.join(AUTH_DIR, 'auth.json');
24
+ const DEFAULT_MODEL = 'deepseek-v3-2-volc';
25
+ const AUTH_DIR = cliHome();
26
+ const AUTH_FILE = authFilePath();
15
27
  const LOGIN_POLL_INTERVAL_MS = 1500;
16
28
  const LOGIN_TIMEOUT_MS = 300000;
17
29
  const LOGIN_TOKEN_PENDING_CODE = 11217;
@@ -83,6 +95,55 @@ const MODEL_ALIASES = {
83
95
  'wb-lite': 'wb-lite'
84
96
  };
85
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
+
86
147
  function showModels() {
87
148
  console.log(`WorkBuddy 完整模型清单(经实测 200 OK 确认可用):
88
149
 
@@ -157,12 +218,19 @@ Commands:
157
218
  logout Revoke session and remove local CLI credentials
158
219
  status, whoami Show current CLI auth and desktop WBIPC status
159
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)
160
225
 
161
226
  Arguments:
162
227
  prompt Your prompt / question
163
228
 
164
229
  Options:
165
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
166
234
  -m, --model <model> Model name or alias (e.g. hy4, deepseek, glm, default: deepseek-v3-2-volc)
167
235
  -l, --models Scan/list available models and aliases
168
236
  --all Include specialized/image models when listing models
@@ -176,9 +244,12 @@ Examples:
176
244
  workbuddy login
177
245
  workbuddy models
178
246
  workbuddy "用Python写一个快速排序"
247
+ workbuddy -c "把刚才的例子改成迭代版本"
248
+ workbuddy resume wb_abc123 "再补上测试"
249
+ workbuddy sessions
179
250
  workbuddy -m hy4 "帮我写一封商务邮件"
180
251
  cat document.txt | workbuddy -p "总结主要内容"
181
- workbuddy --model glm "写一首五言绝句"
252
+ workbuddy acp
182
253
  workbuddy logout
183
254
  `);
184
255
  }
@@ -186,12 +257,18 @@ Examples:
186
257
  function parseArgs(args) {
187
258
  let command = 'chat';
188
259
  let prompt = '';
189
- let model = 'deepseek-v3-2-volc';
260
+ let model = DEFAULT_MODEL;
261
+ let modelExplicit = false;
190
262
  let asJson = false;
191
263
  let systemPrompt = '';
264
+ let systemExplicit = false;
192
265
  let noBrowser = false;
193
266
  let includeAllModels = false;
194
267
  let staticModels = false;
268
+ let continueSession = false;
269
+ let resumeId = undefined;
270
+ let expectResumeId = false;
271
+ let sessionId = '';
195
272
 
196
273
  const first = args[0];
197
274
  if (first === 'login' || first === '--login') {
@@ -206,6 +283,20 @@ function parseArgs(args) {
206
283
  } else if (first === 'models') {
207
284
  command = 'models';
208
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);
209
300
  }
210
301
 
211
302
  for (let i = 0; i < args.length; i++) {
@@ -225,16 +316,41 @@ function parseArgs(args) {
225
316
  includeAllModels = true;
226
317
  } else if (arg === '--static') {
227
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);
228
335
  } else if (arg === '-m' || arg === '--model') {
229
336
  model = args[++i];
337
+ modelExplicit = true;
230
338
  } else if (arg.startsWith('--model=')) {
231
339
  model = arg.slice(8);
340
+ modelExplicit = true;
232
341
  } else if (arg === '-s' || arg === '--system') {
233
342
  systemPrompt = args[++i];
343
+ systemExplicit = true;
234
344
  } else if (arg.startsWith('--system=')) {
235
345
  systemPrompt = arg.slice(9);
346
+ systemExplicit = true;
236
347
  } else if (!arg.startsWith('-')) {
237
- prompt = prompt ? `${prompt} ${arg}` : arg;
348
+ if (expectResumeId && resumeId === undefined) {
349
+ resumeId = arg;
350
+ expectResumeId = false;
351
+ } else {
352
+ prompt = prompt ? `${prompt} ${arg}` : arg;
353
+ }
238
354
  }
239
355
  }
240
356
 
@@ -243,7 +359,23 @@ function parseArgs(args) {
243
359
  model = MODEL_ALIASES[model.toLowerCase()];
244
360
  }
245
361
 
246
- return { command, prompt, model, asJson, systemPrompt, noBrowser, includeAllModels, staticModels };
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
+ };
247
379
  }
248
380
 
249
381
  function encodeTranscript(role, t) {
@@ -545,24 +677,143 @@ async function logoutWorkBuddy() {
545
677
  return { hadSession: true, serverRevoked };
546
678
  }
547
679
 
548
- function parseSseCompletion(raw) {
549
- let fullText = '';
680
+ function createSseAccumulator(onDelta, onReasoning) {
681
+ let text = '';
550
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
+ };
551
705
 
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;
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;
556
714
  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 {}
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
+ };
562
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);
563
785
  }
786
+ if (buf) acc.pushLine(buf);
787
+ return acc.finish();
788
+ }
564
789
 
565
- return { text: fullText, reasoning };
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: [] });
566
817
  }
567
818
 
568
819
  async function fetchDirectApi(session, method, apiPath, body) {
@@ -782,6 +1033,61 @@ function printScannedModels(models, source) {
782
1033
  console.log(`\n提示: 使用 workbuddy -m <model_id> "..." 即可直接调用任意新模型,无需等待 CLI 更新。`);
783
1034
  }
784
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
+
785
1091
  async function callWorkBuddyDirect(session, userPrompt, options = {}) {
786
1092
  let activeSession = session;
787
1093
  if (
@@ -792,18 +1098,8 @@ async function callWorkBuddyDirect(session, userPrompt, options = {}) {
792
1098
  activeSession = await refreshCliSession(activeSession);
793
1099
  }
794
1100
 
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
- };
1101
+ const payload = chatPayload(userPrompt, options);
1102
+ const timeoutMs = options.timeoutMs || 60000;
807
1103
 
808
1104
  const sendRequest = async s => {
809
1105
  const endpoint = (s.endpoint || DEFAULT_ENDPOINT).replace(/\/+$/, '');
@@ -820,24 +1116,32 @@ async function callWorkBuddyDirect(session, userPrompt, options = {}) {
820
1116
  headers['X-Tenant-Id'] = s.account.enterpriseId;
821
1117
  }
822
1118
 
823
- const controller = new AbortController();
824
- const timer = setTimeout(() => controller.abort(), 60000);
1119
+ const linked = linkAbortSignals(options.signal, timeoutMs);
825
1120
  try {
826
1121
  const res = await fetch(`${endpoint}/v2/chat/completions`, {
827
1122
  method: 'POST',
828
1123
  headers,
829
1124
  body: JSON.stringify(payload),
830
- signal: controller.signal
1125
+ signal: linked.signal
831
1126
  });
832
- const raw = await res.text();
833
- return { status: res.status, raw };
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 };
834
1133
  } catch (err) {
835
- if (err?.name === 'AbortError') {
836
- throw new Error('请求超时 (60s)');
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)`);
837
1141
  }
838
1142
  throw err;
839
1143
  } finally {
840
- clearTimeout(timer);
1144
+ linked.close();
841
1145
  }
842
1146
  };
843
1147
 
@@ -858,10 +1162,18 @@ async function callWorkBuddyDirect(session, userPrompt, options = {}) {
858
1162
  throw new Error(errorText);
859
1163
  }
860
1164
 
861
- return parseSseCompletion(res.raw);
1165
+ return res.completion;
862
1166
  }
863
1167
 
864
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
+
865
1177
  const cliSession = readCliSession();
866
1178
  if (cliSession?.auth?.accessToken) {
867
1179
  return callWorkBuddyDirect(cliSession, userPrompt, options);
@@ -879,18 +1191,39 @@ async function callWorkBuddy(userPrompt, options = {}) {
879
1191
  throw new Error(`读取 WBIPC endpoint.json 失败: ${err.message}`);
880
1192
  }
881
1193
 
882
- const { model = 'deepseek-v3-2-volc', systemPrompt } = options;
1194
+ const payload = chatPayload(userPrompt, options);
1195
+ const timeoutMs = options.timeoutMs || 60000;
883
1196
 
884
1197
  return new Promise((resolve, reject) => {
885
1198
  const socket = net.connect({ path: discovery.endpoint });
886
1199
  let buffer = Buffer.alloc(0);
887
1200
  const clientNonce = crypto.randomBytes(16).toString('base64url');
888
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 });
889
1222
 
890
- let timeoutTimer = setTimeout(() => {
1223
+ timeoutTimer = setTimeout(() => {
891
1224
  socket.destroy();
892
- reject(new Error('请求超时 (60s)'));
893
- }, 60000);
1225
+ finish(reject, new Error(`请求超时 (${Math.round(timeoutMs / 1000)}s)`));
1226
+ }, timeoutMs);
894
1227
 
895
1228
  socket.on('connect', () => {
896
1229
  send({
@@ -934,23 +1267,10 @@ async function callWorkBuddy(userPrompt, options = {}) {
934
1267
  send({ jsonrpc: '2.0', id: 1, method: 'broker/GetPipe', params: { pipe: 'wb.request' } });
935
1268
  } else if (f.id === 1) {
936
1269
  if (f.error) {
937
- clearTimeout(timeoutTimer);
938
1270
  socket.end();
939
- return reject(new Error(`GetPipe 错误: ${f.error.message}`));
1271
+ return finish(reject, new Error(`GetPipe 错误: ${f.error.message}`));
940
1272
  }
941
1273
  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
1274
  send({
955
1275
  jsonrpc: '2.0',
956
1276
  id: 2,
@@ -967,11 +1287,10 @@ async function callWorkBuddy(userPrompt, options = {}) {
967
1287
  }
968
1288
  });
969
1289
  } else if (f.id === 2) {
970
- clearTimeout(timeoutTimer);
971
1290
  socket.end();
972
1291
 
973
1292
  if (f.error) {
974
- return reject(new Error(f.error.message));
1293
+ return finish(reject, new Error(f.error.message));
975
1294
  }
976
1295
 
977
1296
  if (f.result?.status && f.result.status >= 400) {
@@ -983,22 +1302,24 @@ async function callWorkBuddy(userPrompt, options = {}) {
983
1302
  errorText += `: ${errJson.msg || errJson.message || bodyStr}`;
984
1303
  } catch {}
985
1304
  }
986
- return reject(new Error(errorText));
1305
+ return finish(reject, new Error(errorText));
987
1306
  }
988
1307
 
989
1308
  if (!f.result || !f.result.body_b64) {
990
- return resolve({ text: '', reasoning: '' });
1309
+ return finish(resolve, { text: '', reasoning: '', toolCalls: [] });
991
1310
  }
992
1311
 
993
1312
  const raw = Buffer.from(f.result.body_b64, 'base64').toString('utf8');
994
- resolve(parseSseCompletion(raw));
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);
995
1317
  }
996
1318
  }
997
1319
  });
998
1320
 
999
1321
  socket.on('error', err => {
1000
- clearTimeout(timeoutTimer);
1001
- reject(new Error(`连接 WorkBuddy 套接字失败: ${err.message}`));
1322
+ finish(reject, new Error(`连接 WorkBuddy 套接字失败: ${err.message}`));
1002
1323
  });
1003
1324
  });
1004
1325
  }
@@ -1109,6 +1430,28 @@ async function main() {
1109
1430
  return;
1110
1431
  }
1111
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
+
1112
1455
  let userPrompt = args.prompt;
1113
1456
 
1114
1457
  // 如果没有从命令行参数提供 prompt,检查 stdin 是否有输入(例如管道传参)
@@ -1125,19 +1468,61 @@ async function main() {
1125
1468
  process.exit(1);
1126
1469
  }
1127
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
+
1128
1496
  try {
1129
1497
  const result = await callWorkBuddy(userPrompt, {
1130
- model: args.model,
1498
+ model,
1499
+ messages,
1131
1500
  systemPrompt: args.systemPrompt
1132
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
+ });
1133
1515
 
1134
1516
  if (args.asJson) {
1135
- console.log(JSON.stringify({ ok: true, data: result }, null, 2));
1517
+ console.log(JSON.stringify({ ok: true, data: { ...result, sessionId: saved.id } }, null, 2));
1136
1518
  } else {
1137
1519
  if (result.reasoning && process.env.WORKBUDDY_SHOW_REASONING === '1') {
1138
1520
  console.error(`[思考过程]\n${result.reasoning}\n`);
1139
1521
  }
1140
1522
  console.log(result.text);
1523
+ if (process.stderr.isTTY) {
1524
+ console.error(`会话 ${saved.id} 已保存。继续:workbuddy -c`);
1525
+ }
1141
1526
  }
1142
1527
  } catch (err) {
1143
1528
  if (args.asJson) {