builtin

package
v0.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2026 License: None detected not legal advice Imports: 0 Imported by: 0

Documentation

Overview

Package builtin - bash_secret_ctx.go 定义 Bash 工具子进程 secret env 注入的 context key.

为什么用 context 而不是 BashTool 字段?

BashTool 是引擎级别的单例(tools.Registry 持有一个实例,所有请求共用). 若将 per-request secret envs 写入 BashTool 字段:

  • 并发请求 A 和 B 会互相覆盖字段值(data race)
  • 即使加锁,B 在 A 执行工具前改写了字段,A 会注入 B 的 secret

context.Context 天然是 per-request 的,且 Execute 函数签名已携带 ctx-- 无需修改任何调用链,注入点精准,隔离性完美.

升华改进(ELEVATED): 和早期实现 的 GHA_SUBPROCESS_SCRUB 黑名单对比, 我们反向设计: 用户通过 engine.SetSecret / WithSecret 主动注册 secret → context 携带 → 子进程环境追加注入. 秘密管理的唯一正确路径是 SecretStore, 引擎不做 env 黑名单 过滤 (2026-04-15 L513 审计决策, 详见 bash.go ExecuteBash 设计注释). 替代方案:<BashTool 字段 + sync.Map per-goroutineID> - 否决:goroutineID 在 Go 中不是一等公民,实现脆弱且不可移植.

Index

Constants

View Source
const (
	MaxStdoutBytes = 200 * 1024 // 200KB stdout
	MaxStderrBytes = 56 * 1024  // 56KB stderr
	MaxTotalBytes  = 256 * 1024 // 256KB 总计
)

输出截断限制常量

View Source
const AssistantBlockingBudgetMs = 15_000

AssistantBlockingBudgetMs 是主 agent 前台命令的自动后台化阈值(15 秒).

升华改进(ELEVATED): 早期实现 BashTool.tsx 中同名常量(ASSISTANT_BLOCKING_BUDGET_MS = 15_000), 仅在 feature('KAIROS') && getKairosActive() 双重门控下生效(Ant 内部 feature flag). 我们将其作为标准功能开放,通过 BashTool.isMainAgent 字段控制-- 主 agent 流中阻塞 > 15s 的命令自动转后台,保持对话响应; subagent 不自动转后台(subagent 通常专注于单一任务,没有"响应性"需求).

Variables

This section is empty.

Functions

func ApplySedSubstitution

func ApplySedSubstitution(content string, info *SedEditInfo) string

ApplySedSubstitution 将 sed 原地替换应用到文件内容,返回替换后的内容. 如果模式无效或其他错误,返回原始内容(保守策略,不影响 UI 使用).

升华改进(ELEVATED): 使用随机 8 字节 salt 生成唯一占位符, 防止 sed 替换字符串本身包含占位符时产生错误的转换结果. 早期实现 同样使用 randomBytes(8),我们用 crypto/rand 实现相同保护.

替换字符串转换规则(sed → Go regexp):

  • `\&` (转义 &,字面量 &) → `&`(Go 中 & 不特殊,直接保留)
  • `&` (全匹配引用) → `${0}`(Go regexp 全匹配语法)
  • `\1`–`\9` (捕获组引用) → `$1`–`$9`
  • `\n` → 实际换行符
  • `\t` → 实际制表符
  • `\/` → `/`(取消分隔符转义)
  • `\\` → `\`(字面量反斜杠)
  • `$` (字面量,sed 中不特殊) → `$$`(Go regexp 中需转义)

func ContextWithSecretEnvs

func ContextWithSecretEnvs(ctx context.Context, envs []string) context.Context

ContextWithSecretEnvs 将 secret env var 列表注入 context.

envs 的格式应为 ["NAME=VALUE", ...],与 os.Environ() 一致. 引擎在调用工具前调用此函数,为该次工具执行创建带 secret 的 context.

调用方(engine.runLoop)负责提供 envs,Bash 工具只负责读取, 职责分离:secret 管理在引擎层,env 组装在工具层.

func IsIgnored

func IsIgnored(relPath string, patterns []IgnorePattern, isDir bool) bool

IsIgnored 判断给定的相对路径是否应被忽略. relPath 是相对于项目根目录的路径(使用 / 分隔). isDir 表示该路径是否为目录.

func IsSearchOrRead

func IsSearchOrRead(cmd string) (isSearch bool, isRead bool, isList bool)

IsSearchOrRead 判断命令是否为搜索,读取或列表类.

func IsSedInPlaceEdit

func IsSedInPlaceEdit(command string) bool

IsSedInPlaceEdit 快速判断命令是否为 sed 原地编辑命令. 只有 `sed -i 's/.../.../' file` 形式才返回 true.

func NewAddSharedTaskTool

func NewAddSharedTaskTool() tools.Tool

NewAddSharedTaskTool 创建 add_shared_task 工具.

func NewClaimSharedTaskTool

func NewClaimSharedTaskTool() tools.Tool

NewClaimSharedTaskTool 创建 claim_shared_task 工具.

func NewCompleteSharedTaskTool

func NewCompleteSharedTaskTool() tools.Tool

NewCompleteSharedTaskTool 创建 complete_shared_task 工具.

func NewListSharedTasksTool

func NewListSharedTasksTool() tools.Tool

NewListSharedTasksTool 创建 list_shared_tasks 工具.

func NewSendMessageTool

func NewSendMessageTool() tools.Tool

NewSendMessageTool 构造 send_message 工具实例. 工具本身无状态, sender 通过 context 注入, 因此全局单例安全.

func SecretEnvsFromCtx

func SecretEnvsFromCtx(ctx context.Context) []string

SecretEnvsFromCtx 从 context 中读取 secret env var 列表. 若 context 中没有 secret(未调用 ContextWithSecretEnvs),返回 nil. 返回 nil 时调用方不应 append 到 cmd.Env(append(nil, nil...) 是安全的,但多余).

func WithTaskListProvider

func WithTaskListProvider(ctx context.Context, provider TaskListProvider) context.Context

WithTaskListProvider 在 ctx 中注入 TaskListProvider. 由 engine.Team 在 runWorker / ContextForLeader 中调用.

func WithTeammateMessageSender

func WithTeammateMessageSender(ctx context.Context, sender TeammateMessageSender) context.Context

WithTeammateMessageSender 返回携带 sender 的派生 context. 由 engine.Team.runWorker 调用, 给每个 Worker 的 ctx 绑定自己的 sender 身份.

Types

type AgentExecutor

type AgentExecutor interface {
	// RunSubAgent 同步运行一个子 Agent,等待完成后返回结果文本.
	RunSubAgent(ctx context.Context, req AgentRunRequest, availableTools []tools.Tool) (string, error)

	// RunSubAgentBackground 在后台运行一个子 Agent,立即返回任务 ID.
	// 调用者可以通过任务 ID 查询进度和结果.
	RunSubAgentBackground(req AgentRunRequest, availableTools []tools.Tool) (string, error)

	// RunSubAgentWorktree 在独立的 git worktree 中运行子 Agent.
	// req.BranchName 为空时自动生成.同步等待完成.
	RunSubAgentWorktree(ctx context.Context, req AgentRunRequest, availableTools []tools.Tool) (string, error)
}

AgentExecutor 是子 Agent 执行器接口. Engine 层实现此接口,注入到 AgentTool 中,避免循环依赖. 精妙之处(CLEVER): 通过 AgentExecutor 接口实现反向依赖注入-- builtin 包定义接口,engine 包实现接口.避免了 builtin → engine 的循环引用. AgentTool 创建时不需要 engine 实例,后续通过 SetExecutor 注入. 这是 Go 中解决循环依赖的经典模式(依赖倒置原则).

type AgentRunRequest

type AgentRunRequest struct {
	// Prompt 发送给子 Agent 的任务提示
	Prompt string
	// Description 任务描述(用于追踪和展示)
	Description string
	// Model 指定模型("" = 继承父代理模型)
	Model string
	// AgentType 指定 Agent 类型("" = general-purpose)
	// 类型决定了工具集和运行行为
	AgentType string
	// BranchName worktree 模式的分支名(为空则自动生成)
	BranchName string
}

AgentRunRequest 是子 Agent 执行请求的统一入参结构体.

升华改进(ELEVATED): 替代早期方案散列参数(prompt, model, description, branchName...), 统一为结构体后新增字段无需修改接口签名--符合开闭原则. 跨行业扩展:可追加 Priority,Deadline,Labels 等字段而不破坏现有实现. 替代方案:散列参数(每次新增字段都需要修改接口+所有实现,破坏性变更).

type AgentTool

type AgentTool struct {
	// contains filtered or unexported fields
}

AgentTool 是 Agent 子进程工具.

func NewAgentTool

func NewAgentTool(registry *tools.Registry) *AgentTool

NewAgentTool 创建一个 Agent 工具实例. registry 用于获取可用工具列表,子 Agent 将使用去除 Agent 工具后的工具子集.

func (*AgentTool) Description

func (t *AgentTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*AgentTool) Execute

func (t *AgentTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 创建并运行子 Agent.

func (*AgentTool) InputSchema

func (t *AgentTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*AgentTool) Metadata

func (t *AgentTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*AgentTool) Name

func (t *AgentTool) Name() string

Name 返回工具名称.

func (*AgentTool) SetExecutor

func (t *AgentTool) SetExecutor(executor AgentExecutor)

SetExecutor 设置子 Agent 执行器. 由 Engine 层在初始化后调用,注入真正的执行逻辑.

type BackgroundBashTask

type BackgroundBashTask struct {
	ID        string      `json:"id"`
	Command   string      `json:"command"`
	Pid       int         `json:"pid"`
	StartTime time.Time   `json:"start_time"`
	Output    *BashOutput `json:"-"`

	Status   string    `json:"status"` // "running" / "completed" / "failed" / "killed"
	EndTime  time.Time `json:"end_time,omitempty"`
	ExitCode int       `json:"exit_code"`
	// contains filtered or unexported fields
}

BackgroundBashTask 表示一个后台执行的 Bash 任务.

精妙之处(CLEVER): mu 保护 Status/ExitCode/EndTime 三个可变字段-- ID/Command/Pid/StartTime 在创建后只写一次,不需要锁保护. Output 有自己的 BashOutput.mu.cancel 通过 context 语义保护(多次调用安全). 只给"竞态字段"加锁,避免过度同步带来的死锁风险.

func (*BackgroundBashTask) GetStatus

func (t *BackgroundBashTask) GetStatus() string

GetStatus 线程安全地返回任务当前状态.

type BackgroundStoreOption

type BackgroundStoreOption func(*BackgroundTaskStore)

BackgroundStoreOption 是 NewBackgroundTaskStore 的可选配置.

升华改进(ELEVATED): functional options 而非 NewBackgroundTaskStoreWithRetention(d) 这种命名变体--后续若加更多配置(如 maxTasks,自定义时钟),option 模式可平滑扩展, 不会污染 New() 签名.

func WithRetention

func WithRetention(d time.Duration) BackgroundStoreOption

WithRetention 覆盖默认的已完成任务保留时长.

主要用途:单元测试设置很短的保留期(如 50ms)以快速验证 GC 行为, 避免在测试中等待 10 分钟.生产代码通常使用默认值.

type BackgroundTaskStore

type BackgroundTaskStore struct {
	// contains filtered or unexported fields
}

BackgroundTaskStore 存储后台 Bash 任务,线程安全.

func NewBackgroundTaskStore

func NewBackgroundTaskStore(opts ...BackgroundStoreOption) *BackgroundTaskStore

NewBackgroundTaskStore 创建一个新的后台任务存储.

func (*BackgroundTaskStore) Add

Add 添加一个后台任务. 返回 error 当任务数已达 maxBackgroundTasks 上限.

精妙之处(CLEVER): Add 顺手清理一次 stale 任务-- 新任务到来时正好是一个机会窗口去回收老任务,无需独立 goroutine. 即使 Add 极少被调用,最终态任务也会在下次 Add 时被清理; 完全没有 Add 的场景下,进程也很快会退出(不是真正的 leak).

func (*BackgroundTaskStore) Get

Get 获取一个后台任务.

func (*BackgroundTaskStore) List

List 列出所有后台任务.

func (*BackgroundTaskStore) NextID

func (s *BackgroundTaskStore) NextID() string

NextID 生成下一个任务 ID.

func (*BackgroundTaskStore) Remove

func (s *BackgroundTaskStore) Remove(id string)

Remove 删除一个已完成的后台任务,释放内存.

type BashOutput

type BashOutput struct {
	// contains filtered or unexported fields
}

BashOutput 是线程安全的输出累积器.

func (*BashOutput) CombinedOutput

func (o *BashOutput) CombinedOutput() string

CombinedOutput 返回合并的输出(stdout + stderr with prefix),线程安全. 如果输出曾被截断,末尾追加截断提示.

func (*BashOutput) Stderr

func (o *BashOutput) Stderr() string

Stderr 返回累积的 stderr 内容(线程安全).

func (*BashOutput) Stdout

func (o *BashOutput) Stdout() string

Stdout 返回累积的 stdout 内容(线程安全).

func (*BashOutput) WriteStderr

func (o *BashOutput) WriteStderr(s string)

WriteStderr 追加 stderr 内容(线程安全). 超出 maxOutputBytes 的内容被丢弃,dropped 计数器记录丢弃量.

func (*BashOutput) WriteStdout

func (o *BashOutput) WriteStdout(s string)

WriteStdout 追加 stdout 内容(线程安全). 超出 maxOutputBytes 的内容被丢弃,dropped 计数器记录丢弃量.

type BashResult

type BashResult struct {
	Output                    string        `json:"output"`
	ExitCode                  int           `json:"exit_code"`
	Duration                  time.Duration `json:"duration,omitempty"`
	CommandClass              CommandClass  `json:"command_class"`                         // 命令分类
	IsTruncated               bool          `json:"is_truncated"`                          // 是否被截断
	AssistantAutoBackgrounded bool          `json:"assistant_auto_backgrounded,omitempty"` // 自动后台化标志
	BackgroundTaskID          string        `json:"background_task_id,omitempty"`          // 后台任务 ID
}

BashResult 是 Bash 工具的执行结果.

type BashTool

type BashTool struct {
	// contains filtered or unexported fields
}

BashTool 是 bash 命令执行工具.

func NewBashTool

func NewBashTool(cwd string, executor execenv.Executor) *BashTool

NewBashTool 创建一个 Bash 工具实例. executor 必填 (方案 β 严格 DI), 本地模式传 execenv.DefaultExecutor{}, nil panic.

func NewBashToolMainAgent

func NewBashToolMainAgent(cwd string, bgStore *BackgroundTaskStore, taskStore *TaskStore, executor execenv.Executor) *BashTool

NewBashToolMainAgent 创建主 agent 专用的 Bash 工具实例(启用 15s 自动后台化).

升华改进(ELEVATED): 与 NewBashTool/NewBashToolWithStores 的区别在于 isMainAgent=true-- 主 agent 的对话需要保持响应性,长阻塞命令自动转后台; subagent 专注单一任务,不需要自动后台化(用 NewBashToolWithStores). 替代方案:统一在 Config 里控制(Config.AutoBackgroundMs)- 否决:过度暴露实现细节给消费层.

executor 必填, 语义同 NewBashTool.

func NewBashToolWithStores

func NewBashToolWithStores(cwd string, bgStore *BackgroundTaskStore, taskStore *TaskStore, executor execenv.Executor) *BashTool

NewBashToolWithStores 创建一个带后台任务支持的 Bash 工具实例. executor 必填, 语义同 NewBashTool.

func (*BashTool) CancelBackgroundTask

func (t *BashTool) CancelBackgroundTask(taskID string) (bool, error)

CancelBackgroundTask 取消一个后台任务.

func (*BashTool) Description

func (t *BashTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*BashTool) Execute

func (t *BashTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 执行 bash 命令. 使用管道流式读取 stdout 和 stderr,通过 progress 回调实时报告输出. 超时后先发 SIGTERM 给进程组优雅终止,等 5 秒后再 SIGKILL 强制终止.

func (*BashTool) GetBackgroundTask

func (t *BashTool) GetBackgroundTask(taskID string) (*BackgroundBashTask, bool)

GetBackgroundTask 获取后台任务信息.

func (*BashTool) InputSchema

func (t *BashTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*BashTool) Metadata

func (t *BashTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*BashTool) Name

func (t *BashTool) Name() string

Name 返回工具名称.

func (*BashTool) SetPlanSockPath

func (t *BashTool) SetPlanSockPath(path string)

SetPlanSockPath 设置 FLYTO_PLAN_SOCK 的实例级值. 由 Engine.New() 在 PlanCommandServer 初始化完成后调用,避免使用 os.Setenv 污染全局进程环境. 空字符串表示不注入该环境变量.

func (*BashTool) SetSessionSockPath

func (t *BashTool) SetSessionSockPath(path string)

SetSessionSockPath 设置 FLYTO_SESSION_SOCK 的实例级值. 由 Engine.New() 在 UDS Inbox 初始化完成后调用,避免使用 os.Setenv 污染全局进程环境. 空字符串表示不注入该环境变量.

type BuiltinGrepEngine

type BuiltinGrepEngine struct{}

BuiltinGrepEngine 使用纯 Go regexp 执行搜索.

func NewBuiltinGrepEngine

func NewBuiltinGrepEngine() *BuiltinGrepEngine

NewBuiltinGrepEngine 创建内置 Grep 引擎.

func (*BuiltinGrepEngine) Name

func (e *BuiltinGrepEngine) Name() string

func (*BuiltinGrepEngine) Search

func (e *BuiltinGrepEngine) Search(ctx context.Context, params *GrepParams) (*GrepResult, error)

Search 使用 Go regexp 执行搜索.

type CommandClass

type CommandClass string

CommandClass 是命令的语义分类.

const (
	ClassSearch  CommandClass = "search"  // 搜索命令:grep, rg, find, ag, ack
	ClassRead    CommandClass = "read"    // 读取命令:cat, head, tail, less, wc, jq
	ClassList    CommandClass = "list"    // 列表命令:ls, tree, du
	ClassWrite   CommandClass = "write"   // 写入操作
	ClassSilent  CommandClass = "silent"  // 静默操作:mv, cp, rm, mkdir, touch, ln
	ClassGeneral CommandClass = "general" // 其他
)

func ClassifyCommand

func ClassifyCommand(cmdName string) CommandClass

ClassifyCommand 对单个命令名进行分类. cmdName 应为命令的基本名称(不含路径和参数).

func ClassifyPipeline

func ClassifyPipeline(commands []string) CommandClass

ClassifyPipeline 对管道命令序列进行分类. commands 是管道中每个命令的名称列表. 降级规则:管道中任一命令为 write/general 时,整条管道降级. 中性命令被跳过.

func ClassifyShellCommand

func ClassifyShellCommand(shellCmd string) CommandClass

ClassifyShellCommand 对完整的 shell 命令字符串进行分类. 支持管道解析:将命令按 | 分割,提取每段的命令名,再调用 ClassifyPipeline.

type ExecTool

type ExecTool struct {
	// contains filtered or unexported fields
}

ExecTool 实现 tools.Tool 接口,通过子进程执行外部程序.

精妙之处(CLEVER): 命令固定在定义文件中,输入通过 stdin 传递-- 不可能通过工具调用注入额外命令行参数,消除了命令注入的攻击面. 替代方案:<把参数拼到 exec 数组尾部> - 否决:任意字符串参数可触发 shell 解析或 被恶意程序解释为子命令(如 git 的 --exec 系列参数).

func LoadExecToolsFromFile

func LoadExecToolsFromFile(path string, executor execenv.Executor) ([]*ExecTool, error)

LoadExecToolsFromFile 从 JSON 文件加载外部工具定义列表.

JSON 格式支持两种形式:

  • 单个工具对象:{...}
  • 工具对象数组:[{...}, {...}]

升华改进(ELEVATED): 同时支持单对象和数组格式,方便不同的生成工具写出的文件. Kubernetes ConfigMap 倾向于单个对象,脚本批量生成倾向于数组. 替代方案:<只支持数组> - 否决:单工具场景需要额外包一层 `[]`,容易遗漏出错.

executor 透传给每个 NewExecTool, nil 即 panic (M1 方案 β 严格 DI).

func NewExecTool

func NewExecTool(def ExecToolDef, executor execenv.Executor) (*ExecTool, error)

NewExecTool 创建 ExecTool 实例. def.Exec 必须非空(至少包含可执行文件路径).

executor 必填, nil 即 panic (M1 方案 β 严格 DI, 无 fallback). 本地 CLI 传 execenv.DefaultExecutor{}, 云端 SaaS 由 platform 层传 sandbox.Backend. ClassUserHook 告诉 backend "这是用户静态声明的 exec tool, 信任度同 UserHook / settings.json hook".

func (*ExecTool) Description

func (t *ExecTool) Description(_ context.Context) string

Description 返回工具描述.

func (*ExecTool) Execute

func (t *ExecTool) Execute(ctx context.Context, input json.RawMessage, _ tools.ProgressFunc) (*tools.Result, error)

Execute 启动子进程执行工具逻辑.

执行流程:

  1. 创建带超时的 context
  2. 启动 Exec 子进程,stdin 连接管道
  3. 将 input JSON 写入 stdin,关闭 stdin(EOF 通知子进程输入结束)
  4. 读取 stdout 作为输出
  5. 等待子进程退出,exit code != 0 → IsError=true

升华改进(ELEVATED): stdin/stdout 协议天然支持流式大输入-- 通过 io.Pipe 可以零内存拷贝地将大型 JSON 输入传入子进程, 比 HTTP 接口的请求体上传更轻量. 替代方案:<命令行参数传递 JSON> - 否决:有 ARG_MAX 限制(Linux 通常 2MB), 大型输入(文件内容嵌入 JSON)会失败.

func (*ExecTool) InputSchema

func (t *ExecTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*ExecTool) Metadata

func (t *ExecTool) Metadata() tools.Metadata

Metadata 返回工具元数据. 外部工具保守默认:不可并发,非只读,非破坏性(具体行为未知).

func (*ExecTool) Name

func (t *ExecTool) Name() string

Name 返回工具名称.

type ExecToolDef

type ExecToolDef struct {
	Name           string          `json:"name"`
	Description    string          `json:"description"`
	InputSchema    json.RawMessage `json:"input_schema"`
	Exec           []string        `json:"exec"`            // 命令 + 参数,至少一个元素
	TimeoutSeconds int             `json:"timeout_seconds"` // 默认 30
}

ExecToolDef 是外部工具的 JSON 定义格式. 通过 JSON 文件描述一个外部可执行程序工具,支持数组形式批量定义.

示例 JSON:

{
  "name": "query_inventory",
  "description": "查询仓库库存系统",
  "input_schema": {"type":"object","properties":{"sku":{"type":"string"}},"required":["sku"]},
  "exec": ["python3", "/opt/tools/query_wms.py"],
  "timeout_seconds": 10
}

type FileCacheRecorder

type FileCacheRecorder interface {
	Record(path string, content []byte)
}

FileCacheRecorder 是文件缓存的记录接口. FileReadTool 通过此接口将读取的文件记录到缓存中, 而不直接依赖 engine 包(避免循环引用).

精妙之处(CLEVER): 用接口打破循环依赖--FileReadTool 在 builtin 包中, FileStateCache 在 engine 包中.如果直接引用会产生 builtin → engine → builtin 循环. 通过 FileCacheRecorder 接口解耦:builtin 只依赖接口,engine 注入实现.

type FileEditResultData

type FileEditResultData struct {
	Diff     string // unified diff 文本
	FilePath string // 编辑的文件路径
}

FileEditResultData 携带编辑的结构化结果(消费层可用于 diff 展示).

type FileEditTool

type FileEditTool struct {
	// contains filtered or unexported fields
}

FileEditTool 是文件编辑工具.

func NewFileEditTool

func NewFileEditTool() *FileEditTool

NewFileEditTool 创建一个 FileEdit 工具实例(无缓存). 默认 cwd 为当前工作目录.

func NewFileEditToolComplete

func NewFileEditToolComplete(cache FileCacheRecorder, history FileHistoryRecorder, cwd string) *FileEditTool

NewFileEditToolComplete 创建一个完整配置的 FileEdit 工具实例. 升华改进(ELEVATED): 注入文件历史,编辑前自动备份. 替代方案:在 Engine 层做备份(散落在编排逻辑中,不如工具内部自包含).

func NewFileEditToolFull

func NewFileEditToolFull(cache FileCacheRecorder, cwd string) *FileEditTool

NewFileEditToolFull 创建一个带文件缓存和指定工作目录的 FileEdit 工具实例.

func NewFileEditToolWithCache

func NewFileEditToolWithCache(cache FileCacheRecorder) *FileEditTool

NewFileEditToolWithCache 创建一个带文件缓存的 FileEdit 工具实例. 精妙之处(CLEVER): 与 FileReadToolWithCache 对称 -- 读时记录,编辑后也 更新缓存,保证缓存一致性.否则编辑后 FileRead 的缓存就是陈旧的.

func NewFileEditToolWithCwd

func NewFileEditToolWithCwd(cwd string) *FileEditTool

NewFileEditToolWithCwd 创建一个指定工作目录的 FileEdit 工具实例(无缓存). 升华改进(ELEVATED): 显式注入 cwd,使工具可测试且不依赖进程全局状态. 替代方案:每次 apply 时调用 os.Getwd()(简单但不可测试).

func NewFileEditToolWithGuard

func NewFileEditToolWithGuard(cache FileCacheRecorder, history FileHistoryRecorder, cwd string, guard security.SecretGuard) *FileEditTool

NewFileEditToolWithGuard 创建带秘密扫描的完整配置 FileEdit 工具实例. guard 对 new_string 内容进行扫描,有秘密时拒绝写入. 升华改进(ELEVATED): 编辑工具只注入 new_string 到文件,因此只扫描 new_string, 不扫描 old_string(old_string 只是匹配条件,不写入文件). 替代方案:<扫描整个 new_string + old_string> - 否决原因:old_string 是文件已有内容, 不是 Agent 新引入的;扫描它会导致含秘密的文件无法被任何编辑操作修改(即使是删除秘密).

func (*FileEditTool) Capability

func (t *FileEditTool) Capability() tools.ToolCapability

Capability 声明 FileEdit 工具的安全能力. 实现 tools.CapabilityProvider 接口.

升华改进(ELEVATED): FileEdit 是 Level 2 工具(DryRun + Reversible), Agent 可以先预览 diff 再决定是否执行,执行后可以回滚到原文件. 替代方案:不声明能力(Agent 无法区分 FileEdit 和 rm -rf 的安全等级).

func (*FileEditTool) Description

func (t *FileEditTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*FileEditTool) DryRun

func (t *FileEditTool) DryRun(ctx context.Context, input json.RawMessage) (*tools.DryRunResult, error)

DryRun 模拟执行文件编辑,返回 diff 预览但不实际修改文件. 实现 tools.DryRunnable 接口.

精妙之处(CLEVER): 复用 validate 阶段的逻辑--validate 本身就不修改文件, 只需要在 validate 成功后计算 diff 即可.

func (*FileEditTool) Execute

func (t *FileEditTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 执行文件编辑操作. 内部分为两步:validate(纯函数,不修改文件)+ execute(应用修改).

func (*FileEditTool) GenerateUndo

func (t *FileEditTool) GenerateUndo(ctx context.Context, input json.RawMessage, result *tools.Result) (*tools.UndoInfo, error)

GenerateUndo 基于编辑结果生成撤销信息. 实现 tools.Reversible 接口.

精妙之处(CLEVER): 撤销 FileEdit 就是用 FileWrite 写回原内容. 不需要反向 diff--直接读备份恢复即可.这里生成的 UndoInfo 指向 "Write" 工具,带上原文件内容作为输入.

func (*FileEditTool) InputSchema

func (t *FileEditTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*FileEditTool) Metadata

func (t *FileEditTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*FileEditTool) Name

func (t *FileEditTool) Name() string

Name 返回工具名称.

func (*FileEditTool) SetMessageID

func (t *FileEditTool) SetMessageID(id string)

SetMessageID 设置当前消息 ID(由编排器在每轮开始时调用).

type FileHistoryRecorder

type FileHistoryRecorder interface {
	// BeforeEdit 编辑前备份(文件必须存在)
	BeforeEdit(filePath string, messageID string) error
	// BeforeWrite 写入前备份(文件不存在时记录为新建)
	BeforeWrite(filePath string, messageID string) error
}

FileHistoryRecorder 是文件历史的记录接口. FileEditTool/FileWriteTool 通过此接口在修改前备份文件内容, 而不直接依赖 engine 包(和 FileCacheRecorder 一样用接口打破循环依赖).

精妙之处(CLEVER): 和 FileCacheRecorder 对称设计-- FileCacheRecorder 在"读后"记录,FileHistoryRecorder 在"写前"备份.

type FileReadTool

type FileReadTool struct {
	// contains filtered or unexported fields
}

FileReadTool 是文件读取工具.

func NewFileReadTool

func NewFileReadTool() *FileReadTool

NewFileReadTool 创建一个 FileRead 工具实例.

func NewFileReadToolFull

func NewFileReadToolFull(cache FileCacheRecorder, stateCache FileStateCacheRecorder) *FileReadTool

NewFileReadToolFull 创建一个完整配置的 FileRead 工具实例.

func NewFileReadToolWithCache

func NewFileReadToolWithCache(cache FileCacheRecorder) *FileReadTool

NewFileReadToolWithCache 创建一个带文件缓存的 FileRead 工具实例. cache 为 nil 时退化为无缓存行为,向后兼容.

func (*FileReadTool) Description

func (t *FileReadTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*FileReadTool) Execute

func (t *FileReadTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 读取文件内容并返回结果. 根据文件类型自动分流到不同的处理路径:

  • 图片 → base64 内联
  • PDF → 文件元信息
  • Jupyter Notebook → cell 格式化
  • 文本 → cat -n 格式行号输出

精妙之处(CLEVER): 处理顺序很重要. 1. 参数验证(无 I/O) 2. 路径安全检查(无 I/O 或仅 Lstat) 3. 设备文件阻止(纯路径检查,无 I/O) 4. 打开文件 + Stat(第一次 I/O) 5. 文件类型分流(基于扩展名 + magic bytes)

这种"分层防御"确保危险路径在任何 I/O 前被拦截.

func (*FileReadTool) InputSchema

func (t *FileReadTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*FileReadTool) Metadata

func (t *FileReadTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*FileReadTool) Name

func (t *FileReadTool) Name() string

Name 返回工具名称.

type FileStateCacheEntry

type FileStateCacheEntry struct {
	ContentHash   string    // SHA-256 of content
	Size          int64     // 文件大小
	LineCount     int       // 总行数
	ModTime       time.Time // 文件修改时间
	IsPartialView bool      // 是否只读取了部分(有 offset)
}

FileStateCacheEntry 表示文件状态缓存的一条记录. 对应原 TS 项目的 readFileState.set() 调用.

精妙之处(CLEVER): 缓存不仅记录内容,还记录读取时的元信息. 这让 dedup 逻辑可以精确判断"上次读的同一范围是否还有效". IsPartialView 标记很重要:partial read 不能用于编辑前的完整性验证.

**消费形态 (同步回调 callback)**: `FileReadTool` 每次读文件后经 `FileStateCacheRecorder.RecordState(path, entry)` 把 entry 塞给**外部 注入的 Recorder 实现**. Recorder 由消费者 (SaaS 平台 / IDE 插件 / 测试 harness) 自己写, 决定读哪些字段消费. 和 engine.PlanApprovalEvent / engine.ElicitationField 同构 (form 3 callback) -- scanner 视野内无 内部 reader 是期望状态, 字段是给外部消费者读的"参数载体", 不该强加内部 reader 来"过扫描器". 见 docs/api-reference.md "API 消费形态" 章节.

字段解读 (供外部 Recorder 消费):

  • ContentHash: 内容 SHA-256, 用于 dedup 或版本校验.
  • Size / LineCount: 文件大小 / 行数, 用于 UI 展示 / 审计.
  • ModTime: 文件修改时间, 用于 freshness 判断.
  • IsPartialView: 本次读是否只读了部分 (偏移/长度限制). Recorder 若做"编辑前完整性验证"必须看这个标记.

Consumption shape (callback / form 3): after every file read, FileReadTool calls FileStateCacheRecorder.RecordState(path, entry), handing the entry to an externally-injected Recorder implementation. The Recorder is written by the consumer (SaaS platform / IDE plugin / test harness) and decides which fields matter. Structurally identical to engine.PlanApprovalEvent / engine.ElicitationField (form 3 callback) -- absence of an internal reader within the scanner's view is expected; fields are the "argument payload" for external consumers. See docs/api-reference.md "API consumption shapes" for the callback-shape catalogue.

type FileStateCacheRecorder

type FileStateCacheRecorder interface {
	RecordState(path string, entry FileStateCacheEntry)
}

FileStateCacheRecorder 是文件状态缓存的记录接口. 区别于 FileCacheRecorder(记录原始内容),这个记录文件元数据状态.

type FileWriteTool

type FileWriteTool struct {
	// contains filtered or unexported fields
}

FileWriteTool 是文件写入工具.

func NewFileWriteTool

func NewFileWriteTool() *FileWriteTool

NewFileWriteTool 创建一个 FileWrite 工具实例.

func NewFileWriteToolWithGuard

func NewFileWriteToolWithGuard(history FileHistoryRecorder, guard security.SecretGuard) *FileWriteTool

NewFileWriteToolWithGuard 创建一个带秘密扫描的 FileWrite 工具实例.

升华改进(ELEVATED): 早期方案 只保护 TeamMem 同步路径; 我们默认对所有路径生效,调用方可通过 guard.ExemptPaths 豁免特定目录. 替代方案:<只在 memory 写入时扫描> - 否决原因:Agent 可以向任意路径写秘密.

func NewFileWriteToolWithHistory

func NewFileWriteToolWithHistory(history FileHistoryRecorder) *FileWriteTool

NewFileWriteToolWithHistory 创建一个带文件历史的 FileWrite 工具实例. 升华改进(ELEVATED): 注入文件历史,写入前自动备份已有文件. 替代方案:不备份(新建文件无所谓,但覆盖已有文件就无法回滚了).

func (*FileWriteTool) Capability

func (t *FileWriteTool) Capability() tools.ToolCapability

Capability 声明 FileWrite 工具的安全能力. 实现 tools.CapabilityProvider 接口.

func (*FileWriteTool) Description

func (t *FileWriteTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*FileWriteTool) DryRun

func (t *FileWriteTool) DryRun(ctx context.Context, input json.RawMessage) (*tools.DryRunResult, error)

DryRun 模拟执行文件写入,返回预览但不实际写入. 实现 tools.DryRunnable 接口.

func (*FileWriteTool) Execute

func (t *FileWriteTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 写入文件内容.

func (*FileWriteTool) GenerateUndo

func (t *FileWriteTool) GenerateUndo(ctx context.Context, input json.RawMessage, result *tools.Result) (*tools.UndoInfo, error)

GenerateUndo 基于写入结果生成撤销信息. 实现 tools.Reversible 接口.

精妙之处(CLEVER): 新建文件的撤销是删除,覆盖文件的撤销是恢复原内容. 具体的恢复由 FileHistory 系统完成,这里只生成撤销指令描述.

func (*FileWriteTool) InputSchema

func (t *FileWriteTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*FileWriteTool) Metadata

func (t *FileWriteTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*FileWriteTool) Name

func (t *FileWriteTool) Name() string

Name 返回工具名称.

func (*FileWriteTool) SetMessageID

func (t *FileWriteTool) SetMessageID(id string)

SetMessageID 设置当前消息 ID(由编排器在每轮开始时调用).

type GitGlobEngine

type GitGlobEngine struct {
	// contains filtered or unexported fields
}

GitGlobEngine 在 git 仓库中使用 git ls-files 进行文件搜索.

func NewGitGlobEngine

func NewGitGlobEngine(gitPath, repoDir string, executor execenv.Executor) *GitGlobEngine

NewGitGlobEngine 创建 Git Glob 引擎. executor 不能为 nil (方案 β 严格 DI).

func (*GitGlobEngine) Name

func (e *GitGlobEngine) Name() string

func (*GitGlobEngine) Search

func (e *GitGlobEngine) Search(ctx context.Context, params *GlobParams) ([]fileWithInfo, int, error)

Search 使用 git ls-files 搜索文件. 升华改进(ELEVATED): 组合 tracked + untracked(排除 ignored)两次调用, 覆盖新建但未 git add 的文件. 替代方案:只用 git ls-files 列出 tracked 文件(更快但漏掉新文件).

type GitignoreTool

type GitignoreTool struct {
	// contains filtered or unexported fields
}

GitignoreTool 管理 .gitignore 文件.

func NewGitignoreTool

func NewGitignoreTool(cwd string) *GitignoreTool

NewGitignoreTool 创建 GitignoreTool. cwd 是 Agent 的当前工作目录,用作 dir 参数的默认值.

func (*GitignoreTool) Description

func (t *GitignoreTool) Description(_ context.Context) string

func (*GitignoreTool) Execute

func (*GitignoreTool) InputSchema

func (t *GitignoreTool) InputSchema() json.RawMessage

func (*GitignoreTool) Metadata

func (t *GitignoreTool) Metadata() tools.Metadata

func (*GitignoreTool) Name

func (t *GitignoreTool) Name() string

type GlobEngine

type GlobEngine interface {
	// Search 根据 glob 模式搜索文件,返回匹配的文件列表.
	Search(ctx context.Context, params *GlobParams) ([]fileWithInfo, int, error)
	// Name 返回引擎名称(用于调试和日志).
	Name() string
}

GlobEngine 是文件搜索引擎接口.

func DetectGlobEngine

func DetectGlobEngine(searchDir string, executor execenv.Executor) GlobEngine

DetectGlobEngine 根据当前环境选择最佳 Glob 引擎.

M1 方案 β: 接受 executor 参数, Git 引擎走 Executor.Command. Walk 引擎 纯 Go 实现无子进程, 不需要 executor. exec.LookPath 是能力探测(本地)而非 子进程执行, 不走 Executor -- 语义边界同 grep_engine.

type GlobParams

type GlobParams struct {
	Pattern        string
	SearchDir      string
	IncludeIgnored bool
}

GlobParams 包含 Glob 搜索的所有参数.

type GlobTool

type GlobTool struct {
	// contains filtered or unexported fields
}

GlobTool 是文件模式匹配搜索工具.

func NewGlobTool

func NewGlobTool(executor execenv.Executor) *GlobTool

NewGlobTool 创建一个 Glob 工具实例. executor 不能为 nil (方案 β 严格 DI). M1: GlobTool 从无状态 struct 升级为持有 Executor, 用于 GitGlobEngine 子进程.

func (*GlobTool) Description

func (t *GlobTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*GlobTool) Execute

func (t *GlobTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 执行 glob 文件搜索.

func (*GlobTool) InputSchema

func (t *GlobTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*GlobTool) Metadata

func (t *GlobTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*GlobTool) Name

func (t *GlobTool) Name() string

Name 返回工具名称.

type GrepEngine

type GrepEngine interface {
	// Search 执行搜索,返回格式化后的输出,匹配文件数,总匹配数.
	Search(ctx context.Context, params *GrepParams) (*GrepResult, error)
	// Name 返回引擎名称.
	Name() string
}

GrepEngine 是搜索引擎接口.

func DetectGrepEngine

func DetectGrepEngine(executor execenv.Executor) GrepEngine

DetectGrepEngine 检测系统是否有 rg(ripgrep),有就用,没有就纯 Go 兜底.

M1 方案 β: 接受 executor 参数, rg 引擎走 Executor.Command. 内置引擎纯 Go 实现无子进程, 不需要 executor. exec.LookPath 是能力探测(本地)而非子进程 执行, 不走 Executor -- Executor 语义是"跑子进程", 能力探测留在本地.

type GrepParams

type GrepParams struct {
	Pattern         string
	SearchPath      string // 搜索路径(文件或目录)
	SearchDir       string // 搜索的基目录(用于相对路径计算)
	IsFile          bool   // 搜索路径是否为单个文件
	Glob            string
	OutputMode      string // content / files_with_matches / count
	ContextBefore   int    // -B
	ContextAfter    int    // -A
	ContextBoth     int    // -C(同时设置 before 和 after)
	CaseInsensitive bool
	HeadLimit       int // 输出上限
	FileType        string
	Multiline       bool
	Offset          int // 跳过前 N 条
}

GrepParams 包含 Grep 搜索的所有参数.

type GrepResult

type GrepResult struct {
	Output       string
	MatchedFiles int
	TotalMatches int
	LimitReached bool
}

GrepResult 是搜索结果.

type GrepTool

type GrepTool struct {
	// contains filtered or unexported fields
}

GrepTool 是正则表达式搜索工具.

func NewGrepTool

func NewGrepTool(executor execenv.Executor) *GrepTool

NewGrepTool 创建一个 Grep 工具实例. executor 不能为 nil (方案 β 严格 DI). M1: GrepTool 从无状态 struct 升级为持有 Executor, 用于 RipgrepEngine 子进程.

func (*GrepTool) Description

func (t *GrepTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*GrepTool) Execute

func (t *GrepTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 执行 grep 搜索.

func (*GrepTool) InputSchema

func (t *GrepTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*GrepTool) Metadata

func (t *GrepTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*GrepTool) Name

func (t *GrepTool) Name() string

Name 返回工具名称.

type IgnorePattern

type IgnorePattern struct {
	// contains filtered or unexported fields
}

IgnorePattern 表示一条 .gitignore 规则.

func CollectIgnorePatterns

func CollectIgnorePatterns(rootDir string) []IgnorePattern

CollectIgnorePatterns 从项目根目录递归收集所有 .gitignore 规则. rootDir 是项目根目录的绝对路径. 返回的规则列表包含默认排除模式. 精妙之处(CLEVER): 递归收集 .gitignore 时利用已有规则过滤目录-- 已收集的忽略规则会影响后续目录是否被递归进入(如 node_modules/ 的 .gitignore 不会被读取). 这意味着规则收集顺序很重要:父目录的 .gitignore 优先于子目录的. 这和 Git 的实际行为一致.

func ParseGitignore

func ParseGitignore(path string, baseDir string) []IgnorePattern

ParseGitignore 解析一个 .gitignore 文件,返回规则列表. path 是 .gitignore 文件的绝对路径. baseDir 是该 .gitignore 相对于项目根目录的路径(根目录下为 "").

type ImageResult

type ImageResult struct {
	MediaType string // "image/png", "image/jpeg", "image/gif", "image/webp"
	Base64    string // base64 编码的图片数据
	Width     int    // pull API, 图片宽度 (外部 type-assert 消费, vision wire 不读)
	Height    int    // pull API, 图片高度 (外部 type-assert 消费, vision wire 不读)
}

ImageResult is the structured image payload stored in tools.Result.Data so callers can access parsed image bytes.

Field consumption:

  • MediaType / Base64 are consumed by the vision wire (engine.go builds array-form tool_result for Anthropic messages API, see commit 087393b). These are the fields the model actually receives.
  • Width / Height are an external type-assertion surface: consumers that do `if img, ok := res.Data.(*ImageResult); ok` can read them for logging / validation / UI rendering. The Anthropic tool_result wire itself does not consume dimensions. Retained as a structured field rather than a free-form Meta map because they are canonical image attributes with a stable type.

ImageResult 是存于 tools.Result.Data 的结构化图片载荷, 让调用方获取 解析后的图片数据.

字段消费形态:

  • MediaType / Base64 由 vision wire 消费 (engine.go 为 Anthropic messages API 构造 array-form tool_result, 见 commit 087393b). 这是 模型实际收到的字段.
  • Width / Height 是外部 type-assert 表面: 消费者经 `if img, ok := res.Data.(*ImageResult); ok` 后读取, 用于日志 / 校验 / UI 渲染. Anthropic tool_result wire 本身不消费尺寸. 保留为 结构化字段而非 free-form Meta map, 因其是规范的图片属性, 有稳定类型.

type MonitorTool

type MonitorTool struct {
	// contains filtered or unexported fields
}

MonitorTool 进度报告工具.

精妙之处(CLEVER): 持有 *inbox.UDSServer 指针而非接口--

UDSServer 是具体实现,此处不需要抽象(只有一种实现).
如果未来需要 mock(测试用),只需将 inbox.UDSServer 指针替换为接口.
替代方案:定义 InboxSink 接口(过度抽象,当前无多态需求).

func NewMonitorTool

func NewMonitorTool(srv *inbox.UDSServer) *MonitorTool

NewMonitorTool 创建 MonitorTool 实例. srv 为 nil 时工具仍可用,但所有调用静默成功(不推送消息).

func (*MonitorTool) Description

func (t *MonitorTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*MonitorTool) Execute

func (t *MonitorTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 执行进度推送.

三层防御:

a) 参数层:message 必填验证
b) UDS 层:srv 为 nil 时静默成功(不中断 Agent 执行)
c) channel 层:非阻塞推送,channel 满时丢弃(不阻塞 Agent 主循环)

func (*MonitorTool) InputSchema

func (t *MonitorTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema.

func (*MonitorTool) Metadata

func (t *MonitorTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*MonitorTool) Name

func (t *MonitorTool) Name() string

Name 返回工具名称.

type ResultExtractor

type ResultExtractor func(toolName string, result *tools.Result) validator.DiffInput

ResultExtractor converts a successful tool Result into a DiffInput the Validator can consume. toolName matches the inner tool's Name() and is routed into DiffInput.SourceTool so the Validator can dispatch on it.

ResultExtractor 把成功的工具 Result 转为 Validator 可消费的 DiffInput. toolName 与 inner tool 的 Name() 一致, 流入 DiffInput.SourceTool 供 Validator 分发.

func DefaultExtractor

func DefaultExtractor() ResultExtractor

DefaultExtractor produces a minimal DiffInput: SourceTool = toolName, Raw = json.Marshal(result.Data), no metadata hints. Use when the Validator inspects Raw bytes only (LLMValidator); Rules needing numeric / string hints (DiffSizeRule / TableWhitelistRule) require a tool-specific extractor that populates Metadata.

DefaultExtractor 产出最小 DiffInput: SourceTool = toolName, Raw = json.Marshal(result.Data), 无 metadata 提示. 适合 Validator 只检查 Raw bytes 的场景 (LLMValidator). 需要数值 / 字符串提示的 Rule (DiffSizeRule / TableWhitelistRule) 要用具体工具的 extractor 填 Metadata.

func ExtractorSQLCAS

func ExtractorSQLCAS() ResultExtractor

ExtractorSQLCAS builds a ResultExtractor for the SQLCAS tool. It marshals Result.Data as Raw and populates Metadata with the conventional keys "affected_rows" and "table_name" (read by DiffSizeRule / TableWhitelistRule respectively) when present in Data's JSON shape.

ExtractorSQLCAS 为 SQLCAS 工具构造 ResultExtractor. marshal Result.Data 作 Raw, 当 Data 的 JSON 形态含 "affected_rows" / "table_name" 约定 key 时填入 Metadata (DiffSizeRule / TableWhitelistRule 会读).

func ExtractorSQLDryRun

func ExtractorSQLDryRun() ResultExtractor

ExtractorSQLDryRun builds a ResultExtractor for the SQLDryRun tool. DryRun's Data typically exposes "affected_row_count" (not "affected_rows") which this extractor normalises to the common key "affected_rows" so Rules keyed on the common name work uniformly across SQL tools. Also surfaces "after_predicate_mismatch" as a metadata hint for consistency checks.

ExtractorSQLDryRun 为 SQLDryRun 工具构造 ResultExtractor. DryRun 的 Data 通常暴露 "affected_row_count" (非 "affected_rows"), 此 extractor 归一化为通用 key "affected_rows", Rule 按通用 key 匹配即可跨 SQL 工具 统一. 同时把 "after_predicate_mismatch" 作为一致性检查 hint 暴露.

type RipgrepEngine

type RipgrepEngine struct {
	// contains filtered or unexported fields
}

RipgrepEngine 调用系统 rg 命令执行搜索.

func NewRipgrepEngine

func NewRipgrepEngine(rgPath string, executor execenv.Executor) *RipgrepEngine

NewRipgrepEngine 创建 Ripgrep 引擎. executor 不能为 nil (方案 β 严格 DI).

func (*RipgrepEngine) Name

func (e *RipgrepEngine) Name() string

func (*RipgrepEngine) Search

func (e *RipgrepEngine) Search(ctx context.Context, params *GrepParams) (*GrepResult, error)

Search 使用 rg 执行搜索.

type SQLCASTool

type SQLCASTool struct {
	// contains filtered or unexported fields
}

SQLCASTool implements the Tool interface for optimistic-lock UPDATE on staging tables. Holds a StagingDB and the retry budget; no other mutable state, safe to share across goroutines.

SQLCASTool 实现 Tool 接口做 staging 表乐观锁 UPDATE. 持有 StagingDB 和 重试预算; 无其他可变状态, 可 goroutine 间共享.

func NewSQLCASTool

func NewSQLCASTool(db StagingDB, maxRetries int) *SQLCASTool

NewSQLCASTool constructs a CAS tool. maxRetries semantics: initial attempt + up to maxRetries additional retries (maxRetries=0 means one attempt then fail; maxRetries=3 means at most 4 round-trips).

Panics on invalid config (DI contract, surfaces errors at startup rather than under load): db.DB must be non-nil, maxRetries must be in [0, 10] (upper bound is a 防呆 guard against typo'd large values; practical retry budgets rarely exceed single digits).

NewSQLCASTool 构造 CAS 工具. maxRetries 语义: 初次尝试加最多 maxRetries 次重试 (maxRetries=0 即一次尝试后直接失败; maxRetries=3 即最多 4 次 往返).

非法配置 panic (DI 契约, 启动期暴露问题而非负载下炸): db.DB 必须非 nil, maxRetries 必须在 [0, 10] 区间 (上限是防呆 guard, 防止误填过大数值; 实际重试预算几乎不超个位数).

func (*SQLCASTool) Description

func (t *SQLCASTool) Description(ctx context.Context) string

Description is what the LLM reads when deciding to call this tool. The staging-only scope and retry budget are both surfaced so the LLM self-limits to the intended usage.

Description 是 LLM 决定调用本工具时阅读的说明. staging 作用域和重试 预算都显式暴露, 让 LLM 自我约束在预期用法内.

func (*SQLCASTool) Execute

func (t *SQLCASTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute runs the CAS loop. All business-level failures (row missing, version type mismatch, identifier rejected, retries exhausted) return &Result{IsError:true} with a human-readable Output so the LLM can self-correct; only input-JSON parse errors propagate as Go errors.

Execute 执行 CAS 循环. 业务级失败 (行缺失 / version 类型不匹配 / 标识符被拒 / 重试耗尽) 全部以 &Result{IsError:true} 并附人类可读 Output 返回, 让 LLM 自我纠正; 仅输入 JSON 解析错误作为 Go error 向上传播.

func (*SQLCASTool) InputSchema

func (t *SQLCASTool) InputSchema() json.RawMessage

InputSchema returns the JSON Schema for the tool's input.

InputSchema 返回工具输入的 JSON Schema.

func (*SQLCASTool) Metadata

func (t *SQLCASTool) Metadata() tools.Metadata

Metadata declares the tool's cross-cutting properties. CAS is concurrency-safe by design (the retry loop converges under contention). Not ReadOnly (UPDATE). Not Destructive (staging scope, blast radius bounded; production destruction is a separate workflow).

Metadata 声明工具的跨切面属性. CAS 按设计 concurrency-safe (重试循环 在争用下收敛). 非 ReadOnly (UPDATE). 非 Destructive (staging 作用域, blast radius 有界; 生产级破坏另有工作流).

func (*SQLCASTool) Name

func (t *SQLCASTool) Name() string

Name returns the tool name.

Name 返回工具名.

type SQLDryRunTool

type SQLDryRunTool struct {
	// contains filtered or unexported fields
}

SQLDryRunTool previews DML statements on a staging database without committing. Holds a StagingDB; no mutable state, safe to share across goroutines.

SQLDryRunTool 在 staging 数据库上预览 DML 语句而不提交. 持有 StagingDB, 无可变状态, 可跨 goroutine 共享.

func NewSQLDryRunTool

func NewSQLDryRunTool(db StagingDB) *SQLDryRunTool

NewSQLDryRunTool constructs a Dry-run tool. Panics on nil db.DB (DI contract; surfaces config errors at startup).

NewSQLDryRunTool 构造 Dry-run 工具. db.DB 为 nil 时 panic (DI 契约, 启动期暴露配置错误).

func (*SQLDryRunTool) Description

func (t *SQLDryRunTool) Description(ctx context.Context) string

Description informs the LLM of the contract (staging only, three operation paths, predicate requirement).

Description 告知 LLM 契约 (仅 staging, 三种 operation 路径, predicate 要求).

func (*SQLDryRunTool) Execute

func (t *SQLDryRunTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute classifies sql by first keyword and dispatches to the per-operation path. Business-level failures (wrong operation, missing predicate, driver error) return &Result{IsError:true} with an Output the LLM can act on.

Execute 按首 keyword 分类 sql, 分派到对应 operation 路径. 业务级失败 (operation 不支持 / predicate 缺失 / driver 错误) 返回 &Result{IsError: true}, Output 给 LLM 据以自纠.

func (*SQLDryRunTool) InputSchema

func (t *SQLDryRunTool) InputSchema() json.RawMessage

InputSchema returns the JSON Schema for the tool's input.

InputSchema 返回工具输入的 JSON Schema.

func (*SQLDryRunTool) Metadata

func (t *SQLDryRunTool) Metadata() tools.Metadata

Metadata declares cross-cutting properties. ReadOnly=false because UPDATE/DELETE/INSERT actually execute (triggers fire, constraints check, indexes update) even though ROLLBACK reverts. ConcurrencySafe =false because BeginTx holds row locks until the tool's ROLLBACK -- two concurrent Dry-runs on the same row would contend.

Metadata 声明跨切面属性. ReadOnly=false -- 尽管 ROLLBACK 最终撤销, UPDATE/DELETE/INSERT 实际会触发 trigger / 约束检查 / 索引更新. ConcurrencySafe=false -- BeginTx 持行锁直到工具 ROLLBACK, 同行两个并发 Dry-run 会争用.

func (*SQLDryRunTool) Name

func (t *SQLDryRunTool) Name() string

Name returns the tool name.

Name 返回工具名.

type SQLValidatorConfig

type SQLValidatorConfig struct {
	// AllowedTables is the table-name whitelist. Nil or empty disables the
	// whitelist check entirely. Names are matched case-insensitively.
	//
	// AllowedTables 是表名白名单. nil 或空 slice 完全禁用白名单检查. 名称
	// 大小写不敏感匹配.
	AllowedTables []string

	// DefaultLimit, when > 0, is the LIMIT value auto-injected when the
	// caller's SQL has no LIMIT clause. Zero disables injection.
	//
	// DefaultLimit 大于 0 时, 用于在调用方 SQL 无 LIMIT 子句时自动注入的
	// LIMIT 值. 零值禁用注入.
	DefaultLimit int

	// RequireLimit, when true, rejects SQL that lacks a LIMIT clause after
	// optional injection (i.e. RequireLimit=true + DefaultLimit=0 means
	// "LIMIT must be present in caller input").
	//
	// RequireLimit 为 true 时, 可选注入后仍缺 LIMIT 子句的 SQL 被拒 (即
	// RequireLimit=true + DefaultLimit=0 表示 "调用方必须自带 LIMIT").
	RequireLimit bool
}

SQLValidatorConfig configures the three tunable rules.

SQLValidatorConfig 配置三条可调规则.

type SQLValidatorTool

type SQLValidatorTool struct {
	// contains filtered or unexported fields
}

SQLValidatorTool implements the Tool interface for SQL pre-flight validation.

SQLValidatorTool 实现 Tool 接口做 SQL 前置校验.

func NewSQLValidatorTool

func NewSQLValidatorTool(cfg SQLValidatorConfig) *SQLValidatorTool

NewSQLValidatorTool constructs a validator with the given config. Zero- value config accepts any SELECT/WITH/EXPLAIN single statement, no LIMIT enforcement, no table whitelist.

NewSQLValidatorTool 以给定配置构造校验器. 零值配置接受任意单条 SELECT/WITH/EXPLAIN 语句, 不强制 LIMIT, 不校验表白名单.

func (*SQLValidatorTool) Description

func (t *SQLValidatorTool) Description(ctx context.Context) string

Description is what the LLM reads when deciding to call this tool. Kept close to the rules so the model self-serves rewrites on rejection.

Description 是 LLM 决定调用本工具时阅读的说明. 贴近规则书写, 便于模型 在被拒时自行改写.

func (*SQLValidatorTool) Execute

func (t *SQLValidatorTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute parses input, runs Validate, and packages the result. Rejection is signalled via IsError=true with a human-readable reason; acceptance returns the normalized SQL in Output and a structured payload in Data.

Execute 解析输入, 调 Validate, 打包结果. 拒绝通过 IsError=true 携带人类 可读的原因; 通过时 Output 为规范化 SQL, Data 为结构化 payload.

func (*SQLValidatorTool) InputSchema

func (t *SQLValidatorTool) InputSchema() json.RawMessage

InputSchema returns the JSON Schema for the tool's input.

InputSchema 返回工具输入的 JSON Schema.

func (*SQLValidatorTool) Metadata

func (t *SQLValidatorTool) Metadata() tools.Metadata

Metadata declares the tool as read-only. The validator does not contact any DB, so it is always safe to run concurrently and always permitted.

Metadata 声明工具为只读. 校验器不连 DB, 始终可并发且始终放行.

func (*SQLValidatorTool) Name

func (t *SQLValidatorTool) Name() string

Name returns the tool name.

Name 返回工具名.

func (*SQLValidatorTool) Validate

func (t *SQLValidatorTool) Validate(sql string) (normalized string, reason string, ok bool)

Validate runs the full rule chain against a caller SQL. Returns the normalized statement on accept (may equal input when no injection happens); on reject, reason is human-readable and normalized is empty.

Exported so other builtin tools (Dry-run, CAS) can reuse the check without re-wrapping the Tool.Execute boundary.

Validate 对调用方 SQL 跑完整规则链. 通过时返回规范化语句 (未注入时与输入 相同); 拒绝时 reason 为人类可读原因, normalized 为空.

导出以便其他 builtin 工具 (Dry-run / CAS) 复用本校验, 无需绕回 Tool.Execute.

type ScratchpadListTool

type ScratchpadListTool struct {
	// contains filtered or unexported fields
}

ScratchpadListTool 列出 Scratchpad 中所有未过期的键.

func NewScratchpadListTool

func NewScratchpadListTool(store ScratchpadStore) *ScratchpadListTool

NewScratchpadListTool 创建 scratchpad_list 工具实例.

func (*ScratchpadListTool) Description

func (t *ScratchpadListTool) Description(_ context.Context) string

func (*ScratchpadListTool) Execute

func (*ScratchpadListTool) InputSchema

func (t *ScratchpadListTool) InputSchema() json.RawMessage

func (*ScratchpadListTool) Metadata

func (t *ScratchpadListTool) Metadata() tools.Metadata

func (*ScratchpadListTool) Name

func (t *ScratchpadListTool) Name() string

type ScratchpadReadTool

type ScratchpadReadTool struct {
	// contains filtered or unexported fields
}

ScratchpadReadTool 从 Scratchpad 读取指定键的值.

func NewScratchpadReadTool

func NewScratchpadReadTool(store ScratchpadStore) *ScratchpadReadTool

NewScratchpadReadTool 创建 scratchpad_read 工具实例.

func (*ScratchpadReadTool) Description

func (t *ScratchpadReadTool) Description(_ context.Context) string

func (*ScratchpadReadTool) Execute

func (*ScratchpadReadTool) InputSchema

func (t *ScratchpadReadTool) InputSchema() json.RawMessage

func (*ScratchpadReadTool) Metadata

func (t *ScratchpadReadTool) Metadata() tools.Metadata

func (*ScratchpadReadTool) Name

func (t *ScratchpadReadTool) Name() string

type ScratchpadStore

type ScratchpadStore interface {
	Set(key, value string, ttl time.Duration)
	Get(key string) (string, bool)
	Delete(key string)
	Keys() []string
}

ScratchpadStore 是 Scratchpad 存储接口.

精妙之处(CLEVER): 定义接口而非直接依赖 *engine.Scratchpad-- builtin 包不能 import engine 包(循环导入). 接口声明在 builtin 包中,engine 包的 *Scratchpad 实现此接口, 在 engine.registerBuiltinTools() 中注入--依赖反转,解循环. 替代方案:<把 Scratchpad 移到独立包> - 可行,但增加包层级; 接口注入方案代价最低,与 TaskStore 模式一致.

type ScratchpadWriteTool

type ScratchpadWriteTool struct {
	// contains filtered or unexported fields
}

ScratchpadWriteTool 向 Scratchpad 写入键值对.

func NewScratchpadWriteTool

func NewScratchpadWriteTool(store ScratchpadStore) *ScratchpadWriteTool

NewScratchpadWriteTool 创建 scratchpad_write 工具实例.

func (*ScratchpadWriteTool) Description

func (t *ScratchpadWriteTool) Description(_ context.Context) string

func (*ScratchpadWriteTool) Execute

func (*ScratchpadWriteTool) InputSchema

func (t *ScratchpadWriteTool) InputSchema() json.RawMessage

func (*ScratchpadWriteTool) Metadata

func (t *ScratchpadWriteTool) Metadata() tools.Metadata

func (*ScratchpadWriteTool) Name

func (t *ScratchpadWriteTool) Name() string

type SedEditInfo

type SedEditInfo struct {
	FilePath      string // 目标文件路径(-i 的操作对象)
	Pattern       string // 搜索正则(sed 语法,未转换)
	Replacement   string // 替换字符串(sed 语法,未转换)
	Flags         string // 替换标志(g=全局, i=不区分大小写, m=多行)
	ExtendedRegex bool   // 是否使用扩展正则(-E 或 -r 标志)
}

SedEditInfo 是解析后的 sed 原地编辑命令信息. 包含执行和预览替换所需的全部字段.

func ParseSedEditCommand

func ParseSedEditCommand(command string) *SedEditInfo

ParseSedEditCommand 解析 sed 原地编辑命令,提取替换信息. 不支持的命令格式(多文件,多表达式,非替换操作等)返回 nil.

精妙之处(CLEVER): 使用 sedTokenize 做 shell 分词-- 保证引号内的空格不被误分割,和安全检查层逻辑一致,避免行为不一致. 如果用 strings.Fields 分词,`sed -i 's/a b/c/'` 中 `'s/a b/c/'` 会被错误切分.

type SkillEntryDesc

type SkillEntryDesc struct {
	Name          string
	Description   string
	WhenToUse     string
	ArgumentHint  string
	UserInvocable bool
}

SkillEntryDesc 是用于工具描述的 Skill 精简信息.

type SkillExecutor

type SkillExecutor interface {
	// InvokeSkill 执行指定 Skill,返回结果.
	// 参数 name/args 对应 skillInput 字段.
	InvokeSkill(ctx context.Context, name, args string) (*SkillResult, error)
	// ListSkillEntries 返回所有可用 Skill 的精简列表(用于工具描述生成).
	ListSkillEntries() []*SkillEntryDesc
}

SkillExecutor 是 SkillTool 依赖的执行器接口.

精妙之处(CLEVER): 接口定义在 builtin 包(消费方),实现在 engine 包-- 这与 AgentExecutor 完全相同的模式(依赖倒置原则): builtin 定义接口和返回类型,engine 导入 builtin 来实现接口, builtin 不需要导入 engine(避免循环依赖). 替代方案:把接口放在 engine 包,让 builtin 导入 engine(循环依赖,不可行).

type SkillResult

type SkillResult struct {
	// Mode 执行模式:"inline" | "fork"
	Mode string
	// Content 内容:inline 为展开的提示词,fork 为子 Agent 结果
	Content string
	// AllowedTools inline 模式的工具限制列表(信息性)
	AllowedTools []string
	// Model 建议使用的模型(可空)
	Model string
}

SkillResult 是 Skill 执行结果(对应 engine.SkillInvokeResult 的镜像). 定义在 builtin 包避免循环依赖.

type SkillTool

type SkillTool struct {
	// contains filtered or unexported fields
}

SkillTool 实现 tools.Tool 接口. 通过 SkillExecutor 接口执行 Skill,与 engine 包解耦.

func NewSkillTool

func NewSkillTool() *SkillTool

NewSkillTool 创建 SkillTool 实例. executor 初始为 nil,需通过 SetExecutor 注入(类似 AgentTool).

func (*SkillTool) Description

func (t *SkillTool) Description(ctx context.Context) string

Description 返回工具描述,包含可用 Skill 列表(动态生成).

升华改进(ELEVATED): 早期实现 用 1% token 预算截断描述. 我们用固定 8000 字符上限,更简单且与 tokenizer 解耦. 替代方案:动态计算 1% 预算(需要引入 tokenizer,增加复杂性).

func (*SkillTool) Execute

func (t *SkillTool) Execute(ctx context.Context, input json.RawMessage, _ tools.ProgressFunc) (*tools.Result, error)

Execute 执行 Skill 工具调用.

执行流程:

  1. 解析输入参数
  2. 若 executor 未注入,返回提示信息(优雅降级)
  3. 调用 executor.InvokeSkill
  4. inline 模式:返回展开的提示词(LLM 接收并执行)
  5. fork 模式:返回子 Agent 的结果文本

func (*SkillTool) InputSchema

func (t *SkillTool) InputSchema() json.RawMessage

InputSchema 返回 JSON Schema 输入定义.

func (*SkillTool) Metadata

func (t *SkillTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*SkillTool) Name

func (t *SkillTool) Name() string

Name 返回工具名称. 精妙之处(CLEVER): 工具名为 "Skill"(大写),与早期实现 保持一致, 确保 prompt cache 的工具名 key 稳定.

func (*SkillTool) SetExecutor

func (t *SkillTool) SetExecutor(exec SkillExecutor)

SetExecutor 注入 Skill 执行器. 在 Engine 初始化完成后,由 SetupSkillTool 调用.

type StagingDB

type StagingDB struct {
	*sql.DB
}

StagingDB wraps *sql.DB to signal at every call site that the handle targets a platform-managed staging / shadow table rather than a production OLTP primary. Embedding *sql.DB means method promotion keeps the caller API ergonomic (StagingDB{db}.QueryRow works). Does not defend against StagingDB{prodDB} lies -- it is an intent marker, not a sandbox -- but it turns the staging-scope constraint from a godoc claim into a type signature that the compiler and every reader must acknowledge.

StagingDB 将 *sql.DB 封装, 在每个调用点表明该 handle 指向平台管理的 staging / 影子表而非生产 OLTP 主库. 内嵌 *sql.DB 经由 method promotion 保持调用方 API 人体工学 (StagingDB{db}.QueryRow 可直接用). 不能防 StagingDB{prodDB} 撒谎 -- 它是意图标记而非沙盒 -- 但把 staging 作用域 约束从 godoc 声明升格为类型签名, 编译器和每位阅读者都必须显式认账.

type Task

type Task struct {
	ID          string     `json:"id"`
	Title       string     `json:"title"`
	Description string     `json:"description,omitempty"`
	Status      TaskStatus `json:"status"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

Task 是一个任务.

type TaskCreateTool

type TaskCreateTool struct {
	// contains filtered or unexported fields
}

TaskCreateTool 是创建任务的工具.

func NewTaskCreateTool

func NewTaskCreateTool(store *TaskStore) *TaskCreateTool

NewTaskCreateTool 创建一个 TaskCreate 工具实例.

func (*TaskCreateTool) Description

func (t *TaskCreateTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*TaskCreateTool) Execute

func (t *TaskCreateTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 创建一个新任务.

func (*TaskCreateTool) InputSchema

func (t *TaskCreateTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*TaskCreateTool) Metadata

func (t *TaskCreateTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*TaskCreateTool) Name

func (t *TaskCreateTool) Name() string

Name 返回工具名称.

type TaskListProvider

type TaskListProvider interface {
	SharedTaskList() *tasklist.TaskList
	// ActorName 返回当前调用方的 agent 名 (用于 Claim by 字段).
	ActorName() string
}

TaskListProvider 是 tasklist 工具的后端接口. engine 包通过 context 注入实际 TaskList 实例.

type TaskListTool

type TaskListTool struct {
	// contains filtered or unexported fields
}

TaskListTool 是列出任务的工具.

func NewTaskListTool

func NewTaskListTool(store *TaskStore) *TaskListTool

NewTaskListTool 创建一个 TaskList 工具实例.

func (*TaskListTool) Description

func (t *TaskListTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*TaskListTool) Execute

func (t *TaskListTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 列出所有任务.

func (*TaskListTool) InputSchema

func (t *TaskListTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*TaskListTool) Metadata

func (t *TaskListTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*TaskListTool) Name

func (t *TaskListTool) Name() string

Name 返回工具名称.

type TaskStatus

type TaskStatus string

TaskStatus 是任务状态.

const (
	TaskStatusPending    TaskStatus = "pending"
	TaskStatusInProgress TaskStatus = "in_progress"
	TaskStatusDone       TaskStatus = "done"
	TaskStatusFailed     TaskStatus = "failed"
	TaskStatusCancelled  TaskStatus = "cancelled"
)

type TaskStore

type TaskStore struct {
	// contains filtered or unexported fields
}

TaskStore 是任务存储,线程安全.

func NewTaskStore

func NewTaskStore() *TaskStore

NewTaskStore 创建一个新的任务存储.

func (*TaskStore) Create

func (s *TaskStore) Create(title, description string) *Task

Create 创建一个新任务.

func (*TaskStore) Get

func (s *TaskStore) Get(id string) (*Task, bool)

Get 获取一个任务.

func (*TaskStore) List

func (s *TaskStore) List() []*Task

List 列出所有任务.

func (*TaskStore) Update

func (s *TaskStore) Update(id string, status TaskStatus) (*Task, bool)

Update 更新任务状态.

type TaskUpdateTool

type TaskUpdateTool struct {
	// contains filtered or unexported fields
}

TaskUpdateTool 是更新任务状态的工具.

func NewTaskUpdateTool

func NewTaskUpdateTool(store *TaskStore) *TaskUpdateTool

NewTaskUpdateTool 创建一个 TaskUpdate 工具实例.

func (*TaskUpdateTool) Description

func (t *TaskUpdateTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*TaskUpdateTool) Execute

func (t *TaskUpdateTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 更新任务状态.

func (*TaskUpdateTool) InputSchema

func (t *TaskUpdateTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*TaskUpdateTool) Metadata

func (t *TaskUpdateTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*TaskUpdateTool) Name

func (t *TaskUpdateTool) Name() string

Name 返回工具名称.

type TeammateMessageSender

type TeammateMessageSender interface {
	// SendTeammateMessage 向指定同伴 Agent 投递消息.
	//
	// msgType 推荐使用 inbox 包预定义的类型 (MsgTaskAssignment / MsgIdleNotification
	// 等 8 种), 也接受自定义字符串 (跨行业扩展 -- 金融可用 "trade_proposal",
	// 医疗可用 "diagnosis_query").
	SendTeammateMessage(ctx context.Context, to, content string, msgType inbox.MessageType) error
}

TeammateMessageSender 是 send_message 工具的后端接口. engine 包的 teamMessageSender 结构体实现此接口, 通过 context 注入到工具 Execute.

升华改进(ELEVATED): 接口而非函数指针 -- 实现可以携带状态 (router / from / 审计 hook), 消费层扩展空间大. 替代方案: func(to, content, type) error (无状态, 无法扩展).

type ToolSearchTool

type ToolSearchTool struct {
	// contains filtered or unexported fields
}

ToolSearchTool 是工具搜索工具.

func NewToolSearchTool

func NewToolSearchTool(deferred *tools.DeferredRegistry) *ToolSearchTool

NewToolSearchTool 创建一个 ToolSearch 工具实例.

deferred 是延迟加载注册表,用于搜索和激活延迟工具. 如果 deferred 为 nil,搜索将返回空结果.

func (*ToolSearchTool) Description

func (t *ToolSearchTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*ToolSearchTool) Execute

func (t *ToolSearchTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 执行工具搜索.

func (*ToolSearchTool) InputSchema

func (t *ToolSearchTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*ToolSearchTool) Metadata

func (t *ToolSearchTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*ToolSearchTool) Name

func (t *ToolSearchTool) Name() string

Name 返回工具名称.

type ValidatedTool

type ValidatedTool struct {
	// contains filtered or unexported fields
}

ValidatedTool wraps a Tool with a validator.Validator gate. Approved verdicts pass through unchanged; Block verdicts transform the inner Result into an error Result carrying the Validator's identity and reason. Warn verdicts pass through unchanged (advisory -- the circuit breaker logs the sample but the write proceeds). Inner-tool errors (err != nil or Result.IsError) skip validation entirely -- no point validating something that already failed.

Integration point for the circuit breaker: the VerdictSink callback fires on every validated call (Warn and Block) with the Validator's own Verdict; the breaker accumulates rejects and opens when a threshold is crossed (upstream TODO in separate commit).

ValidatedTool 把 Tool 挂上 validator.Validator gate. approve 的 Verdict 原样透传; Block 的 Verdict 把 inner Result 改写为 error Result 携带 Validator 身份 + reason. Warn 的 Verdict 原样透传 (advisory -- 熔断器记录样本但允许 commit). Inner 工具错误 (err != nil 或 Result.IsError) 完全跳过 validation -- 已经失败的操作不审.

熔断器集成点: VerdictSink 回调在每次 validated 调用 (Warn + Block) 以 Validator 自己的 Verdict 触发; 熔断器累积 reject, 越过阈值时 open (上游 TODO 另起 commit).

func NewValidatedTool

func NewValidatedTool(inner tools.Tool, v validator.Validator, extractor ResultExtractor, sink VerdictSink) *ValidatedTool

NewValidatedTool wraps inner with the given Validator. extractor converts inner's Result into a DiffInput (use DefaultExtractor if only Raw bytes matter, or ExtractorSQLCAS / ExtractorSQLDryRun for built-in SQL tools). sink may be nil; when non-nil it fires on every validated call for circuit-breaker observation.

Panics at construction if v or extractor is nil: the explicit panic surfaces mis-wiring at startup instead of silently deferring a nil-deref to the first Execute call. Industries that deliberately want an unchecked Tool MUST pass validator.AlwaysApprove{} so the opt-out is auditable at the call site and visible in logs.

NewValidatedTool 用给定 Validator 包装 inner. extractor 把 inner 的 Result 转为 DiffInput (仅需 Raw bytes 用 DefaultExtractor, 内置 SQL 工具用 ExtractorSQLCAS / ExtractorSQLDryRun). sink 可为 nil; 非 nil 时每次 validated 调用触发供熔断器观测.

构造期对 nil v / extractor panic: 显式 panic 让错配置在启动期暴露, 而非把 nil-deref 静默推迟到首次 Execute. 行业 platform 刻意要 unchecked Tool 必须传 validator.AlwaysApprove{}, 让 opt-out 在调用点可审计, 日志可见.

func (*ValidatedTool) Description

func (v *ValidatedTool) Description(ctx context.Context) string

Description forwards to inner.Description (context-aware).

Description 透传 inner.Description (context-aware).

func (*ValidatedTool) Execute

func (v *ValidatedTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute runs the inner tool, then the Validator on its successful Result. Sink fires on every Verdict. Block verdicts (or Validator errors) rewrite the Result into an IsError=true Result whose Output carries Validator identity / reason + the original Output.

Execute 运行 inner 工具, 然后在成功 Result 上跑 Validator. Sink 在 每次 Verdict 触发. Block verdict (或 Validator error) 会把 Result 改写为 IsError=true 的 Result, Output 含 Validator 身份 / reason + 原 Output.

func (*ValidatedTool) InputSchema

func (v *ValidatedTool) InputSchema() json.RawMessage

InputSchema forwards to inner.InputSchema.

InputSchema 透传 inner.InputSchema.

func (*ValidatedTool) Metadata

func (v *ValidatedTool) Metadata() tools.Metadata

Metadata forwards inner's MetadataProvider declaration (or the conservative default if inner does not implement it).

Metadata 透传 inner 的 MetadataProvider (或 inner 未实现时的保守 默认值).

func (*ValidatedTool) Name

func (v *ValidatedTool) Name() string

Name returns the inner tool's name. Deliberately passes through: the ValidatedTool replaces the bare tool at registration without changing how LLMs address it.

Name 返回 inner 工具名. 刻意透传: ValidatedTool 在注册点替换裸工具 但不改变 LLM 的称呼.

type VerdictSink

type VerdictSink func(toolName string, verdict validator.Verdict)

VerdictSink is the observation hook the circuit breaker subscribes to. Every ValidatedTool call that reached the Validator fires the sink with the inner tool's Name() and the produced Verdict (whether Warn or Block, Approved or not). Passing nil disables the hook.

VerdictSink 是熔断器订阅的观测 hook. 每次 ValidatedTool 到达 Validator 的调用以 inner tool 的 Name() 和产出的 Verdict (Warn / Block, Approved 或否) 触发 sink. 传 nil 关闭 hook.

type WalkGlobEngine

type WalkGlobEngine struct{}

WalkGlobEngine 使用 filepath.WalkDir 遍历文件系统搜索文件.

func NewWalkGlobEngine

func NewWalkGlobEngine() *WalkGlobEngine

NewWalkGlobEngine 创建 Walk Glob 引擎.

func (*WalkGlobEngine) Name

func (e *WalkGlobEngine) Name() string

func (*WalkGlobEngine) Search

func (e *WalkGlobEngine) Search(ctx context.Context, params *GlobParams) ([]fileWithInfo, int, error)

Search 使用 filepath.WalkDir 搜索文件.

type WebFetchTool

type WebFetchTool struct{}

WebFetchTool 是网页获取工具.

func NewWebFetchTool

func NewWebFetchTool() *WebFetchTool

NewWebFetchTool 创建一个 WebFetch 工具实例.

func (*WebFetchTool) Description

func (t *WebFetchTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*WebFetchTool) Execute

func (t *WebFetchTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 获取网页内容.

func (*WebFetchTool) InputSchema

func (t *WebFetchTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*WebFetchTool) Metadata

func (t *WebFetchTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*WebFetchTool) Name

func (t *WebFetchTool) Name() string

Name 返回工具名称.

type WebSearchTool

type WebSearchTool struct {
	// contains filtered or unexported fields
}

WebSearchTool 是网页搜索工具.

func NewWebSearchTool

func NewWebSearchTool() *WebSearchTool

NewWebSearchTool 创建一个 WebSearch 工具实例.

func (*WebSearchTool) Description

func (t *WebSearchTool) Description(ctx context.Context) string

Description 返回工具描述.

func (*WebSearchTool) Execute

func (t *WebSearchTool) Execute(ctx context.Context, input json.RawMessage, progress tools.ProgressFunc) (*tools.Result, error)

Execute 执行网页搜索. 精妙之处(CLEVER): 后端按配置优先级级联--有 Google key 用 Google,否则降级. 任何后端失败都会自动尝试下一个,最后是 DDG fallback,保证零配置也能用.

func (*WebSearchTool) InputSchema

func (t *WebSearchTool) InputSchema() json.RawMessage

InputSchema 返回工具的 JSON Schema 输入定义.

func (*WebSearchTool) Metadata

func (t *WebSearchTool) Metadata() tools.Metadata

Metadata 返回工具元数据.

func (*WebSearchTool) Name

func (t *WebSearchTool) Name() string

Name 返回工具名称.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL