Documentation
¶
Overview ¶
Package agentstate 是 Agent 会话状态机(#113,设计稿 04 §2):纯函数,没有数据库、没有时钟、没有全局变量。
- Apply:把一个事件(hook、MCP 调用、屏幕扫描器……)折进会话快照,得到新的快照和「这次发生了什么」;
- Evaluate:给定快照和「现在」,推导展示用的状态(offline / waiting_you 叠加、卡住标志);
- 身份显示名(label.go)与 hook 自报字段的清洗(wire.go)。
存储、节流写库、SSE 广播都在 store / mcp 里;这里只做判断,所以可以用表驱动测试把中断序列、乱序、时钟回拨这些边界一条条钉住。
Index ¶
- Constants
- func Apply(s Snapshot, e Event, c Config) (Snapshot, Change)
- func BaseLabel(in LabelInput) string
- func DirectoryName(dir string) string
- func Labels(items []LabelInput) map[uint]Label
- func NormalizeClientKind(s string) string
- func NormalizeEndReason(s, fallback string) string
- func NormalizeStopStatus(s string) string
- func NormalizeVersion(s string) string
- func ParseUnixMilli(ms int64, now time.Time) time.Time
- func ParseWire(kind, status string) (name, norm string, ok bool)
- func SanitizeTool(s string) string
- type Change
- type Config
- type EvalInput
- type Event
- type Label
- type LabelInput
- type ScreenSignal
- type Snapshot
- type Source
- type State
- type Thresholds
- type View
Constants ¶
const ( SubThinking = "thinking" SubResponding = "responding" SubToolPrefix = "tool:" )
工作中的子状态。工具调用写成 "tool:<名>"。
const ( EvSessionStart = "session_start" // sessionStart EvSessionEnd = "session_end" // sessionEnd EvPrompt = "prompt" // beforeSubmitPrompt:一轮新对话开始 EvThought = "thought" // afterAgentThought:思考心跳 EvToolStart = "tool_start" // preToolUse EvToolEnd = "tool_end" // postToolUse(旧版 hook 汇报的 tool 就是它) EvToolFail = "tool_fail" // postToolUseFailure EvResponse = "response" // afterAgentResponse EvStop = "stop" // stop:一轮结束(Status 是 completed / aborted / error / other) EvCompact = "compact" // preCompact EvChatEnd = "chat_end" // Agent 主动结束(Status 是 completed / blocked / aborted / handoff) EvApprovalWait = "approval_wait" // 屏幕出现 Waiting for approval EvApprovalDone = "approval_done" // 审批等待结束 )
事件名。其中 session_start / session_end / prompt / thought / tool_start / tool_end / tool_fail / response / stop / compact 对应 Cursor 的 hook,chat_end 由 Hub 在 Agent 主动结束会话时产生,approval_* 由托管终端的屏幕扫描器产生(第 3 阶段)。
const ( StopCompleted = "completed" StopAborted = "aborted" StopError = "error" StopOther = "other" )
stop 事件的结束状态。其他取值一律当作 StopOther。
const ( EndCompleted = "completed" EndBlocked = "blocked" EndAborted = "aborted" EndHandoff = "handoff" EndError = "error" EndClosed = "closed" // sessionEnd 没有给出更具体的原因 )
会话结束的原因(EndReason)。
const ( NoteUnknown = "unknown_event" NoteDuplicate = "duplicate" NoteLate = "late" NoteEndedTail = "ended_tail" NoteAbortTail = "abort_tail" NoteFoldedError = "folded_error" NoteRevived = "revived" NoteAbortOverError = "abort_over_error" NoteAlreadyEnded = "already_ended" NoteStopOther = "stop_other" NoteToolFailed = "tool_failed" NoteIgnored = "ignored" // NoteRunAuthority:这个对话正由 Hub 读非交互运行的输出判定状态,hook 的汇报只留记录、不改状态(由 store 标注)。 NoteRunAuthority = "run_authority" )
Change.Note 的取值:说明这次事件为什么没有(或怎样)改变状态,写进事件的 extra 里便于排查。
const ( ReasonQuietSoft = "quiet_soft" // 思考 / 回复中静默超过软阈值 ReasonQuiet = "quiet" // 静默超过硬阈值 ReasonToolRunning = "tool_running" // 工具执行了一阵子:可能在等批准(不报警) ReasonToolOverrun = "tool_overrun" // 工具超过类型上限 ReasonApprovalOverdue = "approval_overdue" // 等批准太久 ReasonTokensFlat = "tokens_flat" // 托管终端:token 计数停了但屏幕还在动(软标记) ReasonTerminalFrozen = "terminal_frozen" // 托管终端:屏幕没有任何输出(硬卡住) )
卡住 / 异常的原因代码(前端按代码配文案)。
Variables ¶
This section is empty.
Functions ¶
func DirectoryName ¶
DirectoryName 取路径的最后一段,Unix 与 Windows 风格的分隔符都认;取不到返回空串。
func Labels ¶
func Labels(items []LabelInput) map[uint]Label
Labels 计算一批身份的显示名(同一批里才会比较重名,调用方传入同一个用户的全部身份)。
func NormalizeClientKind ¶
NormalizeClientKind 把客户端类型收敛到 ide / cli / unknown;没报就是空串。
func NormalizeEndReason ¶
NormalizeEndReason 把会话结束的原因收敛到已知取值;认不出就用 fallback。
func NormalizeStopStatus ¶
NormalizeStopStatus 把 stop 的结束状态收敛到 completed / aborted / error / other。
func NormalizeVersion ¶
NormalizeVersion 清洗客户端版本号:只认字母数字与 . _ + -,最长 32 位;不合格当作没有。
func ParseUnixMilli ¶
ParseUnixMilli 把 hook 自报的毫秒时间戳转成 time.Time;明显不对(非正、早于 2020 年、比现在晚一天以上)就当没有。
func ParseWire ¶
ParseWire 把 hook 随 inbox_peek 汇报的 agent_event / agent_status 翻译成状态机事件。 旧版 hook 只会报 tool(= postToolUse)与 stop;chat_end、approval_* 只能由 Hub 自己产生,hook 报这些名字一律不认。
func SanitizeTool ¶
SanitizeTool 清洗工具名:只留字母数字与 _ : . -,其余换成 _,最长 64 个字符。
Types ¶
type Change ¶
type Change struct {
At time.Time // 事件的有效时间(发送端时间可信就用它,否则是接收时间)
Record bool // 值得写进 agent_events(重复事件、被节流的思考心跳为 false)
StateChanged bool // State 或 Sub 变了(要不要给前端推 SSE)
Durable bool // 快照里除时间戳之外的字段变了(要写库);只是心跳时为 false
Note string // 见 Note* 常量;空串 = 事件正常生效
}
Change 描述一次 Apply 的结果。
type Config ¶
type Config struct {
DedupeWindow time.Duration // 同一事件在这个窗口内重复出现只算一次
ThoughtRecordEvery time.Duration // 思考心跳写进事件表的最小间隔(状态照常刷新)
AbortFoldWindow time.Duration // 中断之后这个窗口内补发的 stop(error) / 收尾事件并入中断序列
EndedTail time.Duration // 会话结束之后这个窗口内到达的收尾事件不算「重新开始」
LateWindow time.Duration // 比最近事件早不到这个窗口的事件算乱序迟到;更早的视为发送端时钟回拨,改用接收时间
FutureTolerance time.Duration // 发送端时间领先接收时间超过这个值就不可信,改用接收时间
}
Config 是状态机的时间参数。零值不可用,用 DefaultConfig。
type EvalInput ¶
type EvalInput struct {
Snap Snapshot
Now time.Time
LastMCPAt time.Time // MCP 侧最近一次活动(零值 = 不知道)
WaitingYou bool // Agent 正阻塞等人回答(调用方从待答复的汇报推导)
HasLiveTerminal bool // 有活的托管终端(第 3 阶段;有的话不判 offline)
Screen *ScreenSignal // 托管终端的屏幕信号;nil = 没有托管终端或没有可用信号
}
EvalInput 是 Evaluate 的输入。
type Event ¶
type Event struct {
Source Source
Name string // Ev* 之一
At time.Time // 发送端自报的时间;零值 = 没有(以接收时间为准)
Received time.Time // Hub 收到的时间;Apply 的时间判断以它为兜底,调用方必须填
Tool string // tool_start / tool_end / tool_fail 的工具名(已清洗)
Status string // stop 的结束状态,或 session_end / chat_end 的原因
Duration time.Duration // tool_end 的耗时(只用于记录)
}
Event 是喂给状态机的一个事件。
type LabelInput ¶
type LabelInput struct {
ID uint
HostName string
ProjectDirectory string
Name string // 用户改的名字;空 = 用目录名
}
LabelInput 是计算显示名需要的字段。
type ScreenSignal ¶
type ScreenSignal struct {
Verified bool
Animating bool // 最近 2 秒仍有输出字节
Approval bool // 屏幕停在 Waiting for approval
Tokens int // 状态行里的实时 token 数;-1 = 没读到
TokensSince time.Time // 计数最近一次变化的时间(Hub 记录,零值 = 不知道)
QuietFor time.Duration // 屏幕距最后一次输出多久;<0 = 不知道
CtxPct float64 // 上下文占用百分比;<0 = 没读到
}
ScreenSignal 是托管终端屏幕扫描器给状态判断的输入(M3.2)。只有 Verified(cursor 版本在已验证清单里)时才会被采信; 未验证时调用方应传 nil 或 Verified=false,判断退回纯 hook 规则,不产生任何屏幕相关的告警。
type Snapshot ¶
type Snapshot struct {
State State
Sub string // 工作中的子状态:thinking / responding / tool:<名>;其他状态为空
Since time.Time // 进入当前 State 的时间(只换子状态不重置)
// Source 是最近一次「正常生效」的 hook / 屏幕 / 运行输出事件的来源(MCP、守护、Web 这类 Hub 侧的事件不算):
// 告诉前端「现在这个状态是谁说的」。空 = 没有记录(旧数据)。
Source Source
StartedAt time.Time
EndedAt time.Time
EndReason string
LastEventAt time.Time // 最近一次被采纳的事件的有效时间
LastRecv time.Time // 那次事件的接收时间(用来识别发送端时钟回拨)
LastTool string
ToolStartedAt time.Time // 当前(或最近一次)工具开始的时间
TurnStartedAt time.Time
TurnEndedAt time.Time
// contains filtered or unexported fields
}
Snapshot 是一个会话(一个 Cursor 对话)在某一时刻的状态。零值就是「还没见过」(State == "")。 小写字段只在内存里:去重与节流用,Hub 重启后清零,不影响正确性。
type Source ¶
type Source string
Source 是事件的来源。
const ( SourceHook Source = "hook" SourceMCP Source = "mcp" SourceTUI Source = "tui" SourceGuard Source = "guard" SourceWeb Source = "web" // SourceRun 是 Hub 自己读到的非交互运行的输出(agent -p --output-format stream-json): // 每个思考、工具调用、回复与结束都是确定的事件,不依赖编辑器 hook;运行期间它比 hook 更权威(见 store 的运行权威标记)。 SourceRun Source = "run" )
type State ¶
type State string
State 是会话的状态。waiting_you 与 offline 只是展示态(见 Evaluate),不会出现在 Snapshot.State 里。
const ( StateIdle State = "idle" // 本轮结束,等下一条 StateWorking State = "working" // 在干活(子状态见 Snapshot.Sub) StateWaitingApproval State = "waiting_approval" // 等人批准工具调用(只有托管终端的屏幕扫描器能确定) StateAborted State = "aborted" // 被人中断 StateError State = "error" // 出错结束 StateEnded State = "ended" // 会话结束(sessionEnd 或 Agent 主动 chat end) StateWaitingYou State = "waiting_you" // 展示态:Agent 正阻塞等人回答(叠加在 working / idle 之上) StateOffline State = "offline" // 展示态:很久没有任何信号 )
type Thresholds ¶
type Thresholds struct {
Offline time.Duration // 没有任何信号这么久 → offline(已结束的不算)
ThinkSoft time.Duration // 思考 / 回复中静默这么久 → 软标记「可能卡住」(不推送)
ThinkStalled time.Duration // 静默这么久 → stalled(沿用会话守护的 30 分钟)
ToolQuiet time.Duration // 工具跑超过这个时间 → 标「工具执行中 / 可能在等批准」(不报警)
ToolMax time.Duration // 一般工具的上限,超过 → stalled
LongToolMax time.Duration // 长工具(shell、子代理)的上限
LongTools []string // 长工具的名字(小写,按前缀匹配)
ApprovalRemind time.Duration // 等批准超过这么久 → 提醒
// 托管终端(屏幕信号可信)时的两条规则,设计稿 04 §2.4:
TUITokenFlat time.Duration // 思考 / 回复中,token 计数不变且屏幕仍在动画这么久 → 软标记
TUIFrozen time.Duration // 思考 / 回复中,屏幕没有任何字节(且不是审批)这么久 → stalled(终端冻结)
}
Thresholds 是「离线」与「卡住」判定的阈值(设计稿 04 §2.4,纯 hook 来源的那一列)。 核心结论(实验 §8):token 不变本身不是证据——工具运行与审批等待期间计数器恒定; 所以这里只用「事件静默多久」与「工具跑了多久」,托管终端的屏幕信号第 3 阶段再叠加。
type View ¶
type View struct {
State State // 展示态:working / idle / waiting_approval / aborted / error / ended / waiting_you / offline;没见过的会话为空
Base State // 快照里的状态
Sub string // 子状态(working 时才有)
Since time.Time
QuietFor time.Duration // 距最近一次信号(hook 事件或 MCP 调用)过了多久
WaitingYou bool
Stalled bool // 硬卡住(可以告警)
StalledSoft bool // 软标记:可能卡住(只显示,不推送)
ApprovalSuspected bool // 疑似在等批准(纯 hook 只能怀疑)
ApprovalOverdue bool
Reason string // Reason* 之一;没有异常为空
}
View 是展示用的状态:基础状态叠加了 waiting_you / offline,以及卡住标志。