Documentation
¶
Overview ¶
aborted.go 复刻官方 session-checkpoint-policy 的"派发前取消"语义:当请求在 真正进入工具体之前就已被取消时,返回一个带稳定错误码的 isError 结果,而不是 带着半截状态进入工具实现。
arguments.go 复刻官方 agent-loop 的 parseArguments:空输入映射为空对象, 合法 JSON 解析为对应值,非法 JSON 不报错而是原样保留为字符串(交给工具层 自行处理/报错),避免在调度边界因模型输出的格式问题直接中断整轮。
本文件对应任务 M25:ToolRunContext deferContext + concludeTurn。
对齐上游:packages/core/tools/types ToolRunContext
设计要点:
- ToolRunContext 提供工具执行期间的运行时上下文(Meta + defer 回调注册);
- concludeTurn 是终止当前 turn 的权威标记:被 goal report_blocker 等调用后, Agent 循环在下一条是否需要继续时据此结束 turn;
- 通过上下文传播:pipeline 内的工具实现可调用 Agent 级 conclude 控制。
本文件实现工具流水线中的「单调守卫」(Monotonic Guard)。
上游语义:pre-execute 是可被多个策略插件重排的策略层,而单调守卫是夹在 pre-execute 与 execute 之间的最终防线——决策只允许朝「更确定 / 更严格」方向 收敛,不允许被后续监听器撤销或放宽。
偏序关系(从严到宽):deny > ask > allow
- 初始未定(ask:等待后续策略);
- 一旦收敛为 deny,任何试图改回 allow/ask 的更新都被拒绝(fail closed);
- allow 之后仍可被更靠后的安全策略升级为 deny(安全优先,可收紧不可放宽)。
本文件对应任务 M23:Tool Execution 四级 Waterfall 链。
对齐上游:packages/core/tools
一次工具调用按四级流水线执行,每一级都是一条可插拔中间件链(复用 pkg/waterfall):
- pre-execute:进入前的拦截/改写(deny 拒绝、换参、注入上下文);
- execute:真正调用工具实现(可中途换 signal 取消);
- post-execute:结果后处理(accept/block、截断、附加 meta);
- result:最终结果加工(统一包装、打点)。
与上游语义对齐:pre-execute 返回 deny → 该调用不执行且结果标记 isError; execute 中换 signal=cancel → post-execute 可 block → 结果带上 isError。
pool.go 复刻官方 agent-loop 的有界滚动并行池:同一 step 内标记为 parallel 的 工具调用最多以 DefaultMaxParallelToolCalls 的并发同时在途,结果严格按模型给出 的顺序归位(并发执行、有序提交)。这里提供与具体工具无关的泛型执行器。
本文件对应任务 H06:Tool Pipeline 对象池(ExecContext / Meta map 热路径结构用 sync.Pool 回收复用)。
设计原则:
- 仅在【显式开启 pooled 模式】(Pipeline.SetPooled(true))后生效,默认 Run 行为不变;
- pool 只回收 ExecContext 及其内部的 Meta map(每次 Run 都会 new 一个 map,是最大 分配热点);
- **ToolCallResult 不禁池**:Run 的返回 `*ToolCallResult` 会交由调用方持有,若从池中 取出复用,下一次 Run 会改写调用方正在引用的上一次结果 → 数据竞争/语义错误。 因此 pooled 模式跑完后把 Result 字段【拷贝到新对象】再返回(安全,调用方可自由持有);
- 复用安全:Get 后必做的字段清零(Result/Signal/Denied/Meta/Ctx),杜绝脏复用。
本文件对应任务 M22:PreToolDecision 三态(allow/deny/ask)。
对齐上游:packages/core/tools/pre-execute
设计要点:
- PreToolDecision 是工具 pre-execute 阶段的三态决策(allow / deny / ask), 复用了 M27 pkg/approval.Decision;
- PreDecisionMiddleware 是一条 pre-execute 中间件:由 DecisionFunc 给出三态, deny → 短路拒绝(结果 IsError、工具不执行);ask → 交给 AskFunc 请求用户, 用户"准许"只放行本次调用(allowed-once 语义),下一次同工具调用继续 ask, 不做按工具名的永久放行;
- DecisionFunc 可由 pkg/approval.Service.Evaluate 映射而来(M27 已实现三层 override 与 ask→allowed-once 决策),M22 负责把它接入四级 Waterfall 的 pre 级。
本文件对应任务 M47:Tool Presentation 中立 vocabulary(9 种 card)。
对齐上游:packages/core/tools/src/presentation.ts
设计要点:
- ToolCallView 与 ToolResultView 是「中立」的渲染意图词汇,工具通过 presentCall / presentResult 声明自身卡片,UI 按其 card 切换渲染,绝不特判工具名;
- ToolCallView 3 种:generic / terminal / diff;ToolResultView 6 种:generic / terminal / diff / search(matches|paths) / read / web(search|fetch) → 合计 9 种 card;
- 自定义工具可提供自定义 card 类型(card 判别为 string,不封闭)。
本文件复刻官方 packages/core/tools/src/ptc.ts 的核心桥接语义(非完整并发调度器)。
PTC(Programmatic Tool Calling)是官方四种运行模式之一:模型不再逐个发出工具调用, 而是写一段程序(async 函数体),程序通过 `tools.name(args)` 组合多步调用。
核心链路:
- run_code 工具入参 code(程序)+ description(摘要);
- 把当前工具集映射为一个 coderuntime 绑定命名空间 "tools",每个工具成为一个 BindingFunction——函数内部走本项目的工具 Pipeline(因此权限/沙箱/单调守卫 对程序内调用同样生效);
- 委托 coderuntime.Runtime 执行程序,得到 logs + 完成值;
- 整理为模型可见文本(logs 与 return 值拼接),只有此外层精选结果进入模型历史。
取舍:上游 createRunCodeTool 内含复杂的 parallel/exclusive 并发调度器,深度耦合 ToolRuntime 分阶段接口。Go 侧采用同步桥接:程序内每次工具调用在对应 binding 内 同步走完流水线;需要并发时由具体 CodeRuntime 后端在其执行模型内安排。
本文件复刻官方 guard/repeat-tool-reminder 的纯逻辑部分:建议性连续重复调用检测。 它不否决、不改写调用,只在模型连续以相同参数重复同一工具达到阈值时给出提醒, 帮助打破"原地打转"。检测用的链键始终比较完整的规范化参数,避免属性顺序不同就 被误判为不同调用。
本文件对应任务 M24:Tool Restriction allow/deny。
对齐上游:packages/core/tools/restriction
设计要点:
- Restriction 是某一作用域层的工具掩码(allow/exempt 与 deny 两个集合);
- RestrictionSet 以「host → 最近作用域」的有序层栈承载多层掩码(层范式对齐 M03 scope: host 最外层、作用域层越近越优先),解析采用 nearest-scope-wins: 从最近层向 host 层逐层查找,第一个「提及」该工具的层决定放行/拒绝;
- 因此「host 层 deny + scope 层 exempt」后工具恢复可用;两层相交(host deny + scope deny) 结果为拒绝;未提及则默认放行;
- 应用场景:Subagent 父限子能力(父在 host/外层 deny)、Preset 隐藏工具(Filter)。
本文件实现任务 S16:Output Retention(tool result canonical value 保留到 committed)。
对齐上游:packages/core/tools output retention gate
设计要点:
- 大工具结果(如 bash 输出 / 文件读取全文)可能在 post-execute 阶段仍被多个 消费者并发读取(模型上下文组装 / 会话展示 / 审计)。若结果值被就地改写或 提前释放,会导致读到缺失/截断字节。
- ResultRetention 是一个以 brand.ToolCallID 为键的只读保留仓库:
- Retain:在工具「提交(committed)」时把 canonical 字节做不可变副本入仓;
- Read:并发安全地返回**完整独立副本**,读方拿到的是可安全持有的字节切片, 多读者互不干扰(RWMutex 保护 + 每次 append 拷贝);
- Remove:语义上标记逻辑删除(供会话清理),不影响已完成安全的读;
- Read 返回的是每个 reader 各自独立的切片拷贝,因此不存在"两个 reader 互相截断" 的可能,满足验收「并发 reader 各得完整字节」。
Package tools 提供工具定义与执行的通用接缝。
本文件对应任务 M48:DefineTool JSON Schema 强校验子集。
对齐上游:packages/core/tools DefineTool Schema
设计动机:
- Agent 的工具调用参数、subagent / workflow 的结构化输出都需要一套严格的 JSON Schema 校验子集,保证 LLM 生成的参数在进入 execute 前就被验证;
- 与原版 1:1 对齐的关键语义:oneOf / additionalProperties=false / items / enum / const / default / examples / number·string·array 约束;
- 不支持的 schema 关键字必须在 define 时报错(fail-closed),而不是静默忽略, 否则模型侧与执行侧会对参数语义产生不一致理解。
本文件复刻官方 guard/timeout-policy:协作式工具调用超时。工具声明 TimeoutMs 并 承诺尊重 ctx;包装器武装截止时间,自己的计时器触发时把结果映射为结构化 TOOL_TIMEOUT,而不是与工具的执行相互竞争或丢弃。
Go 的固有限制:无法强杀 goroutine。超时后包装器立即返回 TOOL_TIMEOUT,被调用的 goroutine 只有在尊重 ctx 时才会退出;不尊重则会继续在后台运行(可能泄漏)。因此 这是"协作式"超时——工具实现必须监听 ctx.Done()。
Index ¶
- Constants
- Variables
- func Canonicalize(value any) []byte
- func CanonicalizeArgs(input map[string]any) string
- func CardOf(v any) string
- func DetailedReminder(toolName string, count int, canonical string, previewCap int) string
- func Equal(a, b []byte) bool
- func HitThreshold(count int, thresholds []int) bool
- func ParseArguments(raw string) any
- func PreDecisionMiddleware(decide DecisionFunc, ask AskFunc) waterfall.Handler[ExecContext]
- func RunParallel[T any](ctx context.Context, tasks []func(context.Context) (T, error), ...) ([]T, error)
- func WithConclude(ctx context.Context, fn ConcludeFunc) context.Context
- type AskFunc
- type ConcludeFunc
- type DecisionFunc
- type DiffCallView
- type DiffResultView
- type ExecContext
- type FileDiff
- type FileLocation
- type GenericCallView
- type GenericResultView
- type JsonSchemaNode
- type MonotonicGuard
- type Pipeline
- func (p *Pipeline) Lookup(name string) *Tool
- func (p *Pipeline) PooledState() bool
- func (p *Pipeline) Run(ctx context.Context, req *ToolCallRequest, tool *Tool) *ToolCallResult
- func (p *Pipeline) RunPooled(ctx context.Context, req *ToolCallRequest, tool *Tool) *ToolCallResult
- func (p *Pipeline) SetPooled(enabled bool) *Pipeline
- func (p *Pipeline) Tools() []*Tool
- func (p *Pipeline) UseExecute(h ...waterfall.Handler[ExecContext]) *Pipeline
- func (p *Pipeline) UsePost(h ...waterfall.Handler[ExecContext]) *Pipeline
- func (p *Pipeline) UsePre(h ...waterfall.Handler[ExecContext]) *Pipeline
- func (p *Pipeline) UseResult(h ...waterfall.Handler[ExecContext]) *Pipeline
- func (p *Pipeline) WithTool(tool *Tool) *Pipeline
- type PreToolDecision
- type ReadFileLine
- type ReadResultView
- type RepeatState
- type Restriction
- type RestrictionLayer
- type RestrictionSet
- func (rs *RestrictionSet) Allowed(tool string) bool
- func (rs *RestrictionSet) Denied(tool string) bool
- func (rs *RestrictionSet) Filter(tools []*Tool) []*Tool
- func (rs *RestrictionSet) Host(mask Restriction)
- func (rs *RestrictionSet) Layers() []RestrictionLayer
- func (rs *RestrictionSet) Scope(key string, mask Restriction)
- func (rs *RestrictionSet) SetLayer(key string, mask Restriction)
- type ResultRetention
- type RetainedEntry
- type RunCodeInput
- type RunCodeOutput
- type SchemaType
- type SearchFileMatches
- type SearchLineMatch
- type SearchResultView
- type Signal
- type TerminalCallView
- type TerminalResultView
- type TimeoutError
- type Tool
- type ToolCallKind
- type ToolCallRequest
- type ToolCallResult
- type ToolCallView
- type ToolExecuteFunc
- type ToolLookup
- type ToolResultView
- type ToolRunContext
- func (tc *ToolRunContext) ConcludeTurn(reason string) bool
- func (tc *ToolRunContext) Context() context.Context
- func (tc *ToolRunContext) DeferContext(fn func())
- func (tc *ToolRunContext) GetMeta(k string) (any, bool)
- func (tc *ToolRunContext) IsConcluded() bool
- func (tc *ToolRunContext) SetMeta(k string, v any)
- type WebResultView
- type WebSource
Constants ¶
const ( PreAllow = approval.DecideAllow PreDeny = approval.DecideDeny PreAsk = approval.DecideAsk )
决策常量(复用 approval 的语义)。
const AbortedBeforeDispatch = "TOOL_ABORTED_BEFORE_DISPATCH"
AbortedBeforeDispatch 是"工具在派发前被取消"的稳定错误码。
const AbortedBeforeDispatchMessage = "tool call aborted before dispatch"
AbortedBeforeDispatchMessage 是模型可见的提示文本。
const DefaultMaxParallelToolCalls = 10
DefaultMaxParallelToolCalls 是单个 agent step 内并行工具调用的默认在途上限。
const GentleReminder = "你在以完全相同的参数重复同一工具调用。请先仔细分析上一次结果," +
"若任务未完成,换一种方式或换一组参数,而不是重复调用。"
GentleReminder 是首个阈值的温和提醒。
const RunCodeName = "run_code"
RunCodeName 是 PTC 模式工具对模型暴露的名字。
const ToolTimeoutCode = "TOOL_TIMEOUT"
ToolTimeoutCode 是超时的结构化错误码(对齐官方 TOOL_TIMEOUT)。
Variables ¶
var DefaultRepeatThresholds = []int{3, 5, 8}
DefaultRepeatThresholds 是默认触发阈值(温和 → 详细逐级升级)。
var ErrGuardRelaxed = errors.New("tools monotonic guard: cannot relax an already stricter decision")
ErrGuardRelaxed 表示单调守卫拒绝了一次"放宽已收敛决策"的更新。
var ErrToolTimeout = errors.New("tool call timed out")
ErrToolTimeout 表示工具调用超过自身声明的预算。
Functions ¶
func Canonicalize ¶
Canonicalize 把一次工具结果 Value 归一化为 canonical 字节。 支持 []byte / string / 其余任意值 JSON 序列化;nil 返回空。
func CanonicalizeArgs ¶
CanonicalizeArgs 返回参数的规范化字符串(深度 key 排序后序列化)。
func DetailedReminder ¶
DetailedReminder 生成后续阈值的详细提醒。
func PreDecisionMiddleware ¶
func PreDecisionMiddleware(decide DecisionFunc, ask AskFunc) waterfall.Handler[ExecContext]
PreDecisionMiddleware 构造一条 pre-execute 决策中间件。
行为:
- PreAllow:放行(不做任何改动);
- PreDeny:写 ec.Denied=true 短路,结果标记 isError;
- PreAsk:调用 ask;准许 → 放行本次(可在 Meta 记录 allowedOnce 审计); 拒绝/失败 → 短路 deny。
func RunParallel ¶
func RunParallel[T any](ctx context.Context, tasks []func(context.Context) (T, error), maxConcurrent int) ([]T, error)
RunParallel 以最多 maxConcurrent 的并发执行 tasks,返回值严格按 tasks 的输入 顺序排列。任一任务返回错误,立即取消其余尚未开始/仍在运行的任务并返回该错误。
func WithConclude ¶
func WithConclude(ctx context.Context, fn ConcludeFunc) context.Context
WithConclude 将 conclude 回调注入 context。
Types ¶
type AskFunc ¶
type AskFunc func(req *ToolCallRequest) (bool, error)
AskFunc 处理 ask 决策:向用户询问并返回是否放行本次调用。 ASK 只对这一次调用放行(allowed-once),返回 true 即执行本次。
func AskFromApproval ¶
func AskFromApproval(evaluate func(req *ToolCallRequest) (approval.Decision, error)) AskFunc
AskFromApproval 把 M27 审批服务的 ask(UQ 询问)映射为 AskFunc。 传入的 evaluate 需返回已经 resolved 的 allow/deny;当它返回 Ask 时, 这里透传给内部 ask 解析。为简化接线,此处假定 evaluate 已把 ask 折叠为 allow/deny。
type ConcludeFunc ¶
type ConcludeFunc func(reason string)
ConcludeFunc 是结束当前 turn 的回调(由 Agent 注册)。
func ConcludeFrom ¶
func ConcludeFrom(ctx context.Context) ConcludeFunc
ConcludeFrom 从 ctx 取 conclude 回调;不存在返回 nil。
type DecisionFunc ¶
type DecisionFunc func(req *ToolCallRequest) (PreToolDecision, error)
DecisionFunc 对一次工具调用给出三态决策。
func DecisionFromApproval ¶
func DecisionFromApproval(decide func(req *ToolCallRequest) (approval.Decision, error)) DecisionFunc
DecisionFromApproval 把 M27 审批服务映射为 DecisionFunc。 approval.Service.Evaluate 已自行处理 ask→allowed-once(内部调用 UQ), 因此这里直接透传它的 Decision,且不重复 ask。
type DiffCallView ¶
type DiffCallView struct {
Card string `json:"card"`
Title string `json:"title"`
Diffs []FileDiff `json:"diffs"`
Locations []FileLocation `json:"locations,omitempty"`
}
DiffCallView 是内联 diff 卡片(创建/修改文件)。
func NewDiffCallView ¶
func NewDiffCallView(title string, diffs []FileDiff) *DiffCallView
NewDiffCallView 构造 diff 调用卡片。
type DiffResultView ¶
type DiffResultView struct {
Card string `json:"card"`
Title string `json:"title,omitempty"`
Diffs []FileDiff `json:"diffs"`
}
DiffResultView 是完成文件变更的 diff 卡片。
type ExecContext ¶
type ExecContext struct {
// Request 原始请求。
Request *ToolCallRequest
// Result 结果(由各阶段填充)。
Result *ToolCallResult
// Signal 运行信号(execute 级可替换)。
Signal Signal
// Denied 是否被 pre/post 级拒绝。
Denied bool
// Meta 附加元数据(post 级可写入,供展示/审计)。
Meta map[string]any
// Ctx 携带进入本次执行的父 ctx(H01:取消/超时/追踪 propagate 到工具实现)。
Ctx context.Context
}
ExecContext 是贯穿四级链的共享上下文(payload)。
func ExecContextFrom ¶
func ExecContextFrom(ctx context.Context) (*ExecContext, bool)
ExecContextFrom 从 ctx 中取出 ExecContext(工具实现内可用)。
type FileDiff ¶
type FileDiff struct {
// Path 文件路径。
Path string `json:"path"`
// OldText 变更前内容;新文件/覆盖时(调用时无先前内容)为 nil 表示。
OldText *string `json:"oldText,omitempty"`
// NewText 变更后内容。
NewText string `json:"newText"`
}
FileDiff 是工具即将做出的单文件变更(用于内联 diff 渲染)。
type FileLocation ¶
type FileLocation struct {
// Path 工具操作的路径(模型向路径)。
Path string `json:"path"`
// Line 可选的 1-based 关注行号。
Line int `json:"line,omitempty"`
}
FileLocation 是工具读取/修改的文件位置(供编辑器"跟随")。
type GenericCallView ¶
type GenericCallView struct {
Card string `json:"card"`
Title string `json:"title"`
Kind ToolCallKind `json:"kind,omitempty"`
RawInput any `json:"rawInput,omitempty"`
Content []any `json:"content,omitempty"`
Locations []FileLocation `json:"locations,omitempty"`
}
GenericCallView 是默认卡片:带标题的工具调用行 + 可选类别/突出输入/附加内容/位置。
func NewGenericCallView ¶
func NewGenericCallView(title string) *GenericCallView
NewGenericCallView 构造 generic 调用卡片。
type GenericResultView ¶
type GenericResultView struct {
Card string `json:"card"`
Title string `json:"title,omitempty"`
Content []any `json:"content,omitempty"`
}
GenericResultView 是默认完成卡片。
func NewGenericResultView ¶
func NewGenericResultView() *GenericResultView
NewGenericResultView 构造 generic 结果卡片。
type JsonSchemaNode ¶
type JsonSchemaNode struct {
// Type 声明节点类型。
Type SchemaType `json:"type,omitempty"`
// Description 提供给模型阅读的字段说明。
Description string `json:"description,omitempty"`
// Properties 仅 object 使用:属性名 → 子 schema。
Properties map[string]*JsonSchemaNode `json:"properties,omitempty"`
// Required 仅 object 使用:必填属性名列表。
Required []string `json:"required,omitempty"`
// AdditionalProperties 仅 object 使用:
// - nil:允许任意额外属性(默认);
// - false:拒绝任何未声明的属性(严格模式,与原版语义一致)。
AdditionalProperties *bool `json:"additionalProperties,omitempty"`
// Items 仅 array 使用:元素子 schema。
Items *JsonSchemaNode `json:"items,omitempty"`
// Enum 限制取值必须属于该列表(与 const 互斥,若都设置则 Enum 优先)。
Enum []any `json:"enum,omitempty"`
// Const 限制取值必须严格等于该常量。
Const any `json:"const,omitempty"`
// Default 提供模型可参考的默认值(不参与校验)。
Default any `json:"default,omitempty"`
// Examples 提供模型可参考的示例(不参与校验)。
Examples []any `json:"examples,omitempty"`
// OneOf 允许值匹配其中任一子 schema。
OneOf []*JsonSchemaNode `json:"oneOf,omitempty"`
// --- number/integer 约束 ---
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
ExclusiveMinimum *bool `json:"exclusiveMinimum,omitempty"`
ExclusiveMaximum *bool `json:"exclusiveMaximum,omitempty"`
// --- string 约束 ---
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
// --- array 约束 ---
MinItems *int `json:"minItems,omitempty"`
MaxItems *int `json:"maxItems,omitempty"`
}
JsonSchemaNode 是 DefineTool 支持的 JSON Schema 强校验子集。 字段与上游 packages/core/tools 的 DefineTool Schema 1:1 对应。
func Compile ¶
func Compile(raw []byte) (*JsonSchemaNode, error)
Compile 从 JSON 字节解析 JsonSchemaNode,并拒绝不支持的 schema 关键字。 这是 define 工具时的唯一入口,保证 fail-closed:遇到未知关键字直接报错。
func Infer ¶
func Infer(v any) (*JsonSchemaNode, error)
Infer 从任意 Go 值推断 JsonSchemaNode(对应上游 DefineTool 的 INFER 能力)。 支持基础类型 / 切片 / map / 结构体。无法推断的类型返回错误。
func (*JsonSchemaNode) Marshal ¶
func (n *JsonSchemaNode) Marshal() ([]byte, error)
Marshal 输出标准 JSON Schema 文本(properties/required/enum 均按字典序,保证确定性)。
func (*JsonSchemaNode) Validate ¶
func (n *JsonSchemaNode) Validate(v any) error
Validate 校验一个 Go 值是否符合该 schema。返回 nil 表示通过。
type MonotonicGuard ¶
type MonotonicGuard struct {
// contains filtered or unexported fields
}
MonotonicGuard 是一次性的决策收敛器,服务于单次工具调用。
func NewMonotonicGuard ¶
func NewMonotonicGuard() *MonotonicGuard
NewMonotonicGuard 创建守卫,初始为未定(ask 语义)。
func (*MonotonicGuard) Decision ¶
func (g *MonotonicGuard) Decision() PreToolDecision
Decision 返回当前收敛到的决策。
func (*MonotonicGuard) IsDenied ¶
func (g *MonotonicGuard) IsDenied() bool
IsDenied 是否已收敛为拒绝(fail-closed 判定)。
func (*MonotonicGuard) Update ¶
func (g *MonotonicGuard) Update(next PreToolDecision) error
Update 尝试用 next 收敛当前决策。
- 首次赋值总是接受;
- 后续仅当 next 不严格宽于当前(秩 >= 当前)时接受;
- 试图把已更严的决策放宽 → 返回 ErrGuardRelaxed,且保持原决策不变。
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
Pipeline 是四级工具执行流水线。
func (*Pipeline) PooledState ¶
PooledState 返回当前 pooled 模式状态(观测/测试用)。
func (*Pipeline) Run ¶
func (p *Pipeline) Run(ctx context.Context, req *ToolCallRequest, tool *Tool) *ToolCallResult
Run 执行一次工具调用,走完四级流水线,返回结果。 若已通过 SetPooled(true) 启用对象池,则内部走 RunPooled(等价语义,复用热结构)。
func (*Pipeline) RunPooled ¶
func (p *Pipeline) RunPooled(ctx context.Context, req *ToolCallRequest, tool *Tool) *ToolCallResult
RunPooled 使用对象池路径执行一次工具调用,返回结果。 语义与 Run 完全一致,仅内部复用 ExecContext / Meta map,减少 GC 压力。 Result 为新建对象,调用方可安全持有/修改。
func (*Pipeline) SetPooled ¶
SetPooled 设置是否启用 H06 对象池回收(opt-in,默认关闭)。 开启后 Run 复用 ExecContext 及其 Meta map,降低 GC;返回的 Result 仍为每次新建, 调用方可安全持有。
func (*Pipeline) UseExecute ¶
func (p *Pipeline) UseExecute(h ...waterfall.Handler[ExecContext]) *Pipeline
UseExecute 追加 execute 中间件(包裹工具实现,可换 signal)。
func (*Pipeline) UsePost ¶
func (p *Pipeline) UsePost(h ...waterfall.Handler[ExecContext]) *Pipeline
UsePost 追加 post-execute 中间件(accept/block/截断/加 meta)。
func (*Pipeline) UsePre ¶
func (p *Pipeline) UsePre(h ...waterfall.Handler[ExecContext]) *Pipeline
UsePre 追加 pre-execute 中间件(拦截/改写入参,可 deny)。
type PreToolDecision ¶
PreToolDecision 是一次工具调用的 pre-execute 决策(三态)。
type ReadFileLine ¶
ReadFileLine 是带 1-based 行号的单行文件内容。
type ReadResultView ¶
type ReadResultView struct {
Card string `json:"card"`
Title string `json:"title,omitempty"`
Path string `json:"path"`
Offset int `json:"offset"`
Lines []ReadFileLine `json:"lines"`
TotalLines int `json:"totalLines"`
Lang string `json:"lang,omitempty"`
Content []any `json:"content,omitempty"`
}
ReadResultView 是带行号代码视图的完成读卡片。
func NewReadResultView ¶
func NewReadResultView(path string, offset int, lines []ReadFileLine, totalLines int) *ReadResultView
NewReadResultView 构造读文件结果卡片。
type RepeatState ¶
type RepeatState struct {
// contains filtered or unexported fields
}
RepeatState 是单个代理的连续重复链状态。
type Restriction ¶
type Restriction struct {
// Allow 显式放行(exempt)的工具名集合。
Allow []string `json:"allow,omitempty"`
// Deny 显式拒绝的工具名集合。
Deny []string `json:"deny,omitempty"`
}
Restriction 是单层的工具访问掩码。
- Allow:显式放行(exempt)的工具名集合;命中即覆盖外层 deny;
- Deny:显式拒绝的工具名集合。
func RestrictionAllow ¶
func RestrictionAllow(names ...string) Restriction
RestrictionAllow 便捷构造一个仅放行的掩码。
func RestrictionDeny ¶
func RestrictionDeny(names ...string) Restriction
RestrictionDeny 便捷构造一个仅拒绝的掩码。
type RestrictionLayer ¶
type RestrictionLayer struct {
// Key 层域名(host / session:xxx / user:xxx / subagent:xxx),仅审计用。
Key string
// Mask 本层掩码。
Mask Restriction
}
RestrictionLayer 是带层域名的掩码层。
type RestrictionSet ¶
type RestrictionSet struct {
// contains filtered or unexported fields
}
RestrictionSet 是分层工具掩码注册表。
func (*RestrictionSet) Allowed ¶
func (rs *RestrictionSet) Allowed(tool string) bool
Allowed 判断某工具是否允许使用(nearest-scope-wins)。
规则:从最近层向 host 层逐层查找,第一个提及该工具(出现在本层 Allow 或 Deny)的层 决定结果:Allow 命中 → true(exempt),Deny 命中 → false;所有层均未提及 → true(默认放行)。
func (*RestrictionSet) Denied ¶
func (rs *RestrictionSet) Denied(tool string) bool
Denied 是 Allowed 的取反(供审计/断言)。
func (*RestrictionSet) Filter ¶
func (rs *RestrictionSet) Filter(tools []*Tool) []*Tool
Filter 应用掩码过滤工具列表(用于 Preset 隐藏工具 / Subagent 限制子能力)。 返回保留的(Allowed 为 true)工具,保持输入顺序。
func (*RestrictionSet) Host ¶
func (rs *RestrictionSet) Host(mask Restriction)
Host 设置 host 层掩码(最外层)。
func (*RestrictionSet) Layers ¶
func (rs *RestrictionSet) Layers() []RestrictionLayer
Layers 返回 host→最近的层浅拷贝(审计/测试用)。
func (*RestrictionSet) Scope ¶
func (rs *RestrictionSet) Scope(key string, mask Restriction)
Scope 追加一个作用域层掩码(追加后成为最近的层,高于所有外层)。 key 形如 "session:xxx" / "user:xxx" / "subagent:xxx"。
func (*RestrictionSet) SetLayer ¶
func (rs *RestrictionSet) SetLayer(key string, mask Restriction)
SetLayer 追加/更新指定层掩码。已存在的同名层被覆盖为最近层;新层追加到最末(最近)。
type ResultRetention ¶
type ResultRetention struct {
// contains filtered or unexported fields
}
ResultRetention 保留工具结果 canonical value,供并发 reader 全量读取。
func (*ResultRetention) Read ¶
func (r *ResultRetention) Read(callID string) ([]byte, bool)
Read 返回指定调用 ID 的**完整独立副本**。不存在或未保留返回 (nil, false)。
func (*ResultRetention) Remove ¶
func (r *ResultRetention) Remove(callID string)
Remove 逻辑删除一条保留记录(读已完成者可继续持有已返回的副本)。
func (*ResultRetention) Retain ¶
func (r *ResultRetention) Retain(callID string, value []byte)
Retain 在 committed 阶段保留某工具调用的 canonical 字节(不可变副本)。 相同的 callID 反复保留采用最后一次(last-write-wins)。
func (*ResultRetention) RetainResult ¶
func (r *ResultRetention) RetainResult(res *ToolCallResult)
RetainResult 便捷版:把 ToolCallResult 的 canonical 值保留到仓库。
type RetainedEntry ¶
type RetainedEntry struct {
// contains filtered or unexported fields
}
RetainedEntry 是仓库中的一条保留记录。raw 为不可变字节;retained 标记逻辑存在。
type RunCodeInput ¶
type RunCodeInput struct {
// Code 程序:async 函数体(顶层 await/return 可用)。
Code string `json:"code"`
// Description 程序作用的简短摘要(主动语态)。
Description string `json:"description"`
}
RunCodeInput 是 run_code 的入参。
type RunCodeOutput ¶
RunCodeOutput 是 run_code 的结构化输出。
func PresentRunCodeResult ¶
func PresentRunCodeResult(res *coderuntime.RunResult) RunCodeOutput
PresentRunCodeResult 把运行结果整理为模型可见文本:logs 按序拼接,再附完成值。
type SchemaType ¶
type SchemaType string
SchemaType 是 JSON Schema 支持的类型名。
const ( TypeString SchemaType = "string" TypeNumber SchemaType = "number" TypeInteger SchemaType = "integer" TypeBoolean SchemaType = "boolean" TypeArray SchemaType = "array" TypeObject SchemaType = "object" TypeNull SchemaType = "null" )
支持的 JSON Schema 类型枚举。
type SearchFileMatches ¶
type SearchFileMatches struct {
Path string `json:"path"`
Matches []SearchLineMatch `json:"matches"`
}
SearchFileMatches 是某文件的分组匹配。
type SearchLineMatch ¶
SearchLineMatch 是文件内单条匹配行。
type SearchResultView ¶
type SearchResultView struct {
Card string `json:"card"`
Shape string `json:"shape"` // "matches" | "paths"
Title string `json:"title,omitempty"`
Files []SearchFileMatches `json:"files,omitempty"`
Paths []string `json:"paths,omitempty"`
Truncated bool `json:"truncated"`
Total int `json:"total"`
}
SearchResultView 是完成搜索卡片(matches/paths 两种 shape)。
func NewSearchMatchesView ¶
func NewSearchMatchesView(files []SearchFileMatches, truncated bool, total int) *SearchResultView
NewSearchMatchesView 构造按文件分组的搜索匹配卡片。
func NewSearchPathsView ¶
func NewSearchPathsView(paths []string, truncated bool, total int) *SearchResultView
NewSearchPathsView 构造扁平路径列表的搜索卡片。
type TerminalCallView ¶
type TerminalCallView struct {
Card string `json:"card"`
Title string `json:"title"`
Description string `json:"description,omitempty"`
Cwd string `json:"cwd,omitempty"`
}
TerminalCallView 是终终端命令卡片(cwd 作为头部)。
func NewTerminalCallView ¶
func NewTerminalCallView(command string) *TerminalCallView
NewTerminalCallView 构造 terminal 调用卡片。
type TerminalResultView ¶
type TerminalResultView struct {
Card string `json:"card"`
Title string `json:"title,omitempty"`
Output string `json:"output,omitempty"`
ExitCode *int `json:"exitCode,omitempty"`
Signal string `json:"signal,omitempty"`
}
TerminalResultView 是终端完成状态。
func NewTerminalResultView ¶
func NewTerminalResultView(output string) *TerminalResultView
NewTerminalResultView 构造 terminal 结果卡片。
type TimeoutError ¶
TimeoutError 是超时的结构化错误,携带 TOOL_TIMEOUT 码供重试/沙箱层路由。
type Tool ¶
type Tool struct {
// Name 工具名(供 LLM 调用)。
Name string
// Description 工具描述(进 prompt)。
Description string
// Schema 参数 JSON Schema(进 prompt + 入参校验)。
Schema *JsonSchemaNode
// TimeoutMs 协作式超时预算(0 = 不限);工具应尊重 ctx,超时映射为 TOOL_TIMEOUT。
TimeoutMs int
// Execute 具体实现。
Execute ToolExecuteFunc
}
Tool 是工具定义(name/schema/execute)。
func NewRunCodeTool ¶
func NewRunCodeTool(runtime coderuntime.Runtime, lookup ToolLookup, pipeline *Pipeline) *Tool
NewRunCodeTool 构造 PTC 的 run_code 桥接工具。
- runtime:代码执行后端(实现 coderuntime.Runtime,由使用方注入);
- lookup:按名查找工具;
- pipeline:每次程序内工具调用所走的流水线(nil 时用仅含工具实现的最小链)。
type ToolCallKind ¶
type ToolCallKind string
ToolCallKind 是工具调用的类别,UI 据此选图标/样式;other 为缺省。
const ( CallKindRead ToolCallKind = "read" CallKindEdit ToolCallKind = "edit" CallKindDelete ToolCallKind = "delete" CallKindMove ToolCallKind = "move" CallKindSearch ToolCallKind = "search" CallKindExecute ToolCallKind = "execute" CallKindFetch ToolCallKind = "fetch" CallKindOther ToolCallKind = "other" )
工具调用类别枚举。
type ToolCallRequest ¶
type ToolCallRequest struct {
// CallID 调用 ID(与 tool/call → tool/result 配对)。
CallID brand.ToolCallID
// Tool 工具名。
Tool string
// Input 解析后的参数。
Input map[string]any
}
ToolCallRequest 是一次工具调用请求。
type ToolCallResult ¶
type ToolCallResult struct {
// CallID 与请求配对。
CallID brand.ToolCallID
// IsError 是否视为失败(deny/block/cancel 或工具返回错误)。
IsError bool
// Value 结构化结果值。
Value any
// Error 错误信息(IsError 时填充)。
Error string
// ErrorCode 稳定错误码(可选,用于路由/重放)。
ErrorCode string
}
ToolCallResult 是一次工具调用的结果。
func AbortedBeforeDispatchResult ¶
func AbortedBeforeDispatchResult(callID brand.ToolCallID) *ToolCallResult
AbortedBeforeDispatchResult 构造派发前取消的结果。
type ToolCallView ¶
type ToolCallView interface {
// contains filtered or unexported methods
}
ToolCallView 是待执行的调用展示(card 判别联合)。
type ToolExecuteFunc ¶
ToolExecuteFunc 是工具实现的执行函数。
func WrapTimeout ¶
func WrapTimeout(exec ToolExecuteFunc, timeoutMs int) ToolExecuteFunc
WrapTimeout 用 timeoutMs 包装一个执行函数;timeoutMs<=0 时原样返回。
type ToolLookup ¶
ToolLookup 按名查找已注册工具(桥接层用它把工具集暴露给程序)。
type ToolResultView ¶
type ToolResultView interface {
// contains filtered or unexported methods
}
ToolResultView 是完成调用展示(card 判别联合)。9 种 card 覆盖 generic/terminal/ diff/search(matches)/search(paths)/read/web(search)/web(fetch),另加 generic。
type ToolRunContext ¶
type ToolRunContext struct {
// contains filtered or unexported fields
}
ToolRunContext 是工具执行期间的运行时上下文。
func NewToolRunContext ¶
func NewToolRunContext(conclude ConcludeFunc) *ToolRunContext
NewToolRunContext 创建工具运行上下文。
func ToolRunContextFrom ¶
func ToolRunContextFrom(ctx context.Context) (*ToolRunContext, bool)
ToolRunContextFrom 从 ctx 取 ToolRunContext。
func (*ToolRunContext) ConcludeTurn ¶
func (tc *ToolRunContext) ConcludeTurn(reason string) bool
ConcludeTurn 结束当前 turn(权威标记),并执行 deferred 回调。 多次调用不会重复触发 conclude。
func (*ToolRunContext) Context ¶
func (tc *ToolRunContext) Context() context.Context
Context 返回携带该 ToolRunContext 的 context(供工具实现读取)。
func (*ToolRunContext) DeferContext ¶
func (tc *ToolRunContext) DeferContext(fn func())
DeferContext 注册一个在工具结束时执行的清理/收尾回调(类似 Go defer)。
func (*ToolRunContext) GetMeta ¶
func (tc *ToolRunContext) GetMeta(k string) (any, bool)
GetMeta 读取运行元数据。
func (*ToolRunContext) IsConcluded ¶
func (tc *ToolRunContext) IsConcluded() bool
IsConcluded 是否已 conclude(Agent 判续步用)。
func (*ToolRunContext) SetMeta ¶
func (tc *ToolRunContext) SetMeta(k string, v any)
SetMeta 设置运行元数据。
type WebResultView ¶
type WebResultView struct {
Card string `json:"card"`
Kind string `json:"kind"` // "search" | "fetch"
Title string `json:"title,omitempty"`
Sources []WebSource `json:"sources,omitempty"`
Answer string `json:"answer,omitempty"`
URL string `json:"url,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
Truncated bool `json:"truncated"`
}
WebResultView 是完成 web 检索卡片(search/fetch 两种 kind)。
func NewWebFetchResultView ¶
func NewWebFetchResultView(url string, statusCode int, truncated bool) *WebResultView
NewWebFetchResultView 构造 web_fetch 结果卡片。
func NewWebSearchResultView ¶
func NewWebSearchResultView(sources []WebSource, answer string, truncated bool) *WebResultView
NewWebSearchResultView 构造 web_search 结果卡片。