tiny-cli-agent 0.1.0__py3-none-any.whl

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.
tiny_agent/cli.py ADDED
@@ -0,0 +1,2343 @@
1
+ """
2
+ tiny-agent:一个小型终端编程 Agent(DeepSeek / OpenAI 兼容接口)。
3
+
4
+ 让模型在循环里自己决定调用哪个工具(读写文件、搜索、执行命令、子 Agent),
5
+ 执行后把结果喂回模型,直到任务完成。围绕这个循环做了权限确认、目录沙箱、
6
+ 上下文压缩、会话保存、记忆文件、计划模式、三种界面(纯文本 / 终端 / 全屏)等工程。
7
+
8
+ 用法见 README.md;开发约定和代码地图见 AGENT.md。
9
+ 本文件按注释分区组织(搜索 "# ---------- " 可以看到所有分区)。
10
+ """
11
+ import argparse
12
+ import asyncio
13
+ import concurrent.futures
14
+ import contextlib
15
+ import difflib
16
+ import glob as globlib
17
+ import itertools
18
+ import json
19
+ import os
20
+ import re
21
+ import random
22
+ import subprocess
23
+ import sys
24
+ import threading
25
+ import time
26
+ from datetime import datetime
27
+ from io import StringIO
28
+
29
+ from openai import APIConnectionError, APIStatusError, OpenAI, RateLimitError
30
+
31
+ from . import __version__
32
+
33
+ try:
34
+ from rich.console import Console, Group
35
+ from rich.live import Live
36
+ from rich.markdown import Markdown
37
+ from rich.panel import Panel
38
+ from rich.syntax import Syntax
39
+ from rich.table import Table
40
+ from rich import box
41
+ from rich.spinner import Spinner
42
+ from rich.text import Text
43
+
44
+ RICH_OK = True
45
+ except ImportError: # 没装 rich 也能运行,只是用纯文本界面
46
+ RICH_OK = False
47
+
48
+ try:
49
+ import readline # noqa: F401 让 input() 支持方向键和历史记录(Windows 没有这个模块)
50
+
51
+ HAVE_READLINE = True
52
+ except ImportError:
53
+ HAVE_READLINE = False
54
+
55
+ try:
56
+ from prompt_toolkit import PromptSession
57
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
58
+ from prompt_toolkit.completion import Completer, Completion
59
+ from prompt_toolkit.history import FileHistory, InMemoryHistory
60
+ from prompt_toolkit.key_binding import KeyBindings
61
+ from prompt_toolkit.styles import Style
62
+
63
+ PT_OK = True
64
+ except ImportError: # 没装 prompt_toolkit 就用普通的 input()
65
+ PT_OK = False
66
+
67
+ try:
68
+ from textual.app import App, ComposeResult
69
+ from textual.binding import Binding
70
+ from textual.containers import Horizontal, Vertical, VerticalScroll
71
+ from textual.message import Message
72
+ from textual.screen import ModalScreen
73
+ from textual.widgets import Button, Footer, Header, Input, Label, Static, TextArea
74
+
75
+ TEXTUAL_OK = True
76
+ except ImportError: # 没装 textual 只是不能用 --tui
77
+ TEXTUAL_OK = False
78
+
79
+ HOME_DIR = os.path.join(os.path.expanduser("~"), ".tiny-agent") # 用户级目录:配置、用户级记忆
80
+ CONFIG_PATH = os.path.join(HOME_DIR, "config.json")
81
+ DEFAULT_BASE_URL = "https://api.deepseek.com"
82
+ DEFAULT_MODEL = "deepseek-flash"
83
+ client = None # API 客户端:由 init_client() 在 main() 里创建,这样 --help / --version 不需要 key
84
+ MODEL = os.environ.get("TINY_AGENT_MODEL") or os.environ.get("DEEPSEEK_MODEL") or DEFAULT_MODEL
85
+ COMPACT_TOKENS = int(os.environ.get("TINY_AGENT_COMPACT_TOKENS") or os.environ.get("COMPACT_TOKENS") or 50000)
86
+ KEEP_LAST = 6
87
+ MAX_STEPS = 30
88
+ SUB_MAX_STEPS = 15
89
+ NO_THINK = {"thinking": {"type": "disabled"}}
90
+ MAX_RETRIES = 5
91
+ CANCEL = threading.Event() # 全屏界面里,核心跑在后台线程,没法靠 KeyboardInterrupt 中断,改用取消标志
92
+
93
+
94
+ class Interrupted(Exception):
95
+ """用户中断了当前任务(由取消标志触发)。"""
96
+ AUTO_YES = os.environ.get("TINY_AGENT_YES") == "1" # 也可由 --yes 打开
97
+
98
+ ROOT = os.path.realpath(os.getcwd())
99
+
100
+ SYSTEM = f"""你是一个编程助手,工作目录是 {ROOT}。
101
+ 原则:
102
+ - 先用 glob / grep 定位,再用 read_file 读取相关文件,不要盲目读大量文件。
103
+ - 大文件不要整个读:先 grep 找位置(例如 grep '^(def|class) ' 看结构),再用 offset / limit 读取需要的行范围;
104
+ read_file 输出末尾会提示还剩多少行。同一个文件、同一个范围不要重复读取。
105
+ - 修改已有文件优先用 edit_file(精确替换),只有新建文件才用 write_file。
106
+ - 改完代码后,用 run_bash 运行测试或脚本来验证,根据报错继续修正。
107
+ - 如果需要"弄清某个模块怎么工作""找出某个用法的所有位置"这类需要读很多文件的调研,
108
+ 用 task 工具交给子 Agent,它只会返回结论,能避免你的上下文被大量文件内容占满。
109
+ 多个互不依赖的调研,请在同一轮里同时发起多个 task,它们会并行执行。
110
+ - 任务需要 3 步以上时,先用 todo_write 列出清单,之后每完成一项就更新状态;
111
+ 同一时间只能有一项 in_progress。简单任务不需要清单。
112
+ - 用户要求你"记住"某个约定时,用 edit_file / write_file 把它追加到工作目录的 AGENT.md。
113
+ - 完成后简要汇报做了什么。"""
114
+
115
+ SUB_SYSTEM = f"""你是一个调研子 Agent,工作目录是 {ROOT}。你只有只读工具(glob / grep / read_file)。
116
+ 你看不到之前的对话,只根据收到的任务描述工作。
117
+ 读大文件请先 grep 定位,再用 offset / limit 分段读取,不要重复读同一段。
118
+ 完成调研后,直接给出精炼的结论:关键文件路径和行号、核心逻辑的要点,
119
+ 不要粘贴大段原文,控制在 300 字以内。"""
120
+
121
+
122
+ # ---------- 0. 终端界面(rich + prompt_toolkit;不可用或非终端时退回纯文本) ----------
123
+ SLASH_COMMANDS = {
124
+ "/plan": "切换计划模式(只读调研,批准后才执行)",
125
+ "/sessions": "列出最近的会话",
126
+ "/usage": "查看用量",
127
+ "/compact": "手动压缩上下文",
128
+ "/memory": "查看已加载的记忆",
129
+ "/todo": "查看任务清单",
130
+ "/expand": "展开上一次工具输出的完整内容",
131
+ "/help": "显示命令和快捷键",
132
+ }
133
+ KEY_HINTS = [
134
+ ("Shift+Tab", "切换计划模式"),
135
+ ("Alt+Enter / 行尾 \\ + 回车", "换行(也可直接粘贴多行)"),
136
+ ("@路径", "引用文件,Tab 补全"),
137
+ ("/", "弹出命令补全"),
138
+ ("Ctrl+C", "中断当前任务;在提示符处连按两次退出"),
139
+ ("Ctrl+D", "退出"),
140
+ ]
141
+
142
+
143
+ def context_meter(width=8):
144
+ """上下文用量条:最近一次请求的 prompt_tokens 占压缩阈值的比例。"""
145
+ used = STATE["tokens"]
146
+ if not used:
147
+ return "▯" * width, None
148
+ pct = min(100, int(100 * used / max(1, COMPACT_TOKENS)))
149
+ filled = round(width * pct / 100)
150
+ return "▮" * filled + "▯" * (width - filled), pct
151
+
152
+
153
+ def git_info():
154
+ """返回形如 main(3 处未提交改动)的字符串;不是 git 仓库或出错返回空串。"""
155
+ try:
156
+ r = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=ROOT,
157
+ capture_output=True, text=True, timeout=2)
158
+ if r.returncode != 0:
159
+ return ""
160
+ s = subprocess.run(["git", "status", "--porcelain"], cwd=ROOT,
161
+ capture_output=True, text=True, timeout=2)
162
+ n = len([x for x in s.stdout.splitlines() if x.strip()])
163
+ return r.stdout.strip() + (f"({n} 处未提交改动)" if n else "(干净)")
164
+ except Exception:
165
+ return ""
166
+
167
+
168
+ def summarize_args(name, a):
169
+ """把工具参数压缩成一行摘要,例如 grep(add in src)。"""
170
+ if name == "todo_write":
171
+ todos = a.get("todos")
172
+ return f"{len(todos) if isinstance(todos, list) else 0} 项"
173
+ if name == "exit_plan_mode":
174
+ return "提交计划"
175
+ key = {"read_file": "path", "write_file": "path", "edit_file": "path", "glob": "pattern",
176
+ "grep": "pattern", "run_bash": "command", "task": "prompt"}.get(name)
177
+ if key and key in a:
178
+ s = str(a[key]).replace("\n", " ")
179
+ s = s[:80] + ("…" if len(s) > 80 else "")
180
+ if name == "grep" and a.get("path"):
181
+ s += f" in {a['path']}"
182
+ if name == "read_file" and a.get("offset"):
183
+ s += f" (第 {a['offset']} 行起)"
184
+ return s
185
+ return json.dumps(a, ensure_ascii=False)[:80]
186
+
187
+
188
+ def complete_paths(prefix, limit=40):
189
+ """@ 后面的路径补全:只列工作目录内的,跳过 .git 等目录,目录排在前面。"""
190
+ d, base = os.path.split(prefix)
191
+ try:
192
+ folder = safe_path(d or ".")
193
+ names = os.listdir(folder)
194
+ except (ValueError, OSError):
195
+ return []
196
+ out = []
197
+ for name in names:
198
+ if name in SKIP_DIRS or (name.startswith(".") and not base.startswith(".")):
199
+ continue
200
+ if name.startswith(base):
201
+ rel = os.path.join(d, name) if d else name
202
+ out.append(rel + ("/" if os.path.isdir(os.path.join(folder, name)) else ""))
203
+ out.sort(key=lambda p: (not p.endswith("/"), p))
204
+ return out[:limit]
205
+
206
+
207
+ if PT_OK:
208
+
209
+ class InputCompleter(Completer):
210
+ def get_completions(self, document, complete_event):
211
+ text = document.text_before_cursor
212
+ if text.startswith("/") and " " not in text and "\n" not in text:
213
+ for cmd, desc in SLASH_COMMANDS.items():
214
+ if cmd.startswith(text):
215
+ yield Completion(cmd, start_position=-len(text), display_meta=desc)
216
+ return
217
+ word = document.get_word_before_cursor(WORD=True)
218
+ if word.startswith("@"):
219
+ for path in complete_paths(word[1:]):
220
+ yield Completion("@" + path, start_position=-len(word))
221
+
222
+ PT_STYLE = Style.from_dict({
223
+ "prompt": "ansigreen bold",
224
+ "prompt.plan": "ansicyan bold",
225
+ "bottom-toolbar": "noreverse bg:ansibrightblack ansiwhite",
226
+ "tb.normal": "noreverse bg:ansigreen ansiblack bold",
227
+ "tb.plan": "noreverse bg:ansicyan ansiblack bold",
228
+ "tb.dim": "noreverse bg:ansibrightblack ansigray",
229
+ })
230
+
231
+ def toolbar():
232
+ bar, pct = context_meter()
233
+ plan = STATE["mode"] == "plan"
234
+ ctx = f" 上下文 {bar} {pct}% " if pct is not None else f" 上下文 {bar} "
235
+ return [
236
+ ("class:tb.plan" if plan else "class:tb.normal", " 计划模式 " if plan else " 执行模式 "),
237
+ ("", f" {MODEL} "),
238
+ ("", ctx),
239
+ ("class:tb.dim", " Shift+Tab 切换计划 · Alt+Enter 换行 · @ 文件 · / 命令 "),
240
+ ]
241
+
242
+ def build_prompt_session(input=None, output=None):
243
+ kb = KeyBindings()
244
+
245
+ @kb.add("enter")
246
+ def _(event):
247
+ buf = event.current_buffer
248
+ if buf.document.text_before_cursor.endswith("\\"): # 行尾反斜杠 + 回车 = 换行
249
+ buf.delete_before_cursor(1)
250
+ buf.insert_text("\n")
251
+ else:
252
+ buf.validate_and_handle()
253
+
254
+ @kb.add("escape", "enter") # Alt+Enter
255
+ @kb.add("c-j")
256
+ def _(event):
257
+ event.current_buffer.insert_text("\n")
258
+
259
+ @kb.add("s-tab") # Shift+Tab:随时切换计划模式,状态栏和提示符立即刷新
260
+ def _(event):
261
+ STATE["mode"] = "normal" if STATE["mode"] == "plan" else "plan"
262
+ event.app.invalidate()
263
+
264
+ try:
265
+ hist_dir = os.path.join(ROOT, ".tiny-agent")
266
+ os.makedirs(hist_dir, exist_ok=True)
267
+ history = FileHistory(os.path.join(hist_dir, "history"))
268
+ except OSError:
269
+ history = InMemoryHistory()
270
+
271
+ def message():
272
+ if STATE["mode"] == "plan":
273
+ return [("class:prompt.plan", "[plan] ❯ ")]
274
+ return [("class:prompt", "❯ ")]
275
+
276
+ return PromptSession(
277
+ message=message,
278
+ multiline=False,
279
+ key_bindings=kb,
280
+ history=history,
281
+ auto_suggest=AutoSuggestFromHistory(),
282
+ completer=InputCompleter(),
283
+ complete_while_typing=True,
284
+ bottom_toolbar=toolbar,
285
+ prompt_continuation=lambda width, line_number, wrap_count: " · ",
286
+ style=PT_STYLE,
287
+ input=input,
288
+ output=output,
289
+ )
290
+
291
+
292
+ class Streamer:
293
+ """一次流式输出的显示句柄。
294
+
295
+ plain 模式:逐字打印,格式与 v6 相同。
296
+ rich 模式:先显示转圈;收到文字后,已经写完的段落按 Markdown 永久打印到终端历史里,
297
+ 只有"正在写的这一段"放在底部的刷新区(Live)。这样即使回复很长,也不会因为
298
+ 刷新区高过屏幕而错乱,退出后内容仍留在终端里可以上翻和复制。
299
+ """
300
+
301
+ def __init__(self, ui, show):
302
+ self.ui, self.show = ui, show
303
+ self.buf, self.started, self.status, self.live = "", False, None, None
304
+ if show and ui.rich:
305
+ self.status = ui.console.status("[dim]思考中…[/]", spinner="dots")
306
+ self.status.start()
307
+
308
+ def _stop_status(self):
309
+ if self.status:
310
+ self.status.stop()
311
+ self.status = None
312
+
313
+ def activity(self):
314
+ """收到任何内容(包括工具调用碎片)时调用:停止转圈。"""
315
+ self._stop_status()
316
+
317
+ def _commit_complete_blocks(self):
318
+ pos = 0
319
+ while True:
320
+ k = self.buf.find("\n\n", pos)
321
+ if k == -1:
322
+ return
323
+ if self.buf[:k].count("```") % 2 == 0: # 不在代码块中间,才能安全切分
324
+ block, self.buf = self.buf[:k], self.buf[k + 2:].lstrip("\n")
325
+ if block.strip():
326
+ self.ui.console.print(Markdown(block))
327
+ pos = 0
328
+ else:
329
+ pos = k + 2 # 代码块里的空行不切
330
+
331
+ def text(self, delta):
332
+ if not self.show:
333
+ return
334
+ if not self.ui.rich:
335
+ if not self.started:
336
+ print("\n[模型] ", end="")
337
+ self.started = True
338
+ print(delta, end="", flush=True)
339
+ return
340
+ self._stop_status()
341
+ if not self.started:
342
+ self.started = True
343
+ self.ui.console.print()
344
+ self.buf += delta
345
+ self._commit_complete_blocks()
346
+ if self.live is None:
347
+ self.live = Live(console=self.ui.console, refresh_per_second=10, vertical_overflow="visible")
348
+ self.live.start()
349
+ self.live.update(Markdown(self.buf) if self.buf.strip() else Text(""))
350
+
351
+ def close(self):
352
+ self._stop_status()
353
+ if self.ui.rich:
354
+ if self.live:
355
+ self.live.update(Markdown(self.buf) if self.buf.strip() else Text(""))
356
+ self.live.stop()
357
+ self.live = None
358
+ elif self.started:
359
+ print()
360
+
361
+
362
+ class SubBoard:
363
+ """并行子 Agent 的实时进度表(仅 rich 模式)。
364
+
365
+ 子 Agent 在不同线程里同时运行。如果让它们各自往终端打印,输出会交错成一团,
366
+ 所以统一把进度汇总成一张表,由 Live 定时刷新;全部结束后表格定格留在终端里。
367
+ """
368
+
369
+ def __init__(self, ui):
370
+ self.ui, self.rows, self.live, self.active = ui, {}, None, 0
371
+ self.lock = threading.RLock() # 可重入:Live.stop() 会回调 _render,而它也要拿锁
372
+
373
+ def _render(self):
374
+ table = Table(box=box.SIMPLE_HEAD, header_style="bold magenta", expand=False, pad_edge=False)
375
+ table.add_column("子Agent")
376
+ table.add_column("任务", max_width=30, no_wrap=True, overflow="ellipsis")
377
+ table.add_column("状态", max_width=46, no_wrap=True, overflow="ellipsis")
378
+ table.add_column("用时", justify="right")
379
+ with self.lock:
380
+ rows = sorted((n, dict(r)) for n, r in self.rows.items())
381
+ now = time.time()
382
+ for n, r in rows:
383
+ secs = (r["t1"] or now) - r["t0"]
384
+ if r["done"]:
385
+ status = Text(r["last"], style="green")
386
+ else:
387
+ status = Spinner("dots", text=Text(" " + r["last"], style="dim"), style="magenta")
388
+ table.add_row(Text(f"#{n}", style="magenta"), Text(r["prompt"].replace("\n", " ")), status,
389
+ Text(f"{secs:.0f}s"))
390
+ return table
391
+
392
+ def start(self, n, prompt):
393
+ with self.lock:
394
+ if self.live is None:
395
+ self.rows = {}
396
+ self.live = Live(get_renderable=self._render, console=self.ui.console,
397
+ refresh_per_second=8, transient=False)
398
+ self.live.start()
399
+ self.rows[n] = {"prompt": prompt, "last": "启动中", "t0": time.time(), "t1": None, "done": False}
400
+ self.active += 1
401
+
402
+ def update(self, n, text):
403
+ with self.lock:
404
+ if n in self.rows:
405
+ self.rows[n]["last"] = text
406
+
407
+ def finish(self, n, n_msgs, n_chars):
408
+ with self.lock:
409
+ r = self.rows.get(n)
410
+ if r:
411
+ r.update(done=True, t1=time.time(), last=f"完成:内部 {n_msgs} 条消息 → 返回 {n_chars} 字")
412
+ self.active -= 1
413
+ if self.active <= 0 and self.live:
414
+ self.live.stop()
415
+ self.live = None
416
+ self.active = 0
417
+
418
+
419
+ class UI:
420
+ def __init__(self):
421
+ self.rich = RICH_OK and sys.stdout.isatty() and not os.environ.get("TINY_AGENT_PLAIN")
422
+ self.use_pt = not os.environ.get("TINY_AGENT_SIMPLE_INPUT")
423
+ self.console = Console(highlight=False) if RICH_OK else None
424
+ self.board = SubBoard(self) if RICH_OK else None
425
+ self.last_output = None # 最近一次工具输出,供 /expand 使用
426
+ self._busy_secs = 0.0
427
+ self._pt = None
428
+
429
+ # --- 基础提示 ---
430
+ def notice(self, msg):
431
+ if self.rich:
432
+ self.console.print(Text(msg, style="dim"))
433
+ else:
434
+ print(f"\n{msg}")
435
+
436
+ def warn(self, msg):
437
+ if self.rich:
438
+ self.console.print(Text(msg, style="yellow"))
439
+ else:
440
+ print(f"\n{msg}")
441
+
442
+ def ask(self, prompt):
443
+ if self.rich:
444
+ return self.console.input(Text(prompt + " ", style="bold"))
445
+ return input(prompt + " ")
446
+
447
+ def prompt(self, plan_mode):
448
+ """简易输入(没有 prompt_toolkit 时使用)。"""
449
+ label = "[plan] ❯ " if plan_mode else "❯ "
450
+ if not self.rich:
451
+ return input("\n[plan] > " if plan_mode else "\n> ")
452
+ print()
453
+ color = "36" if plan_mode else "32"
454
+ if HAVE_READLINE: # \001 \002 告诉 readline 这段是不占宽度的颜色码,否则按方向键会错位
455
+ return input(f"\001\033[1;{color}m\002{label}\001\033[0m\002")
456
+ return self.console.input(Text(label, style="bold cyan" if plan_mode else "bold green"))
457
+
458
+ def read_input(self, plan_mode):
459
+ """主输入入口:有 prompt_toolkit 且在终端里就用增强输入,否则退回简易输入。"""
460
+ if self.rich and self.use_pt and PT_OK and sys.stdin.isatty():
461
+ if self._pt is None:
462
+ self._pt = build_prompt_session()
463
+ self.console.print()
464
+ return self._pt.prompt()
465
+ return self.prompt(plan_mode)
466
+
467
+ def bell(self):
468
+ if self.rich:
469
+ sys.stdout.write("\a")
470
+ sys.stdout.flush()
471
+
472
+ @contextlib.contextmanager
473
+ def busy(self, label):
474
+ """长时间操作期间显示转圈,并记录耗时。不要在需要用户输入的操作里使用。"""
475
+ t0 = time.time()
476
+ st = self.console.status(f"[dim]{label}[/]", spinner="dots") if self.rich else None
477
+ if st:
478
+ st.start()
479
+ try:
480
+ yield
481
+ finally:
482
+ if st:
483
+ st.stop()
484
+ self._busy_secs = time.time() - t0
485
+
486
+ # --- 模型输出与工具 ---
487
+ def stream(self, show):
488
+ return Streamer(self, show)
489
+
490
+ def tool_call(self, tag, name, args):
491
+ if not self.rich:
492
+ print(f"\n{tag} {name}({json.dumps(args, ensure_ascii=False)[:150]})")
493
+ return
494
+ summary = summarize_args(name, args)
495
+ if tag.startswith("["): # 主 Agent
496
+ self.console.print(Text.assemble(("● ", "bold cyan"), (name, "bold"), (f"({summary})", "dim")))
497
+ else: # 子 Agent,tag 形如 " │ 子Agent#1":只更新进度表,不单独打印
498
+ m = re.search(r"#(\d+)", tag)
499
+ if m:
500
+ self.board.update(int(m.group(1)), f"{name}({summary})")
501
+
502
+ def tool_result(self, tag, name, out):
503
+ if not self.rich or not tag.startswith("[") or name in ("task", "todo_write"):
504
+ return # 子 Agent 的中间结果不预览,避免刷屏
505
+ self.last_output = (name, out)
506
+ lines = out.strip().splitlines() or ["(无输出)"]
507
+ limit = 1 if name in ("write_file", "edit_file") else 3
508
+ style = "red" if out.startswith(("错误", "工具执行出错")) else "dim"
509
+ suffix = f" ({self._busy_secs:.1f}s)" if self._busy_secs >= 1 else ""
510
+ self._busy_secs = 0.0
511
+ for i, line in enumerate(lines[:limit]):
512
+ self.console.print(Text((" ⎿ " if i == 0 else " ") + line[:110] + (suffix if i == 0 else ""),
513
+ style=style))
514
+ if len(lines) > limit:
515
+ self.console.print(Text(f" … 还有 {len(lines) - limit} 行(/expand 查看全部)", style="dim"))
516
+
517
+ def expand(self):
518
+ if not self.last_output:
519
+ return self.notice("(还没有可展开的工具输出;纯文本模式不显示工具输出)")
520
+ name, out = self.last_output
521
+ lines = out.splitlines()
522
+ shown = "\n".join(lines[:300]) + (f"\n… 还有 {len(lines) - 300} 行未显示" if len(lines) > 300 else "")
523
+ self.console.print(Panel(Text(shown), title=f"上一次工具输出 · {name}", border_style="dim"))
524
+
525
+ # --- 确认与计划 ---
526
+ def confirm_prompt(self, tool_name, detail, body=None, lang="text"):
527
+ if not self.rich:
528
+ extra = "\n" + body if body else ""
529
+ return input(
530
+ f"\n[需要确认] {tool_name}\n{detail}{extra}\n允许?(y=是 / a=本次会话总是允许该工具 / n=拒绝) "
531
+ ).strip().lower()
532
+ parts = [Text(detail)]
533
+ if body:
534
+ if lang.startswith("path:"): # 按文件名猜语法,如 .py 用 Python 高亮
535
+ lang = Syntax.guess_lexer(lang[5:], body)
536
+ parts.append(Syntax(body, lang, theme="ansi_dark", word_wrap=True))
537
+ self.console.print(Panel(Group(*parts), title=f"[bold yellow]需要确认 · {tool_name}[/]",
538
+ border_style="yellow", expand=False))
539
+ return self.ask("允许?(y=是 / a=本会话总是允许 / n=拒绝)").strip().lower()
540
+
541
+ def plan_review(self, plan):
542
+ if not self.rich:
543
+ print("\n" + "=" * 50 + "\n[计划待审批]\n" + plan + "\n" + "=" * 50)
544
+ return
545
+ self.console.print(Panel(Markdown(plan), title="[bold cyan]计划待审批[/]", border_style="cyan"))
546
+
547
+ # --- 清单、子 Agent、用量、列表 ---
548
+ def todos(self, todos):
549
+ if not self.rich:
550
+ print("\n[任务清单]\n" + render_todos())
551
+ return
552
+ body = Text()
553
+ styles = {"completed": ("☑", "green dim"), "in_progress": ("◐", "bold yellow"), "pending": ("☐", "")}
554
+ for i, item in enumerate(todos):
555
+ if i:
556
+ body.append("\n")
557
+ icon, style = styles[item["status"]]
558
+ body.append(f"{icon} {item['content']}", style=style)
559
+ self.console.print(Panel(body, title="任务清单", border_style="dim", expand=False))
560
+
561
+ def sub_start(self, n, prompt):
562
+ if self.rich:
563
+ self.board.start(n, prompt)
564
+ else:
565
+ print(f"\n ┌ 子Agent#{n} 启动:{prompt[:80]}")
566
+
567
+ def sub_end(self, n, n_msgs, n_chars):
568
+ if self.rich:
569
+ self.board.finish(n, n_msgs, n_chars)
570
+ else:
571
+ print(f"\n └ 子Agent#{n} 完成:内部 {n_msgs} 条消息 -> 只返回 {n_chars} 字")
572
+
573
+ def usage(self, u, secs=None, turn=None):
574
+ if self.rich:
575
+ line = f"用量 · {u['requests']} 次请求 · 输入 {u['prompt']} · 输出 {u['completion']} tokens(累计)"
576
+ if turn is not None:
577
+ line = (f"用量 · 本轮 {turn['requests']} 次请求 · 输入 {turn['prompt']} · 输出 {turn['completion']}"
578
+ + (f" · {secs:.1f}s" if secs is not None else "")
579
+ + f" | 累计 {u['requests']} 次请求 · 输入 {u['prompt']} · 输出 {u['completion']}")
580
+ elif secs is not None:
581
+ line += f" · 本轮 {secs:.1f}s"
582
+ self.console.print(Text(line, style="dim"))
583
+ else: # 评测脚本靠这一行的格式解析用量,不要改
584
+ print(f"\n[用量] 累计 {u['requests']} 次请求,输入 {u['prompt']},输出 {u['completion']} tokens")
585
+
586
+ def banner(self, root, model, memory_files, session_id, mode, git=""):
587
+ mem = ", ".join(memory_files) if memory_files else "无(可输入 # 内容 创建 AGENT.md)"
588
+ if not self.rich:
589
+ print(f"交互模式(工作目录 {root})")
590
+ print(f"已加载记忆文件:{mem}")
591
+ print("命令:/plan /sessions /usage /compact /memory /todo # 记忆内容 exit")
592
+ if mode == "plan":
593
+ print("当前为【计划模式】:只读调研,提交计划并经你批准后才会执行。")
594
+ return
595
+ body = Text()
596
+ rows = [("工作目录", root), ("模型", model)]
597
+ if git:
598
+ rows.append(("git", git))
599
+ rows += [("记忆文件", mem), ("会话", session_id)]
600
+ for label, value in rows:
601
+ body.append(f"{label:<6}", style="dim")
602
+ body.append(f"{value}\n")
603
+ if PT_OK and self.use_pt:
604
+ body.append("\nShift+Tab 切换计划模式 · Alt+Enter 换行 · @ 引用文件 · / 命令 · /help 帮助", style="dim")
605
+ else:
606
+ body.append("\n/help 查看命令(安装 prompt_toolkit 可启用补全、状态栏和多行输入)", style="dim")
607
+ self.console.print(Panel(body, title="[bold]tiny-agent[/]", border_style="blue"))
608
+ if mode == "plan":
609
+ self.console.print(Text("计划模式:只读调研,提交计划并经你批准后才会执行。", style="cyan"))
610
+
611
+ def help(self):
612
+ if not self.rich:
613
+ for cmd, desc in SLASH_COMMANDS.items():
614
+ print(f"{cmd:<10}{desc}")
615
+ print("# 内容 追加一条记忆到 AGENT.md")
616
+ return
617
+ table = Table(box=None, show_header=False, pad_edge=False)
618
+ table.add_column(style="bold")
619
+ table.add_column()
620
+ for cmd, desc in SLASH_COMMANDS.items():
621
+ table.add_row(Text(cmd), Text(desc))
622
+ table.add_row(Text("# 内容"), Text("追加一条记忆到 AGENT.md,立即生效"))
623
+ table.add_row(Text(""), Text(""))
624
+ for key, desc in KEY_HINTS:
625
+ table.add_row(Text(key, style="cyan"), Text(desc))
626
+ self.console.print(Panel(table, title="帮助", border_style="dim", expand=False))
627
+
628
+ def sessions(self, items):
629
+ if not items:
630
+ return self.notice("(没有会话)")
631
+ if not self.rich:
632
+ for s in items:
633
+ print(f"{s['id']} {s['saved_at']} {len(s['messages'])}条 {s['title']}")
634
+ return
635
+ table = Table(box=None, header_style="bold")
636
+ for col, right in (("ID", False), ("时间", False), ("消息", True), ("标题", False)):
637
+ table.add_column(col, justify="right" if right else "left")
638
+ for s in items:
639
+ table.add_row(Text(s["id"]), Text(s["saved_at"]), Text(str(len(s["messages"]))), Text(s["title"]))
640
+ self.console.print(table)
641
+
642
+ def memory(self, text):
643
+ if not text:
644
+ return self.notice("(没有记忆文件)")
645
+ if self.rich:
646
+ self.console.print(Panel(Markdown(text), title="记忆", border_style="dim"))
647
+ else:
648
+ print(text)
649
+
650
+
651
+ ui = UI()
652
+
653
+
654
+ # ---------- 1. 工具定义 ----------
655
+ S = {"type": "string"}
656
+
657
+
658
+ def tool(name, desc, props, required):
659
+ return {
660
+ "type": "function",
661
+ "function": {
662
+ "name": name,
663
+ "description": desc,
664
+ "parameters": {"type": "object", "properties": props, "required": required},
665
+ },
666
+ }
667
+
668
+
669
+ BASE_TOOLS = [
670
+ tool(
671
+ "read_file",
672
+ "读取文本文件。每行前面有行号和制表符,它们不是文件内容,使用 edit_file 时不要把行号带进 old_string。"
673
+ "默认从第 1 行读起,最多 500 行。大文件请用 offset / limit 分段读取;"
674
+ "输出末尾会告诉你还剩多少行以及下一次该用的 offset。不要整文件反复读取,"
675
+ "先用 grep 找到相关位置(例如 grep 模式 ^(def|class) 可以看出文件结构)。",
676
+ {
677
+ "path": S,
678
+ "offset": {"type": "integer", "description": "起始行号,从 1 开始,默认 1"},
679
+ "limit": {"type": "integer", "description": "最多读取的行数,默认 500"},
680
+ },
681
+ ["path"],
682
+ ),
683
+ tool("write_file", "新建文件或整体覆盖文件", {"path": S, "content": S}, ["path", "content"]),
684
+ tool(
685
+ "edit_file",
686
+ "把文件中的 old_string 精确替换为 new_string。old_string 必须在文件中唯一出现,"
687
+ "如果不唯一请带上更多上下文。",
688
+ {"path": S, "old_string": S, "new_string": S},
689
+ ["path", "old_string", "new_string"],
690
+ ),
691
+ tool("glob", "按文件名模式查找文件,例如 **/*.py", {"pattern": S}, ["pattern"]),
692
+ tool(
693
+ "grep",
694
+ "在文件内容中用正则搜索,返回 文件:行号:内容。path 可以是目录,也可以是单个文件(大文件先用它定位行号)。",
695
+ {"pattern": S, "path": S},
696
+ ["pattern"],
697
+ ),
698
+ tool("run_bash", "执行一条 shell 命令并返回输出", {"command": S}, ["command"]),
699
+ ]
700
+ TASK_TOOL = tool(
701
+ "task",
702
+ "把一个独立的只读调研任务交给子 Agent。子 Agent 在全新的上下文里工作,只返回结论。"
703
+ "适合:弄清某模块如何工作、查找某用法的所有位置。"
704
+ "子 Agent 看不到当前对话,所以 prompt 必须自包含、写清楚要查什么、要返回什么。",
705
+ {"prompt": S},
706
+ ["prompt"],
707
+ )
708
+ TODO_TOOL = tool(
709
+ "todo_write",
710
+ "创建或更新任务清单。每次调用都要传入完整清单(会整体替换旧清单)。"
711
+ "status 取值:pending / in_progress / completed。同一时间最多一项 in_progress。",
712
+ {
713
+ "todos": {
714
+ "type": "array",
715
+ "items": {
716
+ "type": "object",
717
+ "properties": {
718
+ "content": S,
719
+ "status": {"type": "string", "enum": ["pending", "in_progress", "completed"]},
720
+ },
721
+ "required": ["content", "status"],
722
+ },
723
+ }
724
+ },
725
+ ["todos"],
726
+ )
727
+ TOOLS = BASE_TOOLS + [TASK_TOOL, TODO_TOOL] # 主 Agent:全部工具
728
+
729
+ READ_ONLY = {"read_file", "glob", "grep"} # 子 Agent:只读,且不能再派生子 Agent
730
+ READ_ONLY_TOOLS = [t for t in BASE_TOOLS if t["function"]["name"] in READ_ONLY]
731
+ ALL_NAMES = {t["function"]["name"] for t in TOOLS}
732
+
733
+ # 计划模式:只读工具 + 子 Agent + 提交计划。没有 write_file / edit_file / run_bash。
734
+ EXIT_PLAN_TOOL = tool(
735
+ "exit_plan_mode",
736
+ "调研完成后调用,提交你的实施计划供用户审批。plan 用 Markdown 书写,写清:要改哪些文件、"
737
+ "每处怎么改、如何验证、有哪些风险。用户批准后才会切换到执行模式。",
738
+ {"plan": S},
739
+ ["plan"],
740
+ )
741
+ PLAN_TOOLS = READ_ONLY_TOOLS + [TASK_TOOL, EXIT_PLAN_TOOL]
742
+ PLAN_ALLOWED = READ_ONLY | {"task", "exit_plan_mode"}
743
+
744
+
745
+ # ---------- 2. 权限与沙箱 ----------
746
+ ALWAYS_ALLOW = set()
747
+
748
+
749
+ def confirm(tool_name: str, detail: str, body: str = None, lang: str = "text") -> bool:
750
+ if AUTO_YES:
751
+ ui.notice(f"[自动批准] {tool_name}: {detail[:100]}")
752
+ return True
753
+ if tool_name in ALWAYS_ALLOW:
754
+ return True
755
+ ans = ui.confirm_prompt(tool_name, detail, body, lang)
756
+ if ans == "a":
757
+ ALWAYS_ALLOW.add(tool_name)
758
+ return True
759
+ return ans == "y"
760
+
761
+
762
+ def safe_path(p: str) -> str:
763
+ full = os.path.realpath(os.path.join(ROOT, p))
764
+ if full != ROOT and not full.startswith(ROOT + os.sep):
765
+ raise ValueError(f"路径 {p} 超出工作目录,已拒绝")
766
+ return full
767
+
768
+
769
+ # ---------- 3. 工具实现 ----------
770
+ SKIP_DIRS = {".git", "node_modules", "venv", ".venv", "__pycache__", ".tiny-agent"}
771
+
772
+
773
+ READ_LINES = 500 # 单次最多读取的行数
774
+ READ_CHARS = 20000 # 单次最多返回的字符数
775
+ MAX_LINE_CHARS = 2000
776
+
777
+
778
+ def do_read(a):
779
+ path = safe_path(a["path"])
780
+ offset = max(1, int(a.get("offset") or 1))
781
+ limit = max(1, int(a.get("limit") or READ_LINES))
782
+ with open(path, encoding="utf-8") as f:
783
+ lines = f.read().splitlines()
784
+ total = len(lines)
785
+ if total == 0:
786
+ return "(空文件)"
787
+ if offset > total:
788
+ return f"错误:offset={offset} 超出文件范围,该文件共 {total} 行。"
789
+ rows, used, last = [], 0, offset - 1
790
+ for i in range(offset - 1, min(total, offset - 1 + limit)):
791
+ text = lines[i]
792
+ if len(text) > MAX_LINE_CHARS:
793
+ text = text[:MAX_LINE_CHARS] + "…(本行过长,已截断)"
794
+ row = f"{i + 1:>6}\t{text}"
795
+ if rows and used + len(row) + 1 > READ_CHARS:
796
+ break # 字符数到上限了,停在这里,并告诉模型从哪里继续
797
+ rows.append(row)
798
+ used += len(row) + 1
799
+ last = i + 1
800
+ body = "\n".join(rows)
801
+ if last < total:
802
+ body += f"\n[已显示第 {offset}-{last} 行,共 {total} 行;还有 {total - last} 行未显示,用 offset={last + 1} 继续读取]"
803
+ elif offset > 1:
804
+ body += f"\n[已显示第 {offset}-{last} 行,共 {total} 行,已到文件末尾]"
805
+ return body
806
+
807
+
808
+ def do_write(a):
809
+ path = safe_path(a["path"])
810
+ content = a["content"]
811
+ old = None
812
+ if os.path.isfile(path):
813
+ try:
814
+ with open(path, encoding="utf-8") as f:
815
+ old = f.read()
816
+ except (UnicodeDecodeError, OSError):
817
+ old = None
818
+ if old is not None: # 覆盖已有文件:给用户看 diff
819
+ body = "".join(difflib.unified_diff(
820
+ old.splitlines(True), content.splitlines(True), "修改前", "修改后", n=2))[:3000]
821
+ body = body or "(内容没有变化)"
822
+ detail, lang = f"覆盖 {a['path']}", "diff"
823
+ else: # 新建文件:给用户看内容预览(按文件类型高亮)
824
+ lines = content.splitlines()
825
+ body = "\n".join(lines[:40]) + (f"\n… 还有 {len(lines) - 40} 行" if len(lines) > 40 else "")
826
+ detail, lang = f"新建 {a['path']}({len(content)} 字符)", f"path:{a['path']}"
827
+ if not confirm("write_file", detail, body, lang):
828
+ return "用户拒绝了该操作"
829
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
830
+ with open(path, "w", encoding="utf-8") as f:
831
+ f.write(content)
832
+ return f"已写入 {a['path']}"
833
+
834
+
835
+ def do_edit(a):
836
+ path = safe_path(a["path"])
837
+ with open(path, encoding="utf-8") as f:
838
+ text = f.read()
839
+ old, new = a["old_string"], a["new_string"]
840
+ n = text.count(old)
841
+ if n == 0:
842
+ return "错误:old_string 在文件中不存在。请先 read_file 确认原文(注意空格和缩进)。"
843
+ if n > 1:
844
+ return f"错误:old_string 出现了 {n} 次,不唯一。请带上更多上下文使其唯一。"
845
+ updated = text.replace(old, new, 1)
846
+ diff = "".join(
847
+ difflib.unified_diff(
848
+ text.splitlines(True), updated.splitlines(True), "修改前", "修改后", n=2
849
+ )
850
+ )
851
+ if not confirm("edit_file", f"修改 {a['path']}", diff[:3000], "diff"):
852
+ return "用户拒绝了该操作"
853
+ with open(path, "w", encoding="utf-8") as f:
854
+ f.write(updated)
855
+ return f"已修改 {a['path']}"
856
+
857
+
858
+ def do_glob(a):
859
+ base = safe_path(".")
860
+ hits = globlib.glob(os.path.join(base, a["pattern"]), recursive=True)
861
+ rel = [os.path.relpath(h, base) for h in hits if not set(h.split(os.sep)) & SKIP_DIRS]
862
+ return "\n".join(sorted(rel)[:200]) or "(没有匹配的文件)"
863
+
864
+
865
+ def do_grep(a):
866
+ regex = re.compile(a["pattern"])
867
+ start = safe_path(a.get("path") or ".")
868
+ if os.path.isfile(start): # path 可以是单个文件(os.walk 对文件路径什么都不会返回,要单独处理)
869
+ walker = [(os.path.dirname(start), [], [os.path.basename(start)])]
870
+ else:
871
+ walker = os.walk(start)
872
+ out = []
873
+ for dirpath, dirs, files in walker:
874
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
875
+ for name in files:
876
+ fp = os.path.join(dirpath, name)
877
+ try:
878
+ with open(fp, encoding="utf-8") as f:
879
+ for i, line in enumerate(f, 1):
880
+ if regex.search(line):
881
+ out.append(f"{os.path.relpath(fp, ROOT)}:{i}: {line.strip()[:200]}")
882
+ if len(out) >= 100:
883
+ return "\n".join(out) + "\n(结果已截断到 100 条)"
884
+ except (UnicodeDecodeError, OSError):
885
+ continue
886
+ return "\n".join(out) or "(没有匹配)"
887
+
888
+
889
+ def do_bash(a):
890
+ if not confirm("run_bash", "执行命令", a["command"], "bash"):
891
+ return "用户拒绝了该命令"
892
+ with ui.busy("执行命令中…"): # 确认之后才开始转圈,避免和输入提示冲突
893
+ r = subprocess.run(
894
+ a["command"], shell=True, capture_output=True, text=True, timeout=60, cwd=ROOT,
895
+ stdin=subprocess.DEVNULL, # 不继承终端输入:交互式命令会直接得到 EOF,而不是抢走你的键盘
896
+ )
897
+ out = r.stdout + r.stderr
898
+ if len(out) > 20000: # 截断时必须告诉模型,否则它会以为自己看到了全部
899
+ out = out[:20000] + f"\n[输出过长,已截断,共 {len(out)} 字符;可用 grep / head / tail 缩小范围]"
900
+ return out or "(无输出)"
901
+
902
+
903
+ # ---------- 3.5 记忆文件 与 TODO 清单 ----------
904
+ USER_MEMORY = os.path.expanduser("~/.tiny-agent/AGENT.md")
905
+ PROJECT_MEMORY = os.path.join(ROOT, "AGENT.md")
906
+
907
+
908
+ def load_memory():
909
+ """读取记忆文件,返回 (拼好的文本, 实际读到的文件列表)。"""
910
+ parts, found = [], []
911
+ for label, path in (("用户级记忆", USER_MEMORY), ("项目记忆", PROJECT_MEMORY)):
912
+ if os.path.isfile(path):
913
+ with open(path, encoding="utf-8") as f:
914
+ txt = f.read().strip()[:8000] # 限长,避免记忆文件本身撑爆上下文
915
+ if txt:
916
+ parts.append(f"## {label}({path})\n{txt}")
917
+ found.append(path)
918
+ return "\n\n".join(parts), found
919
+
920
+
921
+ def build_system(base: str) -> str:
922
+ memory, _ = load_memory()
923
+ if not memory:
924
+ return base
925
+ return f"{base}\n\n以下是用户提供的持久指令(项目约定、常用命令、代码风格等),请遵守:\n<memory>\n{memory}\n</memory>"
926
+
927
+
928
+ def add_memory(note: str) -> None:
929
+ prefix = ""
930
+ if os.path.isfile(PROJECT_MEMORY):
931
+ with open(PROJECT_MEMORY, encoding="utf-8") as f:
932
+ if not f.read().endswith("\n"):
933
+ prefix = "\n"
934
+ with open(PROJECT_MEMORY, "a", encoding="utf-8") as f:
935
+ f.write(f"{prefix}- {note}\n")
936
+
937
+
938
+ TODOS = []
939
+ TODO_ICON = {"pending": "☐", "in_progress": "◐", "completed": "☑"}
940
+
941
+
942
+ def render_todos() -> str:
943
+ return "\n".join(f"{TODO_ICON[t['status']]} {t['content']}" for t in TODOS)
944
+
945
+
946
+ def do_todo(a):
947
+ todos = a.get("todos")
948
+ if not isinstance(todos, list):
949
+ return "错误:todos 必须是数组"
950
+ new = []
951
+ for t in todos:
952
+ if not isinstance(t, dict) or not t.get("content") or t.get("status") not in TODO_ICON:
953
+ return "错误:每一项都需要 content,且 status 只能是 pending / in_progress / completed"
954
+ new.append({"content": str(t["content"]), "status": t["status"]})
955
+ if sum(t["status"] == "in_progress" for t in new) > 1:
956
+ return "错误:同一时间最多只能有一项 in_progress"
957
+ TODOS[:] = new
958
+ ui.todos(TODOS)
959
+ return "任务清单已更新:\n" + render_todos()
960
+
961
+
962
+ # ---------- 3.6 计划模式 ----------
963
+ PLAN_NOTE = """
964
+
965
+ 【当前处于计划模式】你只能使用只读工具(read_file / glob / grep / task)做调研,
966
+ 不能修改任何文件,也不能执行命令。调研清楚后,调用 exit_plan_mode 提交实施计划
967
+ (Markdown:要改哪些文件、每处怎么改、如何验证、有哪些风险)。
968
+ 用户批准后才会切换到执行模式。不要在计划模式里直接开始改代码。"""
969
+
970
+
971
+ def system_prompt() -> str:
972
+ """主 Agent 的 system prompt:基础指令 + 记忆文件 + (计划模式时的)模式说明。"""
973
+ return build_system(SYSTEM) + (PLAN_NOTE if STATE["mode"] == "plan" else "")
974
+
975
+
976
+ def current_tools():
977
+ """按当前模式返回 (工具定义, 允许的工具名)。每轮循环都会重新取,所以模式切换立即生效。"""
978
+ if STATE["mode"] == "plan":
979
+ return PLAN_TOOLS, PLAN_ALLOWED
980
+ return TOOLS, ALL_NAMES
981
+
982
+
983
+ def do_exit_plan(a):
984
+ plan = (a.get("plan") or "").strip()
985
+ if not plan:
986
+ return "错误:plan 不能为空"
987
+ ui.plan_review(plan)
988
+ ans = "y" if AUTO_YES else ui.ask("批准该计划并开始执行?(y=批准 / n=不批准,继续修改)").strip().lower()
989
+ if ans == "y":
990
+ STATE["mode"] = "normal" # 下一轮循环起,current_tools() 会开放全部工具
991
+ ui.notice("[已切换到执行模式]")
992
+ return (
993
+ "计划已获用户批准,已切换到执行模式,所有工具现已可用。"
994
+ "请先用 todo_write 把计划拆成任务清单,然后按计划执行并验证。"
995
+ )
996
+ feedback = ui.ask("修改意见(可直接回车):").strip()
997
+ return "用户未批准该计划,仍处于计划模式。" + (
998
+ f"修改意见:{feedback}" if feedback else "请根据情况修订后重新提交。"
999
+ )
1000
+
1001
+
1002
+ # ---------- 3.7 API 重试 / 用量统计 / 会话保存 ----------
1003
+ def is_retryable(e: Exception) -> bool:
1004
+ """429、网络错误、5xx 值得重试;401(key 错)、400(请求有误)重试也没用。"""
1005
+ if isinstance(e, (RateLimitError, APIConnectionError)): # 超时是 APIConnectionError 的子类
1006
+ return True
1007
+ return isinstance(e, APIStatusError) and getattr(e, "status_code", 0) >= 500
1008
+
1009
+
1010
+ def with_retry(fn, what="模型请求"):
1011
+ for attempt in range(MAX_RETRIES + 1):
1012
+ try:
1013
+ return fn()
1014
+ except Exception as e: # KeyboardInterrupt 不会被捕获,Ctrl+C 仍然能中断
1015
+ if not is_retryable(e) or attempt == MAX_RETRIES:
1016
+ raise
1017
+ delay = min(30, 2**attempt) + random.random() # 1s, 2s, 4s... 加随机抖动
1018
+ ui.warn(f"[{what}失败:{type(e).__name__},{delay:.0f} 秒后重试 ({attempt + 1}/{MAX_RETRIES})]")
1019
+ time.sleep(delay)
1020
+
1021
+
1022
+ def chat_create(**kwargs):
1023
+ return with_retry(lambda: client.chat.completions.create(**kwargs), "请求")
1024
+
1025
+
1026
+ USAGE = {"requests": 0, "prompt": 0, "completion": 0}
1027
+ _usage_lock = threading.Lock() # 子 Agent 并行时会同时累加
1028
+
1029
+
1030
+ def print_usage(secs=None, since=None):
1031
+ """since 是本轮开始时 USAGE 的快照;传入后会同时显示"本轮"和"累计"。"""
1032
+ turn = {k: USAGE[k] - since[k] for k in USAGE} if since else None
1033
+ ui.usage(USAGE, secs, turn)
1034
+
1035
+
1036
+ SESSION_DIR = os.path.join(ROOT, ".tiny-agent", "sessions")
1037
+ SESSION = {"id": datetime.now().strftime("%Y%m%d-%H%M%S")}
1038
+
1039
+
1040
+ def save_session(messages) -> None:
1041
+ os.makedirs(SESSION_DIR, exist_ok=True)
1042
+ if "title" not in SESSION:
1043
+ first = next((m["content"] for m in messages if m["role"] == "user"), "")
1044
+ SESSION["title"] = first[:60]
1045
+ data = {
1046
+ "id": SESSION["id"],
1047
+ "title": SESSION["title"],
1048
+ "saved_at": datetime.now().isoformat(timespec="seconds"),
1049
+ "mode": STATE["mode"],
1050
+ "todos": TODOS,
1051
+ "messages": messages,
1052
+ }
1053
+ path = os.path.join(SESSION_DIR, SESSION["id"] + ".json")
1054
+ with open(path + ".tmp", "w", encoding="utf-8") as f:
1055
+ json.dump(data, f, ensure_ascii=False)
1056
+ os.replace(path + ".tmp", path) # 原子替换:写到一半崩溃也不会损坏旧存档
1057
+
1058
+
1059
+ def list_sessions():
1060
+ found = []
1061
+ if os.path.isdir(SESSION_DIR):
1062
+ for name in os.listdir(SESSION_DIR):
1063
+ if name.endswith(".json"):
1064
+ path = os.path.join(SESSION_DIR, name)
1065
+ try:
1066
+ with open(path, encoding="utf-8") as f:
1067
+ found.append((os.path.getmtime(path), json.load(f)))
1068
+ except (OSError, ValueError):
1069
+ continue # 损坏的存档跳过
1070
+ return [d for _, d in sorted(found, key=lambda x: x[0], reverse=True)]
1071
+
1072
+
1073
+ def load_session(sid: str):
1074
+ """sid 为 'latest' 或具体 id。成功返回 messages,并恢复清单和模式。"""
1075
+ sessions = list_sessions()
1076
+ d = sessions[0] if sid == "latest" and sessions else next((s for s in sessions if s["id"] == sid), None)
1077
+ if not d:
1078
+ return None
1079
+ SESSION["id"], SESSION["title"] = d["id"], d.get("title", "")
1080
+ STATE["mode"] = d.get("mode", "normal")
1081
+ TODOS[:] = d.get("todos", [])
1082
+ return d["messages"]
1083
+
1084
+
1085
+ # ---------- 3.8 配置与客户端初始化 ----------
1086
+ def load_config():
1087
+ try:
1088
+ with open(CONFIG_PATH, encoding="utf-8") as f:
1089
+ data = json.load(f)
1090
+ return data if isinstance(data, dict) else {}
1091
+ except (OSError, ValueError):
1092
+ return {}
1093
+
1094
+
1095
+ def resolve_setting(envs, cfg_key, default):
1096
+ """按 环境变量 > 配置文件 > 默认值 的顺序取值,返回 (值, 来源说明)。"""
1097
+ for name in envs:
1098
+ if os.environ.get(name):
1099
+ return os.environ[name], f"环境变量 {name}"
1100
+ cfg = load_config()
1101
+ if cfg.get(cfg_key):
1102
+ return cfg[cfg_key], f"配置文件 {CONFIG_PATH}"
1103
+ return default, "默认值"
1104
+
1105
+
1106
+ KEY_ENVS = ["TINY_AGENT_API_KEY", "DEEPSEEK_API_KEY"]
1107
+ URL_ENVS = ["TINY_AGENT_BASE_URL"]
1108
+ MODEL_ENVS = ["TINY_AGENT_MODEL", "DEEPSEEK_MODEL"]
1109
+
1110
+
1111
+ def mask_key(key):
1112
+ return "(未设置)" if not key else ("****" if len(key) <= 8 else key[:3] + "…" + key[-4:])
1113
+
1114
+
1115
+ def init_client():
1116
+ """读取配置并创建 API 客户端。已经有客户端(例如测试里注入的)就直接用。"""
1117
+ global client, MODEL, NO_THINK
1118
+ if client is not None:
1119
+ return
1120
+ key, _ = resolve_setting(KEY_ENVS, "api_key", "")
1121
+ if not key:
1122
+ sys.exit("没有找到 API key。请运行 tiny-agent --setup 配置,"
1123
+ "或设置环境变量 DEEPSEEK_API_KEY(也可用 TINY_AGENT_API_KEY)。")
1124
+ base_url, _ = resolve_setting(URL_ENVS, "base_url", DEFAULT_BASE_URL)
1125
+ MODEL, _ = resolve_setting(MODEL_ENVS, "model", DEFAULT_MODEL)
1126
+ # "关闭思考模式"是 DeepSeek 的扩展参数,其他服务商不认识,所以只对 DeepSeek 发送
1127
+ NO_THINK = {"thinking": {"type": "disabled"}} if "deepseek" in base_url.lower() else {}
1128
+ client = OpenAI(api_key=key, base_url=base_url, max_retries=0, timeout=120.0) # 重试统一由 with_retry 负责
1129
+
1130
+
1131
+ def run_setup():
1132
+ """交互式配置:写入 ~/.tiny-agent/config.json(权限 600)。环境变量仍然优先于配置文件。"""
1133
+ import getpass
1134
+
1135
+ cfg = load_config()
1136
+ print("tiny-agent 配置(直接回车保留当前值)\\n")
1137
+ base = input(f"API 地址 [{cfg.get('base_url') or DEFAULT_BASE_URL}]: ").strip() \
1138
+ or cfg.get("base_url") or DEFAULT_BASE_URL
1139
+ model = input(f"模型 [{cfg.get('model') or DEFAULT_MODEL}]: ").strip() or cfg.get("model") or DEFAULT_MODEL
1140
+ key = getpass.getpass(f"API key(输入不会显示)[{mask_key(cfg.get('api_key', ''))}]: ").strip() \
1141
+ or cfg.get("api_key", "")
1142
+ os.makedirs(HOME_DIR, exist_ok=True)
1143
+ fd = os.open(CONFIG_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) # 创建时就限制权限,避免先公开再收紧
1144
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
1145
+ json.dump({"base_url": base, "model": model, "api_key": key}, f, ensure_ascii=False, indent=2)
1146
+ try:
1147
+ os.chmod(CONFIG_PATH, 0o600)
1148
+ except OSError:
1149
+ pass # Windows 上权限模型不同
1150
+ print(f"\\n已保存到 {CONFIG_PATH}。API key 以明文存放在这个文件里,请不要把它提交到 git 或分享给别人。")
1151
+
1152
+
1153
+ def show_config():
1154
+ key, key_src = resolve_setting(KEY_ENVS, "api_key", "")
1155
+ url, url_src = resolve_setting(URL_ENVS, "base_url", DEFAULT_BASE_URL)
1156
+ model, model_src = resolve_setting(MODEL_ENVS, "model", DEFAULT_MODEL)
1157
+ print(f"tiny-agent {__version__}")
1158
+ print(f"配置文件 {CONFIG_PATH}({'存在' if os.path.exists(CONFIG_PATH) else '不存在'})")
1159
+ print(f"API key {mask_key(key)} 来源:{key_src if key else '无'}")
1160
+ print(f"API 地址 {url} 来源:{url_src}")
1161
+ print(f"模型 {model} 来源:{model_src}")
1162
+ print(f"用户记忆 {USER_MEMORY}({'存在' if os.path.exists(USER_MEMORY) else '不存在'})")
1163
+
1164
+
1165
+ # ---------- 4. 流式调用 ----------
1166
+ def _stream_chat_once(messages, tools, show=True):
1167
+ """流式请求一次模型(不含重试)。
1168
+
1169
+ 关键点:流式时,工具调用是被切成碎片发来的——
1170
+ 每个碎片带一个 index,id 和 name 只在第一片出现,
1171
+ arguments(JSON 字符串)要把所有碎片按 index 拼起来,最后才是完整 JSON。
1172
+ """
1173
+ st = ui.stream(show) # 显示句柄:先转圈,收到文字后逐块渲染
1174
+ content, calls, usage = "", {}, None
1175
+ try:
1176
+ stream = client.chat.completions.create(
1177
+ model=MODEL,
1178
+ messages=messages,
1179
+ tools=tools,
1180
+ stream=True,
1181
+ stream_options={"include_usage": True}, # 让最后一个 chunk 带上 token 用量
1182
+ extra_body=NO_THINK,
1183
+ )
1184
+ for chunk in stream:
1185
+ if CANCEL.is_set():
1186
+ raise Interrupted()
1187
+ if getattr(chunk, "usage", None):
1188
+ usage = chunk.usage
1189
+ if not chunk.choices: # 用量 chunk 没有 choices
1190
+ continue
1191
+ delta = chunk.choices[0].delta
1192
+ if delta.content:
1193
+ content += delta.content
1194
+ st.text(delta.content)
1195
+ for tc in delta.tool_calls or []:
1196
+ st.activity()
1197
+ c = calls.setdefault(tc.index, {"id": "", "name": "", "arguments": ""})
1198
+ if tc.id:
1199
+ c["id"] = tc.id
1200
+ if tc.function:
1201
+ if tc.function.name:
1202
+ c["name"] = tc.function.name
1203
+ if tc.function.arguments:
1204
+ c["arguments"] += tc.function.arguments
1205
+ finally:
1206
+ st.close() # 正常结束、出错、Ctrl+C 都要收尾,否则终端会被转圈或刷新区占住
1207
+ if usage:
1208
+ with _usage_lock:
1209
+ USAGE["requests"] += 1
1210
+ USAGE["prompt"] += usage.prompt_tokens
1211
+ USAGE["completion"] += getattr(usage, "completion_tokens", 0) or 0
1212
+ tokens = usage.prompt_tokens if usage else len(json.dumps(messages, ensure_ascii=False)) // 3
1213
+ return content, [calls[i] for i in sorted(calls)], tokens
1214
+
1215
+
1216
+ def stream_chat(messages, tools, show=True):
1217
+ # 注意:连接在流式过程中途断开时,已经打印出的那部分文字会在重试后重新出现一次,
1218
+ # 这是简单实现的代价;Claude Code 这类产品会做更细的处理。
1219
+ return with_retry(lambda: _stream_chat_once(messages, tools, show), "模型请求")
1220
+
1221
+
1222
+ # ---------- 5. 上下文压缩(同 v2) ----------
1223
+ def render(msgs) -> str:
1224
+ lines = []
1225
+ for m in msgs:
1226
+ if m["role"] == "tool":
1227
+ lines.append(f"[工具结果] {m['content'][:1500]}")
1228
+ elif m["role"] == "assistant":
1229
+ if m.get("content"):
1230
+ lines.append(f"[助手] {m['content'][:1500]}")
1231
+ for tc in m.get("tool_calls", []):
1232
+ lines.append(
1233
+ f"[助手调用] {tc['function']['name']}({tc['function']['arguments'][:500]})"
1234
+ )
1235
+ else:
1236
+ lines.append(f"[用户] {m['content'][:1500]}")
1237
+ return "\n".join(lines)
1238
+
1239
+
1240
+ SHRINK_OVER = 1500 # 早期的工具输出超过这个长度就换成占位符
1241
+
1242
+
1243
+ def shrink_old_outputs(messages, cut):
1244
+ """第一步(便宜):把待压缩区间里的大块工具输出换成"头部 + 省略说明",返回节省的字符数。"""
1245
+ saved = 0
1246
+ for m in messages[1:cut]:
1247
+ if m["role"] == "tool" and len(m["content"]) > SHRINK_OVER:
1248
+ n = len(m["content"])
1249
+ m["content"] = m["content"][:300] + f"\n…[此处省略了 {n - 300} 字符的旧输出;如仍需要,请重新读取(按行范围)]"
1250
+ saved += n - 300
1251
+ return saved
1252
+
1253
+
1254
+ def compact(messages):
1255
+ cut = len(messages) - KEEP_LAST
1256
+ while cut < len(messages) and messages[cut]["role"] == "tool":
1257
+ cut += 1
1258
+ if cut <= 2:
1259
+ ui.notice("[压缩] 历史太短,无需压缩")
1260
+ return messages
1261
+ saved = shrink_old_outputs(messages, cut)
1262
+ est = len(json.dumps(messages, ensure_ascii=False)) // 2 # 粗略估算 token 数(偏保守)
1263
+ if saved and est < COMPACT_TOKENS * 0.6:
1264
+ ui.notice(f"[压缩] 已精简早期的大块工具输出(约省 {saved} 字符),无需总结")
1265
+ return messages
1266
+ resp = chat_create(
1267
+ model=MODEL,
1268
+ messages=[
1269
+ {
1270
+ "role": "system",
1271
+ "content": "你负责压缩 AI 编程助手的对话历史。请写一份摘要,必须保留:"
1272
+ "用户目标、已完成的操作、涉及的文件及其关键状态、重要决定、"
1273
+ "尚未完成的事项、遇到的错误。丢弃冗长的原始输出。",
1274
+ },
1275
+ {"role": "user", "content": render(messages[1:cut])},
1276
+ ],
1277
+ extra_body=NO_THINK,
1278
+ )
1279
+ summary = resp.choices[0].message.content
1280
+ if TODOS: # 任务清单不能在压缩中丢失
1281
+ summary += "\n\n当前任务清单:\n" + render_todos()
1282
+ ui.notice(f"[压缩] {cut - 1} 条早期消息 -> 1 条摘要")
1283
+ return [
1284
+ messages[0],
1285
+ {"role": "user", "content": "[以下是之前对话的摘要,请据此继续工作]\n" + summary},
1286
+ ] + messages[cut:]
1287
+
1288
+
1289
+ # ---------- 6. 通用 Agent 循环(主 Agent 和子 Agent 共用) ----------
1290
+ STATE = {"tokens": 0, "mode": "normal"} # tokens: 最近一次 prompt_tokens;mode: normal / plan
1291
+ _sub_counter = itertools.count(1)
1292
+
1293
+
1294
+ def execute_tool(name: str, args: dict) -> str:
1295
+ try:
1296
+ handler = HANDLERS.get(name)
1297
+ return handler(args) if handler else f"未知工具: {name}"
1298
+ except Exception as e:
1299
+ return f"工具执行出错: {type(e).__name__}: {e}"
1300
+
1301
+
1302
+ def run_one(call, allowed, tag):
1303
+ try:
1304
+ args = json.loads(call["arguments"] or "{}")
1305
+ except json.JSONDecodeError:
1306
+ args = {}
1307
+ if not isinstance(args, dict):
1308
+ args = {}
1309
+ if CANCEL.is_set():
1310
+ raise Interrupted()
1311
+ ui.tool_call(tag, call["name"], args)
1312
+ if call["name"] not in allowed:
1313
+ out = f"错误:当前不允许使用工具 {call['name']}"
1314
+ else:
1315
+ out = execute_tool(call["name"], args)
1316
+ ui.tool_result(tag, call["name"], out)
1317
+ return out
1318
+
1319
+
1320
+ def run_loop(messages, tools, allowed, tag, show=True, max_steps=None, compact_ok=False):
1321
+ limit = max_steps or MAX_STEPS # 运行时才取值,这样 --max-steps 才能生效
1322
+ content = ""
1323
+ recent = [] # 最近的 (工具名, 参数),用来发现原地打转
1324
+ for step in range(limit):
1325
+ if compact_ok:
1326
+ STATE["step"], STATE["max_steps"] = step + 1, limit
1327
+ # tools 可以是一个函数:每轮重新取,模式切换(计划 -> 执行)才能立即生效
1328
+ if CANCEL.is_set():
1329
+ raise Interrupted()
1330
+ cur_tools, cur_allowed = tools() if callable(tools) else (tools, allowed)
1331
+ if compact_ok:
1332
+ messages[0]["content"] = system_prompt() # 记忆文件/模式有变化时同步
1333
+ if compact_ok and STATE["tokens"] > COMPACT_TOKENS:
1334
+ messages[:] = compact(messages)
1335
+ STATE["tokens"] = 0
1336
+
1337
+ content, calls, tokens = stream_chat(messages, cur_tools, show)
1338
+ if compact_ok:
1339
+ STATE["tokens"] = tokens
1340
+
1341
+ entry = {"role": "assistant", "content": content}
1342
+ if calls:
1343
+ entry["tool_calls"] = [
1344
+ {
1345
+ "id": c["id"],
1346
+ "type": "function",
1347
+ "function": {"name": c["name"], "arguments": c["arguments"]},
1348
+ }
1349
+ for c in calls
1350
+ ]
1351
+ messages.append(entry)
1352
+ if not calls:
1353
+ return content
1354
+
1355
+ # 同一轮里的多个 task 互不依赖、都是只读的,可以并行
1356
+ if len(calls) > 1 and all(c["name"] == "task" for c in calls):
1357
+ with concurrent.futures.ThreadPoolExecutor() as ex:
1358
+ outputs = list(ex.map(lambda c: run_one(c, cur_allowed, tag), calls))
1359
+ else:
1360
+ outputs = [run_one(c, cur_allowed, tag) for c in calls]
1361
+
1362
+ for c, out in zip(calls, outputs):
1363
+ sig = (c["name"], c["arguments"])
1364
+ recent.append(sig)
1365
+ del recent[:-8]
1366
+ n_same = recent.count(sig)
1367
+ if n_same >= 3: # 完全相同的调用,结果不会变化:提醒模型换思路
1368
+ out += (f"\n[提示:你已用完全相同的参数调用 {c['name']} {n_same} 次,结果不会变化。"
1369
+ "请换一种方式(比如先 grep 定位,再按行范围读取),或基于已有信息直接给出结论。]")
1370
+ ui.warn(f"[检测到重复调用 {c['name']}({n_same} 次),已提醒模型换思路]")
1371
+ messages.append({"role": "tool", "tool_call_id": c["id"], "content": out})
1372
+
1373
+ if show:
1374
+ ui.warn(f"[已达到 {limit} 步上限,已停止。输入「继续」可以接着做,也可以用 --max-steps 调大上限]")
1375
+ return "(已达到最大步数,以下是目前的进展)\n" + content
1376
+
1377
+
1378
+ # ---------- 7. 子 Agent ----------
1379
+ def do_task(a):
1380
+ n = next(_sub_counter)
1381
+ ui.sub_start(n, a["prompt"])
1382
+ sub_messages = [
1383
+ {"role": "system", "content": build_system(SUB_SYSTEM)},
1384
+ {"role": "user", "content": a["prompt"]}, # 全新上下文,只有这一条任务
1385
+ ]
1386
+ result = ""
1387
+ try:
1388
+ result = run_loop(
1389
+ sub_messages,
1390
+ READ_ONLY_TOOLS,
1391
+ READ_ONLY,
1392
+ tag=f" │ 子Agent#{n}",
1393
+ show=False, # 子 Agent 不流式输出,避免并行时输出交错
1394
+ max_steps=SUB_MAX_STEPS,
1395
+ )
1396
+ finally:
1397
+ # 无论成功还是出错都要收尾,否则进度表(Live)会一直占着终端
1398
+ ui.sub_end(n, len(sub_messages), len(result))
1399
+ # 子 Agent 内部可能读了很多文件,但主 Agent 只会收到 result 这一小段
1400
+ return result
1401
+
1402
+
1403
+ HANDLERS = {
1404
+ "read_file": do_read,
1405
+ "write_file": do_write,
1406
+ "edit_file": do_edit,
1407
+ "glob": do_glob,
1408
+ "grep": do_grep,
1409
+ "run_bash": do_bash,
1410
+ "task": do_task,
1411
+ "todo_write": do_todo,
1412
+ "exit_plan_mode": do_exit_plan,
1413
+ }
1414
+
1415
+
1416
+ # ---------- 8. 入口 ----------
1417
+ def run_turn(messages, user_input):
1418
+ messages.append({"role": "user", "content": user_input})
1419
+ run_loop(messages, current_tools, None, tag="[调用工具]", compact_ok=True)
1420
+
1421
+
1422
+ def _main():
1423
+ global AUTO_YES, MAX_STEPS
1424
+ ap = argparse.ArgumentParser(prog="tiny-agent", description="tiny-agent:小型终端编程 Agent")
1425
+ ap.add_argument("--version", action="version", version=f"tiny-agent {__version__}")
1426
+ ap.add_argument("--setup", action="store_true", help="交互式配置 API key、接口地址和模型")
1427
+ ap.add_argument("--show-config", action="store_true", help="显示当前生效的配置及其来源(key 会被遮蔽)")
1428
+ ap.add_argument("task", nargs="*", help="一次性任务;不给则进入交互模式")
1429
+ ap.add_argument("--plan", action="store_true", help="以计划模式启动")
1430
+ ap.add_argument("--yes", action="store_true", help="自动批准所有确认(危险,仅用于临时目录/评测)")
1431
+ ap.add_argument("--resume", nargs="?", const="latest", metavar="ID", help="恢复会话,默认最近一次")
1432
+ ap.add_argument("--plain", action="store_true", help="关闭彩色界面,输出纯文本(输出被重定向时会自动启用)")
1433
+ ap.add_argument("--simple-input", action="store_true", help="不用 prompt_toolkit,改用普通输入")
1434
+ ap.add_argument("--max-steps", type=int, default=MAX_STEPS, help="主 Agent 每轮最多执行的步数(默认 30)")
1435
+ ap.add_argument("--tui", action="store_true", help="使用 Textual 全屏界面(需要 pip install textual)")
1436
+ opts = ap.parse_args()
1437
+ if opts.setup:
1438
+ return run_setup()
1439
+ if opts.show_config:
1440
+ return show_config()
1441
+ init_client()
1442
+ MAX_STEPS = max(1, opts.max_steps)
1443
+ task_words = opts.task
1444
+ if opts.yes:
1445
+ AUTO_YES = True
1446
+ if opts.plain:
1447
+ ui.rich = False
1448
+ elif not RICH_OK and sys.stdout.isatty():
1449
+ ui.notice("提示:未安装 rich,使用纯文本界面。执行 pip install rich 可启用彩色界面。")
1450
+ if opts.simple_input:
1451
+ ui.use_pt = False
1452
+ elif ui.rich and not PT_OK and sys.stdin.isatty():
1453
+ ui.notice("提示:未安装 prompt_toolkit,使用简易输入。执行 pip install prompt_toolkit 可启用补全和状态栏。")
1454
+
1455
+ messages = [{"role": "system", "content": system_prompt()}]
1456
+ if opts.resume:
1457
+ loaded = load_session(opts.resume)
1458
+ if loaded is None and opts.resume != "latest":
1459
+ # --resume 后面跟的其实不是会话 id,而是任务文字
1460
+ task_words = [opts.resume] + task_words
1461
+ loaded = load_session("latest")
1462
+ if loaded is None:
1463
+ sys.exit(f"没有可恢复的会话(目录:{SESSION_DIR})")
1464
+ messages = loaded
1465
+ messages[0]["content"] = system_prompt() # 记忆文件可能已更新
1466
+ ui.notice(f"[已恢复会话 {SESSION['id']}:{SESSION['title']}({len(messages)} 条消息)]")
1467
+ if opts.plan:
1468
+ STATE["mode"] = "plan"
1469
+
1470
+ task = " ".join(task_words)
1471
+ if opts.tui and not task:
1472
+ return run_tui(messages)
1473
+ if task: # 一次性任务模式
1474
+ n = len(messages)
1475
+ t0 = time.time()
1476
+ u0 = dict(USAGE)
1477
+ try:
1478
+ run_turn(messages, task)
1479
+ except BaseException:
1480
+ messages[:] = messages[:n] # 失败/中断时回滚,避免存下残缺的工具调用
1481
+ raise
1482
+ finally:
1483
+ print_usage(time.time() - t0 if ui.rich else None, u0)
1484
+ save_session(messages)
1485
+ return
1486
+
1487
+ _, found = load_memory()
1488
+ ui.banner(ROOT, MODEL, found, SESSION["id"], STATE["mode"], git_info())
1489
+ last_interrupt = 0.0
1490
+ while True:
1491
+ mode_before = STATE["mode"]
1492
+ text, interrupted, eof = "", False, False
1493
+ try:
1494
+ text = ui.read_input(STATE["mode"] == "plan").strip()
1495
+ except KeyboardInterrupt:
1496
+ interrupted = True
1497
+ except EOFError:
1498
+ eof = True
1499
+ if STATE["mode"] != mode_before: # 在提示符处按 Shift+Tab 切换过模式
1500
+ messages[0]["content"] = system_prompt()
1501
+ ui.notice("[已进入计划模式:只读调研,提交计划后需你批准]" if STATE["mode"] == "plan"
1502
+ else "[已回到执行模式]")
1503
+ if eof:
1504
+ print()
1505
+ break
1506
+ if interrupted:
1507
+ now = time.time()
1508
+ if now - last_interrupt < 2: # 两秒内连按两次才退出,避免误触
1509
+ print()
1510
+ break
1511
+ last_interrupt = now
1512
+ ui.notice("再按一次 Ctrl+C 或输入 exit 退出")
1513
+ continue
1514
+ if text in ("exit", "quit"):
1515
+ break
1516
+ if text == "/compact":
1517
+ messages[:] = compact(messages)
1518
+ continue
1519
+ if text == "/sessions":
1520
+ ui.sessions(list_sessions()[:10])
1521
+ continue
1522
+ if text == "/usage":
1523
+ print_usage()
1524
+ continue
1525
+ if text == "/expand":
1526
+ ui.expand()
1527
+ continue
1528
+ if text == "/help":
1529
+ ui.help()
1530
+ continue
1531
+ if text == "/plan":
1532
+ STATE["mode"] = "normal" if STATE["mode"] == "plan" else "plan"
1533
+ messages[0]["content"] = system_prompt()
1534
+ ui.notice("[已进入计划模式:只读调研,提交计划后需你批准]" if STATE["mode"] == "plan"
1535
+ else "[已回到执行模式]")
1536
+ continue
1537
+ if text == "/memory":
1538
+ ui.memory(load_memory()[0])
1539
+ continue
1540
+ if text == "/todo":
1541
+ ui.todos(TODOS) if TODOS else ui.notice("(清单为空)")
1542
+ continue
1543
+ if text.startswith("#"): # 快捷添加记忆,立即生效
1544
+ note = text.lstrip("#").strip()
1545
+ if note:
1546
+ add_memory(note)
1547
+ messages[0]["content"] = system_prompt()
1548
+ ui.notice(f"[已记住] {note} (写入 {PROJECT_MEMORY})")
1549
+ continue
1550
+ if text:
1551
+ n = len(messages)
1552
+ t0 = time.time()
1553
+ u0 = dict(USAGE)
1554
+ try:
1555
+ run_turn(messages, text)
1556
+ except (KeyboardInterrupt, Exception) as e:
1557
+ # 中断时可能留下"有 tool_calls 却没有结果"的消息,
1558
+ # 会让下一次请求报错,所以回滚到本轮开始前的状态
1559
+ messages[:] = messages[:n]
1560
+ kind = "已中断当前任务" if isinstance(e, KeyboardInterrupt) else f"出错 {type(e).__name__}: {e}"
1561
+ ui.warn(f"[{kind},本轮对话已回滚]")
1562
+ secs = time.time() - t0
1563
+ print_usage(secs, u0)
1564
+ if secs > 15:
1565
+ ui.bell() # 长任务做完时响一声,提醒你回来看
1566
+ save_session(messages) # 每轮结束都存档;回滚后存的是回滚后的干净状态
1567
+
1568
+
1569
+ # ---------- 9. Textual 全屏界面(--tui) ----------
1570
+ TUI_KEYS = [
1571
+ ("Enter", "发送"),
1572
+ ("Ctrl+J", "换行(也可直接粘贴多行)"),
1573
+ ("Tab", "补全 / 命令和 @ 文件"),
1574
+ ("↑ ↓", "翻输入历史(光标在首行或末行时)"),
1575
+ ("Shift+Tab", "切换计划模式"),
1576
+ ("Ctrl+C", "中断当前任务;空闲时连按两次退出"),
1577
+ ("Ctrl+L", "清屏"),
1578
+ ("Ctrl+Q", "退出"),
1579
+ ]
1580
+ DEFAULT_HINT = "Enter 发送 · Ctrl+J 换行 · Tab 补全 · Shift+Tab 计划模式 · Ctrl+C 中断 · / 命令 · @ 文件"
1581
+
1582
+
1583
+ def completion_candidates(text):
1584
+ """返回 (替换起点, [(候选, 说明)]),供输入框的 Tab 补全和提示行使用。"""
1585
+ if text.startswith("/") and " " not in text and "\n" not in text:
1586
+ return 0, [(c, d) for c, d in SLASH_COMMANDS.items() if c.startswith(text)]
1587
+ words = text.split()
1588
+ if words and not text.endswith((" ", "\n")) and words[-1].startswith("@"):
1589
+ last = words[-1]
1590
+ return len(text) - len(last), [("@" + p, "") for p in complete_paths(last[1:])]
1591
+ return 0, []
1592
+
1593
+
1594
+ if TEXTUAL_OK:
1595
+
1596
+ def _plain(renderable, width=100):
1597
+ buf = StringIO()
1598
+ Console(file=buf, width=width, color_system=None, highlight=False).print(renderable)
1599
+ return buf.getvalue().rstrip()
1600
+
1601
+ # ---- 弹出对话框 ----
1602
+ class ConfirmScreen(ModalScreen):
1603
+ default_answer = "n"
1604
+ BINDINGS = [
1605
+ Binding("y", "answer('y')", "允许"),
1606
+ Binding("a", "answer('a')", "总是允许"),
1607
+ Binding("n", "answer('n')", "拒绝"),
1608
+ Binding("escape", "answer('n')", "拒绝"),
1609
+ ]
1610
+
1611
+ def __init__(self, tool_name, detail, body, lang):
1612
+ super().__init__()
1613
+ self.tool_name, self.detail, self.body, self.lang = tool_name, detail, body, lang
1614
+
1615
+ def compose(self):
1616
+ with Vertical(id="dialog"):
1617
+ yield Label(f"需要确认 · {self.tool_name}", id="dialog-title")
1618
+ yield Static(Text(self.detail))
1619
+ if self.body:
1620
+ lang = self.lang
1621
+ if lang.startswith("path:"):
1622
+ lang = Syntax.guess_lexer(lang[5:], self.body)
1623
+ with VerticalScroll(id="dialog-body"):
1624
+ yield Static(Syntax(self.body, lang, theme="ansi_dark", word_wrap=True))
1625
+ with Horizontal(id="dialog-buttons"):
1626
+ yield Button("允许 (y)", id="y", variant="success")
1627
+ yield Button("本会话总是允许 (a)", id="a", variant="primary")
1628
+ yield Button("拒绝 (n)", id="n", variant="error")
1629
+
1630
+ def on_button_pressed(self, event):
1631
+ self.dismiss(event.button.id)
1632
+
1633
+ def action_answer(self, value):
1634
+ self.dismiss(value)
1635
+
1636
+ class ChoiceScreen(ModalScreen):
1637
+ """计划审批:上面是可滚动的计划全文,下面两个按钮。"""
1638
+ default_answer = "n"
1639
+ BINDINGS = [
1640
+ Binding("y", "answer('y')", "批准"),
1641
+ Binding("n", "answer('n')", "不批准"),
1642
+ Binding("escape", "answer('n')", "不批准"),
1643
+ ]
1644
+
1645
+ def __init__(self, prompt, body_markdown=None):
1646
+ super().__init__()
1647
+ self.prompt, self.body_markdown = prompt, body_markdown
1648
+
1649
+ def compose(self):
1650
+ with Vertical(id="dialog"):
1651
+ yield Label("计划待审批", id="dialog-title")
1652
+ if self.body_markdown:
1653
+ with VerticalScroll(id="dialog-body"):
1654
+ yield Static(Markdown(self.body_markdown))
1655
+ yield Static(Text(self.prompt))
1656
+ with Horizontal(id="dialog-buttons"):
1657
+ yield Button("批准并执行 (y)", id="y", variant="success")
1658
+ yield Button("不批准,继续修改 (n)", id="n", variant="error")
1659
+
1660
+ def on_button_pressed(self, event):
1661
+ self.dismiss(event.button.id)
1662
+
1663
+ def action_answer(self, value):
1664
+ self.dismiss(value)
1665
+
1666
+ class AskScreen(ModalScreen):
1667
+ default_answer = ""
1668
+ BINDINGS = [Binding("escape", "answer('')", "取消")]
1669
+
1670
+ def __init__(self, prompt):
1671
+ super().__init__()
1672
+ self.prompt = prompt
1673
+
1674
+ def compose(self):
1675
+ with Vertical(id="dialog"):
1676
+ yield Label(self.prompt, id="dialog-title")
1677
+ yield Input(id="ask-input")
1678
+
1679
+ def on_mount(self):
1680
+ self.query_one(Input).focus()
1681
+
1682
+ def on_input_submitted(self, event):
1683
+ self.dismiss(event.value)
1684
+
1685
+ def action_answer(self, value):
1686
+ self.dismiss(value)
1687
+
1688
+ # ---- 底部输入框 ----
1689
+ class PromptArea(TextArea):
1690
+ BINDINGS = [
1691
+ Binding("enter", "submit", "发送", priority=True, show=False),
1692
+ Binding("ctrl+j", "newline", "换行", priority=True, show=False),
1693
+ Binding("tab", "complete", "补全", priority=True, show=False),
1694
+ Binding("up", "history_prev", "上一条", priority=True, show=False),
1695
+ Binding("down", "history_next", "下一条", priority=True, show=False),
1696
+ ]
1697
+
1698
+ class Submitted(Message):
1699
+ def __init__(self, text):
1700
+ super().__init__()
1701
+ self.text = text
1702
+
1703
+ def __init__(self, *args, **kwargs):
1704
+ super().__init__(*args, **kwargs)
1705
+ self._hist, self._hist_i = [], 0
1706
+
1707
+ def action_submit(self):
1708
+ text = self.text.strip()
1709
+ if not text:
1710
+ return
1711
+ self._hist.append(text)
1712
+ self._hist_i = len(self._hist)
1713
+ self.clear()
1714
+ self.post_message(self.Submitted(text))
1715
+
1716
+ def action_newline(self):
1717
+ self.insert("\n")
1718
+
1719
+ def action_complete(self):
1720
+ start, items = completion_candidates(self.text)
1721
+ if not items:
1722
+ self.insert(" ") # 没有可补全的内容时,Tab 当作缩进
1723
+ return
1724
+ texts = [c for c, _ in items]
1725
+ new = texts[0] if len(texts) == 1 else os.path.commonprefix(texts)
1726
+ if len(texts) > 1 and len(new) <= len(self.text) - start:
1727
+ new = texts[0] # 公共前缀没有比已输入的更长,就直接取第一个候选
1728
+ self.text = self.text[:start] + new
1729
+ self.move_cursor(self.document.end)
1730
+
1731
+ def action_history_prev(self):
1732
+ if self._hist and self.cursor_location[0] == 0:
1733
+ self._hist_i = max(0, self._hist_i - 1)
1734
+ self.text = self._hist[self._hist_i]
1735
+ self.move_cursor(self.document.end)
1736
+ else:
1737
+ self.action_cursor_up()
1738
+
1739
+ def action_history_next(self):
1740
+ if self._hist and self.cursor_location[0] >= self.document.line_count - 1 and self._hist_i < len(self._hist):
1741
+ self._hist_i += 1
1742
+ self.text = self._hist[self._hist_i] if self._hist_i < len(self._hist) else ""
1743
+ self.move_cursor(self.document.end)
1744
+ else:
1745
+ self.action_cursor_down()
1746
+
1747
+ # ---- 流式输出(与 Streamer 同一套接口,但输出到 Textual)----
1748
+ class TuiStreamer:
1749
+ def __init__(self, tui, show):
1750
+ self.tui, self.show = tui, show
1751
+ self.buf, self.reply, self.last_push, self.cleared = "", "", 0.0, False
1752
+ if show:
1753
+ tui._ui(tui.app.set_activity, "思考中")
1754
+
1755
+ def _clear(self):
1756
+ if not self.cleared:
1757
+ self.cleared = True
1758
+ self.tui._ui(self.tui.app.set_activity, "")
1759
+
1760
+ def activity(self):
1761
+ if self.show:
1762
+ self._clear()
1763
+
1764
+ def _commit_complete_blocks(self):
1765
+ pos = 0
1766
+ while True:
1767
+ k = self.buf.find("\n\n", pos)
1768
+ if k == -1:
1769
+ return
1770
+ if self.buf[:k].count("```") % 2 == 0: # 不在代码块中间,才能安全切分
1771
+ block, self.buf = self.buf[:k], self.buf[k + 2:].lstrip("\n")
1772
+ if block.strip():
1773
+ self.tui._ui(self.tui.app.add_block, Markdown(block), True)
1774
+ pos = 0
1775
+ else:
1776
+ pos = k + 2
1777
+
1778
+ def text(self, delta):
1779
+ if not self.show:
1780
+ return
1781
+ self._clear()
1782
+ self.reply += delta
1783
+ self.buf += delta
1784
+ self._commit_complete_blocks()
1785
+ now = time.time()
1786
+ if now - self.last_push > 0.05: # 限速:每秒最多刷新约 20 次
1787
+ self.last_push = now
1788
+ self.tui._ui(self.tui.app.set_live, Markdown(self.buf) if self.buf.strip() else Text(""))
1789
+
1790
+ def close(self):
1791
+ if not self.show:
1792
+ return
1793
+ self._clear()
1794
+ final = Markdown(self.buf) if self.buf.strip() else None
1795
+ self.tui._ui(self.tui.app.end_live, final)
1796
+ if self.reply.strip():
1797
+ self.tui.last_reply = self.reply
1798
+ self.tui.record(self.reply)
1799
+
1800
+ # ---- 与 UI 同一套接口,所有界面操作都转交给 Textual 应用 ----
1801
+ class TextualUI:
1802
+ rich = True
1803
+
1804
+ def __init__(self, app):
1805
+ self.app = app
1806
+ self.app_thread = None
1807
+ self.last_output = None
1808
+ self.last_reply = ""
1809
+ self.transcript = []
1810
+ self._busy_secs = 0.0
1811
+ self._pending_plan = None
1812
+
1813
+ def _ui(self, fn, *args, **kwargs):
1814
+ """核心在后台线程里调用 ui.xxx();界面操作必须回到 Textual 的主线程执行。"""
1815
+ try:
1816
+ if self.app_thread is None or threading.get_ident() == self.app_thread:
1817
+ return fn(*args, **kwargs)
1818
+ return self.app.call_from_thread(fn, *args, **kwargs)
1819
+ except RuntimeError: # 应用已经退出,后台线程还在收尾
1820
+ return None
1821
+
1822
+ def record(self, plain):
1823
+ self.transcript.append(plain)
1824
+ del self.transcript[:-3000]
1825
+
1826
+ def block(self, renderable, plain=None, gap=False):
1827
+ self.record(plain if plain is not None else _plain(renderable))
1828
+ self._ui(self.app.add_block, renderable, gap)
1829
+
1830
+ # --- 基础提示 ---
1831
+ def notice(self, msg):
1832
+ self.block(Text(msg, style="dim"), msg)
1833
+
1834
+ def warn(self, msg):
1835
+ self.block(Text(msg, style="yellow"), msg)
1836
+
1837
+ def user_echo(self, text):
1838
+ self.block(Text.assemble(("❯ ", "bold green"), (text, "bold")), "❯ " + text, gap=True)
1839
+
1840
+ def bell(self):
1841
+ self._ui(self.app.bell)
1842
+
1843
+ @contextlib.contextmanager
1844
+ def busy(self, label):
1845
+ t0 = time.time()
1846
+ self._ui(self.app.set_activity, label)
1847
+ try:
1848
+ yield
1849
+ finally:
1850
+ self._ui(self.app.set_activity, "")
1851
+ self._busy_secs = time.time() - t0
1852
+
1853
+ # --- 输入与确认(阻塞后台线程,直到用户在对话框里回答)---
1854
+ def ask(self, prompt):
1855
+ if prompt.startswith("批准该计划"):
1856
+ plan, self._pending_plan = self._pending_plan, None
1857
+ r = self._ui(self.app.ask_modal, ChoiceScreen, prompt, plan)
1858
+ else:
1859
+ r = self._ui(self.app.ask_modal, AskScreen, prompt)
1860
+ return r or ""
1861
+
1862
+ def confirm_prompt(self, tool_name, detail, body=None, lang="text"):
1863
+ r = self._ui(self.app.ask_modal, ConfirmScreen, tool_name, detail, body, lang) or "n"
1864
+ verdict = {"y": "已允许", "a": "已允许(本会话总是允许)"}.get(r, "已拒绝")
1865
+ self.notice(f"[确认] {tool_name}:{verdict} {detail[:60]}") # 在对话里留下审计记录
1866
+ return r
1867
+
1868
+ def plan_review(self, plan):
1869
+ self._pending_plan = plan
1870
+ self.block(Panel(Markdown(plan), title="[bold cyan]计划待审批[/]", border_style="cyan"), "[计划]\n" + plan)
1871
+
1872
+ # --- 模型输出与工具 ---
1873
+ def stream(self, show):
1874
+ return TuiStreamer(self, show)
1875
+
1876
+ def tool_call(self, tag, name, args):
1877
+ summary = summarize_args(name, args)
1878
+ if tag.startswith("["):
1879
+ self.block(Text.assemble(("● ", "bold cyan"), (name, "bold"), (f"({summary})", "dim")),
1880
+ f"● {name}({summary})")
1881
+ else: # 子 Agent:只更新侧边栏
1882
+ m = re.search(r"#(\d+)", tag)
1883
+ if m:
1884
+ self._ui(self.app.sub_update, int(m.group(1)), f"{name}({summary})")
1885
+
1886
+ def tool_result(self, tag, name, out):
1887
+ if not tag.startswith("[") or name in ("task", "todo_write"):
1888
+ return
1889
+ self.last_output = (name, out)
1890
+ lines = out.strip().splitlines() or ["(无输出)"]
1891
+ limit = 1 if name in ("write_file", "edit_file") else 3
1892
+ style = "red" if out.startswith(("错误", "工具执行出错")) else "dim"
1893
+ suffix = f" ({self._busy_secs:.1f}s)" if self._busy_secs >= 1 else ""
1894
+ self._busy_secs = 0.0
1895
+ shown = [(" ⎿ " if i == 0 else " ") + l[:110] + (suffix if i == 0 else "") for i, l in enumerate(lines[:limit])]
1896
+ if len(lines) > limit:
1897
+ shown.append(f" … 还有 {len(lines) - limit} 行(/expand 查看全部)")
1898
+ text = "\n".join(shown)
1899
+ self.block(Text(text, style=style), text)
1900
+
1901
+ def expand(self):
1902
+ if not self.last_output:
1903
+ return self.notice("(还没有可展开的工具输出)")
1904
+ name, out = self.last_output
1905
+ lines = out.splitlines()
1906
+ shown = "\n".join(lines[:300]) + (f"\n… 还有 {len(lines) - 300} 行未显示" if len(lines) > 300 else "")
1907
+ self.block(Panel(Text(shown), title=f"上一次工具输出 · {name}", border_style="dim"), shown)
1908
+
1909
+ # --- 侧边栏相关 ---
1910
+ def todos(self, todos):
1911
+ self._ui(self.app.set_todos, [dict(x) for x in todos])
1912
+ self.notice(f"[任务清单已更新:{len(todos)} 项]")
1913
+
1914
+ def sub_start(self, n, prompt):
1915
+ self._ui(self.app.sub_start, n, prompt)
1916
+
1917
+ def sub_end(self, n, n_msgs, n_chars):
1918
+ self._ui(self.app.sub_end, n, f"完成:返回 {n_chars} 字")
1919
+
1920
+ def usage(self, u, secs=None, turn=None):
1921
+ line = f"用量 · {u['requests']} 次请求 · 输入 {u['prompt']} · 输出 {u['completion']} tokens(累计)"
1922
+ if turn is not None:
1923
+ line = (f"用量 · 本轮 {turn['requests']} 次请求 · 输入 {turn['prompt']} · 输出 {turn['completion']}"
1924
+ + (f" · {secs:.1f}s" if secs is not None else "")
1925
+ + f" | 累计 {u['requests']} 次请求 · 输入 {u['prompt']} · 输出 {u['completion']}")
1926
+ elif secs is not None:
1927
+ line += f" · 本轮 {secs:.1f}s"
1928
+ self.notice(line)
1929
+ self._ui(self.app.set_last_secs, secs)
1930
+
1931
+ # --- 其他展示 ---
1932
+ def banner(self, root, model, memory_files, session_id, mode, git=""):
1933
+ mem = ", ".join(memory_files) if memory_files else "无(可输入 # 内容 创建 AGENT.md)"
1934
+ body = Text()
1935
+ rows = [("工作目录", root), ("模型", model)] + ([("git", git)] if git else []) + [("记忆文件", mem), ("会话", session_id)]
1936
+ for label, value in rows:
1937
+ body.append(f"{label:<6}", style="dim")
1938
+ body.append(f"{value}\n")
1939
+ body.append("\n输入 /help 查看命令和快捷键", style="dim")
1940
+ self.block(Panel(body, title="[bold]tiny-agent[/]", border_style="blue"))
1941
+
1942
+ def help(self):
1943
+ table = Table(box=None, show_header=False, pad_edge=False)
1944
+ table.add_column(style="bold")
1945
+ table.add_column()
1946
+ for cmd, desc in SLASH_COMMANDS.items():
1947
+ table.add_row(Text(cmd), Text(desc))
1948
+ table.add_row(Text("/copy"), Text("复制上一条回复到剪贴板"))
1949
+ table.add_row(Text("/export"), Text("导出整个对话为 Markdown 文件"))
1950
+ table.add_row(Text("# 内容"), Text("追加一条记忆到 AGENT.md,立即生效"))
1951
+ table.add_row(Text(""), Text(""))
1952
+ for key, desc in TUI_KEYS:
1953
+ table.add_row(Text(key, style="cyan"), Text(desc))
1954
+ self.block(Panel(table, title="帮助", border_style="dim", expand=False))
1955
+
1956
+ def sessions(self, items):
1957
+ if not items:
1958
+ return self.notice("(没有会话)")
1959
+ table = Table(box=None, header_style="bold")
1960
+ for col, right in (("ID", False), ("时间", False), ("消息", True), ("标题", False)):
1961
+ table.add_column(col, justify="right" if right else "left")
1962
+ for s in items:
1963
+ table.add_row(Text(s["id"]), Text(s["saved_at"]), Text(str(len(s["messages"]))), Text(s["title"]))
1964
+ self.block(table)
1965
+
1966
+ def memory(self, text):
1967
+ if not text:
1968
+ return self.notice("(没有记忆文件)")
1969
+ self.block(Panel(Markdown(text), title="记忆", border_style="dim"), text)
1970
+
1971
+ # ---- 应用本体 ----
1972
+ class AgentApp(App):
1973
+ TITLE = "tiny-agent"
1974
+ ENABLE_COMMAND_PALETTE = False # 去掉右下角用不上的 ^p palette
1975
+ CSS = """
1976
+ Screen { layout: vertical; }
1977
+ #body { height: 1fr; }
1978
+ #chat { width: 1fr; padding: 0 1; scrollbar-size-vertical: 1; }
1979
+ .block { height: auto; }
1980
+ .gap { margin-bottom: 1; }
1981
+ #side { width: 40; padding: 0 1; border-left: solid $primary-darken-2; }
1982
+ #side Static { height: auto; border: round $primary-darken-2; padding: 0 1; margin-bottom: 1; }
1983
+ #activity { height: 1; padding: 0 2; color: $text-muted; }
1984
+ #hint { height: auto; max-height: 4; padding: 0 2; color: $text-muted; }
1985
+ PromptArea { height: auto; min-height: 3; max-height: 12; border: tall $success; }
1986
+ PromptArea.plan { border: tall $accent; }
1987
+ ConfirmScreen, ChoiceScreen, AskScreen { align: center middle; }
1988
+ #dialog { width: 90%; max-width: 110; height: auto; max-height: 90%; border: thick $warning;
1989
+ background: $surface; padding: 1 2; }
1990
+ #dialog-title { text-style: bold; margin-bottom: 1; }
1991
+ #dialog-body { height: auto; max-height: 22; border: round $primary-darken-2; margin: 1 0; padding: 0 1; }
1992
+ #dialog-buttons { height: auto; align-horizontal: center; margin-top: 1; }
1993
+ #dialog-buttons Button { margin: 0 1; }
1994
+ """
1995
+ BINDINGS = [
1996
+ Binding("shift+tab", "toggle_plan", "计划模式", priority=True),
1997
+ Binding("ctrl+c", "interrupt", "中断", priority=True),
1998
+ Binding("ctrl+l", "clear_chat", "清屏"),
1999
+ Binding("ctrl+q", "quit_app", "退出", priority=True),
2000
+ ]
2001
+
2002
+ def __init__(self, messages):
2003
+ super().__init__()
2004
+ self.messages = messages
2005
+ self.busy = False
2006
+ self.last_int = 0.0
2007
+ self.subs, self.todos = {}, []
2008
+ self.live, self.activity, self.frame = None, "", 0
2009
+ self.hint_text, self.git, self.last_secs = DEFAULT_HINT, "", None
2010
+ self.tui = TextualUI(self)
2011
+
2012
+ def compose(self):
2013
+ yield Header(show_clock=False)
2014
+ with Horizontal(id="body"):
2015
+ yield VerticalScroll(id="chat")
2016
+ with Vertical(id="side"):
2017
+ yield Static(id="todo")
2018
+ yield Static(id="subs")
2019
+ yield Static(id="status")
2020
+ yield Static("", id="activity")
2021
+ yield Static(DEFAULT_HINT, id="hint")
2022
+ yield PromptArea(id="prompt")
2023
+ yield Footer()
2024
+
2025
+ # ---- 生命周期 ----
2026
+ def on_mount(self):
2027
+ global ui
2028
+ self._old_ui = ui
2029
+ self.tui.app_thread = threading.get_ident()
2030
+ ui = self.tui # 核心代码里的 ui.xxx() 从现在起输出到本界面
2031
+ self.query_one("#todo").border_title = "任务清单"
2032
+ self.query_one("#subs").border_title = "子 Agent"
2033
+ self.query_one("#status").border_title = "状态"
2034
+ self.git = git_info()
2035
+ _, found = load_memory()
2036
+ self.tui.banner(ROOT, MODEL, found, SESSION["id"], STATE["mode"], self.git)
2037
+ self.set_todos([])
2038
+ self.refresh_subs()
2039
+ self.refresh_status()
2040
+ self.update_mode_ui()
2041
+ self.set_interval(0.15, self._tick)
2042
+ self.query_one(PromptArea).focus()
2043
+
2044
+ def on_unmount(self):
2045
+ global ui
2046
+ CANCEL.set() # 让还在后台跑的任务尽快停下
2047
+ ui = self._old_ui
2048
+ save_session(self.messages)
2049
+
2050
+ # ---- 对话区 ----
2051
+ def _chat(self):
2052
+ return self.query_one("#chat", VerticalScroll)
2053
+
2054
+ def _scroll(self):
2055
+ self.call_after_refresh(self._chat().scroll_end, animate=False)
2056
+
2057
+ def add_block(self, renderable, gap=False):
2058
+ w = Static(renderable, classes="block gap" if gap else "block")
2059
+ if self.live is not None:
2060
+ self._chat().mount(w, before=self.live) # 已写完的段落排在"正在写的这段"前面
2061
+ else:
2062
+ self._chat().mount(w)
2063
+ self._scroll()
2064
+
2065
+ def set_live(self, renderable):
2066
+ if self.live is None:
2067
+ self.live = Static(renderable, classes="block gap")
2068
+ self._chat().mount(self.live)
2069
+ else:
2070
+ self.live.update(renderable)
2071
+ self._scroll()
2072
+
2073
+ def end_live(self, final):
2074
+ if self.live is not None:
2075
+ self.live.remove()
2076
+ self.live = None
2077
+ if final is not None:
2078
+ self.add_block(final, True)
2079
+
2080
+ def action_clear_chat(self):
2081
+ self._chat().remove_children()
2082
+ self.live = None
2083
+
2084
+ # ---- 活动提示、侧边栏 ----
2085
+ def set_activity(self, text):
2086
+ self.activity = text
2087
+ self._render_activity()
2088
+
2089
+ def _render_activity(self):
2090
+ frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
2091
+ self.query_one("#activity", Static).update(
2092
+ f"{frames[self.frame % len(frames)]} {self.activity}…" if self.activity else "")
2093
+
2094
+ def set_todos(self, todos):
2095
+ self.todos = todos
2096
+ body = Text()
2097
+ styles = {"completed": ("☑", "green dim"), "in_progress": ("◐", "bold yellow"), "pending": ("☐", "")}
2098
+ for i, item in enumerate(todos):
2099
+ if i:
2100
+ body.append("\n")
2101
+ icon, style = styles[item["status"]]
2102
+ body.append(f"{icon} {item['content']}", style=style)
2103
+ if not todos:
2104
+ body.append("(空)", style="dim")
2105
+ self.query_one("#todo", Static).update(body)
2106
+
2107
+ def sub_start(self, n, prompt):
2108
+ if not any(not r["done"] for r in self.subs.values()):
2109
+ self.subs = {} # 上一批已全部结束,开始新一批时清空
2110
+ self.subs[n] = {"prompt": prompt.replace("\n", " "), "last": "启动中", "t0": time.time(), "t1": None, "done": False}
2111
+ self.refresh_subs()
2112
+
2113
+ def sub_update(self, n, text):
2114
+ if n in self.subs:
2115
+ self.subs[n]["last"] = text
2116
+ self.refresh_subs()
2117
+
2118
+ def sub_end(self, n, text):
2119
+ if n in self.subs:
2120
+ self.subs[n].update(done=True, t1=time.time(), last=text)
2121
+ self.refresh_subs()
2122
+
2123
+ def refresh_subs(self):
2124
+ body = Text()
2125
+ if not self.subs:
2126
+ body.append("(无)", style="dim")
2127
+ frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
2128
+ now = time.time()
2129
+ for n, r in sorted(self.subs.items()):
2130
+ secs = (r["t1"] or now) - r["t0"]
2131
+ icon = "✓" if r["done"] else frames[self.frame % len(frames)]
2132
+ body.append(f"{icon} #{n} {secs:.0f}s\n", style="green" if r["done"] else "magenta")
2133
+ body.append(f" {r['prompt'][:32]}\n {r['last'][:32]}\n", style="dim")
2134
+ self.query_one("#subs", Static).update(body)
2135
+
2136
+ def set_last_secs(self, secs):
2137
+ self.last_secs = secs
2138
+ self.refresh_status()
2139
+
2140
+ def status_text(self):
2141
+ bar, pct = context_meter()
2142
+ plan = STATE["mode"] == "plan"
2143
+ t = Text()
2144
+
2145
+ def row(k, v, style=""):
2146
+ t.append(f"{k:<5}", style="dim")
2147
+ t.append(f"{v}\n", style=style)
2148
+
2149
+ row("模式", "计划模式" if plan else "执行模式", "bold cyan" if plan else "bold green")
2150
+ row("模型", MODEL)
2151
+ row("上下文", f"{bar} {pct}%" if pct is not None else bar)
2152
+ if self.busy and STATE.get("step"):
2153
+ row("步数", f"{STATE['step']}/{STATE['max_steps']}")
2154
+ row("请求", f"{USAGE['requests']} 次")
2155
+ row("输入", str(USAGE["prompt"]))
2156
+ row("输出", str(USAGE["completion"]))
2157
+ if self.last_secs is not None:
2158
+ row("本轮", f"{self.last_secs:.1f}s")
2159
+ if self.git:
2160
+ row("git", self.git)
2161
+ t.append(f"{'会话':<5}", style="dim")
2162
+ t.append(SESSION["id"])
2163
+ return t
2164
+
2165
+ def refresh_status(self):
2166
+ self.query_one("#status", Static).update(self.status_text())
2167
+
2168
+ def set_git(self, git):
2169
+ self.git = git
2170
+ self.refresh_status()
2171
+
2172
+ def update_mode_ui(self):
2173
+ plan = STATE["mode"] == "plan"
2174
+ self.sub_title = f"{ROOT} · {'计划模式' if plan else '执行模式'}"
2175
+ self.query_one(PromptArea).set_class(plan, "plan")
2176
+ self.refresh_status()
2177
+
2178
+ def _tick(self):
2179
+ self.frame += 1
2180
+ if self.activity:
2181
+ self._render_activity()
2182
+ if any(not r["done"] for r in self.subs.values()):
2183
+ self.refresh_subs()
2184
+ if self.frame % 8 == 0:
2185
+ self.refresh_status()
2186
+
2187
+ # ---- 对话框 ----
2188
+ async def ask_modal(self, screen_cls, *args):
2189
+ fut = asyncio.get_running_loop().create_future()
2190
+
2191
+ def done(result):
2192
+ if not fut.done():
2193
+ fut.set_result(result)
2194
+
2195
+ await self.push_screen(screen_cls(*args), done)
2196
+ return await fut
2197
+
2198
+ # ---- 输入与命令 ----
2199
+ def on_text_area_changed(self, event):
2200
+ start, items = completion_candidates(event.text_area.text)
2201
+ self.hint_text = " ".join(f"{c} {d}".strip() for c, d in items[:8]) if items else DEFAULT_HINT
2202
+ self.query_one("#hint", Static).update(self.hint_text)
2203
+
2204
+ def on_prompt_area_submitted(self, event):
2205
+ text = event.text
2206
+ if self.busy:
2207
+ self.tui.warn("[上一个任务还在进行,按 Ctrl+C 可以中断]")
2208
+ return
2209
+ self.busy = True
2210
+ self.tui.user_echo(text)
2211
+ self.run_worker(lambda: self._process(text), thread=True, name="turn")
2212
+
2213
+ def _process(self, text): # 在后台线程里运行
2214
+ try:
2215
+ self._dispatch(text)
2216
+ except Exception as e: # 命令本身出错也不能让界面卡死
2217
+ self.tui.warn(f"[出错 {type(e).__name__}: {e}]")
2218
+ finally:
2219
+ self.busy = False
2220
+ self.tui._ui(self.refresh_status)
2221
+ self.tui._ui(self.update_mode_ui)
2222
+
2223
+ def _dispatch(self, text):
2224
+ tui = self.tui
2225
+ if text in ("exit", "quit"):
2226
+ tui._ui(self.exit)
2227
+ elif text == "/compact":
2228
+ self.messages[:] = compact(self.messages)
2229
+ elif text == "/sessions":
2230
+ tui.sessions(list_sessions()[:10])
2231
+ elif text == "/usage":
2232
+ print_usage()
2233
+ elif text == "/expand":
2234
+ tui.expand()
2235
+ elif text == "/help":
2236
+ tui.help()
2237
+ elif text == "/plan":
2238
+ self._toggle_plan()
2239
+ elif text == "/memory":
2240
+ tui.memory(load_memory()[0])
2241
+ elif text == "/todo":
2242
+ tui.todos(TODOS) if TODOS else tui.notice("(清单为空)")
2243
+ elif text == "/copy":
2244
+ if tui.last_reply:
2245
+ tui._ui(self.copy_to_clipboard, tui.last_reply)
2246
+ tui.notice("[已复制上一条回复]")
2247
+ else:
2248
+ tui.notice("(还没有回复可复制)")
2249
+ elif text == "/export":
2250
+ path = os.path.join(ROOT, ".tiny-agent", "transcripts", SESSION["id"] + ".md")
2251
+ os.makedirs(os.path.dirname(path), exist_ok=True)
2252
+ with open(path, "w", encoding="utf-8") as f:
2253
+ f.write("\n\n".join(tui.transcript) + "\n")
2254
+ tui.notice(f"[已导出到 {path}]")
2255
+ elif text.startswith("#"):
2256
+ note = text.lstrip("#").strip()
2257
+ if note:
2258
+ add_memory(note)
2259
+ self.messages[0]["content"] = system_prompt()
2260
+ tui.notice(f"[已记住] {note} (写入 {PROJECT_MEMORY})")
2261
+ else:
2262
+ self._run_turn(text)
2263
+
2264
+ def _run_turn(self, text):
2265
+ tui = self.tui
2266
+ n = len(self.messages)
2267
+ t0 = time.time()
2268
+ u0 = dict(USAGE)
2269
+ CANCEL.clear()
2270
+ try:
2271
+ run_turn(self.messages, text)
2272
+ except (Interrupted, KeyboardInterrupt, Exception) as e:
2273
+ self.messages[:] = self.messages[:n] # 回滚到本轮开始前,避免残缺的工具调用
2274
+ kind = ("已中断当前任务" if isinstance(e, (Interrupted, KeyboardInterrupt))
2275
+ else f"出错 {type(e).__name__}: {e}")
2276
+ tui.warn(f"[{kind},本轮对话已回滚]")
2277
+ finally:
2278
+ tui._ui(self.set_activity, "")
2279
+ tui._ui(self.end_live, None)
2280
+ secs = time.time() - t0
2281
+ print_usage(secs, u0)
2282
+ if secs > 15:
2283
+ tui.bell()
2284
+ save_session(self.messages)
2285
+ tui._ui(self.set_git, git_info())
2286
+
2287
+ def _toggle_plan(self):
2288
+ STATE["mode"] = "normal" if STATE["mode"] == "plan" else "plan"
2289
+ self.messages[0]["content"] = system_prompt()
2290
+ self.tui.notice("[已进入计划模式:只读调研,提交计划后需你批准]" if STATE["mode"] == "plan"
2291
+ else "[已回到执行模式]")
2292
+ self.tui._ui(self.update_mode_ui)
2293
+
2294
+ # ---- 快捷键 ----
2295
+ def action_toggle_plan(self):
2296
+ self._toggle_plan()
2297
+
2298
+ def action_interrupt(self):
2299
+ if isinstance(self.screen, (ConfirmScreen, ChoiceScreen, AskScreen)):
2300
+ self.screen.dismiss(self.screen.default_answer) # 先关掉对话框(视为拒绝)
2301
+ if self.busy:
2302
+ CANCEL.set()
2303
+ self.tui.warn("[正在中断…]")
2304
+ return
2305
+ now = time.time()
2306
+ if now - self.last_int < 2:
2307
+ self.exit()
2308
+ else:
2309
+ self.last_int = now
2310
+ self.tui.notice("再按一次 Ctrl+C 退出")
2311
+
2312
+ def action_quit_app(self):
2313
+ CANCEL.set()
2314
+ self.exit()
2315
+
2316
+
2317
+ def run_tui(messages):
2318
+ if not TEXTUAL_OK:
2319
+ sys.exit("全屏界面需要 textual:pip install textual")
2320
+ app = AgentApp(messages)
2321
+ app.run()
2322
+ print(f"会话已保存({SESSION['id']})。下次用 --resume 恢复。")
2323
+ print_usage()
2324
+
2325
+
2326
+ def main():
2327
+ """命令行入口(pyproject 里的 tiny-agent 命令指向这里)。"""
2328
+ try:
2329
+ _main()
2330
+ except KeyboardInterrupt:
2331
+ sys.exit(130)
2332
+ except APIStatusError as e:
2333
+ code = getattr(e, "status_code", None)
2334
+ hint = {401: "API key 无效或已过期,请运行 tiny-agent --setup 重新配置。",
2335
+ 402: "账户余额不足,请先充值。",
2336
+ 404: "接口地址或模型名可能不对,请用 tiny-agent --show-config 检查。"}.get(code, "")
2337
+ sys.exit(f"请求失败(HTTP {code})。{hint}")
2338
+ except APIConnectionError as e:
2339
+ sys.exit(f"网络连接失败:{e}。请检查网络和 API 地址(tiny-agent --show-config)。")
2340
+
2341
+
2342
+ if __name__ == "__main__":
2343
+ main()