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/mentions.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""@file mentions: completion candidates and attaching mentioned files to a prompt."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
from .tools.base import IGNORE_DIRS, ToolContext, ToolError, is_binary, read_text, skip_dir
|
|
11
|
+
|
|
12
|
+
MENTION = re.compile(r"(?<![\w@])@((?:[^\s@\"']|\\ )+)")
|
|
13
|
+
MAX_FILE_LINES = 2000
|
|
14
|
+
MAX_FILE_CHARS = 80_000
|
|
15
|
+
MAX_TOTAL_CHARS = 250_000
|
|
16
|
+
MAX_INDEX = 20_000
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def index_files(root: Path) -> list[str]:
|
|
20
|
+
"""Project files and folders (relative, '/'-separated), for completion."""
|
|
21
|
+
out: list[str] = []
|
|
22
|
+
deadline = time.monotonic() + 5
|
|
23
|
+
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
|
24
|
+
if time.monotonic() > deadline:
|
|
25
|
+
break
|
|
26
|
+
dirnames[:] = sorted(d for d in dirnames if not d.startswith(".")
|
|
27
|
+
and not skip_dir(d, os.path.join(dirpath, d)))
|
|
28
|
+
rel_dir = Path(dirpath).relative_to(root).as_posix()
|
|
29
|
+
prefix = "" if rel_dir == "." else rel_dir + "/"
|
|
30
|
+
out.extend(prefix + d + "/" for d in dirnames)
|
|
31
|
+
out.extend(prefix + f for f in sorted(filenames) if not f.startswith("."))
|
|
32
|
+
if len(out) >= MAX_INDEX:
|
|
33
|
+
break
|
|
34
|
+
return out[:MAX_INDEX]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _subsequence(query: str, text: str) -> bool:
|
|
38
|
+
it = iter(text)
|
|
39
|
+
return all(ch in it for ch in query)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def rank_paths(paths: list[str], query: str, limit: int = 8) -> list[str]:
|
|
43
|
+
"""Best matches first: file name starts with query > name contains > path contains > fuzzy."""
|
|
44
|
+
q = query.lower().replace("\\", "/")
|
|
45
|
+
if not q:
|
|
46
|
+
top = [p for p in paths if "/" not in p.rstrip("/")]
|
|
47
|
+
return top[:limit]
|
|
48
|
+
scored: list[tuple[int, int, str]] = []
|
|
49
|
+
for p in paths:
|
|
50
|
+
low = p.lower()
|
|
51
|
+
name = low.rstrip("/").rsplit("/", 1)[-1]
|
|
52
|
+
if name.startswith(q):
|
|
53
|
+
score = 0
|
|
54
|
+
elif q in name:
|
|
55
|
+
score = 1
|
|
56
|
+
elif low.startswith(q):
|
|
57
|
+
score = 2
|
|
58
|
+
elif q in low:
|
|
59
|
+
score = 3
|
|
60
|
+
elif _subsequence(q, name):
|
|
61
|
+
score = 4
|
|
62
|
+
else:
|
|
63
|
+
continue
|
|
64
|
+
scored.append((score, len(p), p))
|
|
65
|
+
scored.sort()
|
|
66
|
+
return [p for _, _, p in scored[:limit]]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def find_mentions(text: str) -> list[str]:
|
|
70
|
+
return [m.group(1).replace("\\ ", " ").rstrip(".,;:!?)") for m in MENTION.finditer(text)]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def expand_mentions(text: str, ctx: ToolContext) -> tuple[str, list[str]]:
|
|
74
|
+
"""Append the content of every @mentioned file (or a listing of every @folder) to the prompt.
|
|
75
|
+
|
|
76
|
+
Fully attached files count as read, so the agent may edit them right away.
|
|
77
|
+
Returns (text for the model, attached relative paths).
|
|
78
|
+
"""
|
|
79
|
+
blocks: list[str] = []
|
|
80
|
+
attached: list[str] = []
|
|
81
|
+
total = 0
|
|
82
|
+
for raw in dict.fromkeys(find_mentions(text)):
|
|
83
|
+
try:
|
|
84
|
+
p = ctx.resolve(raw, must_exist=True)
|
|
85
|
+
except ToolError:
|
|
86
|
+
continue # not a path (an e-mail, a decorator…): leave the text alone
|
|
87
|
+
rel = ctx.rel(p)
|
|
88
|
+
if p.is_dir():
|
|
89
|
+
entries = sorted(os.listdir(p))[:200]
|
|
90
|
+
listing = "\n".join(e + ("/" if (p / e).is_dir() else "") for e in entries
|
|
91
|
+
if e not in IGNORE_DIRS)
|
|
92
|
+
block = f'<folder path="{rel}">\n{listing}\n</folder>'
|
|
93
|
+
else:
|
|
94
|
+
if is_binary(p) or p.stat().st_size > 5 * 1024 * 1024:
|
|
95
|
+
continue
|
|
96
|
+
lines = read_text(p).splitlines()
|
|
97
|
+
body_lines, size, cut = [], 0, False
|
|
98
|
+
for i, line in enumerate(lines[:MAX_FILE_LINES], 1):
|
|
99
|
+
size += len(line) + 8
|
|
100
|
+
if size > MAX_FILE_CHARS:
|
|
101
|
+
cut = True
|
|
102
|
+
break
|
|
103
|
+
body_lines.append(f"{i}\t{line}")
|
|
104
|
+
cut = cut or len(lines) > MAX_FILE_LINES
|
|
105
|
+
note = f"\n(first {len(body_lines)} of {len(lines)} lines; read the rest with the read tool)" if cut else ""
|
|
106
|
+
block = f'<file path="{rel}">\n' + "\n".join(body_lines) + f"{note}\n</file>"
|
|
107
|
+
if not cut:
|
|
108
|
+
ctx.mark_read(p)
|
|
109
|
+
if total + len(block) > MAX_TOTAL_CHARS:
|
|
110
|
+
break
|
|
111
|
+
total += len(block)
|
|
112
|
+
blocks.append(block)
|
|
113
|
+
attached.append(rel)
|
|
114
|
+
if not blocks:
|
|
115
|
+
return text, []
|
|
116
|
+
return text + "\n\nAttached by the user:\n" + "\n\n".join(blocks), attached
|
anixcode/projects.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Project folders: recent list, finding git repositories, cloning."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from .i18n import tr
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .tools.base import IGNORE_DIRS
|
|
12
|
+
|
|
13
|
+
MAX_RECENT = 15
|
|
14
|
+
# Never searched for repositories: system and huge folders.
|
|
15
|
+
SKIP_DIRS = frozenset({
|
|
16
|
+
"windows", "program files", "program files (x86)", "programdata", "$recycle.bin", "recovery", "perflogs",
|
|
17
|
+
"system volume information", "appdata", "library", "msocache", "$windows.~bt", "$windows.~ws", "intel",
|
|
18
|
+
"amd", "nvidia", "drivers", "steamlibrary", "steamapps", "games", "xboxgames", "proc", "sys", "dev", "run",
|
|
19
|
+
"snap", "boot", "usr", "lib", "lib64", "bin", "sbin", "etc", "var", "opt", "application data",
|
|
20
|
+
"local settings", "my documents", "cookies", "start menu",
|
|
21
|
+
})
|
|
22
|
+
GIT_URL = re.compile(r"^(https?://|git@|ssh://)\S+?(\.git)?/?$")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_unsuitable(path: Path) -> bool:
|
|
26
|
+
"""Folders where an agent should not start by default (home, drive root, Windows system folders)."""
|
|
27
|
+
p = path.resolve()
|
|
28
|
+
if p == Path.home().resolve() or p.parent == p:
|
|
29
|
+
return True
|
|
30
|
+
parts = [x.lower() for x in p.parts]
|
|
31
|
+
return sys.platform == "win32" and any(x in ("windows", "program files", "program files (x86)") for x in parts)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def is_git_repo(path: Path) -> bool:
|
|
35
|
+
return (path / ".git").exists()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def remember(recent: list[str], path: Path) -> list[str]:
|
|
39
|
+
"""Most recent first, no duplicates (case-insensitive on Windows), at most MAX_RECENT."""
|
|
40
|
+
p = str(path.resolve())
|
|
41
|
+
norm = (lambda s: s.lower()) if sys.platform == "win32" else (lambda s: s)
|
|
42
|
+
return [p, *[r for r in recent if norm(r) != norm(p)]][:MAX_RECENT]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def drives() -> list[Path]:
|
|
46
|
+
"""Disks to browse: C:, D:, … on Windows; / and mounted volumes elsewhere."""
|
|
47
|
+
if sys.platform == "win32":
|
|
48
|
+
try:
|
|
49
|
+
import ctypes
|
|
50
|
+
|
|
51
|
+
mask = ctypes.windll.kernel32.GetLogicalDrives() # no access to the disk itself: never hangs
|
|
52
|
+
except (OSError, AttributeError):
|
|
53
|
+
mask = 0
|
|
54
|
+
letters = [chr(65 + i) for i in range(26) if mask >> i & 1] or ["C"]
|
|
55
|
+
return [Path(f"{letter}:\\") for letter in letters if letter not in ("A", "B")]
|
|
56
|
+
out = [Path("/")]
|
|
57
|
+
for base in (Path("/Volumes"), Path("/mnt"), Path("/media") / os.environ.get("USER", "")):
|
|
58
|
+
try:
|
|
59
|
+
out += sorted(p for p in base.iterdir() if p.is_dir())
|
|
60
|
+
except OSError:
|
|
61
|
+
pass
|
|
62
|
+
return out
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def search_roots() -> list[Path]:
|
|
66
|
+
home = Path.home()
|
|
67
|
+
names = ("Desktop", "Documents", "Projects", "projects", "Code", "code", "dev", "Dev", "src", "repos",
|
|
68
|
+
"GitHub", "git", "source/repos", "work", "Рабочий стол", "Документы", "OneDrive/Desktop",
|
|
69
|
+
"OneDrive/Documents")
|
|
70
|
+
roots = [home / n for n in names if (home / n).is_dir()] or [home]
|
|
71
|
+
if sys.platform == "win32":
|
|
72
|
+
roots += drives() # C:\dev, D:\projects, …: system folders are skipped (SKIP_DIRS)
|
|
73
|
+
return roots
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_repos(roots: list[Path], max_depth: int = 3, limit: int = 200) -> list[Path]:
|
|
77
|
+
"""Git repositories under ``roots`` (does not descend into a repo once found)."""
|
|
78
|
+
found: list[Path] = []
|
|
79
|
+
seen: set[str] = set()
|
|
80
|
+
|
|
81
|
+
def walk(folder: Path, depth: int) -> None:
|
|
82
|
+
if len(found) >= limit:
|
|
83
|
+
return
|
|
84
|
+
key = os.path.normcase(str(folder))
|
|
85
|
+
if key in seen:
|
|
86
|
+
return
|
|
87
|
+
seen.add(key)
|
|
88
|
+
if is_git_repo(folder):
|
|
89
|
+
found.append(folder)
|
|
90
|
+
return
|
|
91
|
+
if depth >= max_depth:
|
|
92
|
+
return
|
|
93
|
+
try:
|
|
94
|
+
entries = sorted(os.scandir(folder), key=lambda e: e.name.lower())
|
|
95
|
+
except OSError:
|
|
96
|
+
return
|
|
97
|
+
for e in entries:
|
|
98
|
+
try:
|
|
99
|
+
if not e.is_dir(follow_symlinks=False):
|
|
100
|
+
continue
|
|
101
|
+
except OSError:
|
|
102
|
+
continue
|
|
103
|
+
if e.name.startswith((".", "$")) or e.name in IGNORE_DIRS or e.name.lower() in SKIP_DIRS:
|
|
104
|
+
continue
|
|
105
|
+
if depth == 0 and sys.platform == "win32" and e.name.lower() == "users":
|
|
106
|
+
continue # the home folder is searched separately
|
|
107
|
+
walk(Path(e.path), depth + 1)
|
|
108
|
+
|
|
109
|
+
for root in roots:
|
|
110
|
+
walk(root, 0)
|
|
111
|
+
found.sort(key=lambda p: _mtime(p), reverse=True)
|
|
112
|
+
return found
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _mtime(p: Path) -> float:
|
|
116
|
+
try:
|
|
117
|
+
return (p / ".git").stat().st_mtime
|
|
118
|
+
except OSError:
|
|
119
|
+
return 0.0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def repo_name(url: str) -> str:
|
|
123
|
+
name = re.split(r"[/\\:]", url.rstrip("/\\"))[-1]
|
|
124
|
+
return re.sub(r"\.git$", "", name) or "repo"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def clone(url: str, parent: Path) -> Path:
|
|
128
|
+
"""git clone ``url`` into parent/<name>. Raises RuntimeError with git's message."""
|
|
129
|
+
target = parent / repo_name(url)
|
|
130
|
+
if target.exists():
|
|
131
|
+
raise RuntimeError(tr('Папка уже существует: {0}', target))
|
|
132
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
133
|
+
try:
|
|
134
|
+
out = subprocess.run(["git", "clone", "--", url, str(target)], capture_output=True, text=True,
|
|
135
|
+
timeout=600, check=False)
|
|
136
|
+
except FileNotFoundError:
|
|
137
|
+
raise RuntimeError(tr("Git не установлен. Скачайте: https://git-scm.com")) from None
|
|
138
|
+
except subprocess.TimeoutExpired:
|
|
139
|
+
raise RuntimeError(tr("Клонирование заняло больше 10 минут и было остановлено.")) from None
|
|
140
|
+
if out.returncode != 0:
|
|
141
|
+
raise RuntimeError((out.stderr or out.stdout).strip()[-500:] or tr("git clone завершился с ошибкой"))
|
|
142
|
+
return target
|
anixcode/prompts.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""System prompts for the Build and Plan agents."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import platform
|
|
5
|
+
import subprocess
|
|
6
|
+
from datetime import date
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .tools import shell_name
|
|
10
|
+
|
|
11
|
+
BASE = """You are ANIX Code, an AI coding agent working inside the user's project.
|
|
12
|
+
|
|
13
|
+
# How you work
|
|
14
|
+
- Use tools to look before you act: ls, glob and grep to find things, read to see code.
|
|
15
|
+
- Always read a file before editing it. Make small, precise edits with the edit tool; use write only for new files or full rewrites.
|
|
16
|
+
- Never edit files through shell commands. Use bash for tests, builds, git and package managers.
|
|
17
|
+
- After changing code, run the relevant tests or a quick check when the project has them.
|
|
18
|
+
- Follow the existing style of the project. Do not add comments that only restate the code.
|
|
19
|
+
- Do not ask for confirmation in the chat before editing files or running commands: the app already asks
|
|
20
|
+
the user to approve each change and command. Just do the task. Ask a question only when the request
|
|
21
|
+
itself is unclear (which file? which behaviour?).
|
|
22
|
+
- Keep answers short and concrete. Use Markdown. Reply in the language the user writes in.
|
|
23
|
+
- When you finish, say briefly what you changed and how to check it.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
PLAN = """
|
|
27
|
+
# Mode: PLAN (read-only)
|
|
28
|
+
You are in Plan mode. You may only read and search. Do not try to edit files or run commands.
|
|
29
|
+
Study the code and reply with a clear step-by-step plan: what to change, in which files, and why.
|
|
30
|
+
The user will switch to Build mode (Tab) to carry it out.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
BUILD = """
|
|
34
|
+
# Mode: BUILD
|
|
35
|
+
You may read, edit files and run commands. Changes may need the user's approval.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _git_info(root: Path) -> str:
|
|
40
|
+
try:
|
|
41
|
+
out = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=root, capture_output=True,
|
|
42
|
+
text=True, timeout=3, check=False)
|
|
43
|
+
except (OSError, subprocess.SubprocessError):
|
|
44
|
+
return "no"
|
|
45
|
+
return f"yes (branch {out.stdout.strip()})" if out.returncode == 0 else "no"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def project_rules(root: Path) -> str:
|
|
49
|
+
for name in ("AGENTS.md", "CLAUDE.md", ".anixcode.md"):
|
|
50
|
+
p = root / name
|
|
51
|
+
if p.is_file():
|
|
52
|
+
try:
|
|
53
|
+
text = p.read_text(encoding="utf-8", errors="replace")[:20_000]
|
|
54
|
+
except OSError:
|
|
55
|
+
continue
|
|
56
|
+
return f"\n# Project rules from {name}\n{text}\n"
|
|
57
|
+
return ""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def system_prompt(root: Path, mode: str) -> str:
|
|
61
|
+
env = (f"\n# Environment\n- Project folder: {root}\n- OS: {platform.system()} {platform.release()}\n"
|
|
62
|
+
f"- Shell for bash tool: {shell_name()}\n- Git repository: {_git_info(root)}\n"
|
|
63
|
+
f"- Today: {date.today().isoformat()}\n")
|
|
64
|
+
return BASE + (PLAN if mode == "plan" else BUILD) + env + project_rules(root)
|
anixcode/providers.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Known OpenAI-compatible providers, plus the user's own ones (stored in settings.json)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from .i18n import tr
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from .settings import Settings
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Provider:
|
|
15
|
+
id: str
|
|
16
|
+
name: str
|
|
17
|
+
base_url: str
|
|
18
|
+
needs_key: bool = True
|
|
19
|
+
default_model: str = ""
|
|
20
|
+
key_url: str = "" # where to get a key
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def is_user(self) -> bool:
|
|
24
|
+
return self.id.startswith("user:")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
PROVIDERS: tuple[Provider, ...] = (
|
|
28
|
+
Provider("deepseek", "DeepSeek", "https://api.deepseek.com/v1", default_model="deepseek-chat",
|
|
29
|
+
key_url="https://platform.deepseek.com/api_keys"),
|
|
30
|
+
Provider("openai", "OpenAI", "https://api.openai.com/v1", key_url="https://platform.openai.com/api-keys"),
|
|
31
|
+
Provider("anthropic", "Anthropic (Claude)", "https://api.anthropic.com/v1/",
|
|
32
|
+
key_url="https://console.anthropic.com/settings/keys"),
|
|
33
|
+
Provider("gemini", "Google Gemini", "https://generativelanguage.googleapis.com/v1beta/openai/",
|
|
34
|
+
key_url="https://aistudio.google.com/apikey"),
|
|
35
|
+
Provider("groq", "Groq", "https://api.groq.com/openai/v1", key_url="https://console.groq.com/keys"),
|
|
36
|
+
Provider("anix", tr("ANIX Router (локально)"), "http://localhost:3001/v1", needs_key=False),
|
|
37
|
+
Provider("ollama", tr("Ollama (локально)"), "http://localhost:11434/v1", needs_key=False),
|
|
38
|
+
Provider("lmstudio", tr("LM Studio (локально)"), "http://localhost:1234/v1", needs_key=False),
|
|
39
|
+
Provider("custom", tr("Свой сервер (OpenAI-совместимый)"), "", needs_key=False),
|
|
40
|
+
)
|
|
41
|
+
BY_ID = {p.id: p for p in PROVIDERS}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def user_providers(settings: Settings | None) -> list[Provider]:
|
|
45
|
+
if settings is None:
|
|
46
|
+
return []
|
|
47
|
+
return [Provider(d["id"], d["name"], d["base_url"], needs_key=False) for d in settings.custom_providers]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def all_providers(settings: Settings | None) -> list[Provider]:
|
|
51
|
+
"""The user's own providers first, then the built-in ones."""
|
|
52
|
+
return [*user_providers(settings), *PROVIDERS]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def get(provider_id: str, settings: Settings | None = None) -> Provider:
|
|
56
|
+
for p in user_providers(settings):
|
|
57
|
+
if p.id == provider_id:
|
|
58
|
+
return p
|
|
59
|
+
return BY_ID.get(provider_id) or BY_ID["custom"]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def make_id(name: str, existing: set[str]) -> str:
|
|
63
|
+
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") or "provider"
|
|
64
|
+
candidate, n = f"user:{slug}", 2
|
|
65
|
+
while candidate in existing:
|
|
66
|
+
candidate, n = f"user:{slug}-{n}", n + 1
|
|
67
|
+
return candidate
|
anixcode/settings.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Settings (settings.json) and API keys (auth.json, readable only by you)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import dataclasses
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
APP = "anixcode"
|
|
13
|
+
PERMISSION_VALUES = ("ask", "allow", "deny")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def config_dir() -> Path:
|
|
17
|
+
if env := os.environ.get("ANIXCODE_HOME"):
|
|
18
|
+
return Path(env)
|
|
19
|
+
if sys.platform == "win32":
|
|
20
|
+
return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / APP
|
|
21
|
+
return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / APP
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Settings:
|
|
26
|
+
provider: str = ""
|
|
27
|
+
model: str = ""
|
|
28
|
+
theme: str = "anix"
|
|
29
|
+
animations: bool = True
|
|
30
|
+
# "ask" | "allow" | "deny" for tools that change things. Reading is always allowed.
|
|
31
|
+
permissions: dict[str, str] = field(default_factory=lambda: {"edit": "ask", "exec": "ask"})
|
|
32
|
+
max_steps: int = 50
|
|
33
|
+
full_access: bool = False # the agent edits and runs commands without asking
|
|
34
|
+
language: str = "" # "ru" | "en"; empty = system language (applied on restart)
|
|
35
|
+
context_window: int = 0 # model context size in tokens; 0 = guess from the model name
|
|
36
|
+
airpc: bool = True # report activity to AI-RPC (Discord status) when it is running
|
|
37
|
+
# Your own OpenAI-compatible providers: [{"id": "user:...", "name": ..., "base_url": ...}]
|
|
38
|
+
custom_providers: list[dict[str, Any]] = field(default_factory=list)
|
|
39
|
+
recent_projects: list[str] = field(default_factory=list)
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def ready(self) -> bool:
|
|
43
|
+
return bool(self.provider and self.model)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _write_private(path: Path, data: dict[str, Any]) -> None:
|
|
47
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
tmp = path.with_suffix(".tmp")
|
|
49
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
50
|
+
try:
|
|
51
|
+
tmp.chmod(0o600)
|
|
52
|
+
except OSError:
|
|
53
|
+
pass
|
|
54
|
+
os.replace(tmp, path)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def load_settings(base: Path | None = None) -> Settings:
|
|
58
|
+
path = (base or config_dir()) / "settings.json"
|
|
59
|
+
try:
|
|
60
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
61
|
+
except (OSError, ValueError):
|
|
62
|
+
return Settings()
|
|
63
|
+
known = {f.name for f in dataclasses.fields(Settings)}
|
|
64
|
+
if raw.get("theme") == "tokyo-night" and "animations" not in raw:
|
|
65
|
+
raw["theme"] = "anix" # 0.1.0 saved its old default theme; switch to the new default once
|
|
66
|
+
if raw.get("theme") == "opencode":
|
|
67
|
+
raw["theme"] = "noir" # renamed in 0.8
|
|
68
|
+
s = Settings(**{k: v for k, v in raw.items() if k in known})
|
|
69
|
+
s.permissions = {k: v for k, v in dict(s.permissions).items() if v in PERMISSION_VALUES}
|
|
70
|
+
s.custom_providers = [
|
|
71
|
+
d for d in (s.custom_providers if isinstance(s.custom_providers, list) else [])
|
|
72
|
+
if isinstance(d, dict) and str(d.get("id", "")).startswith("user:")
|
|
73
|
+
and isinstance(d.get("name"), str) and isinstance(d.get("base_url"), str)
|
|
74
|
+
]
|
|
75
|
+
s.recent_projects = [p for p in (s.recent_projects if isinstance(s.recent_projects, list) else [])
|
|
76
|
+
if isinstance(p, str)]
|
|
77
|
+
return s
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def save_settings(s: Settings, base: Path | None = None) -> None:
|
|
81
|
+
_write_private((base or config_dir()) / "settings.json", dataclasses.asdict(s))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class Credentials:
|
|
86
|
+
api_key: str = ""
|
|
87
|
+
base_url: str = "" # overrides the provider default (required for "custom")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def load_auth(base: Path | None = None) -> dict[str, Credentials]:
|
|
91
|
+
path = (base or config_dir()) / "auth.json"
|
|
92
|
+
try:
|
|
93
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
94
|
+
except (OSError, ValueError):
|
|
95
|
+
return {}
|
|
96
|
+
return {k: Credentials(**{f: str(v.get(f, "")) for f in ("api_key", "base_url")})
|
|
97
|
+
for k, v in raw.items() if isinstance(v, dict)}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def save_auth(auth: dict[str, Credentials], base: Path | None = None) -> None:
|
|
101
|
+
_write_private((base or config_dir()) / "auth.json", {k: dataclasses.asdict(v) for k, v in auth.items()})
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def mask(key: str) -> str:
|
|
105
|
+
return f"{key[:4]}…{key[-4:]}" if len(key) > 12 else "•" * len(key)
|
anixcode/storage.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Sessions and their messages in SQLite."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from .i18n import tr
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sqlite3
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Session:
|
|
17
|
+
id: str
|
|
18
|
+
cwd: str
|
|
19
|
+
title: str = tr("Новая сессия")
|
|
20
|
+
model: str = ""
|
|
21
|
+
created: float = field(default_factory=time.time)
|
|
22
|
+
updated: float = field(default_factory=time.time)
|
|
23
|
+
tokens_in: int = 0
|
|
24
|
+
tokens_out: int = 0
|
|
25
|
+
messages: list[dict[str, Any]] = field(default_factory=list)
|
|
26
|
+
store: Store | None = field(default=None, repr=False, compare=False)
|
|
27
|
+
|
|
28
|
+
def add(self, message: dict[str, Any]) -> None:
|
|
29
|
+
self.messages.append(message)
|
|
30
|
+
if self.title == tr("Новая сессия") and message.get("role") == "user":
|
|
31
|
+
text = " ".join(str(message.get("content", "")).split())
|
|
32
|
+
self.title = text[:60] + ("…" if len(text) > 60 else "")
|
|
33
|
+
self.updated = time.time()
|
|
34
|
+
if self.store:
|
|
35
|
+
self.store.append(self, message)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Store:
|
|
39
|
+
def __init__(self, path: Path) -> None:
|
|
40
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
self._db = sqlite3.connect(str(path), check_same_thread=False)
|
|
42
|
+
self._lock = threading.Lock()
|
|
43
|
+
with self._lock, self._db:
|
|
44
|
+
self._db.executescript("""
|
|
45
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
46
|
+
id TEXT PRIMARY KEY, cwd TEXT, title TEXT, model TEXT,
|
|
47
|
+
created REAL, updated REAL, tokens_in INT DEFAULT 0, tokens_out INT DEFAULT 0);
|
|
48
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
49
|
+
session_id TEXT, idx INT, data TEXT, PRIMARY KEY (session_id, idx));
|
|
50
|
+
CREATE TABLE IF NOT EXISTS snapshots (
|
|
51
|
+
session_id TEXT, turn INT, path TEXT, existed INT, content BLOB,
|
|
52
|
+
PRIMARY KEY (session_id, turn, path));
|
|
53
|
+
""")
|
|
54
|
+
|
|
55
|
+
def create(self, cwd: str, model: str = "") -> Session:
|
|
56
|
+
s = Session(id=uuid.uuid4().hex, cwd=cwd, model=model, store=self)
|
|
57
|
+
self._save_session(s)
|
|
58
|
+
return s
|
|
59
|
+
|
|
60
|
+
def _save_session(self, s: Session) -> None:
|
|
61
|
+
with self._lock, self._db:
|
|
62
|
+
self._db.execute(
|
|
63
|
+
"INSERT INTO sessions VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET "
|
|
64
|
+
"title=excluded.title, model=excluded.model, updated=excluded.updated, "
|
|
65
|
+
"tokens_in=excluded.tokens_in, tokens_out=excluded.tokens_out",
|
|
66
|
+
(s.id, s.cwd, s.title, s.model, s.created, s.updated, s.tokens_in, s.tokens_out))
|
|
67
|
+
|
|
68
|
+
def append(self, s: Session, message: dict[str, Any]) -> None:
|
|
69
|
+
with self._lock, self._db:
|
|
70
|
+
self._db.execute("INSERT OR REPLACE INTO messages VALUES (?,?,?)",
|
|
71
|
+
(s.id, len(s.messages) - 1, json.dumps(message, ensure_ascii=False)))
|
|
72
|
+
self._save_session(s)
|
|
73
|
+
|
|
74
|
+
def replace_messages(self, s: Session) -> None:
|
|
75
|
+
"""Rewrite the whole history (after compaction)."""
|
|
76
|
+
with self._lock, self._db:
|
|
77
|
+
self._db.execute("DELETE FROM messages WHERE session_id = ?", (s.id,))
|
|
78
|
+
self._db.executemany("INSERT INTO messages VALUES (?,?,?)",
|
|
79
|
+
[(s.id, i, json.dumps(m, ensure_ascii=False)) for i, m in enumerate(s.messages)])
|
|
80
|
+
self._save_session(s)
|
|
81
|
+
|
|
82
|
+
# -- file snapshots for /undo ---------------------------------------------------
|
|
83
|
+
def add_snapshot(self, session_id: str, turn: int, path: str, existed: bool, content: bytes) -> None:
|
|
84
|
+
with self._lock, self._db: # first snapshot of a file within a turn wins
|
|
85
|
+
self._db.execute("INSERT OR IGNORE INTO snapshots VALUES (?,?,?,?,?)",
|
|
86
|
+
(session_id, turn, path, int(existed), content))
|
|
87
|
+
|
|
88
|
+
def last_snapshot_turn(self, session_id: str) -> tuple[int, list[tuple[str, bool, bytes]]] | None:
|
|
89
|
+
with self._lock:
|
|
90
|
+
row = self._db.execute("SELECT MAX(turn) FROM snapshots WHERE session_id = ?", (session_id,)).fetchone()
|
|
91
|
+
if not row or row[0] is None:
|
|
92
|
+
return None
|
|
93
|
+
files = self._db.execute("SELECT path, existed, content FROM snapshots WHERE session_id = ? AND turn = ?",
|
|
94
|
+
(session_id, row[0])).fetchall()
|
|
95
|
+
return row[0], [(p, bool(e), c) for p, e, c in files]
|
|
96
|
+
|
|
97
|
+
def drop_snapshot_turn(self, session_id: str, turn: int) -> None:
|
|
98
|
+
with self._lock, self._db:
|
|
99
|
+
self._db.execute("DELETE FROM snapshots WHERE session_id = ? AND turn = ?", (session_id, turn))
|
|
100
|
+
|
|
101
|
+
def touch(self, s: Session) -> None:
|
|
102
|
+
self._save_session(s)
|
|
103
|
+
|
|
104
|
+
def list(self, cwd: str | None = None, limit: int = 50) -> list[Session]:
|
|
105
|
+
q = "SELECT id, cwd, title, model, created, updated, tokens_in, tokens_out FROM sessions"
|
|
106
|
+
params: tuple[Any, ...] = ()
|
|
107
|
+
if cwd:
|
|
108
|
+
q += " WHERE cwd = ?"
|
|
109
|
+
params = (cwd,)
|
|
110
|
+
q += " ORDER BY updated DESC LIMIT ?"
|
|
111
|
+
with self._lock:
|
|
112
|
+
rows = self._db.execute(q, (*params, limit)).fetchall()
|
|
113
|
+
return [Session(*row, store=self) for row in rows]
|
|
114
|
+
|
|
115
|
+
def load(self, session_id: str) -> Session | None:
|
|
116
|
+
with self._lock:
|
|
117
|
+
row = self._db.execute("SELECT id, cwd, title, model, created, updated, tokens_in, tokens_out "
|
|
118
|
+
"FROM sessions WHERE id = ?", (session_id,)).fetchone()
|
|
119
|
+
if not row:
|
|
120
|
+
return None
|
|
121
|
+
msgs = self._db.execute("SELECT data FROM messages WHERE session_id = ? ORDER BY idx",
|
|
122
|
+
(session_id,)).fetchall()
|
|
123
|
+
s = Session(*row, store=self)
|
|
124
|
+
s.messages = [json.loads(m[0]) for m in msgs]
|
|
125
|
+
return s
|
|
126
|
+
|
|
127
|
+
def close(self) -> None:
|
|
128
|
+
with self._lock:
|
|
129
|
+
self._db.close()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""All tools available to the agent."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .base import Tool, ToolContext, ToolError, ToolResult
|
|
5
|
+
from .files import EditTool, GlobTool, LsTool, ReadTool, WriteTool
|
|
6
|
+
from .search import GrepTool
|
|
7
|
+
from .shell import BashTool, shell_name
|
|
8
|
+
|
|
9
|
+
ALL_TOOLS: tuple[type[Tool], ...] = (ReadTool, LsTool, GlobTool, GrepTool, EditTool, WriteTool, BashTool)
|
|
10
|
+
|
|
11
|
+
__all__ = ["Tool", "ToolContext", "ToolError", "ToolResult", "ALL_TOOLS", "default_tools", "shell_name"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def default_tools() -> dict[str, Tool]:
|
|
15
|
+
return {cls.name: cls() for cls in ALL_TOOLS}
|