@vincentbanana/bananacli 0.7.1 → 0.8.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/dist/agent/loop.js +4 -1
- package/dist/providers/anthropic.js +38 -6
- package/dist/providers/openai.js +17 -7
- package/dist/providers/reasoning.js +64 -0
- package/dist/server/ui-server.js +325 -16
- package/dist/session/store.js +12 -1
- package/dist/ui/app.js +481 -46
- package/dist/ui/index.html +37 -2
- package/dist/ui/style.css +147 -0
- package/package.json +4 -2
package/dist/server/ui-server.js
CHANGED
|
@@ -18,13 +18,15 @@ import { createRequire } from 'node:module';
|
|
|
18
18
|
import { TerminalManager, loadPty, normalizeCwd } from "./terminal.js";
|
|
19
19
|
import { bananaHome } from "../config/config.js";
|
|
20
20
|
import { runTurn } from "../agent/loop.js";
|
|
21
|
+
import { REASONING_LEVELS, supportsReasoning, } from "../providers/reasoning.js";
|
|
21
22
|
import { compactMessages } from "../agent/context.js";
|
|
22
23
|
import { createProvider } from "../providers/index.js";
|
|
23
24
|
import { estimateCost, formatCost, resolvePricing } from "../providers/pricing.js";
|
|
24
|
-
import { SessionStore } from "../session/store.js";
|
|
25
|
+
import { SessionStore, deriveTitle } from "../session/store.js";
|
|
25
26
|
import { BackupStore, newTurnId } from "../session/backups.js";
|
|
26
27
|
import { allTools, permissionFor, summarizeInput } from "../tools/index.js";
|
|
27
28
|
import { loadPluginTools, pluginTemplate } from "../tools/plugins.js";
|
|
29
|
+
import { formatTodos } from "../tools/todo.js";
|
|
28
30
|
import { resolvePath } from "../tools/fs.js";
|
|
29
31
|
import { commands, findCommand, suggestCommand } from "../cli/commands.js";
|
|
30
32
|
import { completeCommand, completeFileReference } from "../cli/completion.js";
|
|
@@ -50,6 +52,26 @@ const IMAGE_TYPES = {
|
|
|
50
52
|
};
|
|
51
53
|
const MAX_IMAGE_BYTES = 4 * 1024 * 1024;
|
|
52
54
|
const MAX_FILE_BYTES = 400 * 1024;
|
|
55
|
+
const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
|
|
56
|
+
const MAX_ATTACHMENT_TEXT = 120_000;
|
|
57
|
+
const PLAN_TOOLS = new Set([
|
|
58
|
+
'read_file', 'list_dir', 'glob', 'grep', 'web_search', 'web_fetch', 'todo_read', 'todo_write',
|
|
59
|
+
]);
|
|
60
|
+
const ATTACHMENT_MIME = {
|
|
61
|
+
'.txt': 'text/plain', '.md': 'text/markdown', '.json': 'application/json', '.js': 'text/javascript',
|
|
62
|
+
'.mjs': 'text/javascript', '.cjs': 'text/javascript', '.ts': 'text/typescript', '.tsx': 'text/typescript',
|
|
63
|
+
'.jsx': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.htm': 'text/html',
|
|
64
|
+
'.xml': 'application/xml', '.yml': 'text/yaml', '.yaml': 'text/yaml', '.toml': 'text/toml',
|
|
65
|
+
'.py': 'text/x-python', '.go': 'text/x-go', '.rs': 'text/x-rust', '.java': 'text/x-java',
|
|
66
|
+
'.c': 'text/x-c', '.h': 'text/x-c', '.cpp': 'text/x-c++', '.hpp': 'text/x-c++',
|
|
67
|
+
'.sh': 'text/x-sh', '.bash': 'text/x-sh', '.ps1': 'text/x-powershell', '.sql': 'text/x-sql',
|
|
68
|
+
'.pdf': 'application/pdf', '.doc': 'application/msword',
|
|
69
|
+
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
70
|
+
'.xls': 'application/vnd.ms-excel',
|
|
71
|
+
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
72
|
+
'.zip': 'application/zip', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
73
|
+
'.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',
|
|
74
|
+
};
|
|
53
75
|
const TEXT_EXT = new Set([
|
|
54
76
|
'.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.json', '.md', '.txt', '.yml', '.yaml',
|
|
55
77
|
'.toml', '.css', '.scss', '.html', '.sh', '.bash', '.zsh', '.py', '.go', '.rs', '.java',
|
|
@@ -189,6 +211,84 @@ function lineDiff(before, after) {
|
|
|
189
211
|
});
|
|
190
212
|
return { lines, additions, deletions, truncated };
|
|
191
213
|
}
|
|
214
|
+
function attachmentKind(name, mime = '') {
|
|
215
|
+
const ext = extname(name).toLowerCase();
|
|
216
|
+
const type = (mime || ATTACHMENT_MIME[ext] || '').toLowerCase();
|
|
217
|
+
if (type.startsWith('image/') && ext !== '.svg')
|
|
218
|
+
return 'image';
|
|
219
|
+
if (type === 'application/pdf' || ext === '.pdf')
|
|
220
|
+
return 'pdf';
|
|
221
|
+
if (type.startsWith('text/') ||
|
|
222
|
+
/(json|xml|javascript|yaml|toml|sql|python|x-go|x-rust|x-java|x-c|x-sh|x-powershell)/.test(type) ||
|
|
223
|
+
TEXT_EXT.has(ext)) {
|
|
224
|
+
return 'text';
|
|
225
|
+
}
|
|
226
|
+
return 'binary';
|
|
227
|
+
}
|
|
228
|
+
function formatBytes(bytes) {
|
|
229
|
+
if (!bytes)
|
|
230
|
+
return '';
|
|
231
|
+
if (bytes < 1024)
|
|
232
|
+
return `${bytes} B`;
|
|
233
|
+
if (bytes < 1024 * 1024)
|
|
234
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
235
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
236
|
+
}
|
|
237
|
+
/** 把非图片附件转成给模型的文本上下文;PDF/Office/二进制只给路径和元信息。 */
|
|
238
|
+
async function attachmentContextFor(items) {
|
|
239
|
+
const blocks = [];
|
|
240
|
+
for (const item of items) {
|
|
241
|
+
const kind = item.kind ?? attachmentKind(item.name, item.mime);
|
|
242
|
+
const meta = `${item.name}(${kind},${formatBytes(item.size) || '大小未知'})`;
|
|
243
|
+
if (kind === 'text') {
|
|
244
|
+
try {
|
|
245
|
+
const info = await stat(item.path);
|
|
246
|
+
if (info.size <= MAX_FILE_BYTES) {
|
|
247
|
+
const content = await readFile(item.path, 'utf8');
|
|
248
|
+
blocks.push(`### 附件:${meta}\n路径:${item.path}\n\n\`\`\`\n${content.slice(0, MAX_ATTACHMENT_TEXT)}${content.length > MAX_ATTACHMENT_TEXT ? '\n…[已截断]' : ''}\n\`\`\``);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
/* 读不到就退化成路径说明 */
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (kind === 'pdf' || kind === 'binary') {
|
|
257
|
+
blocks.push(`### 附件:${meta}\n路径:${item.path}\n(未解析正文;需要时用工具按路径读取或让用户提供预览。)`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (!blocks.length)
|
|
261
|
+
return '';
|
|
262
|
+
return `用户附带了以下文件:\n\n${blocks.join('\n\n')}`;
|
|
263
|
+
}
|
|
264
|
+
function planFallbackItems(text) {
|
|
265
|
+
const lines = text.split(/\r?\n/);
|
|
266
|
+
const items = [];
|
|
267
|
+
for (const line of lines) {
|
|
268
|
+
const match = /^\s*(?:\d+[.)、]|[-*])\s+(.{2,120})$/.exec(line);
|
|
269
|
+
if (!match)
|
|
270
|
+
continue;
|
|
271
|
+
const value = match[1].replace(/[*`#]/g, '').trim();
|
|
272
|
+
if (!value || /^```/.test(value))
|
|
273
|
+
continue;
|
|
274
|
+
items.push({ text: value, status: 'pending' });
|
|
275
|
+
if (items.length >= 8)
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
return items;
|
|
279
|
+
}
|
|
280
|
+
function planSystemPrompt(base) {
|
|
281
|
+
return [
|
|
282
|
+
base,
|
|
283
|
+
'',
|
|
284
|
+
'## 当前是 Plan 模式(只读)',
|
|
285
|
+
'你正在做方案设计,不是执行。不要修改文件,也不要运行会改变状态的命令。',
|
|
286
|
+
'先读相关代码和配置,确认现状后再给计划,禁止凭空猜文件或 API。',
|
|
287
|
+
'必须调用 todo_write 生成 3–7 项结构化计划,每项写清要做什么;尽量在正文里补充涉及文件、验证方式和风险。',
|
|
288
|
+
'计划写完后停下,等待用户批准。不要声称已经完成改动。',
|
|
289
|
+
'用户批准后系统会切到 Build 模式并让你按清单执行。',
|
|
290
|
+
].join('\n');
|
|
291
|
+
}
|
|
192
292
|
/** 启动只监听回环地址的本地 GUI 服务;token 保护所有接口。 */
|
|
193
293
|
export async function startUiServer(options) {
|
|
194
294
|
const { config, store } = options;
|
|
@@ -213,8 +313,13 @@ export async function startUiServer(options) {
|
|
|
213
313
|
const provider = () => createProvider(config.current, config);
|
|
214
314
|
const backups = (sessionId) => new BackupStore(join(bananaHome(), 'backups'), sessionId);
|
|
215
315
|
const info = async (session) => ({
|
|
216
|
-
version: '0.
|
|
316
|
+
version: '0.8.0',
|
|
217
317
|
provider: { name: config.current, model: config.providers[config.current]?.model ?? '', protocol: config.providers[config.current]?.protocol ?? 'openai' },
|
|
318
|
+
reasoning: {
|
|
319
|
+
level: session.reasoning ?? 'standard',
|
|
320
|
+
levels: REASONING_LEVELS,
|
|
321
|
+
supported: supportsReasoning(config.current, config.providers[config.current]?.protocol ?? 'openai', config.providers[config.current]?.model ?? ''),
|
|
322
|
+
},
|
|
218
323
|
providers: Object.entries(config.providers).map(([name, item]) => ({
|
|
219
324
|
name,
|
|
220
325
|
model: item.model,
|
|
@@ -238,8 +343,55 @@ export async function startUiServer(options) {
|
|
|
238
343
|
messages: session.messages,
|
|
239
344
|
todos: session.todos ?? [],
|
|
240
345
|
usage: session.usage ?? { inputTokens: 0, outputTokens: 0 },
|
|
346
|
+
mode: session.mode ?? 'build',
|
|
347
|
+
reasoning: session.reasoning ?? 'standard',
|
|
348
|
+
titleSource: session.titleSource ?? 'auto',
|
|
349
|
+
plan: session.plan ?? null,
|
|
241
350
|
},
|
|
242
351
|
});
|
|
352
|
+
/**
|
|
353
|
+
* 首轮结束后用当前 provider 生成 8–12 字标题。
|
|
354
|
+
* 失败 / 超时 / 返回不合规时回退到首条消息截断,绝不阻塞对话收尾太久。
|
|
355
|
+
*/
|
|
356
|
+
const generateSessionTitle = async (session) => {
|
|
357
|
+
const firstUser = session.messages.find((message) => message.role === 'user');
|
|
358
|
+
const fallback = deriveTitle(firstUser?.content ?? '');
|
|
359
|
+
if (session.titleSource === 'user' || !firstUser?.content.trim())
|
|
360
|
+
return session.title || fallback;
|
|
361
|
+
const firstAssistant = session.messages.find((message) => message.role === 'assistant');
|
|
362
|
+
const controller = new AbortController();
|
|
363
|
+
const timer = setTimeout(() => controller.abort(), 3200);
|
|
364
|
+
try {
|
|
365
|
+
const result = await provider().generate({
|
|
366
|
+
messages: [{
|
|
367
|
+
role: 'user',
|
|
368
|
+
content: `用户:${firstUser.content.slice(0, 1200)}\n\n` +
|
|
369
|
+
`助手:${(firstAssistant?.content ?? '').slice(0, 1200)}\n\n` +
|
|
370
|
+
'请给这段对话起一个 8–12 个字的中文标题。只输出标题,不要引号、句号、前缀或解释。',
|
|
371
|
+
}],
|
|
372
|
+
system: '你是标题生成器,只输出一个简洁的中文标题。',
|
|
373
|
+
tools: [],
|
|
374
|
+
signal: controller.signal,
|
|
375
|
+
maxTokens: 32,
|
|
376
|
+
temperature: 0.2,
|
|
377
|
+
});
|
|
378
|
+
const raw = (result.message.content ?? '').split(/\r?\n/)[0] ?? '';
|
|
379
|
+
const title = raw
|
|
380
|
+
.replace(/^#+\s*/, '')
|
|
381
|
+
.replace(/^标题[::]\s*/, '')
|
|
382
|
+
.replace(/[「」“”"'《》]/g, '')
|
|
383
|
+
.replace(/[。.!!??,,;;::]+$/g, '')
|
|
384
|
+
.trim()
|
|
385
|
+
.slice(0, 20);
|
|
386
|
+
return title.length >= 2 ? title : fallback;
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
return fallback;
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
clearTimeout(timer);
|
|
393
|
+
}
|
|
394
|
+
};
|
|
243
395
|
const listSessions = async () => (await store.list()).map((item) => ({
|
|
244
396
|
id: item.id,
|
|
245
397
|
title: item.title,
|
|
@@ -363,6 +515,43 @@ export async function startUiServer(options) {
|
|
|
363
515
|
return json(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
364
516
|
}
|
|
365
517
|
}
|
|
518
|
+
if (path === '/api/attachment' && req.method === 'GET') {
|
|
519
|
+
const requested = url.searchParams.get('path') ?? '';
|
|
520
|
+
const root = resolve(join(bananaHome(), 'attachments'));
|
|
521
|
+
const absolute = resolve(requested);
|
|
522
|
+
if (absolute !== root && !absolute.startsWith(root + sep)) {
|
|
523
|
+
return json(res, 403, { error: '只能预览附件目录里的文件' });
|
|
524
|
+
}
|
|
525
|
+
try {
|
|
526
|
+
const info = await stat(absolute);
|
|
527
|
+
if (!info.isFile())
|
|
528
|
+
return json(res, 400, { error: '不是文件' });
|
|
529
|
+
const name = absolute.split(/[\\/]/).pop() ?? '附件';
|
|
530
|
+
const ext = extname(absolute).toLowerCase();
|
|
531
|
+
const mime = ATTACHMENT_MIME[ext] ?? 'application/octet-stream';
|
|
532
|
+
const kind = attachmentKind(name, mime);
|
|
533
|
+
const base = { path: absolute, name, bytes: info.size, mime, kind };
|
|
534
|
+
if (info.size > MAX_ATTACHMENT_BYTES) {
|
|
535
|
+
return json(res, 200, { ...base, tooLarge: true });
|
|
536
|
+
}
|
|
537
|
+
if (kind === 'image' || (kind === 'pdf' && info.size <= 12 * 1024 * 1024)) {
|
|
538
|
+
const buffer = await readFile(absolute);
|
|
539
|
+
return json(res, 200, { ...base, dataUrl: `data:${mime};base64,${buffer.toString('base64')}` });
|
|
540
|
+
}
|
|
541
|
+
if (kind === 'text') {
|
|
542
|
+
const content = await readFile(absolute, 'utf8');
|
|
543
|
+
return json(res, 200, {
|
|
544
|
+
...base,
|
|
545
|
+
content: content.slice(0, MAX_ATTACHMENT_TEXT),
|
|
546
|
+
truncated: content.length > MAX_ATTACHMENT_TEXT,
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
return json(res, 200, base);
|
|
550
|
+
}
|
|
551
|
+
catch (error) {
|
|
552
|
+
return json(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
553
|
+
}
|
|
554
|
+
}
|
|
366
555
|
if (path === '/api/session' && req.method === 'POST') {
|
|
367
556
|
const body = await readJson(req);
|
|
368
557
|
if (body.action === 'new') {
|
|
@@ -371,6 +560,7 @@ export async function startUiServer(options) {
|
|
|
371
560
|
}
|
|
372
561
|
else if (body.action === 'rename') {
|
|
373
562
|
session.title = body.title?.trim() || session.title;
|
|
563
|
+
session.titleSource = 'user';
|
|
374
564
|
await store.save(session);
|
|
375
565
|
}
|
|
376
566
|
else if (body.action === 'switch') {
|
|
@@ -393,9 +583,24 @@ export async function startUiServer(options) {
|
|
|
393
583
|
else if (body.action === 'clear') {
|
|
394
584
|
session.messages = [];
|
|
395
585
|
session.todos = [];
|
|
586
|
+
session.plan = undefined;
|
|
396
587
|
session.usage = { inputTokens: 0, outputTokens: 0 };
|
|
397
588
|
await store.save(session);
|
|
398
589
|
}
|
|
590
|
+
else if (body.action === 'mode') {
|
|
591
|
+
const mode = body.value === 'plan' ? 'plan' : 'build';
|
|
592
|
+
session.mode = mode;
|
|
593
|
+
if (mode === 'build' && session.plan?.status === 'cancelled')
|
|
594
|
+
session.plan = undefined;
|
|
595
|
+
await store.save(session);
|
|
596
|
+
}
|
|
597
|
+
else if (body.action === 'reasoning') {
|
|
598
|
+
const level = body.value;
|
|
599
|
+
if (REASONING_LEVELS.includes(level)) {
|
|
600
|
+
session.reasoning = level;
|
|
601
|
+
await store.save(session);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
399
604
|
if (turn)
|
|
400
605
|
turn.session = session;
|
|
401
606
|
activeId = session.id;
|
|
@@ -581,14 +786,25 @@ export async function startUiServer(options) {
|
|
|
581
786
|
return json(res, 200, { restored: result.restored, deleted: result.deleted, had: Boolean(result.turn) });
|
|
582
787
|
}
|
|
583
788
|
if (path === '/api/attach' && req.method === 'POST') {
|
|
584
|
-
const name = decodeURIComponent(new URL(req.url ?? '/', 'http://x').searchParams.get('name') ?? '
|
|
789
|
+
const name = decodeURIComponent(new URL(req.url ?? '/', 'http://x').searchParams.get('name') ?? 'file');
|
|
585
790
|
const body = await readBody(req);
|
|
586
791
|
const buffer = Buffer.from(body, 'base64');
|
|
792
|
+
if (buffer.byteLength > MAX_ATTACHMENT_BYTES) {
|
|
793
|
+
return json(res, 413, { error: '附件超过 20MB' });
|
|
794
|
+
}
|
|
587
795
|
const dir = join(bananaHome(), 'attachments');
|
|
588
796
|
await mkdir(dir, { recursive: true });
|
|
589
|
-
const
|
|
797
|
+
const ext = extname(name).toLowerCase();
|
|
798
|
+
const file = join(dir, `${Date.now().toString(36)}-${randomBytes(4).toString('hex')}${ext}`);
|
|
590
799
|
await writeFile(file, buffer);
|
|
591
|
-
|
|
800
|
+
const mime = ATTACHMENT_MIME[ext] ?? 'application/octet-stream';
|
|
801
|
+
return json(res, 200, {
|
|
802
|
+
path: file,
|
|
803
|
+
name,
|
|
804
|
+
bytes: buffer.byteLength,
|
|
805
|
+
mime,
|
|
806
|
+
kind: attachmentKind(name, mime),
|
|
807
|
+
});
|
|
592
808
|
}
|
|
593
809
|
if (path === '/api/approve' && req.method === 'POST') {
|
|
594
810
|
const body = await readJson(req);
|
|
@@ -609,6 +825,37 @@ export async function startUiServer(options) {
|
|
|
609
825
|
}
|
|
610
826
|
return json(res, 200, { ok: Boolean(turn) });
|
|
611
827
|
}
|
|
828
|
+
if (path === '/api/plan' && req.method === 'POST') {
|
|
829
|
+
const body = await readJson(req);
|
|
830
|
+
if (body.action === 'approve') {
|
|
831
|
+
if (!session.plan)
|
|
832
|
+
return json(res, 409, { error: '当前没有待批准的计划' });
|
|
833
|
+
session.plan = {
|
|
834
|
+
...session.plan,
|
|
835
|
+
status: 'approved',
|
|
836
|
+
approvedAt: new Date().toISOString(),
|
|
837
|
+
items: session.plan.items?.length ? session.plan.items : (body.items ?? []),
|
|
838
|
+
};
|
|
839
|
+
if (session.plan.items.length)
|
|
840
|
+
session.todos = session.plan.items;
|
|
841
|
+
session.mode = 'build';
|
|
842
|
+
}
|
|
843
|
+
else if (body.action === 'cancel') {
|
|
844
|
+
if (session.plan)
|
|
845
|
+
session.plan = { ...session.plan, status: 'cancelled' };
|
|
846
|
+
session.mode = 'build';
|
|
847
|
+
}
|
|
848
|
+
else if (body.action === 'revise') {
|
|
849
|
+
if (session.plan)
|
|
850
|
+
session.plan = { ...session.plan, status: 'pending' };
|
|
851
|
+
session.mode = 'plan';
|
|
852
|
+
}
|
|
853
|
+
await store.save(session);
|
|
854
|
+
return json(res, 200, {
|
|
855
|
+
info: await info(session),
|
|
856
|
+
sessions: await listSessions(),
|
|
857
|
+
});
|
|
858
|
+
}
|
|
612
859
|
if (path === '/api/chat' && req.method === 'POST') {
|
|
613
860
|
const body = await readJson(req);
|
|
614
861
|
if (turn)
|
|
@@ -845,18 +1092,56 @@ export async function startUiServer(options) {
|
|
|
845
1092
|
finish();
|
|
846
1093
|
return;
|
|
847
1094
|
}
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
1095
|
+
// 只认附件目录里的文件:前端传来的路径也要过一遍沙箱,避免变成任意文件读取。
|
|
1096
|
+
const attachmentRoot = resolve(join(bananaHome(), 'attachments'));
|
|
1097
|
+
const incoming = body.attachments?.length
|
|
1098
|
+
? body.attachments
|
|
1099
|
+
: (body.images ?? []).map((file) => ({
|
|
1100
|
+
name: file.split(/[\\/]/).pop() ?? '附件',
|
|
1101
|
+
path: file,
|
|
1102
|
+
}));
|
|
1103
|
+
const safeAttachments = [];
|
|
1104
|
+
for (const item of incoming) {
|
|
1105
|
+
const absolute = resolve(String(item.path ?? ''));
|
|
1106
|
+
if (absolute !== attachmentRoot && !absolute.startsWith(attachmentRoot + sep))
|
|
1107
|
+
continue;
|
|
1108
|
+
if (!existsSync(absolute))
|
|
1109
|
+
continue;
|
|
1110
|
+
let bytes = item.size;
|
|
1111
|
+
try {
|
|
1112
|
+
bytes = (await stat(absolute)).size;
|
|
1113
|
+
}
|
|
1114
|
+
catch {
|
|
1115
|
+
continue;
|
|
1116
|
+
}
|
|
1117
|
+
safeAttachments.push({
|
|
1118
|
+
name: item.name || (absolute.split(/[\\/]/).pop() ?? '附件'),
|
|
1119
|
+
path: absolute,
|
|
1120
|
+
size: bytes,
|
|
1121
|
+
mime: item.mime,
|
|
1122
|
+
kind: item.kind ?? attachmentKind(item.name, item.mime ?? ''),
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
const dataUrls = await Promise.all(safeAttachments
|
|
1126
|
+
.filter((item) => item.kind === 'image')
|
|
1127
|
+
.map(async (item) => {
|
|
1128
|
+
const type = IMAGE_TYPES[extname(item.path).toLowerCase()];
|
|
1129
|
+
if (!type || (item.size ?? 0) > MAX_IMAGE_BYTES)
|
|
852
1130
|
return null;
|
|
853
|
-
const
|
|
854
|
-
const buffer = await readFile(absolute);
|
|
1131
|
+
const buffer = await readFile(item.path);
|
|
855
1132
|
if (buffer.byteLength > MAX_IMAGE_BYTES)
|
|
856
1133
|
return null;
|
|
857
1134
|
return `data:${type};base64,${buffer.toString('base64')}`;
|
|
858
1135
|
}));
|
|
859
|
-
const
|
|
1136
|
+
const attachmentContext = await attachmentContextFor(safeAttachments.filter((item) => item.kind !== 'image'));
|
|
1137
|
+
const activeTools = session.mode === 'plan'
|
|
1138
|
+
? options.tools.filter((tool) => PLAN_TOOLS.has(tool.name))
|
|
1139
|
+
: options.tools;
|
|
1140
|
+
const todoContext = session.todos?.length
|
|
1141
|
+
? `\n\n## 当前任务清单\n${formatTodos(session.todos)}\n每完成一项就调用 todo_write 更新状态,不要只口头汇报。`
|
|
1142
|
+
: '';
|
|
1143
|
+
const activeSystem = (session.mode === 'plan' ? planSystemPrompt(config.systemPrompt) : config.systemPrompt) + todoContext;
|
|
1144
|
+
const wasFirstTurn = !session.messages.some((message) => message.role === 'assistant');
|
|
860
1145
|
session.todos ??= [];
|
|
861
1146
|
const recorder = await backups(session.id).beginTurn(newTurnId(), config.workspace);
|
|
862
1147
|
const approve = async (kind, summary, preview) => {
|
|
@@ -881,15 +1166,16 @@ export async function startUiServer(options) {
|
|
|
881
1166
|
try {
|
|
882
1167
|
result = await runTurn({
|
|
883
1168
|
provider: provider(),
|
|
884
|
-
tools:
|
|
1169
|
+
tools: activeTools,
|
|
885
1170
|
permissions: config.permissions,
|
|
886
|
-
system:
|
|
1171
|
+
system: activeSystem,
|
|
887
1172
|
maxSteps: config.maxSteps,
|
|
888
1173
|
maxContextChars: config.maxContextChars,
|
|
889
1174
|
toolsWorkspace: config.workspace,
|
|
890
1175
|
allowOutsideWorkspace: config.allowOutsideWorkspace,
|
|
891
1176
|
signal: controller.signal,
|
|
892
1177
|
todos: session.todos,
|
|
1178
|
+
reasoning: session.reasoning ?? 'standard',
|
|
893
1179
|
recordChange: (path, beforeContent) => recorder.record(path, beforeContent),
|
|
894
1180
|
onText: (chunk) => send('text', { chunk }),
|
|
895
1181
|
onReasoning: (chunk) => send('reasoning', { chunk }),
|
|
@@ -918,6 +1204,9 @@ export async function startUiServer(options) {
|
|
|
918
1204
|
// 详情面板用:命令输出 / 搜索结果等,最多 8KB
|
|
919
1205
|
detail: toolResult.content.slice(0, 8000),
|
|
920
1206
|
});
|
|
1207
|
+
// 任务清单不等到整轮结束才更新,todo_write 完成立刻推
|
|
1208
|
+
if (name === 'todo_write')
|
|
1209
|
+
send('todos', { todos: session.todos ?? [] });
|
|
921
1210
|
},
|
|
922
1211
|
onToolOutput: (chunk, stream, id) => {
|
|
923
1212
|
if (!id)
|
|
@@ -931,7 +1220,7 @@ export async function startUiServer(options) {
|
|
|
931
1220
|
onCompact: () => send('status', { message: '已压缩历史对话' }),
|
|
932
1221
|
onRetry: (info) => send('status', { message: `网络重试 ${info.attempt}:${info.reason}` }),
|
|
933
1222
|
approve,
|
|
934
|
-
}, session.messages, body.message, dataUrls.filter((item) => Boolean(item)));
|
|
1223
|
+
}, session.messages, body.message, dataUrls.filter((item) => Boolean(item)), safeAttachments, attachmentContext);
|
|
935
1224
|
}
|
|
936
1225
|
catch (error) {
|
|
937
1226
|
// 任何异常都要以 error 事件收尾,否则前端会一直等下去
|
|
@@ -945,6 +1234,24 @@ export async function startUiServer(options) {
|
|
|
945
1234
|
session.messages = result.messages;
|
|
946
1235
|
session.provider = config.current;
|
|
947
1236
|
session.model = session.model || provider().model;
|
|
1237
|
+
// Plan 模式跑完就停在这里等审批;把清单抽成可执行计划卡。
|
|
1238
|
+
if (session.mode === 'plan' && result.stopReason === 'done') {
|
|
1239
|
+
const lastAssistant = [...result.messages].reverse().find((message) => message.role === 'assistant');
|
|
1240
|
+
const summary = lastAssistant?.content?.trim() ?? '';
|
|
1241
|
+
const items = session.todos?.length ? [...session.todos] : planFallbackItems(summary);
|
|
1242
|
+
if (summary || items.length) {
|
|
1243
|
+
session.plan = {
|
|
1244
|
+
status: 'pending',
|
|
1245
|
+
items,
|
|
1246
|
+
summary: summary.slice(0, 4000),
|
|
1247
|
+
createdAt: new Date().toISOString(),
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
if (wasFirstTurn && session.titleSource !== 'user' && result.stopReason === 'done') {
|
|
1252
|
+
send('status', { message: '正在生成会话标题…' });
|
|
1253
|
+
session.title = await generateSessionTitle(session);
|
|
1254
|
+
}
|
|
948
1255
|
const pricing = resolvePricing(session.model, config.providers[config.current]?.pricing);
|
|
949
1256
|
const cost = estimateCost(result.usage, pricing);
|
|
950
1257
|
session.usage = {
|
|
@@ -961,7 +1268,9 @@ export async function startUiServer(options) {
|
|
|
961
1268
|
ms: Date.now() - started,
|
|
962
1269
|
usage: result.usage,
|
|
963
1270
|
cost: formatCost(cost),
|
|
964
|
-
todos:
|
|
1271
|
+
todos: session.todos ?? [],
|
|
1272
|
+
plan: session.plan,
|
|
1273
|
+
title: session.title,
|
|
965
1274
|
info: await info(session),
|
|
966
1275
|
});
|
|
967
1276
|
finish();
|
package/dist/session/store.js
CHANGED
|
@@ -36,6 +36,10 @@ export class SessionStore {
|
|
|
36
36
|
createdAt: now,
|
|
37
37
|
updatedAt: now,
|
|
38
38
|
messages: [],
|
|
39
|
+
todos: [],
|
|
40
|
+
mode: 'build',
|
|
41
|
+
reasoning: 'standard',
|
|
42
|
+
titleSource: 'auto',
|
|
39
43
|
};
|
|
40
44
|
}
|
|
41
45
|
async save(session) {
|
|
@@ -52,7 +56,14 @@ export class SessionStore {
|
|
|
52
56
|
return null;
|
|
53
57
|
try {
|
|
54
58
|
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
55
|
-
return {
|
|
59
|
+
return {
|
|
60
|
+
...parsed,
|
|
61
|
+
messages: parsed.messages ?? [],
|
|
62
|
+
todos: parsed.todos ?? [],
|
|
63
|
+
mode: parsed.mode === 'plan' ? 'plan' : 'build',
|
|
64
|
+
reasoning: parsed.reasoning === 'fast' || parsed.reasoning === 'deep' ? parsed.reasoning : 'standard',
|
|
65
|
+
titleSource: parsed.titleSource === 'user' ? 'user' : 'auto',
|
|
66
|
+
};
|
|
56
67
|
}
|
|
57
68
|
catch {
|
|
58
69
|
return null;
|