runtime

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// AgentSDKDiagnosticsEnvName 控制 Agent SDK 诊断事件输出。
	AgentSDKDiagnosticsEnvName = "NEXUS_AGENT_SDK_DIAGNOSTICS"
	// AgentSDKDebugEnvName 兼容 SDK debug 开关,开启后也输出诊断事件。
	AgentSDKDebugEnvName = "NEXUS_AGENT_SDK_DEBUG"
	// AgentSDKProviderDebugBodyEnvName 控制 provider 请求体诊断输出范围。
	AgentSDKProviderDebugBodyEnvName = "NEXUS_AGENT_SDK_PROVIDER_DEBUG_BODY"
)

Variables

View Source
var (
	// ErrRoundInterrupted 表示 round 在收到终态前被中断。
	ErrRoundInterrupted = errors.New("round interrupted")
	// ErrRoundStreamClosedBeforeTerminal 表示 SDK 在产出终态前提前结束消息流。
	ErrRoundStreamClosedBeforeTerminal = errors.New("round stream closed before terminal")
	// ErrRoundStreamIdleTimeout 表示 SDK 消息流长时间无新事件且未结束。
	ErrRoundStreamIdleTimeout = errors.New("round stream idle timeout")
)
View Source
var (
	// ErrNoRunningRound 表示当前 session 没有可接收排队输入的运行中 round。
	ErrNoRunningRound = errors.New("runtime session has no running round")
	// ErrStreamingInputUnsupported 表示底层 client 不支持流式排队输入。
	ErrStreamingInputUnsupported = errors.New("runtime client does not support streaming input")
)

Functions

func AgentSDKDiagnosticsEnabled added in v0.1.17

func AgentSDKDiagnosticsEnabled(env map[string]string) bool

AgentSDKDiagnosticsEnabled 判断当前 runtime 环境是否开启 Agent SDK 诊断。

func AgentSDKDiagnosticsValue added in v0.1.17

func AgentSDKDiagnosticsValue(env map[string]string) string

AgentSDKDiagnosticsValue 返回当前生效的诊断开关值。

func AgentSDKProviderDebugBodyValue added in v0.1.17

func AgentSDKProviderDebugBodyValue(env map[string]string) string

AgentSDKProviderDebugBodyValue 返回请求体诊断开关值,仅用于日志摘要。

func BuildSDKMessageLogFields

func BuildSDKMessageLogFields(message sdkprotocol.ReceivedMessage) []any

BuildSDKMessageLogFields 生成 SDK 消息调试日志字段。

func BuildSDKMessageLogFieldsWithOptions added in v0.1.3

func BuildSDKMessageLogFieldsWithOptions(
	message sdkprotocol.ReceivedMessage,
	options SDKMessageLogOptions,
) []any

BuildSDKMessageLogFieldsWithOptions 按选项生成 SDK 消息调试日志字段。

func BuildSDKMessageLogSummary

func BuildSDKMessageLogSummary(message sdkprotocol.ReceivedMessage) string

BuildSDKMessageLogSummary 生成适合调试视图的单行摘要。

func FormatGuidanceAdditionalContext added in v0.1.2

func FormatGuidanceAdditionalContext(inputs []GuidedInput) string

FormatGuidanceAdditionalContext 把待注入引导渲染成 hook additionalContext。

func GoalUsageFromRaw added in v0.1.15

func GoalUsageFromRaw(raw any) (protocol.GoalUsage, bool)

GoalUsageFromRaw 从动态 usage JSON 提取 Goal accounting usage。

func GoalUsageFromTokenUsage added in v0.1.15

func GoalUsageFromTokenUsage(usage sdkprotocol.TokenUsage) protocol.GoalUsage

GoalUsageFromTokenUsage 把 SDK usage 转成 Goal accounting 口径。

func IsRuntimeTransportClosedError added in v0.1.9

func IsRuntimeTransportClosedError(err error) bool

IsRuntimeTransportClosedError 判断底层 SDK transport 是否已经断开。

func NormalizeRuntimeStderrLine added in v0.1.17

func NormalizeRuntimeStderrLine(line string) string

NormalizeRuntimeStderrLine 归一化 runtime 子进程 stderr 单行内容。

func QueryClientContent added in v0.1.7

func QueryClientContent(ctx context.Context, client Client, content any) error

QueryClientContent 通过 SDK client 启动一轮用户输入,图片等结构化输入走 content block。

func QueryClientContentWithOptions added in v0.1.15

func QueryClientContentWithOptions(ctx context.Context, client Client, content any, options sdkprotocol.OutboundMessageOptions) error

QueryClientContentWithOptions 通过 SDK client 启动一轮带附加语义的用户输入。

func ResultUsageLimitReached added in v0.1.15

func ResultUsageLimitReached(result *sdkprotocol.ResultMessage) (bool, string)

ResultUsageLimitReached 判断 result 是否明确表示账号/计划 usage limit,而不是普通 token/context limit。

func RuntimeInputOptionsForPurpose added in v0.1.15

func RuntimeInputOptionsForPurpose(options sdkprotocol.OutboundMessageOptions, purpose string) sdkprotocol.OutboundMessageOptions

RuntimeInputOptionsForPurpose 剥离只属于本地队列/历史层的控制字段。

func SendClientContent added in v0.1.2

func SendClientContent(ctx context.Context, client Client, content any) error

SendClientContent 通过 SDK streaming input 向活动 client 投递用户输入。

func SendClientContentWithOptions added in v0.1.15

func SendClientContentWithOptions(ctx context.Context, client Client, content any, options sdkprotocol.OutboundMessageOptions) error

SendClientContentWithOptions 通过 SDK streaming input 投递带附加语义的用户输入。

func WithPostToolUseGuidanceHook added in v0.1.2

func WithPostToolUseGuidanceHook(options agentclient.Options, callback sdkhook.Callback) agentclient.Options

WithPostToolUseGuidanceHook 给 SDK options 追加一个 PostToolUse 引导 hook。

Types

type Client

type Client interface {
	Connect(context.Context) error
	Query(context.Context, string) error
	ReceiveMessages(context.Context) <-chan sdkprotocol.ReceivedMessage
	Interrupt(context.Context) error
	Disconnect(context.Context) error
	Reconfigure(context.Context, agentclient.Options) error
	SessionID() string
}

Client 抽象出运行时需要的最小 SDK 能力,便于测试替身接入。

func WrapSDKClient

func WrapSDKClient(options agentclient.Options) Client

type ContextualInputBlock added in v0.1.15

type ContextualInputBlock struct {
	Name     string
	Content  string
	Priority int
	Metadata map[string]string
}

ContextualInputBlock 表示运行时拥有、应注入到下一轮模型输入的隐藏上下文。

func NewContextualInputBlock added in v0.1.15

func NewContextualInputBlock(name string, content string, priority int, metadata map[string]string) ContextualInputBlock

type Factory

type Factory interface {
	New(agentclient.Options) Client
}

Factory 负责创建 SDK client。

type GoalAccountingActivate added in v0.1.15

type GoalAccountingActivate func(context.Context) error

GoalAccountingActivate 由正在运行的 round 提供,用于 Goal 恢复 active 后重置计量基线。

type GoalAccountingClear added in v0.1.15

type GoalAccountingClear func()

GoalAccountingClear 由正在运行的 round 提供,用于 Goal 停止后关闭后续计量。

type GoalAccountingFlush added in v0.1.15

type GoalAccountingFlush func(context.Context) error

GoalAccountingFlush 由正在运行的 round 提供,用于外部 Goal 状态变化前结算当前进度。

type GuidedInput added in v0.1.2

type GuidedInput struct {
	RoundID     string
	Content     string
	ContextName string
}

GuidedInput 是等待注入当前 round 的用户引导或运行时上下文。

type Manager

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

Manager 管理 session_key -> SDK client 与运行中 round。

func NewManager

func NewManager() *Manager

NewManager 创建运行时管理器。

func NewManagerWithFactory

func NewManagerWithFactory(factory Factory) *Manager

NewManagerWithFactory 使用自定义 factory 创建运行时管理器。

func (*Manager) ActivateGoalAccounting added in v0.1.15

func (m *Manager) ActivateGoalAccounting(ctx context.Context, sessionKey string) ([]string, error)

ActivateGoalAccounting 要求指定 session 的运行中 round 从当前快照开始归属 Goal usage。

func (*Manager) ClearGoalAccounting added in v0.1.15

func (m *Manager) ClearGoalAccounting(sessionKey string) []string

ClearGoalAccounting 要求指定 session 的运行中 round 停止把后续 usage 归属到当前 Goal。

func (*Manager) CloseIdleSessions added in v0.1.14

func (m *Manager) CloseIdleSessions(ctx context.Context, idleFor time.Duration) (int, error)

CloseIdleSessions 回收超过空闲阈值且没有运行中 round 的 SDK client。

func (*Manager) CloseSession

func (m *Manager) CloseSession(ctx context.Context, sessionKey string) error

CloseSession 关闭指定 session。

func (*Manager) CountRunningRounds

func (m *Manager) CountRunningRounds(agentID string) int

CountRunningRounds 统计指定 Agent 当前活跃 round 数量。

func (*Manager) FlushGoalAccounting added in v0.1.15

func (m *Manager) FlushGoalAccounting(ctx context.Context, sessionKey string) ([]string, error)

FlushGoalAccounting 要求指定 session 的运行中 round 结算当前 Goal progress。

func (*Manager) GetInterruptReason

func (m *Manager) GetInterruptReason(sessionKey string, roundID string) string

GetInterruptReason 返回 round 是否已收到显式中断请求。

func (*Manager) GetOrCreate

func (m *Manager) GetOrCreate(ctx context.Context, sessionKey string, options agentclient.Options) (Client, error)

GetOrCreate 获取或创建 client,并在复用时应用最新运行时配置。

func (*Manager) GetRunningRoundIDs

func (m *Manager) GetRunningRoundIDs(sessionKey string) []string

GetRunningRoundIDs 返回当前 session 的运行中轮次。

func (*Manager) InterruptSession

func (m *Manager) InterruptSession(ctx context.Context, sessionKey string, reason string) ([]string, error)

InterruptSession 中断当前 session 的全部运行中 round。

func (*Manager) MarkRoundFinished

func (m *Manager) MarkRoundFinished(sessionKey string, roundID string)

MarkRoundFinished 把 round 从运行态中移除。

func (*Manager) PendingGuidanceCount added in v0.1.2

func (m *Manager) PendingGuidanceCount(sessionKey string) int

PendingGuidanceCount 返回当前 session 中尚未被 hook 注入的引导数量。

func (*Manager) QueueContextualGuidanceInput added in v0.1.15

func (m *Manager) QueueContextualGuidanceInput(_ context.Context, sessionKey string, roundID string, contextName string, content string) ([]string, error)

QueueContextualGuidanceInput 把运行时拥有的上下文暂存到运行中 session。

func (*Manager) QueueGuidanceInput added in v0.1.2

func (m *Manager) QueueGuidanceInput(_ context.Context, sessionKey string, roundID string, content string) ([]string, error)

QueueGuidanceInput 把用户引导暂存到运行中 session,等待 PostToolUse hook 消费。

func (*Manager) RegisterGoalAccountingActivate added in v0.1.15

func (m *Manager) RegisterGoalAccountingActivate(sessionKey string, roundID string, activate GoalAccountingActivate)

RegisterGoalAccountingActivate 注册或移除运行中 round 的 Goal accounting active 回调。

func (*Manager) RegisterGoalAccountingClear added in v0.1.15

func (m *Manager) RegisterGoalAccountingClear(sessionKey string, roundID string, clear GoalAccountingClear)

RegisterGoalAccountingClear 注册或移除运行中 round 的 Goal accounting clear 回调。

func (*Manager) RegisterGoalAccountingFlush added in v0.1.15

func (m *Manager) RegisterGoalAccountingFlush(sessionKey string, roundID string, flush GoalAccountingFlush)

RegisterGoalAccountingFlush 注册或移除运行中 round 的 Goal accounting flush 回调。

func (*Manager) SendContentToRunningRound added in v0.1.2

func (m *Manager) SendContentToRunningRound(ctx context.Context, sessionKey string, content any) ([]string, error)

SendContentToRunningRound 把新输入排入当前运行中的 SDK 流。

func (*Manager) StartRound

func (m *Manager) StartRound(sessionKey string, roundID string, cancel context.CancelFunc)

StartRound 注册运行中的 round,并记录其取消函数。

func (*Manager) WithGuidanceHook added in v0.1.2

func (m *Manager) WithGuidanceHook(options agentclient.Options, sessionKey string) agentclient.Options

WithGuidanceHook 给 SDK options 挂载 Nexus 运行时引导 hook。

type RoundExecutionRequest

type RoundExecutionRequest struct {
	Query                  string
	Content                any
	ContextualInputs       []ContextualInputBlock
	InputOptions           sdkprotocol.OutboundMessageOptions
	Client                 Client
	Mapper                 RoundMapper
	IdleTimeout            time.Duration
	InterruptReason        func() string
	AssistantTerminalGrace time.Duration
	SyncSessionID          func(string) error
	AfterQuery             func() error
	HandleDurableMessage   func(protocol.Message) error
	EmitEvent              func(protocol.EventMessage) error
	ObserveIncomingMessage func(sdkprotocol.ReceivedMessage)
}

RoundExecutionRequest 表示执行单轮查询所需的回调与依赖。

type RoundExecutionResult

type RoundExecutionResult struct {
	TerminalStatus       string
	ResultSubtype        string
	ErrorMessage         string
	TerminalCategory     sdkprotocol.TerminalCategory
	Usage                sdkprotocol.TokenUsage
	ElapsedTimeSeconds   int64
	CompletedByAssistant bool
	UsageLimitReached    bool
	UsageLimitReason     string
}

RoundExecutionResult 表示 round 执行的终态结果。

func ExecuteRound

func ExecuteRound(
	ctx context.Context,
	request RoundExecutionRequest,
) (RoundExecutionResult, error)

ExecuteRound 统一执行 query -> receive -> map -> persist -> emit 的主链路。

type RoundMapResult

type RoundMapResult struct {
	Events          []protocol.EventMessage
	DurableMessages []protocol.Message
	TerminalStatus  string
	ResultSubtype   string
}

RoundMapResult 表示单条 SDK 消息映射后的统一结果。

type RoundMapper

type RoundMapper interface {
	Map(sdkprotocol.ReceivedMessage, ...string) (RoundMapResult, error)
	SessionID() string
}

RoundMapper 负责把 SDK 消息映射成统一事件与 durable 消息。

type RoundStreamClosedError added in v0.1.1

type RoundStreamClosedError struct {
	MessagesSeen       int
	LastMessageType    string
	LastMessageSummary string
	LastSessionID      string
	LastMessageID      string
	ReadError          string
	WaitError          string
}

RoundStreamClosedError 携带 SDK 流提前关闭时的定位信息。

func (*RoundStreamClosedError) Error added in v0.1.1

func (e *RoundStreamClosedError) Error() string

func (*RoundStreamClosedError) Unwrap added in v0.1.1

func (e *RoundStreamClosedError) Unwrap() error

type RoundStreamIdleTimeoutError added in v0.1.2

type RoundStreamIdleTimeoutError struct {
	IdleTimeout        time.Duration
	MessagesSeen       int
	LastMessageType    string
	LastMessageSummary string
	LastSessionID      string
	LastMessageID      string
}

RoundStreamIdleTimeoutError 携带 SDK 流空闲超时时的定位信息。

func (*RoundStreamIdleTimeoutError) Error added in v0.1.2

func (*RoundStreamIdleTimeoutError) Unwrap added in v0.1.2

func (e *RoundStreamIdleTimeoutError) Unwrap() error

type SDKMessageLogOptions added in v0.1.3

type SDKMessageLogOptions struct {
	IncludeStreamEvent  bool
	IncludeSnapshotData bool
}

SDKMessageLogOptions 控制 SDK 消息调试日志的输出范围。

func DefaultSDKMessageLogOptions added in v0.1.3

func DefaultSDKMessageLogOptions() SDKMessageLogOptions

DefaultSDKMessageLogOptions 返回兼容历史行为的 SDK 消息日志选项。

type SystemMessageSummary

type SystemMessageSummary struct {
	Subtype  string
	Content  string
	Metadata map[string]any
}

SystemMessageSummary 表示系统消息面向前端的统一摘要。

func SummarizeSystemMessage

func SummarizeSystemMessage(message *sdkprotocol.SystemMessage) (SystemMessageSummary, bool)

SummarizeSystemMessage 把 SDK system 消息收口成前端可消费的系统事件。

Directories

Path Synopsis
mcp
automation
Package automationmcp 提供 nexus_automation MCP server 入口。
Package automationmcp 提供 nexus_automation MCP server 入口。
automation/contract
Package contract 定义 nexus_automation MCP 子包之间共享的契约: Service 接口、ServerContext 上下文、ServerName 常量。
Package contract 定义 nexus_automation MCP 子包之间共享的契约: Service 接口、ServerContext 上下文、ServerName 常量。
automation/internal/argx
Package argx 提供 MCP 工具入参的基础类型转换与访问器。
Package argx 提供 MCP 工具入参的基础类型转换与访问器。
automation/internal/builder
Package builder 把 MCP 工具入参里的对象翻译成 automation 底层结构, 并复用底层的 Normalize + Validate。
Package builder 把 MCP 工具入参里的对象翻译成 automation 底层结构, 并复用底层的 Normalize + Validate。
automation/internal/render
Package render 负责把 MCP 工具返回值序列化为 MCPToolResult, 并为时间字段追加本地化 *_display 展示。
Package render 负责把 MCP 工具返回值序列化为 MCPToolResult, 并为时间字段追加本地化 *_display 展示。
automation/internal/semantic
Package semantic 承载页面语义(execution_mode/reply_mode) 到 automation 底层 SessionTarget / DeliveryTarget / Source 的翻译、校验与默认值守卫。
Package semantic 承载页面语义(execution_mode/reply_mode) 到 automation 底层 SessionTarget / DeliveryTarget / Source 的翻译、校验与默认值守卫。
automation/tool
Package tool 定义 nexus_automation MCP 暴露的定时任务工具。
Package tool 定义 nexus_automation MCP 暴露的定时任务工具。
connectors
Package connectormcp 提供 nexus_connectors MCP server 入口。
Package connectormcp 提供 nexus_connectors MCP server 入口。
imagegen
Package imagegenmcp 提供 nexus_imagegen MCP server 入口。
Package imagegenmcp 提供 nexus_imagegen MCP server 入口。
imagegen/contract
Package contract 定义 nexus_imagegen MCP 子包共享的服务契约与上下文。
Package contract 定义 nexus_imagegen MCP 子包共享的服务契约与上下文。
imagegen/tool
Package tool 定义 nexus_imagegen MCP 暴露的图片生成工具。
Package tool 定义 nexus_imagegen MCP 暴露的图片生成工具。
room
Package roommcp 提供 Room 通讯内建 MCP server 入口。
Package roommcp 提供 Room 通讯内建 MCP server 入口。
room/contract
Package contract 定义 nexus_room MCP 子包之间共享的契约。
Package contract 定义 nexus_room MCP 子包之间共享的契约。
room/tool
Package tool 定义 nexus_room MCP 暴露的 Room 通讯工具。
Package tool 定义 nexus_room MCP 暴露的 Room 通讯工具。
sdktool
Package sdktool 把 Nexus 内部 MCP 工具描述装配成 Agent SDK tool。
Package sdktool 把 Nexus 内部 MCP 工具描述装配成 Agent SDK tool。

Jump to

Keyboard shortcuts

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