codebee 0.1.49 → 0.1.51

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.
@@ -5,7 +5,8 @@
5
5
  进程与框架开销,且 CLI 的事件流日志(启动命令、提示词回显、重连报错)会污染
6
6
  对话视图。内置智能体直接打 chat API + 工具循环:
7
7
  - 模型选择:编排者配置(resolve_orchestrator)优先;未启用时扫首个可用供应商;
8
- - 工具:list_files / read_file / write_file,全部锁死在工作目录内;
8
+ - 工具:list_files / read_file / write_file(锁死工作目录内)+ run_command
9
+ (本机全权执行命令,产品定位全信任,与 codex/claude 全权沙箱同档);
9
10
  - 协议:anthropic / openai 走原生工具循环;google 无工具协议(纯文本直答)。
10
11
  密钥冷却/多 KEY 展开复用 modelhub 既有记账(note_key_ok / note_key_error)。
11
12
  """
@@ -17,9 +18,12 @@ import json
17
18
  import mimetypes
18
19
  import os
19
20
  import threading
21
+ import time
22
+ import urllib.parse
23
+ import urllib.request
20
24
  from pathlib import Path
21
25
 
22
- from . import modelhub, runner
26
+ from . import modelhub, runner, tlsctx
23
27
 
24
28
  MAX_TOOL_ITERS = 16 # 单步工具循环上限(防模型打转)
25
29
  READ_MAX_BYTES = 64 * 1024 # read_file 单次读取上限
@@ -30,6 +34,17 @@ MAX_IMAGES = 8 # 单次最多随消息传几张图(请求体
30
34
  IMAGE_MAX_EDGE = 1568 # 长边上限(视觉模型通行建议值,超出等比缩)
31
35
  IMAGE_JPEG_BYTES = 3500 * 1024 # 缩放后仍超此大小 → 转 JPEG q85
32
36
  IMAGE_MAX_BYTES = 5 * 1024 * 1024 # 单张最终字节硬上限(超出剔除并日志)
37
+ THINK_MAX_CHARS = 20000 # 单次生成保留的思考正文上限(防超长思维链撑爆 run.json)
38
+ STREAM_MAX_CHARS = 20000 # 运行中实时回答的保留上限(与 THINK_MAX_CHARS 同口径)
39
+ BASE_MAX_TOKENS = 8000 # 单次生成输出预算(推理模型的思考 token 也计入此额度)
40
+ MAX_TOKENS_CAP = 16000 # 思考撑爆预算后的提额上限(每轮 run 只提一次)
41
+ THINK_EXHAUST_MIN_CHARS = 1500 # 零正文时思考达到此长度 ≈ 思考占满输出预算
42
+ EMPTY_TEXT_MAX_STREAK = 3 # 连续零正文轮数上限(防同参数盲重试烧穿预算)
43
+
44
+ CMD_DEFAULT_TIMEOUT = 600 # run_command 默认超时(与 CLI 停滞看门狗同口径)
45
+ CMD_MAX_TIMEOUT = 1800 # 上限:模型传 timeout_sec 超过即钳到这
46
+ CMD_OUT_HEAD = 24 * 1024 # 回灌给模型的输出:头 24K + 尾 8K(报错常在尾部)
47
+ CMD_OUT_TAIL = 8 * 1024
33
48
 
34
49
  _SYSTEM_PROMPT = """你是 CodeBee 的内置执行智能体,直接完成用户交代的任务。用户的目标、背景与工作目录内的附件就是全部输入。
35
50
 
@@ -37,6 +52,9 @@ _SYSTEM_PROMPT = """你是 CodeBee 的内置执行智能体,直接完成用户
37
52
  - 需要读文件、看目录、写文件时调用工具;所有路径都是工作目录内的相对路径。
38
53
  - read_file 只能读文本文件;图片、压缩包等二进制文件读不了,如实告知用户即可,不要反复尝试。
39
54
  - 用户消息中的图片附件会直接出现在对话里,可直接看图作答,无需用工具读取。
55
+ - run_command 直接在用户的电脑上执行命令并回传退出码与输出:诊断、修复、改配置、重启服务等操作会真实生效。命令跑完看输出再决定下一步,不要一次性罗列步骤让用户自己敲。
56
+ - Windows 上需要管理员权限的命令(flushdns、winsock reset、防火墙、系统服务等),用 powershell -Command "Start-Process <程序> -ArgumentList '<参数>' -Verb RunAs -Wait" 触发 UAC——用户屏幕会弹窗,点允许即提权执行;提权进程的输出拿不到,之后要用普通命令复核效果。macOS/Linux 用 sudo 并在输出里提示用户输密码不可行时改写临时脚本让用户跑。
57
+ - 避免跑长驻/交互式命令(ping -t、top、要按键应答的安装器),它们会拖满超时被强杀。
40
58
  - 产出文件一律 UTF-8 编码。
41
59
  - 回答用户的语言与用户一致(默认中文)。直接给结论和内容,不要输出任何机器标记或协议行。"""
42
60
 
@@ -329,6 +347,47 @@ def _tool_write_file(workdir, args):
329
347
  return "已写入 %s(%d 字符,UTF-8)" % (rel, len(content))
330
348
 
331
349
 
350
+ def _tool_run_command(workdir, args, cancel_event=None):
351
+ """本机执行一条 shell 命令,返回 (退出码, 合并输出)。
352
+
353
+ 薄适配层:执行/杀树/取消/解码全部复用 runner.run_process(shell_cmd 分支
354
+ → cmd /c 或 /bin/sh -c),仓库唯一的 shell 落点,不另起炉灶。全信任档
355
+ (用户拍板 2026-09-22):无白名单无确认闸,与 codex/claude 全权沙箱同档。
356
+ 提权靠模型自己包 Start-Process -Verb RunAs——UAC 必须人点,绕不过也不该绕。
357
+ 输出按字符头尾截断(解码已在 run_process 完成,无残缺多字节问题)。"""
358
+ cmdline = str(args.get("command") or "").strip()
359
+ if not cmdline:
360
+ return "(命令为空,未执行)"
361
+ try:
362
+ timeout = int(float(args.get("timeout_sec") or CMD_DEFAULT_TIMEOUT))
363
+ except (TypeError, ValueError):
364
+ timeout = CMD_DEFAULT_TIMEOUT
365
+ r = runner.run_process(shell_cmd=cmdline, cwd=os.path.abspath(workdir or "."),
366
+ timeout=max(5, min(timeout, CMD_MAX_TIMEOUT)),
367
+ cancel_event=cancel_event)
368
+ out = runner.clean_cli_text(
369
+ (r.get("stdout") or "") + (("\n" + r["stderr"]) if r.get("stderr") else ""))
370
+ limit = CMD_OUT_HEAD + CMD_OUT_TAIL
371
+ if not out.strip():
372
+ body = "(无输出)"
373
+ elif len(out) <= limit:
374
+ body = out
375
+ else:
376
+ body = (out[:CMD_OUT_HEAD]
377
+ + "\n…(中段省略 %d 字符;头 %dK + 尾 %dK 保留)\n" % (
378
+ len(out) - limit, CMD_OUT_HEAD // 1024, CMD_OUT_TAIL // 1024)
379
+ + out[-CMD_OUT_TAIL:])
380
+ if r.get("cancelled"):
381
+ note = "已取消,进程树已终止"
382
+ elif r.get("timed_out"):
383
+ note = "超时 %d 秒,进程树已强制终止" % timeout
384
+ else:
385
+ note = ""
386
+ prefix = ("(%s)\n" % note) if note else ""
387
+ code = r.get("exit_code")
388
+ return "%s退出码: %s\n%s" % (prefix, "未知" if code is None else code, body)
389
+
390
+
332
391
  TOOLS_SPEC = [
333
392
  {"name": "list_files", "description": "列出工作目录(或其子目录)下的文件",
334
393
  "args": {"path": "子目录相对路径,留空=根目录"}},
@@ -336,17 +395,23 @@ TOOLS_SPEC = [
336
395
  "args": {"path": "文件相对路径"}},
337
396
  {"name": "write_file", "description": "把文本内容写入工作目录内一个文件(UTF-8,父目录自动创建)",
338
397
  "args": {"path": "文件相对路径", "content": "完整文本内容"}},
398
+ {"name": "run_command",
399
+ "description": "在本机执行一条 shell 命令,返回退出码与合并输出。诊断、修复、改配置、重启服务等操作真实生效;先跑命令看结果再定下一步。默认超时 600 秒,可用 timeout_sec 调整(5~1800)。Windows 需要管理员权限的命令(flushdns/防火墙/系统服务等)用 powershell -Command \"Start-Process <程序> -ArgumentList '<参数>' -Verb RunAs -Wait\" 触发 UAC(用户点允许后提权执行;提权进程输出拿不到,事后用普通命令复核)。避免长驻/交互式命令(ping -t、top、按键应答的安装器)。",
400
+ "args": {"command": "完整命令行(shell 语法,本机直接执行)",
401
+ "timeout_sec": "可选,超时秒数"}},
339
402
  ]
340
403
 
341
404
  _TOOL_IMPL = {"list_files": _tool_list_files, "read_file": _tool_read_file,
342
- "write_file": _tool_write_file}
405
+ "write_file": _tool_write_file, "run_command": _tool_run_command}
343
406
 
344
407
 
345
- def _exec_tool(workdir, name, args):
408
+ def _exec_tool(workdir, name, args, cancel_event=None):
346
409
  fn = _TOOL_IMPL.get(name or "")
347
410
  if fn is None:
348
411
  return "(未知工具: %s)" % name
349
412
  try:
413
+ if name == "run_command":
414
+ return fn(workdir, args or {}, cancel_event=cancel_event)
350
415
  return fn(workdir, args or {})
351
416
  except Exception as e:
352
417
  return "工具执行失败: %s" % (e)
@@ -404,6 +469,272 @@ def _post_interruptible(url, headers, body, allow_private, timeout, cancel_event
404
469
  return box.get("r") or (0, None, "无响应")
405
470
 
406
471
 
472
+ # ---------------------------------------------------------------- 思考过程(流式)
473
+ # 用户诉求(2026-09-22):「把思考过程打印出来」——直连对话此前整轮只有三点
474
+ # 打字动画,模型的思维链(DeepSeek/vLLM 系 reasoning_content、Anthropic
475
+ # thinking 块)被 _sse_parse 明确丢弃。这里自带一份「认思考」的增量解析:
476
+ # 边收边把思考与正文分别攒起来,交给调用方实时落盘 + 结束后存进步骤记录。
477
+
478
+ def _reason_from_delta(proto, obj):
479
+ """从一条流式事件里取「思考增量」。三协议字段各异,取不到返回空串。
480
+
481
+ openai 兼容面最杂:reasoning_content(DeepSeek/vLLM/云知声实测)、
482
+ reasoning(部分网关)、reasoning_details[].text(OpenRouter 系)。
483
+ anthropic 是 thinking_delta(另有 redacted_thinking 不文本化,跳过)。"""
484
+ if proto == "openai":
485
+ total = ""
486
+ for ch in obj.get("choices") or []:
487
+ d = ch.get("delta") or {}
488
+ for k in ("reasoning_content", "reasoning"):
489
+ v = d.get(k)
490
+ if isinstance(v, str):
491
+ total += v
492
+ for det in (d.get("reasoning_details") or []):
493
+ if isinstance(det, dict) and isinstance(det.get("text"), str):
494
+ total += det["text"]
495
+ return total
496
+ if proto == "anthropic" and obj.get("type") == "content_block_delta":
497
+ d = obj.get("delta") or {}
498
+ if d.get("type") == "thinking_delta":
499
+ return d.get("thinking") or ""
500
+ return ""
501
+ if proto == "google":
502
+ total = ""
503
+ for cand in obj.get("candidates") or []:
504
+ for p in ((cand.get("content") or {}).get("parts") or []):
505
+ if isinstance(p, dict) and p.get("thought"):
506
+ total += p.get("text") or ""
507
+ return total
508
+ return ""
509
+
510
+
511
+ def _reason_from_message(proto, data):
512
+ """非流式响应里的思考字段(网关不支持流式时的兜底)。"""
513
+ if not isinstance(data, dict):
514
+ return ""
515
+ if proto == "anthropic":
516
+ return "\n".join(b.get("thinking", "") for b in (data.get("content") or [])
517
+ if isinstance(b, dict) and b.get("type") == "thinking")
518
+ if proto == "google":
519
+ total = ""
520
+ for cand in data.get("candidates") or []:
521
+ for p in ((cand.get("content") or {}).get("parts") or []):
522
+ if isinstance(p, dict) and p.get("thought"):
523
+ total += p.get("text") or ""
524
+ return total
525
+ msg = ((data.get("choices") or [{}])[0].get("message") or {})
526
+ total = ""
527
+ for k in ("reasoning_content", "reasoning"):
528
+ v = msg.get(k)
529
+ if isinstance(v, str):
530
+ total += v
531
+ for det in (msg.get("reasoning_details") or []):
532
+ if isinstance(det, dict) and isinstance(det.get("text"), str):
533
+ total += det["text"]
534
+ return total
535
+
536
+
537
+ def _stream_accumulate(proto, obj, acc):
538
+ """把一条 SSE 事件并入累加器(就地改写 acc)。返回是否有「有意义的进展」。
539
+
540
+ acc = {text, reasoning, tools, usage};工具参数按 index 归并——openai 的
541
+ function.arguments 与 anthropic 的 input_json_delta 都是分片到达的。"""
542
+ progress = False
543
+ if proto == "anthropic":
544
+ t = obj.get("type")
545
+ if t == "content_block_start":
546
+ blk = obj.get("content_block") or {}
547
+ if blk.get("type") == "tool_use":
548
+ idx = int(obj.get("index") or 0)
549
+ acc["tools"][idx] = {"id": blk.get("id") or "",
550
+ "name": blk.get("name") or "", "raw": ""}
551
+ progress = True
552
+ elif t == "content_block_delta":
553
+ d = obj.get("delta") or {}
554
+ if d.get("type") == "text_delta" and d.get("text"):
555
+ acc["text"] += d["text"]
556
+ progress = True
557
+ elif d.get("type") == "input_json_delta":
558
+ idx = int(obj.get("index") or 0)
559
+ slot = acc["tools"].setdefault(idx, {"id": "", "name": "", "raw": ""})
560
+ slot["raw"] += d.get("partial_json") or ""
561
+ progress = True
562
+ elif t == "message_start":
563
+ u = (obj.get("message") or {}).get("usage") or obj.get("usage") or {}
564
+ acc["usage"].update({"input": int(u.get("input_tokens") or 0),
565
+ "output": int(u.get("output_tokens") or 0),
566
+ "cached": (int(u.get("cache_read_input_tokens") or 0)
567
+ + int(u.get("cache_creation_input_tokens") or 0))})
568
+ elif t == "message_delta":
569
+ u = obj.get("usage") or {}
570
+ if u.get("output_tokens"):
571
+ acc["usage"]["output"] = int(u["output_tokens"])
572
+ elif proto == "google":
573
+ for cand in obj.get("candidates") or []:
574
+ for p in ((cand.get("content") or {}).get("parts") or []):
575
+ if not isinstance(p, dict):
576
+ continue
577
+ if p.get("thought"):
578
+ acc["reasoning"] += p.get("text") or ""
579
+ progress = True
580
+ elif p.get("functionCall"):
581
+ fc = p["functionCall"]
582
+ acc["tools"][len(acc["tools"])] = {
583
+ "id": "call_%d" % (len(acc["tools"]) + 1),
584
+ "name": fc.get("name") or "",
585
+ "raw": json.dumps(fc.get("args") or {}, ensure_ascii=False)}
586
+ progress = True
587
+ elif p.get("text"):
588
+ acc["text"] += p["text"]
589
+ progress = True
590
+ u = obj.get("usageMetadata")
591
+ if isinstance(u, dict):
592
+ acc["usage"].update({"input": int(u.get("promptTokenCount") or 0),
593
+ "output": int(u.get("candidatesTokenCount") or 0),
594
+ "total": int(u.get("totalTokenCount") or 0)})
595
+ else:
596
+ for ch in obj.get("choices") or []:
597
+ d = ch.get("delta") or {}
598
+ if isinstance(d.get("content"), str) and d["content"]:
599
+ acc["text"] += d["content"]
600
+ progress = True
601
+ for i, tc in enumerate(d.get("tool_calls") or []):
602
+ if not isinstance(tc, dict):
603
+ continue
604
+ idx = int(tc.get("index") if tc.get("index") is not None else i)
605
+ slot = acc["tools"].setdefault(idx, {"id": "", "name": "", "raw": ""})
606
+ if tc.get("id"):
607
+ slot["id"] = tc["id"]
608
+ fn = tc.get("function") or {}
609
+ if fn.get("name"):
610
+ slot["name"] = fn["name"]
611
+ if fn.get("arguments"):
612
+ slot["raw"] += fn["arguments"]
613
+ progress = True
614
+ u = obj.get("usage")
615
+ if isinstance(u, dict):
616
+ acc["usage"].update({"input": int(u.get("prompt_tokens") or 0),
617
+ "output": int(u.get("completion_tokens") or 0),
618
+ "total": int(u.get("total_tokens") or 0),
619
+ "cached": int(((u.get("prompt_tokens_details") or {})
620
+ .get("cached_tokens")) or 0)})
621
+ return progress
622
+
623
+
624
+ def _calls_from_acc(acc):
625
+ """累加器里的工具分片 → [{id, name, args}](参数 JSON 解析失败给空对象)。"""
626
+ out = []
627
+ for idx in sorted(acc["tools"].keys()):
628
+ slot = acc["tools"][idx]
629
+ name = slot.get("name") or ""
630
+ if not name:
631
+ continue
632
+ try:
633
+ args = json.loads(slot.get("raw") or "{}")
634
+ except Exception:
635
+ args = {}
636
+ if not isinstance(args, dict):
637
+ args = {}
638
+ out.append({"id": slot.get("id") or ("call_%d" % (idx + 1)),
639
+ "name": name, "args": args})
640
+ return out
641
+
642
+
643
+ def _post_sse_stream(url, headers, body, allow_private, timeout, proto,
644
+ on_reason=None, on_text=None, on_tick=None, cancel_event=None):
645
+ """流式(SSE)模型调用 → dict(status/text/reasoning/calls/usage/error/events)。
646
+
647
+ 与 _post_interruptible 同款的可打断语义:读取放守护线程,cancel_event 置位
648
+ 即刻放弃等待(socket 随线程结束释放)。三个回调:on_reason 每收到一段思考
649
+ 增量(调用方据此实时打印「思考过程」),on_text 收到**累计**正文(只在真的
650
+ 变长时触发,运行中直接当正文预览),on_tick 是无文本进展时的心跳。
651
+ events=0 表示网关根本没按流回(多半忽略了 stream 字段)——调用方据此回落
652
+ 非流式;events>0 而正文为空则是模型真没说话,不该重发(白烧一次生成)。"""
653
+ acc = {"text": "", "reasoning": "", "tools": {}, "usage": {}}
654
+ box = {"status": 0, "err": "", "events": 0, "sent_text": None}
655
+ lock = threading.Lock()
656
+
657
+ def _emit(cb, payload):
658
+ if cb is None:
659
+ return
660
+ try:
661
+ cb(payload)
662
+ except Exception:
663
+ pass
664
+
665
+ def _go():
666
+ try:
667
+ parsed = urllib.parse.urlsplit(url)
668
+ if parsed.scheme not in ("http", "https"):
669
+ box["err"] = "协议必须是 http/https"
670
+ return
671
+ host, herr = modelhub._validate_host(url, allow_private)
672
+ if host is None:
673
+ box["err"] = herr
674
+ return
675
+ req = urllib.request.Request(
676
+ url, method="POST",
677
+ headers=dict(headers, **{"Content-Type": "application/json",
678
+ "Accept": "text/event-stream"}),
679
+ data=json.dumps(body).encode("utf-8"))
680
+ with modelhub._opener().open(req, timeout=timeout) as resp:
681
+ box["status"] = resp.status
682
+ if not 200 <= resp.status < 300:
683
+ raw = resp.read(65536).decode("utf-8", "replace")
684
+ box["err"] = "HTTP %s %s" % (resp.status, raw[:200])
685
+ return
686
+ for raw in resp:
687
+ line = raw.decode("utf-8", "replace").strip()
688
+ if not line.startswith("data:"):
689
+ continue
690
+ payload = line[5:].strip()
691
+ if not payload or payload == "[DONE]":
692
+ continue
693
+ try:
694
+ obj = json.loads(payload)
695
+ except Exception:
696
+ continue # 半行/坏行静默跳过,不中断整流
697
+ if not isinstance(obj, dict):
698
+ continue
699
+ box["events"] += 1
700
+ reason = _reason_from_delta(proto, obj)
701
+ with lock:
702
+ if reason:
703
+ acc["reasoning"] += reason
704
+ moved = _stream_accumulate(proto, obj, acc)
705
+ text_now = acc["text"]
706
+ if reason:
707
+ _emit(on_reason, reason)
708
+ if text_now != box["sent_text"]:
709
+ box["sent_text"] = text_now
710
+ _emit(on_text, text_now) # 累计正文(运行中实时打印)
711
+ elif moved and not reason:
712
+ _emit(on_tick, None) # 只有工具/用量在推进的心跳
713
+ if sum(len(x) for x in (acc["text"], acc["reasoning"])) > 4 * 1024 * 1024:
714
+ break # 防失控
715
+ except Exception as e:
716
+ box["err"] = box["err"] or tlsctx.humanize(repr(e)[:300])
717
+
718
+ th = threading.Thread(target=_go, daemon=True)
719
+ th.start()
720
+ if cancel_event is None:
721
+ th.join(timeout + 10)
722
+ else:
723
+ while th.is_alive() and not cancel_event.wait(0.5):
724
+ pass
725
+ with lock:
726
+ out = {"status": box["status"], "text": acc["text"],
727
+ "reasoning": acc["reasoning"], "usage": dict(acc["usage"]),
728
+ "calls": _calls_from_acc(acc), "events": box["events"],
729
+ "error": box["err"]}
730
+ if cancel_event is not None and cancel_event.is_set():
731
+ out["error"], out["status"] = "已取消", 0
732
+ return out
733
+ if th.is_alive():
734
+ out["error"], out["status"] = "响应超时", 0
735
+ return out
736
+
737
+
407
738
  def _m_openai(m):
408
739
  """内部消息 → openai 消息。tool_results: [(call_id, 结果文本)]。"""
409
740
  if m["role"] == "assistant":
@@ -450,14 +781,21 @@ def _m_anthropic(m):
450
781
  return {"role": "user", "content": [{"type": "text", "text": m.get("content") or ""}]}
451
782
 
452
783
 
453
- def _build_request(proto, base, use_key, model, system, msgs, with_tools):
454
- """按协议构造 (url, headers, body)。msgs 为内部统一形状。"""
784
+ def _build_request(proto, base, use_key, model, system, msgs, with_tools, stream=False,
785
+ max_tokens=BASE_MAX_TOKENS):
786
+ """按协议构造 (url, headers, body)。msgs 为内部统一形状。
787
+
788
+ stream=True 时按协议打开流式:google 换 :streamGenerateContent?alt=sse,
789
+ openai/anthropic 置 stream 字段(openai 另要 include_usage,否则收尾
790
+ chunk 不带 usage,这一步的 token 记账会凭空少一截)。"""
455
791
  base = (base or "").rstrip("/")
456
792
  if proto == "google":
457
793
  if base.endswith("/v1beta"):
458
- url = base + "/models/%s:generateContent" % model
794
+ prefix = base + "/models/%s"
459
795
  else:
460
- url = base + "/v1beta/models/%s:generateContent" % model
796
+ prefix = base + "/v1beta/models/%s"
797
+ url = (prefix + (":streamGenerateContent?alt=sse" if stream
798
+ else ":generateContent")) % model
461
799
  headers = {"x-goog-api-key": use_key}
462
800
  contents = []
463
801
  for m in msgs:
@@ -470,16 +808,18 @@ def _build_request(proto, base, use_key, model, system, msgs, with_tools):
470
808
  "parts": parts})
471
809
  body = {"contents": contents,
472
810
  "systemInstruction": {"parts": [{"text": system}]},
473
- "generationConfig": {"maxOutputTokens": 8000}}
811
+ "generationConfig": {"maxOutputTokens": max_tokens}}
474
812
  return url, headers, body
475
813
  path = "/messages" if proto == "anthropic" else "/chat/completions"
476
814
  url = (base + path) if base.endswith("/v1") else (base + "/v1" + path)
477
815
  if proto == "anthropic":
478
816
  headers = {"x-api-key": use_key, "anthropic-version": "2023-06-01"}
479
- body = {"model": model, "max_tokens": 8000, "system": system,
817
+ body = {"model": model, "max_tokens": max_tokens, "system": system,
480
818
  "messages": [_m_anthropic(m) for m in msgs]}
481
819
  if with_tools:
482
820
  body["tools"] = _anthropic_tools()
821
+ if stream:
822
+ body["stream"] = True
483
823
  return url, headers, body
484
824
  headers = {"Authorization": "Bearer " + use_key}
485
825
  # tool_results 消息展开成多条 role=tool(_m_openai 对它返回列表,不能嵌套)
@@ -490,10 +830,13 @@ def _build_request(proto, base, use_key, model, system, msgs, with_tools):
490
830
  msgs_wire.extend(w)
491
831
  else:
492
832
  msgs_wire.append(w)
493
- body = {"model": model, "max_tokens": 8000,
833
+ body = {"model": model, "max_tokens": max_tokens,
494
834
  "messages": [{"role": "system", "content": system}] + msgs_wire}
495
835
  if with_tools:
496
836
  body["tools"] = _openai_tools()
837
+ if stream:
838
+ body["stream"] = True
839
+ body["stream_options"] = {"include_usage": True}
497
840
  return url, headers, body
498
841
 
499
842
 
@@ -546,14 +889,34 @@ def _parse_reply(proto, data):
546
889
 
547
890
  # ---------------------------------------------------------------- 主循环
548
891
 
549
- def run(bi, prompt, workdir, timeout=180, cancel_event=None, log=None, images=None):
892
+ def _norm_usage(usage):
893
+ """三协议 usage → {input, output, cached, total}(缺 total 用三项相加补齐)。"""
894
+ out = {"input": 0, "output": 0, "cached": 0, "total": 0}
895
+ for k in out:
896
+ try:
897
+ out[k] = int((usage or {}).get(k) or 0)
898
+ except Exception:
899
+ out[k] = 0
900
+ if not out["total"]:
901
+ out["total"] = out["input"] + out["output"] + out["cached"]
902
+ return out
903
+
904
+
905
+ def run(bi, prompt, workdir, timeout=180, cancel_event=None, log=None, images=None,
906
+ on_reason=None, on_stream=None, on_activity=None, stream=True):
550
907
  """跑一次内置智能体(内部自带工具循环直到给出最终回答)。
551
908
 
552
909
  bi: resolve() 的返回;prompt: 本轮完整输入(目标/续轮块由 pipeline 拼);
553
910
  images: 用户随本轮消息提供的图片绝对路径列表(任务附件/对话追话);
554
911
  log: 追加一行日志的回调(步骤日志)。返回 runner 风格统一结果:
555
- {ok, text, usage, error, model, provider_name, provider_id, iterations, cost_usd}。
556
- """
912
+ {ok, text, usage, error, model, provider_name, provider_id, iterations,
913
+ cost_usd, reasoning}。
914
+
915
+ 思考过程可视化(2026-09-22 用户诉求「把思考过程打印出来」):stream=True 走
916
+ SSE,模型的思维链(reasoning_content / thinking 块)边收边经 on_reason 回调,
917
+ 正文增量经 on_stream(累计值),工具活动经 on_activity——调用方据此在对话
918
+ 时间线上实时打印,不再让用户干看三点打字动画。网关忽略 stream(零事件)时
919
+ 自动回落非流式,思考字段仍从响应体兜底抽取(on_reason 补发一次)。"""
557
920
  prov = bi["prov"]
558
921
  model = bi["model"]
559
922
  allow_private = bool(prov.get("allow_private"))
@@ -575,83 +938,213 @@ def run(bi, prompt, workdir, timeout=180, cancel_event=None, log=None, images=No
575
938
  iters = 0
576
939
  last_err = ""
577
940
  ok = False
941
+ reasons = [] # 各迭代的思考正文(按迭代顺序拼接,供步骤记录展示)
942
+ max_tokens = BASE_MAX_TOKENS # 思考占满预算时提额重试(跨迭代保持,见空正文分支)
943
+ escalated = False # 本轮 run 是否已提额(只提一次,防无限翻倍)
944
+ empty_streak = 0 # 连续零正文轮数(拿到正文/工具即清零)
945
+
946
+ def _fire(cb, *cb_args):
947
+ if cb is None:
948
+ return
949
+ try:
950
+ cb(*cb_args)
951
+ except Exception:
952
+ pass # 可视化是增强:回调炸了不能拖垮生成
953
+
954
+ def _take_reason(reason):
955
+ """收一段思考:攒进本轮正文并实时回调(限长,防超长思维链撑爆 run.json)。"""
956
+ if not reason:
957
+ return
958
+ if not reasons:
959
+ reasons.append("")
960
+ if len(reasons[-1]) < THINK_MAX_CHARS:
961
+ reasons[-1] += reason
962
+ _fire(on_reason, reason)
578
963
 
579
964
  def _fail(err):
580
965
  return {"ok": False, "text": "", "usage": dict(total_usage), "error": err,
581
966
  "model": model, "provider_name": bi["provider_name"],
582
- "provider_id": bi["provider_id"], "iterations": iters, "cost_usd": 0.0}
967
+ "provider_id": bi["provider_id"], "iterations": iters, "cost_usd": 0.0,
968
+ "reasoning": "\n\n".join(r for r in reasons if r)[:THINK_MAX_CHARS]}
583
969
 
584
970
  for it in range(1, MAX_TOOL_ITERS + 1):
585
971
  if cancel_event is not None and cancel_event.is_set():
586
972
  return _fail("已取消")
973
+ reasons.append("") # 每轮迭代各占一段思考(跨轮拼接时分段,join 时滤空段)
587
974
  done = False
588
- for proto, pbase in candidates:
589
- keys = modelhub._chain_keys(prov) or [{"key": prov.get("api_key") or "", "id": ""}]
590
- for kk in keys:
591
- url, headers, body = _build_request(proto, pbase, kk["key"], model,
592
- system, msgs, tools_ok)
593
- effort = str(bi.get("reasoning_effort") or "").strip().lower()
594
- # reasoning_effort 是 OpenAI wire 字段;Anthropic thinking 使用
595
- # 另一套对象结构,向兼容网关硬塞该字段会直接得到 400。
596
- if effort in ("low", "medium", "high") and proto == "openai":
597
- body["reasoning_effort"] = effort
598
- status, data, err = _post_interruptible(url, headers, body,
599
- allow_private, timeout,
600
- cancel_event)
601
- if cancel_event is not None and cancel_event.is_set():
602
- # 取消先于一切记账:健康 KEY 不能因被放弃的请求背上冷却
603
- return _fail("已取消")
604
- if status == 0 or not (200 <= status < 300):
605
- msg = ""
606
- if isinstance(data, dict):
607
- e = data.get("error")
608
- msg = e.get("message", "") if isinstance(e, dict) else str(e)
609
- last_err = err or ("HTTP %s %s" % (status, str(msg)[:200]))
610
- try:
611
- modelhub.note_key_error(bi["provider_id"], kk.get("id") or "", last_err)
612
- except Exception:
613
- pass
614
- continue
615
- try:
616
- modelhub.note_key_ok(bi["provider_id"], kk.get("id") or "")
617
- except Exception:
618
- pass
619
- text, calls, usage = _parse_reply(proto, data)
620
- for k in total_usage:
621
- total_usage[k] += int(usage.get(k) or 0)
622
- iters = it
623
- if calls:
624
- if log:
625
- log("[迭代 %d] %s 请求工具: %s" % (
626
- it, model, ", ".join(c["name"] for c in calls)))
627
- results = []
628
- for c in calls:
629
- out = _exec_tool(workdir, c["name"], c["args"])
975
+ reBump = False # 本轮要提额重试(同一迭代重跑,不烧迭代数)
976
+ stopit = False # 本轮判死(连续零正文),直接终局不再空转
977
+ for _bump in range(2): # 第 2 圈 = 提额后的同轮重试
978
+ for proto, pbase in candidates:
979
+ keys = modelhub._chain_keys(prov) or [{"key": prov.get("api_key") or "", "id": ""}]
980
+ for kk in keys:
981
+ got = False # 本 KEY 拿到了响应(区别于 HTTP 失败换下家)
982
+ stripped = False # thinking 对象被网关 400 拒后已摘除重发
983
+ while True:
984
+ url, headers, body = _build_request(
985
+ proto, pbase, kk["key"], model, system, msgs,
986
+ tools_ok, max_tokens=max_tokens)
987
+ sbody = None
988
+ if stream:
989
+ # 流式体单独构造(+stream / include_usage);非流式体留给回落重发
990
+ _, _, sbody = _build_request(
991
+ proto, pbase, kk["key"], model, system, msgs,
992
+ tools_ok, stream=True, max_tokens=max_tokens)
993
+ effort = str(bi.get("reasoning_effort") or "").strip().lower()
994
+ # reasoning_effort 是 OpenAI wire 字段;Anthropic thinking 使用
995
+ # 另一套对象结构,向兼容网关硬塞该字段会直接得到 400。
996
+ if effort in ("low", "medium", "high") and proto == "openai":
997
+ body["reasoning_effort"] = effort
998
+ if sbody is not None:
999
+ sbody["reasoning_effort"] = effort
1000
+ if effort in ("low", "medium") and proto == "anthropic" \
1001
+ and not stripped:
1002
+ # 「思考程度」此前只对 openai 面生效;GLM 这类推理模型
1003
+ # 在 Anthropic 兼容面上默认全功率思考,能把 max_tokens
1004
+ # 整个烧光(2026-09-22 glm-5.3-flash 47 分钟零正文案)。
1005
+ # low/medium 显式给思考预算,high 留默认(模型自决=放开想)。
1006
+ body["thinking"] = {
1007
+ "type": "enabled",
1008
+ "budget_tokens": 1024 if effort == "low" else 4096}
1009
+ if sbody is not None:
1010
+ sbody["thinking"] = dict(body["thinking"])
1011
+ text, calls, usage = "", [], {}
1012
+ streamed = False
1013
+ if sbody is not None:
1014
+ part = _post_sse_stream(
1015
+ url, headers, sbody, allow_private, timeout, proto,
1016
+ on_reason=_take_reason, on_text=on_stream,
1017
+ cancel_event=cancel_event)
1018
+ if part["error"] == "已取消":
1019
+ return _fail("已取消")
1020
+ if not part["error"] and part["events"]:
1021
+ # 网关确实按流回了:正文/工具取增量累加结果
1022
+ text, calls = part["text"], part["calls"]
1023
+ usage = part["usage"]
1024
+ streamed = True
1025
+ if not reasons or not reasons[-1]:
1026
+ # 调用方没挂实时回调(无可视化诉求)时思考只在
1027
+ # 累加器里:这里兜底收进结果,落库口径一致
1028
+ _take_reason(part["reasoning"])
1029
+ else:
1030
+ # 零事件(网关忽略 stream)或流式这一步失败(不认 stream 参数、
1031
+ # 断流等):都退回同一条 wire 的非流式重发——比直接判死这家
1032
+ # 供应商稳妥;非流式也失败才走下面的记账/换链。
1033
+ last_err = part["error"]
1034
+ if not streamed:
1035
+ status, data, err = _post_interruptible(url, headers, body,
1036
+ allow_private, timeout,
1037
+ cancel_event)
1038
+ if cancel_event is not None and cancel_event.is_set():
1039
+ # 取消先于一切记账:健康 KEY 不能因被放弃的请求背上冷却
1040
+ return _fail("已取消")
1041
+ if status == 0 or not (200 <= status < 300):
1042
+ msg = ""
1043
+ if isinstance(data, dict):
1044
+ e = data.get("error")
1045
+ msg = e.get("message", "") if isinstance(e, dict) else str(e)
1046
+ if status == 400 and isinstance(body.get("thinking"), dict) \
1047
+ and "thinking" in str(msg).lower() and not stripped:
1048
+ # 网关不认 thinking 对象:摘掉同 KEY 立即重发,
1049
+ # 别让「思考程度」偏好把健康 KEY 送进冷却
1050
+ body.pop("thinking", None)
1051
+ if sbody is not None:
1052
+ sbody.pop("thinking", None)
1053
+ stripped = True
1054
+ continue
1055
+ last_err = err or ("HTTP %s %s" % (status, str(msg)[:200]))
1056
+ try:
1057
+ modelhub.note_key_error(bi["provider_id"], kk.get("id") or "", last_err)
1058
+ except Exception:
1059
+ pass
1060
+ break # 换下一个 KEY
1061
+ text, calls, usage = _parse_reply(proto, data)
1062
+ # 非流式响应里的思考字段:补发一次,可视化与流式路径同形
1063
+ _take_reason(_reason_from_message(proto, data))
1064
+ try:
1065
+ modelhub.note_key_ok(bi["provider_id"], kk.get("id") or "")
1066
+ except Exception:
1067
+ pass
1068
+ usage = _norm_usage(usage)
1069
+ for k in total_usage:
1070
+ total_usage[k] += int(usage.get(k) or 0)
1071
+ iters = it
1072
+ got = True
1073
+ break
1074
+ if not got:
1075
+ continue # 本 KEY 失败,换下一个
1076
+ if calls:
630
1077
  if log:
631
- brief = out if len(out) <= 120 else out[:120] + "…"
632
- log("[工具] %s → %s" % (c["name"], brief.replace("\n", " ⏎ ")))
633
- results.append((c["id"], out))
634
- msgs.append({"role": "assistant", "content": text, "tool_calls": calls})
635
- msgs.append({"role": "tool_results", "tool_results": results})
636
- done = True
637
- break
638
- if (text or "").strip():
1078
+ log("[迭代 %d] %s 请求工具: %s" % (
1079
+ it, model, ", ".join(c["name"] for c in calls)))
1080
+ _fire(on_activity, "请求工具: " + "、".join(c["name"] for c in calls))
1081
+ results = []
1082
+ for c in calls:
1083
+ out = _exec_tool(workdir, c["name"], c["args"], cancel_event)
1084
+ if log:
1085
+ brief = out if len(out) <= 120 else out[:120] + "…"
1086
+ log("[工具] %s → %s" % (c["name"], brief.replace("\n", " ⏎ ")))
1087
+ _fire(on_activity, "%s %s" % (
1088
+ c["name"], str(c["args"].get("path")
1089
+ or c["args"].get("command") or "")[:80]))
1090
+ results.append((c["id"], out))
1091
+ msgs.append({"role": "assistant", "content": text, "tool_calls": calls})
1092
+ msgs.append({"role": "tool_results", "tool_results": results})
1093
+ empty_streak = 0
1094
+ done = True
1095
+ break
1096
+ if (text or "").strip():
1097
+ if log:
1098
+ log("[迭代 %d] 最终回答(%d 字)" % (it, len(text)))
1099
+ ok = True
1100
+ empty_streak = 0
1101
+ done = True
1102
+ break
1103
+ # —— 零正文零工具:分辨「思考占满输出预算」还是「模型真没说话」。
1104
+ # 推理模型的思考计入 max_tokens:想满了流会正常收,正文却是空的。
1105
+ rlen = len(reasons[-1] or "")
1106
+ out_tok = int(usage.get("output") or 0)
1107
+ exhausted = (rlen >= THINK_EXHAUST_MIN_CHARS
1108
+ or out_tok >= int(max_tokens * 0.9))
1109
+ empty_streak += 1
1110
+ if exhausted and not escalated:
1111
+ # 同轮提额重试一次:8K 想不完的 16K 大多就想完了
1112
+ escalated = True
1113
+ old = max_tokens
1114
+ max_tokens = min(max_tokens * 2, MAX_TOKENS_CAP)
1115
+ last_err = ("模型思考占满输出预算(max_tokens=%d,思考 %d 字零正文)"
1116
+ % (old, rlen))
1117
+ if log:
1118
+ log("[第 %d 轮] 思考 %d 字仍无正文/工具 → max_tokens %d→%d 同轮重试"
1119
+ % (it, rlen, old, max_tokens))
1120
+ _fire(on_activity, "思考占满输出预算,提高输出预算重试")
1121
+ reBump = True
1122
+ break
1123
+ if empty_streak >= EMPTY_TEXT_MAX_STREAK:
1124
+ last_err = ("模型思考连续占满输出预算(max_tokens 已提到 %d 仍无正文)"
1125
+ % max_tokens) if exhausted else \
1126
+ ("模型连续 %d 轮零正文零工具" % empty_streak)
1127
+ done = True
1128
+ stopit = True
1129
+ break
1130
+ last_err = "模型未返回文本"
639
1131
  if log:
640
- log("[迭代 %d] 最终回答(%d 字)" % (it, len(text)))
641
- ok = True
1132
+ log("[第 %d 轮] 模型零正文零工具(思考 %d 字),重试" % (it, rlen))
1133
+ _fire(on_activity, "模型零正文,重试")
642
1134
  done = True
643
1135
  break
644
- last_err = "模型未返回文本"
645
- done = True
646
- break
647
- if done:
648
- break
1136
+ if done or reBump:
1137
+ break
1138
+ if reBump:
1139
+ continue # 同一迭代用新预算重来
1140
+ break # 非提额路径一锤定音
649
1141
  if not done:
650
1142
  break # 所有 wire/KEY 都失败
651
- if ok:
1143
+ if ok or stopit:
652
1144
  break
653
1145
  if not ok and not text:
654
1146
  return _fail(last_err or "工具循环达上限仍无最终回答")
655
1147
  return {"ok": True, "text": (text or "").strip(), "usage": dict(total_usage),
656
1148
  "error": "", "model": model, "provider_name": bi["provider_name"],
657
- "provider_id": bi["provider_id"], "iterations": iters, "cost_usd": 0.0}
1149
+ "provider_id": bi["provider_id"], "iterations": iters, "cost_usd": 0.0,
1150
+ "reasoning": "\n\n".join(r for r in reasons if r)[:THINK_MAX_CHARS]}