Merge remote-tracking branch 'origin/main' into nanobot-webui
This commit is contained in:
+72
-33
@@ -5,41 +5,71 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.schema import BooleanSchema, IntegerSchema, StringSchema, tool_parameters_schema
|
||||
from nanobot.agent.tools.schema import (
|
||||
BooleanSchema,
|
||||
IntegerSchema,
|
||||
StringSchema,
|
||||
tool_parameters_schema,
|
||||
)
|
||||
from nanobot.cron.service import CronService
|
||||
from nanobot.cron.types import CronJob, CronJobState, CronSchedule
|
||||
|
||||
|
||||
@tool_parameters(
|
||||
tool_parameters_schema(
|
||||
action=StringSchema("Action to perform", enum=["add", "list", "remove"]),
|
||||
name=StringSchema(
|
||||
"Optional short human-readable label for the job "
|
||||
"(e.g., 'weather-monitor', 'daily-standup'). Defaults to first 30 chars of message."
|
||||
),
|
||||
message=StringSchema(
|
||||
"REQUIRED when action='add'. Instruction for the agent to execute when the job triggers "
|
||||
"(e.g., 'Send a reminder to WeChat: xxx' or 'Check system status and report'). "
|
||||
"Not used for action='list' or action='remove'."
|
||||
),
|
||||
every_seconds=IntegerSchema(0, description="Interval in seconds (for recurring tasks)"),
|
||||
cron_expr=StringSchema("Cron expression like '0 9 * * *' (for scheduled tasks)"),
|
||||
tz=StringSchema(
|
||||
"Optional IANA timezone for cron expressions (e.g. 'America/Vancouver'). "
|
||||
"When omitted with cron_expr, the tool's default timezone applies."
|
||||
),
|
||||
at=StringSchema(
|
||||
"ISO datetime for one-time execution (e.g. '2026-02-12T10:30:00'). "
|
||||
"Naive values use the tool's default timezone."
|
||||
),
|
||||
deliver=BooleanSchema(
|
||||
description="Whether to deliver the execution result to the user channel (default true)",
|
||||
default=True,
|
||||
),
|
||||
job_id=StringSchema("REQUIRED when action='remove'. Job ID to remove (obtain via action='list')."),
|
||||
required=["action"],
|
||||
)
|
||||
_CRON_PARAMETERS = tool_parameters_schema(
|
||||
action=StringSchema("Action to perform", enum=["add", "list", "remove"]),
|
||||
name=StringSchema(
|
||||
"Optional short human-readable label for the job "
|
||||
"(e.g., 'weather-monitor', 'daily-standup'). Defaults to first 30 chars of message."
|
||||
),
|
||||
message=StringSchema(
|
||||
"REQUIRED when action='add'. Instruction for the agent to execute when the job triggers "
|
||||
"(e.g., 'Send a reminder to WeChat: xxx' or 'Check system status and report'). "
|
||||
"Not used for action='list' or action='remove'."
|
||||
),
|
||||
every_seconds=IntegerSchema(0, description="Interval in seconds (for recurring tasks)"),
|
||||
cron_expr=StringSchema("Cron expression like '0 9 * * *' (for scheduled tasks)"),
|
||||
tz=StringSchema(
|
||||
"Optional IANA timezone for cron expressions (e.g. 'America/Vancouver'). "
|
||||
"When omitted with cron_expr, the tool's default timezone applies."
|
||||
),
|
||||
at=StringSchema(
|
||||
"ISO datetime for one-time execution (e.g. '2026-02-12T10:30:00'). "
|
||||
"Naive values use the tool's default timezone."
|
||||
),
|
||||
deliver=BooleanSchema(
|
||||
description="Whether to deliver the execution result to the user channel (default true)",
|
||||
default=True,
|
||||
),
|
||||
job_id=StringSchema("REQUIRED when action='remove'. Job ID to remove (obtain via action='list')."),
|
||||
required=["action"],
|
||||
description=(
|
||||
"Action-specific parameters: add requires a non-empty message plus one schedule "
|
||||
"(every_seconds, cron_expr, or at); remove requires job_id; list only needs action."
|
||||
),
|
||||
)
|
||||
_CRON_PARAMETERS["oneOf"] = [
|
||||
{
|
||||
"properties": {
|
||||
"action": {"enum": ["add"]},
|
||||
"message": {"type": "string", "minLength": 1},
|
||||
},
|
||||
"required": ["action", "message"],
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"action": {"enum": ["list"]},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"action": {"enum": ["remove"]},
|
||||
},
|
||||
"required": ["action", "job_id"],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@tool_parameters(_CRON_PARAMETERS)
|
||||
class CronTool(Tool):
|
||||
"""Tool to schedule reminders and recurring tasks."""
|
||||
|
||||
@@ -95,6 +125,15 @@ class CronTool(Tool):
|
||||
f"If tz is omitted, cron expressions and naive ISO times default to {self._default_timezone}."
|
||||
)
|
||||
|
||||
def validate_params(self, params: dict[str, Any]) -> list[str]:
|
||||
errors = super().validate_params(params)
|
||||
action = params.get("action")
|
||||
if action == "add" and not str(params.get("message") or "").strip():
|
||||
errors.append("message is required when action='add'")
|
||||
if action == "remove" and not str(params.get("job_id") or "").strip():
|
||||
errors.append("job_id is required when action='remove'")
|
||||
return errors
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
action: str,
|
||||
@@ -130,8 +169,8 @@ class CronTool(Tool):
|
||||
) -> str:
|
||||
if not message:
|
||||
return (
|
||||
"Error: cron action='add' requires a non-empty 'message' "
|
||||
"parameter describing what to do when the job triggers "
|
||||
"Error: cron action='add' requires a non-empty 'message' parameter "
|
||||
"describing what to do when the job triggers "
|
||||
"(e.g. the reminder text). Retry including message=\"...\"."
|
||||
)
|
||||
if not self._channel or not self._chat_id:
|
||||
|
||||
+11
-1
@@ -18,7 +18,17 @@ from nanobot import __logo__
|
||||
|
||||
|
||||
def _make_console() -> Console:
|
||||
return Console(file=sys.stdout, force_terminal=True)
|
||||
"""Create a Console that emits plain text when stdout is not a TTY.
|
||||
|
||||
Rich's spinner, Live render, and cursor-visibility escape codes all
|
||||
key off ``Console.is_terminal``. Forcing ``force_terminal=True`` overrode
|
||||
the ``isatty()`` check and caused control sequences (``\\x1b[?25l``,
|
||||
braille spinner frames) to pollute programmatic consumers such as
|
||||
``docker exec -i`` or pipes, even with ``NO_COLOR`` or ``TERM=dumb``.
|
||||
Deferring to ``isatty()`` keeps Rich output in interactive terminals
|
||||
and plain text everywhere else (#3265).
|
||||
"""
|
||||
return Console(file=sys.stdout, force_terminal=sys.stdout.isatty())
|
||||
|
||||
|
||||
class ThinkingSpinner:
|
||||
|
||||
@@ -319,17 +319,15 @@ class Config(BaseSettings):
|
||||
return p.api_key if p else None
|
||||
|
||||
def get_api_base(self, model: str | None = None) -> str | None:
|
||||
"""Get API base URL for the given model. Applies default URLs for gateway/local providers."""
|
||||
"""Get API base URL for the given model, falling back to the provider default when present."""
|
||||
from nanobot.providers.registry import find_by_name
|
||||
|
||||
p, name = self._match_provider(model)
|
||||
if p and p.api_base:
|
||||
return p.api_base
|
||||
# Only gateways get a default api_base here. Standard providers
|
||||
# resolve their base URL from the registry in the provider constructor.
|
||||
if name:
|
||||
spec = find_by_name(name)
|
||||
if spec and (spec.is_gateway or spec.is_local) and spec.default_api_base:
|
||||
if spec and spec.default_api_base:
|
||||
return spec.default_api_base
|
||||
return None
|
||||
|
||||
|
||||
@@ -64,14 +64,35 @@ class GitStore:
|
||||
if self.is_initialized():
|
||||
return False
|
||||
|
||||
if self._is_inside_git_repo():
|
||||
logger.warning(
|
||||
"Workspace {} is already inside a git repo; "
|
||||
"skipping nested repo initialization",
|
||||
self._workspace,
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
from dulwich import porcelain
|
||||
|
||||
porcelain.init(str(self._workspace))
|
||||
|
||||
# Write .gitignore
|
||||
# Write .gitignore (merge with existing if present)
|
||||
gitignore = self._workspace / ".gitignore"
|
||||
gitignore.write_text(self._build_gitignore(), encoding="utf-8")
|
||||
dream_entries = self._build_gitignore()
|
||||
if gitignore.exists():
|
||||
existing = gitignore.read_text(encoding="utf-8")
|
||||
existing_lines = set(existing.splitlines())
|
||||
new_lines = [
|
||||
line
|
||||
for line in dream_entries.splitlines()
|
||||
if line not in existing_lines
|
||||
]
|
||||
if new_lines:
|
||||
merged = existing.rstrip("\n") + "\n" + "\n".join(new_lines) + "\n"
|
||||
gitignore.write_text(merged, encoding="utf-8")
|
||||
else:
|
||||
gitignore.write_text(dream_entries, encoding="utf-8")
|
||||
|
||||
# Ensure tracked files exist (touch them if missing) so the initial
|
||||
# commit has something to track.
|
||||
@@ -155,6 +176,22 @@ class GitStore:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _is_inside_git_repo(self) -> bool:
|
||||
"""Check if self._workspace is already inside a git repository.
|
||||
|
||||
Walks up from self._workspace to the filesystem root, returning True
|
||||
if any parent directory contains a .git entry.
|
||||
|
||||
Git worktrees and submodules can use a ``.git`` file instead of a
|
||||
directory, so we must treat either form as "already inside a repo".
|
||||
"""
|
||||
current = self._workspace.resolve()
|
||||
while current != current.parent:
|
||||
if (current / ".git").exists():
|
||||
return True
|
||||
current = current.parent
|
||||
return False
|
||||
|
||||
def _build_gitignore(self) -> str:
|
||||
"""Generate .gitignore content from tracked files."""
|
||||
dirs: set[str] = set()
|
||||
|
||||
Reference in New Issue
Block a user