lithe 0.9.3__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.

Potentially problematic release.


This version of lithe might be problematic. Click here for more details.

Files changed (71) hide show
  1. lithe-0.9.3/LICENSE +21 -0
  2. lithe-0.9.3/PKG-INFO +209 -0
  3. lithe-0.9.3/README.md +162 -0
  4. lithe-0.9.3/lithe/__init__.py +65 -0
  5. lithe-0.9.3/lithe/actions.py +105 -0
  6. lithe-0.9.3/lithe/bundles/__init__.py +71 -0
  7. lithe-0.9.3/lithe/bundles/_textmatch.py +115 -0
  8. lithe-0.9.3/lithe/bundles/admin.py +133 -0
  9. lithe-0.9.3/lithe/bundles/command.py +510 -0
  10. lithe-0.9.3/lithe/bundles/documents.py +386 -0
  11. lithe-0.9.3/lithe/bundles/download.py +280 -0
  12. lithe-0.9.3/lithe/bundles/host.py +631 -0
  13. lithe-0.9.3/lithe/bundles/images.py +362 -0
  14. lithe-0.9.3/lithe/bundles/mcp.py +782 -0
  15. lithe-0.9.3/lithe/bundles/patch.py +506 -0
  16. lithe-0.9.3/lithe/bundles/providers.py +147 -0
  17. lithe-0.9.3/lithe/bundles/sandbox.py +297 -0
  18. lithe-0.9.3/lithe/bundles/skills.py +485 -0
  19. lithe-0.9.3/lithe/bundles/store/__init__.py +18 -0
  20. lithe-0.9.3/lithe/bundles/store/jsonl.py +487 -0
  21. lithe-0.9.3/lithe/bundles/store/protocol.py +255 -0
  22. lithe-0.9.3/lithe/bundles/subagents.py +625 -0
  23. lithe-0.9.3/lithe/bundles/todos.py +288 -0
  24. lithe-0.9.3/lithe/bundles/workspace.py +1071 -0
  25. lithe-0.9.3/lithe/context.py +82 -0
  26. lithe-0.9.3/lithe/events.py +90 -0
  27. lithe-0.9.3/lithe/llm.py +367 -0
  28. lithe-0.9.3/lithe/memory.py +353 -0
  29. lithe-0.9.3/lithe/modes.py +70 -0
  30. lithe-0.9.3/lithe/py.typed +0 -0
  31. lithe-0.9.3/lithe/runtime.py +1267 -0
  32. lithe-0.9.3/lithe/skills.py +28 -0
  33. lithe-0.9.3/lithe/tools.py +329 -0
  34. lithe-0.9.3/lithe/transports.py +871 -0
  35. lithe-0.9.3/lithe.egg-info/PKG-INFO +209 -0
  36. lithe-0.9.3/lithe.egg-info/SOURCES.txt +69 -0
  37. lithe-0.9.3/lithe.egg-info/dependency_links.txt +1 -0
  38. lithe-0.9.3/lithe.egg-info/requires.txt +6 -0
  39. lithe-0.9.3/lithe.egg-info/top_level.txt +1 -0
  40. lithe-0.9.3/pyproject.toml +52 -0
  41. lithe-0.9.3/setup.cfg +4 -0
  42. lithe-0.9.3/tests/test_lithe.py +375 -0
  43. lithe-0.9.3/tests/test_lithe_action_bridge.py +229 -0
  44. lithe-0.9.3/tests/test_lithe_admin.py +76 -0
  45. lithe-0.9.3/tests/test_lithe_command_bundle.py +135 -0
  46. lithe-0.9.3/tests/test_lithe_command_guard.py +168 -0
  47. lithe-0.9.3/tests/test_lithe_documents_bundle.py +262 -0
  48. lithe-0.9.3/tests/test_lithe_download_bundle.py +301 -0
  49. lithe-0.9.3/tests/test_lithe_e2e.py +113 -0
  50. lithe-0.9.3/tests/test_lithe_host_store.py +623 -0
  51. lithe-0.9.3/tests/test_lithe_images_bundle.py +202 -0
  52. lithe-0.9.3/tests/test_lithe_llm.py +101 -0
  53. lithe-0.9.3/tests/test_lithe_mcp_bundle.py +325 -0
  54. lithe-0.9.3/tests/test_lithe_mcp_http.py +155 -0
  55. lithe-0.9.3/tests/test_lithe_memory.py +145 -0
  56. lithe-0.9.3/tests/test_lithe_observability.py +127 -0
  57. lithe-0.9.3/tests/test_lithe_p1_round.py +859 -0
  58. lithe-0.9.3/tests/test_lithe_p2_round.py +880 -0
  59. lithe-0.9.3/tests/test_lithe_parallel_budget.py +159 -0
  60. lithe-0.9.3/tests/test_lithe_parallel_safety.py +292 -0
  61. lithe-0.9.3/tests/test_lithe_patch.py +589 -0
  62. lithe-0.9.3/tests/test_lithe_providers_bundle.py +69 -0
  63. lithe-0.9.3/tests/test_lithe_runtime.py +1455 -0
  64. lithe-0.9.3/tests/test_lithe_sandbox_bundle.py +223 -0
  65. lithe-0.9.3/tests/test_lithe_skills_bundle.py +87 -0
  66. lithe-0.9.3/tests/test_lithe_skills_packages.py +152 -0
  67. lithe-0.9.3/tests/test_lithe_store_v2.py +150 -0
  68. lithe-0.9.3/tests/test_lithe_subagents.py +559 -0
  69. lithe-0.9.3/tests/test_lithe_todos_bundle.py +257 -0
  70. lithe-0.9.3/tests/test_lithe_transports.py +661 -0
  71. lithe-0.9.3/tests/test_lithe_workspace_bundle.py +654 -0
lithe-0.9.3/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 betaloop contributors
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.
lithe-0.9.3/PKG-INFO ADDED
@@ -0,0 +1,209 @@
1
+ Metadata-Version: 2.4
2
+ Name: lithe
3
+ Version: 0.9.3
4
+ Summary: A reusable, storage-free ReAct agent kernel (engine + framework + protocols) with optional capability bundles.
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 betaloop contributors
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ Keywords: agent,llm,react,kernel,tool-calling,mcp
28
+ Classifier: Development Status :: 4 - Beta
29
+ Classifier: Intended Audience :: Developers
30
+ Classifier: License :: OSI Approved :: MIT License
31
+ Classifier: Programming Language :: Python :: 3
32
+ Classifier: Programming Language :: Python :: 3.10
33
+ Classifier: Programming Language :: Python :: 3.11
34
+ Classifier: Programming Language :: Python :: 3.12
35
+ Classifier: Programming Language :: Python :: 3.13
36
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
37
+ Classifier: Typing :: Typed
38
+ Requires-Python: >=3.10
39
+ Description-Content-Type: text/markdown
40
+ License-File: LICENSE
41
+ Requires-Dist: httpx>=0.24
42
+ Provides-Extra: dev
43
+ Requires-Dist: pytest>=8; extra == "dev"
44
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
45
+ Requires-Dist: ruff>=0.4; extra == "dev"
46
+ Dynamic: license-file
47
+
48
+ # lithe
49
+
50
+ [![PyPI](https://img.shields.io/pypi/v/lithe.svg)](https://pypi.org/project/lithe/)
51
+ [![Python](https://img.shields.io/pypi/pyversions/lithe.svg)](https://pypi.org/project/lithe/)
52
+ [![License: MIT](https://img.shields.io/pypi/l/lithe.svg)](https://pypi.org/project/lithe/)
53
+
54
+ **lithe** is a reusable, storage-free ReAct agent kernel for Python: the
55
+ engine, framework, and protocols that drive a tool-calling agent, plus
56
+ optional capability bundles. The kernel knows nothing about how runs are
57
+ stored — or even whether they are — so any application (a thesis-writing
58
+ platform, a coding agent, a support bot) supplies its own tools, system
59
+ prompt, and persistence, and reuses everything else: the loop, the event
60
+ stream, undo, and delegation.
61
+
62
+ ## Highlights
63
+
64
+ - **Zero-I/O core.** `import lithe` performs no file or network I/O. Every
65
+ module in the root package is pure engine + protocol; anything that
66
+ touches a disk or a socket ships as an optional bundle.
67
+ - **Storage-free by design.** Persistence is a pair of host-supplied
68
+ interfaces (an `EventSink` to write, a `MemoryProvider` to replay).
69
+ Don't want storage? Pass nothing. Want storage? `JsonlRunStore` is the
70
+ zero-database default.
71
+ - **An honest event stream.** Streaming `assistant_delta` events, a
72
+ `usage` event per model call (tokens, cost, context fullness), tool
73
+ calls announced *before* they execute, and cancellation that closes the
74
+ in-flight model stream instead of paying for a response nobody wants.
75
+ - **Undo built in.** Every bundled write tool registers a reverter; the
76
+ `UndoEngine` is pure and storage-free like the rest of the core, and
77
+ `AgentHost` exposes one-call `undo_run`.
78
+ - **Delegation without context bloat.** Subagents run isolated, are
79
+ tagged so undo still reverts their work, fan out in parallel with
80
+ per-delegation budgets, and fold their spend back into the parent run's
81
+ stats.
82
+ - **Any OpenAI-compatible endpoint.** Chat-completions and Responses
83
+ protocols behind one interface, with retries, jittered backoff,
84
+ `Retry-After`-aware 429 handling, and SSE streaming; usage is
85
+ normalized to one shape across both.
86
+
87
+ ## Install
88
+
89
+ ```bash
90
+ pip install lithe
91
+ # local development (editable install + test/lint deps):
92
+ pip install -e ".[dev]"
93
+ ```
94
+
95
+ Requires Python 3.10+. The only runtime dependency is `httpx`.
96
+
97
+ ## Quickstart
98
+
99
+ A minimal host: sandboxed file tools, a JSONL store, and a run.
100
+
101
+ ```python
102
+ from lithe import AgentContext, LLMConfig, ToolRegistry
103
+ from lithe.bundles import AgentHost, JsonlRunStore
104
+ from lithe.bundles.workspace import Workspace, register_file_tools
105
+
106
+ registry = ToolRegistry()
107
+ # workspace_for(ctx) -> Workspace (a sandboxed root per user):
108
+ register_file_tools(registry, lambda ctx: Workspace(f"/data/{ctx.user_id}"))
109
+ store = JsonlRunStore("/var/lib/myapp/agent") # zero-DB default
110
+ host = AgentHost(registry,
111
+ LLMConfig(model=..., base_url=..., api_key=...),
112
+ store, build_system_prompt=my_prompt_builder)
113
+
114
+ ctx = AgentContext(run_id=rid, user_id=uid)
115
+ async for event in host.run(ctx, task, history=prior_turns):
116
+ ... # forward run_start / step / tool_call / tool_result / done to your frontend
117
+ ```
118
+
119
+ A host supplies only its **tools**, **system prompt**, and (optionally) a
120
+ store backend — the engine, persistence, run envelope, undo, and (via
121
+ `subagents`) delegation are all reused.
122
+
123
+ ## Architecture
124
+
125
+ ### Core — `lithe` (zero I/O, zero business logic)
126
+
127
+ | Module | What you get |
128
+ | --- | --- |
129
+ | `runtime` | `AgentRuntime`, the ReAct loop as an async event stream: streaming deltas; cancellation checked between deltas; run budgets (`max_cost` / `max_total_tokens`) ending with `status="budget_exceeded"` (cost computed from `LLMConfig.pricing` when the gateway reports none; parallel delegations count their in-flight siblings' live spend against the same ceiling); a repeat-call nudge for stuck models (reset by intervening writes, so read-after-write cycles are never flagged); a forced toolless wrap-up when the step budget is hit; mid-run context trimming that escalates from shrinking old tool outputs to dropping whole old exchanges under an omission note; a steering inbox (`inbox=` queue of user texts injected at step boundaries); error-isolated sinks; an injectable `http_client` for connection pooling (a client still on httpx's 5s default is upgraded to `cfg.timeout` instead of silently failing long calls). Every event is stamped with `run_id` + a monotonic `seq`; runs report wall-clock `duration_s`, tool results carry `elapsed_ms`, and streaming calls report time-to-first-token. |
130
+ | `llm` | OpenAI-compatible client: retry with jittered backoff, `Retry-After`-aware 429 handling, fail-fast on fatal 4xx, response-shape validation, and SSE streaming helpers. |
131
+ | `transports` | Chat-completions and Responses transports with usage normalized to `prompt_tokens` / `completion_tokens` / `total_tokens`; reasoning items replayed within the tool loop where the protocol supports it; `image_url` blocks mapped to `input_image` on the Responses path (unmappable blocks raise instead of vanishing). `LLMConfig.extra_body` / `default_headers` carry vendor fields and gateway headers on every call; `LLMConfig.reasoning_effort` maps to `reasoning_effort` (chat) / `reasoning.effort` (Responses), deep-merged with `extra_body["reasoning"]` siblings. |
132
+ | `tools` | `ToolRegistry`: register / unregister / dispatch, READ/WRITE/META category filtering, argument validation (required + top-level types + enums), pre-validation argument **transforms** (path canonicalization, defaults, redaction), per-tool timeouts, and pre-dispatch **middleware** for audit, quota, or human-in-the-loop confirmation of write tools. |
133
+ | `actions` | `Action` + `UndoEngine`: pure, storage-free undo; reverters may be sync or async. |
134
+ | `memory` | `replay_messages` / `recap_text` / `window_with_recap` / `run_timeline` + the `MemoryProvider` protocol; two-sided, window-safe replay reconciliation drops orphaned tool rows instead of sending API-rejected payloads. |
135
+ | `events` | `EventSink` with separate display + record channels, and SSE serialization (`to_sse`) that degrades non-JSON values instead of crashing. |
136
+ | `context` / `modes` | `AgentContext` plus host-defined modes via `register_mode(name, categories)`; `ctx.shared` is per-run state shared *by reference* with subagent contexts — the vehicle for cross-agent coordination. |
137
+
138
+ ### Bundles — `lithe.bundles` (optional capabilities)
139
+
140
+ | Bundle | What you get |
141
+ | --- | --- |
142
+ | `host` | `AgentHost`: message assembly, the `run_start`/`done` envelope, error funneling, `StoreSink`, zero-config `undo_run`, and `DictToolAdapter` for wrapping dict-based tool systems. Forwards budgets, cancellation, and a shared HTTP client to every run. |
143
+ | `store` | `RunStore` / `ConversationStore` / `BlobStore` Protocols, plus `JsonlRunStore` — a zero-database JSONL store with content-addressed blob spillover for large action values and optional `fsync` crash durability. |
144
+ | `subagents` | `SubagentEngine` + `delegate` / `delegate_parallel` tools: isolated worker agents the orchestrator hands subtasks to — tagged for undo, bounded by `max_parallel`, per-delegation budgets, cancellation propagated from the parent run, live `subagent_progress` heartbeats. |
145
+ | `admin` | Admin-panel tools: `tool_categories`, `list_tools_admin`, `list_tool_packages_admin`, `check_packages`. |
146
+ | `patch` | `apply_patch`: line-oriented multi-file edits via the Codex `*** Begin Patch` envelope, a four-pass fuzzy matcher, and all-or-nothing application against an in-memory overlay. |
147
+ | `providers` | Vendor presets: known-good `LLMConfig` fields per OpenAI-compatible endpoint (openai / zai / deepseek / openrouter / qwen / moonshot) as plain data — `get_preset` / `apply_preset` merge a preset under host overrides (dict fields per key). Defaults, never truth: credentials and model always come from the caller, model-specific switches stay in `notes`. Each preset also names the family's `document_format` dialect (see the `documents` bundle). |
148
+ | `workspace` | Sandboxed file I/O: `read_file` / `write_file` / `edit_file` / `list_files` / `search_files` / `glob_files` with undo reverters, a stale-file guard that refuses to clobber externally changed files, and symlink-safe directory walks. |
149
+ | `todos` | A per-scope task list the agent plans against: `TodoStore` + atomic JSON persistence + `update_todos` / `list_todos` tools + a `todos_block` for the system prompt. |
150
+ | `images` | `image_info` (a stdlib-only header probe: dimensions, dpi, color mode) and `analyze_image` (one vision-model call, memoized per file hash + question) — image answers never enter the main conversation. |
151
+ | `documents` | `document_info` (a stdlib-only probe: PDF version, OOXML subtype, best-effort page count) and `analyze_document` (one model call with the document as a content block, memoized per file hash + question). The block dialect follows the endpoint family: `document_format` = `inline-file` (OpenRouter family, incl. self-built same-format routers) / `files-api` (strict OpenAI two-step upload) / `none` (probe only); `LLMConfig.document_format` carries it, provider presets default it, a 400 names the mismatch. |
152
+ | `sandbox` | `run_code` / `run_file`: Python execution with bubblewrap or passthrough backends, head+tail output truncation so tracebacks stay visible. WRITE-classified, so invisible in read-only modes. |
153
+ | `command` | `run_command`: opt-in native shell execution (bash/sh on Unix-like systems, PowerShell/cmd on Windows), bounded by timeout/output limits and started in the host-selected workspace. Commands run with the host user's permissions and are not sandboxed or undoable. |
154
+ | `download` | `download_file`: streaming HTTP(S) ingress into the workspace — SSRF-guarded (every redirect hop re-validated, all resolved addresses must be globally routable), size-capped, time-budgeted, landed atomically. |
155
+ | `skills` | Markdown skill libraries: flat `SkillLibrary`, package-aware `SkillPackages` with remote registry mirrors, and the `load_skill` tool. |
156
+ | `mcp` | `MCPManager` + `MCPServerConfig`: bridge external MCP servers (stdio or streamable-http) into the registry — `tools/list` pagination followed, a safe env allow-list for spawned servers (never all of `os.environ`), self-healing sessions. |
157
+
158
+ ```python
159
+ from lithe.bundles import MCPManager, MCPServerConfig
160
+
161
+ manager = MCPManager([MCPServerConfig(
162
+ name="zai", command=["npx", "-y", "@z_ai/mcp-server"],
163
+ env={"Z_AI_API_KEY": "...", "Z_AI_MODE": "ZHIPU"},
164
+ default_category="read")])
165
+ await manager.attach(registry) # registry gains zai__* tools
166
+ ```
167
+
168
+ ## Safety defaults
169
+
170
+ Long-lived autonomous loops need guardrails on by default:
171
+
172
+ - **Path sandboxing** — workspace tools resolve inside the sandbox root;
173
+ directory walks never follow symlinks, so code executed by `run_code`
174
+ cannot plant a link to a host file and read it back.
175
+ - **SSRF guard** — `download_file` accepts only globally routable
176
+ http/https addresses, re-validating every redirect hop (cloud metadata
177
+ endpoints included in the rejection set).
178
+ - **Secret hygiene** — spawned MCP servers get an env allow-list, never
179
+ the parent environment; URLs log as `scheme://host` so credentials in
180
+ query strings never reach a log line.
181
+ - **Shell execution is explicit** — `run_command` is an optional host bundle,
182
+ not a default tool. When enabled, commands run with the host user's
183
+ permissions; they are not sandboxed and their side effects cannot be undone.
184
+ - **Write serialization** — READ tools run in parallel, every WRITE/META
185
+ tool runs alone in model order: no write races.
186
+ - **Run budgets** — `max_cost` / `max_total_tokens` cut a runaway run
187
+ short with no further tool execution or model calls.
188
+
189
+ ## Storage model
190
+
191
+ The kernel stores nothing. A host provides:
192
+
193
+ - an **`EventSink`** (write side) — persists message records however it
194
+ likes (DB / file / nowhere);
195
+ - a **`MemoryProvider`** (read side, optional) — replays prior turns;
196
+ - an **`UndoEngine`** fed from wherever the host kept actions.
197
+
198
+ ## More
199
+
200
+ - `examples/minimal_host.py` — a runnable, offline minimal host (tools →
201
+ run → events → undo); runs in CI.
202
+ - `examples/live_host.py` — the same flow against a real OpenAI-compatible
203
+ endpoint (set `LITHE_API_KEY` / `LITHE_BASE_URL` / `LITHE_MODEL`; no
204
+ default endpoint, it never spends tokens by accident).
205
+ - `CHANGELOG.md` — what changed and when.
206
+
207
+ ## License
208
+
209
+ MIT
lithe-0.9.3/README.md ADDED
@@ -0,0 +1,162 @@
1
+ # lithe
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/lithe.svg)](https://pypi.org/project/lithe/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/lithe.svg)](https://pypi.org/project/lithe/)
5
+ [![License: MIT](https://img.shields.io/pypi/l/lithe.svg)](https://pypi.org/project/lithe/)
6
+
7
+ **lithe** is a reusable, storage-free ReAct agent kernel for Python: the
8
+ engine, framework, and protocols that drive a tool-calling agent, plus
9
+ optional capability bundles. The kernel knows nothing about how runs are
10
+ stored — or even whether they are — so any application (a thesis-writing
11
+ platform, a coding agent, a support bot) supplies its own tools, system
12
+ prompt, and persistence, and reuses everything else: the loop, the event
13
+ stream, undo, and delegation.
14
+
15
+ ## Highlights
16
+
17
+ - **Zero-I/O core.** `import lithe` performs no file or network I/O. Every
18
+ module in the root package is pure engine + protocol; anything that
19
+ touches a disk or a socket ships as an optional bundle.
20
+ - **Storage-free by design.** Persistence is a pair of host-supplied
21
+ interfaces (an `EventSink` to write, a `MemoryProvider` to replay).
22
+ Don't want storage? Pass nothing. Want storage? `JsonlRunStore` is the
23
+ zero-database default.
24
+ - **An honest event stream.** Streaming `assistant_delta` events, a
25
+ `usage` event per model call (tokens, cost, context fullness), tool
26
+ calls announced *before* they execute, and cancellation that closes the
27
+ in-flight model stream instead of paying for a response nobody wants.
28
+ - **Undo built in.** Every bundled write tool registers a reverter; the
29
+ `UndoEngine` is pure and storage-free like the rest of the core, and
30
+ `AgentHost` exposes one-call `undo_run`.
31
+ - **Delegation without context bloat.** Subagents run isolated, are
32
+ tagged so undo still reverts their work, fan out in parallel with
33
+ per-delegation budgets, and fold their spend back into the parent run's
34
+ stats.
35
+ - **Any OpenAI-compatible endpoint.** Chat-completions and Responses
36
+ protocols behind one interface, with retries, jittered backoff,
37
+ `Retry-After`-aware 429 handling, and SSE streaming; usage is
38
+ normalized to one shape across both.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install lithe
44
+ # local development (editable install + test/lint deps):
45
+ pip install -e ".[dev]"
46
+ ```
47
+
48
+ Requires Python 3.10+. The only runtime dependency is `httpx`.
49
+
50
+ ## Quickstart
51
+
52
+ A minimal host: sandboxed file tools, a JSONL store, and a run.
53
+
54
+ ```python
55
+ from lithe import AgentContext, LLMConfig, ToolRegistry
56
+ from lithe.bundles import AgentHost, JsonlRunStore
57
+ from lithe.bundles.workspace import Workspace, register_file_tools
58
+
59
+ registry = ToolRegistry()
60
+ # workspace_for(ctx) -> Workspace (a sandboxed root per user):
61
+ register_file_tools(registry, lambda ctx: Workspace(f"/data/{ctx.user_id}"))
62
+ store = JsonlRunStore("/var/lib/myapp/agent") # zero-DB default
63
+ host = AgentHost(registry,
64
+ LLMConfig(model=..., base_url=..., api_key=...),
65
+ store, build_system_prompt=my_prompt_builder)
66
+
67
+ ctx = AgentContext(run_id=rid, user_id=uid)
68
+ async for event in host.run(ctx, task, history=prior_turns):
69
+ ... # forward run_start / step / tool_call / tool_result / done to your frontend
70
+ ```
71
+
72
+ A host supplies only its **tools**, **system prompt**, and (optionally) a
73
+ store backend — the engine, persistence, run envelope, undo, and (via
74
+ `subagents`) delegation are all reused.
75
+
76
+ ## Architecture
77
+
78
+ ### Core — `lithe` (zero I/O, zero business logic)
79
+
80
+ | Module | What you get |
81
+ | --- | --- |
82
+ | `runtime` | `AgentRuntime`, the ReAct loop as an async event stream: streaming deltas; cancellation checked between deltas; run budgets (`max_cost` / `max_total_tokens`) ending with `status="budget_exceeded"` (cost computed from `LLMConfig.pricing` when the gateway reports none; parallel delegations count their in-flight siblings' live spend against the same ceiling); a repeat-call nudge for stuck models (reset by intervening writes, so read-after-write cycles are never flagged); a forced toolless wrap-up when the step budget is hit; mid-run context trimming that escalates from shrinking old tool outputs to dropping whole old exchanges under an omission note; a steering inbox (`inbox=` queue of user texts injected at step boundaries); error-isolated sinks; an injectable `http_client` for connection pooling (a client still on httpx's 5s default is upgraded to `cfg.timeout` instead of silently failing long calls). Every event is stamped with `run_id` + a monotonic `seq`; runs report wall-clock `duration_s`, tool results carry `elapsed_ms`, and streaming calls report time-to-first-token. |
83
+ | `llm` | OpenAI-compatible client: retry with jittered backoff, `Retry-After`-aware 429 handling, fail-fast on fatal 4xx, response-shape validation, and SSE streaming helpers. |
84
+ | `transports` | Chat-completions and Responses transports with usage normalized to `prompt_tokens` / `completion_tokens` / `total_tokens`; reasoning items replayed within the tool loop where the protocol supports it; `image_url` blocks mapped to `input_image` on the Responses path (unmappable blocks raise instead of vanishing). `LLMConfig.extra_body` / `default_headers` carry vendor fields and gateway headers on every call; `LLMConfig.reasoning_effort` maps to `reasoning_effort` (chat) / `reasoning.effort` (Responses), deep-merged with `extra_body["reasoning"]` siblings. |
85
+ | `tools` | `ToolRegistry`: register / unregister / dispatch, READ/WRITE/META category filtering, argument validation (required + top-level types + enums), pre-validation argument **transforms** (path canonicalization, defaults, redaction), per-tool timeouts, and pre-dispatch **middleware** for audit, quota, or human-in-the-loop confirmation of write tools. |
86
+ | `actions` | `Action` + `UndoEngine`: pure, storage-free undo; reverters may be sync or async. |
87
+ | `memory` | `replay_messages` / `recap_text` / `window_with_recap` / `run_timeline` + the `MemoryProvider` protocol; two-sided, window-safe replay reconciliation drops orphaned tool rows instead of sending API-rejected payloads. |
88
+ | `events` | `EventSink` with separate display + record channels, and SSE serialization (`to_sse`) that degrades non-JSON values instead of crashing. |
89
+ | `context` / `modes` | `AgentContext` plus host-defined modes via `register_mode(name, categories)`; `ctx.shared` is per-run state shared *by reference* with subagent contexts — the vehicle for cross-agent coordination. |
90
+
91
+ ### Bundles — `lithe.bundles` (optional capabilities)
92
+
93
+ | Bundle | What you get |
94
+ | --- | --- |
95
+ | `host` | `AgentHost`: message assembly, the `run_start`/`done` envelope, error funneling, `StoreSink`, zero-config `undo_run`, and `DictToolAdapter` for wrapping dict-based tool systems. Forwards budgets, cancellation, and a shared HTTP client to every run. |
96
+ | `store` | `RunStore` / `ConversationStore` / `BlobStore` Protocols, plus `JsonlRunStore` — a zero-database JSONL store with content-addressed blob spillover for large action values and optional `fsync` crash durability. |
97
+ | `subagents` | `SubagentEngine` + `delegate` / `delegate_parallel` tools: isolated worker agents the orchestrator hands subtasks to — tagged for undo, bounded by `max_parallel`, per-delegation budgets, cancellation propagated from the parent run, live `subagent_progress` heartbeats. |
98
+ | `admin` | Admin-panel tools: `tool_categories`, `list_tools_admin`, `list_tool_packages_admin`, `check_packages`. |
99
+ | `patch` | `apply_patch`: line-oriented multi-file edits via the Codex `*** Begin Patch` envelope, a four-pass fuzzy matcher, and all-or-nothing application against an in-memory overlay. |
100
+ | `providers` | Vendor presets: known-good `LLMConfig` fields per OpenAI-compatible endpoint (openai / zai / deepseek / openrouter / qwen / moonshot) as plain data — `get_preset` / `apply_preset` merge a preset under host overrides (dict fields per key). Defaults, never truth: credentials and model always come from the caller, model-specific switches stay in `notes`. Each preset also names the family's `document_format` dialect (see the `documents` bundle). |
101
+ | `workspace` | Sandboxed file I/O: `read_file` / `write_file` / `edit_file` / `list_files` / `search_files` / `glob_files` with undo reverters, a stale-file guard that refuses to clobber externally changed files, and symlink-safe directory walks. |
102
+ | `todos` | A per-scope task list the agent plans against: `TodoStore` + atomic JSON persistence + `update_todos` / `list_todos` tools + a `todos_block` for the system prompt. |
103
+ | `images` | `image_info` (a stdlib-only header probe: dimensions, dpi, color mode) and `analyze_image` (one vision-model call, memoized per file hash + question) — image answers never enter the main conversation. |
104
+ | `documents` | `document_info` (a stdlib-only probe: PDF version, OOXML subtype, best-effort page count) and `analyze_document` (one model call with the document as a content block, memoized per file hash + question). The block dialect follows the endpoint family: `document_format` = `inline-file` (OpenRouter family, incl. self-built same-format routers) / `files-api` (strict OpenAI two-step upload) / `none` (probe only); `LLMConfig.document_format` carries it, provider presets default it, a 400 names the mismatch. |
105
+ | `sandbox` | `run_code` / `run_file`: Python execution with bubblewrap or passthrough backends, head+tail output truncation so tracebacks stay visible. WRITE-classified, so invisible in read-only modes. |
106
+ | `command` | `run_command`: opt-in native shell execution (bash/sh on Unix-like systems, PowerShell/cmd on Windows), bounded by timeout/output limits and started in the host-selected workspace. Commands run with the host user's permissions and are not sandboxed or undoable. |
107
+ | `download` | `download_file`: streaming HTTP(S) ingress into the workspace — SSRF-guarded (every redirect hop re-validated, all resolved addresses must be globally routable), size-capped, time-budgeted, landed atomically. |
108
+ | `skills` | Markdown skill libraries: flat `SkillLibrary`, package-aware `SkillPackages` with remote registry mirrors, and the `load_skill` tool. |
109
+ | `mcp` | `MCPManager` + `MCPServerConfig`: bridge external MCP servers (stdio or streamable-http) into the registry — `tools/list` pagination followed, a safe env allow-list for spawned servers (never all of `os.environ`), self-healing sessions. |
110
+
111
+ ```python
112
+ from lithe.bundles import MCPManager, MCPServerConfig
113
+
114
+ manager = MCPManager([MCPServerConfig(
115
+ name="zai", command=["npx", "-y", "@z_ai/mcp-server"],
116
+ env={"Z_AI_API_KEY": "...", "Z_AI_MODE": "ZHIPU"},
117
+ default_category="read")])
118
+ await manager.attach(registry) # registry gains zai__* tools
119
+ ```
120
+
121
+ ## Safety defaults
122
+
123
+ Long-lived autonomous loops need guardrails on by default:
124
+
125
+ - **Path sandboxing** — workspace tools resolve inside the sandbox root;
126
+ directory walks never follow symlinks, so code executed by `run_code`
127
+ cannot plant a link to a host file and read it back.
128
+ - **SSRF guard** — `download_file` accepts only globally routable
129
+ http/https addresses, re-validating every redirect hop (cloud metadata
130
+ endpoints included in the rejection set).
131
+ - **Secret hygiene** — spawned MCP servers get an env allow-list, never
132
+ the parent environment; URLs log as `scheme://host` so credentials in
133
+ query strings never reach a log line.
134
+ - **Shell execution is explicit** — `run_command` is an optional host bundle,
135
+ not a default tool. When enabled, commands run with the host user's
136
+ permissions; they are not sandboxed and their side effects cannot be undone.
137
+ - **Write serialization** — READ tools run in parallel, every WRITE/META
138
+ tool runs alone in model order: no write races.
139
+ - **Run budgets** — `max_cost` / `max_total_tokens` cut a runaway run
140
+ short with no further tool execution or model calls.
141
+
142
+ ## Storage model
143
+
144
+ The kernel stores nothing. A host provides:
145
+
146
+ - an **`EventSink`** (write side) — persists message records however it
147
+ likes (DB / file / nowhere);
148
+ - a **`MemoryProvider`** (read side, optional) — replays prior turns;
149
+ - an **`UndoEngine`** fed from wherever the host kept actions.
150
+
151
+ ## More
152
+
153
+ - `examples/minimal_host.py` — a runnable, offline minimal host (tools →
154
+ run → events → undo); runs in CI.
155
+ - `examples/live_host.py` — the same flow against a real OpenAI-compatible
156
+ endpoint (set `LITHE_API_KEY` / `LITHE_BASE_URL` / `LITHE_MODEL`; no
157
+ default endpoint, it never spends tokens by accident).
158
+ - `CHANGELOG.md` — what changed and when.
159
+
160
+ ## License
161
+
162
+ MIT
@@ -0,0 +1,65 @@
1
+ """lithe — a reusable, storage-free ReAct agent kernel.
2
+
3
+ Hosts (e.g. a thesis-writing application) plug in their own tools, prompt,
4
+ domain model and persistence. The kernel knows nothing about how runs are
5
+ stored, or even whether they are: it emits events (which a host may sink to a
6
+ DB, a file, or drop) and reads prior turns through an optional memory provider
7
+ (added in a later step).
8
+
9
+ Layout:
10
+ - llm : OpenAI-compatible chat client (retry/backoff/jitter)
11
+ - events : Event vocabulary, EventSink, SSE serialization
12
+ - context : AgentContext (typed, mapping-compatible)
13
+ - modes : AgentMode / ToolCategory + category filtering
14
+ - actions : Action model + UndoEngine (pure logic, no storage)
15
+ - tools : ToolSpec / ToolResult / ToolRegistry (dispatch + undo wiring)
16
+ """
17
+ # Single source of truth for the package version; pyproject reads it via
18
+ # [tool.setuptools.dynamic] (statically, without importing this module).
19
+ __version__ = "0.9.3"
20
+
21
+ from lithe.actions import ( # noqa: F401
22
+ Action, Reverter, UndoEngine, UndoReport,
23
+ )
24
+ from lithe.context import AgentContext # noqa: F401
25
+ from lithe.events import Event, EventSink, EventType, to_sse # noqa: F401
26
+ from lithe.llm import ( # noqa: F401
27
+ bearer_headers, chat_completion, first_content, strip_think,
28
+ )
29
+ from lithe.memory import ( # noqa: F401
30
+ DEFAULT_REPLAY_LIMIT, DEFAULT_TOOL_RESULT_CAP, MemoryProvider,
31
+ recap_text, replay_messages, reasoning_summary_text, run_timeline,
32
+ truncate_tool_result, window_with_recap,
33
+ )
34
+ from lithe.modes import ( # noqa: F401
35
+ AgentMode, ToolCategory, categories_for, register_mode,
36
+ )
37
+ from lithe.runtime import ( # noqa: F401
38
+ DEFAULT_CONTEXT_BUDGET, DEFAULT_REPEAT_CALL_LIMIT, AgentRuntime,
39
+ LLMConfig, RunStats,
40
+ )
41
+ from lithe.tools import ( # noqa: F401
42
+ ToolHandler, ToolMiddleware, ToolRegistry, ToolResult, ToolSpec,
43
+ ToolTransform,
44
+ )
45
+ from lithe.transports import ( # noqa: F401
46
+ ChatCompletionsTransport, LLMTransport, ResponsesTransport, make_transport,
47
+ )
48
+
49
+ __all__ = [
50
+ "Action", "AgentContext", "AgentMode", "AgentRuntime",
51
+ "ChatCompletionsTransport",
52
+ "DEFAULT_CONTEXT_BUDGET", "DEFAULT_REPEAT_CALL_LIMIT",
53
+ "DEFAULT_REPLAY_LIMIT", "DEFAULT_TOOL_RESULT_CAP",
54
+ "Event", "EventSink", "EventType", "LLMConfig", "LLMTransport",
55
+ "MemoryProvider",
56
+ "ResponsesTransport",
57
+ "Reverter", "RunStats",
58
+ "ToolCategory", "ToolHandler", "ToolMiddleware", "ToolTransform",
59
+ "ToolRegistry", "ToolResult", "ToolSpec", "UndoEngine", "UndoReport",
60
+ "bearer_headers", "categories_for", "chat_completion", "first_content",
61
+ "make_transport", "register_mode",
62
+ "recap_text", "replay_messages", "reasoning_summary_text",
63
+ "run_timeline", "strip_think",
64
+ "to_sse", "truncate_tool_result", "window_with_recap",
65
+ ]
@@ -0,0 +1,105 @@
1
+ """Reversible mutations and the undo engine.
2
+
3
+ A write tool records an :class:`Action` (what it changed: kind/target/old/new)
4
+ and registers a :class:`Reverter` that knows how to reverse that kind.
5
+ :class:`UndoEngine` replays the reversals newest-first. None of this touches
6
+ storage: the engine takes a list of actions (from this run's in-memory state,
7
+ or read back by a host from wherever it persisted them), so undo works with or
8
+ without a database.
9
+
10
+ Reverters may be sync or async (``async def`` / coroutine-returning) — an
11
+ async reverter can roll back through remote APIs; :meth:`UndoEngine.undo`
12
+ awaits whatever the reverter returns.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import inspect
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+ from collections.abc import Callable
20
+
21
+ from lithe.context import AgentContext
22
+
23
+ # Action statuses that mean "the mutation is currently in effect" and so should
24
+ # be reverted. Pending/proposed changes that were never applied are skipped.
25
+ _REVERTIBLE = frozenset({"applied", "approved"})
26
+
27
+
28
+ @dataclass
29
+ class Action:
30
+ """One recorded mutation produced by a write tool.
31
+
32
+ ``id`` is opaque and host-assigned (e.g. a DB row id); the kernel only uses
33
+ it for ordering/reporting. ``old_value``/``new_value`` are domain-shaped and
34
+ interpreted by the matching reverter.
35
+ """
36
+ kind: str
37
+ target: str
38
+ old_value: Any = None
39
+ new_value: Any = None
40
+ status: str = "applied"
41
+ id: Any = None
42
+ subagent: str | None = None
43
+
44
+
45
+ # A reverter reverses one action kind: ``fn(action, ctx)`` returning None (sync)
46
+ # or an awaitable (async, e.g. rolling back through a remote API). It is
47
+ # best-effort: a partial failure (e.g. a file already gone) must not abort the
48
+ # rest of an undo run, so each reverter owns its own error handling.
49
+ Reverter = Callable[[Action, AgentContext], Any]
50
+
51
+
52
+ @dataclass
53
+ class UndoReport:
54
+ ok: bool = True
55
+ reverted: int = 0
56
+ skipped: int = 0
57
+ errors: list[str] = field(default_factory=list)
58
+
59
+
60
+ class UndoEngine:
61
+ """Revert a list of actions newest-first via registered reverters.
62
+
63
+ Pure logic: no storage. Unknown kinds and non-revertible statuses are
64
+ skipped; a reverter that raises is recorded as an error (not fatal) so the
65
+ rest of the run still reverts.
66
+ """
67
+
68
+ def __init__(self, reverters: dict[str, Reverter] | None = None):
69
+ self._reverters: dict[str, Reverter] = dict(reverters or {})
70
+
71
+ def register(self, kind: str, reverter: Reverter) -> None:
72
+ self._reverters[kind] = reverter
73
+
74
+ @property
75
+ def reverters(self) -> dict[str, Reverter]:
76
+ return dict(self._reverters)
77
+
78
+ async def undo(self, actions: list[Action], ctx: AgentContext) -> UndoReport:
79
+ """Revert *actions* newest-first, awaiting async reverters.
80
+
81
+ Pure logic: no storage. Unknown kinds and non-revertible statuses are
82
+ skipped; a reverter that raises is recorded as an error (not fatal) so
83
+ the rest of the run still reverts. A reverter's awaitable result is
84
+ awaited — an error *inside* the awaitable counts the same as a sync
85
+ raise.
86
+ """
87
+ report = UndoReport()
88
+ for action in reversed(actions):
89
+ if action.status not in _REVERTIBLE:
90
+ report.skipped += 1
91
+ continue
92
+ fn = self._reverters.get(action.kind)
93
+ if fn is None:
94
+ report.skipped += 1
95
+ continue
96
+ try:
97
+ result = fn(action, ctx)
98
+ if inspect.isawaitable(result):
99
+ await result
100
+ except Exception as exc: # noqa: BLE001
101
+ report.errors.append(f"{action.kind} {action.target}: {exc}")
102
+ report.ok = False
103
+ continue
104
+ report.reverted += 1
105
+ return report
@@ -0,0 +1,71 @@
1
+ """Optional capability bundles for lithe.
2
+
3
+ These are NOT part of the zero-I/O core engine; they are reusable, host-agnostic
4
+ capabilities a host opts into. The core never imports from here, so
5
+ ``import lithe`` alone stays storage- and I/O-free — bundles are pulled in
6
+ only when a host needs them.
7
+ """
8
+ from lithe.bundles.admin import ( # noqa: F401
9
+ ToolPackage, check_packages, list_tool_packages_admin, list_tools_admin,
10
+ package_meta, package_of, tool_categories,
11
+ )
12
+ from lithe.bundles.command import CommandRunner, register_command_tools # noqa: F401
13
+ from lithe.bundles.download import ( # noqa: F401
14
+ register_download_tools,
15
+ )
16
+ from lithe.bundles.documents import ( # noqa: F401
17
+ register_document_tools,
18
+ )
19
+ from lithe.bundles.host import ( # noqa: F401
20
+ AgentHost, DictToolAdapter, StoreSink, assemble_messages, undo_run,
21
+ )
22
+ from lithe.bundles.images import ( # noqa: F401
23
+ register_image_tools,
24
+ )
25
+ from lithe.bundles.mcp import ( # noqa: F401
26
+ MCPServerConfig, MCPManager, parse_servers,
27
+ )
28
+ from lithe.bundles.patch import ( # noqa: F401
29
+ register_apply_patch_tool,
30
+ )
31
+ from lithe.bundles.providers import ( # noqa: F401
32
+ PRESETS, apply_preset, get_preset, known_providers,
33
+ )
34
+ from lithe.bundles.sandbox import CodeRunner, register_code_tools # noqa: F401
35
+ from lithe.bundles.skills import ( # noqa: F401
36
+ PACKAGE_FILE, ROOT_PACKAGE, SKILL_MAIN, RemoteSkillSource, SkillLibrary,
37
+ SkillPackages, register_skill_tool,
38
+ )
39
+ from lithe.bundles.store import ( # noqa: F401
40
+ BlobStore, ConversationStore, JsonlRunStore, RunStore, StoredAction,
41
+ StoredMessage, StoredRun,
42
+ )
43
+ from lithe.bundles.subagents import ( # noqa: F401
44
+ SubagentEngine, SubagentRoster, SubagentSpec, make_delegate_tool,
45
+ make_parallel_delegate_tool, register_delegate_tool, register_delegate_tools,
46
+ )
47
+ from lithe.bundles.todos import ( # noqa: F401
48
+ JsonTodoStore, TodoStore, register_todo_tools, todos_block,
49
+ )
50
+ from lithe.bundles.workspace import Workspace, register_file_tools # noqa: F401
51
+
52
+ __all__ = [
53
+ "AgentHost", "BlobStore", "CodeRunner", "CommandRunner", "ConversationStore",
54
+ "DictToolAdapter", "JsonTodoStore", "JsonlRunStore", "MCPManager",
55
+ "MCPServerConfig", "PRESETS", "RunStore",
56
+ "PACKAGE_FILE", "ROOT_PACKAGE", "SKILL_MAIN", "RemoteSkillSource",
57
+ "SkillLibrary", "SkillPackages", "StoreSink", "StoredAction",
58
+ "StoredMessage", "StoredRun",
59
+ "SubagentEngine", "SubagentRoster", "SubagentSpec", "TodoStore",
60
+ "ToolPackage", "Workspace",
61
+ "apply_preset", "assemble_messages", "check_packages",
62
+ "get_preset", "known_providers", "list_tool_packages_admin",
63
+ "list_tools_admin", "make_delegate_tool", "make_parallel_delegate_tool",
64
+ "package_meta", "package_of", "parse_servers", "register_apply_patch_tool",
65
+ "register_code_tools", "register_command_tools", "register_download_tools",
66
+ "register_delegate_tool", "register_delegate_tools", "register_document_tools",
67
+ "register_file_tools",
68
+ "register_image_tools", "register_skill_tool", "register_todo_tools",
69
+ "tool_categories",
70
+ "todos_block", "undo_run",
71
+ ]