coreloop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coreloop/__init__.py +33 -0
- coreloop/__main__.py +5 -0
- coreloop/_api_client.py +330 -0
- coreloop/_cache.py +19 -0
- coreloop/_logging.py +23 -0
- coreloop/_tool_execution.py +80 -0
- coreloop/agent.py +368 -0
- coreloop/cli/__init__.py +269 -0
- coreloop/cli/_run.py +145 -0
- coreloop/cli/_tools.py +82 -0
- coreloop/config.py +33 -0
- coreloop/coreloop.toml +101 -0
- coreloop/hooks.py +132 -0
- coreloop/profiles.py +176 -0
- coreloop/py.typed +0 -0
- coreloop/tool_registry.py +188 -0
- coreloop/tools/__init__.py +31 -0
- coreloop/tools/_shared.py +59 -0
- coreloop/tools/bash.py +252 -0
- coreloop/tools/edit.py +154 -0
- coreloop/tools/grep.py +86 -0
- coreloop/tools/ls.py +62 -0
- coreloop/tools/read.py +70 -0
- coreloop/types.py +86 -0
- coreloop/web_tools.py +98 -0
- coreloop-0.1.0.dist-info/METADATA +350 -0
- coreloop-0.1.0.dist-info/RECORD +30 -0
- coreloop-0.1.0.dist-info/WHEEL +4 -0
- coreloop-0.1.0.dist-info/entry_points.txt +3 -0
- coreloop-0.1.0.dist-info/licenses/LICENSE +21 -0
coreloop/tools/grep.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""grep.py -- ripgrep-backed pattern search tool."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ..tool_registry import ToolInfo
|
|
7
|
+
from ._shared import _resolve_safe_strict, _make_tool_info
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_grep_tool(root: str, *, max_chars: int = 20_000, search_timeout: float = 30.0) -> ToolInfo:
|
|
11
|
+
"""Build a grep tool scoped to *root* using ripgrep."""
|
|
12
|
+
root_path = Path(root).resolve()
|
|
13
|
+
|
|
14
|
+
async def grep(
|
|
15
|
+
pattern: str,
|
|
16
|
+
path: str = ".",
|
|
17
|
+
file_type: str | None = None,
|
|
18
|
+
after_context: int | None = None,
|
|
19
|
+
files_with_matches: bool = False,
|
|
20
|
+
) -> str:
|
|
21
|
+
"""Use this to find where a pattern, symbol, or string appears across files. Faster than reading files one by one.
|
|
22
|
+
|
|
23
|
+
Parameters
|
|
24
|
+
----------
|
|
25
|
+
pattern :
|
|
26
|
+
Regular expression to search for.
|
|
27
|
+
path :
|
|
28
|
+
Directory or file to search in (relative to root).
|
|
29
|
+
file_type :
|
|
30
|
+
Restrict search to files of this type (e.g. ``py``, ``js``, ``ts``).
|
|
31
|
+
after_context :
|
|
32
|
+
Number of lines to show after each match.
|
|
33
|
+
files_with_matches :
|
|
34
|
+
If true, only print paths of files that contain a match.
|
|
35
|
+
"""
|
|
36
|
+
try:
|
|
37
|
+
safe = _resolve_safe_strict(path, root_path)
|
|
38
|
+
except ValueError as exc:
|
|
39
|
+
return f"Error: {exc}"
|
|
40
|
+
|
|
41
|
+
if after_context is not None and after_context < 0:
|
|
42
|
+
return "Error: after_context must be >= 0"
|
|
43
|
+
|
|
44
|
+
cmd = ["rg", "-e", pattern]
|
|
45
|
+
if file_type:
|
|
46
|
+
cmd += ["--type", file_type]
|
|
47
|
+
if after_context is not None:
|
|
48
|
+
cmd += [f"--after-context={after_context}"]
|
|
49
|
+
if files_with_matches:
|
|
50
|
+
cmd.append("--files-with-matches")
|
|
51
|
+
cmd.append(safe)
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
proc = await asyncio.create_subprocess_exec(
|
|
55
|
+
*cmd,
|
|
56
|
+
stdout=asyncio.subprocess.PIPE,
|
|
57
|
+
stderr=asyncio.subprocess.PIPE,
|
|
58
|
+
)
|
|
59
|
+
try:
|
|
60
|
+
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=search_timeout)
|
|
61
|
+
except asyncio.TimeoutError:
|
|
62
|
+
proc.kill()
|
|
63
|
+
await proc.communicate()
|
|
64
|
+
return f"Error: grep timed out after {search_timeout} seconds"
|
|
65
|
+
except FileNotFoundError:
|
|
66
|
+
return "Error: 'rg' (ripgrep) not found on PATH. Install it from https://github.com/BurntSushi/ripgrep or via your package manager (e.g. 'apt install ripgrep', 'brew install ripgrep')."
|
|
67
|
+
except OSError as exc:
|
|
68
|
+
return f"Error: {exc}"
|
|
69
|
+
|
|
70
|
+
if proc.returncode == 1:
|
|
71
|
+
return "(no matches)"
|
|
72
|
+
if proc.returncode not in (0, 1):
|
|
73
|
+
err = stderr.decode("utf-8", errors="replace").strip()
|
|
74
|
+
return f"Error: rg exited {proc.returncode}: {err}"
|
|
75
|
+
|
|
76
|
+
output = stdout.decode("utf-8", errors="replace")
|
|
77
|
+
if len(output) > max_chars:
|
|
78
|
+
total_chars = len(output)
|
|
79
|
+
output = output[:max_chars]
|
|
80
|
+
last_newline = output.rfind("\n")
|
|
81
|
+
if last_newline > 0:
|
|
82
|
+
output = output[: last_newline + 1]
|
|
83
|
+
output += f"\n... (truncated: showing {max_chars} of {total_chars} chars)"
|
|
84
|
+
return output
|
|
85
|
+
|
|
86
|
+
return _make_tool_info(grep)
|
coreloop/tools/ls.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""ls.py -- directory listing tool."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ..tool_registry import ToolInfo
|
|
7
|
+
from ._shared import _resolve_safe, _resolve_safe_strict, _fmt_size, _make_tool_info
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_ls_tool(root: str, *, max_entries: int = 500) -> ToolInfo:
|
|
11
|
+
"""Build an ls tool scoped to *root*, listing up to max_entries per directory."""
|
|
12
|
+
root_path = Path(root).resolve()
|
|
13
|
+
|
|
14
|
+
async def ls(path: str = ".") -> str:
|
|
15
|
+
"""Use this to explore directory contents before reading or editing files.
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
path :
|
|
20
|
+
Relative or absolute path to the directory.
|
|
21
|
+
"""
|
|
22
|
+
try:
|
|
23
|
+
safe = _resolve_safe_strict(path, root_path)
|
|
24
|
+
except ValueError as exc:
|
|
25
|
+
return f"Error: {exc}"
|
|
26
|
+
|
|
27
|
+
safe_path = Path(safe)
|
|
28
|
+
if not safe_path.is_dir():
|
|
29
|
+
return f"Error: {path!r} is not a directory"
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
entries = sorted(os.listdir(safe))
|
|
33
|
+
except OSError as exc:
|
|
34
|
+
return f"Error: cannot list {path!r}: {exc}"
|
|
35
|
+
|
|
36
|
+
lines: list[str] = []
|
|
37
|
+
for name in entries[:max_entries]:
|
|
38
|
+
full = safe_path / name
|
|
39
|
+
try:
|
|
40
|
+
if full.is_symlink():
|
|
41
|
+
target = os.readlink(full)
|
|
42
|
+
abs_target = target if Path(target).is_absolute() else str(safe_path / target)
|
|
43
|
+
try:
|
|
44
|
+
_resolve_safe(abs_target, root_path)
|
|
45
|
+
lines.append(f"{name} -> {target}")
|
|
46
|
+
except ValueError:
|
|
47
|
+
lines.append(f"{name} -> <outside root>")
|
|
48
|
+
elif full.is_dir():
|
|
49
|
+
lines.append(f"{name}/")
|
|
50
|
+
else:
|
|
51
|
+
size = full.stat().st_size
|
|
52
|
+
lines.append(f"{name} ({_fmt_size(size)})")
|
|
53
|
+
except OSError:
|
|
54
|
+
lines.append(f"{name} (?)")
|
|
55
|
+
|
|
56
|
+
remaining = len(entries) - max_entries
|
|
57
|
+
if remaining > 0:
|
|
58
|
+
lines.append(f"... ({remaining} more entries not shown)")
|
|
59
|
+
|
|
60
|
+
return "\n".join(lines) if lines else "(empty directory)"
|
|
61
|
+
|
|
62
|
+
return _make_tool_info(ls)
|
coreloop/tools/read.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""read.py -- line-based file reader with offset/limit pagination."""
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ..tool_registry import ToolInfo
|
|
7
|
+
from ._shared import _resolve_safe_strict, _fmt_size, _make_tool_info
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_read_tool(
|
|
11
|
+
root: str, *, max_lines: int = 100, max_bytes: int = 10 * 1024 * 1024
|
|
12
|
+
) -> ToolInfo:
|
|
13
|
+
"""Build a read tool scoped to *root* with configurable line and byte limits."""
|
|
14
|
+
root_path = Path(root).resolve()
|
|
15
|
+
|
|
16
|
+
async def read(path: str, offset: int = 1, limit: int = max_lines) -> str:
|
|
17
|
+
"""Use this to read a file's contents. For large files, page through sections with offset and limit.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
path :
|
|
22
|
+
Relative or absolute path to the file.
|
|
23
|
+
offset :
|
|
24
|
+
Line number to start reading from (1-based).
|
|
25
|
+
limit :
|
|
26
|
+
Maximum number of lines to return (default 100).
|
|
27
|
+
"""
|
|
28
|
+
try:
|
|
29
|
+
safe = _resolve_safe_strict(path, root_path)
|
|
30
|
+
except ValueError as exc:
|
|
31
|
+
return f"Error: {exc}"
|
|
32
|
+
|
|
33
|
+
_offset = max(0, int(offset) - 1)
|
|
34
|
+
_limit = min(int(limit), max_lines)
|
|
35
|
+
|
|
36
|
+
if _limit <= 0:
|
|
37
|
+
return "Error: limit must be a positive integer"
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
file_size = Path(safe).stat().st_size
|
|
41
|
+
except OSError as exc:
|
|
42
|
+
return f"Error: cannot stat {path!r}: {exc}"
|
|
43
|
+
|
|
44
|
+
if file_size > max_bytes:
|
|
45
|
+
return (
|
|
46
|
+
f"Error: {path!r} is too large to read "
|
|
47
|
+
f"({_fmt_size(file_size)} > {_fmt_size(max_bytes)})"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
_stop = _offset + _limit
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
with open(safe, encoding="utf-8", errors="replace") as f:
|
|
54
|
+
lines = list(itertools.islice(f, _offset, _stop + 1))
|
|
55
|
+
except OSError as exc:
|
|
56
|
+
return f"Error: cannot read {path!r}: {exc}"
|
|
57
|
+
|
|
58
|
+
if not lines:
|
|
59
|
+
return ""
|
|
60
|
+
|
|
61
|
+
truncated = len(lines) > _limit
|
|
62
|
+
if truncated:
|
|
63
|
+
lines = lines[:_limit]
|
|
64
|
+
|
|
65
|
+
result = "".join(lines)
|
|
66
|
+
if truncated:
|
|
67
|
+
result += f"\n[Truncated: showing lines {_offset + 1}-{_offset + _limit}. Call again with offset={_offset + _limit + 1} to continue.]"
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
return _make_tool_info(read)
|
coreloop/types.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Message and tool-call type models matching OpenAI's chat format."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Usage(BaseModel):
|
|
9
|
+
"""Token usage reported by the model."""
|
|
10
|
+
|
|
11
|
+
prompt_tokens: int = 0
|
|
12
|
+
completion_tokens: int = 0
|
|
13
|
+
total_tokens: int = 0
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FunctionCall(BaseModel):
|
|
17
|
+
"""A function call inside a tool call."""
|
|
18
|
+
|
|
19
|
+
name: str = ""
|
|
20
|
+
arguments: str = ""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ToolCall(BaseModel):
|
|
24
|
+
"""A tool call emitted by the assistant."""
|
|
25
|
+
|
|
26
|
+
id: str
|
|
27
|
+
type: str = "function"
|
|
28
|
+
function: FunctionCall
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Message(BaseModel):
|
|
32
|
+
"""A single message in the conversation, OpenAI-compatible shape.
|
|
33
|
+
|
|
34
|
+
Usage:
|
|
35
|
+
Message(role="user", content="Hello")
|
|
36
|
+
Message(role="assistant", content=None, tool_calls=[...])
|
|
37
|
+
Message(role="tool", content="result", tool_call_id="...", name="read")
|
|
38
|
+
|
|
39
|
+
``reasoning`` is a streaming-only field used by thinking models (Qwen3,
|
|
40
|
+
DeepSeek). It is **not** included in the conversation history sent
|
|
41
|
+
back to the API (``_dump_messages`` omits it).
|
|
42
|
+
|
|
43
|
+
``partial`` is True for incremental content delta messages emitted while
|
|
44
|
+
the LLM is still generating. The final assembled message for a turn has
|
|
45
|
+
``partial=False``. Consumers that only want complete messages should skip
|
|
46
|
+
messages where ``partial is True``.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
role: str
|
|
50
|
+
content: str | None = None
|
|
51
|
+
tool_calls: list[ToolCall] | None = None
|
|
52
|
+
tool_call_id: str | None = None
|
|
53
|
+
name: str | None = None
|
|
54
|
+
reasoning: str | None = None
|
|
55
|
+
partial: bool = False
|
|
56
|
+
usage: Usage | None = None
|
|
57
|
+
duration: float | None = None
|
|
58
|
+
model: str | None = None
|
|
59
|
+
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _dump_messages(messages: list[Message]) -> list[dict]:
|
|
63
|
+
"""Serialize messages to the dict format the API expects."""
|
|
64
|
+
result: list[dict] = []
|
|
65
|
+
for m in messages:
|
|
66
|
+
d: dict = {"role": m.role}
|
|
67
|
+
if m.content is not None:
|
|
68
|
+
d["content"] = m.content
|
|
69
|
+
if m.tool_calls:
|
|
70
|
+
d["tool_calls"] = [
|
|
71
|
+
{
|
|
72
|
+
"id": tc.id,
|
|
73
|
+
"type": tc.type,
|
|
74
|
+
"function": {
|
|
75
|
+
"name": tc.function.name,
|
|
76
|
+
"arguments": tc.function.arguments,
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
for tc in m.tool_calls
|
|
80
|
+
]
|
|
81
|
+
if m.tool_call_id is not None:
|
|
82
|
+
d["tool_call_id"] = m.tool_call_id
|
|
83
|
+
if m.name is not None:
|
|
84
|
+
d["name"] = m.name
|
|
85
|
+
result.append(d)
|
|
86
|
+
return result
|
coreloop/web_tools.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Optional web tools: ``web_search`` and ``web_fetch``.
|
|
2
|
+
|
|
3
|
+
Requires the ``web`` extra: ``pip install coreloop[web]``
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from .tool_registry import ToolInfo
|
|
9
|
+
from .tools._shared import _make_tool_info
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def make_web_tools(searxng_url: str | None = None) -> list[ToolInfo]:
|
|
13
|
+
"""Build web search and fetch tools.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
searxng_url:
|
|
18
|
+
Base URL of your SearXNG instance (e.g. ``"http://localhost:8080"``).
|
|
19
|
+
Falls back to the ``SEARXNG_URL`` environment variable or pvl-webtools'
|
|
20
|
+
own default if ``None``.
|
|
21
|
+
"""
|
|
22
|
+
try:
|
|
23
|
+
from pvlwebtools import web_fetch as _web_fetch
|
|
24
|
+
from pvlwebtools import web_search as _web_search
|
|
25
|
+
except ImportError as exc:
|
|
26
|
+
raise ImportError(
|
|
27
|
+
"Web tools require 'pvl-webtools'. Install with: pip install coreloop[web]"
|
|
28
|
+
) from exc
|
|
29
|
+
|
|
30
|
+
async def web_search(
|
|
31
|
+
query: str,
|
|
32
|
+
max_results: int = 5,
|
|
33
|
+
domain_filter: str | None = None,
|
|
34
|
+
recency: Literal["all_time", "day", "week", "month", "year"] = "all_time",
|
|
35
|
+
) -> str:
|
|
36
|
+
"""Use this to find information on the web. Returns titles, URLs, and snippets for relevant pages.
|
|
37
|
+
|
|
38
|
+
Parameters
|
|
39
|
+
----------
|
|
40
|
+
query:
|
|
41
|
+
Search query string.
|
|
42
|
+
max_results:
|
|
43
|
+
Maximum number of results to return.
|
|
44
|
+
domain_filter:
|
|
45
|
+
Restrict results to a specific domain (e.g. ``"github.com"``).
|
|
46
|
+
recency:
|
|
47
|
+
Time filter: ``all_time``, ``day``, ``week``, ``month``, or ``year``.
|
|
48
|
+
"""
|
|
49
|
+
try:
|
|
50
|
+
results = await _web_search(
|
|
51
|
+
query=query,
|
|
52
|
+
max_results=max_results,
|
|
53
|
+
domain_filter=domain_filter or None,
|
|
54
|
+
recency=recency,
|
|
55
|
+
searxng_url=searxng_url,
|
|
56
|
+
)
|
|
57
|
+
except Exception as exc:
|
|
58
|
+
msg = str(exc)
|
|
59
|
+
if "SearXNG URL not configured" in msg:
|
|
60
|
+
msg += " or set searxng_url in ~/coreloop.toml"
|
|
61
|
+
return f"Error: {msg}"
|
|
62
|
+
|
|
63
|
+
if not results:
|
|
64
|
+
return "No results found."
|
|
65
|
+
|
|
66
|
+
lines: list[str] = []
|
|
67
|
+
for r in results:
|
|
68
|
+
lines.append(f"**{r.title}**")
|
|
69
|
+
lines.append(r.url)
|
|
70
|
+
if r.snippet:
|
|
71
|
+
lines.append(r.snippet)
|
|
72
|
+
if r.published_date:
|
|
73
|
+
lines.append(f"Published: {r.published_date}")
|
|
74
|
+
lines.append("")
|
|
75
|
+
return "\n".join(lines).rstrip()
|
|
76
|
+
|
|
77
|
+
async def web_fetch(
|
|
78
|
+
url: str,
|
|
79
|
+
extract_mode: Literal["markdown", "article", "raw", "metadata"] = "markdown",
|
|
80
|
+
) -> str:
|
|
81
|
+
"""Use this to read a specific web page when you already have its URL.
|
|
82
|
+
|
|
83
|
+
Parameters
|
|
84
|
+
----------
|
|
85
|
+
url:
|
|
86
|
+
HTTP/HTTPS URL to fetch.
|
|
87
|
+
extract_mode:
|
|
88
|
+
How to extract content: ``markdown`` (full page as markdown),
|
|
89
|
+
``article`` (main article text only), ``raw`` (raw HTML),
|
|
90
|
+
or ``metadata`` (title, description, etc.).
|
|
91
|
+
"""
|
|
92
|
+
try:
|
|
93
|
+
result = await _web_fetch(url=url, extract_mode=extract_mode)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
return f"Error: {exc}"
|
|
96
|
+
return result.content
|
|
97
|
+
|
|
98
|
+
return [_make_tool_info(web_search), _make_tool_info(web_fetch)]
|