zcbot/tools/rename_working_dir.py

66 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""对话内重命名当前 task 工作目录登记意图run 收尾后执行。"""
from __future__ import annotations
from pathlib import Path
from core.task_actions import DeferredTaskActions
from .base import Tool
class RenameWorkingDirTool(Tool):
name = "rename_working_dir"
description = (
"Rename the current task's top-level working directory. "
"The rename is safely deferred until the current response finishes, so all tasks "
"sharing this directory keep their association. Use this instead of shell mv/rename "
"for the current working directory."
)
parameters = {
"type": "object",
"properties": {
"new_name": {
"type": "string",
"description": "新的目录 leaf 名,不是路径;不能含 / 或 \\,不能以 . 开头。",
},
},
"required": ["new_name"],
}
def __init__(
self,
actions: DeferredTaskActions,
working_dir: Path,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.actions = actions
self.working_dir = Path(working_dir)
def execute(self, new_name: str) -> str:
# 延迟 import避免 agent_builder -> tool_registry -> 本工具 -> agent_builder
# 的模块初始化环;名称规则仍只有 validate_task_name 一个事实源。
from core.agent_builder import InvalidTaskName, validate_task_name
try:
safe = validate_task_name(new_name)
except InvalidTaskName as e:
return f"[Error] new_name 不合法: {e}"
if safe == self.working_dir.name:
return f"[Error] new_name 与当前工作目录名相同: {safe!r}"
target = self.working_dir.parent / safe
if target.exists():
return f"[Error] 目标目录已存在: {safe!r}"
replaced = self.actions.rename_working_dir_to
self.actions.rename_working_dir_to = safe
if replaced and replaced != safe:
return (
f"[OK] 已把本轮待执行的工作目录改名从 {replaced!r} 更新为 {safe!r}"
"将在本轮回复完成后安全执行。"
)
return (
f"[OK] 已登记工作目录改名为 {safe!r},将在本轮回复完成后安全执行;"
"所有共享该目录的 task 关联会同步更新。"
)