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/__init__.py
ADDED
anixcode/__main__.py
ADDED
anixcode/agent.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""The agent loop: model -> tool calls -> results -> model … until it answers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from .i18n import tr
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Literal, Protocol
|
|
12
|
+
|
|
13
|
+
from . import compaction
|
|
14
|
+
from .airpc import AirpcReporter
|
|
15
|
+
from .checkpoints import Checkpoints
|
|
16
|
+
from .danger import check_command
|
|
17
|
+
from .mentions import expand_mentions
|
|
18
|
+
from .llm import Completion, LLMError, ReasoningDelta, Retrying, TextDelta, ToolCall, is_context_overflow
|
|
19
|
+
from .prompts import system_prompt
|
|
20
|
+
from .settings import Settings
|
|
21
|
+
from .storage import Session
|
|
22
|
+
from .tools import Tool, ToolContext, ToolError, ToolResult, default_tools
|
|
23
|
+
|
|
24
|
+
Decision = Literal["once", "always", "deny"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ChatClient(Protocol):
|
|
28
|
+
def stream_chat(self, model: str, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None
|
|
29
|
+
) -> AsyncIterator[TextDelta | ReasoningDelta | Completion]: ...
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class PermissionRequest:
|
|
34
|
+
tool: str
|
|
35
|
+
kind: str
|
|
36
|
+
title: str
|
|
37
|
+
preview: str | None # diff or command
|
|
38
|
+
danger: list[str] = field(default_factory=list) # destructive: highlighted in red
|
|
39
|
+
warnings: list[str] = field(default_factory=list)
|
|
40
|
+
call_id: str = ""
|
|
41
|
+
feedback: str = "" # what the user typed instead of approving (sent to the model)
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def dangerous(self) -> bool:
|
|
45
|
+
return bool(self.danger)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class ToolStarted:
|
|
50
|
+
call_id: str
|
|
51
|
+
tool: str
|
|
52
|
+
title: str
|
|
53
|
+
kind: str
|
|
54
|
+
dangerous: bool = False
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class Attached:
|
|
59
|
+
paths: list[str]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class ToolFinished:
|
|
64
|
+
call_id: str
|
|
65
|
+
tool: str
|
|
66
|
+
result: ToolResult
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class StepFinished:
|
|
71
|
+
tokens_in: int
|
|
72
|
+
tokens_out: int
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class Done:
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class AgentError:
|
|
82
|
+
message: str
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class Compacting:
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class Compacted:
|
|
92
|
+
before: int # estimated tokens
|
|
93
|
+
after: int
|
|
94
|
+
summarized: bool
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class UndoResult:
|
|
99
|
+
restored: list[str]
|
|
100
|
+
deleted: list[str]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
AgentEvent = (Attached | TextDelta | ReasoningDelta | Retrying | ToolStarted | ToolFinished | StepFinished | Done | AgentError
|
|
104
|
+
| Compacting | Compacted)
|
|
105
|
+
AskPermission = Callable[[PermissionRequest], Awaitable[Decision]]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
async def _deny_all(_req: PermissionRequest) -> Decision:
|
|
109
|
+
return "deny"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class Agent:
|
|
113
|
+
def __init__(self, client: ChatClient, model: str, root: Path, settings: Settings | None = None,
|
|
114
|
+
ask: AskPermission | None = None, tools: dict[str, Tool] | None = None,
|
|
115
|
+
reporter: AirpcReporter | None = None, provider: str = "") -> None:
|
|
116
|
+
self.client = client
|
|
117
|
+
self.model = model
|
|
118
|
+
self.provider = provider
|
|
119
|
+
self.settings = settings or Settings()
|
|
120
|
+
self.ask = ask or _deny_all
|
|
121
|
+
self.tools = tools or default_tools()
|
|
122
|
+
self.ctx = ToolContext(root.resolve())
|
|
123
|
+
self.mode: Literal["build", "plan"] = "build"
|
|
124
|
+
self._always: set[str] = set() # kinds approved for this session
|
|
125
|
+
self.reporter = reporter or AirpcReporter(enabled=False)
|
|
126
|
+
self._checkpoints: dict[str, Checkpoints] = {}
|
|
127
|
+
self.last_args: dict[str, Any] = {} # arguments of the tool call being started (for the UI)
|
|
128
|
+
|
|
129
|
+
# -- context window --------------------------------------------------------------
|
|
130
|
+
@property
|
|
131
|
+
def window(self) -> int:
|
|
132
|
+
return compaction.context_window(self.model, self.settings.context_window)
|
|
133
|
+
|
|
134
|
+
def context_usage(self, session: Session) -> float:
|
|
135
|
+
"""0..1: how full the context is (estimate)."""
|
|
136
|
+
return min(1.0, compaction.estimate_tokens(session.messages) / self.window)
|
|
137
|
+
|
|
138
|
+
async def compact(self, session: Session, force: bool = False) -> Compacted | None:
|
|
139
|
+
"""Prune old tool outputs; summarize old turns if still too big (or if forced)."""
|
|
140
|
+
before = compaction.estimate_tokens(session.messages)
|
|
141
|
+
compaction.prune(session.messages)
|
|
142
|
+
after = compaction.estimate_tokens(session.messages)
|
|
143
|
+
summarized = False
|
|
144
|
+
if force or after > self.window * compaction.COMPACT_AT * 0.75:
|
|
145
|
+
cut = compaction.split_point(session.messages)
|
|
146
|
+
if cut > 0:
|
|
147
|
+
head, tail = session.messages[:cut], session.messages[cut:]
|
|
148
|
+
summary = await self._summarize(head)
|
|
149
|
+
session.messages[:] = compaction.rebuild(summary, tail)
|
|
150
|
+
summarized = True
|
|
151
|
+
after = compaction.estimate_tokens(session.messages)
|
|
152
|
+
if after == before:
|
|
153
|
+
return None
|
|
154
|
+
if session.store:
|
|
155
|
+
session.store.replace_messages(session)
|
|
156
|
+
return Compacted(before, after, summarized)
|
|
157
|
+
|
|
158
|
+
async def _summarize(self, head: list[dict[str, Any]]) -> str:
|
|
159
|
+
text = compaction.transcript(head, max_chars=int(self.window * 3 * 0.6))
|
|
160
|
+
messages = [{"role": "system", "content": compaction.SUMMARIZE_PROMPT},
|
|
161
|
+
{"role": "user", "content": f"Conversation to summarize:\n\n{text}"}]
|
|
162
|
+
result = ""
|
|
163
|
+
async for ev in self.client.stream_chat(self.model, messages, None):
|
|
164
|
+
if isinstance(ev, Completion):
|
|
165
|
+
result = ev.text
|
|
166
|
+
if not result.strip():
|
|
167
|
+
raise LLMError(tr("Не удалось сжать историю: модель вернула пустую сводку."))
|
|
168
|
+
return result
|
|
169
|
+
|
|
170
|
+
def redo(self, session: Session) -> UndoResult | None:
|
|
171
|
+
done = self.checkpoints(session).redo_last()
|
|
172
|
+
if done is None:
|
|
173
|
+
return None
|
|
174
|
+
restored, deleted = done
|
|
175
|
+
for p in (*restored, *deleted):
|
|
176
|
+
self.ctx.read_files.pop(p, None)
|
|
177
|
+
rel = [self.ctx.rel(p) for p in restored], [self.ctx.rel(p) for p in deleted]
|
|
178
|
+
session.add({"role": "user", "content": "[The user re-applied the file changes they had undone: "
|
|
179
|
+
f"{', '.join(rel[0] + rel[1])}. Re-read them before editing.]"})
|
|
180
|
+
return UndoResult(*rel)
|
|
181
|
+
|
|
182
|
+
# -- undo ------------------------------------------------------------------------
|
|
183
|
+
def checkpoints(self, session: Session) -> Checkpoints:
|
|
184
|
+
if session.id not in self._checkpoints:
|
|
185
|
+
self._checkpoints[session.id] = Checkpoints(session)
|
|
186
|
+
return self._checkpoints[session.id]
|
|
187
|
+
|
|
188
|
+
def undo(self, session: Session) -> UndoResult | None:
|
|
189
|
+
"""Put back the files changed by the latest agent turn that changed files."""
|
|
190
|
+
done = self.checkpoints(session).undo_last()
|
|
191
|
+
if done is None:
|
|
192
|
+
return None
|
|
193
|
+
restored, deleted = done
|
|
194
|
+
for p in (*restored, *deleted):
|
|
195
|
+
self.ctx.read_files.pop(p, None) # force a fresh read before the next edit
|
|
196
|
+
rel = [self.ctx.rel(p) for p in restored], [self.ctx.rel(p) for p in deleted]
|
|
197
|
+
note = ("[The user undid the file changes from your previous turn. These files are back to their "
|
|
198
|
+
f"earlier state: {', '.join(rel[0] + rel[1])}. Re-read them before editing again.]")
|
|
199
|
+
session.add({"role": "user", "content": note})
|
|
200
|
+
return UndoResult(*rel)
|
|
201
|
+
|
|
202
|
+
def tool_schemas(self) -> list[dict[str, Any]]:
|
|
203
|
+
return [t.schema() for t in self.tools.values() if self.mode == "build" or t.kind == "read"]
|
|
204
|
+
|
|
205
|
+
async def run(self, session: Session, user_text: str) -> AsyncIterator[AgentEvent]:
|
|
206
|
+
content, attached = expand_mentions(user_text, self.ctx)
|
|
207
|
+
session.add({"role": "user", "content": content})
|
|
208
|
+
if attached:
|
|
209
|
+
yield Attached(attached)
|
|
210
|
+
cps = self.checkpoints(session)
|
|
211
|
+
turn = cps.new_turn()
|
|
212
|
+
self.ctx.before_write = lambda p: cps.snapshot(turn, p)
|
|
213
|
+
self.reporter.send("start", model=self.model, provider=self.provider)
|
|
214
|
+
try:
|
|
215
|
+
async for event in self._loop(session):
|
|
216
|
+
yield event
|
|
217
|
+
finally:
|
|
218
|
+
self.reporter.send("end", model=self.model, tokens=session.tokens_out or None)
|
|
219
|
+
|
|
220
|
+
async def _loop(self, session: Session) -> AsyncIterator[AgentEvent]:
|
|
221
|
+
system = {"role": "system", "content": system_prompt(self.ctx.root, self.mode)}
|
|
222
|
+
overflow_retried = False
|
|
223
|
+
gave_up = False # compaction could not shrink the history: don't retry every step
|
|
224
|
+
for _step in range(self.settings.max_steps):
|
|
225
|
+
limit = self.window * compaction.COMPACT_AT
|
|
226
|
+
if not gave_up and compaction.estimate_tokens(session.messages) > limit:
|
|
227
|
+
yield Compacting()
|
|
228
|
+
try:
|
|
229
|
+
result = await self.compact(session)
|
|
230
|
+
except LLMError as e:
|
|
231
|
+
yield AgentError(str(e))
|
|
232
|
+
return
|
|
233
|
+
if result:
|
|
234
|
+
yield result
|
|
235
|
+
if result is None or result.after > limit:
|
|
236
|
+
gave_up = True
|
|
237
|
+
messages = [system, *session.messages]
|
|
238
|
+
completion: Completion | None = None
|
|
239
|
+
text_so_far: list[str] = []
|
|
240
|
+
last_report = 0.0
|
|
241
|
+
try:
|
|
242
|
+
async for ev in self.client.stream_chat(self.model, messages, self.tool_schemas()):
|
|
243
|
+
if isinstance(ev, Completion):
|
|
244
|
+
completion = ev
|
|
245
|
+
continue
|
|
246
|
+
if isinstance(ev, TextDelta):
|
|
247
|
+
text_so_far.append(ev.text)
|
|
248
|
+
if time.monotonic() - last_report > 2:
|
|
249
|
+
last_report = time.monotonic()
|
|
250
|
+
approx = sum(map(len, text_so_far)) // 4
|
|
251
|
+
self.reporter.send("progress", model=self.model, tokens=session.tokens_out + approx)
|
|
252
|
+
yield ev
|
|
253
|
+
except LLMError as e:
|
|
254
|
+
if is_context_overflow(e) and not overflow_retried and not text_so_far:
|
|
255
|
+
overflow_retried = True # the window guess was too big: compact hard and retry once
|
|
256
|
+
yield Compacting()
|
|
257
|
+
try:
|
|
258
|
+
result = await self.compact(session, force=True)
|
|
259
|
+
except LLMError as e2:
|
|
260
|
+
yield AgentError(str(e2))
|
|
261
|
+
return
|
|
262
|
+
if result:
|
|
263
|
+
yield result
|
|
264
|
+
continue
|
|
265
|
+
yield AgentError(str(e))
|
|
266
|
+
return
|
|
267
|
+
except asyncio.CancelledError:
|
|
268
|
+
if text_so_far:
|
|
269
|
+
session.add({"role": "assistant", "content": "".join(text_so_far) + "\n\n[interrupted]"})
|
|
270
|
+
raise
|
|
271
|
+
if completion is None:
|
|
272
|
+
yield AgentError(tr("Модель ничего не ответила."))
|
|
273
|
+
return
|
|
274
|
+
if completion.usage:
|
|
275
|
+
session.tokens_in += completion.usage.prompt
|
|
276
|
+
session.tokens_out += completion.usage.completion
|
|
277
|
+
message: dict[str, Any] = {"role": "assistant", "content": completion.text or None}
|
|
278
|
+
if completion.tool_calls:
|
|
279
|
+
message["tool_calls"] = [
|
|
280
|
+
{"id": c.id, "type": "function", "function": {"name": c.name, "arguments": c.arguments or "{}"}}
|
|
281
|
+
for c in completion.tool_calls
|
|
282
|
+
]
|
|
283
|
+
elif not completion.text:
|
|
284
|
+
message["content"] = ""
|
|
285
|
+
session.add(message)
|
|
286
|
+
if session.store:
|
|
287
|
+
session.store.touch(session)
|
|
288
|
+
yield StepFinished(session.tokens_in, session.tokens_out)
|
|
289
|
+
if not completion.tool_calls:
|
|
290
|
+
yield Done()
|
|
291
|
+
return
|
|
292
|
+
|
|
293
|
+
pending = [c.id for c in completion.tool_calls]
|
|
294
|
+
try:
|
|
295
|
+
for call in completion.tool_calls:
|
|
296
|
+
async for ev in self._execute(call, session):
|
|
297
|
+
yield ev
|
|
298
|
+
pending.remove(call.id)
|
|
299
|
+
finally:
|
|
300
|
+
# Every tool call needs an answer, or the next request is rejected by the API.
|
|
301
|
+
for call_id in pending:
|
|
302
|
+
session.add({"role": "tool", "tool_call_id": call_id, "content": "Cancelled by the user."})
|
|
303
|
+
yield AgentError(tr('Агент сделал {0} шагов и остановился. Напишите «продолжай».', self.settings.max_steps))
|
|
304
|
+
|
|
305
|
+
async def _execute(self, call: ToolCall, session: Session) -> AsyncIterator[AgentEvent]:
|
|
306
|
+
tool = self.tools.get(call.name)
|
|
307
|
+
try:
|
|
308
|
+
args = call.parse_args()
|
|
309
|
+
except (ValueError, json.JSONDecodeError) as e:
|
|
310
|
+
args, bad_args = {}, str(e)
|
|
311
|
+
else:
|
|
312
|
+
bad_args = ""
|
|
313
|
+
title = tool.title(args) if tool else call.name
|
|
314
|
+
self.last_args = args
|
|
315
|
+
risk = check_command(str(args.get("command", "")), self.ctx.root) if call.name == "bash" else None
|
|
316
|
+
yield ToolStarted(call.id, call.name, title, tool.kind if tool else "read", bool(risk and risk.dangerous))
|
|
317
|
+
if tool is not None:
|
|
318
|
+
self.reporter.send("tool", model=self.model)
|
|
319
|
+
result = await self._run_tool(tool, call, args, bad_args, risk)
|
|
320
|
+
session.add({"role": "tool", "tool_call_id": call.id, "content": result.output})
|
|
321
|
+
yield ToolFinished(call.id, call.name, result)
|
|
322
|
+
|
|
323
|
+
async def _run_tool(self, tool: Tool | None, call: ToolCall, args: dict[str, Any], bad_args: str,
|
|
324
|
+
risk: Any = None) -> ToolResult:
|
|
325
|
+
if tool is None:
|
|
326
|
+
return ToolResult(f"Unknown tool '{call.name}'. Available: {', '.join(self.tools)}", error=True)
|
|
327
|
+
if bad_args:
|
|
328
|
+
return ToolResult(f"Invalid JSON arguments: {bad_args}", error=True)
|
|
329
|
+
if tool.kind != "read":
|
|
330
|
+
if self.mode == "plan":
|
|
331
|
+
return ToolResult("Not allowed in Plan mode. Describe the change instead; the user will switch "
|
|
332
|
+
"to Build mode.", error=True)
|
|
333
|
+
policy = "allow" if self.settings.full_access else self.settings.permissions.get(tool.kind, "ask")
|
|
334
|
+
if policy == "deny":
|
|
335
|
+
return ToolResult("This action is disabled in the settings.", error=True)
|
|
336
|
+
if policy == "ask" and tool.kind not in self._always:
|
|
337
|
+
try:
|
|
338
|
+
preview = tool.preview(args, self.ctx)
|
|
339
|
+
except Exception:
|
|
340
|
+
preview = None
|
|
341
|
+
req = PermissionRequest(tool.name, tool.kind, tool.title(args), preview,
|
|
342
|
+
danger=list(risk.danger) if risk else [],
|
|
343
|
+
warnings=list(risk.warnings) if risk else [], call_id=call.id)
|
|
344
|
+
decision = await self.ask(req)
|
|
345
|
+
if decision == "deny":
|
|
346
|
+
if req.feedback:
|
|
347
|
+
return ToolResult(f"The user denied this action and said: {req.feedback}", error=True)
|
|
348
|
+
return ToolResult("The user denied this action. Ask what they want instead.", error=True)
|
|
349
|
+
if decision == "always":
|
|
350
|
+
self._always.add(tool.kind)
|
|
351
|
+
try:
|
|
352
|
+
return await tool.run(args, self.ctx)
|
|
353
|
+
except ToolError as e:
|
|
354
|
+
return ToolResult(f"Error: {e}", title=tool.title(args), error=True)
|
|
355
|
+
except asyncio.CancelledError:
|
|
356
|
+
raise
|
|
357
|
+
except Exception as e: # a bug in a tool must not kill the session
|
|
358
|
+
return ToolResult(f"Error: {type(e).__name__}: {e}", title=tool.title(args), error=True)
|
anixcode/airpc.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Optional: show agent activity in Discord through AI-RPC (https://github.com/an1zy/ai-rpc).
|
|
2
|
+
|
|
3
|
+
Silently does nothing when AI-RPC is not installed or not running.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import tomllib
|
|
12
|
+
import urllib.request
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _airpc_dir() -> Path:
|
|
18
|
+
if sys.platform == "win32":
|
|
19
|
+
return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "ai-rpc"
|
|
20
|
+
return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "ai-rpc"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AirpcReporter:
|
|
24
|
+
def __init__(self, enabled: bool = True, client: str | None = None) -> None:
|
|
25
|
+
self.client = client or f"anixcode:{os.getpid()}"
|
|
26
|
+
self._url: str | None = None
|
|
27
|
+
self._token: str | None = None
|
|
28
|
+
if enabled:
|
|
29
|
+
base = _airpc_dir()
|
|
30
|
+
try:
|
|
31
|
+
self._token = (base / "server.token").read_text(encoding="utf-8").strip() or None
|
|
32
|
+
except OSError:
|
|
33
|
+
self._token = None
|
|
34
|
+
port = 8765
|
|
35
|
+
try:
|
|
36
|
+
port = int(tomllib.loads((base / "config.toml").read_text(encoding="utf-8"))["server"]["port"])
|
|
37
|
+
except (OSError, KeyError, ValueError, TypeError, tomllib.TOMLDecodeError):
|
|
38
|
+
pass
|
|
39
|
+
self._url = f"http://127.0.0.1:{port}/event"
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def active(self) -> bool:
|
|
43
|
+
return bool(self._token and self._url)
|
|
44
|
+
|
|
45
|
+
def send(self, event: str, **fields: Any) -> None:
|
|
46
|
+
if not self.active:
|
|
47
|
+
return
|
|
48
|
+
body = json.dumps({"client": self.client, "event": event, "agent": "anix-code",
|
|
49
|
+
**{k: v for k, v in fields.items() if v is not None}}).encode()
|
|
50
|
+
req = urllib.request.Request(self._url, data=body, method="POST", headers={ # type: ignore[arg-type]
|
|
51
|
+
"Authorization": f"Bearer {self._token}", "Content-Type": "application/json"})
|
|
52
|
+
|
|
53
|
+
def post() -> None:
|
|
54
|
+
try:
|
|
55
|
+
urllib.request.urlopen(req, timeout=1.5).close()
|
|
56
|
+
except OSError:
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
threading.Thread(target=post, daemon=True).start()
|
anixcode/checkpoints.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""File snapshots taken before the agent changes a file, so /undo can put things back."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .storage import Session
|
|
8
|
+
|
|
9
|
+
MAX_SNAPSHOT = 20 * 1024 * 1024 # don't snapshot giant files
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Checkpoints:
|
|
13
|
+
"""Per-session. Uses the SQLite store when the session has one (survives restarts), else memory."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, session: Session) -> None:
|
|
16
|
+
self.session = session
|
|
17
|
+
self._mem: dict[int, dict[str, tuple[bool, bytes]]] = {}
|
|
18
|
+
self._last_turn = 0
|
|
19
|
+
# states replaced by /undo, newest last: [(path, existed, content)] per undo
|
|
20
|
+
self._redo: list[list[tuple[str, bool, bytes]]] = []
|
|
21
|
+
|
|
22
|
+
def new_turn(self) -> int:
|
|
23
|
+
self._redo.clear() # a new change makes old redo states meaningless
|
|
24
|
+
turn = max(int(time.time() * 1000), self._last_turn + 1) # monotonic, survives compaction
|
|
25
|
+
self._last_turn = turn
|
|
26
|
+
return turn
|
|
27
|
+
|
|
28
|
+
def snapshot(self, turn: int, path: Path) -> None:
|
|
29
|
+
existed = path.is_file()
|
|
30
|
+
if existed and path.stat().st_size > MAX_SNAPSHOT:
|
|
31
|
+
return
|
|
32
|
+
content = path.read_bytes() if existed else b""
|
|
33
|
+
store = self.session.store
|
|
34
|
+
if store is not None:
|
|
35
|
+
store.add_snapshot(self.session.id, turn, str(path), existed, content)
|
|
36
|
+
else:
|
|
37
|
+
self._mem.setdefault(turn, {}).setdefault(str(path), (existed, content))
|
|
38
|
+
|
|
39
|
+
def undo_last(self) -> tuple[list[Path], list[Path]] | None:
|
|
40
|
+
"""Restore the files of the latest turn that changed something. Returns (restored, deleted)."""
|
|
41
|
+
store = self.session.store
|
|
42
|
+
if store is not None:
|
|
43
|
+
found = store.last_snapshot_turn(self.session.id)
|
|
44
|
+
if found is None:
|
|
45
|
+
return None
|
|
46
|
+
turn, files = found
|
|
47
|
+
else:
|
|
48
|
+
if not self._mem:
|
|
49
|
+
return None
|
|
50
|
+
turn = max(self._mem)
|
|
51
|
+
files = [(p, e, c) for p, (e, c) in self._mem[turn].items()]
|
|
52
|
+
restored, deleted = [], []
|
|
53
|
+
current = []
|
|
54
|
+
for raw, _existed, _content in files:
|
|
55
|
+
p = Path(raw)
|
|
56
|
+
current.append((raw, p.is_file(), p.read_bytes() if p.is_file() else b""))
|
|
57
|
+
self._redo.append(current)
|
|
58
|
+
for raw, existed, content in files:
|
|
59
|
+
p = Path(raw)
|
|
60
|
+
if existed:
|
|
61
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
62
|
+
p.write_bytes(content)
|
|
63
|
+
restored.append(p)
|
|
64
|
+
elif p.exists():
|
|
65
|
+
p.unlink()
|
|
66
|
+
deleted.append(p)
|
|
67
|
+
if store is not None:
|
|
68
|
+
store.drop_snapshot_turn(self.session.id, turn)
|
|
69
|
+
else:
|
|
70
|
+
del self._mem[turn]
|
|
71
|
+
return restored, deleted
|
|
72
|
+
|
|
73
|
+
def redo_last(self) -> tuple[list[Path], list[Path]] | None:
|
|
74
|
+
"""Re-apply what the latest /undo reverted. Returns (restored, deleted)."""
|
|
75
|
+
if not self._redo:
|
|
76
|
+
return None
|
|
77
|
+
restored, deleted = [], []
|
|
78
|
+
for raw, existed, content in self._redo.pop():
|
|
79
|
+
p = Path(raw)
|
|
80
|
+
if existed:
|
|
81
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
p.write_bytes(content)
|
|
83
|
+
restored.append(p)
|
|
84
|
+
elif p.exists():
|
|
85
|
+
p.unlink()
|
|
86
|
+
deleted.append(p)
|
|
87
|
+
return restored, deleted
|