anixcode 0.8.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.
- anixcode/__init__.py +3 -0
- anixcode/__main__.py +4 -0
- anixcode/agent.py +358 -0
- anixcode/airpc.py +59 -0
- anixcode/checkpoints.py +87 -0
- anixcode/cli.py +185 -0
- anixcode/commands.py +218 -0
- anixcode/compaction.py +91 -0
- anixcode/danger.py +85 -0
- anixcode/i18n.py +67 -0
- anixcode/i18n_en.py +293 -0
- anixcode/llm.py +258 -0
- anixcode/mentions.py +116 -0
- anixcode/projects.py +142 -0
- anixcode/prompts.py +64 -0
- anixcode/providers.py +67 -0
- anixcode/settings.py +105 -0
- anixcode/storage.py +129 -0
- anixcode/tools/__init__.py +15 -0
- anixcode/tools/base.py +203 -0
- anixcode/tools/files.py +248 -0
- anixcode/tools/search.py +107 -0
- anixcode/tools/shell.py +86 -0
- anixcode/tui/__init__.py +0 -0
- anixcode/tui/anim.py +242 -0
- anixcode/tui/app.py +812 -0
- anixcode/tui/app.tcss +281 -0
- anixcode/tui/screens.py +556 -0
- anixcode/tui/widgets.py +374 -0
- anixcode-0.8.0.dist-info/METADATA +241 -0
- anixcode-0.8.0.dist-info/RECORD +35 -0
- anixcode-0.8.0.dist-info/WHEEL +5 -0
- anixcode-0.8.0.dist-info/entry_points.txt +2 -0
- anixcode-0.8.0.dist-info/licenses/LICENSE +21 -0
- anixcode-0.8.0.dist-info/top_level.txt +1 -0
anixcode/cli.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""anixcode [folder] | anixcode run "task" | anixcode connect | anixcode models"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from .i18n import tr
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import getpass
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import __version__, providers
|
|
12
|
+
from .agent import Agent, AgentError, Compacted, PermissionRequest, ToolFinished, ToolStarted
|
|
13
|
+
from .airpc import AirpcReporter
|
|
14
|
+
from .llm import LLMClient, LLMError, ReasoningDelta, Retrying, TextDelta
|
|
15
|
+
from .settings import Credentials, config_dir, load_auth, load_settings, save_auth, save_settings
|
|
16
|
+
from .storage import Store
|
|
17
|
+
|
|
18
|
+
COMMANDS = {"run", "connect", "models"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _client(settings, auth) -> LLMClient:
|
|
22
|
+
p = providers.get(settings.provider, settings)
|
|
23
|
+
cred = auth.get(settings.provider, Credentials())
|
|
24
|
+
return LLMClient(cred.base_url or p.base_url, cred.api_key)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def cmd_tui(args: argparse.Namespace) -> int:
|
|
28
|
+
try:
|
|
29
|
+
from .tui.app import AnixApp
|
|
30
|
+
except ImportError as e:
|
|
31
|
+
print(tr('Не хватает библиотеки {0}. Установите: pip install -e .', e.name), file=sys.stderr)
|
|
32
|
+
return 1
|
|
33
|
+
from .projects import is_unsuitable
|
|
34
|
+
|
|
35
|
+
root = Path(args.folder or ".").resolve()
|
|
36
|
+
if not root.is_dir():
|
|
37
|
+
print(tr('Нет такой папки: {0}', root), file=sys.stderr)
|
|
38
|
+
return 2
|
|
39
|
+
# Started from home, a drive root or C:\Windows\System32 (a fresh cmd window)? Ask which project.
|
|
40
|
+
pick = args.folder is None and is_unsuitable(root)
|
|
41
|
+
AnixApp(root, load_settings(), Store(config_dir() / "sessions.db"), pick_project=pick).run()
|
|
42
|
+
return 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def cmd_connect(_args: argparse.Namespace) -> int:
|
|
46
|
+
settings, auth = load_settings(), load_auth()
|
|
47
|
+
print(tr("Провайдеры:"))
|
|
48
|
+
for i, p in enumerate(providers.PROVIDERS, 1):
|
|
49
|
+
print(f" {i}. {p.name}")
|
|
50
|
+
choice = input(tr("Номер: ")).strip()
|
|
51
|
+
try:
|
|
52
|
+
p = providers.PROVIDERS[int(choice) - 1]
|
|
53
|
+
except (ValueError, IndexError):
|
|
54
|
+
print(tr("Неверный номер."))
|
|
55
|
+
return 2
|
|
56
|
+
cred = auth.get(p.id, Credentials())
|
|
57
|
+
base = input(tr('Адрес сервера [{0}]: ', cred.base_url or p.base_url)).strip() or cred.base_url or p.base_url
|
|
58
|
+
if p.key_url:
|
|
59
|
+
print(tr('Ключ можно взять здесь: {0}', p.key_url))
|
|
60
|
+
key = getpass.getpass(tr("API-ключ (Enter — оставить прежний): ")).strip()
|
|
61
|
+
if key:
|
|
62
|
+
cred.api_key = key
|
|
63
|
+
cred.base_url = "" if base == p.base_url else base
|
|
64
|
+
model = input(tr('Модель [{0}]: ', p.default_model or settings.model)).strip() or p.default_model or settings.model
|
|
65
|
+
if not model:
|
|
66
|
+
print(tr("Нужно указать модель. Список: anixcode models"))
|
|
67
|
+
auth[p.id] = cred
|
|
68
|
+
settings.provider, settings.model = p.id, model
|
|
69
|
+
save_auth(auth)
|
|
70
|
+
save_settings(settings)
|
|
71
|
+
print(tr('Сохранено: {0} · {1}', p.name, model))
|
|
72
|
+
return 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def cmd_models(_args: argparse.Namespace) -> int:
|
|
76
|
+
settings, auth = load_settings(), load_auth()
|
|
77
|
+
if not settings.provider:
|
|
78
|
+
print(tr("Сначала: anixcode connect"), file=sys.stderr)
|
|
79
|
+
return 2
|
|
80
|
+
|
|
81
|
+
async def go() -> list[str]:
|
|
82
|
+
client = _client(settings, auth)
|
|
83
|
+
try:
|
|
84
|
+
return await client.list_models()
|
|
85
|
+
finally:
|
|
86
|
+
await client.aclose()
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
for m in asyncio.run(go()):
|
|
90
|
+
print(m)
|
|
91
|
+
except LLMError as e:
|
|
92
|
+
print(e, file=sys.stderr)
|
|
93
|
+
return 1
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_run(args: argparse.Namespace) -> int:
|
|
98
|
+
settings, auth = load_settings(), load_auth()
|
|
99
|
+
if not settings.ready:
|
|
100
|
+
print(tr("Сначала подключите модель: anixcode connect"), file=sys.stderr)
|
|
101
|
+
return 2
|
|
102
|
+
root = Path(args.folder or ".").resolve()
|
|
103
|
+
prompt = args.prompt
|
|
104
|
+
if prompt.startswith("/"): # ready-made and own prompt commands work here too: anixcode run "/review"
|
|
105
|
+
from . import commands
|
|
106
|
+
|
|
107
|
+
name, rest = commands.parse(prompt)
|
|
108
|
+
cmd = commands.find(name, commands.all_commands(root, config_dir()))
|
|
109
|
+
if cmd is None or cmd.template is None:
|
|
110
|
+
print(tr('Команда /{0} работает только в интерфейсе или не существует.', name), file=sys.stderr)
|
|
111
|
+
return 2
|
|
112
|
+
prompt = commands.render(cmd.template, rest)
|
|
113
|
+
|
|
114
|
+
async def ask(req: PermissionRequest) -> str:
|
|
115
|
+
for why in req.danger:
|
|
116
|
+
print(f"\n\033[91m⚠ {why}\033[0m", file=sys.stderr)
|
|
117
|
+
for why in req.warnings:
|
|
118
|
+
print(f"\033[93m! {why}\033[0m", file=sys.stderr)
|
|
119
|
+
if args.yes:
|
|
120
|
+
return "once"
|
|
121
|
+
print(f"\n? {req.title}", file=sys.stderr)
|
|
122
|
+
if req.preview:
|
|
123
|
+
print(req.preview, file=sys.stderr)
|
|
124
|
+
answer = (await asyncio.to_thread(input, tr("Разрешить? [y]es / [a]lways / [n]o: "))).strip().lower()
|
|
125
|
+
return {"y": "once", "a": "always"}.get(answer[:1], "deny")
|
|
126
|
+
|
|
127
|
+
async def go() -> int:
|
|
128
|
+
client = _client(settings, auth)
|
|
129
|
+
store = Store(config_dir() / "sessions.db")
|
|
130
|
+
session = store.create(str(root), settings.model)
|
|
131
|
+
agent = Agent(client, settings.model, root, settings, ask=ask, reporter=AirpcReporter(settings.airpc),
|
|
132
|
+
provider=settings.provider)
|
|
133
|
+
agent.mode = "plan" if args.plan else "build"
|
|
134
|
+
code = 0
|
|
135
|
+
try:
|
|
136
|
+
async for ev in agent.run(session, prompt):
|
|
137
|
+
if isinstance(ev, TextDelta):
|
|
138
|
+
print(ev.text, end="", flush=True)
|
|
139
|
+
elif isinstance(ev, ReasoningDelta) and args.verbose:
|
|
140
|
+
print(ev.text, end="", file=sys.stderr, flush=True)
|
|
141
|
+
elif isinstance(ev, ToolStarted):
|
|
142
|
+
print(f"\n· {ev.title}", file=sys.stderr, flush=True)
|
|
143
|
+
elif isinstance(ev, ToolFinished) and ev.result.error:
|
|
144
|
+
print(f" ✗ {ev.result.output.splitlines()[0] if ev.result.output else ''}", file=sys.stderr)
|
|
145
|
+
elif isinstance(ev, AgentError):
|
|
146
|
+
print(f"\n✗ {ev.message}", file=sys.stderr)
|
|
147
|
+
code = 1
|
|
148
|
+
elif isinstance(ev, Retrying):
|
|
149
|
+
print(tr('\n… повтор {0}/{1} через {2:.0f}с ({3})', ev.attempt, ev.max_attempts, ev.delay, ev.reason), file=sys.stderr)
|
|
150
|
+
elif isinstance(ev, Compacted):
|
|
151
|
+
print(tr('\n🗜 история сжата: ~{0} → ~{1} токенов', ev.before, ev.after), file=sys.stderr)
|
|
152
|
+
finally:
|
|
153
|
+
await client.aclose()
|
|
154
|
+
store.close()
|
|
155
|
+
print()
|
|
156
|
+
return code
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
return asyncio.run(go())
|
|
160
|
+
except KeyboardInterrupt:
|
|
161
|
+
return 130
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def main(argv: list[str] | None = None) -> int:
|
|
165
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
166
|
+
if argv and argv[0] in ("-V", "--version"):
|
|
167
|
+
print(f"anixcode {__version__}")
|
|
168
|
+
return 0
|
|
169
|
+
parser = argparse.ArgumentParser(prog="anixcode", description=tr("ИИ-агент для кода в терминале"))
|
|
170
|
+
if argv and argv[0] in COMMANDS:
|
|
171
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
172
|
+
p = sub.add_parser("run", help=tr("выполнить задачу без интерфейса"))
|
|
173
|
+
p.add_argument("prompt")
|
|
174
|
+
p.add_argument("folder", nargs="?")
|
|
175
|
+
p.add_argument("--plan", action="store_true", help=tr("только читать и планировать"))
|
|
176
|
+
p.add_argument("-y", "--yes", action="store_true", help=tr("разрешать все действия без вопросов"))
|
|
177
|
+
p.add_argument("-v", "--verbose", action="store_true", help=tr("показывать размышления модели"))
|
|
178
|
+
p.set_defaults(func=cmd_run)
|
|
179
|
+
sub.add_parser("connect", help=tr("подключить модель и API-ключ")).set_defaults(func=cmd_connect)
|
|
180
|
+
sub.add_parser("models", help=tr("список моделей провайдера")).set_defaults(func=cmd_models)
|
|
181
|
+
else:
|
|
182
|
+
parser.add_argument("folder", nargs="?", help=tr("папка проекта (по умолчанию текущая)"))
|
|
183
|
+
parser.set_defaults(func=cmd_tui)
|
|
184
|
+
args = parser.parse_args(argv)
|
|
185
|
+
return args.func(args)
|
anixcode/commands.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Slash commands: built-in actions, ready-made prompt commands, and your own from Markdown files.
|
|
2
|
+
|
|
3
|
+
Own commands (like Claude Code / OpenCode): put a Markdown file into
|
|
4
|
+
<project>/.anixcode/commands/<name>.md (only this project)
|
|
5
|
+
<config dir>/commands/<name>.md (every project)
|
|
6
|
+
Optional front matter: ---\\ndescription: what it does\\n---
|
|
7
|
+
In the text, $ARGUMENTS is replaced with everything after the command, $1..$9 with single words.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
from .i18n import tr
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import shlex
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from .tools.base import read_text
|
|
18
|
+
|
|
19
|
+
NAME = re.compile(r"^[a-z0-9][a-z0-9_-]{0,40}$")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Command:
|
|
24
|
+
name: str
|
|
25
|
+
description: str
|
|
26
|
+
action: str | None = None # handled by the app
|
|
27
|
+
template: str | None = None # sent to the agent
|
|
28
|
+
args_hint: str = ""
|
|
29
|
+
source: str = "builtin" # builtin | project | user
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def takes_args(self) -> bool:
|
|
33
|
+
return bool(self.args_hint)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
INIT_PROMPT = """Study this project and write an AGENTS.md file in its root folder: instructions for AI coding
|
|
37
|
+
agents working here. Include: what the project is; a short map of the folder structure; exact commands to
|
|
38
|
+
install dependencies, run, build and test; code style and conventions you actually observe in the code;
|
|
39
|
+
anything risky or important (generated files, secrets, slow tests). Be concise and practical (under 120 lines).
|
|
40
|
+
If AGENTS.md already exists, improve it and keep the user's own rules. Write it in the language of the existing
|
|
41
|
+
docs (README), or in English if there are none. Start by exploring with ls, glob, grep and read."""
|
|
42
|
+
|
|
43
|
+
PROMPTS: tuple[Command, ...] = (
|
|
44
|
+
Command("init", tr("изучить проект и написать AGENTS.md"), template=INIT_PROMPT),
|
|
45
|
+
Command("review", tr("ревью незакоммиченных изменений: баги, риски"), args_hint=tr("[на что смотреть]"), template=(
|
|
46
|
+
"Review the current uncommitted changes: run `git status`, `git diff` and `git diff --staged`. If there are "
|
|
47
|
+
"no changes, review the last commit (`git show --stat` then `git show`). Look for bugs, security problems, "
|
|
48
|
+
"missed edge cases, broken behaviour and unclear code. Do not edit files. Report findings ordered by "
|
|
49
|
+
"severity, each with file:line and a concrete suggestion, then a one-line verdict.\nFocus: $ARGUMENTS")),
|
|
50
|
+
Command("commit", tr("закоммитить изменения с хорошим сообщением"), args_hint=tr("[уточнения]"), template=(
|
|
51
|
+
"Commit the current changes. Run `git status`, `git diff`, `git diff --staged` and `git log -5 --oneline`. "
|
|
52
|
+
"Stage the relevant files (never secrets, .env files or build artifacts). Write a concise commit message in "
|
|
53
|
+
"the style and language of the recent commits (Conventional Commits if the project uses them): a summary "
|
|
54
|
+
"line, then a short body explaining why, if useful. Run `git commit`. Do not push.\nExtra: $ARGUMENTS")),
|
|
55
|
+
Command("test", tr("найти и запустить тесты, починить падающие"), args_hint=tr("[что тестировать]"), template=(
|
|
56
|
+
"Find out how tests are run in this project (AGENTS.md, README, package/config files) and run them. If "
|
|
57
|
+
"something fails, find the cause, fix it with minimal changes and run the tests again, until they pass or "
|
|
58
|
+
"you can clearly explain what blocks you.\nScope: $ARGUMENTS")),
|
|
59
|
+
Command("fix", tr("починить ошибку: вставьте текст ошибки или опишите баг"), args_hint=tr("<ошибка или описание>"),
|
|
60
|
+
template=("Fix this problem: $ARGUMENTS\n\nFirst locate the cause (read the code, reproduce it if you "
|
|
61
|
+
"can), then make a minimal fix and verify it (run the tests or the failing command).")),
|
|
62
|
+
Command("explain", tr("объяснить код: файл, функцию или весь проект"), args_hint=tr("<@файл или что объяснить>"),
|
|
63
|
+
template=("Explain $ARGUMENTS: what it does, how it works, the important parts and how it connects to the "
|
|
64
|
+
"rest of the project. Read the relevant code first. Do not edit files. Be clear and concrete.")),
|
|
65
|
+
Command("pr", tr("описание pull request для текущей ветки"), args_hint=tr("[уточнения]"), template=(
|
|
66
|
+
"Write a pull request description for the current branch. Find the default branch (main or master), then "
|
|
67
|
+
"look at `git log <default>..HEAD --oneline` and `git diff <default>...HEAD --stat` and the diff itself. "
|
|
68
|
+
"Output a title, a short summary, a list of changes and how to test them. Do not push or create anything."
|
|
69
|
+
"\nExtra: $ARGUMENTS")),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
ACTIONS: tuple[Command, ...] = (
|
|
73
|
+
Command("help", tr("все команды и клавиши"), action="help"),
|
|
74
|
+
Command("new", tr("новая сессия"), action="new"),
|
|
75
|
+
Command("clear", tr("новая сессия (то же, что /new)"), action="new"),
|
|
76
|
+
Command("sessions", tr("прошлые сессии этого проекта"), action="sessions"),
|
|
77
|
+
Command("resume", tr("продолжить прошлую сессию"), action="sessions"),
|
|
78
|
+
Command("undo", tr("откатить правки файлов из последнего ответа"), action="undo"),
|
|
79
|
+
Command("redo", tr("вернуть то, что откатили /undo"), action="redo"),
|
|
80
|
+
Command("compact", tr("сжать историю, чтобы освободить контекст"), action="compact"),
|
|
81
|
+
Command("model", tr("модель, провайдер и API-ключ"), action="connect"),
|
|
82
|
+
Command("models", tr("модель, провайдер и API-ключ"), action="connect"),
|
|
83
|
+
Command("connect", tr("подключить провайдера"), action="connect"),
|
|
84
|
+
Command("project", tr("выбрать проект или склонировать репозиторий"), action="project"),
|
|
85
|
+
Command("theme", tr("выбрать тему"), action="theme"),
|
|
86
|
+
Command("themes", tr("выбрать тему"), action="theme"),
|
|
87
|
+
Command("mode", tr("переключить Build / Plan"), action="mode"),
|
|
88
|
+
Command("permissions", tr("полный доступ вкл/выкл"), action="permissions"),
|
|
89
|
+
Command("status", tr("сводка: проект, модель, токены, контекст"), action="status"),
|
|
90
|
+
Command("export", tr("сохранить сессию в Markdown"), action="export"),
|
|
91
|
+
Command("language", tr("язык интерфейса: русский / English"), action="language"),
|
|
92
|
+
Command("doctor", tr("проверить git, ripgrep, подключение к модели"), action="doctor"),
|
|
93
|
+
Command("exit", tr("выход"), action="exit"),
|
|
94
|
+
Command("quit", tr("выход"), action="exit"),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _parse_file(path: Path, source: str) -> Command | None:
|
|
99
|
+
name = path.stem.lower()
|
|
100
|
+
if not NAME.match(name):
|
|
101
|
+
return None
|
|
102
|
+
try:
|
|
103
|
+
text = read_text(path).replace("\r\n", "\n") # UTF-8, UTF-8 with BOM or cp1251 (old Notepad)
|
|
104
|
+
except OSError:
|
|
105
|
+
return None
|
|
106
|
+
description = ""
|
|
107
|
+
m = re.match(r"^---\s*\n(.*?)\n---\s*\n", text, re.DOTALL)
|
|
108
|
+
if m:
|
|
109
|
+
for line in m.group(1).splitlines():
|
|
110
|
+
key, _, value = line.partition(":")
|
|
111
|
+
if key.strip().lower() == "description":
|
|
112
|
+
description = value.strip().strip("\"'")
|
|
113
|
+
text = text[m.end():]
|
|
114
|
+
text = text.strip()
|
|
115
|
+
if not text:
|
|
116
|
+
return None
|
|
117
|
+
if not description:
|
|
118
|
+
first = next((ln.strip("# ").strip() for ln in text.splitlines() if ln.strip()), "")
|
|
119
|
+
description = first[:70]
|
|
120
|
+
hint = tr("[аргументы]") if "$ARGUMENTS" in text or re.search(r"\$[1-9]", text) else ""
|
|
121
|
+
return Command(name, description, template=text, args_hint=hint, source=source)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def custom_commands(root: Path | None, config_dir: Path | None) -> list[Command]:
|
|
125
|
+
out: dict[str, Command] = {}
|
|
126
|
+
for folder, source in ((config_dir / "commands" if config_dir else None, "user"),
|
|
127
|
+
(root / ".anixcode" / "commands" if root else None, "project")):
|
|
128
|
+
if folder and folder.is_dir():
|
|
129
|
+
for f in sorted(folder.glob("*.md")):
|
|
130
|
+
cmd = _parse_file(f, source)
|
|
131
|
+
if cmd:
|
|
132
|
+
out[cmd.name] = cmd # project commands override user ones
|
|
133
|
+
return list(out.values())
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def all_commands(root: Path | None = None, config_dir: Path | None = None) -> list[Command]:
|
|
137
|
+
"""Actions can't be overridden; your own files override the ready-made prompt commands."""
|
|
138
|
+
action_names = {c.name for c in ACTIONS}
|
|
139
|
+
merged: dict[str, Command] = {c.name: c for c in PROMPTS}
|
|
140
|
+
for c in custom_commands(root, config_dir):
|
|
141
|
+
if c.name not in action_names:
|
|
142
|
+
merged[c.name] = c
|
|
143
|
+
return [*ACTIONS, *sorted(merged.values(), key=lambda c: c.name)]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def find(name: str, commands: list[Command]) -> Command | None:
|
|
147
|
+
return next((c for c in commands if c.name == name.lower()), None)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def parse(text: str) -> tuple[str, str]:
|
|
151
|
+
"""'/review src/api.py' -> ('review', 'src/api.py')"""
|
|
152
|
+
body = text[1:] if text.startswith("/") else text
|
|
153
|
+
name, _, args = body.strip().partition(" ")
|
|
154
|
+
return name.lower(), args.strip()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def render(template: str, args: str) -> str:
|
|
158
|
+
try:
|
|
159
|
+
words = shlex.split(args, posix=True) if args else []
|
|
160
|
+
except ValueError:
|
|
161
|
+
words = args.split()
|
|
162
|
+
out = template.replace("$ARGUMENTS", args)
|
|
163
|
+
for i in range(1, 10):
|
|
164
|
+
out = out.replace(f"${i}", words[i - 1] if i <= len(words) else "")
|
|
165
|
+
if args and "$ARGUMENTS" not in template and not re.search(r"\$[1-9]", template):
|
|
166
|
+
out += f"\n\n{args}"
|
|
167
|
+
return re.sub(r"\n(Focus|Extra|Scope):[ \t]*$", "", out.rstrip(), flags=re.MULTILINE).rstrip()
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def suggest(prefix: str, commands: list[Command], limit: int = 10) -> list[Command]:
|
|
171
|
+
p = prefix.lower()
|
|
172
|
+
seen, starts, contains = set(), [], []
|
|
173
|
+
for c in commands:
|
|
174
|
+
if c.name in seen:
|
|
175
|
+
continue
|
|
176
|
+
if c.name.startswith(p):
|
|
177
|
+
starts.append(c)
|
|
178
|
+
seen.add(c.name)
|
|
179
|
+
elif p and (p in c.name or (len(p) >= 3 and p in c.description.lower())):
|
|
180
|
+
contains.append(c)
|
|
181
|
+
seen.add(c.name)
|
|
182
|
+
return (starts + contains)[:limit]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def append_memory(root: Path, note: str) -> Path:
|
|
186
|
+
"""'# use pnpm, not npm' -> a line in AGENTS.md (like Claude Code's # memory)."""
|
|
187
|
+
path = root / "AGENTS.md"
|
|
188
|
+
note = note.strip()
|
|
189
|
+
if path.exists():
|
|
190
|
+
text = path.read_text(encoding="utf-8")
|
|
191
|
+
if tr("## Заметки") not in text and "## Notes" not in text:
|
|
192
|
+
text = text.rstrip() + tr("\n\n## Заметки\n")
|
|
193
|
+
elif not text.endswith("\n"):
|
|
194
|
+
text += "\n"
|
|
195
|
+
text += f"- {note}\n"
|
|
196
|
+
else:
|
|
197
|
+
text = tr('# Правила для агента\n\n## Заметки\n- {0}\n', note)
|
|
198
|
+
path.write_text(text, encoding="utf-8")
|
|
199
|
+
return path
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def session_markdown(title: str, model: str, messages: list[dict]) -> str:
|
|
203
|
+
lines = [f"# {title}", "", tr('_Модель: {0}_', model), ""]
|
|
204
|
+
for m in messages:
|
|
205
|
+
role, content = m.get("role"), m.get("content") or ""
|
|
206
|
+
if role == "user":
|
|
207
|
+
text = str(content).split("\n\nAttached by the user:")[0]
|
|
208
|
+
lines += [tr("## 🧑 Вы"), "", text, ""]
|
|
209
|
+
elif role == "assistant":
|
|
210
|
+
if content:
|
|
211
|
+
lines += ["## ◆ ANIX Code", "", str(content), ""]
|
|
212
|
+
for call in m.get("tool_calls") or []:
|
|
213
|
+
fn = call.get("function", {})
|
|
214
|
+
lines += [f"> 🔧 `{fn.get('name')}` `{str(fn.get('arguments', ''))[:300]}`", ""]
|
|
215
|
+
elif role == "tool":
|
|
216
|
+
out = str(content)
|
|
217
|
+
lines += [tr("<details><summary>результат</summary>"), "", "```", out[:3000], "```", "", "</details>", ""]
|
|
218
|
+
return "\n".join(lines)
|
anixcode/compaction.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Keeping long sessions inside the model's context window.
|
|
2
|
+
|
|
3
|
+
1. prune: old, big tool outputs are replaced with a short note (cheap, no model call);
|
|
4
|
+
2. summarize: if that is not enough, everything except the last turns is summarized by the model.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
from .i18n import tr
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
# Rough context sizes by model name (first match wins). Override with settings.context_window.
|
|
13
|
+
CONTEXT_HINTS: tuple[tuple[str, int], ...] = (
|
|
14
|
+
("gemini", 1_000_000), ("gpt-4.1", 1_000_000), ("gpt-5", 400_000), ("claude", 200_000), ("o3", 200_000),
|
|
15
|
+
("o4", 200_000), ("gpt-4o", 128_000), ("deepseek", 128_000), ("qwen", 128_000), ("llama", 128_000),
|
|
16
|
+
("mistral", 128_000), ("kimi", 128_000), ("glm", 128_000), ("grok", 128_000),
|
|
17
|
+
)
|
|
18
|
+
DEFAULT_WINDOW = 64_000
|
|
19
|
+
COMPACT_AT = 0.8 # compact when the history reaches 80% of the window
|
|
20
|
+
PRUNED = "[old tool output removed to save context; run the tool again if you need it]"
|
|
21
|
+
SUMMARY_PREFIX = "[Summary of the earlier conversation]"
|
|
22
|
+
|
|
23
|
+
SUMMARIZE_PROMPT = """You compress a coding session so the agent can continue it with less context.
|
|
24
|
+
Write a concise summary that keeps every specific detail needed to continue:
|
|
25
|
+
- the user's goal and requirements, and decisions made;
|
|
26
|
+
- files read or changed (exact paths) and what was changed;
|
|
27
|
+
- commands run and their important results or errors;
|
|
28
|
+
- the current state and what remains to be done.
|
|
29
|
+
Use short bullet points. Write in the language the user writes in."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def context_window(model: str, override: int = 0) -> int:
|
|
33
|
+
if override > 0:
|
|
34
|
+
return override
|
|
35
|
+
low = model.lower()
|
|
36
|
+
return next((size for key, size in CONTEXT_HINTS if key in low), DEFAULT_WINDOW)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def estimate_tokens(messages: list[dict[str, Any]]) -> int:
|
|
40
|
+
"""~3 characters per token: deliberately pessimistic (code and Cyrillic tokenize worse than English)."""
|
|
41
|
+
return sum(len(json.dumps(m, ensure_ascii=False)) for m in messages) // 3
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _user_turn_starts(messages: list[dict[str, Any]]) -> list[int]:
|
|
45
|
+
return [i for i, m in enumerate(messages)
|
|
46
|
+
if m.get("role") == "user" and not str(m.get("content", "")).startswith(SUMMARY_PREFIX)]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def prune(messages: list[dict[str, Any]], keep_turns: int = 2, min_chars: int = 1500) -> int:
|
|
50
|
+
"""Shrink big tool outputs older than the last ``keep_turns`` turns. Returns characters saved."""
|
|
51
|
+
starts = _user_turn_starts(messages)
|
|
52
|
+
limit = starts[-keep_turns] if len(starts) >= keep_turns else 0
|
|
53
|
+
saved = 0
|
|
54
|
+
for m in messages[:limit]:
|
|
55
|
+
content = m.get("content")
|
|
56
|
+
if m.get("role") == "tool" and isinstance(content, str) and len(content) > min_chars:
|
|
57
|
+
saved += len(content) - len(PRUNED)
|
|
58
|
+
m["content"] = PRUNED
|
|
59
|
+
return saved
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def split_point(messages: list[dict[str, Any]], keep_turns: int = 2) -> int:
|
|
63
|
+
"""Index where the kept tail starts (always at a user message, so tool calls stay paired)."""
|
|
64
|
+
starts = _user_turn_starts(messages)
|
|
65
|
+
if len(starts) <= keep_turns:
|
|
66
|
+
return starts[-1] if len(starts) > 1 else 0
|
|
67
|
+
return starts[-keep_turns]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def transcript(messages: list[dict[str, Any]], max_chars: int) -> str:
|
|
71
|
+
lines: list[str] = []
|
|
72
|
+
for m in messages:
|
|
73
|
+
role, content = m.get("role"), m.get("content") or ""
|
|
74
|
+
if role == "tool":
|
|
75
|
+
lines.append(f"[tool result] {str(content)[:600]}")
|
|
76
|
+
continue
|
|
77
|
+
if content:
|
|
78
|
+
lines.append(f"[{role}] {content}")
|
|
79
|
+
for call in m.get("tool_calls") or []:
|
|
80
|
+
fn = call.get("function", {})
|
|
81
|
+
lines.append(f"[{role} calls {fn.get('name')}] {str(fn.get('arguments', ''))[:400]}")
|
|
82
|
+
text = "\n".join(lines)
|
|
83
|
+
return text if len(text) <= max_chars else "…(older part cut)…\n" + text[-max_chars:]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def rebuild(summary: str, tail: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
87
|
+
return [
|
|
88
|
+
{"role": "user", "content": f"{SUMMARY_PREFIX}\n{summary.strip()}"},
|
|
89
|
+
{"role": "assistant", "content": tr("Понял контекст, продолжаю с того же места.")},
|
|
90
|
+
*tail,
|
|
91
|
+
]
|
anixcode/danger.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Spotting risky shell commands so the permission dialog can warn in red.
|
|
2
|
+
|
|
3
|
+
This is a safety net, not a sandbox: it catches common destructive commands in bash, cmd and
|
|
4
|
+
PowerShell. The real protection is that every command needs the user's approval.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
from .i18n import tr
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Risk:
|
|
16
|
+
danger: list[str] = field(default_factory=list) # destructive: shown in red, always asks
|
|
17
|
+
warnings: list[str] = field(default_factory=list) # worth a look: shown in yellow
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def dangerous(self) -> bool:
|
|
21
|
+
return bool(self.danger)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_I = re.IGNORECASE
|
|
25
|
+
DANGER: tuple[tuple[re.Pattern[str], str], ...] = tuple((re.compile(p, _I), why) for p, why in (
|
|
26
|
+
(r"\brm\s+(-[a-z]*[rf][a-z]*\s+)+", tr("удаление файлов без возврата (rm -r / -f)")),
|
|
27
|
+
(r"\brm\s+(?!-)", tr("удаление файлов (rm)")),
|
|
28
|
+
(r"\b(rmdir|rd)\b.*(/s|-r)", tr("удаление папки со всем содержимым")),
|
|
29
|
+
(r"\b(del|erase)\b", tr("удаление файлов (del)")),
|
|
30
|
+
(r"\bremove-item\b|\bri\s", tr("удаление файлов (Remove-Item)")),
|
|
31
|
+
(r"\bclear-content\b|\bclc\s", tr("очистка содержимого файлов")),
|
|
32
|
+
(r"\bformat(-volume)?\s+[a-z]:|\bformat\s+/|\bmkfs\b|\bdiskpart\b|\bclear-disk\b", tr("форматирование диска")),
|
|
33
|
+
(r"\bdd\s+.*\bof=", tr("запись на диск напрямую (dd)")),
|
|
34
|
+
(r">\s*/dev/(sd|nvme|disk)", tr("запись на диск напрямую")),
|
|
35
|
+
(r"\bgit\s+reset\s+--hard\b", tr("git reset --hard: несохранённые изменения пропадут")),
|
|
36
|
+
(r"\bgit\s+clean\s+-[a-z]*f", tr("git clean: удаление неотслеживаемых файлов")),
|
|
37
|
+
(r"\bgit\s+push\b.*(--force\b|\s-f\b|--force-with-lease)", tr("принудительный git push: можно затереть чужие коммиты")),
|
|
38
|
+
(r"\bgit\s+(checkout|restore)\s+(--\s+)?\.(\s|$)", tr("откат всех незакоммиченных изменений")),
|
|
39
|
+
(r"\bgit\s+branch\s+-D\b", tr("удаление ветки без проверки")),
|
|
40
|
+
(r"\b(curl|wget|iwr|invoke-webrequest|irm|invoke-restmethod)\b.*\|\s*(sh|bash|zsh|iex|invoke-expression|python)",
|
|
41
|
+
tr("скачивание и запуск скрипта из интернета")),
|
|
42
|
+
(r"\biex\b|\binvoke-expression\b", tr("выполнение произвольного кода (Invoke-Expression)")),
|
|
43
|
+
(r"\b(shutdown|reboot|poweroff|restart-computer|stop-computer)\b", tr("выключение или перезагрузка компьютера")),
|
|
44
|
+
(r"\breg\s+(delete|add)\b|\bremove-itemproperty\b|\bset-itemproperty\b.*hk(lm|cu)", tr("изменение реестра Windows")),
|
|
45
|
+
(r"\bset-executionpolicy\b", tr("изменение политики запуска скриптов")),
|
|
46
|
+
(r"\bbcdedit\b|\bcipher\s+/w\b|\bvssadmin\b.*delete", tr("системная утилита, опасная для данных")),
|
|
47
|
+
(r"\bchmod\s+-r\b|\bchmod\s+777\b|\bchown\s+-r\b", tr("массовая смена прав доступа")),
|
|
48
|
+
(r"\bsudo\b|\brunas\b|-verb\s+runas", tr("запуск с правами администратора")),
|
|
49
|
+
(r"\b(drop\s+(table|database|schema)|truncate\s+table)\b", tr("удаление данных из базы")),
|
|
50
|
+
(r"\b(npm|pnpm|yarn)\s+publish\b|\btwine\s+upload\b|\bcargo\s+publish\b", tr("публикация пакета")),
|
|
51
|
+
(r":\(\)\s*\{\s*:\|:&\s*\};:", tr("fork-бомба")),
|
|
52
|
+
(r"\b(taskkill\b.*/f|stop-process\b|kill\s+-9|killall|pkill)\b", tr("принудительное завершение процессов")),
|
|
53
|
+
))
|
|
54
|
+
WARN: tuple[tuple[re.Pattern[str], str], ...] = tuple((re.compile(p, _I), why) for p, why in (
|
|
55
|
+
(r"\b(mv|move|move-item|ren|rename-item)\b", tr("перемещение или переименование файлов")),
|
|
56
|
+
(r"(^|[^>])>\s*[^&\s|]", tr("перезапись файла через >")),
|
|
57
|
+
(r"\b(pip|pip3|npm|pnpm|yarn|cargo|choco|winget|apt|apt-get|brew)\s+(install|add|uninstall|remove)\b",
|
|
58
|
+
tr("установка или удаление пакетов")),
|
|
59
|
+
(r"\bgit\s+(push|commit\s+--amend|rebase)\b", tr("изменение истории или отправка в удалённый репозиторий")),
|
|
60
|
+
(r"\b(curl|wget|iwr|invoke-webrequest)\b", tr("обращение в интернет")),
|
|
61
|
+
))
|
|
62
|
+
_OUTSIDE = re.compile(
|
|
63
|
+
r"(\$env:userprofile|%userprofile%|\$home\b|~[/\\]|getfolderpath|\bdesktop\b|рабочий стол|"
|
|
64
|
+
r"(?<![\w.])[a-z]:[\\/]|(?<![\w.~])/(home|users|etc|usr|var|mnt|media|opt|root)\b)", _I)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def check_command(command: str, root: Path | None = None) -> Risk:
|
|
68
|
+
risk = Risk()
|
|
69
|
+
text = " ".join(command.split())
|
|
70
|
+
for pattern, why in DANGER:
|
|
71
|
+
if pattern.search(text) and why not in risk.danger:
|
|
72
|
+
risk.danger.append(why)
|
|
73
|
+
# "rm -rf" also matches plain "rm": keep the more specific reason only
|
|
74
|
+
if len([d for d in risk.danger if d.startswith(tr("удаление файлов"))]) > 1:
|
|
75
|
+
risk.danger = [d for d in risk.danger if d != tr("удаление файлов (rm)")]
|
|
76
|
+
for pattern, why in WARN:
|
|
77
|
+
if pattern.search(text) and why not in risk.warnings:
|
|
78
|
+
risk.warnings.append(why)
|
|
79
|
+
for m in _OUTSIDE.finditer(text):
|
|
80
|
+
hit = m.group(0)
|
|
81
|
+
if root is not None and str(root).lower() in text.lower()[max(0, m.start() - 1): m.start() + len(str(root)) + 1]:
|
|
82
|
+
continue # an absolute path into the project itself
|
|
83
|
+
risk.warnings.append(tr('затрагивает файлы вне папки проекта ({0})', hit.strip()))
|
|
84
|
+
break
|
|
85
|
+
return risk
|
anixcode/i18n.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Interface language: Russian (source strings) or English.
|
|
2
|
+
|
|
3
|
+
The language is chosen once at start-up: settings.json "language" ("ru" / "en"), else the
|
|
4
|
+
ANIXCODE_LANG environment variable, else the system language (Russian-speaking systems get Russian,
|
|
5
|
+
everyone else English). Changing it needs a restart.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import locale
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
LANGUAGES = {"ru": "Русский", "en": "English"}
|
|
16
|
+
_RU_FAMILY = {"ru", "uk", "be", "kk"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _config_dir() -> Path: # same rules as settings.config_dir(), without importing it (no cycles)
|
|
20
|
+
if env := os.environ.get("ANIXCODE_HOME"):
|
|
21
|
+
return Path(env)
|
|
22
|
+
if sys.platform == "win32":
|
|
23
|
+
return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "anixcode"
|
|
24
|
+
return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "anixcode"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def system_language() -> str:
|
|
28
|
+
code = ""
|
|
29
|
+
if sys.platform == "win32":
|
|
30
|
+
try:
|
|
31
|
+
import ctypes
|
|
32
|
+
from locale import windows_locale
|
|
33
|
+
|
|
34
|
+
code = windows_locale.get(ctypes.windll.kernel32.GetUserDefaultUILanguage(), "")
|
|
35
|
+
except (AttributeError, OSError, ImportError):
|
|
36
|
+
code = ""
|
|
37
|
+
if not code:
|
|
38
|
+
code = os.environ.get("LC_ALL") or os.environ.get("LC_MESSAGES") or os.environ.get("LANG") or ""
|
|
39
|
+
if not code:
|
|
40
|
+
try:
|
|
41
|
+
code = locale.getlocale()[0] or ""
|
|
42
|
+
except ValueError:
|
|
43
|
+
code = ""
|
|
44
|
+
return "ru" if code[:2].lower() in _RU_FAMILY else "en"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def detect_language() -> str:
|
|
48
|
+
try:
|
|
49
|
+
saved = json.loads((_config_dir() / "settings.json").read_text(encoding="utf-8")).get("language", "")
|
|
50
|
+
except (OSError, ValueError, AttributeError):
|
|
51
|
+
saved = ""
|
|
52
|
+
for candidate in (saved, os.environ.get("ANIXCODE_LANG", "")):
|
|
53
|
+
if candidate in LANGUAGES:
|
|
54
|
+
return candidate
|
|
55
|
+
return system_language()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
LANG = detect_language()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def tr(text: str, *args: object) -> str:
|
|
62
|
+
"""Translate a Russian source string; positional args fill {0}, {1}, …"""
|
|
63
|
+
if LANG == "en":
|
|
64
|
+
from .i18n_en import EN
|
|
65
|
+
|
|
66
|
+
text = EN.get(text, text)
|
|
67
|
+
return text.format(*args) if args else text
|