runtime

package
v0.1.24 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// AgentSDKDiagnosticsEnvName 控制 Agent SDK 诊断事件输出。
	AgentSDKDiagnosticsEnvName = "NEXUS_AGENT_SDK_DIAGNOSTICS"
	// AgentSDKDiagnosticsJSONLEnvName 控制 Agent SDK session JSONL 诊断输出。
	AgentSDKDiagnosticsJSONLEnvName = "NEXUS_AGENT_SDK_DIAGNOSTICS_JSONL"
	// AgentSDKDiagnosticsStreamProgressEnvName 控制瞬时 stream 诊断事件输出。
	AgentSDKDiagnosticsStreamProgressEnvName = "NEXUS_AGENT_SDK_DIAGNOSTICS_STREAM_PROGRESS"
	// 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 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 RoundStreamStopDiagnosticLogFields added in v0.1.21

func RoundStreamStopDiagnosticLogFields(diagnostics RoundStreamStopDiagnostics) []any

RoundStreamStopDiagnosticLogFields 返回 message_stop 诊断日志字段。

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
	StopTask(context.Context, string) error
	SendTaskMessage(context.Context, string, string, string) 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 IdleMessageHandler added in v0.1.23

type IdleMessageHandler func(context.Context, sdkprotocol.ReceivedMessage) bool

IdleMessageHandler 处理 round 外到达的 SDK 消息。返回 false 表示停止 drain。

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) SendTaskMessage added in v0.1.23

func (m *Manager) SendTaskMessage(ctx context.Context, sessionKey string, taskID string, message string, summary string) error

SendTaskMessage 向指定 session 的后台任务投递一条后续消息。

func (*Manager) StartIdleMessageDrain added in v0.1.23

func (m *Manager) StartIdleMessageDrain(sessionKey string, handler IdleMessageHandler)

StartIdleMessageDrain 在没有活动 round 时接管 client 消息,用于后台 task 通知。

func (*Manager) StartRound

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

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

func (*Manager) StopTask added in v0.1.23

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

StopTask 停止指定 session 中的后台任务。

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
	LastStreamStop     RoundStreamStopDiagnostics
}

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
	LastStreamStop     RoundStreamStopDiagnostics
}

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

func (*RoundStreamIdleTimeoutError) Error added in v0.1.2

func (*RoundStreamIdleTimeoutError) Unwrap added in v0.1.2

func (e *RoundStreamIdleTimeoutError) Unwrap() error

type RoundStreamStopDiagnostics added in v0.1.21

type RoundStreamStopDiagnostics struct {
	Observed                  bool
	MessageIndex              int
	MessagesAfter             int
	ConversationMessagesAfter int
	ProgressMessagesAfter     int
	PassiveMessagesAfter      int
	UnknownMessagesAfter      int
	Age                       time.Duration
	Summary                   string
	StopReason                string
	SessionID                 string
	MessageID                 string
	Model                     string
}

RoundStreamStopDiagnostics 表示最近一次 provider message_stop 的定位信息。

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

Jump to

Keyboard shortcuts

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