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,172 @@
1
+ """The standalone, embeddable agent0 runtime.
2
+
3
+ The backend/tool protocols, structured events, sessions, lifecycle, and plugins
4
+ are independent of terminal interfaces and application-owned policy.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ from .backend import BackendRegistry, ModelBackend, ModelInfo, ModelRequest
10
+ from .builtin_tools import (
11
+ BUILTIN_TOOL_SCHEMAS,
12
+ BuiltinToolsConfig,
13
+ create_builtin_registry,
14
+ )
15
+ from .capabilities import MODEL_CAPABILITIES, ModelCapability
16
+ from .client import (
17
+ OpenAIClient,
18
+ OpenAISyncClient,
19
+ make_openai_client,
20
+ make_openai_sync_client,
21
+ )
22
+ from .credentials import FileCredentialStore
23
+ from .events import (
24
+ EventBus,
25
+ EventEmitter,
26
+ EventListener,
27
+ ListenerError,
28
+ RuntimeEvent,
29
+ RuntimeEventKind,
30
+ )
31
+ from .filesystem import ImageReader, VisionSupport
32
+ from .history import ResponsesHistoryPolicy
33
+ from .images import PillowImageReader, supports_vision
34
+ from .lifecycle import (
35
+ LifecycleContext,
36
+ LifecycleEvent,
37
+ LifecycleHooks,
38
+ LifecycleKind,
39
+ LifecycleListenerError,
40
+ emit_lifecycle,
41
+ run_with_lifecycle,
42
+ )
43
+ from .loop import DEFAULT_MAX_TURNS, Agent, HistoryPolicy
44
+ from .managed import ManagedProvider
45
+ from .openai_backend import OpenAIResponsesBackend
46
+ from .plugins import (
47
+ PLUGIN_API_VERSION,
48
+ PLUGIN_ENTRY_POINT,
49
+ Plugin,
50
+ PluginContext,
51
+ PluginError,
52
+ PluginInfo,
53
+ PluginManager,
54
+ discover_plugins,
55
+ )
56
+ from .providers import (
57
+ BUILTIN_PROVIDERS,
58
+ Credential,
59
+ ProviderSpec,
60
+ default_model_for,
61
+ get_provider,
62
+ list_providers,
63
+ resolve_all_env,
64
+ )
65
+ from .routing import AUTO_REF, FailoverRoute, RouteSelection, RouteTarget, build_auto_route
66
+ from .routing_backend import RoutedResponsesBackend, stream_response_failover
67
+ from .search import SearchProvider
68
+ from .session import MemorySessionStore, RunContext, RuntimeSession, SessionStore
69
+ from .shell import Shell
70
+ from .tools import Tool, ToolContext, ToolExecution, ToolExecutor, ToolRegistry, tool
71
+ from .types import (
72
+ TOOL_ATTACHMENTS_KEY,
73
+ AgentInterrupted,
74
+ Attachment,
75
+ CancellationToken,
76
+ Message,
77
+ ModelTurn,
78
+ Recovery,
79
+ RunResult,
80
+ RunStatus,
81
+ ToolCall,
82
+ ToolResult,
83
+ new_run_id,
84
+ )
85
+ from .web_search import DeepSeekSearchProvider
86
+
87
+ __all__ = [
88
+ "Agent",
89
+ "AgentInterrupted",
90
+ "Attachment",
91
+ "AUTO_REF",
92
+ "BackendRegistry",
93
+ "BUILTIN_PROVIDERS",
94
+ "BUILTIN_TOOL_SCHEMAS",
95
+ "BuiltinToolsConfig",
96
+ "CancellationToken",
97
+ "Credential",
98
+ "DEFAULT_MAX_TURNS",
99
+ "DeepSeekSearchProvider",
100
+ "EventBus",
101
+ "EventEmitter",
102
+ "EventListener",
103
+ "FileCredentialStore",
104
+ "FailoverRoute",
105
+ "HistoryPolicy",
106
+ "ImageReader",
107
+ "OpenAIResponsesBackend",
108
+ "OpenAIClient",
109
+ "OpenAISyncClient",
110
+ "LifecycleContext",
111
+ "LifecycleEvent",
112
+ "LifecycleHooks",
113
+ "LifecycleKind",
114
+ "LifecycleListenerError",
115
+ "ListenerError",
116
+ "Message",
117
+ "ModelBackend",
118
+ "ModelCapability",
119
+ "MODEL_CAPABILITIES",
120
+ "ModelInfo",
121
+ "ModelRequest",
122
+ "MemorySessionStore",
123
+ "ManagedProvider",
124
+ "ModelTurn",
125
+ "PLUGIN_API_VERSION",
126
+ "PLUGIN_ENTRY_POINT",
127
+ "Plugin",
128
+ "ProviderSpec",
129
+ "PluginContext",
130
+ "PluginError",
131
+ "PluginInfo",
132
+ "PluginManager",
133
+ "PillowImageReader",
134
+ "Recovery",
135
+ "RunContext",
136
+ "RunResult",
137
+ "RunStatus",
138
+ "ResponsesHistoryPolicy",
139
+ "RouteSelection",
140
+ "RouteTarget",
141
+ "RoutedResponsesBackend",
142
+ "RuntimeEvent",
143
+ "RuntimeEventKind",
144
+ "RuntimeSession",
145
+ "TOOL_ATTACHMENTS_KEY",
146
+ "SearchProvider",
147
+ "SessionStore",
148
+ "Shell",
149
+ "Tool",
150
+ "ToolCall",
151
+ "ToolContext",
152
+ "ToolExecution",
153
+ "ToolExecutor",
154
+ "ToolRegistry",
155
+ "ToolResult",
156
+ "VisionSupport",
157
+ "build_auto_route",
158
+ "create_builtin_registry",
159
+ "default_model_for",
160
+ "discover_plugins",
161
+ "emit_lifecycle",
162
+ "get_provider",
163
+ "list_providers",
164
+ "make_openai_client",
165
+ "make_openai_sync_client",
166
+ "new_run_id",
167
+ "resolve_all_env",
168
+ "run_with_lifecycle",
169
+ "stream_response_failover",
170
+ "supports_vision",
171
+ "tool",
172
+ ]
@@ -0,0 +1,78 @@
1
+ """Model backend SPI and registry.
2
+
3
+ A backend owns provider wire formats and streaming. The generic loop owns model
4
+ rounds, tool rounds, history, cancellation, and terminal run outcomes.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
12
+
13
+ from .types import CancellationToken, Message, ModelTurn
14
+
15
+ if TYPE_CHECKING:
16
+ from .events import EventEmitter
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class ModelRequest:
21
+ """Everything a backend needs for one model round."""
22
+
23
+ messages: list[Message]
24
+ tools: list[dict[str, Any]]
25
+ run_id: str
26
+ turn: int = 1
27
+ cancellation: CancellationToken | None = None
28
+
29
+
30
+ @runtime_checkable
31
+ class ModelBackend(Protocol):
32
+ """The required backend boundary; metadata and ``prepare`` are optional."""
33
+
34
+ async def complete(self, request: ModelRequest, events: EventEmitter) -> ModelTurn: ...
35
+
36
+
37
+ @runtime_checkable
38
+ class ModelInfo(Protocol):
39
+ """Optional backend metadata used by routing, status, and tool context."""
40
+
41
+ @property
42
+ def model(self) -> str: ...
43
+
44
+ @property
45
+ def provider_id(self) -> str | None: ...
46
+
47
+ @property
48
+ def context_limit(self) -> int | None: ...
49
+
50
+
51
+ BackendFactory = Callable[..., ModelBackend]
52
+
53
+
54
+ class BackendRegistry:
55
+ """Named backend factories, primarily populated by plugins."""
56
+
57
+ def __init__(self) -> None:
58
+ self._factories: dict[str, BackendFactory] = {}
59
+
60
+ def register(self, name: str, factory: BackendFactory, *, replace: bool = False) -> None:
61
+ key = name.strip()
62
+ if not key:
63
+ raise ValueError("backend name cannot be empty")
64
+ if not callable(factory):
65
+ raise TypeError("backend factory must be callable")
66
+ if key in self._factories and not replace:
67
+ raise ValueError(f"backend already registered: {key}")
68
+ self._factories[key] = factory
69
+
70
+ def create(self, name: str, **kwargs: Any) -> ModelBackend:
71
+ try:
72
+ factory = self._factories[name]
73
+ except KeyError:
74
+ raise ValueError(f"unknown backend: {name}") from None
75
+ return factory(**kwargs)
76
+
77
+ def names(self) -> tuple[str, ...]:
78
+ return tuple(sorted(self._factories))
@@ -0,0 +1,200 @@
1
+ """Generic built-in tools, registered through the same public Tool SPI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+
10
+ from . import web_fetch, web_search
11
+ from .filesystem import ImageReader, VisionSupport, edit_file, read_file, write_file
12
+ from .search import SearchProvider
13
+ from .shell import Shell, resolve_shell, run_shell
14
+ from .tools import Tool, ToolContext, ToolRegistry
15
+ from .types import ToolResult
16
+
17
+ DEFAULT_SEARCH_COUNT = 8
18
+ MIN_SEARCH_COUNT, MAX_SEARCH_COUNT = 1, 50
19
+ MAX_SEARCH_QUERY_CHARS = 128
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class BuiltinToolsConfig:
24
+ """Application-provided services for the generic built-in tools."""
25
+
26
+ shell: Shell = field(default_factory=resolve_shell)
27
+ image_reader: ImageReader | None = None
28
+ supports_vision: VisionSupport | None = None
29
+ search_provider: SearchProvider | None = None
30
+
31
+
32
+ def _fn(name: str, desc: str, props: dict[str, Any], required: list[str]) -> dict[str, Any]:
33
+ return {
34
+ "type": "function",
35
+ "function": {
36
+ "name": name,
37
+ "description": desc,
38
+ "parameters": {"type": "object", "properties": props, "required": required},
39
+ },
40
+ }
41
+
42
+
43
+ _EDIT_ITEM = {
44
+ "type": "object",
45
+ "properties": {
46
+ "old_string": {"type": "string"},
47
+ "new_string": {"type": "string"},
48
+ },
49
+ "required": ["old_string", "new_string"],
50
+ }
51
+
52
+ BUILTIN_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
53
+ _fn(
54
+ "read",
55
+ "Read text file (numbered). Default 200 lines; page with offset/limit. "
56
+ "Also reads images (png/jpg/jpeg/gif/webp/bmp), which are returned as image attachments.",
57
+ {"path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}},
58
+ ["path"],
59
+ ),
60
+ _fn(
61
+ "write",
62
+ "Create or overwrite a whole file.",
63
+ {"path": {"type": "string"}, "content": {"type": "string"}},
64
+ ["path", "content"],
65
+ ),
66
+ _fn(
67
+ "edit",
68
+ "Precise edits. One call may include multiple edits[] against the original "
69
+ "file; no overlaps.",
70
+ {"path": {"type": "string"}, "edits": {"type": "array", "items": _EDIT_ITEM}},
71
+ ["path", "edits"],
72
+ ),
73
+ _fn(
74
+ "bash",
75
+ "Run a shell command in cwd (host shell). Output capped ~12k chars.",
76
+ {"command": {"type": "string"}, "timeout": {"type": "integer"}},
77
+ ["command"],
78
+ ),
79
+ _fn(
80
+ "fetch",
81
+ "Fetch an http/https web page and extract readable Markdown text with metadata.",
82
+ {
83
+ "url": {"type": "string"},
84
+ "max_chars": {
85
+ "type": "integer",
86
+ "minimum": 1,
87
+ "maximum": web_fetch.MAX_FETCH_CHARS,
88
+ "description": (
89
+ f"Maximum returned characters; defaults to {web_fetch.DEFAULT_FETCH_CHARS}."
90
+ ),
91
+ },
92
+ },
93
+ ["url"],
94
+ ),
95
+ _fn(
96
+ "search",
97
+ "Search the web (DeepSeek Search API) for ranked pages with summaries. "
98
+ 'The query takes site:, -site:, "...", lang:, after: and before: operators. '
99
+ f"Read {web_search.skill_path()} before the first search of a task for "
100
+ "query syntax and result triage.",
101
+ {
102
+ "query": {
103
+ "type": "string",
104
+ "minLength": 1,
105
+ "maxLength": web_search.MAX_QUERY_CHARS,
106
+ "description": "Search terms, optionally with search operators.",
107
+ },
108
+ "count": {
109
+ "type": "integer",
110
+ "minimum": web_search.MIN_COUNT,
111
+ "maximum": web_search.MAX_COUNT,
112
+ "description": (
113
+ f"Results to return; defaults to {web_search.DEFAULT_COUNT}. "
114
+ "Does not change the price of the request."
115
+ ),
116
+ },
117
+ },
118
+ ["query"],
119
+ ),
120
+ )
121
+
122
+
123
+ def create_builtin_registry(config: BuiltinToolsConfig | None = None) -> ToolRegistry:
124
+ """Create an instance-scoped registry of the generic built-in tools."""
125
+
126
+ config = config or BuiltinToolsConfig()
127
+ registry = ToolRegistry()
128
+
129
+ def read(context: ToolContext, args: dict[str, Any]) -> str | ToolResult:
130
+ return read_file(
131
+ context.cwd,
132
+ str(args.get("path") or ""),
133
+ args.get("offset"),
134
+ args.get("limit"),
135
+ model=context.model,
136
+ image_reader=config.image_reader,
137
+ supports_vision=config.supports_vision,
138
+ )
139
+
140
+ def write(context: ToolContext, args: dict[str, Any]) -> str:
141
+ return write_file(
142
+ context.cwd,
143
+ str(args.get("path") or ""),
144
+ str(args.get("content") or ""),
145
+ on_preview=context.preview,
146
+ )
147
+
148
+ def edit(context: ToolContext, args: dict[str, Any]) -> str:
149
+ edits = args.get("edits")
150
+ return edit_file(
151
+ context.cwd,
152
+ str(args.get("path") or ""),
153
+ edits if isinstance(edits, list) else [],
154
+ on_preview=context.preview,
155
+ )
156
+
157
+ def bash(context: ToolContext, args: dict[str, Any]) -> str:
158
+ timeout = args.get("timeout")
159
+ return run_shell(
160
+ context.cwd,
161
+ str(args.get("command") or ""),
162
+ int(timeout) if isinstance(timeout, int) else None,
163
+ shell=config.shell,
164
+ )
165
+
166
+ def fetch(_context: ToolContext, args: dict[str, Any]) -> str:
167
+ max_chars = args.get("max_chars")
168
+ return web_fetch.tool_fetch(
169
+ _context.cwd,
170
+ str(args.get("url") or ""),
171
+ int(max_chars) if isinstance(max_chars, int) else None,
172
+ )
173
+
174
+ async def search(_context: ToolContext, args: dict[str, Any]) -> str:
175
+ query = args.get("query")
176
+ if not isinstance(query, str) or not query.strip():
177
+ return "error: query must be a non-empty string"
178
+ if config.search_provider is None:
179
+ return "error: no search provider is configured"
180
+ count = args.get("count")
181
+ result = config.search_provider.search(
182
+ query,
183
+ int(count) if isinstance(count, int) else None,
184
+ user_question=_context.user_question,
185
+ )
186
+ if inspect.isawaitable(result):
187
+ result = await result
188
+ return result
189
+
190
+ handlers: dict[str, Callable[[ToolContext, dict[str, Any]], Any]] = {
191
+ "read": read,
192
+ "write": write,
193
+ "edit": edit,
194
+ "bash": bash,
195
+ "fetch": fetch,
196
+ "search": search,
197
+ }
198
+ for schema in BUILTIN_TOOL_SCHEMAS:
199
+ registry.register(Tool(schema=schema, handler=handlers[schema["function"]["name"]]))
200
+ return registry
@@ -0,0 +1,50 @@
1
+ """Reviewed model capabilities shared by routing, image tools, and hosts."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class ModelCapability:
8
+ """Reviewed model metadata; unknown listed models stay out of auto routing."""
9
+
10
+ provider_id: str
11
+ model: str
12
+ context_limit: int
13
+ strengths: frozenset[str]
14
+ scorer_priority: int | None = None
15
+ supports_responses: bool = True
16
+ supports_tools: bool = True
17
+ supports_vision: bool = True
18
+ routing_hint: str = ""
19
+
20
+ @property
21
+ def ref(self) -> str:
22
+ return f"{self.provider_id}/{self.model}"
23
+
24
+
25
+ MODEL_CAPABILITIES = (
26
+ ModelCapability(
27
+ provider_id="deepseek",
28
+ model="deepseek-flash",
29
+ context_limit=1_048_576,
30
+ strengths=frozenset({"fast", "coding"}),
31
+ scorer_priority=1,
32
+ supports_vision=True,
33
+ routing_hint="Fast general coding, explanations, and quick edits.",
34
+ ),
35
+ ModelCapability(
36
+ provider_id="kimi",
37
+ model="kimi-for-coding",
38
+ context_limit=1_048_576,
39
+ strengths=frozenset({"fast", "coding"}),
40
+ scorer_priority=2,
41
+ routing_hint="Fast implementation, refactoring, and test-focused coding.",
42
+ ),
43
+ ModelCapability(
44
+ provider_id="kimi",
45
+ model="k3.1-pro",
46
+ context_limit=1_048_576,
47
+ strengths=frozenset({"strong"}),
48
+ routing_hint="Strong architecture and repository-wide coding; largest context.",
49
+ ),
50
+ )
@@ -0,0 +1,69 @@
1
+ """Configurable OpenAI client factories with host-specific User-Agent metadata."""
2
+
3
+ from typing import Any
4
+
5
+ from openai import AsyncOpenAI, OpenAI
6
+
7
+
8
+ class OpenAIClient(AsyncOpenAI):
9
+ """Async OpenAI client carrying an embedding application's identity."""
10
+
11
+ def __init__(
12
+ self, *args: Any, application: str = "agent0-runtime", version: str = "", **kwargs: Any
13
+ ):
14
+ self.application = application
15
+ self.application_version = version
16
+ super().__init__(*args, **kwargs)
17
+
18
+ @property
19
+ def user_agent(self) -> str:
20
+ suffix = f"/{self.application_version}" if self.application_version else ""
21
+ return f"{self.application}{suffix}"
22
+
23
+
24
+ class OpenAISyncClient(OpenAI):
25
+ """Synchronous counterpart used for model discovery and host tooling."""
26
+
27
+ def __init__(
28
+ self, *args: Any, application: str = "agent0-runtime", version: str = "", **kwargs: Any
29
+ ):
30
+ self.application = application
31
+ self.application_version = version
32
+ super().__init__(*args, **kwargs)
33
+
34
+ @property
35
+ def user_agent(self) -> str:
36
+ suffix = f"/{self.application_version}" if self.application_version else ""
37
+ return f"{self.application}{suffix}"
38
+
39
+
40
+ def make_openai_client(
41
+ api_key: str,
42
+ base_url: str,
43
+ *,
44
+ application: str = "agent0-runtime",
45
+ version: str = "",
46
+ ) -> OpenAIClient:
47
+ return OpenAIClient(
48
+ api_key=api_key,
49
+ base_url=base_url,
50
+ application=application,
51
+ version=version,
52
+ )
53
+
54
+
55
+ def make_openai_sync_client(
56
+ api_key: str,
57
+ base_url: str,
58
+ *,
59
+ timeout: float,
60
+ application: str = "agent0-runtime",
61
+ version: str = "",
62
+ ) -> OpenAISyncClient:
63
+ return OpenAISyncClient(
64
+ api_key=api_key,
65
+ base_url=base_url,
66
+ timeout=timeout,
67
+ application=application,
68
+ version=version,
69
+ )
@@ -0,0 +1,85 @@
1
+ """Small JSON credential store with atomic writes and owner-only permissions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ from collections.abc import Callable
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .providers import Credential
13
+
14
+
15
+ class FileCredentialStore:
16
+ """Store provider credentials in a host-selected JSON file.
17
+
18
+ The path may be dynamic so embedding applications can honor their own
19
+ environment and XDG configuration policy without runtime dependencies.
20
+ """
21
+
22
+ def __init__(self, path: Path | Callable[[], Path], *, source: str = "stored") -> None:
23
+ self._path = path
24
+ self.source = source
25
+
26
+ @property
27
+ def path(self) -> Path:
28
+ return self._path() if callable(self._path) else self._path
29
+
30
+ def load(self) -> dict[str, Any]:
31
+ path = self.path
32
+ if not path.is_file():
33
+ return {}
34
+ try:
35
+ data = json.loads(path.read_text(encoding="utf-8"))
36
+ except (OSError, json.JSONDecodeError):
37
+ return {}
38
+ return data if isinstance(data, dict) else {}
39
+
40
+ def save(self, data: dict[str, Any]) -> Path:
41
+ path = self.path
42
+ path.parent.mkdir(parents=True, exist_ok=True)
43
+ tmp = path.with_suffix(".tmp")
44
+ tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
45
+ with contextlib.suppress(OSError):
46
+ os.chmod(tmp, 0o600)
47
+ tmp.replace(path)
48
+ with contextlib.suppress(OSError):
49
+ os.chmod(path, 0o600)
50
+ return path
51
+
52
+ def resolve(self, provider_id: str, default_base_url: str) -> Credential | None:
53
+ entry = self.load().get(provider_id)
54
+ if not isinstance(entry, dict) or entry.get("type") == "oauth":
55
+ return None
56
+ key = entry.get("key")
57
+ if not isinstance(key, str) or not key.strip():
58
+ return None
59
+ base_url = entry.get("baseUrl")
60
+ return Credential(
61
+ key.strip(),
62
+ base_url if isinstance(base_url, str) else default_base_url,
63
+ self.source,
64
+ )
65
+
66
+ def login(self, provider_id: str, key: str, base_url: str) -> Credential:
67
+ data = self.load()
68
+ data[provider_id] = {"type": "api_key", "key": key, "baseUrl": base_url}
69
+ data["active"] = provider_id
70
+ self.save(data)
71
+ return Credential(key, base_url, "login")
72
+
73
+ def logout(self, provider_id: str) -> bool:
74
+ data = self.load()
75
+ if provider_id not in data:
76
+ return False
77
+ del data[provider_id]
78
+ if data.get("active") == provider_id:
79
+ data.pop("active", None)
80
+ self.save(data)
81
+ return True
82
+
83
+ def active_provider(self) -> str:
84
+ active = self.load().get("active")
85
+ return active if isinstance(active, str) else ""