first commit

This commit is contained in:
2026-03-13 12:33:54 +08:00
commit 3ef61ee373
35 changed files with 1393 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
# Python cache and compiled files
__pycache__/
*.py[cod]
*.pyo
# Build artifacts
build/
dist/
*.egg-info/
# Test and tooling cache
.pytest_cache/
.ruff_cache/
.coverage
.mypy_cache/
# Virtual environments
.venv/
venv/
# Local environment and secrets
.env
.env.*
config.json
config.local.json
# Runtime data
.voidbot/
# Editor and OS files
.DS_Store
+10
View File
@@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.venv" />
</content>
<orderEntry type="jdk" jdkName="uv (VoidBot)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.github.wanniwa.editorjumper.settings.EditorJumperProjectSettings">
<option name="projectEditorType" value="Cursor" />
</component>
</project>
+7
View File
@@ -0,0 +1,7 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="TsLint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KubernetesApiProvider"><![CDATA[{}]]></component>
<component name="ProjectRootManager" version="2" project-jdk-name="uv (VoidBot)" project-jdk-type="Python SDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/VoidBot.iml" filepath="$PROJECT_DIR$/.idea/VoidBot.iml" />
</modules>
</component>
</project>
Generated
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+79
View File
@@ -0,0 +1,79 @@
# VoidBot
VoidBot is a minimal Python agent runtime designed around three ideas:
- Borrow the lightweight execution loop and session persistence style from `nanobot`.
- Borrow the provider compatibility and gateway/runtime separation from `openclaw`.
- Keep the first version small: single session, CLI gateway, OpenAI-compatible model calls, tool loop.
## Architecture
```text
CLI Gateway
-> AgentRuntime
-> ContextBuilder
-> SessionStore
-> ToolRegistry
-> ProviderRegistry
-> OpenAI Compatible Provider
```
See [docs/architecture.md](/home/mcallzbl/File2/Workshop/Projects/VoidBot/docs/architecture.md) for the layer breakdown and message flow.
## Initial Capabilities
- Build runtime context from workspace metadata, system prompt, tool list, and session history
- Call an OpenAI-compatible chat completions endpoint
- Execute tools and feed tool results back into the model loop
- Run as a single-session CLI gateway
- Support provider presets for:
- `openai_chatgpt`
- `zhipu_coding_plan`
- `custom_openai_compatible`
## Quick Start
1. Create a config file:
```json
{
"provider": "zhipu_coding_plan",
"api_key": "YOUR_API_KEY",
"model": "glm-4.7",
"workspace": ".",
"max_iterations": 8
}
```
You can also start from [config.example.json](/home/mcallzbl/File2/Workshop/Projects/VoidBot/config.example.json).
2. Run one turn:
```bash
/home/mcallzbl/.local/bin/uv run voidbot chat --config /home/mcallzbl/File2/Workshop/Projects/VoidBot/config.example.json --message "Summarize this repository"
```
3. Run interactive mode:
```bash
/home/mcallzbl/.local/bin/uv run voidbot chat --config /path/to/config.json
```
## Config Fields
- `provider`: provider preset name
- `api_key`: provider API key
- `api_base`: optional override for the provider base URL
- `model`: optional override for the model ID
- `workspace`: workspace path used by tools and context
- `session_file`: optional JSONL transcript path
- `max_iterations`: max tool-call rounds in one turn
- `history_limit`: number of previous messages to include
- `system_prompt`: optional custom system prompt
## Notes
- The current gateway is CLI-only and single-session by design.
- The model layer is deliberately OpenAI-compatible first, so adding more gateways later is straightforward.
- The current built-in tools are `list_dir`, `read_file`, `write_file`, and `run_command`.
- Every inbound request gets `session_id`, `run_id`, and `message_id` before entering the runtime.
+11
View File
@@ -0,0 +1,11 @@
{
"provider": "zhipu_coding_plan",
"api_key": "YOUR_API_KEY",
"api_base": "https://open.bigmodel.cn/api/coding/paas/v4",
"model": "glm-4.7",
"workspace": ".",
"session_file": ".voidbot/session.jsonl",
"max_iterations": 8,
"history_limit": 24,
"system_prompt": "You are VoidBot, a concise coding agent. Use tools when needed, cite tool results plainly, and finish once the task is complete."
}
+101
View File
@@ -0,0 +1,101 @@
# VoidBot Architecture
## Design Goals
- Keep the first version small and runnable.
- Separate gateway, runtime, and model adapter from the start.
- Normalize tool calling so more providers can be added later without rewriting the agent loop.
## Layers
### 1. Gateway
Files:
- `src/voidbot/gateway/cli.py`
- `src/voidbot/gateway/messages.py`
Responsibilities:
- Parse CLI input
- Normalize inbound text into `InboundMessageContext`
- Generate `session_id`, `run_id`, and `message_id`
- Hand normalized input to the runtime layer
### 2. Runtime
Files:
- `src/voidbot/agent.py`
- `src/voidbot/context.py`
- `src/voidbot/session.py`
Responsibilities:
- Load aligned history from JSONL
- Build a stable system prompt and a volatile runtime block
- Execute the loop:
- call model
- inspect tool calls
- execute tools
- inject tool results
- continue until final answer or iteration limit
### 3. Model Compatibility Layer
Files:
- `src/voidbot/providers/base.py`
- `src/voidbot/providers/registry.py`
- `src/voidbot/providers/compat.py`
- `src/voidbot/providers/openai_compatible.py`
Responsibilities:
- Resolve provider presets
- Normalize request payload shape
- Hide provider-specific API details behind one `chat()` method
- Keep compatibility rules out of the runtime loop
### 4. Tools
Files:
- `src/voidbot/tools/base.py`
- `src/voidbot/tools/filesystem.py`
- `src/voidbot/tools/shell.py`
Responsibilities:
- Provide OpenAI-style JSON schema definitions
- Execute real capabilities inside the workspace
- Return plain text results that can be injected back into the transcript
## Current Message Flow
```text
CLI input
-> InboundMessageContext
-> AgentRuntime.run_turn()
-> ContextBuilder.build_messages()
-> Provider.chat()
-> LLMResponse
-> ToolRegistry.execute() if tool calls exist
-> tool result messages appended
-> Provider.chat() again
-> final assistant reply
-> JSONL session persistence
```
## Why This Matches openclaw + nanobot
- From `nanobot`: the loop is kept simple and centered on normalized `LLMResponse`, tool schemas, and append-only history.
- From `openclaw`: gateway context is explicit, provider presets are registry-driven, and compatibility logic is separated from the loop.
## Planned Next Extensions
- Streaming output adapter
- HTTP/WebSocket gateway in addition to CLI
- More providers and provider-specific compat patches
- Safer command execution policies and approval hooks
- Multiple sessions and session routing
+36
View File
@@ -0,0 +1,36 @@
[project]
name = "voidbot"
version = "0.1.0"
description = "A minimal Python agent runtime with gateway and provider compatibility."
readme = "README.md"
requires-python = ">=3.11"
authors = [
{ name = "mcallzbl" }
]
dependencies = []
[project.scripts]
voidbot = "voidbot.gateway.cli:main"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/voidbot"]
[tool.hatch.build.targets.sdist]
include = [
"README.md",
"src/voidbot",
"tests",
"config.example.json",
]
[tool.pytest.ini_options]
testpaths = ["tests"]
[dependency-groups]
dev = [
"ruff>=0.15.6",
]
+5
View File
@@ -0,0 +1,5 @@
"""VoidBot package."""
__all__ = ["__version__"]
__version__ = "0.1.0"
+5
View File
@@ -0,0 +1,5 @@
from voidbot.gateway.cli import main
if __name__ == "__main__":
main()
+95
View File
@@ -0,0 +1,95 @@
"""Agent runtime loop."""
from __future__ import annotations
from dataclasses import dataclass
from voidbot.config import AppConfig
from voidbot.context import ContextBuilder
from voidbot.gateway.messages import InboundMessageContext
from voidbot.models import RunTurnResult
from voidbot.providers.base import LLMProvider
from voidbot.session import SessionStore
from voidbot.tools.base import ToolRegistry
@dataclass(slots=True)
class AgentRuntime:
"""Single-session runtime."""
config: AppConfig
provider: LLMProvider
session: SessionStore
tools: ToolRegistry
context_builder: ContextBuilder
def run_turn(self, inbound: InboundMessageContext) -> RunTurnResult:
"""Run one user turn through the tool loop."""
history = self.session.load_history(limit=self.config.history_limit)
tool_summaries = self.tools.summaries()
messages = self.context_builder.build_messages(history, inbound, tool_summaries)
self.session.append(
{
"role": "user",
"content": inbound.body_for_agent,
"run_id": inbound.run_id,
"message_id": inbound.message_id,
"raw_body": inbound.raw_body,
"session_id": inbound.session_id,
}
)
tool_events: list[dict] = []
final_reply = "No reply produced."
iteration = 0
while iteration < self.config.max_iterations:
iteration += 1
response = self.provider.chat(messages=messages, tools=self.tools.schemas())
assistant_message = {
"role": "assistant",
"content": response.content,
}
if response.has_tool_calls:
assistant_message["tool_calls"] = [
tool_call.as_openai_payload() for tool_call in response.tool_calls
]
messages.append(assistant_message)
self.session.append(assistant_message)
if not response.has_tool_calls:
final_reply = response.content or final_reply
break
for tool_call in response.tool_calls:
result = self.tools.execute(tool_call.name, tool_call.arguments)
tool_event = {
"tool_name": tool_call.name,
"arguments": tool_call.arguments,
"result": result,
"run_id": inbound.run_id,
}
tool_events.append(tool_event)
tool_message = {
"role": "tool",
"tool_call_id": tool_call.id,
"name": tool_call.name,
"run_id": inbound.run_id,
"content": self.tools.stringify_result(
tool_call.name,
tool_call.arguments,
result,
),
}
messages.append(tool_message)
self.session.append(tool_message)
else:
final_reply = (
f"Stopped after reaching max_iterations={self.config.max_iterations}."
)
return RunTurnResult(
reply=final_reply, iterations=iteration, tool_events=tool_events
)
+80
View File
@@ -0,0 +1,80 @@
"""Configuration loading."""
from __future__ import annotations
import json
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@dataclass(slots=True)
class AppConfig:
"""Runtime configuration."""
provider: str = "openai_chatgpt"
api_key: str = ""
api_base: str | None = None
model: str | None = None
workspace: Path = Path(".")
session_file: Path = Path(".voidbot/session.jsonl")
max_iterations: int = 8
history_limit: int = 24
system_prompt: str | None = None
request_timeout: int = 120
@classmethod
def from_mapping(cls, data: dict[str, Any]) -> "AppConfig":
"""Build config from a user mapping."""
workspace = Path(data.get("workspace") or ".").expanduser().resolve()
session_value = data.get("session_file") or ".voidbot/session.jsonl"
session_file = Path(session_value).expanduser()
if not session_file.is_absolute():
session_file = workspace / session_file
return cls(
provider=str(data.get("provider") or "openai_chatgpt"),
api_key=str(data.get("api_key") or ""),
api_base=str(data["api_base"]) if data.get("api_base") else None,
model=str(data["model"]) if data.get("model") else None,
workspace=workspace,
session_file=session_file.resolve(),
max_iterations=int(data.get("max_iterations") or 8),
history_limit=int(data.get("history_limit") or 24),
system_prompt=str(data["system_prompt"])
if data.get("system_prompt")
else None,
request_timeout=int(data.get("request_timeout") or 120),
)
def load_config(config_path: str | Path | None) -> AppConfig:
"""Load config from JSON file and environment."""
payload: dict[str, Any] = {}
if config_path:
path = Path(config_path).expanduser().resolve()
payload = json.loads(path.read_text(encoding="utf-8"))
env_map = {
"provider": os.getenv("VOIDBOT_PROVIDER"),
"api_key": os.getenv("VOIDBOT_API_KEY"),
"api_base": os.getenv("VOIDBOT_API_BASE"),
"model": os.getenv("VOIDBOT_MODEL"),
"workspace": os.getenv("VOIDBOT_WORKSPACE"),
"session_file": os.getenv("VOIDBOT_SESSION_FILE"),
"max_iterations": os.getenv("VOIDBOT_MAX_ITERATIONS"),
"history_limit": os.getenv("VOIDBOT_HISTORY_LIMIT"),
"system_prompt": os.getenv("VOIDBOT_SYSTEM_PROMPT"),
"request_timeout": os.getenv("VOIDBOT_REQUEST_TIMEOUT"),
}
for key, value in env_map.items():
if value not in (None, ""):
payload[key] = value
config = AppConfig.from_mapping(payload)
if not config.api_key:
raise ValueError(
"api_key is required. Set it in config JSON or VOIDBOT_API_KEY."
)
return config
+79
View File
@@ -0,0 +1,79 @@
"""Context assembly for model calls."""
from __future__ import annotations
import platform
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from voidbot.config import AppConfig
from voidbot.gateway.messages import InboundMessageContext
@dataclass(slots=True)
class ContextBuilder:
"""Build system prompt and request messages."""
config: AppConfig
def build_messages(
self,
history: list[dict],
inbound: InboundMessageContext,
tool_summaries: list[str],
) -> list[dict]:
"""Build a chat completion message array."""
runtime_block = self._build_runtime_block(inbound, tool_summaries)
return [
{"role": "system", "content": self._build_system_prompt()},
*history,
{
"role": "user",
"content": f"{runtime_block}\n\nUser Request:\n{inbound.body_for_agent}",
},
]
def _build_system_prompt(self) -> str:
if self.config.system_prompt:
return self.config.system_prompt
return (
"You are VoidBot, a practical coding agent.\n"
"Use tools when needed.\n"
"When a tool result is useful, reflect it in the final answer plainly.\n"
"Do not invent tool results.\n"
"Finish as soon as the task is completed."
)
def _build_runtime_block(
self,
inbound: InboundMessageContext,
tool_summaries: list[str],
) -> str:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
tool_text = (
"\n".join(f"- {item}" for item in tool_summaries) or "- no tools registered"
)
instructions = self._load_workspace_instructions(self.config.workspace)
return (
"[Runtime Context]\n"
f"Time: {now}\n"
f"Workspace: {self.config.workspace}\n"
f"Platform: {platform.system()} {platform.machine()}\n"
f"Session ID: {inbound.session_id}\n"
f"Run ID: {inbound.run_id}\n"
f"Message ID: {inbound.message_id}\n"
f"Received At: {inbound.received_at}\n"
"Available Tools:\n"
f"{tool_text}\n\n"
"Workspace Instructions:\n"
f"{instructions}"
)
@staticmethod
def _load_workspace_instructions(workspace: Path) -> str:
for candidate in ("AGENTS.md", "CLAUDE.md", "SYSTEM.md"):
path = workspace / candidate
if path.exists():
return path.read_text(encoding="utf-8").strip()
return "(none)"
+1
View File
@@ -0,0 +1 @@
"""Gateway package."""
+84
View File
@@ -0,0 +1,84 @@
"""CLI gateway."""
from __future__ import annotations
import argparse
from pathlib import Path
from voidbot.agent import AgentRuntime
from voidbot.config import load_config
from voidbot.context import ContextBuilder
from voidbot.gateway.messages import InboundMessageContext
from voidbot.providers import build_provider
from voidbot.session import SessionStore
from voidbot.tools import build_default_tool_registry
def build_parser() -> argparse.ArgumentParser:
"""Build CLI parser."""
parser = argparse.ArgumentParser(prog="voidbot", description="VoidBot CLI gateway")
subparsers = parser.add_subparsers(dest="command", required=True)
chat_parser = subparsers.add_parser(
"chat", help="Run the single-session chat gateway"
)
chat_parser.add_argument("--config", type=Path, help="Path to a JSON config file")
chat_parser.add_argument("--message", "-m", help="Send one message and exit")
return parser
def main() -> None:
"""CLI entrypoint."""
parser = build_parser()
args = parser.parse_args()
if args.command == "chat":
run_chat(config_path=args.config, first_message=args.message)
def run_chat(config_path: Path | None, first_message: str | None) -> None:
"""Run the chat gateway."""
config = load_config(config_path)
provider = build_provider(config)
runtime = AgentRuntime(
config=config,
provider=provider,
session=SessionStore(config.session_file),
tools=build_default_tool_registry(config.workspace),
context_builder=ContextBuilder(config),
)
if first_message:
_run_one_turn(runtime, first_message)
return
print(
f"VoidBot CLI gateway. Provider={config.provider} Model={provider.model_name}"
)
print("Type 'exit' or 'quit' to leave.")
while True:
try:
user_message = input("You> ").strip()
except EOFError:
print()
break
if not user_message:
continue
if user_message.lower() in {"exit", "quit"}:
break
_run_one_turn(runtime, user_message)
def _run_one_turn(runtime: AgentRuntime, user_message: str) -> None:
inbound = InboundMessageContext(
session_id="main",
raw_body=user_message,
body_for_agent=user_message.strip(),
)
result = runtime.run_turn(inbound)
print(
f"[run] session={inbound.session_id} run_id={inbound.run_id} message_id={inbound.message_id}"
)
for event in result.tool_events:
print(f"[tool] {event['tool_name']}({event['arguments']})")
print(event["result"])
print(f"VoidBot> {result.reply}")
+21
View File
@@ -0,0 +1,21 @@
"""Gateway message shapes."""
from __future__ import annotations
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
@dataclass(slots=True)
class InboundMessageContext:
"""Normalized gateway message."""
session_id: str
raw_body: str
body_for_agent: str
run_id: str = field(default_factory=lambda: uuid.uuid4().hex)
message_id: str = field(default_factory=lambda: uuid.uuid4().hex)
received_at: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat()
)
+51
View File
@@ -0,0 +1,51 @@
"""Shared runtime models."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
@dataclass(slots=True)
class ToolCall:
"""Model-emitted tool call."""
id: str
name: str
arguments: dict[str, Any]
def as_openai_payload(self) -> dict[str, Any]:
"""Return OpenAI-style tool call payload for assistant messages."""
import json
return {
"id": self.id,
"type": "function",
"function": {
"name": self.name,
"arguments": json.dumps(self.arguments, ensure_ascii=False),
},
}
@dataclass(slots=True)
class LLMResponse:
"""Normalized LLM output."""
content: str | None = None
tool_calls: list[ToolCall] = field(default_factory=list)
finish_reason: str = "stop"
raw: dict[str, Any] | None = None
@property
def has_tool_calls(self) -> bool:
return bool(self.tool_calls)
@dataclass(slots=True)
class RunTurnResult:
"""One user turn execution result."""
reply: str
iterations: int
tool_events: list[dict[str, Any]] = field(default_factory=list)
+17
View File
@@ -0,0 +1,17 @@
"""Provider helpers."""
from voidbot.config import AppConfig
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
from voidbot.providers.registry import get_provider_spec
def build_provider(config: AppConfig) -> OpenAICompatibleProvider:
"""Build the configured provider."""
spec = get_provider_spec(config.provider)
return OpenAICompatibleProvider(
spec=spec,
api_key=config.api_key,
api_base=config.api_base or spec.default_base_url,
_model_name=config.model or spec.default_model,
timeout=config.request_timeout,
)
+33
View File
@@ -0,0 +1,33 @@
"""Provider abstractions."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from voidbot.models import LLMResponse
@dataclass(frozen=True, slots=True)
class ProviderSpec:
"""Provider preset metadata."""
name: str
label: str
default_base_url: str
default_model: str
class LLMProvider(ABC):
"""Normalized provider interface."""
@abstractmethod
def chat(
self, messages: list[dict], tools: list[dict] | None = None
) -> LLMResponse:
"""Execute one chat completion call."""
@property
@abstractmethod
def model_name(self) -> str:
"""Resolved model identifier."""
+33
View File
@@ -0,0 +1,33 @@
"""Compatibility helpers for OpenAI-compatible providers."""
from __future__ import annotations
from typing import Any
def normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Trim provider-unsafe empty payloads."""
normalized: list[dict[str, Any]] = []
for message in messages:
clean = dict(message)
content = clean.get("content")
if isinstance(content, str) and content == "":
clean["content"] = None if clean.get("role") == "assistant" else "(empty)"
normalized.append(clean)
return normalized
def build_request_payload(
model: str,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None,
) -> dict[str, Any]:
"""Build a chat completions payload with the current compat defaults."""
payload: dict[str, Any] = {
"model": model,
"messages": normalize_messages(messages),
}
if tools:
payload["tools"] = tools
payload["tool_choice"] = "auto"
return payload
+109
View File
@@ -0,0 +1,109 @@
"""OpenAI-compatible chat completions provider."""
from __future__ import annotations
import json
import urllib.error
import urllib.request
import uuid
from dataclasses import dataclass
from typing import Any
from voidbot.models import LLMResponse, ToolCall
from voidbot.providers.base import LLMProvider, ProviderSpec
from voidbot.providers.compat import build_request_payload
@dataclass(slots=True)
class OpenAICompatibleProvider(LLMProvider):
"""Provider for OpenAI-style `/chat/completions` endpoints."""
spec: ProviderSpec
api_key: str
api_base: str
_model_name: str
timeout: int = 120
@property
def model_name(self) -> str:
return self._model_name
def chat(
self, messages: list[dict], tools: list[dict] | None = None
) -> LLMResponse:
payload = build_request_payload(self.model_name, messages, tools)
request = urllib.request.Request(
url=f"{self.api_base.rstrip('/')}/chat/completions",
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
"User-Agent": "VoidBot/0.1.0",
"X-Session-Affinity": uuid.uuid4().hex,
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
raw = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
return LLMResponse(
content=f"HTTP {exc.code}: {body}", finish_reason="error"
)
except urllib.error.URLError as exc:
return LLMResponse(content=f"Network error: {exc}", finish_reason="error")
return self._parse_response(raw)
@staticmethod
def _parse_response(raw: dict[str, Any]) -> LLMResponse:
choices = raw.get("choices") or []
if not choices:
return LLMResponse(
content=f"Malformed response: {raw}", finish_reason="error", raw=raw
)
choice = choices[0]
message = choice.get("message") or {}
tool_calls: list[ToolCall] = []
for tool_call in message.get("tool_calls") or []:
function = tool_call.get("function") or {}
arguments = function.get("arguments") or "{}"
parsed_arguments = OpenAICompatibleProvider._load_arguments(arguments)
tool_calls.append(
ToolCall(
id=str(tool_call.get("id") or uuid.uuid4().hex),
name=str(function.get("name") or ""),
arguments=parsed_arguments,
)
)
content = message.get("content")
if isinstance(content, list):
content = "\n".join(
part.get("text", "")
for part in content
if isinstance(part, dict) and part.get("type") == "text"
).strip()
return LLMResponse(
content=content if isinstance(content, str) else None,
tool_calls=tool_calls,
finish_reason=str(choice.get("finish_reason") or "stop"),
raw=raw,
)
@staticmethod
def _load_arguments(arguments: Any) -> dict[str, Any]:
if isinstance(arguments, dict):
return arguments
if not isinstance(arguments, str) or not arguments.strip():
return {}
try:
parsed = json.loads(arguments)
except json.JSONDecodeError:
return {"raw": arguments}
return parsed if isinstance(parsed, dict) else {"value": parsed}
+38
View File
@@ -0,0 +1,38 @@
"""Provider registry."""
from __future__ import annotations
from voidbot.providers.base import ProviderSpec
PROVIDERS: dict[str, ProviderSpec] = {
"openai_chatgpt": ProviderSpec(
name="openai_chatgpt",
label="OpenAI ChatGPT",
default_base_url="https://api.openai.com/v1",
default_model="gpt-4.1-mini",
),
"zhipu_coding_plan": ProviderSpec(
name="zhipu_coding_plan",
label="Zhipu Coding Plan",
default_base_url="https://open.bigmodel.cn/api/coding/paas/v4",
default_model="glm-4.7",
),
"custom_openai_compatible": ProviderSpec(
name="custom_openai_compatible",
label="Custom OpenAI-Compatible",
default_base_url="http://localhost:8000/v1",
default_model="default",
),
}
def get_provider_spec(name: str) -> ProviderSpec:
"""Return a provider preset by name."""
try:
return PROVIDERS[name]
except KeyError as exc:
available = ", ".join(sorted(PROVIDERS))
raise ValueError(
f"unknown provider '{name}', expected one of: {available}"
) from exc
+67
View File
@@ -0,0 +1,67 @@
"""Single-session transcript storage."""
from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
def _utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
@dataclass(slots=True)
class SessionStore:
"""Append-only JSONL session storage."""
path: Path
def ensure_parent(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
def append(self, message: dict[str, Any]) -> None:
self.ensure_parent()
record = {"timestamp": _utc_now(), **message}
with self.path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
def load_history(self, limit: int = 24) -> list[dict[str, Any]]:
if not self.path.exists():
return []
rows: list[dict[str, Any]] = []
with self.path.open("r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
rows.append(json.loads(line))
trimmed = rows[-limit:]
start_index = 0
for index, row in enumerate(trimmed):
if row.get("role") == "user":
start_index = index
break
aligned = trimmed[start_index:]
messages: list[dict[str, Any]] = []
for row in aligned:
message = self._to_llm_message(row)
if message is not None:
messages.append(message)
return messages
@staticmethod
def _to_llm_message(row: dict[str, Any]) -> dict[str, Any] | None:
role = row.get("role")
if role not in {"user", "assistant", "tool"}:
return None
message: dict[str, Any] = {"role": role, "content": row.get("content")}
if role == "assistant" and row.get("tool_calls"):
message["tool_calls"] = row["tool_calls"]
if role == "tool":
message["tool_call_id"] = row.get("tool_call_id")
message["name"] = row.get("name")
return message
+17
View File
@@ -0,0 +1,17 @@
"""Built-in tools."""
from pathlib import Path
from voidbot.tools.base import ToolRegistry
from voidbot.tools.filesystem import ListDirTool, ReadFileTool, WriteFileTool
from voidbot.tools.shell import RunCommandTool
def build_default_tool_registry(workspace: Path) -> ToolRegistry:
"""Create the default tool registry."""
registry = ToolRegistry()
registry.register(ListDirTool(workspace))
registry.register(ReadFileTool(workspace))
registry.register(WriteFileTool(workspace))
registry.register(RunCommandTool(workspace))
return registry
+68
View File
@@ -0,0 +1,68 @@
"""Tool abstractions and registry."""
from __future__ import annotations
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any
class Tool(ABC):
"""Base tool definition."""
name: str
description: str
parameters: dict[str, Any]
@abstractmethod
def execute(self, arguments: dict[str, Any]) -> str:
"""Execute a tool call."""
def schema(self) -> dict[str, Any]:
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
},
}
@dataclass(slots=True)
class ToolRegistry:
"""Dynamic tool registry."""
_tools: dict[str, Tool] = field(default_factory=dict)
def register(self, tool: Tool) -> None:
self._tools[tool.name] = tool
def schemas(self) -> list[dict[str, Any]]:
return [tool.schema() for tool in self._tools.values()]
def summaries(self) -> list[str]:
return [f"{tool.name}: {tool.description}" for tool in self._tools.values()]
def execute(self, name: str, arguments: dict[str, Any]) -> str:
tool = self._tools.get(name)
if tool is None:
return f"Tool '{name}' is not registered."
try:
return tool.execute(arguments)
except Exception as exc:
return f"Tool '{name}' failed: {exc}"
@staticmethod
def stringify_result(name: str, arguments: dict[str, Any], result: str) -> str:
preview = result if len(result) <= 4000 else result[:4000] + "\n...[truncated]"
return json.dumps(
{
"tool": name,
"arguments": arguments,
"result": preview,
},
ensure_ascii=False,
indent=2,
)
+92
View File
@@ -0,0 +1,92 @@
"""Filesystem tools."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from voidbot.tools.base import Tool
class ListDirTool(Tool):
name = "list_dir"
description = "List files and directories under a relative path."
parameters = {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Relative path inside the workspace.",
},
},
}
def __init__(self, workspace: Path):
self.workspace = workspace
def execute(self, arguments: dict[str, Any]) -> str:
target = _resolve_workspace_path(
self.workspace, str(arguments.get("path") or ".")
)
if not target.exists():
return f"{target} does not exist."
rows = []
for child in sorted(target.iterdir(), key=lambda item: item.name):
suffix = "/" if child.is_dir() else ""
rows.append(f"{child.relative_to(self.workspace)}{suffix}")
return "\n".join(rows) or "(empty directory)"
class ReadFileTool(Tool):
name = "read_file"
description = "Read a UTF-8 text file inside the workspace."
parameters = {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Relative path inside the workspace.",
},
},
"required": ["path"],
}
def __init__(self, workspace: Path):
self.workspace = workspace
def execute(self, arguments: dict[str, Any]) -> str:
target = _resolve_workspace_path(self.workspace, str(arguments["path"]))
return target.read_text(encoding="utf-8")
class WriteFileTool(Tool):
name = "write_file"
description = "Write a UTF-8 text file inside the workspace."
parameters = {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Relative path inside the workspace.",
},
"content": {"type": "string", "description": "Text content to write."},
},
"required": ["path", "content"],
}
def __init__(self, workspace: Path):
self.workspace = workspace
def execute(self, arguments: dict[str, Any]) -> str:
target = _resolve_workspace_path(self.workspace, str(arguments["path"]))
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(str(arguments["content"]), encoding="utf-8")
return f"wrote {target.relative_to(self.workspace)}"
def _resolve_workspace_path(workspace: Path, raw_path: str) -> Path:
candidate = (workspace / raw_path).resolve()
workspace_root = workspace.resolve()
if workspace_root not in candidate.parents and candidate != workspace_root:
raise ValueError("path escapes the workspace")
return candidate
+51
View File
@@ -0,0 +1,51 @@
"""Shell execution tool."""
from __future__ import annotations
import subprocess
from pathlib import Path
from typing import Any
from voidbot.tools.base import Tool
class RunCommandTool(Tool):
name = "run_command"
description = (
"Run a shell command inside the workspace and capture stdout and stderr."
)
parameters = {
"type": "object",
"properties": {
"command": {"type": "string", "description": "Shell command to execute."},
"timeout": {
"type": "integer",
"description": "Timeout in seconds.",
"minimum": 1,
"maximum": 600,
},
},
"required": ["command"],
}
def __init__(self, workspace: Path):
self.workspace = workspace
def execute(self, arguments: dict[str, Any]) -> str:
timeout = int(arguments.get("timeout") or 120)
completed = subprocess.run(
arguments["command"],
cwd=self.workspace,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
stdout = completed.stdout.strip()
stderr = completed.stderr.strip()
return (
f"exit_code: {completed.returncode}\n"
f"stdout:\n{stdout or '(empty)'}\n"
f"stderr:\n{stderr or '(empty)'}"
)
+66
View File
@@ -0,0 +1,66 @@
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from voidbot.agent import AgentRuntime
from voidbot.config import AppConfig
from voidbot.context import ContextBuilder
from voidbot.gateway.messages import InboundMessageContext
from voidbot.models import LLMResponse, ToolCall
from voidbot.session import SessionStore
from voidbot.tools import build_default_tool_registry
class FakeProvider:
def __init__(self) -> None:
self.calls = 0
self.model_name = "fake-model"
def chat(self, messages: list[dict], tools: list[dict] | None = None) -> LLMResponse:
self.calls += 1
if self.calls == 1:
return LLMResponse(
content="I should inspect the workspace first.",
tool_calls=[ToolCall(id="tool-1", name="list_dir", arguments={"path": "."})],
)
return LLMResponse(content="I checked the workspace and finished.")
class AgentRuntimeTests(unittest.TestCase):
def test_run_turn_executes_tool_loop(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
(workspace / "hello.txt").write_text("hello", encoding="utf-8")
config = AppConfig(
api_key="test-key",
workspace=workspace,
session_file=workspace / ".voidbot/session.jsonl",
max_iterations=4,
)
runtime = AgentRuntime(
config=config,
provider=FakeProvider(),
session=SessionStore(config.session_file),
tools=build_default_tool_registry(workspace),
context_builder=ContextBuilder(config),
)
inbound = InboundMessageContext(
session_id="main",
raw_body="Inspect the repo",
body_for_agent="Inspect the repo",
)
result = runtime.run_turn(inbound)
self.assertEqual(result.reply, "I checked the workspace and finished.")
self.assertEqual(len(result.tool_events), 1)
self.assertEqual(result.tool_events[0]["tool_name"], "list_dir")
history = runtime.session.load_history(limit=10)
self.assertEqual(history[0]["role"], "user")
self.assertEqual(history[-1]["role"], "assistant")
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -0,0 +1,16 @@
from __future__ import annotations
import unittest
from voidbot.providers.registry import get_provider_spec
class ProviderRegistryTests(unittest.TestCase):
def test_zhipu_coding_plan_preset_exists(self) -> None:
spec = get_provider_spec("zhipu_coding_plan")
self.assertEqual(spec.default_base_url, "https://open.bigmodel.cn/api/coding/paas/v4")
self.assertEqual(spec.default_model, "glm-4.7")
if __name__ == "__main__":
unittest.main()
Generated
+43
View File
@@ -0,0 +1,43 @@
version = 1
revision = 3
requires-python = ">=3.11"
[[package]]
name = "ruff"
version = "0.15.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/51/df/f8629c19c5318601d3121e230f74cbee7a3732339c52b21daa2b82ef9c7d/ruff-0.15.6.tar.gz", hash = "sha256:8394c7bb153a4e3811a4ecdacd4a8e6a4fa8097028119160dffecdcdf9b56ae4", size = 4597916, upload-time = "2026-03-12T23:05:47.51Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/9e/2f/4e03a7e5ce99b517e98d3b4951f411de2b0fa8348d39cf446671adcce9a2/ruff-0.15.6-py3-none-linux_armv6l.whl", hash = "sha256:7c98c3b16407b2cf3d0f2b80c80187384bc92c6774d85fefa913ecd941256fff", size = 10508953, upload-time = "2026-03-12T23:05:17.246Z" },
{ url = "https://files.pythonhosted.org/packages/70/60/55bcdc3e9f80bcf39edf0cd272da6fa511a3d94d5a0dd9e0adf76ceebdb4/ruff-0.15.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:ee7dcfaad8b282a284df4aa6ddc2741b3f4a18b0555d626805555a820ea181c3", size = 10942257, upload-time = "2026-03-12T23:05:23.076Z" },
{ url = "https://files.pythonhosted.org/packages/e7/f9/005c29bd1726c0f492bfa215e95154cf480574140cb5f867c797c18c790b/ruff-0.15.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:3bd9967851a25f038fc8b9ae88a7fbd1b609f30349231dffaa37b6804923c4bb", size = 10322683, upload-time = "2026-03-12T23:05:33.738Z" },
{ url = "https://files.pythonhosted.org/packages/5f/74/2f861f5fd7cbb2146bddb5501450300ce41562da36d21868c69b7a828169/ruff-0.15.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:13f4594b04e42cd24a41da653886b04d2ff87adbf57497ed4f728b0e8a4866f8", size = 10660986, upload-time = "2026-03-12T23:05:53.245Z" },
{ url = "https://files.pythonhosted.org/packages/c1/a1/309f2364a424eccb763cdafc49df843c282609f47fe53aa83f38272389e0/ruff-0.15.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e2ed8aea2f3fe57886d3f00ea5b8aae5bf68d5e195f487f037a955ff9fbaac9e", size = 10332177, upload-time = "2026-03-12T23:05:56.145Z" },
{ url = "https://files.pythonhosted.org/packages/30/41/7ebf1d32658b4bab20f8ac80972fb19cd4e2c6b78552be263a680edc55ac/ruff-0.15.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:70789d3e7830b848b548aae96766431c0dc01a6c78c13381f423bf7076c66d15", size = 11170783, upload-time = "2026-03-12T23:06:01.742Z" },
{ url = "https://files.pythonhosted.org/packages/76/be/6d488f6adca047df82cd62c304638bcb00821c36bd4881cfca221561fdfc/ruff-0.15.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:542aaf1de3154cea088ced5a819ce872611256ffe2498e750bbae5247a8114e9", size = 12044201, upload-time = "2026-03-12T23:05:28.697Z" },
{ url = "https://files.pythonhosted.org/packages/71/68/e6f125df4af7e6d0b498f8d373274794bc5156b324e8ab4bf5c1b4fc0ec7/ruff-0.15.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1c22e6f02c16cfac3888aa636e9eba857254d15bbacc9906c9689fdecb1953ab", size = 11421561, upload-time = "2026-03-12T23:05:31.236Z" },
{ url = "https://files.pythonhosted.org/packages/f1/9f/f85ef5fd01a52e0b472b26dc1b4bd228b8f6f0435975442ffa4741278703/ruff-0.15.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:98893c4c0aadc8e448cfa315bd0cc343a5323d740fe5f28ef8a3f9e21b381f7e", size = 11310928, upload-time = "2026-03-12T23:05:45.288Z" },
{ url = "https://files.pythonhosted.org/packages/8c/26/b75f8c421f5654304b89471ed384ae8c7f42b4dff58fa6ce1626d7f2b59a/ruff-0.15.6-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:70d263770d234912374493e8cc1e7385c5d49376e41dfa51c5c3453169dc581c", size = 11235186, upload-time = "2026-03-12T23:05:50.677Z" },
{ url = "https://files.pythonhosted.org/packages/fc/d4/d5a6d065962ff7a68a86c9b4f5500f7d101a0792078de636526c0edd40da/ruff-0.15.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:55a1ad63c5a6e54b1f21b7514dfadc0c7fb40093fa22e95143cf3f64ebdcd512", size = 10635231, upload-time = "2026-03-12T23:05:37.044Z" },
{ url = "https://files.pythonhosted.org/packages/d6/56/7c3acf3d50910375349016cf33de24be021532042afbed87942858992491/ruff-0.15.6-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:8dc473ba093c5ec238bb1e7429ee676dca24643c471e11fbaa8a857925b061c0", size = 10340357, upload-time = "2026-03-12T23:06:04.748Z" },
{ url = "https://files.pythonhosted.org/packages/06/54/6faa39e9c1033ff6a3b6e76b5df536931cd30caf64988e112bbf91ef5ce5/ruff-0.15.6-py3-none-musllinux_1_2_i686.whl", hash = "sha256:85b042377c2a5561131767974617006f99f7e13c63c111b998f29fc1e58a4cfb", size = 10860583, upload-time = "2026-03-12T23:05:58.978Z" },
{ url = "https://files.pythonhosted.org/packages/cb/1e/509a201b843b4dfb0b32acdedf68d951d3377988cae43949ba4c4133a96a/ruff-0.15.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:cef49e30bc5a86a6a92098a7fbf6e467a234d90b63305d6f3ec01225a9d092e0", size = 11410976, upload-time = "2026-03-12T23:05:39.955Z" },
{ url = "https://files.pythonhosted.org/packages/6c/25/3fc9114abf979a41673ce877c08016f8e660ad6cf508c3957f537d2e9fa9/ruff-0.15.6-py3-none-win32.whl", hash = "sha256:bbf67d39832404812a2d23020dda68fee7f18ce15654e96fb1d3ad21a5fe436c", size = 10616872, upload-time = "2026-03-12T23:05:42.451Z" },
{ url = "https://files.pythonhosted.org/packages/89/7a/09ece68445ceac348df06e08bf75db72d0e8427765b96c9c0ffabc1be1d9/ruff-0.15.6-py3-none-win_amd64.whl", hash = "sha256:aee25bc84c2f1007ecb5037dff75cef00414fdf17c23f07dc13e577883dca406", size = 11787271, upload-time = "2026-03-12T23:05:20.168Z" },
{ url = "https://files.pythonhosted.org/packages/7f/d0/578c47dd68152ddddddf31cd7fc67dc30b7cdf639a86275fda821b0d9d98/ruff-0.15.6-py3-none-win_arm64.whl", hash = "sha256:c34de3dd0b0ba203be50ae70f5910b17188556630e2178fd7d79fc030eb0d837", size = 11060497, upload-time = "2026-03-12T23:05:25.968Z" },
]
[[package]]
name = "voidbot"
version = "0.1.0"
source = { editable = "." }
[package.dev-dependencies]
dev = [
{ name = "ruff" },
]
[package.metadata]
[package.metadata.requires-dev]
dev = [{ name = "ruff", specifier = ">=0.15.6" }]