agent0-runtime 0.1.0__tar.gz → 0.1.1__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 (56) hide show
  1. agent0_runtime-0.1.1/CHANGELOG.md +41 -0
  2. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/PKG-INFO +26 -5
  3. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/README.md +14 -0
  4. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/docs/runtime.md +74 -8
  5. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/pyproject.toml +13 -1
  6. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/__init__.py +21 -3
  7. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/backend.py +2 -1
  8. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/builtin_tools.py +14 -1
  9. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/events.py +11 -4
  10. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/filesystem.py +67 -7
  11. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/images.py +22 -4
  12. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/loop.py +55 -7
  13. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/openai_backend.py +36 -2
  14. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/responses.py +2 -2
  15. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/routing.py +7 -0
  16. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/routing_backend.py +10 -1
  17. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/tools.py +45 -8
  18. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/types.py +50 -1
  19. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/web_fetch.py +10 -2
  20. agent0_runtime-0.1.1/tests/loop_fakes.py +31 -0
  21. agent0_runtime-0.1.1/tests/test_extras.py +54 -0
  22. agent0_runtime-0.1.1/tests/test_generation.py +107 -0
  23. agent0_runtime-0.1.1/tests/test_policy.py +136 -0
  24. agent0_runtime-0.1.1/tests/test_tool_limits.py +76 -0
  25. agent0_runtime-0.1.1/tests/test_usage_errors.py +83 -0
  26. agent0_runtime-0.1.0/CHANGELOG.md +0 -10
  27. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/.gitignore +0 -0
  28. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/LICENSE +0 -0
  29. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/examples/minimal_agent.py +0 -0
  30. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/capabilities.py +0 -0
  31. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/client.py +0 -0
  32. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/credentials.py +0 -0
  33. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/history.py +0 -0
  34. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/lifecycle.py +0 -0
  35. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/managed.py +0 -0
  36. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/plugins.py +0 -0
  37. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/providers.py +0 -0
  38. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/py.typed +0 -0
  39. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/search.py +0 -0
  40. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/session.py +0 -0
  41. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/shell.py +0 -0
  42. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/skills/websearch/SKILL.md +0 -0
  43. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/src/agent0_runtime/web_search.py +0 -0
  44. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/responses_fakes.py +0 -0
  45. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_assistant.py +0 -0
  46. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_builtin_tools.py +0 -0
  47. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_filesystem.py +0 -0
  48. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_images.py +0 -0
  49. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_managed.py +0 -0
  50. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_routing.py +0 -0
  51. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_runtime.py +0 -0
  52. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_shell.py +0 -0
  53. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_simple_api.py +0 -0
  54. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_web_fetch.py +0 -0
  55. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_web_search.py +0 -0
  56. {agent0_runtime-0.1.0 → agent0_runtime-0.1.1}/tests/test_web_search_api.py +0 -0
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.1
6
+
7
+ ### Added
8
+
9
+ - `GenerationConfig` (temperature, max output tokens, tool choice, parallel tool
10
+ calls, and a verbatim `extra` escape hatch) for per-run and per-backend
11
+ sampling settings; `Agent.run(generation=...)` overrides a backend default.
12
+ - `RunResult.usage_by_turn`, the per-round usage detail behind the run total.
13
+ - `WorkspacePolicy` confines `read`/`write`/`edit` to one root (symlink-aware),
14
+ supports a read-only workspace that also disables `bash`, and is injected
15
+ through `BuiltinToolsConfig(policy=...)`.
16
+ - `Agent(tool_timeout=..., max_tool_output_chars=...)` bounds one tool call and
17
+ caps tool output before it enters history.
18
+ - Stdlib logging under the `agent0_runtime` logger with a `NullHandler`: retries,
19
+ failover, compaction, observer, and tool failures are reported without any host
20
+ configuration.
21
+
22
+ ### Changed
23
+
24
+ - `RunResult.usage` is summed over every model round instead of reporting the
25
+ latest round only, so a host can report one cost per run.
26
+ - Only `openai` is a required dependency. Pillow moved to the `images` extra;
27
+ trafilatura, urllib3, and certifi moved to the `web` extra; `pip install
28
+ "agent0-runtime[all]"` restores the previous install footprint. Missing extras
29
+ surface as an install hint on the tool that needs them, never as an import
30
+ failure.
31
+ - `EventBus.errors` is a bounded deque (`max_errors=100`) instead of an unbounded
32
+ list.
33
+
34
+ ## 0.1.0
35
+
36
+ - Initial standalone release of the headless agent runtime.
37
+ - Provides the model/tool loop, OpenAI-compatible Responses backend, typed events,
38
+ lifecycle hooks, sessions, cancellation, plugins, provider clients, and generic
39
+ filesystem/shell/web tools.
40
+ - Applications own their terminal UI, persistence formats, credentials paths, and
41
+ product-specific recovery guidance.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: agent0-runtime
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: A small embeddable agent runtime with tools, sessions, events, and plugins
5
5
  Project-URL: Homepage, https://github.com/r1cardohj/agent0-runtime
6
6
  Project-URL: Repository, https://github.com/r1cardohj/agent0-runtime
@@ -19,11 +19,18 @@ Classifier: Programming Language :: Python :: 3.12
19
19
  Classifier: Programming Language :: Python :: 3.13
20
20
  Classifier: Typing :: Typed
21
21
  Requires-Python: >=3.10
22
- Requires-Dist: certifi>=2024
23
22
  Requires-Dist: openai>=1.40.0
24
- Requires-Dist: pillow>=12.3.0
25
- Requires-Dist: trafilatura<3,>=2.3
26
- Requires-Dist: urllib3>=2
23
+ Provides-Extra: all
24
+ Requires-Dist: certifi>=2024; extra == 'all'
25
+ Requires-Dist: pillow>=12.3.0; extra == 'all'
26
+ Requires-Dist: trafilatura<3,>=2.3; extra == 'all'
27
+ Requires-Dist: urllib3>=2; extra == 'all'
28
+ Provides-Extra: images
29
+ Requires-Dist: pillow>=12.3.0; extra == 'images'
30
+ Provides-Extra: web
31
+ Requires-Dist: certifi>=2024; extra == 'web'
32
+ Requires-Dist: trafilatura<3,>=2.3; extra == 'web'
33
+ Requires-Dist: urllib3>=2; extra == 'web'
27
34
  Description-Content-Type: text/markdown
28
35
 
29
36
  # agent0-runtime
@@ -39,6 +46,18 @@ application policy belong to consumers.
39
46
  python -m pip install agent0-runtime
40
47
  ```
41
48
 
49
+ `openai` is the only required dependency. Image reading and web fetch are opt-in
50
+ extras (web search needs only the standard library), and nothing from an extra is
51
+ imported unless the matching tool runs:
52
+
53
+ ```bash
54
+ python -m pip install "agent0-runtime[images]" # Pillow image attachments
55
+ python -m pip install "agent0-runtime[web]" # trafilatura + urllib3 + certifi
56
+ python -m pip install "agent0-runtime[all]" # every optional capability
57
+ ```
58
+
59
+ A host that embeds the loop with its own tools never pays for the extras.
60
+
42
61
  Python 3.10 through 3.13 are supported. The package is typed and ships `py.typed`.
43
62
 
44
63
  ## Minimal agent
@@ -97,6 +116,8 @@ python -m build
97
116
  python -m twine check --strict dist/*
98
117
  ```
99
118
 
119
+ Run the tests with `-e .[all]` when you touch images or web tools.
120
+
100
121
  ## License
101
122
 
102
123
  [MIT](LICENSE)
@@ -11,6 +11,18 @@ application policy belong to consumers.
11
11
  python -m pip install agent0-runtime
12
12
  ```
13
13
 
14
+ `openai` is the only required dependency. Image reading and web fetch are opt-in
15
+ extras (web search needs only the standard library), and nothing from an extra is
16
+ imported unless the matching tool runs:
17
+
18
+ ```bash
19
+ python -m pip install "agent0-runtime[images]" # Pillow image attachments
20
+ python -m pip install "agent0-runtime[web]" # trafilatura + urllib3 + certifi
21
+ python -m pip install "agent0-runtime[all]" # every optional capability
22
+ ```
23
+
24
+ A host that embeds the loop with its own tools never pays for the extras.
25
+
14
26
  Python 3.10 through 3.13 are supported. The package is typed and ships `py.typed`.
15
27
 
16
28
  ## Minimal agent
@@ -69,6 +81,8 @@ python -m build
69
81
  python -m twine check --strict dist/*
70
82
  ```
71
83
 
84
+ Run the tests with `-e .[all]` when you touch images or web tools.
85
+
72
86
  ## License
73
87
 
74
88
  [MIT](LICENSE)
@@ -69,8 +69,9 @@ await agent.close()
69
69
  ```
70
70
 
71
71
  `RunResult` contains `status`, `text`, `turns`, `run_id`, `finish_reason`,
72
- `stop_reason`, and the latest token usage. Interruption and backend failures are
73
- still exceptions, with corresponding terminal events emitted first.
72
+ `stop_reason`, and `usage`, which is summed over every model round in the run;
73
+ `usage_by_turn` keeps the per-round detail in order. Interruption and backend
74
+ failures are still exceptions, with corresponding terminal events emitted first.
74
75
 
75
76
  Each `RuntimeEvent` has a `kind`, per-run sequence number, `run_id`, timestamp,
76
77
  optional model-turn number, and a transport-safe payload. Event kinds cover
@@ -78,6 +79,12 @@ model/text/reasoning deltas, routing, usage, compaction, tool start/preview/end,
78
79
  and terminal turn states. `event.to_dict()` is suitable for a future JSON-RPC or
79
80
  WebSocket adapter. `on_event` may be synchronous or asynchronous.
80
81
 
82
+ Observer failures never break a run: they go to the `agent0_runtime` logger and to
83
+ a bounded `EventBus.errors` deque (`max_errors`, default 100), so a long-lived
84
+ agent cannot accumulate them without limit. The runtime logs retries, failovers,
85
+ compaction, and tool failures to the same logger tree and installs a
86
+ `NullHandler`, so hosts see nothing until they configure logging.
87
+
81
88
  For custom backends, instantiate `agent0_runtime.Agent` directly. The required
82
89
  backend protocol is only `complete(request, events) -> ModelTurn`; `model`,
83
90
  `provider_id`, `context_limit`, and `prepare()` are optional metadata/policy.
@@ -94,10 +101,10 @@ The runtime owns the model integration layer and normally depends on the
94
101
  OpenAI-compatible Responses endpoint, including streaming, function calls,
95
102
  usage mapping, retry-safe requests, raw Responses history, and client cleanup.
96
103
  The runtime owns provider metadata, configurable clients, credential storage,
97
- model discovery, and `RoutedResponsesBackend` intent/failover. Hosts such as
98
- hosts inject their credential store, client identity, and provider selection;
99
- other applications can use the default provider registry, their own router, or
100
- a different backend entirely.
104
+ model discovery, and `RoutedResponsesBackend` intent/failover. Embedding
105
+ applications inject their credential store, client identity, and provider
106
+ selection; other applications can use the default provider registry, their own
107
+ router, or a different backend entirely.
101
108
 
102
109
  `Agent(backend)` owns and closes its backend by default. Pass
103
110
  `close_backend=False` when a host shares that backend or its network client across
@@ -120,6 +127,29 @@ This factory installs `OpenAIResponsesBackend` and `ResponsesHistoryPolicy`.
120
127
  It defaults to `close_backend=False`; the host remains responsible for closing
121
128
  the injected client.
122
129
 
130
+ ## Generation settings
131
+
132
+ `GenerationConfig` carries per-run or per-backend sampling and output settings.
133
+ Every field is optional, so one backend default can be overridden per run:
134
+
135
+ ```python
136
+ from agent0_runtime import Agent, GenerationConfig
137
+
138
+ agent = Agent.from_openai(
139
+ client,
140
+ "deepseek-chat",
141
+ generation=GenerationConfig(temperature=0.2, max_output_tokens=4096),
142
+ )
143
+ result = await agent.run("summarize this", generation=GenerationConfig(temperature=0.0))
144
+ ```
145
+
146
+ The run config is merged over the backend default: here `temperature=0.0` wins and
147
+ `max_output_tokens=4096` is inherited. Unset fields are not sent at all. `extra`
148
+ is merged last and verbatim, so provider-specific parameters (for example a
149
+ `text` format object) reach the request without growing the neutral field list.
150
+ A backend that does not understand generation settings may ignore them; the
151
+ protocol still requires only `complete()`.
152
+
123
153
  ## Tool registry
124
154
 
125
155
  `@tool` derives names, JSON schemas, required arguments, and descriptions from a
@@ -161,6 +191,13 @@ Handlers receive a `ToolContext` and a decoded argument dictionary. They may be
161
191
  synchronous or asynchronous and return `str` or `ToolResult`. Synchronous
162
192
  handlers run in a worker thread so they do not block the event loop.
163
193
 
194
+ `Agent(tool_timeout=..., max_tool_output_chars=...)` bounds one handler call and
195
+ caps what enters history, so a hung or chatty tool cannot stall a run or blow up
196
+ the next prompt. Defaults: no timeout, 64,000 characters per result. A timed-out
197
+ handler returns `error: <name> timed out after Ns`; an oversized result is
198
+ truncated with a `[truncated N chars]` marker. Attachments and private state
199
+ survive truncation. Pass `None` to disable either limit.
200
+
164
201
  ## Generic built-in tools
165
202
 
166
203
  The runtime includes provider-neutral `read`, `write`, `edit`, `bash`, `fetch`,
@@ -184,6 +221,34 @@ a workspace only when selected by the model, so an assistant with no workspace c
184
221
  still use its own tools. Hosts supply their own credential resolvers without
185
222
  implementing the search transport itself.
186
223
 
224
+ `PillowImageReader` needs the `images` extra and `fetch` needs the `web` extra;
225
+ without them the tool returns an install hint instead of failing at import.
226
+ `search` uses only the standard library.
227
+
228
+ ### Workspace policy
229
+
230
+ `WorkspacePolicy` confines the filesystem tools to one root and can make it
231
+ read-only. It is injected through `BuiltinToolsConfig`, so a host never has to
232
+ fork the tools to sandbox them:
233
+
234
+ ```python
235
+ from pathlib import Path
236
+ from agent0_runtime import BuiltinToolsConfig, WorkspacePolicy, create_builtin_registry
237
+
238
+ registry = create_builtin_registry(
239
+ BuiltinToolsConfig(policy=WorkspacePolicy(root=Path("/srv/workspace"), read_only=True))
240
+ )
241
+ ```
242
+
243
+ Paths are resolved through symlinks and refused when they leave the root, so
244
+ `../secrets` and `/etc/passwd` become `error: path escapes the workspace` tool
245
+ results. `read_only=True` rejects `write`/`edit` and disables `bash` in the
246
+ registry. `allow_outside=True` opts back into unrestricted paths.
247
+
248
+ `bash` runs in the host process and is **not** confined by this policy: use a
249
+ container or an OS sandbox when shell confinement matters. Without a policy the
250
+ tools keep their previous permissive behaviour.
251
+
187
252
  ## Sessions and stores
188
253
 
189
254
  The core models only portable runtime state:
@@ -235,8 +300,9 @@ failures are isolated and recorded in `hooks.errors`; an optional `on_error`
235
300
  callback can forward them to a host logger.
236
301
 
237
302
  Lifecycle events distinguish the real `session_id` from `workspace_id`, and turn
238
- events include the matching `run_id`. Terminal signal handling remains in the
239
- REPL; outcome classification lives in `core.lifecycle`.
303
+ events include the matching `run_id`. Terminal signal handling belongs to the
304
+ host; outcome classification lives in
305
+ `agent0_runtime.lifecycle.run_with_lifecycle`.
240
306
 
241
307
  ## Plugins
242
308
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "agent0-runtime"
3
- version = "0.1.0"
3
+ version = "0.1.1"
4
4
  description = "A small embeddable agent runtime with tools, sessions, events, and plugins"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -27,6 +27,18 @@ classifiers = [
27
27
  ]
28
28
  dependencies = [
29
29
  "openai>=1.40.0",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ # The model integration layer is always required; every other capability is
34
+ # opt-in so `pip install agent0-runtime` stays small for headless embedders.
35
+ images = ["pillow>=12.3.0"]
36
+ web = [
37
+ "trafilatura>=2.3,<3",
38
+ "urllib3>=2",
39
+ "certifi>=2024",
40
+ ]
41
+ all = [
30
42
  "pillow>=12.3.0",
31
43
  "trafilatura>=2.3,<3",
32
44
  "urllib3>=2",
@@ -4,7 +4,9 @@ The backend/tool protocols, structured events, sessions, lifecycle, and plugins
4
4
  are independent of terminal interfaces and application-owned policy.
5
5
  """
6
6
 
7
- __version__ = "0.1.0"
7
+ import logging
8
+
9
+ __version__ = "0.1.1"
8
10
 
9
11
  from .backend import BackendRegistry, ModelBackend, ModelInfo, ModelRequest
10
12
  from .builtin_tools import (
@@ -28,7 +30,7 @@ from .events import (
28
30
  RuntimeEvent,
29
31
  RuntimeEventKind,
30
32
  )
31
- from .filesystem import ImageReader, VisionSupport
33
+ from .filesystem import ImageReader, VisionSupport, WorkspacePolicy
32
34
  from .history import ResponsesHistoryPolicy
33
35
  from .images import PillowImageReader, supports_vision
34
36
  from .lifecycle import (
@@ -67,12 +69,21 @@ from .routing_backend import RoutedResponsesBackend, stream_response_failover
67
69
  from .search import SearchProvider
68
70
  from .session import MemorySessionStore, RunContext, RuntimeSession, SessionStore
69
71
  from .shell import Shell
70
- from .tools import Tool, ToolContext, ToolExecution, ToolExecutor, ToolRegistry, tool
72
+ from .tools import (
73
+ DEFAULT_MAX_TOOL_OUTPUT_CHARS,
74
+ Tool,
75
+ ToolContext,
76
+ ToolExecution,
77
+ ToolExecutor,
78
+ ToolRegistry,
79
+ tool,
80
+ )
71
81
  from .types import (
72
82
  TOOL_ATTACHMENTS_KEY,
73
83
  AgentInterrupted,
74
84
  Attachment,
75
85
  CancellationToken,
86
+ GenerationConfig,
76
87
  Message,
77
88
  ModelTurn,
78
89
  Recovery,
@@ -84,6 +95,10 @@ from .types import (
84
95
  )
85
96
  from .web_search import DeepSeekSearchProvider
86
97
 
98
+ # Library default: stay silent unless the embedding application configures
99
+ # logging for the "agent0_runtime" logger tree.
100
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
101
+
87
102
  __all__ = [
88
103
  "Agent",
89
104
  "AgentInterrupted",
@@ -96,12 +111,14 @@ __all__ = [
96
111
  "CancellationToken",
97
112
  "Credential",
98
113
  "DEFAULT_MAX_TURNS",
114
+ "DEFAULT_MAX_TOOL_OUTPUT_CHARS",
99
115
  "DeepSeekSearchProvider",
100
116
  "EventBus",
101
117
  "EventEmitter",
102
118
  "EventListener",
103
119
  "FileCredentialStore",
104
120
  "FailoverRoute",
121
+ "GenerationConfig",
105
122
  "HistoryPolicy",
106
123
  "ImageReader",
107
124
  "OpenAIResponsesBackend",
@@ -154,6 +171,7 @@ __all__ = [
154
171
  "ToolRegistry",
155
172
  "ToolResult",
156
173
  "VisionSupport",
174
+ "WorkspacePolicy",
157
175
  "build_auto_route",
158
176
  "create_builtin_registry",
159
177
  "default_model_for",
@@ -10,7 +10,7 @@ from collections.abc import Callable
10
10
  from dataclasses import dataclass
11
11
  from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
12
12
 
13
- from .types import CancellationToken, Message, ModelTurn
13
+ from .types import CancellationToken, GenerationConfig, Message, ModelTurn
14
14
 
15
15
  if TYPE_CHECKING:
16
16
  from .events import EventEmitter
@@ -25,6 +25,7 @@ class ModelRequest:
25
25
  run_id: str
26
26
  turn: int = 1
27
27
  cancellation: CancellationToken | None = None
28
+ generation: GenerationConfig | None = None
28
29
 
29
30
 
30
31
  @runtime_checkable
@@ -8,7 +8,14 @@ from dataclasses import dataclass, field
8
8
  from typing import Any
9
9
 
10
10
  from . import web_fetch, web_search
11
- from .filesystem import ImageReader, VisionSupport, edit_file, read_file, write_file
11
+ from .filesystem import (
12
+ ImageReader,
13
+ VisionSupport,
14
+ WorkspacePolicy,
15
+ edit_file,
16
+ read_file,
17
+ write_file,
18
+ )
12
19
  from .search import SearchProvider
13
20
  from .shell import Shell, resolve_shell, run_shell
14
21
  from .tools import Tool, ToolContext, ToolRegistry
@@ -27,6 +34,7 @@ class BuiltinToolsConfig:
27
34
  image_reader: ImageReader | None = None
28
35
  supports_vision: VisionSupport | None = None
29
36
  search_provider: SearchProvider | None = None
37
+ policy: WorkspacePolicy | None = None
30
38
 
31
39
 
32
40
  def _fn(name: str, desc: str, props: dict[str, Any], required: list[str]) -> dict[str, Any]:
@@ -135,6 +143,7 @@ def create_builtin_registry(config: BuiltinToolsConfig | None = None) -> ToolReg
135
143
  model=context.model,
136
144
  image_reader=config.image_reader,
137
145
  supports_vision=config.supports_vision,
146
+ policy=config.policy,
138
147
  )
139
148
 
140
149
  def write(context: ToolContext, args: dict[str, Any]) -> str:
@@ -143,6 +152,7 @@ def create_builtin_registry(config: BuiltinToolsConfig | None = None) -> ToolReg
143
152
  str(args.get("path") or ""),
144
153
  str(args.get("content") or ""),
145
154
  on_preview=context.preview,
155
+ policy=config.policy,
146
156
  )
147
157
 
148
158
  def edit(context: ToolContext, args: dict[str, Any]) -> str:
@@ -152,9 +162,12 @@ def create_builtin_registry(config: BuiltinToolsConfig | None = None) -> ToolReg
152
162
  str(args.get("path") or ""),
153
163
  edits if isinstance(edits, list) else [],
154
164
  on_preview=context.preview,
165
+ policy=config.policy,
155
166
  )
156
167
 
157
168
  def bash(context: ToolContext, args: dict[str, Any]) -> str:
169
+ if config.policy is not None and config.policy.read_only:
170
+ return "error: workspace policy is read-only; bash is disabled"
158
171
  timeout = args.get("timeout")
159
172
  return run_shell(
160
173
  context.cwd,
@@ -3,12 +3,16 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import logging
7
+ from collections import deque
6
8
  from collections.abc import Awaitable, Callable, Iterable
7
9
  from contextlib import suppress
8
10
  from dataclasses import dataclass, field
9
11
  from datetime import datetime, timezone
10
12
  from typing import Any, Literal, TypeAlias
11
13
 
14
+ logger = logging.getLogger(__name__)
15
+
12
16
  RuntimeEventKind = Literal[
13
17
  "turn_started",
14
18
  "model_started",
@@ -79,16 +83,18 @@ ErrorListener = Callable[[ListenerError], Any]
79
83
  class EventBus:
80
84
  """Process-local subscriptions; each run gets an independent sequence/ID.
81
85
 
82
- Observer failures are isolated from the agent loop and recorded in
83
- ``errors``. An optional error listener can forward them to a host logger.
86
+ Observer failures are isolated from the agent loop and recorded in the
87
+ bounded ``errors`` deque (newest kept), so a long-lived agent cannot grow
88
+ without limit. An optional error listener can forward them to a host logger.
84
89
  Event delivery is ordered and backpressured: an async GUI subscriber must
85
90
  finish handling one event before the next is delivered to that subscriber.
86
91
  """
87
92
 
88
- def __init__(self, *, on_error: ErrorListener | None = None) -> None:
93
+ def __init__(self, *, on_error: ErrorListener | None = None, max_errors: int = 100) -> None:
89
94
  self._subscriptions: list[_Subscription] = []
90
95
  self._on_error = on_error
91
- self.errors: list[ListenerError] = []
96
+ self.max_errors = max(1, int(max_errors))
97
+ self.errors: deque[ListenerError] = deque(maxlen=self.max_errors)
92
98
 
93
99
  def subscribe(
94
100
  self, listener: EventListener, *, kinds: Iterable[RuntimeEventKind] | None = None
@@ -119,6 +125,7 @@ class EventBus:
119
125
  except Exception as error: # observers must not break a model/tool round
120
126
  failure = ListenerError(error, event, subscription.listener)
121
127
  self.errors.append(failure)
128
+ logger.warning("event listener failed on %s: %s", event.kind, type(error).__name__)
122
129
  if self._on_error is not None:
123
130
  # Diagnostics are observers too; never recursively fail a run.
124
131
  with suppress(Exception):
@@ -7,6 +7,7 @@ import os
7
7
  import tempfile
8
8
  from collections.abc import Callable
9
9
  from contextlib import suppress
10
+ from dataclasses import dataclass
10
11
  from pathlib import Path
11
12
  from typing import Any, Protocol
12
13
 
@@ -41,6 +42,40 @@ def resolve_path(cwd: Path, path: str) -> Path:
41
42
  return p if p.is_absolute() else cwd / p
42
43
 
43
44
 
45
+ @dataclass(frozen=True)
46
+ class WorkspacePolicy:
47
+ """Confine the filesystem tools to one workspace root.
48
+
49
+ ``root`` defaults to the run's cwd. Paths are resolved through symlinks and
50
+ must stay inside that root unless ``allow_outside`` opts out; ``read_only``
51
+ rejects every write and disables ``bash`` in the built-in registry.
52
+
53
+ ``bash`` itself runs in the host process and cannot be confined here: use a
54
+ container or an OS-level sandbox when shell confinement matters.
55
+ """
56
+
57
+ root: Path | None = None
58
+ read_only: bool = False
59
+ allow_outside: bool = False
60
+
61
+ def resolve(self, cwd: Path | None, path: str, *, write: bool = False) -> Path:
62
+ """Return the target path, or raise ``PermissionError`` if it is refused."""
63
+
64
+ if write and self.read_only:
65
+ raise PermissionError("workspace policy is read-only")
66
+ base = self.root if self.root is not None else cwd
67
+ fp = resolve_path(base or Path.cwd(), path)
68
+ if self.allow_outside:
69
+ return fp
70
+ if base is None:
71
+ raise PermissionError(f"no workspace is configured for {path!r}")
72
+ root = base.resolve()
73
+ target = fp.resolve()
74
+ if target != root and root not in target.parents:
75
+ raise PermissionError(f"path escapes the workspace: {path}")
76
+ return target
77
+
78
+
44
79
  def detect_image_mime(path: Path) -> str | None:
45
80
  """Suffix first, then magic bytes, so a suffix-less screenshot still works."""
46
81
 
@@ -99,6 +134,14 @@ def _truncate_text(s: str, limit: int, *, tag: str = "truncated") -> str:
99
134
  return s if len(s) <= limit else s[:limit] + f"\n...[{tag} {len(s) - limit} chars]"
100
135
 
101
136
 
137
+ def _target_path(
138
+ cwd: Path | None, path: str, policy: WorkspacePolicy | None, *, write: bool
139
+ ) -> Path:
140
+ """Resolve one tool path through the policy when the host configured one."""
141
+
142
+ return policy.resolve(cwd, path, write=write) if policy is not None else resolve_path(cwd, path)
143
+
144
+
102
145
  def read_file(
103
146
  cwd: Path | None,
104
147
  path: str,
@@ -108,10 +151,14 @@ def read_file(
108
151
  model: str | None = None,
109
152
  image_reader: ImageReader | None = None,
110
153
  supports_vision: VisionSupport | None = None,
154
+ policy: WorkspacePolicy | None = None,
111
155
  ) -> str | ToolResult:
112
- if cwd is None:
156
+ if cwd is None and (policy is None or policy.root is None):
113
157
  return "error: no workspace is configured"
114
- fp = resolve_path(cwd, path)
158
+ try:
159
+ fp = _target_path(cwd, path, policy, write=False)
160
+ except PermissionError as e:
161
+ return f"error: {e}"
115
162
  if not fp.is_file():
116
163
  return f"error: not a file: {fp}"
117
164
  mime = detect_image_mime(fp)
@@ -122,7 +169,10 @@ def read_file(
122
169
  "[Current model does not support images. The image is omitted from this request.]"
123
170
  )
124
171
  if image_reader is None:
125
- return f"error: image reader is not available for {fp}"
172
+ return (
173
+ f"error: no image reader is configured for {fp}; pass PillowImageReader "
174
+ "(pip install 'agent0-runtime[images]') as image_reader"
175
+ )
126
176
  return image_reader.read(fp, mime)
127
177
  want = limit if limit is not None and limit > 0 else DEFAULT_READ_LINES
128
178
  start = max(0, (offset or 1) - 1) if offset is not None else 0
@@ -176,10 +226,15 @@ def write_file(
176
226
  path: str,
177
227
  content: str,
178
228
  on_preview: Callable[[str], None] | None = None,
229
+ *,
230
+ policy: WorkspacePolicy | None = None,
179
231
  ) -> str:
180
- if cwd is None:
232
+ if cwd is None and (policy is None or policy.root is None):
181
233
  return "error: no workspace is configured"
182
- fp = resolve_path(cwd, path)
234
+ try:
235
+ fp = _target_path(cwd, path, policy, write=True)
236
+ except PermissionError as e:
237
+ return f"error: {e}"
183
238
  try:
184
239
  before = fp.read_text(encoding="utf-8") if fp.exists() else ""
185
240
  except UnicodeDecodeError:
@@ -198,10 +253,15 @@ def edit_file(
198
253
  path: str,
199
254
  edits: list[dict[str, Any]],
200
255
  on_preview: Callable[[str], None] | None = None,
256
+ *,
257
+ policy: WorkspacePolicy | None = None,
201
258
  ) -> str:
202
- if cwd is None:
259
+ if cwd is None and (policy is None or policy.root is None):
203
260
  return "error: no workspace is configured"
204
- fp = resolve_path(cwd, path)
261
+ try:
262
+ fp = _target_path(cwd, path, policy, write=True)
263
+ except PermissionError as e:
264
+ return f"error: {e}"
205
265
  if not fp.is_file():
206
266
  return f"error: not a file: {fp}"
207
267
  try:
@@ -4,9 +4,9 @@ from __future__ import annotations
4
4
 
5
5
  import base64
6
6
  import io
7
+ from functools import lru_cache
7
8
  from pathlib import Path
8
-
9
- from PIL import Image, ImageOps
9
+ from typing import Any
10
10
 
11
11
  from .capabilities import MODEL_CAPABILITIES
12
12
  from .filesystem import ImageReader
@@ -80,7 +80,21 @@ def detect_mime(path: Path) -> str | None:
80
80
  return None
81
81
 
82
82
 
83
- def _encode(image: Image.Image, mime_type: str, quality: int = 85) -> bytes:
83
+ @lru_cache(maxsize=1)
84
+ def _pillow() -> tuple[Any, Any]:
85
+ """Import Pillow on demand so the core runtime has no image dependency."""
86
+
87
+ try:
88
+ from PIL import Image, ImageOps
89
+ except ImportError as e:
90
+ raise RuntimeError(
91
+ "image support needs Pillow; install the images extra: "
92
+ "pip install 'agent0-runtime[images]'"
93
+ ) from e
94
+ return Image, ImageOps
95
+
96
+
97
+ def _encode(image: Any, mime_type: str, quality: int = 85) -> bytes:
84
98
  out = io.BytesIO()
85
99
  if mime_type == "image/jpeg":
86
100
  image.convert("RGB").save(out, format="JPEG", quality=quality, optimize=True)
@@ -98,6 +112,7 @@ def process_image(
98
112
  ) -> tuple[Attachment, list[str]] | None:
99
113
  """Normalize an image to a supported format and fit inline size limits."""
100
114
 
115
+ Image, ImageOps = _pillow()
101
116
  mime = base_mime(mime_type)
102
117
  hints: list[str] = []
103
118
  try:
@@ -154,7 +169,10 @@ class PillowImageReader(ImageReader):
154
169
  return ToolResult(f"error: {type(e).__name__}: {e}")
155
170
  if not data:
156
171
  return ToolResult(f"error: empty file: {path}")
157
- processed = process_image(data, mime)
172
+ try:
173
+ processed = process_image(data, mime)
174
+ except RuntimeError as e: # Pillow is an optional extra
175
+ return ToolResult(f"error: {e}")
158
176
  if processed is None:
159
177
  return ToolResult(
160
178
  f"Read image file [{mime or 'unknown'}]\n"