runtime

package
v0.1.27 Latest Latest
Warning

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

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

Documentation

Overview

INPUT: SDK bridge client、会话控制请求与子进程关闭态错误。 OUTPUT: Nexus runtime 所需的最小 Client 能力和稳定的关闭语义。 POS: runtime Manager 与具体 SDK bridge 之间的适配边界。

Package runtime 驱动 bridge runtime 的 round 执行与会话生命周期。

L2 | 父级: internal(L1 见 AGENTS.md)

成员清单:

  • client.go:Client 接口、Factory 与 sdkClientAdapter(runtime 需要的最小 SDK 能力抽象),并统一识别进程退出后的关闭态控制错误。
  • session.go / round.go / idle*.go / interrupt.go / streaming_input.go / task.go / mcp.go / goal_accounting.go:Manager 管理 session_key → SDK client、运行中 round、Goal accounting 与 objective revision adoption。
  • guidance.go / contextual_input.go / input_options.go:轮内引导、协商后的 applied ACK 消费回调、隐藏上下文和输入选项剥离。
  • diagnostics_env.go / stderr_line.go:诊断开关、stderr 归一化。
  • goal_usage.go:Goal token 口径换算。
  • round_timeout.go / text_util.go:跨 core/exec 共用的常量与小工具。

子包:exec/(轮次执行内核,ExecuteRound 主链)、trace/(SDK 消息调试字段与摘要)。 系统消息到产品事件的投影统一由 internal/message 负责,runtime 不保留第二套展示语义。

[PROTOCOL]: 变更时更新此头部,然后检查父级入口 AGENTS.md(L1)

INPUT: 运行中 round 的 Goal accounting 回调与 objective revision 指针。 OUTPUT: session/round 级结算、清理、激活和 revision adoption。 POS: runtime Manager 中 Goal 执行态的注册与并发协调入口。

INPUT: 运行中 round 的用户引导与内部上下文。 OUTPUT: PostToolUse 可消费的 SDK additionalContext,以及消费后回调。 POS: runtime 层统一的轮内引导队列与格式化入口。

INPUT: SDK client factory 与 session/round 生命周期状态。 OUTPUT: 并发安全的 runtime session 状态管理器。 POS: runtime client、round、guidance 与 Goal accounting 的共享状态根。

INPUT: session/round 标识、取消函数与权限模式更新。 OUTPUT: round 注册、完成清理、查询与 Agent 级权限同步。 POS: runtime Manager 的 round 生命周期入口。

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"
)
View Source
const RoundIdleAbortTimeout = 5 * time.Second

RoundIdleAbortTimeout 是 round 空闲后中断/断连的宽限:manager 会话空闲回收与 exec 轮次执行共用,故定义在 runtime 核心并导出给 exec 引用。

Variables

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 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 PrepareRoundContentWithContext added in v0.1.27

func PrepareRoundContentWithContext(
	ctx context.Context,
	client Client,
	content any,
	blocks []ContextualInputBlock,
) (any, error)

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
	StopTask(context.Context, string) error
	SendTaskMessage(context.Context, string, string, string) error
	RemoveMessages(context.Context, []string) error
	SetPermissionMode(context.Context, sdkpermission.Mode) 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
	// contains filtered or unexported fields
}

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) AdoptGoalObjectiveRevision added in v0.1.27

func (m *Manager) AdoptGoalObjectiveRevision(sessionKey string, revision int64) []string

AdoptGoalObjectiveRevision 在 steering 真正被 runtime 消费后推进运行中 round 的 revision fence。

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) GetOrCreateWithFactory added in v0.1.27

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

GetOrCreateWithFactory 获取或创建 client,并允许上层为该 session 指定 factory。

Room 的每个 Agent slot 必须和 DM 一样进入统一 Manager,后续 task 控制才能按 runtime session key 找回原进程;factory 仍由 Room 注入,避免破坏测试与定制启动器。

func (*Manager) GetRunningRoundIDs

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

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

func (*Manager) HasSubagentHistory added in v0.1.27

func (m *Manager) HasSubagentHistory(sessionKey string) bool

HasSubagentHistory 判断该 runtime 是否需要为 task follow-up 保留进程。

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) MarkSubagentHistory added in v0.1.27

func (m *Manager) MarkSubagentHistory(sessionKey string)

MarkSubagentHistory 标记该 runtime 已承载过 subagent task。 标记随 sessionState 生命周期保留,使父 round 结束后仍可复用同一 task/thread。

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) QueueContextualGuidanceInputOnConsumed added in v0.1.27

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

QueueContextualGuidanceInputOnConsumed 暂存内部上下文,并在 PostToolUse 真正取走该上下文后执行回调。

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) RegisterGoalObjectiveRevision added in v0.1.27

func (m *Manager) RegisterGoalObjectiveRevision(sessionKey string, roundID string, revision *atomic.Int64)

RegisterGoalObjectiveRevision 让运行中 round 的 MCP 与终态回调共享同一 objective revision。

func (*Manager) RuntimeKind added in v0.1.27

func (m *Manager) RuntimeKind(sessionKey string) agentclient.RuntimeKind

RuntimeKind 返回当前 session 实际持有的 runtime 类型。

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) SetPermissionModeForAgent added in v0.1.27

func (m *Manager) SetPermissionModeForAgent(ctx context.Context, agentID string, mode sdkpermission.Mode) error

SetPermissionModeForAgent 将权限模式热同步到指定 agent 已存在的 DM runtime。

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) SupportsHookResponseAck added in v0.1.27

func (m *Manager) SupportsHookResponseAck(sessionKey string) bool

SupportsHookResponseAck 报告当前 session 是否协商了 hook 输出应用确认。

func (*Manager) UpdateEnvironmentForAgent added in v0.1.27

func (m *Manager) UpdateEnvironmentForAgent(ctx context.Context, agentID string, environment map[string]string) error

UpdateEnvironmentForAgent 将 WebSearch 等运行期环境同步到指定 Agent 的 nxs 会话。

func (*Manager) WithGuidanceHook added in v0.1.2

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

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

Directories

Path Synopsis
Package clientopts 组装 SDK runtime client 的启动选项、provider 解析与环境。
Package clientopts 组装 SDK runtime client 的启动选项、provider 解析与环境。
Package exec 是轮次执行内核:ExecuteRound 主链(query → receive → map → persist → emit)。
Package exec 是轮次执行内核:ExecuteRound 主链(query → receive → map → persist → emit)。
Package permission 处理 runtime 工具权限请求的呈现与 WebSocket 交互。
Package permission 处理 runtime 工具权限请求的呈现与 WebSocket 交互。
Package provider 归一化用户可配置的 runtime kind。
Package provider 归一化用户可配置的 runtime kind。
Package trace 把 SDK 消息解析为调试日志字段与单行摘要。
Package trace 把 SDK 消息解析为调试日志字段与单行摘要。

Jump to

Keyboard shortcuts

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