euron-code 1.0.0__tar.gz → 1.0.2__tar.gz

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.
Files changed (118) hide show
  1. {euron_code-1.0.0 → euron_code-1.0.2}/CHANGELOG.md +24 -0
  2. {euron_code-1.0.0 → euron_code-1.0.2}/PKG-INFO +1 -1
  3. {euron_code-1.0.0 → euron_code-1.0.2}/pyproject.toml +1 -1
  4. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/__init__.py +1 -1
  5. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/api.py +8 -1
  6. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/errorlog.py +4 -1
  7. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/repl.py +5 -0
  8. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/background.py +15 -1
  9. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/base.py +246 -244
  10. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/fs.py +72 -8
  11. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/normalize.py +19 -7
  12. euron_code-1.0.2/src/euron_code/tools/todo.py +106 -0
  13. euron_code-1.0.2/src/euron_code/update_check.py +92 -0
  14. {euron_code-1.0.0 → euron_code-1.0.2}/tests/conftest.py +1 -0
  15. euron_code-1.0.2/tests/test_dashboard_fixes_102.py +103 -0
  16. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_tools_fs.py +17 -13
  17. euron_code-1.0.2/tests/test_update_check.py +61 -0
  18. euron_code-1.0.0/src/euron_code/tools/todo.py +0 -62
  19. {euron_code-1.0.0 → euron_code-1.0.2}/.gitignore +0 -0
  20. {euron_code-1.0.0 → euron_code-1.0.2}/LICENSE +0 -0
  21. {euron_code-1.0.0 → euron_code-1.0.2}/README.md +0 -0
  22. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/__main__.py +0 -0
  23. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/activity.py +0 -0
  24. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/agent.py +0 -0
  25. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/attachments.py +0 -0
  26. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/auth.py +0 -0
  27. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/builtin_skills/build-from-reference/SKILL.md +0 -0
  28. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/builtin_skills/explain-codebase/SKILL.md +0 -0
  29. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/builtin_skills/review/SKILL.md +0 -0
  30. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/builtin_skills/test-writer/SKILL.md +0 -0
  31. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/cache.py +0 -0
  32. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/checkpoints.py +0 -0
  33. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/cli.py +0 -0
  34. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/config.py +0 -0
  35. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/context.py +0 -0
  36. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/contextforge/LICENSE +0 -0
  37. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/contextforge/__init__.py +0 -0
  38. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/contextforge/text.py +0 -0
  39. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/contextforge/toolout.py +0 -0
  40. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/credentials.py +0 -0
  41. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/doctor.py +0 -0
  42. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/documents.py +0 -0
  43. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/error_hints.py +0 -0
  44. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/frontmatter.py +0 -0
  45. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/hooks.py +0 -0
  46. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/keys.py +0 -0
  47. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/knowledge.py +0 -0
  48. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/licensing.py +0 -0
  49. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/logo.py +0 -0
  50. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/markdown_view.py +0 -0
  51. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/memory.py +0 -0
  52. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/osscache.py +0 -0
  53. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/ossgithub.py +0 -0
  54. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/permissions.py +0 -0
  55. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/project_setup.py +0 -0
  56. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/prompts.py +0 -0
  57. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/repomap.py +0 -0
  58. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/rules.py +0 -0
  59. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/security_scan.py +0 -0
  60. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/sessions.py +0 -0
  61. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/skills.py +0 -0
  62. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/textsafe.py +0 -0
  63. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/__init__.py +0 -0
  64. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/db.py +0 -0
  65. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/document.py +0 -0
  66. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/erie.py +0 -0
  67. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/ignore.py +0 -0
  68. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/oss.py +0 -0
  69. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/pathfind.py +0 -0
  70. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/reuse.py +0 -0
  71. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/search.py +0 -0
  72. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/shell.py +0 -0
  73. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/skill.py +0 -0
  74. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/symbols.py +0 -0
  75. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/task.py +0 -0
  76. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/tools/web.py +0 -0
  77. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/transcript.py +0 -0
  78. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/trust.py +0 -0
  79. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/ui.py +0 -0
  80. {euron_code-1.0.0 → euron_code-1.0.2}/src/euron_code/usage_view.py +0 -0
  81. {euron_code-1.0.0 → euron_code-1.0.2}/tests/helpers.py +0 -0
  82. {euron_code-1.0.0 → euron_code-1.0.2}/tests/mock_gateway.py +0 -0
  83. {euron_code-1.0.0 → euron_code-1.0.2}/tests/serve_helper.py +0 -0
  84. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_agent_mock.py +0 -0
  85. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_api_shell.py +0 -0
  86. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_bench.py +0 -0
  87. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_cli_e2e.py +0 -0
  88. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_context_memory_sessions.py +0 -0
  89. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_dashboard_fixes.py +0 -0
  90. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_db.py +0 -0
  91. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_erie.py +0 -0
  92. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_knowledge_security.py +0 -0
  93. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_markdown_view.py +0 -0
  94. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_oss_local.py +0 -0
  95. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_permissions.py +0 -0
  96. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_powershell_exit_codes.py +0 -0
  97. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_qa_attach_secrets.py +0 -0
  98. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_qa_long_task.py +0 -0
  99. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_qa_print_output.py +0 -0
  100. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_qa_reuse_unrelated.py +0 -0
  101. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_qa_yolo_outside.py +0 -0
  102. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_repl.py +0 -0
  103. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_reuse_honesty.py +0 -0
  104. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_search.py +0 -0
  105. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_textsafe.py +0 -0
  106. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_transcript_ui.py +0 -0
  107. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v2_rules_skills_hooks.py +0 -0
  108. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v2_tokens_shortcuts.py +0 -0
  109. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v2_usage_headers.py +0 -0
  110. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v31_security.py +0 -0
  111. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v3_accounts_value_setup.py +0 -0
  112. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v3_activity.py +0 -0
  113. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v3_attachments.py +0 -0
  114. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v3_context.py +0 -0
  115. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v3_live_repl.py +0 -0
  116. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v3_single_login.py +0 -0
  117. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v4.py +0 -0
  118. {euron_code-1.0.0 → euron_code-1.0.2}/tests/test_v5.py +0 -0
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.2 (2026-11-06)
4
+
5
+ Fixes for the tool errors still reported by 1.0.1 users.
6
+
7
+ - Edits: an exact, unique match is applied even if the file was not read first or changed since (the
8
+ text being replaced is verifiably there); anything looser shows the current file first. old_string
9
+ sent with literal \n escapes, curly quotes or different spacing now matches. When nothing matches,
10
+ the error quotes the closest lines of the file so the next try can copy them exactly.
11
+ - Parameter names in any spelling (filePath, file-path, oldText, search_text, original_code ...) are
12
+ understood. A parameter that is still missing is reported with what the call did contain.
13
+ - todo_write accepts the shapes models send: plain text lines ("- [x] done"), {"items": [...]}, items as
14
+ strings, and statuses like "done" or "in-progress".
15
+ - stop_process with nothing running is not an error; "all" stops every background process.
16
+ - A server or proxy error page (HTML) is never shown; a 5xx page is retried like "busy".
17
+ - Error reports keep plain parameter and file names, so a failure says what was missing (code and
18
+ values are still hidden).
19
+
20
+ ## 1.0.1 (2026-11-06)
21
+
22
+ - Euron Code tells you when a newer version is out, with the command to upgrade
23
+ (`pip install -U euron-code`). It checks PyPI at most once a day, in the background of start-up, with a
24
+ two-second limit, and says nothing when you are offline or up to date. Turn it off with
25
+ `EURON_NO_UPDATE_CHECK=1`.
26
+
3
27
  ## 1.0.0 (2026-11-06)
4
28
 
5
29
  Fixes for every failure recorded on the Euron Code error dashboard since launch.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: euron-code
3
- Version: 1.0.0
3
+ Version: 1.0.2
4
4
  Summary: Euron Code: an agentic coding assistant in your terminal for Euron Plus and Super 30 students.
5
5
  Project-URL: Homepage, https://euron.one/code-agent
6
6
  Author-email: Euron <contact@euron.one>
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "euron-code"
7
- version = "1.0.0"
7
+ version = "1.0.2"
8
8
  description = "Euron Code: an agentic coding assistant in your terminal for Euron Plus and Super 30 students."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,3 +1,3 @@
1
1
  """Euron Code: an agentic coding assistant for the terminal."""
2
2
 
3
- __version__ = "1.0.0"
3
+ __version__ = "1.0.2"
@@ -232,7 +232,14 @@ def _error_from_response(resp: httpx.Response) -> EuronError:
232
232
  try:
233
233
  body = resp.json()
234
234
  except ValueError:
235
- body = {"error": {"message": (resp.text or "")[:300] or f"HTTP {resp.status_code}"}}
235
+ text = resp.text or ""
236
+ if "<html" in text[:500].lower() or "<!doctype" in text[:200].lower():
237
+ # A proxy's error page (deploy, edge timeout). Never show the HTML; a 5xx page is retryable.
238
+ if resp.status_code >= 500 or resp.status_code in (408, 429):
239
+ return BusyError(f"Euron Code servers are briefly unavailable (HTTP {resp.status_code}). Retrying.",
240
+ status=resp.status_code, code="server_unavailable")
241
+ text = f"Euron Code returned an error page (HTTP {resp.status_code})."
242
+ body = {"error": {"message": text[:300] or f"HTTP {resp.status_code}"}}
236
243
  return error_from_body(resp.status_code, body, _parse_retry_after(resp.headers.get("retry-after")))
237
244
 
238
245
 
@@ -47,6 +47,7 @@ _SECRET_PATTERNS = [
47
47
  re.compile(r"\b[A-Za-z0-9+/_\-]{32,}={0,2}"), # long base64 / hex blobs
48
48
  re.compile(r"(?i)\b[a-z][a-z0-9+.\-]*://[^\s/:@]+:[^\s/@]+@"), # credentials in URLs
49
49
  ]
50
+ _PLAIN_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]{0,39}$")
50
51
  _QUOTED = re.compile(r"'[^'\n]{0,400}'|\"[^\"\n]{0,400}\"|`[^`\n]{0,400}`")
51
52
 
52
53
  WIRE_FIELDS = ("at", "kind", "code", "message", "tool", "command", "httpStatus", "version", "os", "python",
@@ -64,7 +65,9 @@ def _home_variants() -> List[str]:
64
65
  def scrub(text: Any, root: Optional[Path] = None, limit: int = 500) -> str:
65
66
  """Remove quoted content, mask paths, redact secrets, cap the length."""
66
67
  s = str(text or "")
67
- s = _QUOTED.sub("[...]", s) # quoted bits are where code, commands and values hide
68
+ # Quoted bits are where code, commands and values hide; a bare parameter or file name
69
+ # (`new_string`, `todos`, `p1`) is kept so a report says WHAT was missing.
70
+ s = _QUOTED.sub(lambda m: m.group(0) if _PLAIN_NAME.match(m.group(0)[1:-1]) else "[...]", s)
68
71
  flags = re.IGNORECASE if os.name == "nt" else 0
69
72
  if root is not None:
70
73
  for r in sorted({str(root), str(root).replace("\\", "/"), str(root).replace("/", "\\")}, key=len, reverse=True):
@@ -793,6 +793,11 @@ class Repl:
793
793
  self.ui.plain(" " + row)
794
794
  self.ui.plain("")
795
795
  self.ui.info(f"[bold]Euron Code[/bold] {__version__} [dim]{escape(str(self.agent.root))}[/dim]")
796
+ if getattr(self.ui, "interactive", False):
797
+ from euron_code import update_check
798
+ upgrade = update_check.notice()
799
+ if upgrade:
800
+ self.ui.warn(upgrade)
796
801
  if self.me:
797
802
  access = self.me.get("access") or {}
798
803
  q = self.me.get("quota") or {}
@@ -285,7 +285,21 @@ class StopProcess(Tool):
285
285
  return str(args.get("id") or "")
286
286
 
287
287
  def run(self, args, ctx):
288
- bp = manager(ctx).stop(require(args, "id"))
288
+ pm = manager(ctx)
289
+ key = str(args.get("id") or "").strip().lower()
290
+ if not pm.running():
291
+ # Nothing to do is not a failure (the process already exited, or none was started here).
292
+ return ToolResult("No background process is running in this session, so there is nothing to stop.",
293
+ preview="nothing running")
294
+ if key in ("all", "*", "everything"):
295
+ n = pm.stop_all()
296
+ return ToolResult(f"Stopped {n} background process(es).", preview=f"stopped {n}")
297
+ bp = pm.resolve(args.get("id"))
298
+ if bp is None and len(pm.running()) == 1:
299
+ bp = pm.running()[0] # the only one running: that is the one meant
300
+ if bp is None:
301
+ bp = pm.get(require(args, "id")) # raises with the list of ids
302
+ bp = pm.stop(bp.id)
289
303
  return ToolResult(f"Stopped {bp.id} (exit code {bp.proc.returncode}). Last output:\n{_tail(bp.text(), 10)}",
290
304
  preview=f"stopped {bp.id}")
291
305
 
@@ -1,244 +1,246 @@
1
- """Tool plumbing shared by every tool."""
2
-
3
- from __future__ import annotations
4
-
5
- import hashlib
6
- import os
7
- from dataclasses import dataclass, field
8
- from pathlib import Path
9
- from typing import Any, Callable, Dict, List, Optional
10
-
11
- from euron_code.permissions import Request
12
-
13
-
14
- class ToolError(Exception):
15
- """Raised by a tool to return an error message to the model."""
16
-
17
-
18
- @dataclass
19
- class ToolResult:
20
- content: str
21
- is_error: bool = False
22
- preview: Optional[str] = None # short text for the user; defaults to content
23
-
24
-
25
- @dataclass
26
- class ReadRange:
27
- offset: int
28
- limit: int
29
- turn: int
30
- chars: int # size of the output the model got (for the savings counter)
31
- call_id: Optional[str] = None
32
-
33
-
34
- @dataclass
35
- class FileRecord:
36
- mtime: float
37
- size: int
38
- digest: str = ""
39
- ranges: List[ReadRange] = field(default_factory=list)
40
-
41
-
42
- def file_digest(path: Path) -> str:
43
- try:
44
- return hashlib.sha1(path.read_bytes()).hexdigest()
45
- except OSError:
46
- return ""
47
-
48
-
49
- class ReadTracker:
50
- """Remembers which files the model has read (for edit safety and read dedupe).
51
-
52
- A file counts as unchanged when its mtime and size match, or, if they do not, when its
53
- content hash still matches (a formatter that touched it without changing anything).
54
- """
55
-
56
- def __init__(self) -> None:
57
- self.files: Dict[str, FileRecord] = {}
58
-
59
- @staticmethod
60
- def _key(path: Path) -> str:
61
- k = str(path.resolve())
62
- return k.lower() if os.name == "nt" else k
63
-
64
- def _fresh(self, path: Path, rec: Optional[FileRecord]) -> bool:
65
- if rec is None:
66
- return False
67
- try:
68
- st = path.stat()
69
- except OSError:
70
- return False
71
- if rec.mtime == st.st_mtime and rec.size == st.st_size:
72
- return True
73
- if rec.size == st.st_size and rec.digest and file_digest(path) == rec.digest:
74
- rec.mtime = st.st_mtime
75
- return True
76
- return False
77
-
78
- def mark_read(self, path: Path, rng: Optional[tuple] = None, turn: int = 0, chars: int = 0,
79
- call_id: Optional[str] = None) -> None:
80
- st = path.stat()
81
- key = self._key(path)
82
- rec = self.files.get(key)
83
- if not self._fresh(path, rec):
84
- rec = FileRecord(st.st_mtime, st.st_size, file_digest(path))
85
- self.files[key] = rec
86
- if rng is not None:
87
- rec.ranges = [r for r in rec.ranges if (r.offset, r.limit) != tuple(rng)]
88
- rec.ranges.append(ReadRange(rng[0], rng[1], turn, chars, call_id))
89
-
90
- def mark_written(self, path: Path) -> None:
91
- st = path.stat()
92
- self.files[self._key(path)] = FileRecord(st.st_mtime, st.st_size, file_digest(path), [])
93
-
94
- def was_read(self, path: Path) -> bool:
95
- return self._key(path) in self.files
96
-
97
- def unchanged_since_read(self, path: Path) -> bool:
98
- return self._fresh(path, self.files.get(self._key(path)))
99
-
100
- def covering_read(self, path: Path, rng: tuple) -> Optional[ReadRange]:
101
- """An earlier read of the same file that already covers `rng`, if the file is unchanged."""
102
- rec = self.files.get(self._key(path))
103
- if not rec or not rec.ranges or not self._fresh(path, rec):
104
- return None
105
- off, lim = rng
106
- for r in reversed(rec.ranges):
107
- if r.offset <= off and off + lim <= r.offset + r.limit:
108
- return r
109
- return None
110
-
111
- def already_has(self, path: Path, rng: tuple) -> bool:
112
- return self.covering_read(path, rng) is not None
113
-
114
- def forget_calls(self, call_ids) -> None:
115
- """Those tool results were removed from context: their content must be read again."""
116
- ids = set(call_ids)
117
- if not ids:
118
- return
119
- for rec in self.files.values():
120
- rec.ranges = [r for r in rec.ranges if r.call_id not in ids]
121
-
122
- def clear(self) -> None:
123
- """Called after compaction: file contents are no longer in context."""
124
- for rec in self.files.values():
125
- rec.ranges.clear()
126
-
127
-
128
- class Savings:
129
- """Characters kept out of the context by the automatic token-saving measures."""
130
-
131
- KINDS = ("dedupe", "truncate", "micro", "compact")
132
-
133
- def __init__(self) -> None:
134
- self.chars: Dict[str, int] = {k: 0 for k in self.KINDS}
135
-
136
- def add(self, kind: str, chars: int) -> None:
137
- if chars > 0:
138
- self.chars[kind] = self.chars.get(kind, 0) + int(chars)
139
-
140
- def tokens(self, kind: Optional[str] = None) -> int:
141
- n = self.chars.get(kind, 0) if kind else sum(self.chars.values())
142
- return int(n / 3.5)
143
-
144
-
145
- @dataclass
146
- class ToolContext:
147
- root: Path
148
- settings: Dict[str, Any]
149
- ui: Any
150
- tracker: ReadTracker = field(default_factory=ReadTracker)
151
- shell: Any = None # ShellSession
152
- todos: List[Dict[str, Any]] = field(default_factory=list)
153
- agent: Any = None # the running Agent (for the task tool)
154
- savings: Savings = field(default_factory=Savings)
155
- turn: int = 0 # model step counter, shown in "unchanged since turn N"
156
- call_id: Optional[str] = None # id of the tool call being run
157
- processes: Any = None # background.ProcessManager, created on first use
158
-
159
- @property
160
- def max_output_chars(self) -> int:
161
- return int(self.settings.get("toolOutputMaxChars") or 12000)
162
-
163
- def cut(self, text: str, note: str = "", max_chars: Optional[int] = None) -> str:
164
- """truncate() with the configured limit, counting what was cut as saved."""
165
- out = truncate(text, max_chars or self.max_output_chars, note)
166
- self.savings.add("truncate", len(text) - len(out))
167
- return out
168
-
169
- def resolve(self, p: str) -> Path:
170
- if not isinstance(p, str) or not p.strip():
171
- raise ToolError("A non-empty path is required.")
172
- raw = os.path.expanduser(p.strip())
173
- path = Path(raw)
174
- if not path.is_absolute():
175
- path = self.root / path
176
- return Path(os.path.normpath(str(path)))
177
-
178
- def rel(self, path: Path) -> str:
179
- try:
180
- return path.resolve().relative_to(self.root.resolve()).as_posix()
181
- except ValueError:
182
- return str(path)
183
-
184
-
185
- def truncate(text: str, max_chars: int, note: str = "") -> str:
186
- """Keep the head and tail of long output, with a note saying what was cut."""
187
- if len(text) <= max_chars:
188
- return text
189
- head = int(max_chars * 0.6)
190
- tail = max_chars - head
191
- cut = text[head: len(text) - tail]
192
- cut_lines = cut.count("\n")
193
- msg = (f"\n\n[... output truncated: {len(cut)} characters / ~{cut_lines} lines omitted"
194
- f"{'; ' + note if note else ''} ...]\n\n")
195
- return text[:head] + msg + text[len(text) - tail:]
196
-
197
-
198
- class Tool:
199
- name: str = ""
200
- description: str = ""
201
- parameters: Dict[str, Any] = {}
202
- read_only: bool = False
203
-
204
- def schema(self) -> Dict[str, Any]:
205
- return {
206
- "type": "function",
207
- "function": {"name": self.name, "description": self.description, "parameters": self.parameters},
208
- }
209
-
210
- def permission(self, args: Dict[str, Any], ctx: ToolContext) -> Request:
211
- return Request(category=None, tool=self.name)
212
-
213
- def describe(self, args: Dict[str, Any], ctx: ToolContext) -> str:
214
- """One-line summary shown to the user."""
215
- return ""
216
-
217
- def preview(self, args: Dict[str, Any], ctx: ToolContext) -> Optional[str]:
218
- """Extra detail shown in the permission prompt (e.g. a diff). May raise ToolError."""
219
- return None
220
-
221
- def run(self, args: Dict[str, Any], ctx: ToolContext) -> ToolResult:
222
- raise NotImplementedError
223
-
224
-
225
- def require(args: Dict[str, Any], key: str, typ: type = str) -> Any:
226
- if key not in args or args[key] is None:
227
- raise ToolError(f"Missing required parameter `{key}`.")
228
- v = args[key]
229
- if typ is str and not isinstance(v, str):
230
- raise ToolError(f"Parameter `{key}` must be a string.")
231
- return v
232
-
233
-
234
- def opt_int(args: Dict[str, Any], key: str, default: Optional[int]) -> Optional[int]:
235
- v = args.get(key)
236
- if v is None or v == "":
237
- return default
238
- try:
239
- return int(v)
240
- except (TypeError, ValueError):
241
- raise ToolError(f"Parameter `{key}` must be an integer.")
242
-
243
-
244
- DiffFn = Callable[[str, str, str], str]
1
+ """Tool plumbing shared by every tool."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any, Callable, Dict, List, Optional
10
+
11
+ from euron_code.permissions import Request
12
+
13
+
14
+ class ToolError(Exception):
15
+ """Raised by a tool to return an error message to the model."""
16
+
17
+
18
+ @dataclass
19
+ class ToolResult:
20
+ content: str
21
+ is_error: bool = False
22
+ preview: Optional[str] = None # short text for the user; defaults to content
23
+
24
+
25
+ @dataclass
26
+ class ReadRange:
27
+ offset: int
28
+ limit: int
29
+ turn: int
30
+ chars: int # size of the output the model got (for the savings counter)
31
+ call_id: Optional[str] = None
32
+
33
+
34
+ @dataclass
35
+ class FileRecord:
36
+ mtime: float
37
+ size: int
38
+ digest: str = ""
39
+ ranges: List[ReadRange] = field(default_factory=list)
40
+
41
+
42
+ def file_digest(path: Path) -> str:
43
+ try:
44
+ return hashlib.sha1(path.read_bytes()).hexdigest()
45
+ except OSError:
46
+ return ""
47
+
48
+
49
+ class ReadTracker:
50
+ """Remembers which files the model has read (for edit safety and read dedupe).
51
+
52
+ A file counts as unchanged when its mtime and size match, or, if they do not, when its
53
+ content hash still matches (a formatter that touched it without changing anything).
54
+ """
55
+
56
+ def __init__(self) -> None:
57
+ self.files: Dict[str, FileRecord] = {}
58
+
59
+ @staticmethod
60
+ def _key(path: Path) -> str:
61
+ k = str(path.resolve())
62
+ return k.lower() if os.name == "nt" else k
63
+
64
+ def _fresh(self, path: Path, rec: Optional[FileRecord]) -> bool:
65
+ if rec is None:
66
+ return False
67
+ try:
68
+ st = path.stat()
69
+ except OSError:
70
+ return False
71
+ if rec.mtime == st.st_mtime and rec.size == st.st_size:
72
+ return True
73
+ if rec.size == st.st_size and rec.digest and file_digest(path) == rec.digest:
74
+ rec.mtime = st.st_mtime
75
+ return True
76
+ return False
77
+
78
+ def mark_read(self, path: Path, rng: Optional[tuple] = None, turn: int = 0, chars: int = 0,
79
+ call_id: Optional[str] = None) -> None:
80
+ st = path.stat()
81
+ key = self._key(path)
82
+ rec = self.files.get(key)
83
+ if not self._fresh(path, rec):
84
+ rec = FileRecord(st.st_mtime, st.st_size, file_digest(path))
85
+ self.files[key] = rec
86
+ if rng is not None:
87
+ rec.ranges = [r for r in rec.ranges if (r.offset, r.limit) != tuple(rng)]
88
+ rec.ranges.append(ReadRange(rng[0], rng[1], turn, chars, call_id))
89
+
90
+ def mark_written(self, path: Path) -> None:
91
+ st = path.stat()
92
+ self.files[self._key(path)] = FileRecord(st.st_mtime, st.st_size, file_digest(path), [])
93
+
94
+ def was_read(self, path: Path) -> bool:
95
+ return self._key(path) in self.files
96
+
97
+ def unchanged_since_read(self, path: Path) -> bool:
98
+ return self._fresh(path, self.files.get(self._key(path)))
99
+
100
+ def covering_read(self, path: Path, rng: tuple) -> Optional[ReadRange]:
101
+ """An earlier read of the same file that already covers `rng`, if the file is unchanged."""
102
+ rec = self.files.get(self._key(path))
103
+ if not rec or not rec.ranges or not self._fresh(path, rec):
104
+ return None
105
+ off, lim = rng
106
+ for r in reversed(rec.ranges):
107
+ if r.offset <= off and off + lim <= r.offset + r.limit:
108
+ return r
109
+ return None
110
+
111
+ def already_has(self, path: Path, rng: tuple) -> bool:
112
+ return self.covering_read(path, rng) is not None
113
+
114
+ def forget_calls(self, call_ids) -> None:
115
+ """Those tool results were removed from context: their content must be read again."""
116
+ ids = set(call_ids)
117
+ if not ids:
118
+ return
119
+ for rec in self.files.values():
120
+ rec.ranges = [r for r in rec.ranges if r.call_id not in ids]
121
+
122
+ def clear(self) -> None:
123
+ """Called after compaction: file contents are no longer in context."""
124
+ for rec in self.files.values():
125
+ rec.ranges.clear()
126
+
127
+
128
+ class Savings:
129
+ """Characters kept out of the context by the automatic token-saving measures."""
130
+
131
+ KINDS = ("dedupe", "truncate", "micro", "compact")
132
+
133
+ def __init__(self) -> None:
134
+ self.chars: Dict[str, int] = {k: 0 for k in self.KINDS}
135
+
136
+ def add(self, kind: str, chars: int) -> None:
137
+ if chars > 0:
138
+ self.chars[kind] = self.chars.get(kind, 0) + int(chars)
139
+
140
+ def tokens(self, kind: Optional[str] = None) -> int:
141
+ n = self.chars.get(kind, 0) if kind else sum(self.chars.values())
142
+ return int(n / 3.5)
143
+
144
+
145
+ @dataclass
146
+ class ToolContext:
147
+ root: Path
148
+ settings: Dict[str, Any]
149
+ ui: Any
150
+ tracker: ReadTracker = field(default_factory=ReadTracker)
151
+ shell: Any = None # ShellSession
152
+ todos: List[Dict[str, Any]] = field(default_factory=list)
153
+ agent: Any = None # the running Agent (for the task tool)
154
+ savings: Savings = field(default_factory=Savings)
155
+ turn: int = 0 # model step counter, shown in "unchanged since turn N"
156
+ call_id: Optional[str] = None # id of the tool call being run
157
+ processes: Any = None # background.ProcessManager, created on first use
158
+
159
+ @property
160
+ def max_output_chars(self) -> int:
161
+ return int(self.settings.get("toolOutputMaxChars") or 12000)
162
+
163
+ def cut(self, text: str, note: str = "", max_chars: Optional[int] = None) -> str:
164
+ """truncate() with the configured limit, counting what was cut as saved."""
165
+ out = truncate(text, max_chars or self.max_output_chars, note)
166
+ self.savings.add("truncate", len(text) - len(out))
167
+ return out
168
+
169
+ def resolve(self, p: str) -> Path:
170
+ if not isinstance(p, str) or not p.strip():
171
+ raise ToolError("A non-empty path is required.")
172
+ raw = os.path.expanduser(p.strip())
173
+ path = Path(raw)
174
+ if not path.is_absolute():
175
+ path = self.root / path
176
+ return Path(os.path.normpath(str(path)))
177
+
178
+ def rel(self, path: Path) -> str:
179
+ try:
180
+ return path.resolve().relative_to(self.root.resolve()).as_posix()
181
+ except ValueError:
182
+ return str(path)
183
+
184
+
185
+ def truncate(text: str, max_chars: int, note: str = "") -> str:
186
+ """Keep the head and tail of long output, with a note saying what was cut."""
187
+ if len(text) <= max_chars:
188
+ return text
189
+ head = int(max_chars * 0.6)
190
+ tail = max_chars - head
191
+ cut = text[head: len(text) - tail]
192
+ cut_lines = cut.count("\n")
193
+ msg = (f"\n\n[... output truncated: {len(cut)} characters / ~{cut_lines} lines omitted"
194
+ f"{'; ' + note if note else ''} ...]\n\n")
195
+ return text[:head] + msg + text[len(text) - tail:]
196
+
197
+
198
+ class Tool:
199
+ name: str = ""
200
+ description: str = ""
201
+ parameters: Dict[str, Any] = {}
202
+ read_only: bool = False
203
+
204
+ def schema(self) -> Dict[str, Any]:
205
+ return {
206
+ "type": "function",
207
+ "function": {"name": self.name, "description": self.description, "parameters": self.parameters},
208
+ }
209
+
210
+ def permission(self, args: Dict[str, Any], ctx: ToolContext) -> Request:
211
+ return Request(category=None, tool=self.name)
212
+
213
+ def describe(self, args: Dict[str, Any], ctx: ToolContext) -> str:
214
+ """One-line summary shown to the user."""
215
+ return ""
216
+
217
+ def preview(self, args: Dict[str, Any], ctx: ToolContext) -> Optional[str]:
218
+ """Extra detail shown in the permission prompt (e.g. a diff). May raise ToolError."""
219
+ return None
220
+
221
+ def run(self, args: Dict[str, Any], ctx: ToolContext) -> ToolResult:
222
+ raise NotImplementedError
223
+
224
+
225
+ def require(args: Dict[str, Any], key: str, typ: type = str) -> Any:
226
+ if key not in args or args[key] is None:
227
+ sent = ", ".join(sorted(str(k) for k in args)) or "nothing"
228
+ hint = " To delete text, pass new_string as an empty string." if key == "new_string" else ""
229
+ raise ToolError(f"Missing required parameter `{key}` (this call had: {sent}).{hint}")
230
+ v = args[key]
231
+ if typ is str and not isinstance(v, str):
232
+ raise ToolError(f"Parameter `{key}` must be a string.")
233
+ return v
234
+
235
+
236
+ def opt_int(args: Dict[str, Any], key: str, default: Optional[int]) -> Optional[int]:
237
+ v = args.get(key)
238
+ if v is None or v == "":
239
+ return default
240
+ try:
241
+ return int(v)
242
+ except (TypeError, ValueError):
243
+ raise ToolError(f"Parameter `{key}` must be an integer.")
244
+
245
+
246
+ DiffFn = Callable[[str, str, str], str]