-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzcode.py
More file actions
1842 lines (1799 loc) · 95.5 KB
/
Copy pathzcode.py
File metadata and controls
1842 lines (1799 loc) · 95.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "httpx",
# "tiktoken",
# "textual",
# ]
# ///
"""
ZCode TUI - A Textual-based AI coding assistant
Backend: OpenAI-compatible LLM endpoint
Update 2026-05-03:
- 多后备 API endpoint 支持
- 手动端点切换按钮(工具栏 EP 按钮)
- 轮次递进压缩(compression.rounds 配置)
- 移除对话区端点切换 info 消息
- 技能纯语义自动加载,从 config.json skills.dir 路径读取
- 取消 /skill 命令,技能完全自动匹配
"""
import asyncio
import copy
import json
import os
import re
import subprocess
import sys
import time
import unicodedata
import warnings
from datetime import datetime
from pathlib import Path
warnings.filterwarnings("ignore", category=ResourceWarning)
import httpx
import tiktoken
_TIKTOKEN_ENC = None
def _get_tiktoken_enc():
global _TIKTOKEN_ENC
if _TIKTOKEN_ENC is None:
_TIKTOKEN_ENC = tiktoken.get_encoding("cl100k_base")
return _TIKTOKEN_ENC
from textual import on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, ScrollableContainer, Vertical
from textual.css.query import NoMatches
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import (
Button,
Collapsible,
Footer,
Header,
Markdown,
Static,
TextArea,
)
# ─────────────────────────── Config ───────────────────────────
CONFIG_TEMPLATE_PATH = Path(__file__).parent / "config.json"
def _infer_ep_type(base: str) -> str:
"""Guess endpoint type from base URL when 'type' field is absent."""
b = base.lower()
if "anthropic" in b: return "anthropic"
if "openrouter" in b: return "openrouter"
if "openai.com" in b: return "openai"
if "deepseek" in b: return "deepseek"
if "localhost" in b or "127.0.0.1" in b or "0.0.0.0" in b: return "llama-server"
return "generic"
def _normalize_config(config: dict) -> dict:
"""
Normalise config to new format:
top-level 'endpoints' list, each entry has a 'type' field.
Transparently migrates old-style 'api' section configs.
"""
# Already new format — deep copy to avoid mutating input
if "endpoints" in config and isinstance(config.get("endpoints"), list):
config = copy.deepcopy(config)
eps = config["endpoints"]
for ep in eps:
if "type" not in ep:
ep["type"] = _infer_ep_type(ep.get("base", ""))
return config
# Old format: top-level 'api' dict with optional nested 'endpoints'
api = config.get("api", {})
raw_eps = api.get("endpoints", [])
base_defaults = {k: v for k, v in api.items() if k != "endpoints"}
if not raw_eps:
merged_eps = [base_defaults]
else:
merged_eps = []
for ep in raw_eps:
m = copy.deepcopy(base_defaults); m.update(ep)
if "timeout" in ep and isinstance(ep["timeout"], dict):
m["timeout"] = {**copy.deepcopy(base_defaults.get("timeout", {})), **ep["timeout"]}
merged_eps.append(m)
# Lift old-style top-level reasoning/context into each endpoint
old_reasoning = config.get("reasoning", {})
old_ctx_limit = config.get("context", {}).get("limit", 0)
old_keep_recent = config.get("context", {}).get("keep_recent", 3)
for ep in merged_eps:
if "type" not in ep:
ep["type"] = _infer_ep_type(ep.get("base", ""))
if "reasoning" not in ep and old_reasoning:
ep["reasoning"] = old_reasoning.copy()
if "context_limit" not in ep and old_ctx_limit:
ep["context_limit"] = old_ctx_limit
if "keep_recent" not in ep and old_keep_recent:
ep["keep_recent"] = old_keep_recent
out = {k: v for k, v in config.items() if k not in ("api", "reasoning")}
out["endpoints"] = merged_eps
return out
def load_default_config() -> dict:
"""Load and normalise config from template file."""
if CONFIG_TEMPLATE_PATH.exists():
with open(CONFIG_TEMPLATE_PATH, encoding="utf-8") as f:
return _normalize_config(json.load(f))
raise FileNotFoundError(
f"Config template not found: {CONFIG_TEMPLATE_PATH}\n"
"Please ensure config.json exists in the application directory."
)
_DEFAULT_CONFIG_CACHE = None
def get_default_config() -> dict:
global _DEFAULT_CONFIG_CACHE
if _DEFAULT_CONFIG_CACHE is None:
_DEFAULT_CONFIG_CACHE = load_default_config()
return _DEFAULT_CONFIG_CACHE
def get_skills_dir(config: dict = None) -> Path:
"""Get skills directory from config.json skills.dir, fallback to ~/.claudecode/skills."""
cfg = config or get_default_config()
skills_cfg = cfg.get("skills", {})
dir_path = skills_cfg.get("dir", "")
if dir_path:
return Path(dir_path).expanduser()
return Path("~/.claudecode/skills").expanduser()
def get_mcp_config(config: dict = None) -> dict:
"""Get MCP configuration (servers, enabled)."""
cfg = config or get_default_config()
return cfg.get("mcp", {"enabled": False, "servers": {}})
def load_config() -> dict:
"""Load and normalise config (single source of truth)."""
skills_dir = get_skills_dir()
skills_dir.mkdir(parents=True, exist_ok=True)
return copy.deepcopy(get_default_config())
# ─────────────────────────── Tokenizer ───────────────────────────
def _fallback_count_tokens(text: str) -> int:
"""
Token 估算:中文/全角符号 计 2.0,英文/代码符号 计 0.75
使用 unicodedata.east_asian_width 判断字符宽度。
"""
if not text:
return 0
total = 0.0
for ch in text:
w = unicodedata.east_asian_width(ch)
total += 2.0 if w in ("W", "F") else 0.75
return int(total)
def count_tokens(text: str, multiplier: float = 1.0) -> int:
"""优先使用 tiktoken,失败时使用 fallback 估算"""
if not text:
return 0
try:
base = len(_get_tiktoken_enc().encode(text))
except Exception:
base = _fallback_count_tokens(text)
return max(1, int(base * multiplier))
def messages_token_count(messages: list, multiplier: float = 1.0) -> int:
"""
计算消息列表的总 token 数,正确处理:
- content 文本块
- tool_calls (OpenAI 格式)
- tool_use / tool_result (Anthropic 格式)
每则消息额外 4 tokens 结构开销。
"""
total = 0
for m in messages:
content = m.get("content", "")
if isinstance(content, list):
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
total += count_tokens(block.get("text", ""), multiplier)
elif isinstance(content, str):
total += count_tokens(content, multiplier)
tool_calls = m.get("tool_calls")
if tool_calls:
for tc in tool_calls:
fn = tc.get("function", {})
total += count_tokens(fn.get("name", ""), multiplier)
total += count_tokens(fn.get("arguments", ""), multiplier)
if m.get("role") == "assistant" and isinstance(content, list):
for block in content:
if isinstance(block, dict) and block.get("type") == "tool_use":
total += count_tokens(block.get("name", ""), multiplier)
total += count_tokens(json.dumps(block.get("input", {})), multiplier)
if m.get("role") == "user" and isinstance(content, list):
for block in content:
if isinstance(block, dict) and block.get("type") == "tool_result":
total += count_tokens(block.get("content", ""), multiplier)
if m.get("role") == "tool":
total += count_tokens(m.get("name", ""), multiplier)
total += count_tokens(m.get("tool_call_id", ""), multiplier)
total += 4
return total
# ─────────────────────────── Async Rate Limiter ───────────────────────────
class AsyncRateLimiter:
"""
Per-endpoint token-bucket rate limiter supporting:
rpm_limit – max requests per minute (0 = disabled)
tpm_limit – max tokens per minute (0 = disabled)
qps_limit – max queries per second (0 = disabled)
token_budget – hard lifetime token cap (0 = disabled)
"""
def __init__(self, rpm_limit: int = 0, tpm_limit: int = 0,
qps_limit: float = 0, token_budget: int = 0):
self.rpm_limit = rpm_limit
self.tpm_limit = tpm_limit
self.qps_limit = qps_limit
self.token_budget = token_budget
self._rpm_bucket = float(rpm_limit) if rpm_limit > 0 else 0.0
self._tpm_bucket = float(tpm_limit) if tpm_limit > 0 else 0.0
self._qps_bucket = 1.0 if qps_limit > 0 else 0.0
self._total_tokens_used: int = 0
self._last_time = time.monotonic()
self._lock = asyncio.Lock()
self._cooldown_until: float = 0.0
def _refill(self):
now = time.monotonic()
elapsed = now - self._last_time
if elapsed <= 0:
return
if self.rpm_limit > 0:
self._rpm_bucket = min(self._rpm_bucket + elapsed * (self.rpm_limit / 60.0), float(self.rpm_limit))
if self.tpm_limit > 0:
self._tpm_bucket = min(self._tpm_bucket + elapsed * (self.tpm_limit / 60.0), float(self.tpm_limit))
if self.qps_limit > 0:
self._qps_bucket = min(self._qps_bucket + elapsed * self.qps_limit, 1.0)
self._last_time = now
def check_budget(self) -> str | None:
"""Return error message if token budget is exhausted, else None."""
if self.token_budget > 0 and self._total_tokens_used >= self.token_budget:
return (f"Token budget exhausted: {self._total_tokens_used:,} / "
f"{self.token_budget:,} tokens used on this endpoint")
return None
async def acquire(self, estimated_tokens: int = 0) -> float:
"""Wait until rate limits allow a request. Returns seconds waited."""
active = self.rpm_limit > 0 or self.tpm_limit > 0 or self.qps_limit > 0
if not active:
return 0.0
async with self._lock:
# Honour any forced cooldown (e.g. after 429)
now = time.monotonic()
if now < self._cooldown_until:
wait = self._cooldown_until - now
await asyncio.sleep(wait)
self._refill()
wait_time = 0.0
if self.rpm_limit > 0 and self._rpm_bucket < 1.0:
wait_time = max(wait_time, (1.0 - self._rpm_bucket) / self.rpm_limit * 60.0)
if self.tpm_limit > 0 and estimated_tokens > 0 and self._tpm_bucket < estimated_tokens:
wait_time = max(wait_time, (estimated_tokens - self._tpm_bucket) / self.tpm_limit * 60.0)
if self.qps_limit > 0 and self._qps_bucket < 1.0:
wait_time = max(wait_time, (1.0 - self._qps_bucket) / self.qps_limit)
if wait_time > 0:
await asyncio.sleep(wait_time)
self._refill()
# Consume buckets
if self.rpm_limit > 0:
self._rpm_bucket -= 1.0
if self.qps_limit > 0:
self._qps_bucket -= 1.0
# Pre-consume estimated input tokens from TPM bucket
if self.tpm_limit > 0 and estimated_tokens > 0:
self._tpm_bucket -= estimated_tokens
return wait_time
def consume_tokens(self, tokens: int, input_tokens: int = 0):
"""Called after response completes with actual output (and optionally input) token count."""
if tokens <= 0 and input_tokens <= 0:
return
# Output tokens reduce the TPM bucket (input was already deducted in acquire)
if self.tpm_limit > 0:
self._tpm_bucket -= tokens
self._total_tokens_used += tokens + input_tokens
def force_429_cooldown(self, seconds: int = 60):
self._rpm_bucket = 0.0
self._tpm_bucket = 0.0
self._qps_bucket = 0.0
self._cooldown_until = time.monotonic() + seconds
def get_status(self) -> dict:
self._refill()
budget_remaining = (max(0, self.token_budget - self._total_tokens_used)
if self.token_budget > 0 else None)
return {
"rpm_limit": self.rpm_limit, "rpm_bucket": self._rpm_bucket,
"tpm_limit": self.tpm_limit, "tpm_bucket": self._tpm_bucket,
"qps_limit": self.qps_limit, "qps_bucket": self._qps_bucket,
"token_budget": self.token_budget,
"total_tokens_used": self._total_tokens_used,
"budget_remaining": budget_remaining,
}
# ─────────────────────────── Vision ───────────────────────────
MIME_MAP = {
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
".webp": "image/webp", ".gif": "image/gif", ".bmp": "image/bmp",
}
# ─────────────────────────── Skills (纯语义自动加载) ───────────────────────────
def load_skills(config: dict = None) -> dict[str, str]:
"""Load all .md files from the skills directory specified in config.json.
Skill name = parent dir name if file is in a subfolder, otherwise the file stem."""
skills = {}
skills_dir = get_skills_dir(config)
if not skills_dir.exists():
return skills
for p in skills_dir.glob("**/*.md"):
# Use parent folder name as skill name (e.g., playwright/SKILL.md → playwright)
# If file is directly in skills_dir, use file stem
if p.parent != skills_dir:
name = p.parent.name
else:
name = p.stem
try:
skills[name] = p.read_text(encoding="utf-8")
except Exception:
pass
return skills
def build_system_prompt(config: dict, skills: dict[str, str]) -> str:
"""Build system prompt with available skills listed (not auto-injected).
The LLM uses the `load_skill` tool to load full skill instructions on demand."""
parts = [config.get("system_prompt", "You are ZCode, an expert AI coding assistant. Be concise, precise, and technically rigorous.")]
if skills:
parts.append("\n\n## Available Skills")
parts.append("The following skills provide specialized instructions. Use the `load_skill` tool to load a skill when the task matches its domain.\n")
for name in sorted(skills.keys()):
content = skills[name]
desc = ""
for line in content.split("\n"):
line = line.strip()
if line.startswith("# "):
desc = line[2:].strip()
break
if not desc:
for line in content.split("\n"):
line = line.strip()
if line and not line.startswith("---"):
desc = line[:120]
break
parts.append(f"- **{name}**: {desc or name}")
return "\n".join(parts)
# ─────────────────────────── MCP ───────────────────────────
class MCPClient:
_CONNECT_TIMEOUT = 10
def __init__(self):
self.servers: dict[str, dict] = {}
self.tools: list[dict] = []
self._procs: dict[str, asyncio.subprocess.Process] = {}
self._next_id: int = 1
async def _readline(self, proc: asyncio.subprocess.Process, timeout: float) -> bytes:
return await asyncio.wait_for(proc.stdout.readline(), timeout=timeout)
async def connect(self, name: str, cmd: list[str], env: dict | None = None):
try:
e = os.environ.copy()
if env:
e.update(env)
proc = await asyncio.create_subprocess_exec(
*cmd, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE, env=e,
)
self._procs[name] = proc
# 启动后台任务消费 stderr,防止 pipe 阻塞
async def _drain_stderr():
try:
while True:
line = await proc.stderr.readline()
if not line:
break
except Exception:
pass
asyncio.get_event_loop().create_task(_drain_stderr())
for _ in range(30):
if proc.returncode is not None:
raise Exception(f"MCP process exited with {proc.returncode}")
if proc.stdin and not proc.stdin.is_closing():
break
await asyncio.sleep(0.1)
else:
raise Exception("MCP process failed to start within 3 seconds")
init_req = json.dumps({
"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2024-11-05", "capabilities": {},
"clientInfo": {"name": "claudecode", "version": "1.0"}}
}) + "\n"
proc.stdin.write(init_req.encode()); await proc.stdin.drain()
raw = await self._readline(proc, self._CONNECT_TIMEOUT)
if not raw:
return False
while raw and not raw.strip().startswith(b"{"):
raw = await self._readline(proc, self._CONNECT_TIMEOUT)
if not raw:
return False
resp = json.loads(raw)
if "result" in resp:
notif = json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n"
proc.stdin.write(notif.encode()); await proc.stdin.drain()
list_req = json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}) + "\n"
proc.stdin.write(list_req.encode()); await proc.stdin.drain()
raw = await self._readline(proc, self._CONNECT_TIMEOUT)
while raw and not raw.strip().startswith(b"{"):
raw = await self._readline(proc, self._CONNECT_TIMEOUT)
if not raw:
return False
resp = json.loads(raw)
tools = resp.get("result", {}).get("tools", [])
for t in tools:
self.tools.append({
"type": "function",
"function": {
"name": f"{name}__{t['name']}",
"description": t.get("description", ""),
"parameters": t.get("inputSchema", {"type": "object", "properties": {}}),
},
})
self.servers[name] = {"cmd": cmd, "tools": tools}
return True
except asyncio.TimeoutError:
return False
except Exception:
return False
async def call_tool(self, full_name: str, arguments: dict, timeout: float = 30) -> str:
server_name, tool_name = full_name.split("__", 1)
proc = self._procs.get(server_name)
if not proc:
return f"Error: MCP server '{server_name}' not running"
max_retries = 3
retry_delays = [1, 2, 3]
for attempt in range(max_retries):
try:
req_id = self._next_id; self._next_id += 1
req = json.dumps({
"jsonrpc": "2.0", "id": req_id, "method": "tools/call",
"params": {"name": tool_name, "arguments": arguments}
}) + "\n"
proc.stdin.write(req.encode()); await proc.stdin.drain()
raw = await asyncio.wait_for(proc.stdout.readline(), timeout=timeout)
if not raw:
if attempt < max_retries - 1:
await asyncio.sleep(retry_delays[attempt]); continue
return "No response from MCP server"
while raw and not raw.strip().startswith(b"{"):
raw = await asyncio.wait_for(proc.stdout.readline(), timeout=timeout)
if not raw:
break
if not raw:
if attempt < max_retries - 1:
await asyncio.sleep(retry_delays[attempt]); continue
return "No response from MCP server"
resp = json.loads(raw)
if "error" in resp:
return f"MCP error: {resp['error']}"
content = resp.get("result", {}).get("content", [])
result_text = "\n".join(c.get("text", "") for c in content if c.get("type") == "text")
if not result_text:
if attempt < max_retries - 1:
await asyncio.sleep(retry_delays[attempt]); continue
return f"Tool '{tool_name}' returned empty result"
return result_text
except asyncio.TimeoutError:
if attempt < max_retries - 1:
await asyncio.sleep(retry_delays[attempt]); continue
return f"Tool '{tool_name}' timed out after {timeout}s"
except Exception as e:
if attempt < max_retries - 1:
await asyncio.sleep(retry_delays[attempt]); continue
return f"MCP error: {e}"
return f"Tool '{tool_name}' failed after {max_retries} attempts"
def close_all(self):
for name, proc in self._procs.items():
try:
proc.terminate()
except Exception:
try:
proc.kill()
except Exception:
pass
self._procs.clear()
self.tools.clear()
self.servers.clear()
# ─────────────────────────── Built-in Tools ───────────────────────────
BUILTIN_TOOLS = [
{"type": "function", "function": {"name": "read_file", "description": "Read the contents of a file from the filesystem.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute or relative file path"}}, "required": ["path"]}}},
{"type": "function", "function": {"name": "write_file", "description": "Write content to a file (creates or overwrites).", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}},
{"type": "function", "function": {"name": "list_dir", "description": "List files and directories at a given path.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Directory path (default: current dir)"}}, "required": []}}},
{"type": "function", "function": {"name": "run_command", "description": "Run a shell command and return stdout/stderr.", "parameters": {"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "cwd": {"type": "string", "description": "Working directory (optional)"}}, "required": ["command"]}}},
{"type": "function", "function": {"name": "search_files", "description": "Search for text pattern in files using grep.", "parameters": {"type": "object", "properties": {"pattern": {"type": "string"}, "path": {"type": "string", "description": "Directory to search in"}, "file_pattern": {"type": "string", "description": "File glob pattern e.g. '*.py'"}}, "required": ["pattern"]}}},
{"type": "function", "function": {"name": "load_skill", "description": "Load a skill's full instructions from SKILL.md into the conversation. Skills are specialized instruction sets for specific tasks (browser automation, web search, etc.). Call this when the user's task matches a skill's domain, then follow the skill instructions precisely.", "parameters": {"type": "object", "properties": {"skill_name": {"type": "string", "description": "Name of the skill to load (e.g., 'playwright', 'taobao_search_headed')"}}, "required": ["skill_name"]}}},
]
_ANSI_ESCAPE_RE = re.compile(r'\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
_OSC_ESCAPE_RE = re.compile(r'\x1b\][^\x07]*\x07')
_CONTROL_CHARS_RE = re.compile(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]')
def _clean_output(text: str) -> str:
"""剥离 ANSI 转义序列(含OSC)、控制字符,防止 Textual 渲染被污染"""
if not text:
return text
text = _ANSI_ESCAPE_RE.sub('', text)
text = _OSC_ESCAPE_RE.sub('', text)
text = _CONTROL_CHARS_RE.sub('', text)
text = re.sub(r'\r\n', '\n', text)
return text.strip()
async def execute_builtin_tool(name: str, arguments: dict, timeout: int = 30, command_timeout: int = 30, search_timeout: int = 15) -> str:
try:
if name == "read_file":
p = Path(arguments["path"]).expanduser()
loop = asyncio.get_event_loop()
content = await loop.run_in_executor(None, lambda: p.read_text(encoding="utf-8", errors="replace"))
return _clean_output(content)
elif name == "write_file":
p = Path(arguments["path"]).expanduser()
p.parent.mkdir(parents=True, exist_ok=True)
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, lambda: p.write_text(arguments["content"], encoding="utf-8"))
return f"Written {len(arguments['content'])} chars to {p}"
elif name == "list_dir":
p = Path(arguments.get("path", ".")).expanduser()
loop = asyncio.get_event_loop()
entries = await loop.run_in_executor(None, lambda: sorted(p.iterdir(), key=lambda x: (x.is_file(), x.name)))
lines = [f"{'📄' if e.is_file() else '📁'} {e.name}" for e in entries]
return _clean_output("\n".join(lines)) if lines else "(empty)"
elif name == "run_command":
cmd_timeout = arguments.get("timeout", command_timeout)
cwd = arguments.get("cwd")
_env = os.environ.copy()
_env.update({"TERM": "dumb", "COLUMNS": "80", "LINES": "24",
"CLICOLOR": "0", "NO_COLOR": "1", "PYTHONUNBUFFERED": "1"})
proc = await asyncio.create_subprocess_shell(
arguments["command"],
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
stdin=asyncio.subprocess.DEVNULL,
cwd=cwd,
env=_env,
)
try:
stdout_b, _ = await asyncio.wait_for(proc.communicate(), timeout=cmd_timeout)
output = stdout_b.decode("utf-8", errors="replace") if stdout_b else ""
output = _clean_output(output)
max_chars = 8000
if len(output) > max_chars:
output = output[:max_chars] + "\n\n... [Output truncated for stability]"
return f"STDOUT/STDERR:\n{output}\nEXIT_CODE: {proc.returncode}"
except asyncio.TimeoutError:
try:
proc.terminate()
await proc.wait()
return f"Error: Command timed out after {cmd_timeout}s."
except Exception:
try:
proc.kill()
except Exception:
pass
return f"Error: Command timed out after {cmd_timeout}s and was killed."
elif name == "load_skill":
skill_name = arguments.get("skill_name", "")
if not skill_name:
return "Error: 'skill_name' is required"
skills_dir = get_skills_dir()
paths_to_try = [
skills_dir / skill_name / "SKILL.md",
skills_dir / f"{skill_name}.md",
]
for p in paths_to_try:
if p.exists():
content = p.read_text(encoding="utf-8")
return content
available = []
if skills_dir.exists():
for d in skills_dir.iterdir():
if d.is_dir() and (d / "SKILL.md").exists():
available.append(d.name)
for f in skills_dir.glob("*.md"):
available.append(f.stem)
return f"Skill '{skill_name}' not found. Available skills: {', '.join(sorted(set(available))) if available else '(none)'}"
elif name == "search_files":
s_timeout = arguments.get("timeout", search_timeout)
pattern = arguments.get("pattern", "")
file_pat = arguments.get("file_pattern", "*")
search_path = Path(arguments.get("path", ".")).expanduser()
if not pattern:
return "Error: 'pattern' is required"
re_flags = re.IGNORECASE if sys.platform == "win32" else 0
try:
regex = re.compile(pattern, re_flags)
except re.error as e:
return f"Error: invalid regex pattern: {e}"
results = []
loop = asyncio.get_event_loop()
def _search():
matches = []
for p in search_path.rglob(file_pat):
if not p.is_file():
continue
try:
for i, line in enumerate(p.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
if regex.search(line):
matches.append(f"{p}:{i}: {line.rstrip()[:500]}")
except Exception:
pass
return matches
try:
matches = await asyncio.wait_for(
loop.run_in_executor(None, _search), timeout=s_timeout)
except asyncio.TimeoutError:
return f"search_files timed out after {s_timeout}s"
if not matches:
return "(no matches)"
output = "\n".join(matches[:200])
if len(matches) > 200:
output += f"\n\n... ({len(matches) - 200} more matches truncated)"
return _clean_output(output)
except Exception as e:
return f"Tool error: {e}"
return f"Unknown tool: {name}"
# ─────────────────────────── XML Tool-Call Parser ───────────────────────────
_XML_TOOL_CALL_RE = re.compile(r"<tool_call>([\s\S]*?)</tool_call>", re.MULTILINE)
_XML_FUNC_RE = re.compile(r"<function=([^>]+)>\s*(?:<parameter>\s*)?(.*?)(?:\s*</parameter>)?\s*</function>", re.DOTALL)
def _parse_xml_tool_calls(text: str) -> tuple[list[dict], str]:
calls = []
_id_counter = [0]
def _make_id() -> str:
_id_counter[0] += 1
return f"xml_tc_{_id_counter[0]}"
def _try_parse_args(raw: str) -> dict:
raw = raw.strip()
if not raw:
return {}
try:
obj = json.loads(raw)
if isinstance(obj, dict):
for key in ("parameters", "arguments", "params"):
if key in obj and isinstance(obj[key], dict):
return obj[key]
return obj if isinstance(obj, dict) else {}
except json.JSONDecodeError:
pass
start = raw.find("{"); end = raw.rfind("}")
if start != -1 and end != -1:
try:
return json.loads(raw[start:end + 1])
except json.JSONDecodeError:
pass
return {}
cleaned = text
for m in _XML_TOOL_CALL_RE.finditer(text):
body = m.group(1).strip()
try:
obj = json.loads(body)
except json.JSONDecodeError:
start = body.find("{"); end = body.rfind("}")
try:
obj = json.loads(body[start:end + 1]) if start != -1 else {}
except Exception:
obj = {}
name = obj.get("name") or obj.get("function") or ""
args = obj.get("parameters") or obj.get("arguments") or obj.get("params") or {}
if not isinstance(args, dict):
args = {}
if name:
calls.append({"id": _make_id(), "name": name, "arguments": args})
cleaned = cleaned.replace(m.group(0), "", 1)
if not calls:
for m in _XML_FUNC_RE.finditer(text):
name = m.group(1).strip()
body = m.group(2).strip()
args = _try_parse_args(body)
if name:
calls.append({"id": _make_id(), "name": name, "arguments": args})
cleaned = cleaned.replace(m.group(0), "", 1)
return calls, cleaned.strip()
# ─────────────────────────── LLM Client ───────────────────────────
class LLMClient:
def __init__(self, config: dict):
self.config = config
self.retry = config.get("retry", {})
self.endpoints: list[dict] = config["endpoints"]
self.active_endpoint_index = 0
self.app = None
self._init_rate_limiters()
def count_tokens(self, text: str) -> int:
"""优先使用 tiktoken,失败时回退至 fallback 逻辑"""
if not text:
return 0
try:
return len(_get_tiktoken_enc().encode(text))
except Exception:
return _fallback_count_tokens(text)
def get_ep_type(self, ep: dict | None = None) -> str:
ep = ep or self.get_active_endpoint()
return ep.get("type") or _infer_ep_type(ep.get("base", ""))
def _init_rate_limiters(self):
rl_cfg = self.config.get("rate_limit", {})
rl_enabled = rl_cfg.get("enabled", True)
api_cfg = self.config.get("api", {})
if rl_enabled:
g_rpm = rl_cfg.get("rpm", 0)
g_tpm = rl_cfg.get("tpm", 0)
g_qps = rl_cfg.get("qps", 0.0)
g_budget = rl_cfg.get("token_budget", 0)
else:
g_rpm = g_tpm = 0; g_qps = 0.0; g_budget = 0
# 兼容旧版 api.rpm_limit / api.tpm_limit
if g_rpm <= 0 and g_tpm <= 0:
g_rpm = int(api_cfg.get("rpm_limit", 0))
g_tpm = int(api_cfg.get("tpm_limit", 0))
self._limiters: dict[int, AsyncRateLimiter] = {}
for i, ep in enumerate(self.endpoints):
rpm = int(ep.get("rpm_limit", g_rpm))
tpm = int(ep.get("tpm_limit", g_tpm))
qps = float(ep.get("qps_limit", g_qps))
budget = int(ep.get("token_budget", g_budget))
self._limiters[i] = AsyncRateLimiter(rpm, tpm, qps, budget)
@property
def limiter(self) -> AsyncRateLimiter:
return self._limiters[self.active_endpoint_index]
def get_active_endpoint(self) -> dict:
return self.endpoints[self.active_endpoint_index]
def switch_to_next_endpoint(self) -> str:
"""切换端点并同步更新 UI 按钮文字"""
self.active_endpoint_index = (self.active_endpoint_index + 1) % len(self.endpoints)
new_ep_name = self.get_active_endpoint().get("name", f"ep{self.active_endpoint_index + 1}")
if hasattr(self, "app") and self.app:
try:
btn = self.app.query_one("#btn-ep", Button)
total = len(self.endpoints)
btn.label = f"EP: {new_ep_name} ({self.active_endpoint_index + 1}/{total})"
except Exception:
pass
return new_ep_name
ANTHROPIC_THINKING_MODELS = frozenset([
"claude-sonnet-4-20250514", "claude-sonnet-4-20250501",
"claude-3-5-sonnet-20241022", "claude-3-5-sonnet-20240620",
"claude-3-5-sonnet", "claude-3-7-sonnet-20250219", "claude-3-7-sonnet",
])
def get_headers(self, ep: dict | None = None) -> dict:
ep = ep or self.get_active_endpoint()
ep_type = self.get_ep_type(ep)
headers = {"Content-Type": "application/json"}
key = ep.get("key", "")
if ep_type == "anthropic":
if key: headers["x-api-key"] = key
headers["anthropic-version"] = "2023-06-01"
reasoning = ep.get("reasoning", {})
if reasoning.get("enabled") and self._model_supports_thinking(ep.get("model", "")):
headers["anthropic-beta"] = "interleaved-thinking-2025-05-14"
else:
if key: headers["Authorization"] = f"Bearer {key}"
if ep_type == "openrouter":
if ep.get("referer"): headers["HTTP-Referer"] = ep["referer"]
if ep.get("title"): headers["X-OpenRouter-Title"] = ep["title"]
return headers
def _model_supports_thinking(self, model: str) -> bool:
if not model: return False
m = model.lower()
if "claude" not in m:
return False
return any(s in m for s in self.ANTHROPIC_THINKING_MODELS) or "sonnet" in m or "3.7" in m
def _is_reasoning_model(self, model: str) -> bool:
if not model: return False
ml = model.lower()
if ml in ("o1", "o3", "o4"):
return True
return ml.startswith(("o1-", "o3-", "o4-", "o1-mini", "o3-mini", "o4-mini"))
def build_payload(self, messages: list, tools: list, stream: bool = True) -> dict:
ep = self.get_active_endpoint()
ep_type = self.get_ep_type(ep)
model = ep.get("model", "")
reasoning = ep.get("reasoning", {})
is_rm = self._is_reasoning_model(model)
payload = {"model": model, "messages": messages, "stream": stream}
if ep_type == "anthropic":
payload["system"] = messages[0]["content"] if messages and messages[0]["role"] == "system" else ""
payload["messages"] = [m for m in messages if m["role"] != "system"]
payload["max_tokens"] = ep.get("max_tokens", 8192)
if reasoning.get("enabled"):
r = {"enabled": True}
mode = reasoning.get("mode", "effort")
if mode == "effort":
r["effort"] = reasoning.get("effort", "medium")
elif mode == "max_tokens":
r["max_tokens"] = reasoning.get("budget", reasoning.get("max_tokens", 4000))
if reasoning.get("exclude"): r["exclude"] = True
payload["reasoning"] = r
payload["temperature"] = 1.0
else:
payload["temperature"] = ep.get("temperature", 0.7)
if tools: payload["tools"] = self._format_tools(tools)
elif ep_type == "openrouter":
for p in ["temperature", "max_tokens", "top_p", "top_k", "min_p", "top_a",
"frequency_penalty", "presence_penalty", "repetition_penalty",
"seed", "logit_bias", "logprobs", "top_logprobs",
"response_format", "structured_outputs", "route", "stop",
"parallel_tool_calls", "verbosity"]:
v = ep.get(p)
if v is not None: payload[p] = v
if tools: payload["tools"] = self._format_tools(tools)
if reasoning.get("enabled"):
r = {"enabled": True}
mode = reasoning.get("mode", "effort")
if mode == "effort":
r["effort"] = reasoning.get("effort", "medium")
elif mode == "max_tokens":
r["max_tokens"] = reasoning.get("budget", reasoning.get("max_tokens", 4000))
if reasoning.get("exclude"): r["exclude"] = True
payload["reasoning"] = r
if is_rm:
for p in ["temperature", "max_tokens", "top_p", "top_k", "min_p", "top_a",
"frequency_penalty", "presence_penalty", "repetition_penalty", "seed"]:
payload.pop(p, None)
elif ep_type in ("openai", "deepseek"):
payload["max_tokens"] = ep.get("max_tokens", 8192)
if is_rm:
for k in ("temperature", "top_p", "top_k", "presence_penalty", "frequency_penalty"):
payload.pop(k, None)
payload["max_completion_tokens"] = payload.pop("max_tokens")
else:
payload["temperature"] = ep.get("temperature", 0.7)
for p in ["top_p", "frequency_penalty", "presence_penalty"]:
v = ep.get(p)
if v is not None and v != 0.0: payload[p] = v
if tools: payload["tools"] = self._format_tools(tools)
if reasoning.get("enabled") and not is_rm:
mode = reasoning.get("mode", "effort")
if mode == "max_tokens":
payload["max_completion_tokens"] = reasoning.get("budget", reasoning.get("max_tokens", 4000))
effort = reasoning.get("effort", "medium")
if effort in ("low", "medium", "high", "none"):
payload["reasoning_effort"] = effort
else:
payload["max_tokens"] = ep.get("max_tokens", 8192)
payload["temperature"] = ep.get("temperature", 0.7)
for p in ["top_p", "top_k", "frequency_penalty", "presence_penalty", "repetition_penalty", "min_p"]:
v = ep.get(p)
if v is not None and v != 0.0: payload[p] = v
if tools: payload["tools"] = self._format_tools(tools)
if reasoning.get("enabled"):
budget = reasoning.get("budget", reasoning.get("max_tokens", 4000))
payload["thinking"] = {"type": "enabled", "budget_tokens": budget}
return payload
@staticmethod
def _sanitize_request_for_log(headers: dict, payload: dict) -> tuple[dict, dict]:
safe_headers = {}
for k, v in headers.items():
if k.lower() in ("authorization", "x-api-key"):
safe_headers[k] = v[:20] + "***" if len(v) > 20 else "***"
else:
safe_headers[k] = v
safe_payload = {}
for k, v in payload.items():
if k == "messages":
safe_msgs = []
for m in v:
mc = m.copy()
if "content" in mc:
c = mc["content"]
if isinstance(c, str) and len(c) > 200:
mc["content"] = c[:200] + f"...[{len(c)} chars]"
elif isinstance(c, list):
mc["content"] = f"[{len(c)} content blocks]"
safe_msgs.append(mc)
safe_payload[k] = safe_msgs
else:
safe_payload[k] = v
return safe_headers, safe_payload
def _format_tools(self, tools: list) -> list:
return [{"type": "function", "function": {"name": t["function"]["name"], "description": t["function"]["description"], "parameters": t["function"]["parameters"]}} for t in tools]
async def stream_completion(self, messages: list, tools: list):
retry_cfg = self.retry
max_retries = retry_cfg.get("max_retries", 3)
total_endpoints = len(self.endpoints)
original_index = self.active_endpoint_index
for offset in range(total_endpoints):
if offset > 0:
self.switch_to_next_endpoint()
last_error_msg = ""
for attempt in range(max_retries):
try:
async for event in self._do_stream(messages, tools):
yield event
return
except (httpx.ConnectError, httpx.ReadTimeout, httpx.ConnectTimeout) as e:
last_error_msg = f"Connection error ({type(e).__name__}): {e}"
if attempt < max_retries - 1:
delay = retry_cfg.get("delays", [10, 20, 40])[attempt] if attempt < len(retry_cfg.get("delays", [])) else 10
await asyncio.sleep(delay)
continue
except httpx.HTTPStatusError as e:
status = e.response.status_code
try:
resp_body = e.response.text[:3000]
except Exception:
resp_body = "(unable to read response body)"
if status == 429:
self.limiter.force_429_cooldown(60)
backoff = self.config.get("rate_limit", {}).get("backoff_delays", [10, 20, 40])
last_error_msg = f"HTTP 429 Rate Limited\nResponse: {resp_body}"
if attempt < max_retries - 1:
delay = backoff[attempt] if attempt < len(backoff) else backoff[-1]
await asyncio.sleep(delay)
continue
elif 400 <= status < 500:
yield ("error", f"HTTP {status} Client Error\nResponse: {resp_body}")
return
elif status >= 500:
last_error_msg = f"HTTP {status} Server Error\nResponse: {resp_body}"
if attempt < max_retries - 1:
delay = retry_cfg.get("delays", [10, 20, 40])[attempt] if attempt < len(retry_cfg.get("delays", [])) else 10
await asyncio.sleep(delay)
continue
except Exception as e:
yield ("error", f"Unexpected error: {type(e).__name__}: {e}")
return
if last_error_msg:
yield ("error", f"{last_error_msg} (max retries exceeded)")
self.active_endpoint_index = original_index
yield ("error", "All API endpoints failed.")
async def _do_stream(self, messages: list, tools: list):
budget_err = self.limiter.check_budget()
if budget_err:
yield ("error", f"⛔ {budget_err}")
return
mult = float(self.get_active_endpoint().get("token_count_multiplier", 1.0))
input_tokens = messages_token_count(messages, mult)
wait_time = await self.limiter.acquire(input_tokens)
if wait_time > 0:
yield ("rate_limit_wait", wait_time)
ep = self.get_active_endpoint()
ep_type = self.get_ep_type(ep)
is_anthropic = ep_type == "anthropic"
base = ep.get("base", "").rstrip("/")
url = f"{base}/messages" if is_anthropic else f"{base}/chat/completions"
payload = self.build_payload(messages, tools, stream=True)
headers = self.get_headers(ep)
pending_tool_calls: dict[int, dict] = {}
timeout_cfg = ep.get("timeout", {})
timeout = httpx.Timeout(timeout_cfg.get("connect", 120), read=timeout_cfg.get("read", 120))
async with httpx.AsyncClient(timeout=timeout, limits=httpx.Limits(max_connections=10)) as client:
async with client.stream("POST", url, json=payload, headers=headers) as resp:
if resp.status_code != 200:
safe_headers, safe_payload = self._sanitize_request_for_log(headers, payload)
try:
body = await resp.aread()
body_text = body.decode(errors="replace")
except Exception:
body_text = "(unable to read response body)"
raise httpx.HTTPStatusError(
f"HTTP {resp.status_code}: {body_text[:500]}",
request=resp.request,
response=resp
)
usage = {}
if is_anthropic:
async for line in resp.aiter_lines():
if not line or not line.startswith("data:"):
continue
raw = line[5:].strip()
if raw == "[DONE]":
break
try:
ev = json.loads(raw)
except json.JSONDecodeError:
continue
t = ev.get("type", "")
if t == "content_block_start":
block = ev.get("content_block", {})
if block.get("type") == "tool_use":
pending_tool_calls[ev["index"]] = {"id": block["id"], "name": block["name"], "input_json": ""}
elif t == "content_block_delta":
delta = ev.get("delta", {}); dt = delta.get("type", ""); idx = ev.get("index", 0)
if dt == "text_delta":
yield ("text", delta.get("text", ""))
elif dt == "thinking_delta":
yield ("thinking", delta.get("thinking", ""))
elif dt == "input_json_delta" and idx in pending_tool_calls: