coreloop 0.1.5__tar.gz → 0.2.0__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 (43) hide show
  1. coreloop-0.2.0/PKG-INFO +606 -0
  2. coreloop-0.2.0/README.md +573 -0
  3. {coreloop-0.1.5 → coreloop-0.2.0}/pyproject.toml +13 -8
  4. {coreloop-0.1.5 → coreloop-0.2.0}/pyproject.toml.orig +10 -9
  5. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/.coreloop.toml +1 -1
  6. coreloop-0.2.0/src/coreloop/__init__.py +87 -0
  7. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/_api_client.py +74 -23
  8. coreloop-0.2.0/src/coreloop/_tool_execution.py +125 -0
  9. coreloop-0.2.0/src/coreloop/agent.py +832 -0
  10. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/cli/__init__.py +16 -5
  11. coreloop-0.2.0/src/coreloop/cli/_herdr.py +75 -0
  12. coreloop-0.2.0/src/coreloop/cli/_run.py +152 -0
  13. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/cli/_tools.py +13 -4
  14. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/complete.py +7 -0
  15. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/config.py +4 -2
  16. coreloop-0.2.0/src/coreloop/events.py +126 -0
  17. coreloop-0.2.0/src/coreloop/hooks.py +334 -0
  18. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/profiles.py +1 -4
  19. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/tool_registry.py +74 -13
  20. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/tools/_shared.py +9 -2
  21. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/tools/bash.py +1 -1
  22. coreloop-0.2.0/src/coreloop/tools/code.py +226 -0
  23. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/tools/edit.py +1 -1
  24. coreloop-0.2.0/src/coreloop/types.py +179 -0
  25. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/web_tools.py +10 -5
  26. coreloop-0.1.5/PKG-INFO +0 -387
  27. coreloop-0.1.5/README.md +0 -354
  28. coreloop-0.1.5/src/coreloop/__init__.py +0 -37
  29. coreloop-0.1.5/src/coreloop/_tool_execution.py +0 -80
  30. coreloop-0.1.5/src/coreloop/agent.py +0 -382
  31. coreloop-0.1.5/src/coreloop/cli/_run.py +0 -145
  32. coreloop-0.1.5/src/coreloop/hooks.py +0 -146
  33. coreloop-0.1.5/src/coreloop/types.py +0 -86
  34. {coreloop-0.1.5 → coreloop-0.2.0}/LICENSE +0 -0
  35. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/__main__.py +0 -0
  36. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/_cache.py +0 -0
  37. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/_logging.py +0 -0
  38. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/py.typed +0 -0
  39. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/structured.py +0 -0
  40. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/tools/__init__.py +0 -0
  41. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/tools/grep.py +0 -0
  42. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/tools/ls.py +0 -0
  43. {coreloop-0.1.5 → coreloop-0.2.0}/src/coreloop/tools/read.py +0 -0
@@ -0,0 +1,606 @@
1
+ Metadata-Version: 2.4
2
+ Name: coreloop
3
+ Version: 0.2.0
4
+ Summary: Minimal async agent loop for any OpenAI-compatible API: tool calling, composable hooks, typed events and JSONL tracing, subagents and code mode. Small enough for local models. Library and CLI.
5
+ Keywords: llm,agent,tool-calling,openai,ollama,cli,async,streaming,hooks,httpx,local-models,subagents,tracing,structured-output,code-mode
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: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Dist: httpx>=0.29.0
20
+ Requires-Dist: typer>=0.29.3
21
+ Requires-Dist: pydantic>=2.0,<3
22
+ Requires-Dist: diskcache>=5.6.3
23
+ Requires-Dist: python-dotenv>=1.0.1
24
+ Requires-Dist: rich>=13.0.0
25
+ Requires-Dist: html-to-markdown>=3.23 ; extra == 'web'
26
+ Requires-Python: >=3.12
27
+ Project-URL: Homepage, https://github.com/rhiza-fr/coreloop
28
+ Project-URL: Repository, https://github.com/rhiza-fr/coreloop
29
+ Project-URL: Issues, https://github.com/rhiza-fr/coreloop/issues
30
+ Project-URL: Changelog, https://github.com/rhiza-fr/coreloop/blob/main/CHANGELOG.md
31
+ Provides-Extra: web
32
+ Description-Content-Type: text/markdown
33
+
34
+ # coreloop
35
+
36
+ A lightweight async tool-calling agent for any OpenAI-compatible API (via `httpx`).
37
+ The core is an async generator loop that streams `Message` objects; you observe and
38
+ intercept it via lifecycle hooks. Usable as a library or through a minimal CLI.
39
+
40
+ The minimal core imposes no forced overhead, so it pairs well with small local
41
+ models; early exit via hooks and `stop()` makes high-throughput batch work fast and
42
+ keeps token costs down.
43
+
44
+ Built-in tools: path-scoped `read`, `ls`, `edit`, `grep`; a `bash` tool with
45
+ best-effort guardrails (not a security sandbox — see below); a `python` code-mode tool
46
+ (also not a sandbox); optional `web_search`
47
+ and `web_fetch` (via the `[web]` extra).
48
+
49
+ - **Observability** — [hook into every stage of the loop](#hooks) and [read typed events or a JSONL trace](#events-and-tracing): turns, tool calls, end reason, usage
50
+ — examples: [streaming](examples/example6_streaming.py) · [raw message stream](examples/example7_raw_messages.py) · [logging & timing hooks](examples/example8_hooks.py) · [events & trace](examples/example16_events_trace.py)
51
+ - **Loop control** — [stop cleanly, abort immediately, inject responses, or drive the loop turn by turn](#agent): `stop()`, `abort()`, `step()`, `on_before_llm`
52
+ — examples: [lifecycle control](examples/example3_agent_lifecycle.py) · [intercept & replace results](examples/example9_intrusive_hooks.py) · [step loop & approval gate](examples/example15_step_loop.py) · [tool policy & fail-closed hooks](examples/example22_policy.py)
53
+ - **Extensibility** — [register custom tools with `@tool`](#custom-tools) (async or sync, with run context and structured results) and [use agents as tools](#subagents)
54
+ — examples: [custom tools](examples/example5_customtools.py) · [tool context & results](examples/example17_tool_context.py) · [subagents](examples/example12_subagents.py) · [code mode](examples/example20_code_mode.py) · [code mode driving subagents](examples/example21_orchestrator.py)
55
+ - **Context and memory** — [shape what the LLM sees with `prepare_messages`](#hooks), [attach images](#images), [save and resume history](#saving-history)
56
+ — examples: [memory & persistence](examples/example19_memory.py) · [images](examples/example18_images.py)
57
+
58
+ ## Install
59
+
60
+ Requires Python 3.12+.
61
+
62
+ ```bash
63
+ pip install coreloop
64
+ pip install "coreloop[web]" # adds web_search and web_fetch
65
+ ```
66
+
67
+ ## Library quick-start
68
+
69
+ ```python
70
+ import asyncio
71
+ from coreloop import Agent, Message
72
+
73
+ agent = Agent(
74
+ model="gpt-4o-mini",
75
+ base_url="https://api.openai.com/v1",
76
+ api_key="sk-...",
77
+ tools=["read", "ls", "grep"],
78
+ root="/tmp/sandbox",
79
+ )
80
+
81
+
82
+ async def main():
83
+ async for msg in agent.run([Message(role="user", content="What files are here?")]):
84
+ if msg.role == "assistant" and not msg.partial and msg.content:
85
+ print(msg.content)
86
+
87
+
88
+ asyncio.run(main())
89
+ ```
90
+
91
+ Or load settings from a named profile in `~/.coreloop.toml`:
92
+
93
+ ```python
94
+ agent = Agent.from_profile("openai")
95
+ ```
96
+
97
+ ## CLI
98
+
99
+ `core` is a REPL / one-shot runner with profile support. On first run it copies
100
+ the bundled `coreloop.toml` to `~/.coreloop.toml` — edit that file to set
101
+ your default model, tools, and provider credentials.
102
+
103
+ ```bash
104
+ # Interactive REPL using the default profile (Ollama)
105
+ core
106
+
107
+ # One-shot with a named profile
108
+ core --profile openai -p "Summarise this repo"
109
+
110
+ # Override model and enable file tools
111
+ core --profile openai --model gpt-4o --tools read,ls,grep --root .
112
+
113
+ # Bypass profiles entirely
114
+ core --base-url https://api.openai.com/v1 --api-key $OPENAI_API_KEY --model gpt-4o-mini -p "Hello"
115
+
116
+ # Enable reasoning
117
+ core --think -p "Explain this step by step" --model qwen3-14b
118
+ ```
119
+
120
+ | Flag | Default | Description |
121
+ |------|---------|-------------|
122
+ | `--profile` | `default` | Named profile from `~/.coreloop.toml` |
123
+ | `-m, --model` | profile value | Model name — overrides profile (`CORELOOP_MODEL`) |
124
+ | `--base-url` | profile value | API base URL — overrides profile (`CORELOOP_BASE_URL`) |
125
+ | `--api-key` | profile value | API key — overrides profile (`CORELOOP_API_KEY`) |
126
+ | `-s, --system` | — | System prompt |
127
+ | `--tools` | profile value | Comma-separated: `read,ls,edit,grep,bash,web_search,web_fetch` |
128
+ | `-r, --root` | cwd | Allowed root directory for file tools |
129
+ | `--searxng-url` | `$SEARXNG_URL` | SearXNG base URL for web tools |
130
+ | `-t, --llm-timeout` | profile value | Asyncio wall-clock timeout per LLM turn (seconds) |
131
+ | `--tool-timeout` | profile value | Hard timeout per tool call (seconds) |
132
+ | `--http-request-timeout` | profile value | httpx per-chunk read timeout (seconds) |
133
+ | `--cache-dir` | profile value | LLM response cache directory |
134
+ | `--no-cache` | off | Disable response caching |
135
+ | `-e, --extra` | — | Extra JSON merged into the API request body |
136
+ | `--think/--no-think` | off | Set `reasoning_effort` to `medium` / `none` |
137
+ | `-n, --max-turns` | `20` | Maximum loop iterations |
138
+ | `-p, --prompt` | — | Run once and print final response |
139
+ | `--json` | off | Output all non-partial messages as JSONL |
140
+ | `--trace PATH` | — | Append run events (turns, tool calls, end reason, usage) as JSONL |
141
+ | `-l, --log-level` | — | `DEBUG`, `INFO`, `WARNING`, `ERROR` |
142
+
143
+ REPL commands: `/quit` `/exit` `/q` to exit; `/new` to clear history;
144
+ `/model <name>` to switch models; `/root <path>` to change the file-tool root.
145
+
146
+ ## `Agent`
147
+
148
+ ```python
149
+ Agent(
150
+ model: str,
151
+ base_url: str = "http://localhost:11434/v1",
152
+ api_key: str | None = None,
153
+ system: str | None = None,
154
+ tools: list[str | ToolInfo] | None = None,
155
+ root: str | Path | None = None,
156
+ http_request_timeout: float = 300.0, # httpx per-chunk read timeout
157
+ tool_timeout: float = 360.0, # hard wall per tool call
158
+ llm_timeout: float = 300.0, # asyncio wall for the entire LLM turn
159
+ hooks: AgentHooks | list[AgentHooks] | None = None,
160
+ llm_extra_body: dict | None = None,
161
+ cache_dir: Path | str | None = None, # opt-in response cache
162
+ trace: str | Path | Callable[[Event], None] | None = None, # JSONL path or event sink
163
+ max_retries: int = 2, # re-send on 429/5xx or connection errors before streaming
164
+ )
165
+ ```
166
+
167
+ `tools` accepts built-in names (`"read"`, `"ls"`, `"edit"`, `"grep"`, `"bash"`,
168
+ `"web_search"`, `"web_fetch"`), names of `@tool`-registered functions, or `ToolInfo`
169
+ objects. File tools are scoped to `root`; an unknown name raises `ValueError`. An agent
170
+ has exactly the tools you list — there is no implicit inclusion of the global registry.
171
+
172
+ `run(messages)` is an async generator. Partial streaming chunks have `partial=True`;
173
+ the final assembled message for each LLM turn has `partial=False`. Pass
174
+ `usage=Usage()` to accumulate token counts across turns.
175
+
176
+ | Method / property | Description |
177
+ |---|---|
178
+ | `run(messages, *, usage=None)` | Run the agent loop, yielding `Message` objects; `messages` may be a prompt string |
179
+ | `ask(prompt, *, schema=None)` | Run the loop and return the final text, or a validated `schema` instance |
180
+ | `fork(**overrides)` | Child agent with the same settings, empty history, linked to this one |
181
+ | `as_tool(name, description, *, schema=None, max_depth=3)` | This agent as a tool; each call runs a fresh fork |
182
+ | `events(messages, *, usage=None)` | Same loop, yielding typed events (see [Events and tracing](#events-and-tracing)) |
183
+ | `stop(reason="stopped")` | Finish the current turn cleanly, then exit. Safe from a hook or tool. |
184
+ | `stop_reason` | Reason given to `stop()` (`"aborted"` after `abort()`), else `None` |
185
+ | `last_run` | `RunEnd` of the last `run()`/`events()`: `reason`, `usage`, `error` |
186
+ | `run_id` | Id of the current or last run; tags every event |
187
+ | `turn` | Index of the current or last turn (1-based) |
188
+ | `run_usage` | Live token usage of the current run |
189
+ | `tools` | Mutable `dict[str, ToolInfo]` of the tools offered to the LLM |
190
+ | `add_tools(*tools)` | Add tools by name or `ToolInfo` |
191
+ | `abort()` | Cancel immediately; `on_after_agent` is not called |
192
+ | `reset()` | Clear history and stop flag |
193
+ | `stopped` | `True` after `stop()` or `abort()` |
194
+ | `messages` | Shallow copy of full chat history from the last `run()` |
195
+ | `start(messages)` | Load history (adds system prompt) for driving the loop yourself |
196
+ | `step(*, usage=None)` | One turn (LLM call + its tools); returns a `Turn` |
197
+ | `call_llm(*, usage=None)` | One LLM call; appends and returns the assistant message |
198
+ | `exec_tools(calls)` | Run tool calls (with hooks); appends and returns the results |
199
+ | `append(*messages)` | Add messages to the history between steps |
200
+
201
+ **Driving the loop yourself** — `run()` is `start()` plus `step()` until a turn is
202
+ done. Write the loop to decide between turns (approval, routing, model switching):
203
+
204
+ ```python
205
+ agent.start([Message(role="user", content="Fix the failing test")])
206
+ while True:
207
+ turn = await agent.step()
208
+ if turn.done or agent.stopped:
209
+ break
210
+ if over_budget():
211
+ agent.model = "cheaper-model"
212
+ ```
213
+
214
+ For finer control split a turn: `msg = await agent.call_llm()`, inspect
215
+ `msg.tool_calls`, then `await agent.exec_tools(msg.tool_calls)`. Every tool call needs a
216
+ result in the history before the next LLM call. `step()` fires the per-turn hooks only;
217
+ `on_before_agent`/`on_after_agent` (and so `MaxTurnsHook`'s reset) belong to `run()`.
218
+
219
+ **Restart pattern** — pass `agent.messages` to keep history across runs:
220
+
221
+ ```python
222
+ async for msg in agent.run([Message(role="user", content="Hello")]):
223
+ ...
224
+
225
+ agent.model = "stronger-model"
226
+ async for msg in agent.run(agent.messages + [Message(role="user", content="Now do X")]):
227
+ ...
228
+ ```
229
+
230
+ ## Subagents
231
+
232
+ `agent.as_tool(name, description)` turns an agent into a tool. Each call runs a fresh fork,
233
+ so parallel calls do not share history.
234
+
235
+ ```python
236
+ researcher = Agent(model="...", tools=[population], system="Answer using the tool.")
237
+ lead = Agent(
238
+ model="...",
239
+ tools=[researcher.as_tool("research", "Look up a city", schema=Facts)],
240
+ trace="run.jsonl",
241
+ )
242
+ answer = await lead.ask("Which is bigger, Paris or Tokyo?")
243
+ ```
244
+
245
+ - The child is linked to the calling agent: its usage is added to the caller's run,
246
+ `stop()`/`abort()` on the caller reach it, and its `RunStart` carries `depth`,
247
+ `parent_run_id` and `parent_call_id`. A child without its own trace sink writes to the
248
+ caller's, so one JSONL file holds the whole tree.
249
+ - With `schema`, the tool result's `data` is the validated instance and `content` its JSON.
250
+ - Calls deeper than `max_depth` (default 3) return an error result instead of running.
251
+ - The caller's `tool_timeout` bounds each child.
252
+ - `fork(**overrides)` copies model, endpoint, key, system prompt, tools, root, timeouts,
253
+ `llm_extra_body`, backend, cache and trace sink, but not hooks (they hold per-run state).
254
+
255
+ `ask(prompt, schema=Model)` runs the full tool loop, then makes one extra LLM call
256
+ constrained to the schema and returns a validated instance; that call's usage is added to
257
+ `last_run.usage` but is not part of the traced `RunEnd`.
258
+
259
+ ## Events and tracing
260
+
261
+ `agent.events(messages)` runs the same loop as `run()` and yields typed events, all
262
+ tagged with `run_id`, `turn` and `time`:
263
+
264
+ ```
265
+ RunStart -> (TurnStart -> LLMDelta* -> LLMEnd -> (ToolStart* -> ToolEnd*)? -> TurnEnd)* -> RunEnd
266
+ ```
267
+
268
+ `ToolStart` arrives before the tool runs; `LLMEnd.message` and `TurnEnd.assistant` are the
269
+ message stored in history (after `on_after_llm`), so `run()` yields hook replacements; `RunStart` carries `depth`, `parent_run_id` and `parent_call_id` for subagents; `RunEnd` carries `reason` (`"done"`, `"max_turns"`,
270
+ `"stopped"` or any reason given to `stop()`, `"aborted"`, `"cancelled"`, `"error"`),
271
+ the run's summed `usage`, and `error`. `step()` emits the turn events only.
272
+
273
+ `Agent(trace="run.jsonl")` appends every event except `LLMDelta` to a JSONL file; pass
274
+ any callable instead to receive `Event` objects (`trace=events.append`). A run that
275
+ raises still writes its `RunEnd` (reason `"error"`) first. A failing sink is logged and
276
+ ignored. `read_trace(path)` loads a trace back.
277
+
278
+ ```python
279
+ async for ev in agent.events([Message(role="user", content="...")]):
280
+ if ev.kind == "tool_start":
281
+ print("running", ev.call.function.name)
282
+ print(agent.last_run.reason, agent.last_run.usage)
283
+ ```
284
+
285
+ ## Images
286
+
287
+ `Message.attachments` takes images, sent as OpenAI-style content parts after the text:
288
+
289
+ ```python
290
+ from coreloop import ImagePart
291
+
292
+ Message(
293
+ role="user", content="What is in this picture?", attachments=[ImagePart.from_path("photo.jpg")]
294
+ ) # or ImagePart.from_url(url)
295
+ ```
296
+
297
+ The model must support vision. `content` stays a plain string, so code that reads
298
+ messages is unaffected.
299
+
300
+ ## Code mode
301
+
302
+ Add the built-in `"python"` tool (or `make_code_tool()`) and the model can write one Python
303
+ script instead of many tool calls. Every other tool of the agent is a function in the
304
+ script (keyword arguments, returns the result string, raises `ToolError` on failure).
305
+ Each call goes back to the parent process and through the normal tool pipeline:
306
+ validation, hooks (an `on_before_tool` policy can deny or rewrite it), `parallel_safe` and
307
+ timeouts. Nested calls appear in the trace with ids like `call_abc:1`. Only what the
308
+ script prints is returned to the LLM, so large intermediate results stay out of context.
309
+
310
+ ```python
311
+ agent = Agent(model="...", tools=[list_items, stock_level, "python"], hooks=Policy())
312
+ ```
313
+
314
+ `make_code_tool(name="python", tools=None, python=sys.executable, max_chars=20_000)`:
315
+ `tools` limits which tools scripts may call. The agent's `tool_timeout` bounds the whole
316
+ script, and the process is killed when it expires. Scripts run with `python -I` in the
317
+ agent's `root`.
318
+
319
+ > **`python` is not sandboxed.** The script runs with your user privileges and can read
320
+ > and write files, start processes and use the network directly; only calls to the
321
+ > agent's tools pass through hooks. Enable it only where you would enable `bash`.
322
+
323
+ ## Built-in tools
324
+
325
+ All file tools reject path traversal and are scoped to `root`.
326
+
327
+ | Tool | Description |
328
+ |------|-------------|
329
+ | `read` | Read a text file; `offset`/`limit` for paging (1-based line numbers) |
330
+ | `ls` | List a directory |
331
+ | `edit` | Replace an exact string in a file; fails on ambiguous matches |
332
+ | `grep` | Regex search via `rg`; supports `type`, `after_context`, `files_with_matches` |
333
+ | `bash` | Run arbitrary shell commands via `bash -c`; kills the entire process group on timeout |
334
+ | `python` | [Code mode](#code-mode): run a Python script in which the agent's other tools are functions |
335
+
336
+ > **`bash` is not sandboxed.** It runs whatever the model sends with your full
337
+ > user privileges. The `workdir` is scoped to `root`, but a command can still read,
338
+ > write, or delete anything your account can reach, and make network calls. The
339
+ > dangerous-pattern blocklist (e.g. `rm -rf /`, `mkfs`, fork bombs) is a speed bump
340
+ > against obvious accidents, **not** a security boundary — trivial variants slip
341
+ > through (`curl … | bash`, `python -c "…"`, unusual flag orders). Only enable
342
+ > `bash` for models and prompts you trust, and prefer running in a container or VM.
343
+
344
+ Web tools require `pip install "coreloop[web]"` and a running
345
+ [SearXNG](https://docs.searxng.org/) instance:
346
+
347
+ ```bash
348
+ docker run -d -p 8080:8080 searxng/searxng
349
+ ```
350
+
351
+ | Tool | Description |
352
+ |------|-------------|
353
+ | `web_search` | Search via SearXNG; returns titles, URLs, snippets; supports `max_results`, `domain_filter`, `recency` |
354
+ | `web_fetch` | Fetch a URL; `extract_mode`: `markdown` (default), `raw`, `metadata`. Output is capped at 100 000 chars (raw: 50 000); `make_web_tools(max_chars=...)` or `[config.tool.web_fetch] max_chars` lowers it for small-context models |
355
+
356
+ ## Custom tools
357
+
358
+ ```python
359
+ from coreloop import tool
360
+
361
+
362
+ @tool
363
+ async def read_env(name: str) -> str:
364
+ """Read an environment variable."""
365
+ import os
366
+
367
+ return os.environ.get(name, "(not set)")
368
+
369
+
370
+ # Attach by name or pass the ToolInfo object directly
371
+ agent = Agent(model="...", tools=["read_env"])
372
+ agent = Agent(model="...", tools=[read_env]) # equivalent
373
+ ```
374
+
375
+ `@tool` infers JSON Schema from type annotations (`str`, `int`, `float`, `bool`,
376
+ `list[T]`, `dict`, `Optional[T]`). Unrecognised types fall back to `string` with a
377
+ warning. Override name or description:
378
+
379
+ ```python
380
+ @tool(name="my_read", description="Read a local file")
381
+ async def _impl(path: str) -> str: ...
382
+
383
+
384
+ @tool(allow_override=True) # re-register if a tool with that name already exists
385
+ async def read_env(name: str) -> str: ...
386
+ ```
387
+
388
+ The decorated object is both a `ToolInfo` and directly callable (`await my_tool(...)`
389
+ works alongside registration).
390
+
391
+ **Sync tools.** A plain `def` works too; it runs in a worker thread so it does not block
392
+ the loop. On timeout the thread is abandoned, not killed.
393
+
394
+ **Run context.** Annotate a parameter as `RunContext` to receive the run: it is left out of
395
+ the schema and filled in by the agent.
396
+
397
+ ```python
398
+ from coreloop import RunContext, ToolResult, tool
399
+
400
+
401
+ @tool
402
+ async def search(query: str, ctx: RunContext) -> ToolResult:
403
+ """Search the index."""
404
+ hits = index.search(query)
405
+ if not hits:
406
+ ctx.agent.stop("nothing_found") # also: ctx.call.id, ctx.run_id, ctx.turn, ctx.usage
407
+ return ToolResult(content=format_hits(hits), data=hits, is_error=not hits)
408
+ ```
409
+
410
+ **Structured results.** Return a `ToolResult` instead of a string: `content` is what the
411
+ LLM sees, `data` stays on the tool message for your code, and `is_error` flags failure.
412
+ Validation errors, timeouts and exceptions set `is_error` too. Both are on the tool
413
+ `Message` and the `ToolEnd` event; neither is sent to the API.
414
+
415
+ **Concurrency.** Tool calls from one LLM turn run in parallel. Pass
416
+ `@tool(parallel_safe=False)` for tools that must not overlap; unsafe calls run one at a
417
+ time in call order while safe ones stay parallel. The built-in `edit` and `bash` are
418
+ unsafe.
419
+
420
+ **Changing the tool set.** `agent.tools` is a plain `dict[str, ToolInfo]`; change it
421
+ between turns (for example in `on_before_turn`) to vary what the LLM is offered.
422
+ `agent.add_tools("read", my_tool)` resolves names like the constructor does.
423
+
424
+ Registry helpers:
425
+
426
+ ```python
427
+ from coreloop import list_tools, get_tool, clear_registry
428
+
429
+ list_tools() # list[ToolInfo] — all globally registered tools
430
+ get_tool("read_env") # ToolInfo | None
431
+ clear_registry() # remove all tools (useful in tests)
432
+ ```
433
+
434
+ ## Hooks
435
+
436
+ Subclass `AgentHooks` to observe or intercept any stage of the loop:
437
+
438
+ ```python
439
+ from coreloop import AgentHooks
440
+
441
+
442
+ class LogHook(AgentHooks):
443
+ async def on_before_tool(self, agent, name, args, call):
444
+ print(f"→ {name}({args}) [{call.id}]")
445
+ return None # None = run the tool
446
+
447
+
448
+ agent = Agent(..., hooks=LogHook())
449
+ agent = Agent(..., hooks=[LogHook(), MaxTurnsHook(10)]) # a list composes hooks in order
450
+ ```
451
+
452
+ Hook firing order per turn:
453
+
454
+ ```
455
+ on_before_turn
456
+ on_before_llm → return Message to skip the LLM call entirely
457
+ prepare_messages → return list[Message] to send instead of the history (history unchanged)
458
+ <LLM streams>
459
+ on_after_llm → return Message to replace before appending to history
460
+ for each tool (in parallel):
461
+ on_before_tool → str/ToolResult: inject result; Deny(reason): refuse; Rewrite(args): change args
462
+ <tool runs>
463
+ on_after_tool → return str/ToolResult to replace result in history
464
+ on_after_turn
465
+ ```
466
+
467
+ `on_before_agent` / `on_after_agent` bracket the entire `run()` call.
468
+ `on_after_agent` is **not** called after `abort()`.
469
+
470
+ With a list of hooks: notifications reach every hook; the first `on_before_llm` injection
471
+ wins; `on_after_llm`, `on_after_tool` and `prepare_messages` form a pipeline;
472
+ `on_before_tool` applies each `Rewrite` in turn and stops at the first str or `Deny`.
473
+
474
+ Errors: hook exceptions are logged and swallowed, so an observer bug cannot crash the
475
+ agent, except that:
476
+
477
+ - an exception in `on_before_tool` **denies** the call (fail-closed), so a broken policy
478
+ hook never lets a tool run;
479
+ - a hook class with `critical = True` has its exceptions re-raised as `HookError`, ending
480
+ the run;
481
+ - any hook may raise `HookError` itself to end the run.
482
+
483
+ `prepare_messages` is the seam for memory and context management (truncation,
484
+ summaries, retrieval). `Message.meta` is a free-form dict that is never sent to the
485
+ API; use it to tag messages (`pinned`, `source`) for such policies.
486
+
487
+ `MaxTurnsHook(n)` calls `agent.stop()` after `n` turns; the counter resets on each
488
+ `run()`, so it enforces a per-run limit, not a lifetime one.
489
+
490
+ ## Config profiles
491
+
492
+ `Agent.from_profile("openai")` builds an `AgentConfig` from `~/.coreloop.toml`
493
+ (or `$CORELOOP_CONFIG`). Every profile inherits from `[profiles.default]`; named
494
+ profiles override individual keys.
495
+
496
+ ```toml
497
+ [profiles.default]
498
+ base_url = "http://localhost:11434/v1"
499
+ model = "qwen3.5:9b"
500
+
501
+ [profiles.openai]
502
+ base_url = "https://api.openai.com/v1"
503
+ api_key = "{{OPENAI_API_KEY}}"
504
+ model = "gpt-4o-mini"
505
+ tools = ["read", "ls", "grep"]
506
+
507
+ [profiles.together]
508
+ base_url = "https://api.together.xyz/v1"
509
+ api_key = "{{TOGETHER_API_KEY}}"
510
+ ```
511
+
512
+ `{{VAR_NAME}}` in any string value is interpolated from the environment. Unknown keys
513
+ are silently ignored. The shipped `src/coreloop/coreloop.toml` includes
514
+ pre-configured profiles for Ollama, OpenAI, Groq, DeepSeek, Together, and OpenRouter.
515
+
516
+ `AgentConfig` is a dataclass mirroring the `Agent` constructor (excluding hooks). Use
517
+ `dataclasses.replace(cfg, model="other")` to derive variants, or `Agent.from_config(cfg)`
518
+ to construct an agent from one.
519
+
520
+ ## Structured output
521
+
522
+ `complete()` is a one-shot call — no tools, no loop. With `schema`, output is constrained
523
+ via `response_format: {"type": "json_schema"}` and validated before it is returned.
524
+
525
+ ```python
526
+ from pydantic import BaseModel
527
+ from coreloop import complete
528
+
529
+
530
+ class Triage(BaseModel):
531
+ category: str
532
+ urgent: bool
533
+
534
+
535
+ result = await complete("Kettle broke again.", model="qwen3:8b", schema=Triage)
536
+ # -> Triage(category='...', urgent=True)
537
+ ```
538
+
539
+ Without `schema` it returns the final `Message`. `ValidationError` propagates to the
540
+ caller, so retry policy stays yours.
541
+
542
+ `prompt` also accepts a message list, which makes "loop, then extract" compose:
543
+
544
+ ```python
545
+ async for _ in agent.run([Message(role="user", content="Check the logs and triage.")]):
546
+ pass
547
+
548
+ record = await complete(agent.messages, model="qwen3:8b", schema=Triage)
549
+ ```
550
+
551
+ It is deliberately not an `Agent` parameter: constrained decoding and tool-calling cannot
552
+ coexist in one turn, so the loop stays unconstrained and `complete()` is the terminal
553
+ extraction step.
554
+
555
+ ## `Message`
556
+
557
+ | Field | Type | Description |
558
+ |-------|------|-------------|
559
+ | `role` | `Role` | `"user"`, `"assistant"`, `"system"`, `"tool"`; anything else fails validation |
560
+ | `content` | `str \| None` | Text content; `None` when `tool_calls` is set |
561
+ | `attachments` | `list[ImagePart] \| None` | Images, sent as content parts after the text |
562
+ | `tool_calls` | `list[ToolCall] \| None` | Tool calls emitted by the assistant |
563
+ | `tool_call_id` | `str \| None` | Links a `"tool"` message to its call |
564
+ | `name` | `str \| None` | Tool name on `role="tool"` messages |
565
+ | `reasoning` | `str \| None` | Thinking-model scratchpad (Qwen3, DeepSeek). Not sent back to the API. A final message with only reasoning (no content, no tool calls) takes it as `content` and gets `meta["content_from_reasoning"] = True`. |
566
+ | `partial` | `bool` | `True` for streaming delta chunks |
567
+ | `usage` | `Usage \| None` | Token counts from the model |
568
+ | `model` | `str \| None` | Model name reported by the API |
569
+ | `duration` | `float \| None` | Seconds elapsed for the LLM turn or tool call |
570
+ | `timestamp` | `datetime` | UTC creation time |
571
+ | `meta` | `dict` | Application data (tags, provenance). Not sent to the API. |
572
+ | `is_error` | `bool` | Tool messages: the call failed. Not sent to the API. |
573
+ | `data` | `Any` | Tool messages: `ToolResult.data`. Not sent to the API. |
574
+
575
+ ## Caching
576
+
577
+ `Agent` does not cache by default: an agent with side-effecting tools that replays a
578
+ cached response would repeat the same tool calls. Pass `cache_dir` to enable a disk cache
579
+ keyed by SHA-256 of (model, messages, tools, extra_body), which replays identical requests
580
+ without hitting the API (useful in development and tests). Forks share the parent's cache.
581
+ `complete()` (no tools) still caches in `~/.cache/coreloop-llm-cache/` by default; pass
582
+ `cache_dir=None` to disable it there.
583
+
584
+ ```python
585
+ agent = Agent(model="...", cache_dir="~/.cache/coreloop-llm-cache") # enable
586
+ ```
587
+
588
+ ## Retries
589
+
590
+ A request that fails before streaming starts (HTTP 429, 500, 502, 503, 504, or a
591
+ connection error) is re-sent up to `max_retries` times (default 2), waiting for
592
+ `Retry-After` or 1, 2, 4... seconds (capped at 30). Errors after the first streamed chunk
593
+ are not retried. `complete(..., retries=n)` does the same.
594
+
595
+ ## Saving history
596
+
597
+ `save_messages(messages, path)` writes a conversation as JSONL and `load_messages(path)`
598
+ reads it back, including `meta`, attachments, tool calls and tool `data` (non-JSON data
599
+ is saved as its `repr`).
600
+
601
+ ```python
602
+ from coreloop import load_messages, save_messages
603
+
604
+ save_messages(agent.messages, "chat.jsonl")
605
+ answer = await agent.ask(load_messages("chat.jsonl") + [Message(role="user", content="Continue.")])
606
+ ```