coreloop 0.1.4__tar.gz → 0.1.6__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 (32) hide show
  1. {coreloop-0.1.4 → coreloop-0.1.6}/PKG-INFO +1 -1
  2. {coreloop-0.1.4 → coreloop-0.1.6}/pyproject.toml +1 -1
  3. {coreloop-0.1.4 → coreloop-0.1.6}/pyproject.toml.orig +1 -1
  4. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/.coreloop.toml +1 -1
  5. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/_api_client.py +6 -5
  6. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/_tool_execution.py +2 -2
  7. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/agent.py +2 -2
  8. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/cli/__init__.py +7 -5
  9. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/cli/_tools.py +1 -2
  10. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/config.py +1 -0
  11. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/hooks.py +1 -1
  12. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/profiles.py +1 -4
  13. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/structured.py +26 -8
  14. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/tool_registry.py +2 -3
  15. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/tools/_shared.py +4 -1
  16. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/tools/bash.py +1 -1
  17. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/tools/edit.py +6 -2
  18. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/tools/grep.py +2 -2
  19. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/tools/ls.py +1 -1
  20. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/tools/read.py +7 -3
  21. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/types.py +2 -2
  22. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/web_tools.py +8 -7
  23. {coreloop-0.1.4 → coreloop-0.1.6}/LICENSE +0 -0
  24. {coreloop-0.1.4 → coreloop-0.1.6}/README.md +0 -0
  25. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/__init__.py +4 -4
  26. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/__main__.py +0 -0
  27. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/_cache.py +0 -0
  28. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/_logging.py +0 -0
  29. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/cli/_run.py +0 -0
  30. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/complete.py +0 -0
  31. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/py.typed +0 -0
  32. {coreloop-0.1.4 → coreloop-0.1.6}/src/coreloop/tools/__init__.py +1 -1
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: coreloop
3
- Version: 0.1.4
3
+ Version: 0.1.6
4
4
  Summary: A lightweight async tool-calling agent for any OpenAI-compatible API, usable as a library or CLI
5
5
  Keywords: llm,agent,tool-calling,openai,ollama,cli,async,streaming,hooks,httpx,local-models
6
6
  Author: Chris Kilner
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "coreloop"
3
- version = "0.1.4"
3
+ version = "0.1.6"
4
4
  description = "A lightweight async tool-calling agent for any OpenAI-compatible API, usable as a library or CLI"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "coreloop"
3
- version = "0.1.4"
3
+ version = "0.1.6"
4
4
  description = "A lightweight async tool-calling agent for any OpenAI-compatible API, usable as a library or CLI"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -96,6 +96,6 @@ max_timeout = 300
96
96
  # [config.tool.web_search]
97
97
  # url = "http://localhost:8888"
98
98
 
99
- [config.ui.ma]
99
+ [config.ui.core]
100
100
  max_turns = 20
101
101
  tool_result_preview = 300
@@ -17,7 +17,8 @@ arrive at the end.
17
17
  import json
18
18
  import logging
19
19
  import time
20
- from typing import Any, AsyncIterator, Protocol
20
+ from collections.abc import AsyncIterator
21
+ from typing import Any, Protocol
21
22
 
22
23
  import httpx
23
24
  from pydantic import BaseModel
@@ -172,7 +173,7 @@ class OpenAIBackend:
172
173
  continue
173
174
 
174
175
  # --- usage (arrives in a separate no-choices chunk after finish_reason) ---
175
- if "usage" in chunk and chunk["usage"]:
176
+ if chunk.get("usage"):
176
177
  u = chunk["usage"]
177
178
  pt = u.get("prompt_tokens", 0)
178
179
  ct = u.get("completion_tokens", 0)
@@ -228,13 +229,13 @@ class OpenAIBackend:
228
229
  "function": {"name": "", "arguments": ""},
229
230
  },
230
231
  )
231
- if "id" in tc_delta and tc_delta["id"]:
232
+ if tc_delta.get("id"):
232
233
  partial["id"] = tc_delta["id"]
233
234
  if "function" in tc_delta:
234
235
  fn = tc_delta["function"]
235
- if "name" in fn and fn["name"]:
236
+ if fn.get("name"):
236
237
  partial["function"]["name"] += fn["name"]
237
- if "arguments" in fn and fn["arguments"]:
238
+ if fn.get("arguments"):
238
239
  partial["function"]["arguments"] += fn["arguments"]
239
240
 
240
241
  # --- assemble on finish, but keep reading for the usage chunk ---
@@ -70,11 +70,11 @@ async def run_tool(info: ToolInfo, args: dict[str, Any], timeout: float) -> str:
70
70
  async with asyncio.timeout(timeout):
71
71
  result = await info.fn(**args)
72
72
  return str(result)
73
- except asyncio.TimeoutError:
73
+ except TimeoutError:
74
74
  logger.error("Tool '%s' timed out after %.1fs", info.name, timeout)
75
75
  return f"Error: tool '{info.name}' timed out after {timeout}s"
76
76
  except asyncio.CancelledError:
77
77
  raise
78
- except Exception as exc:
78
+ except Exception as exc: # noqa: BLE001 -- tool failures are reported to the LLM, not raised
79
79
  logger.error("Tool '%s' raised %s: %s", info.name, type(exc).__name__, exc)
80
80
  return f"Error in tool '{info.name}': {exc}"
@@ -3,9 +3,9 @@
3
3
  import asyncio
4
4
  import logging
5
5
  import uuid
6
- from collections.abc import Sequence
6
+ from collections.abc import AsyncIterator, Sequence
7
7
  from pathlib import Path
8
- from typing import TYPE_CHECKING, Any, AsyncIterator
8
+ from typing import TYPE_CHECKING, Any
9
9
 
10
10
  if TYPE_CHECKING:
11
11
  from .config import AgentConfig
@@ -162,10 +162,10 @@ def main(
162
162
  Edit it to set your provider credentials and default tools.
163
163
 
164
164
  [bold]Examples[/bold]
165
- ma REPL with default profile (Ollama)
166
- ma --profile openai -p "Hello" one-shot with a named profile
167
- ma -m gpt-4o --tools read,ls,grep --root . override model and add file tools
168
- ma --base-url http://localhost:11434/v1 -m qwen direct endpoint, no config needed
165
+ core REPL with default profile (Ollama)
166
+ core --profile openai -p "Hello" one-shot with a named profile
167
+ core -m gpt-4o --tools read,ls,grep --root . override model and add file tools
168
+ core --base-url http://localhost:11434/v1 -m qwen direct endpoint, no config needed
169
169
  """
170
170
  if ctx.invoked_subcommand is not None:
171
171
  return
@@ -234,7 +234,9 @@ def main(
234
234
  built_tools = build_tools(tools_opt, agent_cfg.root, searxng_url, raw)
235
235
 
236
236
  if max_turns is None:
237
- max_turns = int(get_config("ui.ma.max_turns", raw, 20))
237
+ max_turns = int(
238
+ get_config("ui.core.max_turns", raw) or get_config("ui.ma.max_turns", raw, 20)
239
+ )
238
240
 
239
241
  try:
240
242
  agent = Agent.from_config(agent_cfg, hooks=MaxTurnsHook(max_turns), tools=built_tools)
@@ -72,8 +72,7 @@ def build_tools(
72
72
  web_tools = make_web_tools(searxng_url=searxng_url)
73
73
  except ImportError:
74
74
  typer.echo(
75
- "To use web_search or web_fetch, install web extras: "
76
- "pip install coreloop[web]",
75
+ "To use web_search or web_fetch, install web extras: pip install coreloop[web]",
77
76
  err=True,
78
77
  )
79
78
  raise typer.Exit(1)
@@ -20,6 +20,7 @@ from typing import Any
20
20
  @dataclass
21
21
  class AgentConfig:
22
22
  """Portable, serialisable bundle of Agent constructor parameters."""
23
+
23
24
  model: str
24
25
  base_url: str = "http://localhost:11434/v1"
25
26
  api_key: str | None = None
@@ -142,5 +142,5 @@ async def _safe_hook(hooks: AgentHooks, method: str, *args: Any) -> Any:
142
142
  """Call a hook method, logging and swallowing any exceptions."""
143
143
  try:
144
144
  return await getattr(hooks, method)(*args)
145
- except Exception as exc:
145
+ except Exception as exc: # noqa: BLE001 -- a broken hook must not abort the agent
146
146
  logger.warning("Hook %s raised %s: %s", method, type(exc).__name__, exc)
@@ -57,10 +57,7 @@ _CONFIG_PATH = _find_config_path()
57
57
  def _load_config(path: Path | None = None) -> dict[str, Any]:
58
58
  p = path or _CONFIG_PATH
59
59
  if not p.exists():
60
- msg = (
61
- f"Config file not found at {p}. "
62
- f"Create ~/{_CONFIG_FILENAME} or set CORELOOP_CONFIG."
63
- )
60
+ msg = f"Config file not found at {p}. Create ~/{_CONFIG_FILENAME} or set CORELOOP_CONFIG."
64
61
  raise FileNotFoundError(msg)
65
62
  return tomllib.loads(p.read_bytes().decode("utf-8"))
66
63
 
@@ -11,6 +11,14 @@ from pydantic import BaseModel
11
11
 
12
12
  __all__ = ["to_strict_schema"]
13
13
 
14
+ # Annotation keywords strict validators reject. Stripped from schema *nodes*
15
+ # only -- never from the name maps below, where these appear as field names.
16
+ _STRIP_KEYWORDS = ("title", "default")
17
+
18
+ # Dicts keyed by user-chosen names rather than JSON Schema keywords. Their keys
19
+ # are data; only their values are schema nodes to recurse into.
20
+ _NAME_MAPS = ("properties", "$defs", "definitions", "patternProperties")
21
+
14
22
 
15
23
  def _tighten(node: Any) -> None:
16
24
  """Recursively rewrite *node* in place into a strict-legal schema."""
@@ -21,15 +29,22 @@ def _tighten(node: Any) -> None:
21
29
  if not isinstance(node, dict):
22
30
  return
23
31
 
24
- node.pop("title", None)
25
- node.pop("default", None)
32
+ for keyword in _STRIP_KEYWORDS:
33
+ node.pop(keyword, None)
26
34
 
27
- if isinstance(node.get("properties"), dict):
35
+ properties = node.get("properties")
36
+ if isinstance(properties, dict):
28
37
  node["additionalProperties"] = False
29
- node["required"] = list(node["properties"])
38
+ node["required"] = list(properties)
30
39
 
31
- for value in node.values():
32
- _tighten(value)
40
+ for key, value in node.items():
41
+ if key in _NAME_MAPS and isinstance(value, dict):
42
+ # Recurse into the definitions, not over their names. A field called
43
+ # "title" or "default" must survive keyword stripping.
44
+ for subschema in value.values():
45
+ _tighten(subschema)
46
+ else:
47
+ _tighten(value)
33
48
 
34
49
 
35
50
  def to_strict_schema(schema: type[BaseModel]) -> dict[str, Any]:
@@ -37,8 +52,11 @@ def to_strict_schema(schema: type[BaseModel]) -> dict[str, Any]:
37
52
 
38
53
  Every object with ``properties`` gets ``additionalProperties: false`` and a
39
54
  ``required`` list naming **all** its properties; ``title`` and ``default``
40
- are stripped everywhere. ``$defs`` / ``$ref`` are preserved -- only rewritten
41
- in place.
55
+ are stripped from schema nodes. ``$defs`` / ``$ref`` are preserved -- only
56
+ rewritten in place.
57
+
58
+ Field names are never treated as keywords: a model with a field called
59
+ ``title`` or ``default`` keeps it.
42
60
 
43
61
  ``X | None`` fields keep working: Pydantic emits ``anyOf: [..., {"type":
44
62
  "null"}]``, so the field stays formally required while remaining nullable.
@@ -4,8 +4,9 @@ import inspect
4
4
  import types
5
5
  import typing
6
6
  import warnings
7
+ from collections.abc import Callable, Coroutine
7
8
  from dataclasses import dataclass
8
- from typing import Any, Callable, Coroutine, overload
9
+ from typing import Any, overload
9
10
 
10
11
 
11
12
  @dataclass
@@ -113,7 +114,6 @@ def tool(
113
114
  allow_override: bool = False,
114
115
  ) -> ToolInfo:
115
116
  """Use as @tool directly on a function."""
116
- ...
117
117
 
118
118
 
119
119
  @overload
@@ -124,7 +124,6 @@ def tool(
124
124
  allow_override: bool = False,
125
125
  ) -> Callable[[Callable[..., Coroutine[Any, Any, str]]], ToolInfo]:
126
126
  """Use as @tool(...) with keyword arguments."""
127
- ...
128
127
 
129
128
 
130
129
  def tool(
@@ -11,7 +11,10 @@ _MAX_READ_BYTES = 10 * 1024 * 1024 # 10 MB
11
11
  def _resolve_safe(requested: str, root: "Path | str") -> str:
12
12
  """Resolve *requested* relative to *root* and raise ValueError on path traversal."""
13
13
  if not isinstance(requested, str):
14
- raise ValueError(f"path must be a string, got {type(requested).__name__}")
14
+ # ValueError, not TypeError: callers catch ValueError for every path failure.
15
+ raise ValueError( # noqa: TRY004
16
+ f"path must be a string, got {type(requested).__name__}"
17
+ )
15
18
 
16
19
  # Normalize Windows-style separators so traversal is caught on all platforms.
17
20
  raw = Path(requested.replace("\\", "/"))
@@ -130,7 +130,7 @@ def make_bash_tool(
130
130
  )
131
131
  try:
132
132
  stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=_timeout)
133
- except asyncio.TimeoutError:
133
+ except TimeoutError:
134
134
  _kill_process_group(proc)
135
135
  await proc.communicate()
136
136
  return (
@@ -1,5 +1,6 @@
1
1
  """edit.py -- atomic string-replace edit tool for text files."""
2
2
 
3
+ import asyncio
3
4
  import os
4
5
  import tempfile
5
6
  from pathlib import Path
@@ -67,9 +68,12 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
67
68
  f"({_fmt_size(file_size)} > {_fmt_size(max_bytes)})"
68
69
  )
69
70
 
70
- try:
71
+ def _read_all() -> str:
71
72
  with open(safe, encoding="utf-8", errors="strict") as f:
72
- content = f.read()
73
+ return f.read()
74
+
75
+ try:
76
+ content = await asyncio.to_thread(_read_all)
73
77
  except UnicodeDecodeError:
74
78
  return f"Error: {path!r} contains non-UTF-8 bytes; cannot edit"
75
79
  except OSError as exc:
@@ -4,7 +4,7 @@ import asyncio
4
4
  from pathlib import Path
5
5
 
6
6
  from ..tool_registry import ToolInfo
7
- from ._shared import _resolve_safe_strict, _make_tool_info
7
+ from ._shared import _make_tool_info, _resolve_safe_strict
8
8
 
9
9
 
10
10
  def make_grep_tool(root: str, *, max_chars: int = 20_000, search_timeout: float = 30.0) -> ToolInfo:
@@ -58,7 +58,7 @@ def make_grep_tool(root: str, *, max_chars: int = 20_000, search_timeout: float
58
58
  )
59
59
  try:
60
60
  stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=search_timeout)
61
- except asyncio.TimeoutError:
61
+ except TimeoutError:
62
62
  proc.kill()
63
63
  await proc.communicate()
64
64
  return f"Error: grep timed out after {search_timeout} seconds"
@@ -4,7 +4,7 @@ import os
4
4
  from pathlib import Path
5
5
 
6
6
  from ..tool_registry import ToolInfo
7
- from ._shared import _resolve_safe, _resolve_safe_strict, _fmt_size, _make_tool_info
7
+ from ._shared import _fmt_size, _make_tool_info, _resolve_safe, _resolve_safe_strict
8
8
 
9
9
 
10
10
  def make_ls_tool(root: str, *, max_entries: int = 500) -> ToolInfo:
@@ -1,10 +1,11 @@
1
1
  """read.py -- line-based file reader with offset/limit pagination."""
2
2
 
3
+ import asyncio
3
4
  import itertools
4
5
  from pathlib import Path
5
6
 
6
7
  from ..tool_registry import ToolInfo
7
- from ._shared import _resolve_safe_strict, _fmt_size, _make_tool_info
8
+ from ._shared import _fmt_size, _make_tool_info, _resolve_safe_strict
8
9
 
9
10
 
10
11
  def make_read_tool(
@@ -49,9 +50,12 @@ def make_read_tool(
49
50
 
50
51
  _stop = _offset + _limit
51
52
 
52
- try:
53
+ def _read_slice() -> list[str]:
53
54
  with open(safe, encoding="utf-8", errors="replace") as f:
54
- lines = list(itertools.islice(f, _offset, _stop + 1))
55
+ return list(itertools.islice(f, _offset, _stop + 1))
56
+
57
+ try:
58
+ lines = await asyncio.to_thread(_read_slice)
55
59
  except OSError as exc:
56
60
  return f"Error: cannot read {path!r}: {exc}"
57
61
 
@@ -1,6 +1,6 @@
1
1
  """Message and tool-call type models matching OpenAI's chat format."""
2
2
 
3
- from datetime import datetime, timezone
3
+ from datetime import UTC, datetime
4
4
 
5
5
  from pydantic import BaseModel, Field
6
6
 
@@ -56,7 +56,7 @@ class Message(BaseModel):
56
56
  usage: Usage | None = None
57
57
  duration: float | None = None
58
58
  model: str | None = None
59
- timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
59
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
60
60
 
61
61
 
62
62
  def _dump_messages(messages: list[Message]) -> list[dict]:
@@ -32,12 +32,14 @@ def _metadata(html_content: str) -> str:
32
32
  meta["title"] = _html.unescape(m.group(1).strip())
33
33
  if m := re.search(
34
34
  r'<meta[^>]*name=["\']description["\'][^>]*content=["\']([^"\']*)["\']',
35
- html_content, re.IGNORECASE,
35
+ html_content,
36
+ re.IGNORECASE,
36
37
  ):
37
38
  meta["description"] = _html.unescape(m.group(1).strip())
38
39
  for prop, value in re.findall(
39
40
  r'<meta[^>]*property=["\']og:(\w+)["\'][^>]*content=["\']([^"\']*)["\']',
40
- html_content, re.IGNORECASE,
41
+ html_content,
42
+ re.IGNORECASE,
41
43
  ):
42
44
  meta[f"og_{prop}"] = _html.unescape(value.strip())
43
45
  return "\n".join(f"{k}: {v}" for k, v in meta.items())
@@ -87,7 +89,7 @@ def make_web_tools(searxng_url: str | None = None) -> list[ToolInfo]:
87
89
  r = await client.get(f"{base}/search", params=params)
88
90
  r.raise_for_status()
89
91
  data = r.json()
90
- except Exception as exc:
92
+ except Exception as exc: # noqa: BLE001 -- any search failure becomes a tool error string
91
93
  msg = str(exc)
92
94
  if "SearXNG URL not configured" in msg:
93
95
  msg += " or set searxng_url in ~/coreloop.toml"
@@ -129,11 +131,10 @@ def make_web_tools(searxng_url: str | None = None) -> list[ToolInfo]:
129
131
  ) as client:
130
132
  r = await client.get(url)
131
133
  r.raise_for_status()
132
- if cl := r.headers.get("content-length"):
133
- if int(cl) > _MAX_CONTENT_BYTES:
134
- return f"Error: Content too large ({cl} bytes)"
134
+ if (cl := r.headers.get("content-length")) and int(cl) > _MAX_CONTENT_BYTES:
135
+ return f"Error: Content too large ({cl} bytes)"
135
136
  page_html = r.text
136
- except Exception as exc:
137
+ except Exception as exc: # noqa: BLE001 -- any fetch failure becomes a tool error string
137
138
  return f"Error: {exc}"
138
139
 
139
140
  if extract_mode == "raw":
File without changes
File without changes
@@ -3,14 +3,14 @@
3
3
  from .agent import Agent
4
4
  from .complete import complete
5
5
  from .config import AgentConfig
6
+ from .hooks import AgentHooks, MaxTurnsHook
7
+ from .structured import to_strict_schema
8
+ from .tool_registry import ToolInfo, clear_registry, get_tool, list_tools, tool
6
9
  from .tools import make_tools
7
10
  from .tools.bash import make_bash_tool
8
11
  from .tools.grep import make_grep_tool
9
- from .hooks import AgentHooks, MaxTurnsHook
10
- from .tool_registry import ToolInfo, clear_registry, get_tool, list_tools, tool
11
- from .structured import to_strict_schema
12
- from .web_tools import make_web_tools
13
12
  from .types import FunctionCall, Message, ToolCall, Usage
13
+ from .web_tools import make_web_tools
14
14
 
15
15
  __all__ = [
16
16
  "Agent",
File without changes
@@ -3,9 +3,9 @@ from pathlib import Path
3
3
 
4
4
  from ..tool_registry import ToolInfo
5
5
  from .edit import make_edit_tool
6
+ from .grep import make_grep_tool
6
7
  from .ls import make_ls_tool
7
8
  from .read import make_read_tool
8
- from .grep import make_grep_tool
9
9
 
10
10
 
11
11
  def make_tools(