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,739 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {
|
|
5
|
+
createSessionId,
|
|
6
|
+
listSessions,
|
|
7
|
+
loadSession,
|
|
8
|
+
saveSession
|
|
9
|
+
} from './sessions.mjs';
|
|
10
|
+
|
|
11
|
+
const TOOLS = [
|
|
12
|
+
{
|
|
13
|
+
type: 'function',
|
|
14
|
+
function: {
|
|
15
|
+
name: 'read_file',
|
|
16
|
+
description: 'Read a UTF-8 text file in the working directory.',
|
|
17
|
+
parameters: {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
path: { type: 'string', description: 'File path, absolute or relative to the working directory.' }
|
|
21
|
+
},
|
|
22
|
+
required: ['path']
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
type: 'function',
|
|
28
|
+
function: {
|
|
29
|
+
name: 'list_dir',
|
|
30
|
+
description: 'List files and directories.',
|
|
31
|
+
parameters: {
|
|
32
|
+
type: 'object',
|
|
33
|
+
properties: {
|
|
34
|
+
path: { type: 'string', description: 'Directory path. Defaults to the working directory.' }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
type: 'function',
|
|
41
|
+
function: {
|
|
42
|
+
name: 'write_file',
|
|
43
|
+
description: 'Create or overwrite a UTF-8 text file.',
|
|
44
|
+
parameters: {
|
|
45
|
+
type: 'object',
|
|
46
|
+
properties: {
|
|
47
|
+
path: { type: 'string' },
|
|
48
|
+
content: { type: 'string' }
|
|
49
|
+
},
|
|
50
|
+
required: ['path', 'content']
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
type: 'function',
|
|
56
|
+
function: {
|
|
57
|
+
name: 'bash',
|
|
58
|
+
description: 'Run a shell command in the working directory.',
|
|
59
|
+
parameters: {
|
|
60
|
+
type: 'object',
|
|
61
|
+
properties: {
|
|
62
|
+
command: { type: 'string' }
|
|
63
|
+
},
|
|
64
|
+
required: ['command']
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
const TOOL_KIND = {
|
|
71
|
+
read_file: 'read',
|
|
72
|
+
list_dir: 'search',
|
|
73
|
+
write_file: 'edit',
|
|
74
|
+
bash: 'execute'
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
function debug(message) {
|
|
78
|
+
if (process.env.WORKBUDDY_ACP_DEBUG === '1') {
|
|
79
|
+
process.stderr.write(`[acp] ${message}\n`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function promptToText(blocks) {
|
|
84
|
+
const parts = [];
|
|
85
|
+
for (const block of blocks || []) {
|
|
86
|
+
if (!block || typeof block !== 'object') continue;
|
|
87
|
+
if (block.type === 'text' && block.text) parts.push(String(block.text));
|
|
88
|
+
else if (block.type === 'resource' && block.resource?.text) {
|
|
89
|
+
const uri = block.resource.uri || '';
|
|
90
|
+
parts.push(`<resource uri="${uri}">\n${block.resource.text}\n</resource>`);
|
|
91
|
+
} else if (block.type === 'resource_link') {
|
|
92
|
+
parts.push(`[resource] ${block.uri || block.name || ''}`);
|
|
93
|
+
} else if (block.type === 'image') {
|
|
94
|
+
parts.push('[image omitted: this agent accepts text only]');
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return parts.join('\n').trim();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function withinCwd(cwd, target) {
|
|
101
|
+
const root = path.resolve(cwd);
|
|
102
|
+
const resolved = path.resolve(cwd, target || '.');
|
|
103
|
+
const rel = path.relative(root, resolved);
|
|
104
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
|
105
|
+
return resolved;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function windowMessages(messages) {
|
|
109
|
+
const systems = messages.filter(message => message.role === 'system');
|
|
110
|
+
const rest = messages.filter(message => message.role !== 'system');
|
|
111
|
+
const tail = rest.slice(-40);
|
|
112
|
+
while (tail.length && tail[0].role === 'tool') tail.shift();
|
|
113
|
+
return [...systems, ...tail];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function publicMessages(messages) {
|
|
117
|
+
return messages
|
|
118
|
+
.filter(message => message.role === 'user' || message.role === 'assistant')
|
|
119
|
+
.map(message => ({
|
|
120
|
+
role: message.role,
|
|
121
|
+
content: typeof message.content === 'string' ? message.content : ''
|
|
122
|
+
}))
|
|
123
|
+
.filter(message => message.content);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function runAcpServer(deps) {
|
|
127
|
+
const active = new Map();
|
|
128
|
+
const aborters = new Map();
|
|
129
|
+
const pending = new Map();
|
|
130
|
+
const chains = new Map();
|
|
131
|
+
let nextId = 1;
|
|
132
|
+
let clientCapabilities = {};
|
|
133
|
+
const defaultModel = deps.defaultModel;
|
|
134
|
+
|
|
135
|
+
const send = obj => {
|
|
136
|
+
process.stdout.write(JSON.stringify(obj) + '\n');
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
|
|
140
|
+
const fail = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
|
|
141
|
+
|
|
142
|
+
function rpcCall(method, params, signal) {
|
|
143
|
+
const id = `wbcli-${nextId++}`;
|
|
144
|
+
return new Promise((resolve, reject) => {
|
|
145
|
+
const timer = setTimeout(() => {
|
|
146
|
+
pending.delete(id);
|
|
147
|
+
reject(new Error(`ACP 客户端超时: ${method}`));
|
|
148
|
+
}, 120000);
|
|
149
|
+
const onAbort = () => {
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
pending.delete(id);
|
|
152
|
+
const err = new Error('cancelled');
|
|
153
|
+
err.name = 'AbortError';
|
|
154
|
+
reject(err);
|
|
155
|
+
};
|
|
156
|
+
if (signal?.aborted) {
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
onAbort();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
162
|
+
pending.set(id, {
|
|
163
|
+
resolve: value => {
|
|
164
|
+
clearTimeout(timer);
|
|
165
|
+
signal?.removeEventListener('abort', onAbort);
|
|
166
|
+
resolve(value);
|
|
167
|
+
},
|
|
168
|
+
reject: err => {
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
signal?.removeEventListener('abort', onAbort);
|
|
171
|
+
reject(err);
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
send({ jsonrpc: '2.0', id, method, params });
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function notify(sessionId, update) {
|
|
179
|
+
send({ jsonrpc: '2.0', method: 'session/update', params: { sessionId, update } });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function modelCatalog(current) {
|
|
183
|
+
const models = deps.models.map(model => ({ ...model }));
|
|
184
|
+
if (current && !models.some(model => model.modelId === current)) {
|
|
185
|
+
models.unshift({ modelId: current, name: current });
|
|
186
|
+
}
|
|
187
|
+
return models;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function sessionPayload(session) {
|
|
191
|
+
const availableModels = modelCatalog(session.model);
|
|
192
|
+
return {
|
|
193
|
+
sessionId: session.id,
|
|
194
|
+
models: {
|
|
195
|
+
currentModelId: session.model,
|
|
196
|
+
availableModels
|
|
197
|
+
},
|
|
198
|
+
configOptions: [
|
|
199
|
+
{
|
|
200
|
+
id: 'model',
|
|
201
|
+
name: 'Model',
|
|
202
|
+
category: 'model',
|
|
203
|
+
type: 'select',
|
|
204
|
+
currentValue: session.model,
|
|
205
|
+
options: availableModels.map(model => ({ value: model.modelId, name: model.name }))
|
|
206
|
+
}
|
|
207
|
+
]
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function systemPrompt(cwd) {
|
|
212
|
+
return `You are WorkBuddy, a coding assistant connected through the Agent Client Protocol. The working directory is ${cwd}. Use read_file, list_dir, write_file, and bash to inspect and change the project. Do not invent file contents. Reply in the user's language.`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function activate(session) {
|
|
216
|
+
active.set(session.id, session);
|
|
217
|
+
return session;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function requireSession(id) {
|
|
221
|
+
const cached = active.get(id);
|
|
222
|
+
if (cached) return cached;
|
|
223
|
+
const loaded = loadSession(id);
|
|
224
|
+
if (!loaded) return null;
|
|
225
|
+
return activate(loaded);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function requestPermission(sessionId, toolCall, signal) {
|
|
229
|
+
try {
|
|
230
|
+
const result = await rpcCall('session/request_permission', {
|
|
231
|
+
sessionId,
|
|
232
|
+
toolCall,
|
|
233
|
+
options: [
|
|
234
|
+
{ optionId: 'allow-once', name: 'Allow once', kind: 'allow_once' },
|
|
235
|
+
{ optionId: 'reject-once', name: 'Reject', kind: 'reject_once' }
|
|
236
|
+
]
|
|
237
|
+
}, signal);
|
|
238
|
+
const outcome = result?.outcome;
|
|
239
|
+
if (outcome?.outcome === 'selected') {
|
|
240
|
+
return outcome.optionId === 'allow-once' || outcome.optionId === 'allow-always';
|
|
241
|
+
}
|
|
242
|
+
return false;
|
|
243
|
+
} catch (err) {
|
|
244
|
+
if (err?.name === 'AbortError') throw err;
|
|
245
|
+
const code = err?.code;
|
|
246
|
+
if (code === -32601) return true;
|
|
247
|
+
throw err;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function readFile(session, filePath, signal) {
|
|
252
|
+
const absolute = path.resolve(session.cwd, filePath);
|
|
253
|
+
if (clientCapabilities.fs?.readTextFile) {
|
|
254
|
+
const result = await rpcCall('fs/read_text_file', {
|
|
255
|
+
sessionId: session.id,
|
|
256
|
+
path: absolute,
|
|
257
|
+
line: 1,
|
|
258
|
+
limit: 400
|
|
259
|
+
}, signal);
|
|
260
|
+
return result?.content ?? '';
|
|
261
|
+
}
|
|
262
|
+
const local = withinCwd(session.cwd, filePath);
|
|
263
|
+
if (!local) return `拒绝读取工作区之外的文件: ${filePath}`;
|
|
264
|
+
return fs.readFileSync(local, 'utf8');
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function listDir(session, dirPath) {
|
|
268
|
+
const local = withinCwd(session.cwd, dirPath || '.');
|
|
269
|
+
if (!local) return `拒绝列出工作区之外的目录: ${dirPath || '.'}`;
|
|
270
|
+
const entries = fs.readdirSync(local, { withFileTypes: true });
|
|
271
|
+
return entries
|
|
272
|
+
.slice(0, 200)
|
|
273
|
+
.map(entry => `${entry.isDirectory() ? 'd' : 'f'} ${entry.name}`)
|
|
274
|
+
.join('\n');
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function writeFile(session, filePath, content, signal) {
|
|
278
|
+
const absolute = path.resolve(session.cwd, filePath);
|
|
279
|
+
if (clientCapabilities.fs?.writeTextFile) {
|
|
280
|
+
await rpcCall('fs/write_text_file', {
|
|
281
|
+
sessionId: session.id,
|
|
282
|
+
path: absolute,
|
|
283
|
+
content: String(content ?? '')
|
|
284
|
+
}, signal);
|
|
285
|
+
return `已写入 ${absolute}`;
|
|
286
|
+
}
|
|
287
|
+
const local = withinCwd(session.cwd, filePath);
|
|
288
|
+
if (!local) return `拒绝写入工作区之外的文件: ${filePath}`;
|
|
289
|
+
fs.mkdirSync(path.dirname(local), { recursive: true });
|
|
290
|
+
fs.writeFileSync(local, String(content ?? ''));
|
|
291
|
+
return `已写入 ${local}`;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function runBash(session, command, signal) {
|
|
295
|
+
if (clientCapabilities.terminal) {
|
|
296
|
+
try {
|
|
297
|
+
const created = await rpcCall('terminal/create', {
|
|
298
|
+
sessionId: session.id,
|
|
299
|
+
command: 'bash',
|
|
300
|
+
args: ['-lc', command],
|
|
301
|
+
cwd: session.cwd,
|
|
302
|
+
outputByteLimit: 20000
|
|
303
|
+
}, signal);
|
|
304
|
+
const terminalId = created?.terminalId;
|
|
305
|
+
if (!terminalId) throw new Error('terminal/create 没有返回 terminalId');
|
|
306
|
+
const exit = await rpcCall('terminal/wait_for_exit', { sessionId: session.id, terminalId }, signal);
|
|
307
|
+
const output = await rpcCall('terminal/output', { sessionId: session.id, terminalId }, signal);
|
|
308
|
+
await rpcCall('terminal/release', { sessionId: session.id, terminalId }).catch(() => {});
|
|
309
|
+
const text = output?.output || '';
|
|
310
|
+
const exitCode = exit?.exitCode ?? output?.exitStatus?.exitCode ?? 0;
|
|
311
|
+
return `${text}${text.endsWith('\n') || !text ? '' : '\n'}exit ${exitCode}`;
|
|
312
|
+
} catch (err) {
|
|
313
|
+
if (err?.name === 'AbortError' || err?.code !== -32601) throw err;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return new Promise((resolve, reject) => {
|
|
317
|
+
if (signal?.aborted) {
|
|
318
|
+
const err = new Error('cancelled');
|
|
319
|
+
err.name = 'AbortError';
|
|
320
|
+
reject(err);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const child = spawn('bash', ['-lc', command], {
|
|
324
|
+
cwd: session.cwd,
|
|
325
|
+
env: process.env
|
|
326
|
+
});
|
|
327
|
+
let output = '';
|
|
328
|
+
const append = chunk => {
|
|
329
|
+
output += chunk.toString('utf8');
|
|
330
|
+
if (output.length > 20000) output = output.slice(0, 20000) + '\n[truncated]';
|
|
331
|
+
};
|
|
332
|
+
child.stdout.on('data', append);
|
|
333
|
+
child.stderr.on('data', append);
|
|
334
|
+
const timer = setTimeout(() => child.kill('SIGTERM'), 60000);
|
|
335
|
+
const onAbort = () => child.kill('SIGTERM');
|
|
336
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
337
|
+
child.on('error', err => {
|
|
338
|
+
clearTimeout(timer);
|
|
339
|
+
signal?.removeEventListener('abort', onAbort);
|
|
340
|
+
reject(err);
|
|
341
|
+
});
|
|
342
|
+
child.on('close', code => {
|
|
343
|
+
clearTimeout(timer);
|
|
344
|
+
signal?.removeEventListener('abort', onAbort);
|
|
345
|
+
if (signal?.aborted) {
|
|
346
|
+
const err = new Error('cancelled');
|
|
347
|
+
err.name = 'AbortError';
|
|
348
|
+
reject(err);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
resolve(`${output}${output.endsWith('\n') || !output ? '' : '\n'}exit ${code ?? 0}`);
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function executeTool(session, call, signal) {
|
|
357
|
+
const args = JSON.parse(call.arguments || '{}');
|
|
358
|
+
const toolCallId = call.id;
|
|
359
|
+
const title = `${call.name} ${args.path || args.command || ''}`.trim();
|
|
360
|
+
const kind = TOOL_KIND[call.name] || 'other';
|
|
361
|
+
const rawInput = args;
|
|
362
|
+
notify(session.id, {
|
|
363
|
+
sessionUpdate: 'tool_call',
|
|
364
|
+
toolCallId,
|
|
365
|
+
title,
|
|
366
|
+
kind,
|
|
367
|
+
status: 'pending',
|
|
368
|
+
rawInput
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
const needsPermission = call.name === 'write_file' || call.name === 'bash' || call.name === 'read_file';
|
|
372
|
+
if (needsPermission) {
|
|
373
|
+
const allowed = await requestPermission(session.id, {
|
|
374
|
+
toolCallId,
|
|
375
|
+
title,
|
|
376
|
+
kind,
|
|
377
|
+
status: 'pending',
|
|
378
|
+
rawInput
|
|
379
|
+
}, signal);
|
|
380
|
+
if (!allowed) {
|
|
381
|
+
notify(session.id, {
|
|
382
|
+
sessionUpdate: 'tool_call_update',
|
|
383
|
+
toolCallId,
|
|
384
|
+
status: 'failed',
|
|
385
|
+
content: [{ type: 'content', content: { type: 'text', text: '用户拒绝了这次工具调用。' } }]
|
|
386
|
+
});
|
|
387
|
+
return '用户拒绝了这次工具调用。';
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
notify(session.id, { sessionUpdate: 'tool_call_update', toolCallId, status: 'in_progress' });
|
|
392
|
+
let text = '';
|
|
393
|
+
if (call.name === 'read_file') text = await readFile(session, args.path, signal);
|
|
394
|
+
else if (call.name === 'list_dir') text = listDir(session, args.path);
|
|
395
|
+
else if (call.name === 'write_file') text = await writeFile(session, args.path, args.content, signal);
|
|
396
|
+
else if (call.name === 'bash') text = await runBash(session, String(args.command || ''), signal);
|
|
397
|
+
else text = `未知工具: ${call.name}`;
|
|
398
|
+
|
|
399
|
+
const shown = text.length > 8000 ? `${text.slice(0, 8000)}\n[truncated]` : text;
|
|
400
|
+
notify(session.id, {
|
|
401
|
+
sessionUpdate: 'tool_call_update',
|
|
402
|
+
toolCallId,
|
|
403
|
+
status: 'completed',
|
|
404
|
+
rawOutput: shown,
|
|
405
|
+
content: [{ type: 'content', content: { type: 'text', text: shown } }]
|
|
406
|
+
});
|
|
407
|
+
return shown;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async function runTurn(session, signal) {
|
|
411
|
+
const planNote = session.mode === 'plan'
|
|
412
|
+
? [{ role: 'system', content: 'Plan mode is active. Do not modify files or run commands. Read the project and answer with a plan.' }]
|
|
413
|
+
: [];
|
|
414
|
+
for (let round = 0; round < 12; round += 1) {
|
|
415
|
+
if (signal.aborted) {
|
|
416
|
+
const err = new Error('cancelled');
|
|
417
|
+
err.name = 'AbortError';
|
|
418
|
+
throw err;
|
|
419
|
+
}
|
|
420
|
+
const messages = windowMessages([...planNote, ...session.messages]);
|
|
421
|
+
let streamed = '';
|
|
422
|
+
const result = await deps.completeChat({
|
|
423
|
+
messages,
|
|
424
|
+
model: session.model || defaultModel,
|
|
425
|
+
tools: session.mode === 'plan' ? TOOLS.filter(tool => tool.function.name === 'read_file' || tool.function.name === 'list_dir') : TOOLS,
|
|
426
|
+
signal,
|
|
427
|
+
timeoutMs: 180000,
|
|
428
|
+
onDelta: delta => {
|
|
429
|
+
streamed += delta;
|
|
430
|
+
notify(session.id, {
|
|
431
|
+
sessionUpdate: 'agent_message_chunk',
|
|
432
|
+
content: { type: 'text', text: delta }
|
|
433
|
+
});
|
|
434
|
+
},
|
|
435
|
+
onReasoning: delta => {
|
|
436
|
+
notify(session.id, {
|
|
437
|
+
sessionUpdate: 'agent_thought_chunk',
|
|
438
|
+
content: { type: 'text', text: delta }
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
const toolCalls = result.toolCalls || [];
|
|
443
|
+
if (!toolCalls.length) {
|
|
444
|
+
const text = result.text || streamed;
|
|
445
|
+
if (text && !streamed) {
|
|
446
|
+
notify(session.id, {
|
|
447
|
+
sessionUpdate: 'agent_message_chunk',
|
|
448
|
+
content: { type: 'text', text }
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
session.messages.push({ role: 'assistant', content: text });
|
|
452
|
+
session.updatedAt = Date.now();
|
|
453
|
+
saveSession(session);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
session.messages.push({
|
|
458
|
+
role: 'assistant',
|
|
459
|
+
content: result.text || '',
|
|
460
|
+
tool_calls: toolCalls.map(call => ({
|
|
461
|
+
id: call.id,
|
|
462
|
+
type: 'function',
|
|
463
|
+
function: { name: call.name, arguments: call.arguments }
|
|
464
|
+
}))
|
|
465
|
+
});
|
|
466
|
+
for (const call of toolCalls) {
|
|
467
|
+
let toolText = '';
|
|
468
|
+
try {
|
|
469
|
+
toolText = await executeTool(session, call, signal);
|
|
470
|
+
} catch (err) {
|
|
471
|
+
if (err?.name === 'AbortError' || signal.aborted) throw err;
|
|
472
|
+
toolText = `工具执行失败: ${err.message}`;
|
|
473
|
+
notify(session.id, {
|
|
474
|
+
sessionUpdate: 'tool_call_update',
|
|
475
|
+
toolCallId: call.id,
|
|
476
|
+
status: 'failed',
|
|
477
|
+
content: [{ type: 'content', content: { type: 'text', text: toolText } }]
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
session.messages.push({ role: 'tool', tool_call_id: call.id, content: toolText });
|
|
481
|
+
}
|
|
482
|
+
session.updatedAt = Date.now();
|
|
483
|
+
saveSession(session);
|
|
484
|
+
}
|
|
485
|
+
const text = '已达到单轮工具调用上限,停在这里。';
|
|
486
|
+
notify(session.id, {
|
|
487
|
+
sessionUpdate: 'agent_message_chunk',
|
|
488
|
+
content: { type: 'text', text }
|
|
489
|
+
});
|
|
490
|
+
session.messages.push({ role: 'assistant', content: text });
|
|
491
|
+
session.updatedAt = Date.now();
|
|
492
|
+
saveSession(session);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function replay(session) {
|
|
496
|
+
for (const message of publicMessages(session.messages)) {
|
|
497
|
+
notify(session.id, {
|
|
498
|
+
sessionUpdate: message.role === 'user' ? 'user_message_chunk' : 'agent_message_chunk',
|
|
499
|
+
content: { type: 'text', text: message.content }
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
async function handlePrompt(msg) {
|
|
505
|
+
const sessionId = msg.params?.sessionId;
|
|
506
|
+
const session = sessionId ? requireSession(sessionId) : null;
|
|
507
|
+
if (!session) {
|
|
508
|
+
fail(msg.id, -32002, `Session not found: ${sessionId || ''}`);
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
if (!deps.isLoggedIn()) {
|
|
512
|
+
fail(msg.id, -32000, 'Authentication required. Run `workbuddy login` first.');
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
const text = promptToText(msg.params?.prompt);
|
|
516
|
+
if (!text) {
|
|
517
|
+
fail(msg.id, -32602, 'session/prompt requires a text prompt');
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const controller = new AbortController();
|
|
521
|
+
aborters.set(session.id, controller);
|
|
522
|
+
try {
|
|
523
|
+
if (!session.title) session.title = text.slice(0, 48);
|
|
524
|
+
session.messages.push({ role: 'user', content: text });
|
|
525
|
+
session.updatedAt = Date.now();
|
|
526
|
+
saveSession(session);
|
|
527
|
+
await runTurn(session, controller.signal);
|
|
528
|
+
reply(msg.id, { stopReason: controller.signal.aborted ? 'cancelled' : 'end_turn' });
|
|
529
|
+
} catch (err) {
|
|
530
|
+
if (controller.signal.aborted || err?.name === 'AbortError') {
|
|
531
|
+
reply(msg.id, { stopReason: 'cancelled' });
|
|
532
|
+
} else {
|
|
533
|
+
fail(msg.id, -32603, err.message || 'prompt failed');
|
|
534
|
+
}
|
|
535
|
+
} finally {
|
|
536
|
+
aborters.delete(session.id);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function enqueuePrompt(msg) {
|
|
541
|
+
const sessionId = msg.params?.sessionId || '_';
|
|
542
|
+
const prev = chains.get(sessionId) || Promise.resolve();
|
|
543
|
+
const next = prev.then(() => handlePrompt(msg), () => handlePrompt(msg));
|
|
544
|
+
chains.set(sessionId, next);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function loggedInMethods() {
|
|
548
|
+
if (deps.isLoggedIn()) return [];
|
|
549
|
+
return [
|
|
550
|
+
{
|
|
551
|
+
id: 'workbuddy-login',
|
|
552
|
+
name: '浏览器登录 WorkBuddy',
|
|
553
|
+
description: '在终端运行 workbuddy login,完成后 T3 Code 会重新连接。',
|
|
554
|
+
type: 'terminal',
|
|
555
|
+
args: ['login'],
|
|
556
|
+
env: []
|
|
557
|
+
}
|
|
558
|
+
];
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function onRequest(msg) {
|
|
562
|
+
const { id, method, params } = msg;
|
|
563
|
+
if (method === 'initialize') {
|
|
564
|
+
const requested = Number(params?.protocolVersion || 1);
|
|
565
|
+
if (!Number.isFinite(requested) || requested < 1) {
|
|
566
|
+
fail(id, -32022, 'Unsupported protocol version');
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
clientCapabilities = params?.clientCapabilities || params?.capabilities || {};
|
|
570
|
+
reply(id, {
|
|
571
|
+
protocolVersion: 1,
|
|
572
|
+
agentCapabilities: {
|
|
573
|
+
loadSession: true,
|
|
574
|
+
promptCapabilities: {
|
|
575
|
+
image: false,
|
|
576
|
+
audio: false,
|
|
577
|
+
embeddedContext: true
|
|
578
|
+
}
|
|
579
|
+
},
|
|
580
|
+
agentInfo: {
|
|
581
|
+
name: 'workbuddy-cli',
|
|
582
|
+
title: 'WorkBuddy CLI',
|
|
583
|
+
version: deps.version
|
|
584
|
+
},
|
|
585
|
+
authMethods: loggedInMethods()
|
|
586
|
+
});
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
if (method === 'authenticate') {
|
|
590
|
+
fail(id, -32602, 'Use the terminal login method: workbuddy login');
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
if (method === 'auth/logout' || method === 'logout') {
|
|
594
|
+
Promise.resolve(deps.logout()).then(
|
|
595
|
+
() => reply(id, {}),
|
|
596
|
+
err => fail(id, -32603, err.message || 'logout failed')
|
|
597
|
+
);
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
if (method === 'session/new') {
|
|
601
|
+
const cwd = params?.cwd || process.cwd();
|
|
602
|
+
const model = params?.model || params?._meta?.model || defaultModel;
|
|
603
|
+
const session = activate(saveSession({
|
|
604
|
+
id: createSessionId(),
|
|
605
|
+
cwd,
|
|
606
|
+
model,
|
|
607
|
+
title: '',
|
|
608
|
+
mode: 'default',
|
|
609
|
+
createdAt: Date.now(),
|
|
610
|
+
updatedAt: Date.now(),
|
|
611
|
+
messages: [{ role: 'system', content: systemPrompt(cwd) }]
|
|
612
|
+
}));
|
|
613
|
+
reply(id, sessionPayload(session));
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
if (method === 'session/load' || method === 'session/resume') {
|
|
617
|
+
const session = requireSession(params?.sessionId);
|
|
618
|
+
if (!session) {
|
|
619
|
+
fail(id, -32002, `Session not found: ${params?.sessionId || ''}`);
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
if (params?.cwd) session.cwd = params.cwd;
|
|
623
|
+
replay(session);
|
|
624
|
+
reply(id, sessionPayload(session));
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
if (method === 'session/list') {
|
|
628
|
+
const sessions = listSessions().slice(0, 100).map(session => ({
|
|
629
|
+
sessionId: session.id,
|
|
630
|
+
cwd: session.cwd,
|
|
631
|
+
title: session.title || '',
|
|
632
|
+
updatedAt: new Date(session.updatedAt || session.createdAt || Date.now()).toISOString()
|
|
633
|
+
}));
|
|
634
|
+
reply(id, { sessions });
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
if (method === 'session/close') {
|
|
638
|
+
active.delete(params?.sessionId);
|
|
639
|
+
reply(id, {});
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
if (method === 'session/cancel') {
|
|
643
|
+
aborters.get(params?.sessionId)?.abort();
|
|
644
|
+
if (id !== undefined) reply(id, {});
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if (method === 'session/prompt') {
|
|
648
|
+
enqueuePrompt(msg);
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
if (method === 'session/set_model') {
|
|
652
|
+
const session = requireSession(params?.sessionId);
|
|
653
|
+
if (!session) {
|
|
654
|
+
fail(id, -32002, `Session not found: ${params?.sessionId || ''}`);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
session.model = params?.modelId || session.model;
|
|
658
|
+
session.updatedAt = Date.now();
|
|
659
|
+
saveSession(session);
|
|
660
|
+
reply(id, sessionPayload(session));
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
if (method === 'session/set_config_option') {
|
|
664
|
+
const session = requireSession(params?.sessionId);
|
|
665
|
+
if (!session) {
|
|
666
|
+
fail(id, -32002, `Session not found: ${params?.sessionId || ''}`);
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
if (params?.configId === 'model' && params?.value) session.model = String(params.value);
|
|
670
|
+
session.updatedAt = Date.now();
|
|
671
|
+
saveSession(session);
|
|
672
|
+
reply(id, {
|
|
673
|
+
configOptions: sessionPayload(session).configOptions
|
|
674
|
+
});
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
if (method === 'session/set_mode') {
|
|
678
|
+
const session = requireSession(params?.sessionId);
|
|
679
|
+
if (!session) {
|
|
680
|
+
fail(id, -32002, `Session not found: ${params?.sessionId || ''}`);
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
session.mode = params?.modeId || 'default';
|
|
684
|
+
session.updatedAt = Date.now();
|
|
685
|
+
saveSession(session);
|
|
686
|
+
reply(id, {});
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
fail(id, -32601, `Method not found: ${method}`);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function onMessage(msg) {
|
|
693
|
+
if (!msg || typeof msg !== 'object') return;
|
|
694
|
+
if (msg.method && msg.id !== undefined) {
|
|
695
|
+
onRequest(msg);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (msg.id !== undefined && (Object.prototype.hasOwnProperty.call(msg, 'result') || msg.error)) {
|
|
699
|
+
const waiter = pending.get(msg.id);
|
|
700
|
+
if (!waiter) return;
|
|
701
|
+
pending.delete(msg.id);
|
|
702
|
+
if (msg.error) {
|
|
703
|
+
const err = new Error(msg.error.message || 'ACP client error');
|
|
704
|
+
err.code = msg.error.code;
|
|
705
|
+
waiter.reject(err);
|
|
706
|
+
} else {
|
|
707
|
+
waiter.resolve(msg.result);
|
|
708
|
+
}
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (msg.method === 'session/cancel') {
|
|
712
|
+
aborters.get(msg.params?.sessionId)?.abort();
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
let buffer = '';
|
|
717
|
+
process.stdin.setEncoding('utf8');
|
|
718
|
+
process.stdin.on('data', chunk => {
|
|
719
|
+
buffer += chunk;
|
|
720
|
+
for (;;) {
|
|
721
|
+
const nl = buffer.indexOf('\n');
|
|
722
|
+
if (nl < 0) break;
|
|
723
|
+
const line = buffer.slice(0, nl).trim();
|
|
724
|
+
buffer = buffer.slice(nl + 1);
|
|
725
|
+
if (!line) continue;
|
|
726
|
+
try {
|
|
727
|
+
onMessage(JSON.parse(line));
|
|
728
|
+
} catch (err) {
|
|
729
|
+
debug(err.message);
|
|
730
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
|
|
735
|
+
await new Promise(resolve => {
|
|
736
|
+
process.stdin.on('end', resolve);
|
|
737
|
+
process.stdin.resume();
|
|
738
|
+
});
|
|
739
|
+
}
|