@vincentbanana/bananacli 0.7.1 → 0.8.1

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.
@@ -30,7 +30,7 @@ export function truncateToolOutputs(messages, maxChars = MAX_TOOL_MESSAGE_CHARS)
30
30
  * 跑完一整轮:请求 -> 工具调用 -> 回灌结果 -> 再请求,直到模型不再要工具。
31
31
  * messages 不会被原地修改,返回的是新数组,方便会话持久化。
32
32
  */
33
- export async function runTurn(deps, messages, input, images) {
33
+ export async function runTurn(deps, messages, input, images, attachments, attachmentContext) {
34
34
  const tools = toolMap(deps.tools);
35
35
  const schemas = toolSchemas(deps.tools);
36
36
  const convo = [...messages];
@@ -39,6 +39,8 @@ export async function runTurn(deps, messages, input, images) {
39
39
  role: 'user',
40
40
  content: input,
41
41
  ...(images?.length ? { images } : {}),
42
+ ...(attachments?.length ? { attachments } : {}),
43
+ ...(attachmentContext ? { attachmentContext } : {}),
42
44
  });
43
45
  }
44
46
  const usage = {};
@@ -97,6 +99,7 @@ export async function runTurn(deps, messages, input, images) {
97
99
  onText: deps.onText,
98
100
  onReasoning: deps.onReasoning,
99
101
  onRetry: deps.onRetry,
102
+ reasoning: deps.reasoning,
100
103
  });
101
104
  }
102
105
  catch (error) {
@@ -1,4 +1,5 @@
1
1
  import { fetchWithRetry } from "./http.js";
2
+ import { REASONING_BUDGET, supportsReasoning } from "./reasoning.js";
2
3
  import { newMessageId } from "./types.js";
3
4
  const ANTHROPIC_VERSION = '2023-06-01';
4
5
  function toAnthropicTools(tools, promptCaching) {
@@ -44,6 +45,13 @@ export function toAnthropicMessages(messages) {
44
45
  continue;
45
46
  }
46
47
  const content = [];
48
+ if (message.role === 'assistant' && message.reasoning && message.reasoningSignature) {
49
+ content.push({
50
+ type: 'thinking',
51
+ thinking: message.reasoning,
52
+ signature: message.reasoningSignature,
53
+ });
54
+ }
47
55
  if (message.role === 'user') {
48
56
  for (const image of message.images ?? []) {
49
57
  const parsed = parseDataUrl(image);
@@ -55,8 +63,9 @@ export function toAnthropicMessages(messages) {
55
63
  }
56
64
  }
57
65
  }
58
- if (message.content)
59
- content.push({ type: 'text', text: message.content });
66
+ const text = [message.content, message.attachmentContext].filter(Boolean).join('\n\n');
67
+ if (text)
68
+ content.push({ type: 'text', text });
60
69
  for (const call of message.toolCalls ?? []) {
61
70
  content.push({ type: 'tool_use', id: call.id, name: call.name, input: call.input ?? {} });
62
71
  }
@@ -128,6 +137,7 @@ async function streamMessages(url, headers, body, generate) {
128
137
  }
129
138
  let text = '';
130
139
  let reasoning = '';
140
+ let reasoningSignature = '';
131
141
  let stopReason = '';
132
142
  const usage = {};
133
143
  const blocks = new Map();
@@ -163,6 +173,9 @@ async function streamMessages(url, headers, body, generate) {
163
173
  reasoning += delta.thinking;
164
174
  generate.onReasoning?.(delta.thinking);
165
175
  }
176
+ else if (delta?.type === 'signature_delta' && typeof delta.signature === 'string') {
177
+ reasoningSignature += delta.signature;
178
+ }
166
179
  else if (delta?.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
167
180
  const slot = blocks.get(event.index);
168
181
  if (slot)
@@ -189,6 +202,8 @@ async function streamMessages(url, headers, body, generate) {
189
202
  message.toolCalls = toolCalls;
190
203
  if (reasoning)
191
204
  message.reasoning = reasoning;
205
+ if (reasoningSignature)
206
+ message.reasoningSignature = reasoningSignature;
192
207
  if (stopReason === 'max_tokens' && text)
193
208
  message.content += '\n[输出达到长度上限,未完成]';
194
209
  return { message, usage };
@@ -207,12 +222,16 @@ function fromPayload(payload, generate) {
207
222
  const content = (payload?.content ?? []);
208
223
  let text = '';
209
224
  let reasoning = '';
225
+ let reasoningSignature = '';
210
226
  const toolCalls = [];
211
227
  for (const block of content) {
212
228
  if (block?.type === 'text')
213
229
  text += block.text ?? '';
214
- else if (block?.type === 'thinking')
230
+ else if (block?.type === 'thinking') {
215
231
  reasoning += block.thinking ?? '';
232
+ if (typeof block.signature === 'string')
233
+ reasoningSignature += block.signature;
234
+ }
216
235
  else if (block?.type === 'tool_use') {
217
236
  toolCalls.push({ id: block.id ?? newMessageId(), name: block.name, input: block.input ?? {} });
218
237
  }
@@ -226,6 +245,8 @@ function fromPayload(payload, generate) {
226
245
  message.toolCalls = toolCalls;
227
246
  if (reasoning)
228
247
  message.reasoning = reasoning;
248
+ if (reasoningSignature)
249
+ message.reasoningSignature = reasoningSignature;
229
250
  return {
230
251
  message,
231
252
  usage: {
@@ -251,7 +272,7 @@ export function createAnthropicProvider(options) {
251
272
  const promptCaching = config.promptCaching !== false;
252
273
  const body = {
253
274
  model: config.model,
254
- max_tokens: config.maxTokens ?? 8192,
275
+ max_tokens: generateOptions.maxTokens ?? config.maxTokens ?? 8192,
255
276
  messages: toAnthropicMessages(generateOptions.messages),
256
277
  stream: true,
257
278
  };
@@ -263,8 +284,19 @@ export function createAnthropicProvider(options) {
263
284
  if (generateOptions.tools.length) {
264
285
  body['tools'] = toAnthropicTools(generateOptions.tools, promptCaching);
265
286
  }
266
- if (typeof config.temperature === 'number')
267
- body['temperature'] = config.temperature;
287
+ const thinking = generateOptions.reasoning &&
288
+ supportsReasoning(name, 'anthropic', config.model)
289
+ ? REASONING_BUDGET[generateOptions.reasoning]
290
+ : 0;
291
+ if (thinking > 0) {
292
+ body['thinking'] = { type: 'enabled', budget_tokens: thinking };
293
+ body['max_tokens'] = Math.max(Number(config.maxTokens ?? 8192), thinking + 1024);
294
+ }
295
+ else {
296
+ const temperature = generateOptions.temperature ?? config.temperature;
297
+ if (typeof temperature === 'number')
298
+ body['temperature'] = temperature;
299
+ }
268
300
  return streamMessages(messagesUrl(config.baseUrl), headers, body, generateOptions);
269
301
  },
270
302
  };
@@ -1,4 +1,5 @@
1
1
  import { fetchWithRetry, isStreamOptionsUnsupported } from "./http.js";
2
+ import { openAIReasoningBody } from "./reasoning.js";
2
3
  import { newMessageId } from "./types.js";
3
4
  function toFunctionTools(tools) {
4
5
  return tools.map((tool) => ({
@@ -14,22 +15,26 @@ function toChatMessages(messages) {
14
15
  const out = [];
15
16
  for (const message of messages) {
16
17
  if (message.role === 'user') {
18
+ const text = [message.content, message.attachmentContext].filter(Boolean).join('\n\n');
17
19
  if (message.images?.length) {
18
20
  const parts = [];
19
- if (message.content)
20
- parts.push({ type: 'text', text: message.content });
21
+ if (text)
22
+ parts.push({ type: 'text', text });
21
23
  for (const image of message.images) {
22
24
  parts.push({ type: 'image_url', image_url: { url: image } });
23
25
  }
24
26
  out.push({ role: 'user', content: parts });
25
27
  }
26
28
  else {
27
- out.push({ role: 'user', content: message.content });
29
+ out.push({ role: 'user', content: text });
28
30
  }
29
31
  continue;
30
32
  }
31
33
  if (message.role === 'assistant') {
32
34
  const entry = { role: 'assistant', content: message.content || null };
35
+ // DeepSeek / 部分推理模型要求把 reasoning_content 回传,否则带 tools 的续轮会 400。
36
+ if (message.reasoning)
37
+ entry['reasoning_content'] = message.reasoning;
33
38
  if (message.toolCalls?.length) {
34
39
  entry['tool_calls'] = message.toolCalls.map((call) => ({
35
40
  id: call.id,
@@ -220,10 +225,15 @@ export function createOpenAIProvider(options) {
220
225
  body['tools'] = toFunctionTools(generateOptions.tools);
221
226
  body['tool_choice'] = 'auto';
222
227
  }
223
- if (typeof config.temperature === 'number')
224
- body['temperature'] = config.temperature;
225
- if (typeof config.maxTokens === 'number')
226
- body['max_tokens'] = config.maxTokens;
228
+ const temperature = generateOptions.temperature ?? config.temperature;
229
+ const maxTokens = generateOptions.maxTokens ?? config.maxTokens;
230
+ if (typeof temperature === 'number')
231
+ body['temperature'] = temperature;
232
+ if (typeof maxTokens === 'number')
233
+ body['max_tokens'] = maxTokens;
234
+ if (generateOptions.reasoning) {
235
+ Object.assign(body, openAIReasoningBody(name, 'openai', config.model, generateOptions.reasoning));
236
+ }
227
237
  const url = `${config.baseUrl.replace(/\/+$/, '')}/chat/completions`;
228
238
  const runtime = { generate: generateOptions };
229
239
  try {
@@ -0,0 +1,64 @@
1
+ export const REASONING_LEVELS = ['fast', 'standard', 'deep'];
2
+ export const REASONING_LABEL = {
3
+ fast: '快',
4
+ standard: '标准',
5
+ deep: '深入',
6
+ };
7
+ export const REASONING_HINT = {
8
+ fast: '低推理,响应快、消耗少',
9
+ standard: '日常默认,速度和准确率平衡',
10
+ deep: '高推理,更慢但更适合复杂任务',
11
+ };
12
+ /** Anthropic extended thinking 的预算(token)。 */
13
+ export const REASONING_BUDGET = {
14
+ fast: 2048,
15
+ standard: 8192,
16
+ deep: 24576,
17
+ };
18
+ const EFFORT = {
19
+ fast: 'low',
20
+ standard: 'medium',
21
+ deep: 'high',
22
+ };
23
+ /**
24
+ * 哪些模型支持显式思考强度。宁可保守:不支持的模型不传未知字段,
25
+ * 避免部分 OpenAI 兼容网关直接 400。
26
+ */
27
+ export function supportsReasoning(name, protocol, model) {
28
+ const id = model.toLowerCase();
29
+ if (protocol === 'anthropic') {
30
+ return /claude-(3[.-]7|sonnet-4|opus-4|haiku-4|4)/.test(id);
31
+ }
32
+ if (/^(o[1-9]|gpt-5)/.test(id))
33
+ return true;
34
+ if (name === 'deepseek' || id.includes('deepseek'))
35
+ return true;
36
+ if (name === 'qwen' || /qwen3|qwq|thinking/.test(id))
37
+ return true;
38
+ if (id.includes('reasoner'))
39
+ return true;
40
+ return false;
41
+ }
42
+ export function effortFor(level) {
43
+ return EFFORT[level];
44
+ }
45
+ /** 给 OpenAI 兼容协议挑字段;不支持时返回空对象。 */
46
+ export function openAIReasoningBody(name, protocol, model, level) {
47
+ if (!supportsReasoning(name, protocol, model))
48
+ return {};
49
+ const id = model.toLowerCase();
50
+ if (/^(o[1-9]|gpt-5)/.test(id))
51
+ return { reasoning_effort: effortFor(level) };
52
+ if (name === 'deepseek' || id.includes('deepseek')) {
53
+ return {
54
+ thinking: { type: level === 'fast' ? 'disabled' : 'enabled' },
55
+ ...(level === 'fast' ? {} : { reasoning_effort: effortFor(level) }),
56
+ };
57
+ }
58
+ if (name === 'qwen' || /qwen3|qwq|thinking/.test(id)) {
59
+ return level === 'fast'
60
+ ? { enable_thinking: false }
61
+ : { enable_thinking: true, thinking_budget: REASONING_BUDGET[level] };
62
+ }
63
+ return { reasoning_effort: effortFor(level) };
64
+ }