tools

package
v0.0.0-...-41a1881 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 50 Imported by: 0

README

node/internal/tools

N3 在 Node 进程内本地执行;面向模型的普通 tool schema 均为同步调用(仅 call_purpose 通用参数)。Browser 同样是同步的 browser_call / browser_evaluate,不创建异步任务或回灌会话。

bash_run 超时语义:

  • 显式传入 timeout_seconds:同步等待该秒数,超时终止并返回 timed_out 失败结果,不会创建后台 job。
  • 省略 timeout_seconds:最长等待硬上限(默认 600 秒),超时同样终止并报错。
  • UI 控制(仅 bash):执行中可「终止」;不支持把 bash_run 转为后台。需要长期运行状态时使用 terminal_open。

bash_run 和 Browser 都走同步执行路径;Browser 不再使用独立 task_id、轮询或异步回灌协议。

配置:工具组由 Agent defaults.tools.enabled_groups 决定,见 handbook/04-能力与策略.md §1、handbook/附录/内置工具参考.md、shared/config/README.md。
工具用法:写在各 tool schema description 中(各 tool_* / fs_* / bash_* 文件)。

工具结果契约

工具 handler 保持各自正文格式;统一状态在 result_contract.go 中分类,并由 turn 层附加到 tool_result SSE:

字段 语义
status succeeded、failed、denied、running、queued、cancelled、timed_out、awaiting_user、unknown
error 失败状态的 {code, message, retryable},策略拒绝使用 policy_denied
rejected 仅表示策略拒绝;执行失败不再误报为“已拒绝”

状态优先于正文是否为空、ERROR: 前缀或本地化文案。正文中的既有字段(例如 exit_code、stdout_bytes、output_empty、job_id)继续作为工具证据保留。 执行器若同时返回部分正文和 Go error,编排器会保留正文并追加错误诊断,不再丢失 远端/MCP/SSH/SFTP 提供的证据。

terminal_read 延时读取:可传入 wait_seconds,工具会严格等待指定秒数后再读取终端输出;默认 0,最大 60 秒。等待期间如果 turn 被取消,会立即结束等待并返回取消错误。输出仍使用 after_seq / next_seq 游标读取。


目录布局(阶段 A,2026-06)

同 package tools,按 文件名前缀 分组:

tools/
├── 核心 registry
│   types.go                  # ToolDef、FunctionDef、handler
│   result_contract.go        # 统一 tool_result status/error 分类
│   registry.go               # Registry、NewRegistry、Definitions、Execute
│   registry_path.go          # resolveWorkspaceRoot、resolvePath(Agent workspace)
│   registry_enabled.go       # SetBuiltinEnabled、filterToolDefs
│   executor.go               # Executor 接口
│   execution_mode.go         # call_purpose 清洗与上下文标记
│   tools_test.go             # registry 集成 smoke
├── 文件 fs_*
│   fs_read.go / fs_write.go / fs_search_replace.go
│   fs_glob_tool.go / fs_glob_internal.go
│   fs_grep_file.go / fs_grep_files.go / fs_grep_shared.go  # grep_file 仅留兼容 handler;模型只见覆盖两种模式的 grep_files
│   fs_helpers.go / fs_encoding.go / fs_path_encoding.go
│   fs_stat.go                # StatRelPath(写盘信任链 Hook)
│   fs_*_test.go
├── Shell bash_*
│   bash_run_tool.go          # bashRunToolDef
│   bash_runner.go / bash_shell.go / bash_policy.go
│   bash_compress.go          # 配置 + 清洗 + 截断 + SSE 统计(原 6 文件合并)
│   shell_output_encoding.go / shell_platform_*.go
│   bash_*_test.go
├── Shell 执行状态
│   shell_execution.go        # 单次同步 bash 的取消/终态状态
├── 领域 tool_*
│   tool_skills.go / tool_hitl.go / tool_triggers.go
│   tool_childagent.go
│   tool_*_test.go
└── README.md / REFERENCE.md

执行边界

在 Registry 执行 在 turn 编排器执行
fs、bash、trigger CRUD load_skills / unload_skills / clear_skills
ask_user_information
子 Agent 管理类(registry 为 stub)

阶段 B(未做)

子 package + Register(r *Registry);待阶段 A 稳定后再开。


执行模式

  • 同步(默认):orchestrator 调用 Execute;read_file / write_file / trigger_create 等始终同步完成。
  • bash_run:始终同步调用;到达显式 timeout 或默认硬上限后杀进程并返回 TIMED_OUT,不登记后台 job,也不产生异步回灌。
  • terminal_open:用于需要保持目录、环境或进程状态的长期交互任务。
  • 写盘信任链:write_file / search_replace 为 rule 时,同 session Agent 自建文件在 mtime 未变前提下后续写操作可免 HITL(node/internal/hooks,见 ux-agent-owned-file-approval.md)。

触发器 condition 语义见 ../triggers/README.md.

Documentation

Index

Constants

View Source
const (
	// DefaultLinuxTransferConcurrency is deliberately conservative for a Node
	// that may also be serving interactive terminals and LLM requests.
	DefaultLinuxTransferConcurrency = 2
	DefaultLinuxTransferQueueLimit  = 32
	DefaultLinuxTransferTimeout     = 10 * time.Minute
	MaxLinuxTransferBytes           = 100 << 20
)
View Source
const (
	// CallPurposeKey 为各工具通用必填参数:简短说明调用目的(Client 首行展示)。
	CallPurposeKey = "call_purpose"
)
View Source
const DefaultTerminalSessionLimit = 8

DefaultTerminalSessionLimit is the in-memory per-Agent terminal limit. It is deliberately finite because terminal sessions are interactive resources and are not restored after a Node restart.

View Source
const TerminalConfigLinuxPrefix = "linux_channel:"

TerminalConfigLinuxPrefix prevents a remote channel ID from colliding with the built-in local config ID and makes it impossible to confuse a config identifier with an arbitrary provider target.

Variables

View Source
var ErrLinuxPrivateKeyEncrypted = errors.New("encrypted SSH private keys are not supported; provide an unencrypted PEM/OpenSSH private key")

ErrLinuxPrivateKeyEncrypted indicates that a private key needs a passphrase, which Linux channel credentials do not currently accept.

View Source
var ErrLinuxPrivateKeyInvalid = errors.New("linux private key is invalid; expected PEM/OpenSSH private-key contents, not a file path")

ErrLinuxPrivateKeyInvalid classifies credential material that cannot be parsed as an unencrypted PEM/OpenSSH private key. The error intentionally never contains the supplied credential bytes.

View Source
var ErrSyncShellNotFound = fmt.Errorf("sync bash tool call not found")

ErrSyncShellNotFound 表示没有可控制的同步 bash。

Functions

func ApprovalIDFromContext

func ApprovalIDFromContext(ctx context.Context) string

func DefaultLinuxHostKeyResolver

func DefaultLinuxHostKeyResolver(_ context.Context, cfg LinuxChannelConfig) (ssh.HostKeyCallback, error)

DefaultLinuxHostKeyResolver uses an explicit channel path when provided or the current user's ~/.ssh/known_hosts. It deliberately has no insecure fallback and is suitable as the Node default.

func EnabledBypassFromContext

func EnabledBypassFromContext(ctx context.Context) bool

EnabledBypassFromContext 是否跳过 enabledOnly 门禁。

func ErrToolNotEnabled

func ErrToolNotEnabled(name string) error

ErrToolNotEnabled 返回未启用工具的 soft-reject 文案(对齐 Workgroup allowlist 风格)。

func IsAskUserInformation

func IsAskUserInformation(name string) bool

IsAskUserInformation 判断工具名是否为 ask_user_information。

func IsKnownBuiltinTool

func IsKnownBuiltinTool(name string) bool

IsKnownBuiltinTool 判断是否为可配置的内置工具名。

func IsMemoryForget

func IsMemoryForget(name string) bool

func IsMemoryGet

func IsMemoryGet(name string) bool

func IsMemorySearch

func IsMemorySearch(name string) bool

func IsMemoryTool

func IsMemoryTool(name string) bool

func IsReadImageTool

func IsReadImageTool(name string) bool

IsReadImageTool 判断工具名是否为 read_image。

func IsRemember

func IsRemember(name string) bool

IsRemember 判断工具名是否为 remember。

func IsSkillTool

func IsSkillTool(name string) bool

IsSkillTool 判断是否为 session skills 工具。

func ParseToolArgumentsMap

func ParseToolArgumentsMap(raw string) map[string]any

ParseToolArgumentsMap 解析 tool call arguments JSON。

func ParseToolCallArguments

func ParseToolCallArguments(arguments string) string

ParseToolCallArguments 剥离只供界面展示的 call_purpose 后返回 handler 用 JSON。

func ResultDescriptionSuffixForTool

func ResultDescriptionSuffixForTool(name string) string

ResultDescriptionSuffixForTool adds only the small tool-specific decoding hint that is otherwise easy for a model to miss in a long description. The common result protocol is intentionally not repeated here.

func ResultEventFields

func ResultEventFields(toolName, content string, failureHint bool) map[string]any

ResultEventFields returns the stable status/error projection that can be merged into SSE or audit payloads. Status is the only outcome field; callers must not infer policy denial from a second boolean projection.

func ResultEventFieldsWithStatus

func ResultEventFieldsWithStatus(toolName, content string, failureHint bool, explicitStatus ResultStatus) map[string]any

ResultEventFieldsWithStatus lets asynchronous bridges provide the durable job status when the client-facing body is intentionally a short/cleaned preview and no longer contains the original status marker.

func ResultProtocolPrompt

func ResultProtocolPrompt() string

ResultProtocolPrompt returns the common result behavior for the single stable system-prompt section. Tool definitions should not repeat it.

func SessionIDFromContext

func SessionIDFromContext(ctx context.Context) string

SessionIDFromContext 读取 context 中的 session_id。

func TriggerSessionTargetFromContext

func TriggerSessionTargetFromContext(ctx context.Context) string

TriggerSessionTargetFromContext 读取 trigger 审批投递目标。

func TrustedAutoIdleAgentID

func TrustedAutoIdleAgentID(ctx context.Context) string

func TrustedAutoIdleAvailable

func TrustedAutoIdleAvailable(ctx context.Context) bool

TrustedAutoIdleAvailable reports whether this request belongs to the provider-validated system-auto activation that may use the control tool.

func ValidateAutoIdleArguments

func ValidateAutoIdleArguments(args json.RawMessage) error

func ValidateLinuxPrivateKeySecret

func ValidateLinuxPrivateKeySecret(secret string) error

ValidateLinuxPrivateKeySecret validates direct API input before it is saved. Environment-backed values are validated later, when the connection is tested.

func WithApprovalID

func WithApprovalID(ctx context.Context, approvalID string) context.Context

WithApprovalID marks the tool call as having passed the current HITL decision. Providers may use the opaque ID only as a presence signal; it is never sent to the remote host.

func WithEnabledBypass

func WithEnabledBypass(ctx context.Context) context.Context

WithEnabledBypass 跳过 Registry.enabledOnly 检查(子 Agent 在自身 allowlist 校验后使用)。

func WithHandbookMaintenance

func WithHandbookMaintenance(ctx context.Context) context.Context

func WithHandbookNoopRecorder

func WithHandbookNoopRecorder(ctx context.Context, recorder func(context.Context, HandbookNoop) error) context.Context

func WithSession

func WithSession(ctx context.Context, sessionID string) context.Context

WithSession 将 session_id 写入 context,供后台任务完成回调使用。

func WithToolCallID

func WithToolCallID(ctx context.Context, toolCallID string) context.Context

func WithTriggerSessionTarget

func WithTriggerSessionTarget(ctx context.Context, target string) context.Context

WithTriggerSessionTarget 写入审批通过的 trigger 投递目标(same_session / new_session / latest_active_session)。

func WithTrustedAutoIdleActivation

func WithTrustedAutoIdleActivation(ctx context.Context, agentID, triggerID, deliveryID string) context.Context

WithTrustedAutoIdleActivation marks one provider-validated system-auto activation. The marker is created only by the session ingress after the TriggerActivationProvider has accepted the agent/trigger/delivery tuple.

Types

type BashCompressConfig

type BashCompressConfig struct {
	Enabled               bool
	MaxOutputChars        int // stdout 最大 rune 数;0 表示默认 maxBashOutputRunes
	MaxOutputCharsStderr  int // stderr 最大 rune 数;0 表示与 stdout 相同
	OutputMode            string
	TailOutputChars       int // head_tail 模式下 stdout 尾部最大 rune 数
	TailOutputCharsStderr int // head_tail 模式下 stderr 尾部最大 rune 数;0 表示与 stdout 相同
}

BashCompressConfig 控制 bash_run 输出压缩(P0:L1 清洗 + rune 安全截断)。

func DefaultBashCompressConfig

func DefaultBashCompressConfig() BashCompressConfig

DefaultBashCompressConfig 为 P0 默认:开启清洗,stdout 12000 / stderr 16000 runes。

type EnvironmentPolicy

type EnvironmentPolicy struct {
	Mode  EnvironmentPolicyMode
	Allow []string
	Set   map[string]string
}

type EnvironmentPolicyMode

type EnvironmentPolicyMode string

EnvironmentPolicy controls which Node environment variables cross the local execution boundary. The zero value is scrub, which preserves the existing safe default. Set and ExecRequest.Env are explicit values and are applied after inherited values, with Env taking precedence over Set.

const (
	EnvironmentPolicyInherit EnvironmentPolicyMode = "inherit"
	EnvironmentPolicyScrub   EnvironmentPolicyMode = "scrub"
	EnvironmentPolicyAllow   EnvironmentPolicyMode = "allow"
	EnvironmentPolicySet     EnvironmentPolicyMode = "set"
)

type ExecRequest

type ExecRequest struct {
	Target         ExecutionTarget
	Context        ExecutionContext
	ShellType      string
	Command        string
	Argv           []string
	CWD            string
	Env            map[string]string
	Environment    EnvironmentPolicy
	TTY            bool
	PipeStdin      bool
	Timeout        time.Duration
	MaxOutputBytes int
	EventSink      ProcessEventSink
}

ExecRequest is the internal request passed from a tool to an execution provider. Command keeps shell syntax (pipelines, redirects, and scripts), while Argv is reserved for future direct process execution.

type ExecutionContext

type ExecutionContext struct {
	AgentID        string
	SessionID      string
	TurnID         string
	ToolCallID     string
	Target         ExecutionTarget
	PolicyDecision string
	ApprovalID     string
	RiskLevel      string
	CommandDigest  string
}

ExecutionContext carries the correlation fields needed by execution events. It is deliberately separate from the model-facing tool arguments.

type ExecutionTarget

type ExecutionTarget struct {
	Kind string
	ID   string
}

ExecutionTarget identifies the execution world selected by the policy and orchestration layers. The local provider is the first implementation; the target fields leave room for SSH, container, and exec-server providers without changing the model-facing bash_run schema.

type Executor

type Executor interface {
	Definitions() []ToolDef
	Execute(ctx context.Context, name, arguments string) (string, error)
	TakeBashCompressStatsForCall(toolCallID string) map[string]any
	TakeToolResultMediaForCall(toolCallID string) map[string]any
	TakeReadImageVisionForCall(toolCallID string) *ReadImageVisionPayload
}

Executor 为 turn 编排调用的工具后端;*Registry 与 childagent.RestrictedRegistry 均实现。

type ExitStatus

type ExitStatus struct {
	Code  int
	Error string
}

ExitStatus is independent of os.ProcessState so remote providers can expose the same lifecycle event without pretending to have a local process.

type FunctionDef

type FunctionDef struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters"`
}

FunctionDef 为 OpenAI function tool 定义。

type HandbookNoop

type HandbookNoop struct {
	ToolCallID string
	ToolName   string
	Path       string
	Digest     string
}

HandbookNoop records a handbook edit request whose resulting bytes were already present on disk. Path is relative to the handbook namespace.

type LinuxChannelBinding

type LinuxChannelBinding struct {
	AgentID         string
	ChannelID       string
	Enabled         bool
	IsDefault       bool
	RemoteCWD       string
	Shell           string
	MaxConcurrency  int
	ApprovalMode    string
	AllowedCommands []string
	DeniedCommands  []string
}

LinuxChannelBinding is the effective per-agent selection. The provider only needs Enabled/CWD/Shell to establish an execution boundary; policy and approval fields remain available to the orchestration layer.

type LinuxChannelBindingResolver

type LinuxChannelBindingResolver interface {
	ResolveLinuxBinding(ctx context.Context, agentID, channelID string) (LinuxChannelBinding, error)
}

type LinuxChannelConfig

type LinuxChannelConfig struct {
	ID             string
	DisplayName    string
	Host           string
	Port           int
	Username       string
	CredentialID   string
	HostKeyPolicy  string
	HostKeyRef     string
	RemoteShell    string
	DefaultCWD     string
	ConnectTimeout time.Duration
	CommandTimeout time.Duration
	Enabled        bool
	MaxSessions    int
}

LinuxChannelConfig contains non-secret connection settings. SecretRef is resolved only inside the provider and is never copied into execution events or tool results.

type LinuxChannelResolver

type LinuxChannelResolver interface {
	ResolveLinuxChannel(ctx context.Context, channelID string) (LinuxChannelConfig, error)
	ResolveLinuxCredential(ctx context.Context, credentialID string) (LinuxCredential, error)
}

LinuxChannelResolver supplies channel and credential metadata from the durable store. It must not return plaintext credentials in the channel configuration.

type LinuxCredential

type LinuxCredential struct {
	ID           string
	DisplayName  string
	AuthType     string
	SecretRef    string
	UsernameHint string
	Enabled      bool
}

LinuxCredential is a reference to an authentication secret. SecretRef is deliberately opaque to the caller; the provider's resolver is the only component allowed to turn it into a password or private-key PEM.

type LinuxHostKeyResolver

type LinuxHostKeyResolver func(ctx context.Context, cfg LinuxChannelConfig) (ssh.HostKeyCallback, error)

LinuxHostKeyResolver creates a strict callback for a channel. Production callers should use knownhosts.New or a pinned-key callback. Returning nil is not allowed by the provider.

type LinuxSecretResolver

type LinuxSecretResolver func(ctx context.Context, secretRef string) (string, error)

LinuxSecretResolver resolves an opaque secret reference at connection time. Implementations may use an environment variable, OS keyring, or the local encrypted secret store. The returned value must never be logged or emitted.

type LinuxShellProvider

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

LinuxShellProvider executes one non-PTY command in one SSH session. The SSH client is intentionally not exposed as a persistent shell: cwd, env, and process state do not leak between commands.

func NewLinuxShellProvider

func NewLinuxShellProvider(resolver LinuxChannelResolver, secretResolver LinuxSecretResolver) *LinuxShellProvider

func (*LinuxShellProvider) InspectRemoteProcess

func (p *LinuxShellProvider) InspectRemoteProcess(ctx context.Context, agentID string, recovery RemoteProcessRecovery) (string, error)

InspectRemoteProcess checks whether a remote process group is still alive without sending it a signal. It is used for restart-recovered jobs where Node can report remote state but must not silently mutate the process.

func (*LinuxShellProvider) OpenTerminal

func (p *LinuxShellProvider) OpenTerminal(ctx context.Context, req TerminalRequest) (Terminal, error)

OpenTerminal opens a persistent SSH PTY. Unlike Start, it does not run a one-shot command: the caller owns the terminal until Close or an explicit session expiry policy closes it.

func (*LinuxShellProvider) Preflight

func (p *LinuxShellProvider) Preflight(ctx context.Context, agentID, channelID, command string) (policy.Action, string, error)

Preflight checks only durable channel/binding policy. It intentionally does not resolve credentials or open a socket; those checks remain at Start so a stale approval can never bypass current connection state.

func (*LinuxShellProvider) RecoverRemoteProcess

func (p *LinuxShellProvider) RecoverRemoteProcess(ctx context.Context, agentID string, recovery RemoteProcessRecovery) (string, error)

RecoverRemoteProcess terminates a remote process group only when the persisted PID file contains the exact Node-generated token. It returns a small status token and never returns remote command output.

func (*LinuxShellProvider) Start

func (*LinuxShellProvider) Test

func (*LinuxShellProvider) WithBindingResolver

func (p *LinuxShellProvider) WithBindingResolver(resolver LinuxChannelBindingResolver) *LinuxShellProvider

func (*LinuxShellProvider) WithHostKeyResolver

func (p *LinuxShellProvider) WithHostKeyResolver(resolver LinuxHostKeyResolver) *LinuxShellProvider

type LinuxTransferEventSink

type LinuxTransferEventSink func(agentID, eventType string, data map[string]any, replayable bool)

type LinuxTransferManager

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

LinuxTransferManager owns the process-wide queue. A transfer is counted as one file regardless of its direction; queued work waits FIFO for a slot.

func NewLinuxTransferManager

func NewLinuxTransferManager(provider *LinuxShellProvider, maxConcurrent int, sink LinuxTransferEventSink) *LinuxTransferManager

func (*LinuxTransferManager) Cancel

func (m *LinuxTransferManager) Cancel(transferID string) bool

func (*LinuxTransferManager) List

func (*LinuxTransferManager) MaxConcurrent

func (m *LinuxTransferManager) MaxConcurrent() int

func (*LinuxTransferManager) Submit

type LinuxTransferRequest

type LinuxTransferRequest struct {
	AgentID       string
	ToolCallID    string
	ApprovalID    string
	TerminalID    string
	ChannelID     string
	Direction     string
	LocalPath     string
	RemotePath    string
	WorkspaceRoot string // Agent workspace root.
	Overwrite     bool
}

type LinuxTransferSnapshot

type LinuxTransferSnapshot struct {
	TransferID string    `json:"transfer_id"`
	AgentID    string    `json:"agent_id"`
	ToolCallID string    `json:"tool_call_id,omitempty"`
	TerminalID string    `json:"terminal_id,omitempty"`
	ChannelID  string    `json:"channel_id"`
	Direction  string    `json:"direction"`
	LocalPath  string    `json:"local_path"`
	RemotePath string    `json:"remote_path"`
	Status     string    `json:"status"`
	BytesDone  int64     `json:"bytes_done"`
	TotalBytes int64     `json:"total_bytes"`
	Progress   int       `json:"progress"`
	SpeedBPS   int64     `json:"speed_bps,omitempty"`
	Error      string    `json:"error,omitempty"`
	Result     string    `json:"result,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

type LocalShellProvider

type LocalShellProvider struct{}

LocalShellProvider executes a shell command on the current Node host. It owns only process construction and lifecycle; bash_run still owns timeout, output decoding, compression, and background-job semantics.

func NewLocalShellProvider

func NewLocalShellProvider() *LocalShellProvider

func (*LocalShellProvider) OpenTerminal

func (p *LocalShellProvider) OpenTerminal(ctx context.Context, req TerminalRequest) (Terminal, error)

OpenTerminal opens a local native PTY. The platform-specific constructor supplies the actual PTY/process handles; lifecycle, events, and policy correlation remain identical to the SSH Terminal implementation.

func (*LocalShellProvider) Start

func (*LocalShellProvider) Test

type MCPTool

type MCPTool struct {
	Name        string
	Description string
	Parameters  map[string]any
	Call        func(context.Context, json.RawMessage) (mcp.CallResult, error)
}

MCPTool is the Registry-facing projection of a remote MCP tool.

type MediaArtifactRef

type MediaArtifactRef struct {
	ID      string `json:"id"`
	Kind    string `json:"kind"`
	MIME    string `json:"mime"`
	URL     string `json:"url"`
	Label   string `json:"label,omitempty"`
	Caption string `json:"caption,omitempty"`
}

MediaArtifactRef 为工具结果 SSE / hydrate 使用的媒体引用(F-M0)。

type MediaRegisterFunc

type MediaRegisterFunc func(ctx context.Context, toolCallID, relPath, source, label, caption string) (*MediaArtifactRef, error)

MediaRegisterFunc 将会话内图片注册为可 GET 的 media artifact。

type OutputBudget

type OutputBudget struct {
	bytes.Buffer
	// contains filtered or unexported fields
}

OutputBudget is the byte-level collection boundary for process output.

Providers must apply a budget while bytes are being read, rather than only clipping the completed string afterwards. Write reports the input length so io.Copy keeps draining the process pipe and a noisy child cannot block on a full pipe. The first Limit bytes are retained and the remainder is marked as truncated. Higher layers may still apply rune/token/semantic compression.

func NewHeadTailOutputBudget

func NewHeadTailOutputBudget(totalLimit, tailLimit int) *OutputBudget

NewHeadTailOutputBudget creates a budget that keeps the first headLimit bytes and the last tailLimit bytes after the total budget is exceeded. The returned value still drains every input byte, so it is safe to attach to a process pipe. UTF-8 boundaries are repaired when Bytes is read.

func NewOutputBudget

func NewOutputBudget(limit int) *OutputBudget

NewOutputBudget creates a head-preserving byte budget. A non-positive limit means unlimited collection and is useful for providers that already enforce a stronger bound elsewhere.

func (*OutputBudget) Bytes

func (b *OutputBudget) Bytes() []byte

Bytes never exposes a partial UTF-8 sequence when a byte budget ends in the middle of a rune. The raw buffer may still keep that byte so a later Write can complete the sequence before the process ends.

func (*OutputBudget) String

func (b *OutputBudget) String() string

func (*OutputBudget) Truncated

func (b *OutputBudget) Truncated() bool

func (*OutputBudget) Write

func (b *OutputBudget) Write(data []byte) (int, error)

Write implements io.Writer while retaining only the configured prefix. Returning len(data), nil is intentional: callers should continue draining the pipe even after the model-visible budget has been exhausted.

type OutputCompressStats

type OutputCompressStats struct {
	RawRunes  int
	OutRunes  int
	SavedPct  int
	Truncated bool
}

OutputCompressStats 为 bash_run 输出压缩统计(仅在有节省时写入 SSE)。

func (*OutputCompressStats) SSEFields

func (s *OutputCompressStats) SSEFields() map[string]any

type Process

type Process interface {
	ID() string
	StdoutPipe() (io.ReadCloser, error)
	StderrPipe() (io.ReadCloser, error)
	SetOutput(stdout, stderr io.Writer)
	Start() error
	Wait() error
	ExitStatus() *ExitStatus
	Terminate(ctx context.Context) error
	Close() error
}

Process is the provider-neutral lifecycle handle used by synchronous and background shell execution. Pipes are acquired before Start so callers can keep the current stdout/stderr collection and synchronous timeout behavior.

type ProcessEvent

type ProcessEvent struct {
	Type        ProcessEventType
	ProcessID   string
	Seq         uint64
	Context     ExecutionContext
	Stream      string
	Data        []byte
	OutputBytes int64
	Exit        *ExitStatus
}

ProcessEvent is a runtime execution event. Seq is monotonic per process; output bytes are kept separate by Stream and are not mixed with stderr.

type ProcessEventSink

type ProcessEventSink func(ProcessEvent)

type ProcessEventType

type ProcessEventType string
const (
	ProcessEventStarted            ProcessEventType = "process_started"
	ProcessEventOutput             ProcessEventType = "process_output"
	ProcessEventTerminateRequested ProcessEventType = "process_terminate_requested"
	ProcessEventExited             ProcessEventType = "process_exited"
)

type ReadImageVisionPayload

type ReadImageVisionPayload struct {
	RelPath string
	Detail  string
	DataURL string
	FrameID string
	// Prompt 非空时作为视觉 follow-up 文本;空则使用 read_image 默认文案。
	Prompt string
}

ReadImageVisionPayload 为 read_image / browser_* 截图成功后待注入 LLM 的视觉 user 消息载荷。

type Registry

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

Registry 注册内置工具并在 Agent workspace 内执行。

func NewRegistry

func NewRegistry(workspaceRoot string, bashTimeoutSeconds int, encodings ...string) (*Registry, error)

NewRegistry 创建工具表;workspaceRoot 为空时用当前目录。 encodings[0]=tools.bash_output_encoding,encodings[1]=tools.file_encoding;空串表示按平台/shell 自动选择。

func (*Registry) CancelAllSessionJobs

func (r *Registry) CancelAllSessionJobs(sessionID string) int

CancelAllSessionJobs 取消该 session 下全部同步 bash。

func (*Registry) CancelSyncBash

func (r *Registry) CancelSyncBash(sessionID, toolCallID string) error

CancelSyncBash 终止仍在同步等待的 bash_run(按 tool_call_id)。

func (*Registry) CloseBrowser

func (r *Registry) CloseBrowser() error

func (*Registry) Definitions

func (r *Registry) Definitions() []ToolDef

Definitions 返回传给 LLM 的 tools 列表。

func (*Registry) DefinitionsForContext

func (r *Registry) DefinitionsForContext(ctx context.Context) []ToolDef

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name, arguments string) (string, error)

Execute 按名称 dispatch 工具;未知工具或未启用工具返回 error 文本。 子 Agent RestrictedRegistry 在通过自身 allowlist 后应使用 WithEnabledBypass, 以免父 Agent 的 enabledOnly 误拦子会话允许的工具。

func (*Registry) HandbookHistory

func (r *Registry) HandbookHistory(ctx context.Context, raw string) ([]handbookfs.Entry, error)

HandbookHistory exposes filesystem history to the control plane without making .history reachable through model-facing file tools.

func (*Registry) HandbookMutationCount

func (r *Registry) HandbookMutationCount() uint64

HandbookMutationCount reports successful filesystem history commits for the bound handbook, allowing maintenance to distinguish read-only turns.

func (*Registry) HandbookRoot

func (r *Registry) HandbookRoot() string

HandbookRoot returns the canonical root bound to the registry. The value is immutable for the lifetime of a built Agent runtime and is safe for callers that need to persist the execution-time handbook identity.

func (*Registry) MultimodalEnabled

func (r *Registry) MultimodalEnabled() bool

MultimodalEnabled 是否已启用多模态工具能力。

func (*Registry) OpenTerminal

func (r *Registry) OpenTerminal(ctx context.Context, req TerminalRequest) (Terminal, error)

OpenTerminal routes local and Linux-channel terminals through the same registry that owns model-facing tools. The registry fills in the owning agent and runtime event sink so a terminal API cannot accidentally bypass per-agent channel binding or execution observability.

func (*Registry) PreflightTool

func (r *Registry) PreflightTool(ctx context.Context, name string, args map[string]any) (ToolPreflightDecision, bool)

PreflightTool evaluates live provider policy before the orchestrator queues a tool. The provider still repeats the check immediately before connecting.

func (*Registry) RegisterChildAgentToolStubs

func (r *Registry) RegisterChildAgentToolStubs()

RegisterChildAgentToolStubs 注册临时 Agent 工具占位(执行由 orchestrator 处理)。

func (*Registry) ResolveLocalTerminalCWD

func (r *Registry) ResolveLocalTerminalCWD(raw string) (string, error)

ResolveLocalTerminalCWD applies the same workspace-relative path policy as bash_run. An empty value resolves to the Agent workspace root.

func (*Registry) RestoreHandbook

func (r *Registry) RestoreHandbook(ctx context.Context, raw, expectedDigest string, revision int64) (handbookfs.Entry, error)

func (*Registry) SessionToolJobCounts

func (r *Registry) SessionToolJobCounts(sessionID string) ToolJobCounts

SessionToolJobCounts 返回指定 session 的工具执行计数。

func (*Registry) SetAgentID

func (r *Registry) SetAgentID(agentID string)

SetAgentID attaches the owning Agent identity to execution requests and lifecycle events. It is also used by per-agent channel binding checks.

func (*Registry) SetAutonomyEnabled

func (r *Registry) SetAutonomyEnabled(enabled bool)

SetAutonomyEnabled exposes Auto-only todo tools on an explicitly selected Auto main runtime.

func (*Registry) SetAutonomyTodoStore

func (r *Registry) SetAutonomyTodoStore(s *autonomy.Store)

func (*Registry) SetBashCompress

func (r *Registry) SetBashCompress(cfg BashCompressConfig)

SetBashCompress 注入 bash 输出压缩配置(由 Node 启动时从 config.yaml 映射)。

func (*Registry) SetBrowserManager

func (r *Registry) SetBrowserManager(mgr *browser.Manager)

SetBrowserManager injects the process-level browser manager. Browser tools are ordinary synchronous tools and do not create background jobs.

func (*Registry) SetBuiltinEnabled

func (r *Registry) SetBuiltinEnabled(names []string) error

SetBuiltinEnabled 设置 LLM 可见/可执行的内置工具允许列表;names 为空表示全部启用。 未列入的工具仍保留 handler(供子 Agent bypass 委托),但 Execute 会 soft reject。

func (*Registry) SetBuiltinEnabledNone

func (r *Registry) SetBuiltinEnabledNone()

SetBuiltinEnabledNone 禁用全部内置工具(显式空允许列表)。

func (*Registry) SetHandbookRoot

func (r *Registry) SetHandbookRoot(root string) error

SetHandbookRoot binds the reserved relative "handbook/" path namespace to an Agent-owned directory. Existing file tools then provide the same policy, quota, and write lease chain for handbook edits.

func (*Registry) SetMCPTools

func (r *Registry) SetMCPTools(remoteTools []MCPTool) error

func (*Registry) SetMediaRegister

func (r *Registry) SetMediaRegister(fn MediaRegisterFunc)

func (*Registry) SetMultimodalEnabled

func (r *Registry) SetMultimodalEnabled(enabled bool)

SetMultimodalEnabled 控制 read_image、browser 视觉模式与 vision 载荷暂存;默认 false。

func (*Registry) SetProcessEventSink

func (r *Registry) SetProcessEventSink(sink ProcessEventSink)

SetProcessEventSink attaches the runtime execution-event bridge. The sink must be non-blocking because stdout/stderr collection calls it on the process IO path.

func (*Registry) SetTerminalConfigResolver

func (r *Registry) SetTerminalConfigResolver(resolver TerminalConfigResolver)

SetTerminalConfigResolver binds the Agent-scoped terminal config view. The resolver is consulted both when listing configs and when opening one, so a model cannot bypass the Agent's binding by guessing a channel ID.

func (*Registry) SetTerminalSessionBroker

func (r *Registry) SetTerminalSessionBroker(broker TerminalSessionBroker)

SetTerminalSessionBroker binds the API-owned long-lived terminal registry. Keeping the interface in tools avoids importing the HTTP layer into Agent execution while allowing tools and WebSocket clients to share sessions.

func (*Registry) SetTriggerRuntime

func (r *Registry) SetTriggerRuntime(store *triggers.Store, sched *triggers.Scheduler, agentID string)

SetTriggerRuntime 注入触发器 store / scheduler 与默认 target_agent_id。

func (*Registry) SetWeComClient

func (r *Registry) SetWeComClient(client *wecom.Client)

SetWeComClient 注入企业微信 webhook 客户端;nil 时不暴露 wecom_* 工具。

func (*Registry) SetWorkspaceCoordinator

func (r *Registry) SetWorkspaceCoordinator(c *workspacecoord.Coordinator)

SetWorkspaceCoordinator injects the Node-shared local write coordinator.

func (*Registry) StatRelPath

func (r *Registry) StatRelPath(relPath string) (exists bool, mtime time.Time, err error)

StatRelPath 在 Agent workspace 内 Stat 相对路径(供 Agent 文件信任链 Hook 使用)。

func (*Registry) TakeBashCompressStatsForCall

func (r *Registry) TakeBashCompressStatsForCall(toolCallID string) map[string]any

func (*Registry) TakeReadImageVisionForCall

func (r *Registry) TakeReadImageVisionForCall(toolCallID string) *ReadImageVisionPayload

TakeReadImageVisionForCall 取出并清除 read_image 的视觉 follow-up 载荷。

func (*Registry) TakeToolResultMediaForCall

func (r *Registry) TakeToolResultMediaForCall(toolCallID string) map[string]any

TakeToolResultMediaForCall 取出并清除 tool result 附带的 media[] SSE 字段。

func (*Registry) ToolRetryAllowed

func (r *Registry) ToolRetryAllowed(name string) bool

ToolRetryAllowed is deliberately an allowlist. Unknown/custom tools and commands that may mutate state are never retried automatically because a process restart or transport error cannot prove whether their side effect committed.

func (*Registry) WithLinuxShellProvider

func (r *Registry) WithLinuxShellProvider(provider *LinuxShellProvider) error

WithLinuxShellProvider enables Linux-channel terminal targets.

func (*Registry) WithLinuxTransferManager

func (r *Registry) WithLinuxTransferManager(manager *LinuxTransferManager) error

WithLinuxTransferManager binds the Node-level Linux file transfer queue. The manager is shared by all Agent registries so one Agent cannot exhaust the Node's SSH/SFTP transfer capacity.

func (*Registry) WithShellProvider

func (r *Registry) WithShellProvider(provider ShellProvider) error

WithShellProvider replaces the execution backend used by shell tools. It is intentionally an internal seam for the current Local provider and future SSH/container/exec-server providers; tool policy remains in the Registry and is not bypassed by changing the provider.

func (*Registry) WorkspaceRoot

func (r *Registry) WorkspaceRoot() string

WorkspaceRoot returns the effective Agent workspace used by file, bash and local terminal tools. It is intentionally read-only; placement is fixed when the Agent is created.

type RemoteProcessRecovery

type RemoteProcessRecovery struct {
	TargetID string
	JobToken string
	PIDFile  string
}

RemoteProcessRecovery identifies a remote process group without storing the command or credentials. The provider uses it to terminate a synchronous remote command reliably when the local context is cancelled.

type ResultError

type ResultError struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

ResultError is the stable error projection exposed with tool_result events.

type ResultMetadata

type ResultMetadata struct {
	Status ResultStatus
	Error  *ResultError
}

ResultMetadata is the common, provider-neutral result envelope metadata. Content is intentionally not included: each tool keeps its existing output body, while this metadata is attached to the event and lifecycle boundary.

func ClassifyResult

func ClassifyResult(toolName, content string, failureHint bool) ResultMetadata

ClassifyResult is the single boundary for provider result text. It understands JSON results, shell result headers and policy messages without requiring every handler to share one response body format.

func (ResultMetadata) Denied

func (m ResultMetadata) Denied() bool

func (ResultMetadata) Succeeded

func (m ResultMetadata) Succeeded() bool

type ResultStatus

type ResultStatus string

ResultStatus is the authoritative state of a tool result. The raw tool body remains tool-specific, while the orchestrator/UI use this status instead of guessing from an empty body or a localized error string.

const (
	ResultStatusSucceeded    ResultStatus = "succeeded"
	ResultStatusFailed       ResultStatus = "failed"
	ResultStatusDenied       ResultStatus = "denied"
	ResultStatusRunning      ResultStatus = "running"
	ResultStatusQueued       ResultStatus = "queued"
	ResultStatusCancelled    ResultStatus = "cancelled"
	ResultStatusTimedOut     ResultStatus = "timed_out"
	ResultStatusAwaitingUser ResultStatus = "awaiting_user"
	ResultStatusUnknown      ResultStatus = "unknown"
)

func NormalizeResultStatus

func NormalizeResultStatus(raw string) ResultStatus

NormalizeResultStatus maps provider/job spellings to the public status set.

type ShellProvider

type ShellProvider interface {
	Start(ctx context.Context, req ExecRequest) (Process, error)
	Test(ctx context.Context, target ExecutionTarget) (TargetStatus, error)
}

ShellProvider creates process handles for a selected execution target. Policy, HITL, history, and tool-result formatting remain outside providers.

type TargetStageStatus

type TargetStageStatus struct {
	Name       string `json:"name"`
	Status     string `json:"status"`
	Code       string `json:"code,omitempty"`
	Message    string `json:"message,omitempty"`
	DurationMS int64  `json:"duration_ms"`
}

TargetStageStatus describes one observable connection/test phase.

type TargetStatus

type TargetStatus struct {
	Available          bool                `json:"available"`
	Message            string              `json:"message"`
	ErrorCode          string              `json:"error_code,omitempty"`
	HostKeyFingerprint string              `json:"host_key_fingerprint,omitempty"`
	Stages             []TargetStageStatus `json:"stages,omitempty"`
}

TargetStatus describes provider reachability and diagnostic phases. The original Available/Message fields remain stable for existing callers.

type Terminal

type Terminal interface {
	ID() string
	Input(ctx context.Context, data []byte) error
	Output() (io.ReadCloser, error)
	Resize(ctx context.Context, rows, cols int) error
	Start() error
	Wait() error
	ExitStatus() *ExitStatus
	Terminate(ctx context.Context) error
	Close() error
}

Terminal is the provider-neutral contract for an interactive PTY. Output is a single PTY stream, so stderr is intentionally not exposed separately. Implementations must treat Close as idempotent and must not keep remote sessions alive after the caller explicitly closes the terminal.

type TerminalCommandRequest

type TerminalCommandRequest struct {
	TerminalID     string
	Target         ExecutionTarget
	ConfigID       string
	Shell          string
	CWD            string
	Command        string
	Timeout        time.Duration
	MaxOutputBytes int
}

TerminalCommandRequest is the bounded command contract attached to an already-open terminal session. The command is written to that session's existing PTY; it must never cause a provider to open a second transport. terminal_id is validated by the session broker. Target/ConfigID are filled from authoritative session metadata and are not model supplied.

type TerminalCommandResult

type TerminalCommandResult struct {
	Status          string `json:"status"`
	TerminalID      string `json:"terminal_id"`
	TargetKind      string `json:"target_kind"`
	ExitCode        int    `json:"exit_code"`
	Stdout          string `json:"stdout,omitempty"`
	Stderr          string `json:"stderr,omitempty"`
	StdoutBytes     int    `json:"stdout_bytes"`
	StderrBytes     int    `json:"stderr_bytes"`
	OutputTruncated bool   `json:"output_truncated"`
	Cancelled       bool   `json:"cancelled,omitempty"`
	TimedOut        bool   `json:"timed_out"`
	Error           string `json:"error,omitempty"`
}

TerminalCommandResult keeps command completion and exit semantics separate from the interactive PTY transcript. Since a PTY is one combined stream, providers may return diagnostic output in Stdout rather than Stderr.

type TerminalConfigInfo

type TerminalConfigInfo struct {
	ConfigID    string `json:"config_id"`
	DisplayName string `json:"display_name,omitempty"`
	Host        string `json:"host,omitempty"`
	Port        int    `json:"port,omitempty"`
	Username    string `json:"username,omitempty"`
	Remark      string `json:"remark,omitempty"`
	Shell       string `json:"shell,omitempty"`
	TargetKind  string `json:"-"`
	TargetID    string `json:"-"`
}

TerminalConfigInfo is the safe, model-visible summary of a terminal target. Authentication material, host-key details, and other secrets are excluded. TargetKind/TargetID are internal routing fields and are intentionally not serialized into terminal_config_list results.

type TerminalConfigResolver

type TerminalConfigResolver interface {
	ListTerminalConfigs(ctx context.Context, agentID string) ([]TerminalConfigInfo, error)
	ResolveTerminalConfig(ctx context.Context, agentID, configID string) (TerminalConfigInfo, error)
}

TerminalConfigResolver exposes only the terminal configs bound to one Agent. Implementations must never return passwords, private keys, secret refs, or host-key material.

type TerminalOutput

type TerminalOutput struct {
	Chunks            []TerminalOutputChunk `json:"chunks"`
	NextSeq           uint64                `json:"next_seq"`
	ReplayGap         bool                  `json:"replay_gap,omitempty"`
	Exited            bool                  `json:"exited"`
	Graceful          bool                  `json:"graceful,omitempty"`
	Forced            bool                  `json:"forced,omitempty"`
	TerminationStatus string                `json:"termination_status,omitempty"`
	Exit              *ExitStatus           `json:"exit,omitempty"`
}

TerminalOutput is deliberately cursor-based so an Agent can poll without copying an unbounded PTY transcript into every tool result.

type TerminalOutputChunk

type TerminalOutputChunk struct {
	Seq  uint64 `json:"seq"`
	Data []byte `json:"data"`
}

TerminalOutputChunk is a bounded output fragment returned to an Agent tool or another non-WebSocket consumer. Seq is monotonic within one session.

type TerminalProvider

type TerminalProvider interface {
	OpenTerminal(ctx context.Context, req TerminalRequest) (Terminal, error)
	Test(ctx context.Context, target ExecutionTarget) (TargetStatus, error)
}

TerminalProvider opens interactive terminals for an execution target. The provider owns transport and PTY lifecycle; orchestration still owns policy, HITL, history, and user-facing result formatting.

type TerminalRequest

type TerminalRequest struct {
	Target      ExecutionTarget
	Context     ExecutionContext
	ConfigID    string
	CWD         string
	Env         map[string]string
	Environment EnvironmentPolicy
	Shell       string
	Rows        int
	Cols        int
	EventSink   ProcessEventSink
}

TerminalRequest describes a long-lived interactive shell session. It is deliberately separate from ExecRequest: an interactive terminal owns a persistent stdin/stdout stream and must not inherit one-shot command timeout or background-job semantics.

type TerminalSessionBroker

type TerminalSessionBroker interface {
	Open(ctx context.Context, agentID string, req TerminalRequest) (TerminalSessionInfo, error)
	List(agentID string) []TerminalSessionInfo
	Lookup(agentID, terminalID string) (TerminalSessionInfo, error)
	ReadOutput(ctx context.Context, agentID, terminalID string, afterSeq uint64, maxBytes int) (TerminalOutput, error)
	Input(ctx context.Context, agentID, terminalID string, data []byte) error
	RunCommand(ctx context.Context, agentID, terminalID string, req TerminalCommandRequest) (TerminalCommandResult, error)
	Terminate(ctx context.Context, agentID, terminalID string) (TerminalOutput, error)
}

TerminalSessionBroker is the lifecycle seam shared by the Agent terminal tools and the WebSocket/UI transport. Implementations must enforce Agent ownership for every operation.

type TerminalSessionInfo

type TerminalSessionInfo struct {
	ID         string    `json:"terminal_id"`
	AgentID    string    `json:"agent_id"`
	ConfigID   string    `json:"config_id,omitempty"`
	TargetKind string    `json:"target_kind"`
	TargetID   string    `json:"target_id,omitempty"`
	Shell      string    `json:"shell,omitempty"`
	CWD        string    `json:"cwd,omitempty"`
	Status     string    `json:"status"`
	CreatedAt  time.Time `json:"created_at"`
}

TerminalSessionInfo is the model/UI-visible metadata for a long-lived terminal. The terminal's byte stream remains private to the session broker; callers use ReadOutput to consume bounded text snapshots.

type ToolDef

type ToolDef struct {
	Type     string      `json:"type"`
	Function FunctionDef `json:"function"`
}

ToolDef 为 OpenAI tools 数组项。

func ListAvailableSkillsToolDef

func ListAvailableSkillsToolDef() ToolDef

ListAvailableSkillsToolDef describes the metadata-only discovery tool. It is appended by the turn orchestrator when the Skills tool group is visible.

type ToolJobCounts

type ToolJobCounts struct {
	Running        int      `json:"running"`
	RunningCallIDs []string `json:"running_call_ids"`
}

ToolJobCounts 为某 session 当前可由 UI 终止的同步 bash 数量与调用 ID。

type ToolMediaPath

type ToolMediaPath struct {
	RelPath string
	Source  string
	Label   string
	Caption string
}

ToolMediaPath 描述工具结果中可注册为 UI media 的图片路径(F-M2/M4)。

func ExtractAllToolMediaPaths

func ExtractAllToolMediaPaths(toolName, content string, args map[string]any) []ToolMediaPath

ExtractAllToolMediaPaths 解析工具结果中全部可展示图片路径。

func ExtractToolMediaPaths

func ExtractToolMediaPaths(toolName, content string, args map[string]any) (ToolMediaPath, bool)

ExtractToolMediaPaths 从 tool 结果解析可展示图片路径(取第一条)。

type ToolPreflight

type ToolPreflight interface {
	PreflightTool(context.Context, string, map[string]any) (ToolPreflightDecision, bool)
}

ToolPreflight lets an executor contribute live target policy without changing the model-visible tool schema. It is optional so restricted/test executors can keep the existing Executor contract.

type ToolPreflightDecision

type ToolPreflightDecision struct {
	Action         policy.Action
	ApprovalReason string
}

ToolPreflightDecision is a provider-specific safety decision evaluated before a tool is scheduled. It deliberately contains no connection or credential data; the provider must repeat the check at the execution edge.

type ToolRetryPolicy

type ToolRetryPolicy interface {
	ToolRetryAllowed(name string) bool
}

ToolRetryPolicy lets an executor explicitly identify tools whose failed transport/read attempt may be retried without risking a duplicate side effect. The lifecycle layer still records every retry against the same ToolCall/ToolExecution identity.

Jump to

Keyboard shortcuts

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