@vincentbanana/bananacli 0.8.3 → 0.8.5

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/README.md CHANGED
@@ -228,8 +228,8 @@ export default {
228
228
  | `glob` | – | `**/*.ts`、`{a,b}` 风格 glob |
229
229
  | `grep` | – | 正则搜代码,返回 `file:line` |
230
230
  | `shell` | shell | 执行命令,回传 stdout/stderr/退出码,带超时与输出截断 |
231
- | `web_search` | network | 优先 Tavily / Brave,回退 DuckDuckGo |
232
- | `web_fetch` | network | 抓 URL 转纯文本(HTML 去标签去脚本) |
231
+ | `web_search` | network | 联网搜索;默认合并 Bing / DuckDuckGo,配置 Tavily / Brave Key 自动升级;支持 depth=deep 读正文 |
232
+ | `web_fetch` | network | 抓 URL 转纯文本(HTML 去导航、脚本,保留正文段落) |
233
233
  | `todo_write` | – | 写入/更新任务清单(整表覆盖,随会话保存) |
234
234
  | `todo_read` | – | 读取当前任务清单 |
235
235
  | 插件工具 | 自定义 | `.banana/tools/` 下的脚本自动注册,权限类别由插件声明 |
@@ -257,7 +257,7 @@ export default {
257
257
 
258
258
  Anthropic 协议默认给 `system` 和工具定义打 `cache_control: ephemeral`(prompt caching,长对话能省不少钱);如果你的网关不认这个字段,在对应 provider 里设 `"promptCaching": false`。
259
259
 
260
- 环境变量:`ANTHROPIC_API_KEY` / `OPENAI_API_KEY` / `DEEPSEEK_API_KEY` / `MOONSHOT_API_KEY` / `DASHSCOPE_API_KEY` / `GEMINI_API_KEY` / `OPENROUTER_API_KEY`;搜索可选 `TAVILY_API_KEY` 或 `BRAVE_API_KEY`;临时覆盖用 `BANANA_PROVIDER` / `BANANA_MODEL` / `BANANA_BASE_URL` / `BANANA_SHOW_REASONING` / `BANANA_HOME` / `BANANA_CONFIG`。
260
+ 环境变量:`ANTHROPIC_API_KEY` / `OPENAI_API_KEY` / `DEEPSEEK_API_KEY` / `MOONSHOT_API_KEY` / `DASHSCOPE_API_KEY` / `GEMINI_API_KEY` / `OPENROUTER_API_KEY`;搜索可选 `TAVILY_API_KEY` 或 `BRAVE_API_KEY`(也可以直接在 GUI 设置 → 联网搜索里填);临时覆盖用 `BANANA_PROVIDER` / `BANANA_MODEL` / `BANANA_BASE_URL` / `BANANA_SHOW_REASONING` / `BANANA_HOME` / `BANANA_CONFIG`。
261
261
 
262
262
  `protocol` 只有两个值:`openai`(OpenAI 兼容)和 `anthropic`(Claude 原生)。绝大多数第三方服务都能用 `openai` 协议接进来。
263
263
 
@@ -323,7 +323,7 @@ npm publish
323
323
 
324
324
  - 模型名和 provider baseUrl 是内置默认值,不同服务可能需要 `/model` 或配置改一下。
325
325
  - 上下文压缩按字符数估算 token,超长会话建议调小 `maxContextChars`。
326
- - `web_search` 在没有 Tavily/Brave key 时走 DuckDuckGo HTML 抓取,无外网环境下会失败(会明确报错,不会假装成功)。
326
+ - `web_search` 在没有 Tavily/Brave key 时会同时抓 Bing 和 DuckDuckGo,合并去重后返回;两个源都不可用时明确报错,不会假装成功。开启「深度搜索」或传 `depth=deep` 会额外读取前几页正文。
327
327
  - 图片以 data URL 存进会话 JSON,多张大图会让会话文件变大(模型侧仍受单张 4MB 限制)。
328
328
  - `/undo` 只覆盖 `write_file` / `edit_file`;`shell` 命令和插件工具的副作用无法回滚。
329
329
  - 插件以当前进程权限运行,等同用户自己的代码,只应放可信脚本。
@@ -57,6 +57,7 @@ export async function runTurn(deps, messages, input, images, attachments, attach
57
57
  permissions: deps.permissions,
58
58
  todos,
59
59
  recordChange: deps.recordChange,
60
+ search: deps.search,
60
61
  };
61
62
  const tryCompact = async (aggressive) => {
62
63
  deps.onNotice?.(aggressive ? '上游报告上下文超限,正在压缩历史对话后重试…' : '上下文接近上限,正在压缩历史对话…');
@@ -121,7 +122,21 @@ export async function runTurn(deps, messages, input, images, attachments, attach
121
122
  if (calls.length === 0) {
122
123
  return { messages: convo, steps, usage, stopReason: 'done', compacted };
123
124
  }
124
- for (let index = 0; index < calls.length; index += 1) {
125
+ // 只读工具可以并发跑,并在同一轮里复用完全相同的调用结果。
126
+ // 写文件 / shell 仍然串行,避免顺序和副作用被打乱。
127
+ const READ_ONLY_TOOLS = new Set(['read_file', 'list_dir', 'glob', 'grep']);
128
+ const toolCache = new Map();
129
+ const recordResult = (call, toolResult) => {
130
+ deps.onToolEnd?.(call.name, toolResult, call.id);
131
+ convo.push({
132
+ role: 'tool',
133
+ toolCallId: call.id,
134
+ name: call.name,
135
+ content: toolResult.content,
136
+ isError: !toolResult.ok,
137
+ });
138
+ };
139
+ for (let index = 0; index < calls.length;) {
125
140
  const call = calls[index];
126
141
  if (deps.signal.aborted) {
127
142
  // 为所有未执行的 tool_use 补上结果,避免下一轮协议校验失败
@@ -143,8 +158,44 @@ export async function runTurn(deps, messages, input, images, attachments, attach
143
158
  ok: false,
144
159
  content: `未知工具 "${call.name}"。可用工具: ${[...tools.keys()].join(', ')}。请改用已有工具。`,
145
160
  };
146
- deps.onToolEnd?.(call.name, result, call.id);
147
- convo.push({ role: 'tool', toolCallId: call.id, name: call.name, content: result.content, isError: true });
161
+ recordResult(call, result);
162
+ index += 1;
163
+ continue;
164
+ }
165
+ if (READ_ONLY_TOOLS.has(call.name)) {
166
+ // 收集连续的只读调用一起执行;保持结果顺序与模型请求一致。
167
+ const batch = [];
168
+ let cursor = index;
169
+ while (cursor < calls.length &&
170
+ READ_ONLY_TOOLS.has(calls[cursor].name) &&
171
+ tools.has(calls[cursor].name)) {
172
+ const item = calls[cursor];
173
+ batch.push({
174
+ call: item,
175
+ input: (item.input && typeof item.input === 'object' ? item.input : {}),
176
+ });
177
+ cursor += 1;
178
+ }
179
+ for (const item of batch)
180
+ deps.onToolStart?.(item.call.name, item.input, item.call.id);
181
+ const results = await Promise.all(batch.map(async (item) => {
182
+ const key = `${item.call.name}\u0000${JSON.stringify(item.input)}`;
183
+ const cached = toolCache.get(key);
184
+ if (cached)
185
+ return cached;
186
+ const itemTool = tools.get(item.call.name);
187
+ const callContext = {
188
+ ...toolContext,
189
+ onOutput: (chunk, stream) => deps.onToolOutput?.(chunk, stream, item.call.id),
190
+ };
191
+ const result = await runTool(itemTool, item.input, callContext, permissionFor(deps.permissions, itemTool));
192
+ toolCache.set(key, result);
193
+ return result;
194
+ }));
195
+ for (let offset = 0; offset < batch.length; offset += 1) {
196
+ recordResult(batch[offset].call, results[offset]);
197
+ }
198
+ index = cursor;
148
199
  continue;
149
200
  }
150
201
  deps.onToolStart?.(call.name, input, call.id);
@@ -153,14 +204,10 @@ export async function runTurn(deps, messages, input, images, attachments, attach
153
204
  onOutput: (chunk, stream) => deps.onToolOutput?.(chunk, stream, call.id),
154
205
  };
155
206
  const toolResult = await runTool(tool, input, callContext, permissionFor(deps.permissions, tool));
156
- deps.onToolEnd?.(call.name, toolResult, call.id);
157
- convo.push({
158
- role: 'tool',
159
- toolCallId: call.id,
160
- name: call.name,
161
- content: toolResult.content,
162
- isError: !toolResult.ok,
163
- });
207
+ recordResult(call, toolResult);
208
+ // 一旦发生写操作/命令,之前的只读缓存可能过期。
209
+ toolCache.clear();
210
+ index += 1;
164
211
  }
165
212
  }
166
213
  return { messages: convo, steps, usage, stopReason: 'max_steps', compacted };
package/dist/cli/repl.js CHANGED
@@ -364,6 +364,7 @@ export async function startRepl(options) {
364
364
  allowOutsideWorkspace: config.allowOutsideWorkspace,
365
365
  signal: controller.signal,
366
366
  todos: session.todos,
367
+ search: config.search,
367
368
  recordChange: (path, before) => recorder.record(path, before),
368
369
  onText: (chunk) => {
369
370
  clearStatus();
@@ -156,6 +156,12 @@ function defaultConfig(workspace) {
156
156
  allowOutsideWorkspace: false,
157
157
  showReasoning: true,
158
158
  disabledPlugins: [],
159
+ search: {
160
+ provider: 'auto',
161
+ deep: false,
162
+ deepPages: 3,
163
+ language: 'en',
164
+ },
159
165
  };
160
166
  }
161
167
  async function readConfigFile(path) {
@@ -177,9 +183,10 @@ function merge(base, patch) {
177
183
  }
178
184
  return {
179
185
  ...base,
180
- ...Object.fromEntries(Object.entries(patch).filter(([key]) => key !== 'providers' && key !== 'permissions')),
186
+ ...Object.fromEntries(Object.entries(patch).filter(([key]) => key !== 'providers' && key !== 'permissions' && key !== 'search')),
181
187
  providers,
182
188
  permissions: { ...base.permissions, ...(patch.permissions ?? {}) },
189
+ search: { ...base.search, ...(patch.search ?? {}) },
183
190
  };
184
191
  }
185
192
  function applyEnvOverrides(config) {
@@ -310,6 +310,9 @@ export async function startUiServer(options) {
310
310
  // 当前会话记在服务进程内存里:新建对话后所有后续请求都认它,
311
311
  // 不再依赖「磁盘上谁最新」这种容易串台的推断。
312
312
  let activeId = null;
313
+ // 删光所有会话后保留一个“空白草稿”:它不落盘、不出现在侧栏,也不占标签。
314
+ // 用户发出第一条消息时才真正创建会话。
315
+ let blank = null;
313
316
  // 内嵌终端:不弹外部窗口,命令在当前工作区里执行,cd 之后的工作目录会被记住
314
317
  let terminalCwd = null;
315
318
  let terminalChild = null;
@@ -317,7 +320,7 @@ export async function startUiServer(options) {
317
320
  const provider = () => createProvider(config.current, config);
318
321
  const backups = (sessionId) => new BackupStore(join(bananaHome(), 'backups'), sessionId);
319
322
  const info = async (session) => ({
320
- version: '0.8.3',
323
+ version: '0.8.5',
321
324
  provider: { name: config.current, model: config.providers[config.current]?.model ?? '', protocol: config.providers[config.current]?.protocol ?? 'openai' },
322
325
  reasoning: {
323
326
  level: session.reasoning ?? 'standard',
@@ -339,11 +342,28 @@ export async function startUiServer(options) {
339
342
  permissions: config.permissions,
340
343
  systemPrompt: config.systemPrompt,
341
344
  showReasoning: config.showReasoning,
345
+ search: {
346
+ provider: config.search?.provider ?? 'auto',
347
+ deep: Boolean(config.search?.deep),
348
+ deepPages: Math.min(Math.max(Number(config.search?.deepPages) || 3, 1), 5),
349
+ language: config.search?.language ?? 'en',
350
+ tavily: {
351
+ saved: Boolean(config.search?.tavilyKey),
352
+ ready: Boolean(config.search?.tavilyKey || process.env['TAVILY_API_KEY'] || process.env['BANANA_TAVILY_KEY']),
353
+ env: 'TAVILY_API_KEY',
354
+ },
355
+ brave: {
356
+ saved: Boolean(config.search?.braveKey),
357
+ ready: Boolean(config.search?.braveKey || process.env['BRAVE_API_KEY'] || process.env['BANANA_BRAVE_KEY']),
358
+ env: 'BRAVE_API_KEY',
359
+ },
360
+ },
342
361
  disabledPlugins: config.disabledPlugins,
343
362
  tools: options.tools.map((tool) => ({ name: tool.name, approval: tool.approval, permission: permissionFor(config.permissions, tool) })),
344
363
  session: {
345
364
  id: session.id,
346
365
  title: session.title,
366
+ draft: blank === session,
347
367
  // 图片 base64 和附件全文只用于请求模型,不必每次 /api/info 全量回传前端。
348
368
  messages: session.messages.map(({ images, attachmentContext, ...message }) => ({
349
369
  ...message,
@@ -482,17 +502,23 @@ export async function startUiServer(options) {
482
502
  }
483
503
  let session = turn?.session ??
484
504
  (activeId ? await store.load(activeId) : null) ??
485
- (await store.lastActive().then(async (id) => (id ? await store.load(id) : null)));
505
+ (blank ? null : await store.lastActive().then(async (id) => (id ? await store.load(id) : null)));
486
506
  if (!session) {
487
- // 空会话也立刻落盘:否则每个请求都会重新 create,会话 id 一直变
488
- session = store.create();
489
- await store.save(session);
507
+ // 没有会话时用一个不落盘的草稿承接界面状态;发第一条消息才保存。
508
+ if (!blank)
509
+ blank = store.create();
510
+ session = blank;
511
+ activeId = null;
512
+ }
513
+ else if (session !== blank) {
514
+ blank = null;
515
+ activeId = session.id;
490
516
  }
491
- activeId = session.id;
492
517
  if (path === '/api/info' && req.method === 'GET')
493
518
  return json(res, 200, await info(session));
494
- if (path === '/api/sessions' && req.method === 'GET')
495
- return json(res, 200, { sessions: await listSessions(), current: session.id });
519
+ if (path === '/api/sessions' && req.method === 'GET') {
520
+ return json(res, 200, { sessions: await listSessions(), current: blank === session ? null : session.id });
521
+ }
496
522
  if (path === '/api/files' && req.method === 'GET') {
497
523
  const target = url.searchParams.get('path') ?? '.';
498
524
  try {
@@ -577,11 +603,13 @@ export async function startUiServer(options) {
577
603
  return json(res, 200, { session: found });
578
604
  }
579
605
  if (body.action === 'new') {
606
+ blank = null;
580
607
  session = store.create(body.title?.trim() || '新对话');
581
608
  // 用户明确指定了标题,后续自动标题不要覆盖它。
582
609
  if (body.title?.trim())
583
610
  session.titleSource = 'user';
584
611
  await store.save(session);
612
+ activeId = session.id;
585
613
  }
586
614
  else if (body.action === 'rename') {
587
615
  // 支持直接重命名侧栏里的某个会话,不必先把用户切过去。
@@ -591,12 +619,18 @@ export async function startUiServer(options) {
591
619
  target.title = body.title?.trim() || target.title;
592
620
  target.titleSource = 'user';
593
621
  await store.save(target);
622
+ if (blank === target) {
623
+ blank = null;
624
+ activeId = target.id;
625
+ }
594
626
  }
595
627
  else if (body.action === 'switch') {
596
628
  const found = body.ref ? await store.find(body.ref) : null;
597
629
  if (!found)
598
630
  return json(res, 404, { error: '没找到这个对话' });
631
+ blank = null;
599
632
  session = found;
633
+ activeId = found.id;
600
634
  }
601
635
  else if (body.action === 'delete') {
602
636
  const found = body.ref ? await store.find(body.ref) : null;
@@ -604,8 +638,19 @@ export async function startUiServer(options) {
604
638
  await store.remove(found.id);
605
639
  await backups(found.id).clear();
606
640
  if (found.id === session.id) {
607
- session = store.create();
608
- await store.save(session);
641
+ // 优先切到剩下的最近会话;一个都不剩时进入空白草稿,不强行新建对话。
642
+ const remaining = await store.lastActive();
643
+ const next = remaining ? await store.load(remaining) : null;
644
+ if (next) {
645
+ session = next;
646
+ activeId = next.id;
647
+ blank = null;
648
+ }
649
+ else {
650
+ session = store.create();
651
+ blank = session;
652
+ activeId = null;
653
+ }
609
654
  }
610
655
  }
611
656
  }
@@ -614,23 +659,26 @@ export async function startUiServer(options) {
614
659
  session.todos = [];
615
660
  session.plan = undefined;
616
661
  session.usage = { inputTokens: 0, outputTokens: 0 };
617
- await store.save(session);
662
+ if (blank !== session)
663
+ await store.save(session);
618
664
  }
619
665
  else if (body.action === 'mode') {
620
666
  const mode = body.value === 'plan' ? 'plan' : 'build';
621
667
  session.mode = mode;
622
668
  if (mode === 'build' && session.plan?.status === 'cancelled')
623
669
  session.plan = undefined;
624
- await store.save(session);
670
+ if (blank !== session)
671
+ await store.save(session);
625
672
  }
626
673
  else if (body.action === 'reasoning') {
627
674
  const level = body.value;
628
675
  if (REASONING_LEVELS.includes(level)) {
629
676
  session.reasoning = level;
630
- await store.save(session);
677
+ if (blank !== session)
678
+ await store.save(session);
631
679
  }
632
680
  }
633
- activeId = session.id;
681
+ activeId = blank === session ? null : session.id;
634
682
  return json(res, 200, { session: session.id, sessions: await listSessions(), info: await info(session) });
635
683
  }
636
684
  if (path === '/api/complete' && req.method === 'GET') {
@@ -794,6 +842,36 @@ export async function startUiServer(options) {
794
842
  else if (body.action === 'showReasoning') {
795
843
  config.showReasoning = body.value === 'true' || body.value === '1';
796
844
  }
845
+ else if (body.action === 'searchProvider') {
846
+ const value = String(body.value ?? '');
847
+ if (value === 'auto' || value === 'tavily' || value === 'brave' || value === 'free') {
848
+ config.search.provider = value;
849
+ }
850
+ }
851
+ else if (body.action === 'searchKey') {
852
+ const name = String(body.name ?? '');
853
+ const value = String(body.value ?? '').trim();
854
+ if (name === 'tavily') {
855
+ if (value)
856
+ config.search.tavilyKey = value;
857
+ else
858
+ delete config.search.tavilyKey;
859
+ }
860
+ else if (name === 'brave') {
861
+ if (value)
862
+ config.search.braveKey = value;
863
+ else
864
+ delete config.search.braveKey;
865
+ }
866
+ }
867
+ else if (body.action === 'searchDeep') {
868
+ config.search.deep = body.value === 'true' || body.value === '1';
869
+ }
870
+ else if (body.action === 'searchLanguage') {
871
+ const value = String(body.value ?? '');
872
+ if (value === 'en' || value === 'auto' || value === 'zh')
873
+ config.search.language = value;
874
+ }
797
875
  else if (body.action === 'workspace' && body.value) {
798
876
  const next = resolve(String(body.value).trim());
799
877
  if (!existsSync(next)) {
@@ -816,7 +894,8 @@ export async function startUiServer(options) {
816
894
  try {
817
895
  session.model = provider().model;
818
896
  session.provider = config.current;
819
- await store.save(session);
897
+ if (blank !== session)
898
+ await store.save(session);
820
899
  }
821
900
  catch {
822
901
  /* provider 暂时不可用,不影响设置已保存 */
@@ -941,6 +1020,12 @@ export async function startUiServer(options) {
941
1020
  if (found)
942
1021
  target = found;
943
1022
  }
1023
+ // 空白草稿在第一次真正对话时才落盘。
1024
+ if (target === blank) {
1025
+ await store.save(target);
1026
+ blank = null;
1027
+ }
1028
+ session = target;
944
1029
  activeId = target.id;
945
1030
  return chat(body, res, target);
946
1031
  }
@@ -1093,11 +1178,18 @@ export async function startUiServer(options) {
1093
1178
  setSessionAndSave: async (value) => {
1094
1179
  next = value;
1095
1180
  await store.save(value);
1181
+ if (blank === value) {
1182
+ blank = null;
1183
+ activeId = value.id;
1184
+ }
1096
1185
  },
1097
1186
  setProvider: () => { },
1098
1187
  setConfig: (value) => Object.assign(config, value),
1099
1188
  setTools: () => { },
1100
1189
  saveSession: async () => {
1190
+ // 空白草稿不因为 /provider、/system 之类的命令偷偷落盘。
1191
+ if (blank === next)
1192
+ return;
1101
1193
  await store.save(next);
1102
1194
  },
1103
1195
  reloadProvider: () => { },
@@ -1233,6 +1325,7 @@ export async function startUiServer(options) {
1233
1325
  allowOutsideWorkspace: config.allowOutsideWorkspace,
1234
1326
  permissions: config.permissions,
1235
1327
  todos: session.todos,
1328
+ search: config.search,
1236
1329
  };
1237
1330
  const started = Date.now();
1238
1331
  const toolStartedAt = new Map();
@@ -1250,6 +1343,7 @@ export async function startUiServer(options) {
1250
1343
  signal: controller.signal,
1251
1344
  todos: session.todos,
1252
1345
  reasoning: session.reasoning ?? 'standard',
1346
+ search: config.search,
1253
1347
  recordChange: (path, beforeContent) => recorder.record(path, beforeContent),
1254
1348
  onText: (chunk) => send('text', { chunk }),
1255
1349
  onReasoning: (chunk) => send('reasoning', { chunk }),