agent0-runtime 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,335 @@
1
+ """Instance-scoped tool definitions, registry, and serial async executor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ import json
8
+ from collections.abc import Awaitable, Callable, Iterable, Mapping
9
+ from dataclasses import dataclass, field, replace
10
+ from functools import wraps
11
+ from pathlib import Path
12
+ from types import UnionType
13
+ from typing import Any, Literal, TypeAlias, Union, get_args, get_origin, get_type_hints
14
+
15
+ from .events import EventEmitter
16
+ from .types import AgentInterrupted, CancellationToken, ToolCall, ToolResult
17
+
18
+ ToolReturn: TypeAlias = str | ToolResult
19
+ ToolHandler: TypeAlias = Callable[
20
+ ["ToolContext", dict[str, Any]], ToolReturn | Awaitable[ToolReturn]
21
+ ]
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Tool:
26
+ """A Chat-function-compatible schema plus its runtime handler."""
27
+
28
+ schema: dict[str, Any]
29
+ handler: ToolHandler
30
+
31
+ def __post_init__(self) -> None:
32
+ function = self.schema.get("function")
33
+ if self.schema.get("type") != "function" or not isinstance(function, dict):
34
+ raise ValueError("tool schema must be a function tool")
35
+ if not str(function.get("name") or "").strip():
36
+ raise ValueError("tool schema needs a function.name")
37
+ if not callable(self.handler):
38
+ raise TypeError("tool handler must be callable")
39
+
40
+ @property
41
+ def name(self) -> str:
42
+ return self.schema["function"]["name"]
43
+
44
+ @classmethod
45
+ def define(
46
+ cls,
47
+ name: str,
48
+ description: str,
49
+ parameters: dict[str, Any],
50
+ handler: ToolHandler,
51
+ *,
52
+ required: list[str] | None = None,
53
+ ) -> Tool:
54
+ """Define a function tool without hand-writing the outer schema."""
55
+
56
+ return cls(
57
+ schema={
58
+ "type": "function",
59
+ "function": {
60
+ "name": name,
61
+ "description": description,
62
+ "parameters": {
63
+ "type": "object",
64
+ "properties": parameters,
65
+ "required": required or [],
66
+ },
67
+ },
68
+ },
69
+ handler=handler,
70
+ )
71
+
72
+
73
+ _JSON_SCALAR_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"}
74
+
75
+
76
+ def _parameter_schema(annotation: Any) -> dict[str, Any]:
77
+ """Translate common Python annotations into a function-tool JSON schema."""
78
+
79
+ if annotation is inspect.Parameter.empty or annotation is Any:
80
+ return {}
81
+ if annotation is type(None):
82
+ return {"type": "null"}
83
+ origin = get_origin(annotation)
84
+ if origin is Literal:
85
+ return {"enum": list(get_args(annotation))}
86
+ if origin in (Union, UnionType):
87
+ return {"anyOf": [_parameter_schema(item) for item in get_args(annotation)]}
88
+ if annotation is list or origin is list:
89
+ schema: dict[str, Any] = {"type": "array"}
90
+ args = get_args(annotation)
91
+ if args:
92
+ schema["items"] = _parameter_schema(args[0])
93
+ return schema
94
+ if annotation is dict or origin is dict:
95
+ return {"type": "object"}
96
+ if annotation in _JSON_SCALAR_TYPES:
97
+ return {"type": _JSON_SCALAR_TYPES[annotation]}
98
+ raise TypeError(f"unsupported tool parameter annotation: {annotation!r}")
99
+
100
+
101
+ _TOOL_ATTRIBUTE = "__agent0_tool__"
102
+
103
+
104
+ def _as_tool(value: Any) -> Tool:
105
+ """Resolve a Tool or a decorated function into its Tool definition."""
106
+
107
+ if isinstance(value, Tool):
108
+ return value
109
+ tool_definition = getattr(value, _TOOL_ATTRIBUTE, None)
110
+ if isinstance(tool_definition, Tool):
111
+ return tool_definition
112
+ raise TypeError("tools must be Tool instances or functions decorated with @tool")
113
+
114
+
115
+ def tool(
116
+ name_or_function: str | Callable[..., Any] | None = None,
117
+ *,
118
+ name: str = "",
119
+ description: str = "",
120
+ ) -> Callable[..., Any] | Callable[[Callable[..., Any]], Callable[..., Any]]:
121
+ """Mark a typed function as a Tool and keep it callable.
122
+
123
+ ``@tool``, ``@tool(name="...")``, and ``@tool("...")`` all work. The name,
124
+ JSON schema, required arguments, and docstring are stored on the returned
125
+ function so an Agent can later resolve a decorated tool by its string name.
126
+ """
127
+
128
+ if isinstance(name_or_function, str):
129
+
130
+ def configure(function: Callable[..., Any]) -> Callable[..., Any]:
131
+ return _decorate_tool(function, name=name or name_or_function, description=description)
132
+
133
+ return configure
134
+
135
+ def decorate(function: Callable[..., Any]) -> Callable[..., Any]:
136
+ return _decorate_tool(function, name=name, description=description)
137
+
138
+ return decorate if name_or_function is None else decorate(name_or_function)
139
+
140
+
141
+ def _decorate_tool(func: Callable[..., Any], *, name: str, description: str) -> Callable[..., Any]:
142
+ """Build a Tool from a function and attach it to the function itself."""
143
+
144
+ hints = get_type_hints(func)
145
+ signature = inspect.signature(func)
146
+ properties: dict[str, Any] = {}
147
+ required: list[str] = []
148
+ for parameter_name, parameter in signature.parameters.items():
149
+ if parameter.kind not in (
150
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
151
+ inspect.Parameter.KEYWORD_ONLY,
152
+ ):
153
+ raise TypeError("@tool functions may only declare named parameters")
154
+ properties[parameter_name] = _parameter_schema(
155
+ hints.get(parameter_name, parameter.annotation)
156
+ )
157
+ if parameter.default is inspect.Parameter.empty:
158
+ required.append(parameter_name)
159
+
160
+ tool_definition = Tool.define(
161
+ name or func.__name__,
162
+ description or inspect.getdoc(func) or func.__name__.replace("_", " "),
163
+ properties,
164
+ _tool_handler(func),
165
+ required=required,
166
+ )
167
+ setattr(func, _TOOL_ATTRIBUTE, tool_definition)
168
+ return func
169
+
170
+
171
+ def _tool_handler(
172
+ func: Callable[..., Any],
173
+ ) -> Callable[[ToolContext, dict[str, Any]], Any]:
174
+ if inspect.iscoroutinefunction(func):
175
+
176
+ @wraps(func)
177
+ async def invoke(_context: ToolContext, args: dict[str, Any]) -> Any:
178
+ return await func(**args)
179
+
180
+ else:
181
+
182
+ @wraps(func)
183
+ def invoke(_context: ToolContext, args: dict[str, Any]) -> Any:
184
+ return func(**args)
185
+
186
+ return invoke
187
+
188
+
189
+ class ToolRegistry:
190
+ """Tools registered on one runtime, never process-global mutable handlers."""
191
+
192
+ def __init__(self, tools: Iterable[Tool | Callable[..., Any]] = ()) -> None:
193
+ self._tools: dict[str, Tool] = {}
194
+ for tool in tools:
195
+ self.register(tool)
196
+
197
+ def register(self, tool: Tool | Callable[..., Any], *, replace_existing: bool = False) -> None:
198
+ tool = _as_tool(tool)
199
+ if tool.name in self._tools and not replace_existing:
200
+ raise ValueError(f"tool already registered: {tool.name}")
201
+ self._tools[tool.name] = tool
202
+
203
+ def unregister(self, name: str) -> None:
204
+ self._tools.pop(name, None)
205
+
206
+ def get(self, name: str) -> Tool | None:
207
+ return self._tools.get(name)
208
+
209
+ def names(self) -> tuple[str, ...]:
210
+ return tuple(self._tools)
211
+
212
+ def schemas(self) -> list[dict[str, Any]]:
213
+ return [tool.schema for tool in self._tools.values()]
214
+
215
+
216
+ @dataclass(frozen=True)
217
+ class ToolContext:
218
+ """Host-neutral execution context supplied to every tool/plugin."""
219
+
220
+ cwd: Path | None # required only by filesystem/shell tools
221
+ call: ToolCall
222
+ model: str | None = None
223
+ user_question: str | None = None
224
+ preview: Callable[[str], None] | None = None
225
+ cancellation: CancellationToken | None = None
226
+ services: Mapping[str, Any] = field(default_factory=dict)
227
+
228
+
229
+ @dataclass(frozen=True)
230
+ class ToolExecution:
231
+ call: ToolCall
232
+ args: dict[str, Any]
233
+ result: ToolResult
234
+
235
+
236
+ class ToolExecutor:
237
+ """Validate arguments, execute sync/async handlers, and emit tool events."""
238
+
239
+ def __init__(self, registry: ToolRegistry) -> None:
240
+ self.registry = registry
241
+
242
+ async def execute(
243
+ self,
244
+ call: ToolCall,
245
+ context: ToolContext,
246
+ events: EventEmitter,
247
+ *,
248
+ turn: int,
249
+ ) -> ToolExecution:
250
+ if context.cancellation is not None:
251
+ context.cancellation.throw_if_cancelled(run_id=events.run_id)
252
+ args: dict[str, Any] = {}
253
+ try:
254
+ decoded = json.loads(call.arguments or "{}")
255
+ if not isinstance(decoded, dict):
256
+ raise TypeError("expected a JSON object")
257
+ args = decoded
258
+ error: str | None = None
259
+ except (json.JSONDecodeError, TypeError) as exc:
260
+ error = f"error: invalid JSON arguments: {call.arguments!r} ({exc})"
261
+
262
+ await events.emit(
263
+ "tool_started",
264
+ turn=turn,
265
+ call_id=call.id,
266
+ name=call.name,
267
+ args=args,
268
+ )
269
+ if error is not None:
270
+ result = ToolResult(error)
271
+ await events.emit(
272
+ "tool_finished",
273
+ turn=turn,
274
+ call_id=call.id,
275
+ name=call.name,
276
+ args=args,
277
+ result=result.text,
278
+ )
279
+ return ToolExecution(call, args, result)
280
+
281
+ tool = self.registry.get(call.name)
282
+ if tool is None:
283
+ result = ToolResult(f"error: unknown tool {call.name}")
284
+ await events.emit(
285
+ "tool_finished",
286
+ turn=turn,
287
+ call_id=call.id,
288
+ name=call.name,
289
+ args=args,
290
+ result=result.text,
291
+ )
292
+ return ToolExecution(call, args, result)
293
+
294
+ previews: list[str] = []
295
+ local = replace(context, preview=previews.append)
296
+ try:
297
+ if inspect.iscoroutinefunction(tool.handler):
298
+ returned = await tool.handler(local, args)
299
+ else:
300
+ returned = await asyncio.to_thread(tool.handler, local, args)
301
+ if inspect.isawaitable(returned):
302
+ returned = await returned
303
+ if isinstance(returned, ToolResult):
304
+ result = returned
305
+ elif isinstance(returned, str):
306
+ result = ToolResult(returned)
307
+ else:
308
+ raise TypeError("tool handler must return str or ToolResult")
309
+ except (AgentInterrupted, asyncio.CancelledError, KeyboardInterrupt):
310
+ raise
311
+ except TypeError as exc:
312
+ result = ToolResult(f"error: bad args for {call.name}: {exc}")
313
+ except Exception as exc:
314
+ result = ToolResult(f"error: {type(exc).__name__}: {exc}")
315
+
316
+ for preview in previews:
317
+ await events.emit(
318
+ "tool_preview",
319
+ turn=turn,
320
+ call_id=call.id,
321
+ name=call.name,
322
+ args=args,
323
+ text=preview,
324
+ )
325
+ if context.cancellation is not None:
326
+ context.cancellation.throw_if_cancelled(run_id=events.run_id)
327
+ await events.emit(
328
+ "tool_finished",
329
+ turn=turn,
330
+ call_id=call.id,
331
+ name=call.name,
332
+ args=args,
333
+ result=result.text,
334
+ )
335
+ return ToolExecution(call, args, result)
@@ -0,0 +1,153 @@
1
+ """Shared, transport-neutral values used by the agent runtime.
2
+
3
+ This module deliberately knows nothing about OpenAI, host sessions, or a UI.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import threading
9
+ import uuid
10
+ from dataclasses import dataclass, field
11
+ from enum import Enum
12
+ from typing import Any
13
+
14
+ Message = dict[str, Any]
15
+ JSONState = dict[str, Any]
16
+ # Generic tool-result attachment blocks carried next to a text message.
17
+ TOOL_ATTACHMENTS_KEY = "_attachments"
18
+
19
+
20
+ def new_run_id() -> str:
21
+ """Return an ID suitable for logs, event streams, and future RPC transport."""
22
+
23
+ return f"run-{uuid.uuid4().hex}"
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ToolCall:
28
+ """One model-requested tool invocation with its encoded JSON arguments."""
29
+
30
+ id: str
31
+ name: str
32
+ arguments: str = "{}"
33
+
34
+ def as_message(self) -> dict[str, Any]:
35
+ """Project to the portable assistant/tool history shape."""
36
+
37
+ return {
38
+ "id": self.id,
39
+ "type": "function",
40
+ "function": {"name": self.name, "arguments": self.arguments or "{}"},
41
+ }
42
+
43
+
44
+ @dataclass
45
+ class ModelTurn:
46
+ """One completed model round, normalized across backend implementations.
47
+
48
+ ``state`` may contain JSON-safe, private message fields (named ``_*``). A
49
+ Responses adapter uses this for raw replay items without leaking that wire
50
+ concept into the generic loop.
51
+ """
52
+
53
+ text: str = ""
54
+ calls: list[ToolCall] = field(default_factory=list)
55
+ usage: dict[str, int] | None = None
56
+ finish_reason: str | None = None
57
+ model: str | None = None
58
+ state: JSONState = field(default_factory=dict)
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class Attachment:
63
+ """One model-facing attachment, independent of any provider wire format."""
64
+
65
+ data: str
66
+ mime_type: str
67
+ kind: str = "image"
68
+
69
+ def to_dict(self) -> dict[str, str]:
70
+ return {"kind": self.kind, "mime_type": self.mime_type, "data": self.data}
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class ToolResult:
75
+ """Text shown to the model plus provider-neutral result extensions."""
76
+
77
+ text: str
78
+ state: JSONState = field(default_factory=dict)
79
+ attachments: tuple[Attachment, ...] = ()
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class Recovery:
84
+ """A history edit that makes one failed model request safe to retry."""
85
+
86
+ messages: list[Message]
87
+ compacted: int = 0
88
+
89
+
90
+ class RunStatus(str, Enum):
91
+ """Terminal states for a normally completed run.
92
+
93
+ Interruption and backend failure remain exceptions; their corresponding
94
+ lifecycle events are emitted before those exceptions cross the API boundary.
95
+ """
96
+
97
+ SUCCEEDED = "succeeded"
98
+ BLOCKED = "blocked"
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class RunResult:
103
+ """The typed outcome of an agent run."""
104
+
105
+ text: str
106
+ status: RunStatus
107
+ turns: int
108
+ run_id: str
109
+ session_id: str = ""
110
+ finish_reason: str | None = None
111
+ stop_reason: str | None = None
112
+ usage: dict[str, int] | None = None
113
+
114
+
115
+ class AgentInterrupted(Exception):
116
+ """A cancelled run, optionally carrying text emitted before interruption."""
117
+
118
+ def __init__(self, partial: str = "", *, reason: str = "interrupted", run_id: str = "") -> None:
119
+ self.partial = partial
120
+ self.reason = reason
121
+ self.run_id = run_id
122
+ super().__init__(partial)
123
+
124
+
125
+ class CancellationToken:
126
+ """Thread-safe cooperative cancellation for hosts that do not own a Task.
127
+
128
+ Cancelling the asyncio task remains the way to interrupt a blocked network
129
+ stream immediately. A token is checked at runtime and backend boundaries;
130
+ like ``asyncio.to_thread``, it cannot kill an arbitrary synchronous plugin.
131
+ """
132
+
133
+ def __init__(self) -> None:
134
+ self._event = threading.Event()
135
+ self._lock = threading.Lock()
136
+ self._reason = "cancelled"
137
+
138
+ @property
139
+ def cancelled(self) -> bool:
140
+ return self._event.is_set()
141
+
142
+ @property
143
+ def reason(self) -> str:
144
+ return self._reason
145
+
146
+ def cancel(self, reason: str = "cancelled") -> None:
147
+ with self._lock:
148
+ self._reason = reason or "cancelled"
149
+ self._event.set()
150
+
151
+ def throw_if_cancelled(self, *, partial: str = "", run_id: str = "") -> None:
152
+ if self.cancelled:
153
+ raise AgentInterrupted(partial, reason=self.reason, run_id=run_id)