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.
@@ -0,0 +1,350 @@
1
+ Metadata-Version: 2.4
2
+ Name: coreloop
3
+ Version: 0.1.0
4
+ Summary: A lightweight async tool-calling agent for any OpenAI-compatible API, usable as a library or CLI
5
+ Keywords: llm,agent,tool-calling,openai,ollama,cli,async,streaming,hooks,httpx,local-models
6
+ Author: Chris Kilner
7
+ Author-email: Chris Kilner <chris@rhiza.fr>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Typing :: Typed
18
+ Requires-Dist: httpx>=0.28.1
19
+ Requires-Dist: typer>=0.26.1
20
+ Requires-Dist: pydantic>=2.0,<3
21
+ Requires-Dist: diskcache>=5.6.3
22
+ Requires-Dist: python-dotenv>=1.0.1
23
+ Requires-Dist: rich>=13.0.0
24
+ Requires-Dist: pvl-webtools[markdown]>=0.1.0 ; extra == 'web'
25
+ Requires-Python: >=3.14
26
+ Project-URL: Homepage, https://github.com/rhiza-fr/coreloop
27
+ Project-URL: Repository, https://github.com/rhiza-fr/coreloop
28
+ Project-URL: Issues, https://github.com/rhiza-fr/coreloop/issues
29
+ Provides-Extra: web
30
+ Description-Content-Type: text/markdown
31
+
32
+ # coreloop
33
+
34
+ A lightweight async tool-calling agent for any OpenAI-compatible API (via `httpx`).
35
+ The core is an async generator loop that streams `Message` objects; you observe and
36
+ intercept it via lifecycle hooks. Usable as a library or through a minimal CLI.
37
+
38
+ The minimal core imposes no forced overhead, so it pairs well with small local
39
+ models; early exit via hooks and `stop()` makes high-throughput batch work fast and
40
+ keeps token costs down.
41
+
42
+ Built-in tools: path-scoped `read`, `ls`, `edit`, `grep`; a `bash` tool with
43
+ best-effort guardrails (not a security sandbox — see below); optional `web_search`
44
+ and `web_fetch` (via the `[web]` extra).
45
+
46
+ - **Observability** — [hook into every stage of the loop](#hooks): before/after each turn, LLM call, and tool execution
47
+ — examples: [streaming](examples/example6_streaming.py) · [raw message stream](examples/example7_raw_messages.py) · [logging & timing hooks](examples/example8_hooks.py)
48
+ - **Loop control** — [stop cleanly, abort immediately, or inject responses mid-run](#agent): `stop()`, `abort()`, `on_before_llm`
49
+ — examples: [lifecycle control](examples/example3_agent_lifecycle.py) · [intercept & replace results](examples/example9_intrusive_hooks.py)
50
+ - **Extensibility** — [register custom async tools with `@tool`](#custom-tools): inferred JSON Schema, callable directly or by name
51
+ — examples: [custom tools](examples/example5_customtools.py) · [subagents](examples/example12_subagents.py)
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ pip install coreloop
57
+ pip install "coreloop[web]" # adds web_search and web_fetch
58
+ ```
59
+
60
+ ## Library quick-start
61
+
62
+ ```python
63
+ import asyncio
64
+ from coreloop import Agent, Message
65
+
66
+ agent = Agent(
67
+ model="gpt-4o-mini",
68
+ base_url="https://api.openai.com/v1",
69
+ api_key="sk-...",
70
+ tools=["read", "ls", "grep"],
71
+ root="/tmp/sandbox",
72
+ )
73
+
74
+ async def main():
75
+ async for msg in agent.run([Message(role="user", content="What files are here?")]):
76
+ if msg.role == "assistant" and not msg.partial and msg.content:
77
+ print(msg.content)
78
+
79
+ asyncio.run(main())
80
+ ```
81
+
82
+ Or load settings from a named profile in `~/coreloop.toml`:
83
+
84
+ ```python
85
+ agent = Agent.from_profile("openai")
86
+ ```
87
+
88
+ ## CLI
89
+
90
+ `core` is a REPL / one-shot runner with profile support. On first run it copies
91
+ the bundled `coreloop.toml` to `~/coreloop.toml` — edit that file to set
92
+ your default model, tools, and provider credentials.
93
+
94
+ ```bash
95
+ # Interactive REPL using the default profile (Ollama)
96
+ core
97
+
98
+ # One-shot with a named profile
99
+ core --profile openai -p "Summarise this repo"
100
+
101
+ # Override model and enable file tools
102
+ core --profile openai --model gpt-4o --tools read,ls,grep --root .
103
+
104
+ # Bypass profiles entirely
105
+ core --base-url https://api.openai.com/v1 --api-key $OPENAI_API_KEY --model gpt-4o-mini -p "Hello"
106
+
107
+ # Enable reasoning
108
+ core --think -p "Explain this step by step" --model qwen3-14b
109
+ ```
110
+
111
+ | Flag | Default | Description |
112
+ |------|---------|-------------|
113
+ | `--profile` | `default` | Named profile from `~/coreloop.toml` |
114
+ | `-m, --model` | profile value | Model name — overrides profile (`CORELOOP_MODEL`) |
115
+ | `--base-url` | profile value | API base URL — overrides profile (`CORELOOP_BASE_URL`) |
116
+ | `--api-key` | profile value | API key — overrides profile (`CORELOOP_API_KEY`) |
117
+ | `-s, --system` | — | System prompt |
118
+ | `--tools` | profile value | Comma-separated: `read,ls,edit,grep,bash,web_search,web_fetch` |
119
+ | `-r, --root` | cwd | Allowed root directory for file tools |
120
+ | `--searxng-url` | `$SEARXNG_URL` | SearXNG base URL for web tools |
121
+ | `-t, --llm-timeout` | profile value | Asyncio wall-clock timeout per LLM turn (seconds) |
122
+ | `--tool-timeout` | profile value | Hard timeout per tool call (seconds) |
123
+ | `--http-request-timeout` | profile value | httpx per-chunk read timeout (seconds) |
124
+ | `--cache-dir` | profile value | LLM response cache directory |
125
+ | `--no-cache` | off | Disable response caching |
126
+ | `-e, --extra` | — | Extra JSON merged into the API request body |
127
+ | `--think/--no-think` | off | Set `reasoning_effort` to `medium` / `none` |
128
+ | `-n, --max-turns` | `20` | Maximum loop iterations |
129
+ | `-p, --prompt` | — | Run once and print final response |
130
+ | `--json` | off | Output all non-partial messages as JSONL |
131
+ | `-l, --log-level` | — | `DEBUG`, `INFO`, `WARNING`, `ERROR` |
132
+
133
+ REPL commands: `/quit` `/exit` `/q` to exit; `/new` to clear history;
134
+ `/model <name>` to switch models; `/root <path>` to change the file-tool root.
135
+
136
+ ## `Agent`
137
+
138
+ ```python
139
+ Agent(
140
+ model: str,
141
+ base_url: str = "http://localhost:11434/v1",
142
+ api_key: str | None = None,
143
+ system: str | None = None,
144
+ tools: list[str | ToolInfo] | None = None,
145
+ root: str | Path | None = None,
146
+ http_request_timeout: float = 300.0, # httpx per-chunk read timeout
147
+ tool_timeout: float = 360.0, # hard wall per tool call
148
+ llm_timeout: float = 300.0, # asyncio wall for the entire LLM turn
149
+ hooks: AgentHooks | None = None,
150
+ llm_extra_body: dict | None = None,
151
+ cache_dir: Path | str | None = "~/.cache/coreloop-llm-cache",
152
+ )
153
+ ```
154
+
155
+ `tools` accepts built-in names (`"read"`, `"ls"`, `"edit"`, `"grep"`, `"bash"`,
156
+ `"web_search"`, `"web_fetch"`), names of `@tool`-registered functions, or `ToolInfo`
157
+ objects. File tools are scoped to `root`; an unknown name raises `ValueError`. An agent
158
+ has exactly the tools you list — there is no implicit inclusion of the global registry.
159
+
160
+ `run(messages)` is an async generator. Partial streaming chunks have `partial=True`;
161
+ the final assembled message for each LLM turn has `partial=False`. Pass
162
+ `usage=Usage()` to accumulate token counts across turns.
163
+
164
+ | Method / property | Description |
165
+ |---|---|
166
+ | `run(messages, *, usage=None)` | Run the agent loop, yielding `Message` objects |
167
+ | `stop()` | Finish the current turn cleanly, then exit. Safe from a hook or tool. |
168
+ | `abort()` | Cancel immediately; `on_after_agent` is not called |
169
+ | `reset()` | Clear history and stop flag |
170
+ | `stopped` | `True` after `stop()` or `abort()` |
171
+ | `messages` | Shallow copy of full chat history from the last `run()` |
172
+
173
+ **Restart pattern** — pass `agent.messages` to keep history across runs:
174
+
175
+ ```python
176
+ async for msg in agent.run([Message(role="user", content="Hello")]):
177
+ ...
178
+
179
+ agent.model = "stronger-model"
180
+ async for msg in agent.run(agent.messages + [Message(role="user", content="Now do X")]):
181
+ ...
182
+ ```
183
+
184
+ ## Built-in tools
185
+
186
+ All file tools reject path traversal and are scoped to `root`.
187
+
188
+ | Tool | Description |
189
+ |------|-------------|
190
+ | `read` | Read a text file; `offset`/`limit` for paging (1-based line numbers) |
191
+ | `ls` | List a directory |
192
+ | `edit` | Replace an exact string in a file; fails on ambiguous matches |
193
+ | `grep` | Regex search via `rg`; supports `type`, `after_context`, `files_with_matches` |
194
+ | `bash` | Run arbitrary shell commands via `bash -c`; kills the entire process group on timeout |
195
+
196
+ > **`bash` is not sandboxed.** It runs whatever the model sends with your full
197
+ > user privileges. The `workdir` is scoped to `root`, but a command can still read,
198
+ > write, or delete anything your account can reach, and make network calls. The
199
+ > dangerous-pattern blocklist (e.g. `rm -rf /`, `mkfs`, fork bombs) is a speed bump
200
+ > against obvious accidents, **not** a security boundary — trivial variants slip
201
+ > through (`curl … | bash`, `python -c "…"`, unusual flag orders). Only enable
202
+ > `bash` for models and prompts you trust, and prefer running in a container or VM.
203
+
204
+ Web tools require `pip install "coreloop[web]"` and a running
205
+ [SearXNG](https://docs.searxng.org/) instance:
206
+
207
+ ```bash
208
+ docker run -d -p 8080:8080 searxng/searxng
209
+ ```
210
+
211
+ | Tool | Description |
212
+ |------|-------------|
213
+ | `web_search` | Search via SearXNG; returns titles, URLs, snippets; supports `max_results`, `domain_filter`, `recency` |
214
+ | `web_fetch` | Fetch a URL; `extract_mode`: `markdown` (default), `article`, `raw`, `metadata` |
215
+
216
+ ## Custom tools
217
+
218
+ ```python
219
+ from coreloop import tool
220
+
221
+ @tool
222
+ async def read_env(name: str) -> str:
223
+ """Read an environment variable."""
224
+ import os
225
+ return os.environ.get(name, "(not set)")
226
+
227
+ # Attach by name or pass the ToolInfo object directly
228
+ agent = Agent(model="...", tools=["read_env"])
229
+ agent = Agent(model="...", tools=[read_env]) # equivalent
230
+ ```
231
+
232
+ `@tool` infers JSON Schema from type annotations (`str`, `int`, `float`, `bool`,
233
+ `list[T]`, `dict`, `Optional[T]`). Unrecognised types fall back to `string` with a
234
+ warning. Override name or description:
235
+
236
+ ```python
237
+ @tool(name="my_read", description="Read a local file")
238
+ async def _impl(path: str) -> str:
239
+ ...
240
+
241
+ @tool(allow_override=True) # re-register if a tool with that name already exists
242
+ async def read_env(name: str) -> str:
243
+ ...
244
+ ```
245
+
246
+ The decorated object is both a `ToolInfo` and directly callable (`await my_tool(...)`
247
+ works alongside registration).
248
+
249
+ Registry helpers:
250
+
251
+ ```python
252
+ from coreloop import list_tools, get_tool, clear_registry
253
+
254
+ list_tools() # list[ToolInfo] — all globally registered tools
255
+ get_tool("read_env") # ToolInfo | None
256
+ clear_registry() # remove all tools (useful in tests)
257
+ ```
258
+
259
+ ## Hooks
260
+
261
+ Subclass `AgentHooks` to observe or intercept any stage of the loop:
262
+
263
+ ```python
264
+ from coreloop import AgentHooks
265
+
266
+ class LogHook(AgentHooks):
267
+ async def on_before_tool(self, agent, name, args):
268
+ print(f"→ {name}({args})")
269
+ return None # None = run the tool; return str to inject a result instead
270
+
271
+ agent = Agent(..., hooks=LogHook())
272
+ ```
273
+
274
+ Hook firing order per turn:
275
+
276
+ ```
277
+ on_before_turn
278
+ on_before_llm → return Message to skip the LLM call entirely
279
+ <LLM streams>
280
+ on_after_llm → return Message to replace before appending to history
281
+ for each tool (in parallel):
282
+ on_before_tool → return str to skip tool execution
283
+ <tool runs>
284
+ on_after_tool → return str to replace result in history
285
+ on_after_turn
286
+ ```
287
+
288
+ `on_before_agent` / `on_after_agent` bracket the entire `run()` call.
289
+ `on_after_agent` is **not** called after `abort()`. Hook exceptions are logged and
290
+ swallowed — they cannot crash the agent.
291
+
292
+ `MaxTurnsHook(n)` calls `agent.stop()` after `n` turns; the counter resets on each
293
+ `run()`, so it enforces a per-run limit, not a lifetime one.
294
+
295
+ ## Config profiles
296
+
297
+ `Agent.from_profile("openai")` builds an `AgentConfig` from `~/coreloop.toml`
298
+ (or `$CORELOOP_CONFIG`). Every profile inherits from `[profiles.default]`; named
299
+ profiles override individual keys.
300
+
301
+ ```toml
302
+ [profiles.default]
303
+ base_url = "http://localhost:11434/v1"
304
+ model = "qwen3.5:9b"
305
+
306
+ [profiles.openai]
307
+ base_url = "https://api.openai.com/v1"
308
+ api_key = "{{OPENAI_API_KEY}}"
309
+ model = "gpt-4o-mini"
310
+ tools = ["read", "ls", "grep"]
311
+
312
+ [profiles.together]
313
+ base_url = "https://api.together.xyz/v1"
314
+ api_key = "{{TOGETHER_API_KEY}}"
315
+ ```
316
+
317
+ `{{VAR_NAME}}` in any string value is interpolated from the environment. Unknown keys
318
+ are silently ignored. The shipped `src/coreloop/coreloop.toml` includes
319
+ pre-configured profiles for Ollama, OpenAI, Groq, DeepSeek, Together, and OpenRouter.
320
+
321
+ `AgentConfig` is a dataclass mirroring the `Agent` constructor (excluding hooks). Use
322
+ `dataclasses.replace(cfg, model="other")` to derive variants, or `Agent.from_config(cfg)`
323
+ to construct an agent from one.
324
+
325
+ ## `Message`
326
+
327
+ | Field | Type | Description |
328
+ |-------|------|-------------|
329
+ | `role` | `str` | `"user"`, `"assistant"`, `"system"`, `"tool"` |
330
+ | `content` | `str \| None` | Text content; `None` when `tool_calls` is set |
331
+ | `tool_calls` | `list[ToolCall] \| None` | Tool calls emitted by the assistant |
332
+ | `tool_call_id` | `str \| None` | Links a `"tool"` message to its call |
333
+ | `name` | `str \| None` | Tool name on `role="tool"` messages |
334
+ | `reasoning` | `str \| None` | Thinking-model scratchpad (Qwen3, DeepSeek). Not sent back to the API. |
335
+ | `partial` | `bool` | `True` for streaming delta chunks |
336
+ | `usage` | `Usage \| None` | Token counts from the model |
337
+ | `model` | `str \| None` | Model name reported by the API |
338
+ | `duration` | `float \| None` | Seconds elapsed for the LLM turn or tool call |
339
+ | `timestamp` | `datetime` | UTC creation time |
340
+
341
+ ## Caching
342
+
343
+ LLM responses are disk-cached by default (`~/.cache/coreloop-llm-cache/`), keyed
344
+ by SHA-256 of (model, messages, tools, extra_body). This replays identical requests
345
+ without hitting the API — useful during development. Pass `cache_dir=None` to disable.
346
+
347
+ ```python
348
+ agent = Agent(model="...", cache_dir="/tmp/my-cache") # custom location
349
+ agent = Agent(model="...", cache_dir=None) # disabled
350
+ ```
@@ -0,0 +1,30 @@
1
+ coreloop/__init__.py,sha256=VnZ1MhxZHYF0-KcyL1vdM8hnyUabc_eD66eIwH1gdmY,789
2
+ coreloop/__main__.py,sha256=jc-plD4Zcf7jantm1URSbaYC3LWxW8CIjvSo-f49QZM,83
3
+ coreloop/_api_client.py,sha256=JYMXfNjuyrNlTCsF-S42bxm03ZOkJxvHCeP64JVj47c,12489
4
+ coreloop/_cache.py,sha256=s9zRmgbgrJvT0KVxYrjWKPhW-jQfTrnLmzy6nqIM3V4,603
5
+ coreloop/_logging.py,sha256=d8E7tYqQY-B3OSDMZ4hMlJgrlGYH2-oetTH6BFMUwpc,609
6
+ coreloop/_tool_execution.py,sha256=RDyLJSHH7uAOxdoBwoJduXOl0dfqO5RQz9j8zaLENDM,3271
7
+ coreloop/agent.py,sha256=eo-MIm0Ze-V-oyAuL3XgxT5V5HjDla0ttoehn1kvypM,13746
8
+ coreloop/cli/__init__.py,sha256=9sZmAM3__-KU9GmGY9-hgWaDvaaJVKN4krVM2tVnwfA,9204
9
+ coreloop/cli/_run.py,sha256=qH5dzao3SdCMPrpTzYKWmFcS51UEhV6bMhUi7gLQmVw,5296
10
+ coreloop/cli/_tools.py,sha256=BcPHwQaau6IKiG_newD9H3TmiS0VVWUNEmAvQ50zUlc,2956
11
+ coreloop/config.py,sha256=Zu_M9Z4XyqBStSd_VOG1FDxN1TnzTgAlNA5l63iEYFU,1091
12
+ coreloop/coreloop.toml,sha256=SLirSZE3PzC2tCQNCHxY-vI8Q4tEFMEU21TQ_-3AHE0,2831
13
+ coreloop/hooks.py,sha256=YBuZra0dp4uGcyFu9AP9QzGa9x13pucva5SsazFn6O4,5064
14
+ coreloop/profiles.py,sha256=AC0zu9JM9iWcC_y3nB9g1J76zgmWU7hQuFjJ2EZ7Tuk,5749
15
+ coreloop/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ coreloop/tool_registry.py,sha256=UvxcbpUQJ990deCih3hzy1eKLfp3LQ39m6FVUfkBtrY,6049
17
+ coreloop/tools/__init__.py,sha256=m-5YU8mMDwosvmnp3ZbWmlNFyA-HRiv47Z7vPRFSYyk,1029
18
+ coreloop/tools/_shared.py,sha256=x3BLB9hekY1IxdFvQzRNUrPlkDjOf-rxk2id23mAeaw,2073
19
+ coreloop/tools/bash.py,sha256=HoBYQDvpWvC0cFCM6FZ-pZWWvauQ3O9xhhMm-tgvi-I,8358
20
+ coreloop/tools/edit.py,sha256=klk42I_ZUZwh27v2OjJ0ZMhOQmUkB2-Qph1MP4sSwRk,5750
21
+ coreloop/tools/grep.py,sha256=jl0rSQHVaj8kew9eEAlr5BG0NxzYwtreF3DKSxSSjMo,3235
22
+ coreloop/tools/ls.py,sha256=wR-ubaICP_bJqQhS5FcAemK1FzFZKUWw9mQWFWIj_4I,2142
23
+ coreloop/tools/read.py,sha256=tb3pjXGh89FX-d8rQr5EhREUKLRw3jA2EERc_FcYNCc,2248
24
+ coreloop/types.py,sha256=P7XPguvIEvfkLmFcmGQbxjQ2yNcnu_JjzH-B88dlORg,2607
25
+ coreloop/web_tools.py,sha256=iUyZP9zJRGOie-xmEfRhRhBoe5bc6pCDfbGy73pvjzA,3270
26
+ coreloop-0.1.0.dist-info/licenses/LICENSE,sha256=eNIx-PuOckM3BtWyc-2L60TuX4tz_Cp-V9d0lApI4Hk,1069
27
+ coreloop-0.1.0.dist-info/WHEEL,sha256=Q9FtwzuR2QE37l-JIkuyklGnJJiCBHKnsPVQ9vzCMzQ,81
28
+ coreloop-0.1.0.dist-info/entry_points.txt,sha256=ZV_rFc9hBTv6Fhyi8KF08UPpS73EayG_X1fOnTbxmuk,43
29
+ coreloop-0.1.0.dist-info/METADATA,sha256=TeRf_Dr3aDx60zdQh8PNBhtCGIZStOAxYytQSO7rmQk,13752
30
+ coreloop-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.11.17
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ core = coreloop.cli:app
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Chris Kilner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.