Documentation
¶
Index ¶
- Constants
- Variables
- func ApprovalIDFromContext(ctx context.Context) string
- func DefaultLinuxHostKeyResolver(_ context.Context, cfg LinuxChannelConfig) (ssh.HostKeyCallback, error)
- func EnabledBypassFromContext(ctx context.Context) bool
- func ErrToolNotEnabled(name string) error
- func IsAskUserInformation(name string) bool
- func IsKnownBuiltinTool(name string) bool
- func IsMemoryForget(name string) bool
- func IsMemoryGet(name string) bool
- func IsMemorySearch(name string) bool
- func IsMemoryTool(name string) bool
- func IsReadImageTool(name string) bool
- func IsRemember(name string) bool
- func IsSkillTool(name string) bool
- func ParseToolArgumentsMap(raw string) map[string]any
- func ParseToolCallArguments(arguments string) string
- func ResultDescriptionSuffixForTool(name string) string
- func ResultEventFields(toolName, content string, failureHint bool) map[string]any
- func ResultEventFieldsWithStatus(toolName, content string, failureHint bool, explicitStatus ResultStatus) map[string]any
- func ResultProtocolPrompt() string
- func SessionIDFromContext(ctx context.Context) string
- func TriggerSessionTargetFromContext(ctx context.Context) string
- func TrustedAutoIdleAgentID(ctx context.Context) string
- func TrustedAutoIdleAvailable(ctx context.Context) bool
- func ValidateAutoIdleArguments(args json.RawMessage) error
- func ValidateLinuxPrivateKeySecret(secret string) error
- func WithApprovalID(ctx context.Context, approvalID string) context.Context
- func WithEnabledBypass(ctx context.Context) context.Context
- func WithHandbookMaintenance(ctx context.Context) context.Context
- func WithHandbookNoopRecorder(ctx context.Context, recorder func(context.Context, HandbookNoop) error) context.Context
- func WithSession(ctx context.Context, sessionID string) context.Context
- func WithToolCallID(ctx context.Context, toolCallID string) context.Context
- func WithTriggerSessionTarget(ctx context.Context, target string) context.Context
- func WithTrustedAutoIdleActivation(ctx context.Context, agentID, triggerID, deliveryID string) context.Context
- type BashCompressConfig
- type EnvironmentPolicy
- type EnvironmentPolicyMode
- type ExecRequest
- type ExecutionContext
- type ExecutionTarget
- type Executor
- type ExitStatus
- type FunctionDef
- type HandbookNoop
- type LinuxChannelBinding
- type LinuxChannelBindingResolver
- type LinuxChannelConfig
- type LinuxChannelResolver
- type LinuxCredential
- type LinuxHostKeyResolver
- type LinuxSecretResolver
- type LinuxShellProvider
- func (p *LinuxShellProvider) InspectRemoteProcess(ctx context.Context, agentID string, recovery RemoteProcessRecovery) (string, error)
- func (p *LinuxShellProvider) OpenTerminal(ctx context.Context, req TerminalRequest) (Terminal, error)
- func (p *LinuxShellProvider) Preflight(ctx context.Context, agentID, channelID, command string) (policy.Action, string, error)
- func (p *LinuxShellProvider) RecoverRemoteProcess(ctx context.Context, agentID string, recovery RemoteProcessRecovery) (string, error)
- func (p *LinuxShellProvider) Start(ctx context.Context, req ExecRequest) (Process, error)
- func (p *LinuxShellProvider) Test(ctx context.Context, target ExecutionTarget) (TargetStatus, error)
- func (p *LinuxShellProvider) WithBindingResolver(resolver LinuxChannelBindingResolver) *LinuxShellProvider
- func (p *LinuxShellProvider) WithHostKeyResolver(resolver LinuxHostKeyResolver) *LinuxShellProvider
- type LinuxTransferEventSink
- type LinuxTransferManager
- type LinuxTransferRequest
- type LinuxTransferSnapshot
- type LocalShellProvider
- type MCPTool
- type MediaArtifactRef
- type MediaRegisterFunc
- type OutputBudget
- type OutputCompressStats
- type Process
- type ProcessEvent
- type ProcessEventSink
- type ProcessEventType
- type ReadImageVisionPayload
- type Registry
- func (r *Registry) CancelAllSessionJobs(sessionID string) int
- func (r *Registry) CancelSyncBash(sessionID, toolCallID string) error
- func (r *Registry) CloseBrowser() error
- func (r *Registry) Definitions() []ToolDef
- func (r *Registry) DefinitionsForContext(ctx context.Context) []ToolDef
- func (r *Registry) Execute(ctx context.Context, name, arguments string) (string, error)
- func (r *Registry) HandbookHistory(ctx context.Context, raw string) ([]handbookfs.Entry, error)
- func (r *Registry) HandbookMutationCount() uint64
- func (r *Registry) HandbookRoot() string
- func (r *Registry) MultimodalEnabled() bool
- func (r *Registry) OpenTerminal(ctx context.Context, req TerminalRequest) (Terminal, error)
- func (r *Registry) PreflightTool(ctx context.Context, name string, args map[string]any) (ToolPreflightDecision, bool)
- func (r *Registry) RegisterChildAgentToolStubs()
- func (r *Registry) ResolveLocalTerminalCWD(raw string) (string, error)
- func (r *Registry) RestoreHandbook(ctx context.Context, raw, expectedDigest string, revision int64) (handbookfs.Entry, error)
- func (r *Registry) SessionToolJobCounts(sessionID string) ToolJobCounts
- func (r *Registry) SetAgentID(agentID string)
- func (r *Registry) SetAutonomyEnabled(enabled bool)
- func (r *Registry) SetAutonomyTodoStore(s *autonomy.Store)
- func (r *Registry) SetBashCompress(cfg BashCompressConfig)
- func (r *Registry) SetBrowserManager(mgr *browser.Manager)
- func (r *Registry) SetBuiltinEnabled(names []string) error
- func (r *Registry) SetBuiltinEnabledNone()
- func (r *Registry) SetHandbookRoot(root string) error
- func (r *Registry) SetMCPTools(remoteTools []MCPTool) error
- func (r *Registry) SetMediaRegister(fn MediaRegisterFunc)
- func (r *Registry) SetMultimodalEnabled(enabled bool)
- func (r *Registry) SetProcessEventSink(sink ProcessEventSink)
- func (r *Registry) SetTerminalConfigResolver(resolver TerminalConfigResolver)
- func (r *Registry) SetTerminalSessionBroker(broker TerminalSessionBroker)
- func (r *Registry) SetTriggerRuntime(store *triggers.Store, sched *triggers.Scheduler, agentID string)
- func (r *Registry) SetWeComClient(client *wecom.Client)
- func (r *Registry) SetWorkspaceCoordinator(c *workspacecoord.Coordinator)
- func (r *Registry) StatRelPath(relPath string) (exists bool, mtime time.Time, err error)
- func (r *Registry) TakeBashCompressStatsForCall(toolCallID string) map[string]any
- func (r *Registry) TakeReadImageVisionForCall(toolCallID string) *ReadImageVisionPayload
- func (r *Registry) TakeToolResultMediaForCall(toolCallID string) map[string]any
- func (r *Registry) ToolRetryAllowed(name string) bool
- func (r *Registry) WithLinuxShellProvider(provider *LinuxShellProvider) error
- func (r *Registry) WithLinuxTransferManager(manager *LinuxTransferManager) error
- func (r *Registry) WithShellProvider(provider ShellProvider) error
- func (r *Registry) WorkspaceRoot() string
- type RemoteProcessRecovery
- type ResultError
- type ResultMetadata
- type ResultStatus
- type ShellProvider
- type TargetStageStatus
- type TargetStatus
- type Terminal
- type TerminalCommandRequest
- type TerminalCommandResult
- type TerminalConfigInfo
- type TerminalConfigResolver
- type TerminalOutput
- type TerminalOutputChunk
- type TerminalProvider
- type TerminalRequest
- type TerminalSessionBroker
- type TerminalSessionInfo
- type ToolDef
- type ToolJobCounts
- type ToolMediaPath
- type ToolPreflight
- type ToolPreflightDecision
- type ToolRetryPolicy
Constants ¶
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 )
const (
// CallPurposeKey 为各工具通用必填参数:简短说明调用目的(Client 首行展示)。
CallPurposeKey = "call_purpose"
)
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.
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 ¶
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.
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.
var ErrSyncShellNotFound = fmt.Errorf("sync bash tool call not found")
ErrSyncShellNotFound 表示没有可控制的同步 bash。
Functions ¶
func ApprovalIDFromContext ¶
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 ¶
EnabledBypassFromContext 是否跳过 enabledOnly 门禁。
func ErrToolNotEnabled ¶
ErrToolNotEnabled 返回未启用工具的 soft-reject 文案(对齐 Workgroup allowlist 风格)。
func IsAskUserInformation ¶
IsAskUserInformation 判断工具名是否为 ask_user_information。
func IsKnownBuiltinTool ¶
IsKnownBuiltinTool 判断是否为可配置的内置工具名。
func IsMemoryForget ¶
func IsMemoryGet ¶
func IsMemorySearch ¶
func IsMemoryTool ¶
func ParseToolArgumentsMap ¶
ParseToolArgumentsMap 解析 tool call arguments JSON。
func ParseToolCallArguments ¶
ParseToolCallArguments 剥离只供界面展示的 call_purpose 后返回 handler 用 JSON。
func ResultDescriptionSuffixForTool ¶
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 ¶
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 ¶
SessionIDFromContext 读取 context 中的 session_id。
func TriggerSessionTargetFromContext ¶
TriggerSessionTargetFromContext 读取 trigger 审批投递目标。
func TrustedAutoIdleAgentID ¶
func TrustedAutoIdleAvailable ¶
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 ¶
ValidateLinuxPrivateKeySecret validates direct API input before it is saved. Environment-backed values are validated later, when the connection is tested.
func WithApprovalID ¶
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 ¶
WithEnabledBypass 跳过 Registry.enabledOnly 检查(子 Agent 在自身 allowlist 校验后使用)。
func WithSession ¶
WithSession 将 session_id 写入 context,供后台任务完成回调使用。
func WithTriggerSessionTarget ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (p *LinuxShellProvider) Start(ctx context.Context, req ExecRequest) (Process, error)
func (*LinuxShellProvider) Test ¶
func (p *LinuxShellProvider) Test(ctx context.Context, target ExecutionTarget) (TargetStatus, error)
func (*LinuxShellProvider) WithBindingResolver ¶
func (p *LinuxShellProvider) WithBindingResolver(resolver LinuxChannelBindingResolver) *LinuxShellProvider
func (*LinuxShellProvider) WithHostKeyResolver ¶
func (p *LinuxShellProvider) WithHostKeyResolver(resolver LinuxHostKeyResolver) *LinuxShellProvider
type LinuxTransferEventSink ¶
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 (m *LinuxTransferManager) List(agentID string) []LinuxTransferSnapshot
func (*LinuxTransferManager) MaxConcurrent ¶
func (m *LinuxTransferManager) MaxConcurrent() int
func (*LinuxTransferManager) Submit ¶
func (m *LinuxTransferManager) Submit(ctx context.Context, req LinuxTransferRequest) (string, error)
type LinuxTransferRequest ¶
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 (p *LocalShellProvider) Start(_ context.Context, req ExecRequest) (Process, error)
func (*LocalShellProvider) Test ¶
func (p *LocalShellProvider) Test(ctx context.Context, target ExecutionTarget) (TargetStatus, error)
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 ¶
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
type OutputCompressStats ¶
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 ¶
CancelAllSessionJobs 取消该 session 下全部同步 bash。
func (*Registry) CancelSyncBash ¶
CancelSyncBash 终止仍在同步等待的 bash_run(按 tool_call_id)。
func (*Registry) CloseBrowser ¶
func (*Registry) Definitions ¶
Definitions 返回传给 LLM 的 tools 列表。
func (*Registry) DefinitionsForContext ¶
func (*Registry) Execute ¶
Execute 按名称 dispatch 工具;未知工具或未启用工具返回 error 文本。 子 Agent RestrictedRegistry 在通过自身 allowlist 后应使用 WithEnabledBypass, 以免父 Agent 的 enabledOnly 误拦子会话允许的工具。
func (*Registry) HandbookHistory ¶
HandbookHistory exposes filesystem history to the control plane without making .history reachable through model-facing file tools.
func (*Registry) HandbookMutationCount ¶
HandbookMutationCount reports successful filesystem history commits for the bound handbook, allowing maintenance to distinguish read-only turns.
func (*Registry) HandbookRoot ¶
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 ¶
MultimodalEnabled 是否已启用多模态工具能力。
func (*Registry) OpenTerminal ¶
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 ¶
ResolveLocalTerminalCWD applies the same workspace-relative path policy as bash_run. An empty value resolves to the Agent workspace root.
func (*Registry) RestoreHandbook ¶
func (*Registry) SessionToolJobCounts ¶
func (r *Registry) SessionToolJobCounts(sessionID string) ToolJobCounts
SessionToolJobCounts 返回指定 session 的工具执行计数。
func (*Registry) SetAgentID ¶
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 ¶
SetAutonomyEnabled exposes Auto-only todo tools on an explicitly selected Auto main runtime.
func (*Registry) SetAutonomyTodoStore ¶
func (*Registry) SetBashCompress ¶
func (r *Registry) SetBashCompress(cfg BashCompressConfig)
SetBashCompress 注入 bash 输出压缩配置(由 Node 启动时从 config.yaml 映射)。
func (*Registry) SetBrowserManager ¶
SetBrowserManager injects the process-level browser manager. Browser tools are ordinary synchronous tools and do not create background jobs.
func (*Registry) SetBuiltinEnabled ¶
SetBuiltinEnabled 设置 LLM 可见/可执行的内置工具允许列表;names 为空表示全部启用。 未列入的工具仍保留 handler(供子 Agent bypass 委托),但 Execute 会 soft reject。
func (*Registry) SetBuiltinEnabledNone ¶
func (r *Registry) SetBuiltinEnabledNone()
SetBuiltinEnabledNone 禁用全部内置工具(显式空允许列表)。
func (*Registry) SetHandbookRoot ¶
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 (*Registry) SetMediaRegister ¶
func (r *Registry) SetMediaRegister(fn MediaRegisterFunc)
func (*Registry) SetMultimodalEnabled ¶
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 ¶
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 ¶
StatRelPath 在 Agent workspace 内 Stat 相对路径(供 Agent 文件信任链 Hook 使用)。
func (*Registry) TakeBashCompressStatsForCall ¶
func (*Registry) TakeReadImageVisionForCall ¶
func (r *Registry) TakeReadImageVisionForCall(toolCallID string) *ReadImageVisionPayload
TakeReadImageVisionForCall 取出并清除 read_image 的视觉 follow-up 载荷。
func (*Registry) TakeToolResultMediaForCall ¶
TakeToolResultMediaForCall 取出并清除 tool result 附带的 media[] SSE 字段。
func (*Registry) ToolRetryAllowed ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
Source Files
¶
- auto_idle.go
- autonomy_todo.go
- bash_compress.go
- bash_policy.go
- bash_run_tool.go
- bash_runner.go
- bash_shell.go
- browser_tool.go
- execution.go
- execution_mode.go
- executor.go
- fs_encoding.go
- fs_encoding_detect.go
- fs_glob_internal.go
- fs_glob_tool.go
- fs_grep_file.go
- fs_grep_files.go
- fs_grep_shared.go
- fs_helpers.go
- fs_path_encoding.go
- fs_read.go
- fs_read_image.go
- fs_search_replace.go
- fs_stat.go
- fs_write.go
- handbook_history.go
- handbook_noop.go
- linux_process.go
- linux_shell_provider.go
- linux_terminal.go
- linux_transfer.go
- linux_transfer_tools.go
- local_terminal.go
- local_terminal_unix.go
- mcp.go
- media_paths.go
- media_register.go
- output_budget.go
- powershell_clixml.go
- read_image_vision.go
- registry.go
- registry_enabled.go
- registry_path.go
- result_contract.go
- shell_execution.go
- shell_output_encoding.go
- shell_platform_unix.go
- shell_process_tree.go
- shell_process_tree_unix.go
- ssh_context.go
- sync_shell_control.go
- terminal.go
- terminal_command.go
- terminal_tools.go
- tool_childagent.go
- tool_desktop.go
- tool_hitl.go
- tool_memory.go
- tool_remember.go
- tool_skills.go
- tool_triggers.go
- tool_wecom.go
- types.go
- workspace_coord.go