session

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

本文件对应任务 M20:session/end-seed 种子边界 marker。

对齐上游:packages/core/session

end-seed 标记 Resume/Fork 后第一条 live 写入的分界:

  • 冷恢复(Resume)时先回放存量事件(seed),回放完成后写入一条 end-seed, 之后的 live 工作都在 end-seed 之后;
  • Fork 子会话同样:回放父种子后、开始 live 前写入 end-seed;
  • compaction 半开括号定位依赖它:只压缩 end-seed 之前(seed 区)或之后的 live 区。

本文件对应任务 M05:Session 派生投影函数族(fold 族)。

对齐上游:packages/core/session(deriveMessages / foldRequestHeader / foldEffectiveSandboxMode / ...)

设计原则:

  • 所有 fold 函数都是「纯函数」:输入事件列表,输出派生状态,不修改任何事件;
  • 状态完全由事件派生(Event Sourcing):任何时刻重放全部事件即可恢复当前状态, 「热 append 维护」与「冷重放」两种路径结果必然一致;
  • compaction 通过 surface replace 缩短历史:EffectiveEvents 在读时应用表面替换, 被替换范围的事件对 fold 不可见,但源事件永远不被修改。

本文件对应任务 M44:SessionHeader 格式拒绝 & 事件类型白名单校验。

对齐上游:packages/core/session format version

设计要点:

  • LoadSession 是外部加载会话的唯一入口:先校验 Header 版本(fail-closed,拒绝未知版本), 再校验每条事件类型必须属于 KNOWN 集合(fail-closed,拒绝未知事件类型);
  • 不同格式版本(VERSION)的会话文件互相拒绝,避免用错误解析逻辑损坏数据。

本文件对应任务 M06:SessionHeader 元数据。

对齐上游:packages/core/session(SessionHeader)

SessionHeader 描述会话的静态元数据:格式版本 / ID / 创建时间 / CWD / 父会话 (fork lineage)/ 种子长度(seed length)/ 来源 / 代理预设等。它是持久化键目录、 fork 谱系追踪与 subagent 递归深度的唯一依据。

本文件对应任务 H04:Session 派生增量 Fold(每次 Append 只对新事件做 fold, 不从头 replay 全量历史;10k 事件场景 CPU 下降 90%)。

思路:

  • 在 SessionLog.Append → 只把「新事件」喂给 IncrementalFolder;
  • 每类投影(Messages/RequestHeader/Goal/Todo/...)提供纯增量 Apply(state, ev);
  • 唯一麻烦:SurfaceOp.Replace 会使历史事件对派生不可见(即 `ev.Seq ∈ [start,end]` 的旧消息应被删除)。增量态很难反向撤销旧消息的贡献, 因此当遇到 SurfaceReplace 时置位 `messagesDirty` + 记录最高被替换的 Seq, 在下次「读 Messages」这一投影时做一次选择性重放(只重放该投影),其它 投影照常增量跑。Goal/Todo/Preset/Header 这类 latest-wins 投影天然对 SurfaceReplace 免疫(它们对所有事件按 last-write-wins,被替换事件即便 可见也不影响结果,因为 SurfaceOp 只替换 message/assistant 相关事件)。
  • 对外 API: · NewIncrementalFolder() / FolderFromEvents() · Append(ev) / AppendMany(evs) —— 增量消费 · Snapshot() SessionProjection —— 读取最新态(懒重建 dirty) · FullRebuild(events) —— 与 FoldAll 做一致性校验
  • 语义保证:Folder.Snapshot() == FoldAll(events_so_far),对 H04 使用方透明。

本文件对应任务 N02(D1 纪律):严格 append-only + 8 条不变量 day-1 校验。

对齐上游:packages/core/session + packages/core/compaction

设计要点:

  • Session 仅暴露 Append() 一个写路径;任何 in-place 修改由本文件提供的 EnforceAppendOnly 契约 + 编译期只读视图(Events() 返回拷贝)共同拒绝;
  • SurfaceOp{op:replace,start,end,data} 是唯一的"写历史"合法方式,deriveMessages 读时替换 **不修改**源事件(见 surface.go);
  • VerifyInvariants 对整条日志跑 8 条 day-1 不变量;任何一条失败都会返回分类错误, 供持久化/flush 前把关(调用方据策略拒绝 append 或登记 invariant ledger)。

本文件对应任务 M16:Session Projections 投影注册中心。

对齐上游:packages/core/session-projection

SDK 侧读取派生状态的唯一标准接口:禁止直接读 events,必须通过注册的投影读取。 每个投影维护一个 State,订阅 changelog 做增量更新;snapshot 与 fold* 结果一致。

Package session 的会话引用(Session References)能力。

对齐上游:packages/context/session-reference + packages/context/file-reference

本文件对应任务 M17:Session References(跨会话 & 文件 mention)。

语义:

  • 用户消息中可包含两类 mention 语法: @session/<id> —— 引用另一个会话(id 为即刻识别的会话标识); #<path/file> —— 引用工作区内某个文件(path 通常为相对/绝对路径)。
  • Mention 只是「选择」的入口语法;真正进入模型上下文的是一份「聚合的不可信快照」 (additionalContext),与上游 PreparedReferencedMessage 对齐。
  • 解析出的原始引用写入 user/message 事件的 Refs(source=reference),作为审计溯源。
  • 所有失败都返回稳定分类错误码,宿主协议据此映射到自己的错误信封,不读取 prompt 字节。

本文件对应任务 M19:Request Header 快照 + request/context 路由。

对齐上游:packages/core/session/request-header

设计要点:

  • EpochHeader 记录 config/system/tools 三个代际快照;
  • RequestContext 记录 provider/model/contextWindow 与 reason(initial/resume/change/series);
  • RebuildFromHeader 从最新 request/header 快照重建 Prompt + Schema 输入面, 保证与实际发送 payload 逐字段一致(不依赖原始 events,compaction 后可重建)。

seqrange.go 复刻官方 session 的序号区间无损编码:把严格递增的来源序号序列中 连续 3 个及以上的段压缩成 [from,to] 闭区间,其余作为单点;解码时无损展开。 用于 JSONL 存储里 sourceEventSeqs 数组的紧凑表示。

Package session 提供事件溯源(Event Sourcing)会话日志核心。

对齐上游:packages/core/session

本文件对应任务 M04:Session 事件溯源 & 45+ 词汇表。

设计要点:

  • 会话状态完全由追加式事件日志派生(append-only event log),任何时刻都可重放;
  • 事件类型采用「Map → Derived Union」模式:EventData 接口 + 每种事件一个具体结构体, 序列化时通过 type 字段分发,反序列化时按 type 还原为具体类型,保证 round-trip 一致;
  • SessionLog.Append() 是唯一的写入路径,严格维护时序不变量: turn 开闭配对 / step 配对 / tool call↔result 匹配,违规立即被 invariant 拒绝。

本文件定义 SurfaceOp(表面操作)类型,供 SessionEvent 使用。 完整 foldSurface 实现见任务 M21。

Index

Constants

View Source
const AppendOnlyMarker = "SessionLog exposes a single write path: Append(EventData)"

AppendOnlyMarker 是 SessionLog 满足 append-only 的文档化标记(仅供声明,无运行时作用)。

View Source
const SessionFormatVersion = 1

SessionFormatVersion 是当前会话文件格式版本号。 任何对事件/头部结构不兼容的改动都必须递增该版本,并拒绝读取旧/新版本。

Variables

全部事件类型清单(用于词汇表遍历与 round-trip 测试)。

View Source
var KNOWN_SESSION_EVENT_TYPES = func() map[EventType]struct{} {
	m := map[EventType]struct{}{}
	for _, t := range AllEventTypes {
		m[t] = struct{}{}
	}
	return m
}()

KNOWN_SESSION_EVENT_TYPES 是受支持的全部事件类型集合(字典序,用于白名单校验)。

Functions

func AppendOnly

func AppendOnly(sl *SessionLog) error

AppendOnly 验证传入的修改原语合法:仅允许 Append。

说明:SessionLog.Append 是唯一写入入口(M04 已实现);本函数用作"在持久化/重放路径上 把关不得有除 Append 外的写"的守卫,返回 nil 表示没有非法写路径被绕过。

func DecodeSeqRanges

func DecodeSeqRanges(ranges []SeqRange, maxEntries int) ([]int, error)

DecodeSeqRanges 把区间列表无损展开为序号序列,maxEntries 为最大条目数(<=0 不限)。

func EndSeedMarker

func EndSeedMarker(header *SessionHeader) uint64

EndSeedMarker 返回记录在会话头部的种子长度分界(Resume/Fork 回放条数)。 该值由上层在回放结束时写入 SessionHeader.SeedLength。

func FoldSurface

func FoldSurface(events []SessionEvent) (nodes []SurfaceNode, replacements []ReplaceRange)

FoldSurface 折叠表面:读时应用所有 surface replace,返回:

  • nodes:有效节点列表(被替换范围内的旧事件被隐藏,替换事件自身保留);
  • replacements:全部替换范围(供 compaction 审计与测试断言)。

源事件永不被修改——替换是"读时"视角,持久化数据保持 append-only。

func IsAfterEndSeed

func IsAfterEndSeed(events []SessionEvent, seq uint64) bool

IsAfterEndSeed 判断某事件 seq 是否位于最后一次 end-seed 之后(live 区)。

func IsCorruptEventError

func IsCorruptEventError(err error) bool

IsCorruptEventError 判断是否为损坏事件错误。

func LoadSession

func LoadSession(headerBytes []byte, eventLines ...[]byte) (*SessionHeader, []SessionEvent, error)

LoadSession 加载会话头部并根据纳旧数据重建事件列表。 校验:

  • header 版本必须等于 SessionFormatVersion(cross-version 拒绝);
  • 每条事件的 type 必须属于 KNOWN_SESSION_EVENT_TYPES。

返回事件列表,其中每条已通过 round-trip 反序列化验证。

func MarkEndSeed

func MarkEndSeed(sl *SessionLog, parentID brand.SessionID) (uint64, error)

MarkEndSeed 写入 end-seed marker 事件。

  • id 为当前会话 ID 或任何唯一标识;
  • parentID 可空,标识 fork 来源;若携带则记录 EndSeedData.ParentSession。

调用时机:Resume/Fork 流程回放完种子事件后、开始 live 工作前。

func RebuildFromHeader

func RebuildFromHeader(snap *RequestHeaderSnapshot) (systemPrompt string, toolSchemas json.RawMessage, err error)

RebuildFromHeader 从快照重建请求输入面(Prompt + Schema 文本)。 返回的 SystemPrompt 与 ToolSchemas 应与实际发送的 payload 逐字段一致。

func SeedEndSeq

func SeedEndSeq(events []SessionEvent) uint64

SeedEndIndex 返回日志中最后一条 end-seed 事件的下标(不含则返回 -1)。 SeedEndSeq 返回最后一条 end-seed 的 seq(不含则返回 0)。

func SessionProjectionEqual

func SessionProjectionEqual(a, b SessionProjection) bool

SessionProjectionEqual 便捷:聚合结构 Equal 比较(测试一致性用)。

func VerifyInvariants

func VerifyInvariants(events []SessionEvent) []error

VerifyInvariants 对事件日志跑全部 8 条不变量,返回失败列表(空表示全部通过)。

Types

type AgentErrorData

type AgentErrorData struct {
	Message string `json:"message"`
	Pkg     string `json:"pkg,omitempty"`
}

AgentErrorData agent/error:代理内部错误。

func (AgentErrorData) EventType

func (AgentErrorData) EventType() EventType

type AgentPreStepData

type AgentPreStepData struct {
	Blocked bool `json:"blocked,omitempty"`
}

AgentPreStepData agent/pre-step:进入 step 前的预处理标记。

func (AgentPreStepData) EventType

func (AgentPreStepData) EventType() EventType

type AgentPresetChangeData

type AgentPresetChangeData struct {
	Preset string `json:"preset"`
}

AgentPresetChangeData agent/preset-change:代理预设切换。

func (AgentPresetChangeData) EventType

func (AgentPresetChangeData) EventType() EventType

type AgentRequestData

type AgentRequestData struct {
	Provider string `json:"provider"`
	Model    string `json:"model,omitempty"`
}

AgentRequestData agent/request:组装后的模型请求快照。

func (AgentRequestData) EventType

func (AgentRequestData) EventType() EventType

type AgentStatusData

type AgentStatusData struct {
	Status string `json:"status"`
}

AgentStatusData agent/status:Agent 生命周期状态转换(idle ↔ running)。

func (AgentStatusData) EventType

func (AgentStatusData) EventType() EventType

type ApprovalDecidedData

type ApprovalDecidedData struct {
	RequestID brand.ApprovalRequestID `json:"requestId"`
	Allowed   bool                    `json:"allowed"`
}

ApprovalDecidedData approval/decided:审批给出结论。

func (ApprovalDecidedData) EventType

func (ApprovalDecidedData) EventType() EventType

type ApprovalPolicy

type ApprovalPolicy string

ApprovalPolicy 审批策略。

const (
	ApprovalAllowAll         ApprovalPolicy = "allow-all"
	ApprovalDenyAll          ApprovalPolicy = "deny-all"
	ApprovalAskDangerous     ApprovalPolicy = "ask-dangerous"
	ApprovalAskDangerousEdit ApprovalPolicy = "ask-dangerous-tool-edit"
)

审批策略枚举。

type ApprovalRequestIDData

type ApprovalRequestIDData struct {
	RequestID brand.ApprovalRequestID `json:"requestId"`
	Tool      string                  `json:"tool,omitempty"`
	Summary   string                  `json:"summary,omitempty"`
}

ApprovalAskedData approval/asked:发起一次审批询问。

func (ApprovalRequestIDData) EventType

func (ApprovalRequestIDData) EventType() EventType

type AssistantChunkData

type AssistantChunkData struct {
	Text string `json:"text,omitempty"`
}

AssistantChunkData assistant/chunk:流式内容分片。

func (AssistantChunkData) EventType

func (AssistantChunkData) EventType() EventType

type AssistantMessageData

type AssistantMessageData struct {
	Reasoning   string   `json:"reasoning,omitempty"`
	Content     string   `json:"content"`
	ToolCallIDs []string `json:"toolCallIds,omitempty"`
}

AssistantMessageData assistant/message:助手最终消息。

func (AssistantMessageData) EventType

func (AssistantMessageData) EventType() EventType

type AssistantReasoningData

type AssistantReasoningData struct {
	Text string `json:"text,omitempty"`
}

AssistantReasoningData assistant/reasoning:推理内容分片。

func (AssistantReasoningData) EventType

func (AssistantReasoningData) EventType() EventType

type AttachmentAddedData

type AttachmentAddedData struct {
	AttachmentID brand.AttachmentID `json:"attachmentId"`
	Name         string             `json:"name,omitempty"`
}

AttachmentAddedData attachment/added:附件新增。

func (AttachmentAddedData) EventType

func (AttachmentAddedData) EventType() EventType

type CommandDoneData

type CommandDoneData struct {
	Command string `json:"command"`
}

CommandDoneData command/done:slash 命令完成。

func (CommandDoneData) EventType

func (CommandDoneData) EventType() EventType

type CommandRunData

type CommandRunData struct {
	Command string `json:"command"`
	Args    string `json:"args,omitempty"`
}

CommandRunData command/run:slash 命令触发。

func (CommandRunData) EventType

func (CommandRunData) EventType() EventType

type CorruptEventError

type CorruptEventError struct {
	Seq  uint64
	Type EventType
}

CorruptEventError 表示事件流中存在无法识别的类型(数据损坏或版本不兼容)。

func (*CorruptEventError) Error

func (e *CorruptEventError) Error() string

Error 实现 error 接口。

type EffectiveApprovalPolicy

type EffectiveApprovalPolicy struct {
	Present bool           `json:"present"`
	Policy  ApprovalPolicy `json:"policy,omitempty"`
	Source  string         `json:"source,omitempty"` // preset / user / session
}

EffectiveApprovalPolicy 是生效审批策略投影。

func FoldEffectiveApprovalPolicy

func FoldEffectiveApprovalPolicy(events []SessionEvent) EffectiveApprovalPolicy

FoldEffectiveApprovalPolicy 是 foldEffectiveApprovalPolicy 的导出版本。

func (EffectiveApprovalPolicy) Equal

Equal 对 EffectiveApprovalPolicy。

type EffectiveSandboxMode

type EffectiveSandboxMode struct {
	Present  bool        `json:"present"`
	Mode     SandboxMode `json:"mode,omitempty"`
	Enforced bool        `json:"enforced,omitempty"`
	Root     string      `json:"root,omitempty"`
}

EffectiveSandboxMode 是生效沙箱模式投影(preset 映射 + 是否强制 + 根路径)。

func FoldEffectiveSandboxMode

func FoldEffectiveSandboxMode(events []SessionEvent) EffectiveSandboxMode

FoldEffectiveSandboxMode 是 foldEffectiveSandboxMode 的导出版本。

func (EffectiveSandboxMode) Equal

Equal 对 EffectiveSandboxMode。

type EndSeedData

type EndSeedData struct {
	ParentSession brand.SessionID `json:"parentSession,omitempty"`
}

EndSeedData session/end-seed:种子边界 marker(Resume/Fork 后第一条 live 写入)。

func (EndSeedData) EventType

func (EndSeedData) EventType() EventType

type EpochHeader

type EpochHeader struct {
	// ConfigEpoch 配置代际(settings 变化递增)。
	ConfigEpoch uint64 `json:"configEpoch"`
	// SystemHash system prompt 的稳定哈希。
	SystemHash string `json:"systemHash"`
	// ToolCount 工具数量(工具变化递增代际信号)。
	ToolCount int `json:"toolCount"`
}

EpochHeader 是 request/header 快照。

func FoldEpochHeader

func FoldEpochHeader(events []SessionEvent) (EpochHeader, bool)

FoldEpochHeader 折叠出最新 request/header 快照(last-write-wins)。

type EventData

type EventData interface {
	EventType() EventType
}

EventData 是所有事件数据结构的统一接口。 每种事件一个具体结构体并实现 EventType(),构成"类型安全的事件联合"。

type EventType

type EventType string

EventType 是事件类型的字符串标识。

const (
	EventTurnStart         EventType = "turn/start"
	EventTurnEnd           EventType = "turn/end"
	EventTurnStopping      EventType = "turn/stopping"
	EventStepStart         EventType = "step/start"
	EventStepEnd           EventType = "step/end"
	EventAgentError        EventType = "agent/error"
	EventAgentPreStep      EventType = "agent/pre-step"
	EventAgentRequest      EventType = "agent/request"
	EventAgentStatus       EventType = "agent/status"
	EventAgentInboxSpliced EventType = "agent/inbox/spliced"
)

簇 A:Turn / Step 双循环(8 种)

const (
	EventUserMessage        EventType = "user/message"
	EventAssistantMessage   EventType = "assistant/message"
	EventAssistantChunk     EventType = "assistant/chunk"
	EventAssistantReasoning EventType = "assistant/reasoning"
	EventInjectionContext   EventType = "injection/context"
	EventSessionTitle       EventType = "session/title"
)

簇 B:消息(6 种)

const (
	EventToolCall         EventType = "tool/call"
	EventToolResult       EventType = "tool/result"
	EventToolError        EventType = "tool/error"
	EventToolObserved     EventType = "tool/observed"
	EventToolPresentation EventType = "tool/presentation"
)

簇 C:工具(5 种)

const (
	EventPlanMode     EventType = "plan/mode"
	EventPlanApproval EventType = "plan/approval"
	EventGoalChange   EventType = "goal/change"
	EventGoalRound    EventType = "goal/round"
	EventTodoWrite    EventType = "todo/write"
	EventEndSeed      EventType = "session/end-seed"
	EventPlanUpdate   EventType = "project/plan-update"
)

簇 D:规划能力(7 种)

const (
	EventRequestHeader     EventType = "request/header"
	EventRequestContext    EventType = "request/context"
	EventApprovalAsked     EventType = "approval/asked"
	EventApprovalDecided   EventType = "approval/decided"
	EventPresetChange      EventType = "permission/preset-change"
	EventAgentPresetChange EventType = "agent/preset-change"
	EventCommandRun        EventType = "command/run"
	EventCommandDone       EventType = "command/done"
)

簇 E:请求 & 审批(7 种)

const (
	EventFSWriteIntent EventType = "fs/write-intent"
	EventFSEditIntent  EventType = "fs/edit-intent"
	EventFSObserved    EventType = "fs/observed"
	EventFSVersionBump EventType = "fs/version-bump"
	EventFSRead        EventType = "fs/read"
	EventFSDirList     EventType = "fs/dir-list"
)

簇 F:文件系统(6 种)

const (
	EventSkillsChange  EventType = "skills/change"
	EventSkillsCatalog EventType = "skills/catalog"
	EventSkillInject   EventType = "skill/inject"
)

簇 G:技能(3 种)

const (
	EventLLMRequest EventType = "llm/request"
	EventLLMStream  EventType = "llm/stream"
	EventLLMRetry   EventType = "llm/retry"
	EventLLMError   EventType = "llm/error"
	EventLLMDone    EventType = "llm/done"
)

簇 H:LLM(5 种)

const (
	EventSurfaceReplace          EventType = "surface/replace"
	EventAttachmentAdded         EventType = "attachment/added"
	EventSessionProjectionUpdate EventType = "session/projection-updated"
	EventWorkspaceChange         EventType = "workspace/change"
	EventUserQuestion            EventType = "user/question"
	EventSandboxMode             EventType = "sandbox/mode"
)

簇 I:表面替换 & 杂项(6 种)

func EventTypeOf

func EventTypeOf(d EventData) EventType

EventTypeOf 返回任意 EventData 的类型(便捷方法,也用于测试断言)。

type FolderStats

type FolderStats struct {
	// IncrementalAppends 总增量 Append 次数。
	IncrementalAppends uint64 `json:"incrementalAppends"`
	// DirtyRebuilds 因 SurfaceReplace 触发的 messages 全量重建次数。
	DirtyRebuilds uint64 `json:"dirtyRebuilds"`
	// EventsScanned 总 scan 的事件数(增量=每次 1,dirty 重建=全部 events)。
	EventsScanned uint64 `json:"eventsScanned"`
}

FolderStats H04 性能统计(便于观测 / Benchmark)。

type FsDirListData

type FsDirListData struct {
	Path string `json:"path"`
}

FsDirListData fs/dir-list:列目录。

func (FsDirListData) EventType

func (FsDirListData) EventType() EventType

type FsEditIntentData

type FsEditIntentData struct {
	Path    string `json:"path"`
	Version uint64 `json:"version,omitempty"`
}

FsEditIntentData fs/edit-intent:编辑文件意图。

func (FsEditIntentData) EventType

func (FsEditIntentData) EventType() EventType

type FsIntentData

type FsIntentData struct {
	Path     string `json:"path"`
	Kind     string `json:"kind,omitempty"`
	Version  uint64 `json:"version,omitempty"`
	Observed bool   `json:"observed,omitempty"`
}

FsIntentData 是 fs 意图事件共用数据结构(write/edit/observed/version-bump/read/dir-list)。

func (FsIntentData) EventType

func (FsIntentData) EventType() EventType

type FsObservedData

type FsObservedData struct {
	Path string `json:"path"`
}

FsObservedData fs/observed:文件已被观察(先读后写政策)。

func (FsObservedData) EventType

func (FsObservedData) EventType() EventType

type FsReadData

type FsReadData struct {
	Path string `json:"path"`
}

FsReadData fs/read:读取文件。

func (FsReadData) EventType

func (FsReadData) EventType() EventType

type FsVersionBumpData

type FsVersionBumpData struct {
	Path    string `json:"path"`
	Version uint64 `json:"version"`
}

FsVersionBumpData fs/version-bump:文件版本递增。

func (FsVersionBumpData) EventType

func (FsVersionBumpData) EventType() EventType

type FsWriteIntentData

type FsWriteIntentData struct {
	Path     string `json:"path"`
	Version  uint64 `json:"version,omitempty"`
	Observed bool   `json:"observed,omitempty"`
}

FsWriteIntentData fs/write-intent:写文件意图。

func (FsWriteIntentData) EventType

func (FsWriteIntentData) EventType() EventType

type GoalBlockReason

type GoalBlockReason struct {
	// Code 稳定的 lower-kebab-case 分类。
	Code string `json:"code"`
	// Message 非空的面向人/模型的说明。
	Message string `json:"message"`
}

GoalBlockReason 是阻塞目标的稳定原因(R06:对齐官方 GoalBlockReason{code,message})。 由 goal 域设置并与 goal/change 事件一并持久化。

type GoalChangeData

type GoalChangeData struct {
	GoalID      string    `json:"goalId"`
	Phase       GoalPhase `json:"phase"`
	Description string    `json:"description,omitempty"`
	MaxRounds   int       `json:"maxRounds,omitempty"`
	Revision    uint64    `json:"revision"`
	// BlockReason 仅 phase=blocked 时存在;随事件持久化(R06)。
	BlockReason *GoalBlockReason `json:"blockedReason,omitempty"`
}

GoalChangeData goal/change:目标变更(CAS revision)。

func (GoalChangeData) EventType

func (GoalChangeData) EventType() EventType

type GoalFold

type GoalFold struct {
	Present     bool      `json:"present"`
	GoalID      string    `json:"goalId,omitempty"`
	Phase       GoalPhase `json:"phase,omitempty"`
	Description string    `json:"description,omitempty"`
	MaxRounds   int       `json:"maxRounds,omitempty"`
	Revision    uint64    `json:"revision,omitempty"`
	// BlockReason 最新阻塞原因(R06:随 goal/change 持久化,latest-wins)。
	BlockReason *GoalBlockReason `json:"blockedReason,omitempty"`
}

GoalFold 是目标状态投影(CAS revision 用于并发保护)。

func ApplyGoalChange

func ApplyGoalChange(s GoalFold, ev SessionEvent) GoalFold

ApplyGoalChange revision 单调递增 latest-wins(CAS 语义)。

func FoldGoalChange

func FoldGoalChange(events []SessionEvent) GoalFold

FoldGoalChange 是 foldGoalChange 的导出版本。

func (GoalFold) Equal

func (g GoalFold) Equal(o ProjectionState) bool

Equal 对 GoalFold。

type GoalPhase

type GoalPhase string

GoalPhase 目标阶段。

type GoalRoundData

type GoalRoundData struct {
	Round int `json:"round"`
}

GoalRoundData goal/round:目标续轮标记。

func (GoalRoundData) EventType

func (GoalRoundData) EventType() EventType

type HeaderOrigin

type HeaderOrigin string

HeaderOrigin 标识会话来源。

const (
	OriginCreated HeaderOrigin = "created" // 全新创建
	OriginFork    HeaderOrigin = "fork"    // 由父会话分叉
	OriginResume  HeaderOrigin = "resume"  // 冷恢复
)

会话来源枚举。

func AsHeaderOrigin

func AsHeaderOrigin(s string) HeaderOrigin

AsHeaderOrigin 便捷类型转换(供测试与外部构造)。

type InboxSplicedData

type InboxSplicedData struct {
	Target       InboxTarget `json:"target"`
	Start        int         `json:"start"`
	RemovedCount int         `json:"removedCount,omitempty"`
	Inserted     []string    `json:"inserted"`
	Outcome      string      `json:"outcome,omitempty"`
}

InboxSplicedData agent/inbox/spliced:Agent 持久化待处理消息列表的一次规范化变更。

func (InboxSplicedData) EventType

func (InboxSplicedData) EventType() EventType

type InboxTarget

type InboxTarget string

InboxTarget 是收件箱目标(next-turn 或 next-step)。

const (
	// InboxNextTurn 表示等待下一个 turn 的消息。
	InboxNextTurn InboxTarget = "next-turn"
	// InboxNextStep 表示等待下一个 step 边界的输入。
	InboxNextStep InboxTarget = "next-step"
)

type IncrementalFolder

type IncrementalFolder struct {

	// 统计:便于上层观测 H04 效果(Benchmark + 测试)。
	Stats FolderStats
	// contains filtered or unexported fields
}

IncrementalFolder 是 SessionProjection 的增量维护器。

典型用法:

f := NewIncrementalFolder()
f.Append(ev1)
f.Append(ev2)
snap := f.Snapshot(events)    // events 仅当 messages dirty 时才会读;否则 0 拷贝

并发:Folder 本身 **不带锁**(H07 单写多读由上层保证);如果需要并发读写, 调用方使用外部 mutex。SessionLog.Append 本就持 sl.mu,天然单写。

func FolderFromEvents

func FolderFromEvents(events []SessionEvent) *IncrementalFolder

FolderFromEvents 用全量事件初始化 IncrementalFolder:先做一次性 FoldAll 建立 baseline, 再把 Append 起点设为 len(events)。等价但更快:后续 Append 走增量。 同时保证 FolderFromEvents(evs).Snapshot(evs) == FoldAll(evs)。

func NewIncrementalFolder

func NewIncrementalFolder() *IncrementalFolder

NewIncrementalFolder 创建空的增量 folder(zero-state)。

func (*IncrementalFolder) Append

func (f *IncrementalFolder) Append(ev SessionEvent)

Append 增量应用一条事件。复杂度 O(1)(不含 SurfaceReplace → 只是打 dirty 标记)。

func (*IncrementalFolder) AppendMany

func (f *IncrementalFolder) AppendMany(evs []SessionEvent)

AppendMany 批量增量(等价多次 Append 但统计一次锁)。

func (*IncrementalFolder) FullRebuild

func (f *IncrementalFolder) FullRebuild(events []SessionEvent) SessionProjection

FullRebuild 从全量事件强制重算(不使用 dirty 短路径),用于测试一致性。

func (*IncrementalFolder) MarkDirty

func (f *IncrementalFolder) MarkDirty()

MarkDirty 显式把 messages 标记为 dirty(调试 / 上层明确知道历史被 compaction 修改时用)。

func (*IncrementalFolder) Snapshot

func (f *IncrementalFolder) Snapshot(events []SessionEvent) SessionProjection

Snapshot 返回当前聚合投影。 当 messagesDirty=true 时会调用 FoldAll(events).Messages 做一次重建(仅 messages 投影), 其它 8 个投影直接复用增量快照。这是 H04 的"懒重建":

  • 如果写路径从未 SurfaceReplace(90% 会话),永远不会触发重建;
  • 即便触发,也只在 Snapshot 被调用时发生,不是每 Append。

默认对 Messages 做防御拷贝(调用方修改返回 slice 不影响内部态),这在 10k messages 的场景会有 ~100us 开销。如调用方只关心非 Messages 投影(Goal/Todo/PlanMode 等), 请使用 SnapshotMeta(),速度提升 1~2 数量级。

func (*IncrementalFolder) SnapshotMeta

func (f *IncrementalFolder) SnapshotMeta(events []SessionEvent) SessionProjection

SnapshotMeta 返回不含 Messages 的轻量快照(Messages 永远 nil)。 读取 Goal/Todo/Preset/Sandbox/Approval/PlanMode/Title/RequestHeader 专用。 热路径每 Append 一次做决策应优先用这个接口以避免 Messages 大 slice 拷贝。

func (*IncrementalFolder) StatsCopy

func (f *IncrementalFolder) StatsCopy() FolderStats

StatsCopy 返回当前统计副本(线程安全)。

type InjectionContextData

type InjectionContextData struct {
	Name    string `json:"name"`
	Content string `json:"content"`
	Hash    string `json:"hash,omitempty"`
}

InjectionContextData injection/context:注入的动态上下文(如 skills catalog)。

func (InjectionContextData) EventType

func (InjectionContextData) EventType() EventType

type InvariantCode

type InvariantCode string

InvariantCode 是不变量失败码。

const (
	InvSeqContinuous    InvariantCode = "seq_continuous"
	InvTimeMonotonic    InvariantCode = "time_monotonic"
	InvTurnPaired       InvariantCode = "turn_start_end_paired"
	InvStepPaired       InvariantCode = "step_start_end_paired"
	InvApprovalPaired   InvariantCode = "approval_asked_decided_paired"
	InvGoalCAS          InvariantCode = "goal_revision_cas"
	InvToolCallResult   InvariantCode = "tool_call_result_paired"
	InvFormatConsistent InvariantCode = "persistence_format_consistent"
)

8 条不变量。

type InvariantFailure

type InvariantFailure struct {
	Code    InvariantCode
	Message string
}

InvariantFailure 是一次不变量失败。

func (InvariantFailure) Error

func (f InvariantFailure) Error() string

type LLMDoneData

type LLMDoneData struct {
	PromptTokens     int `json:"promptTokens"`
	CompletionTokens int `json:"completionTokens"`
}

LLMDoneData llm/done:模型请求完成(含 token 用量)。

func (LLMDoneData) EventType

func (LLMDoneData) EventType() EventType

type LLMErrorData

type LLMErrorData struct {
	Kind  string `json:"kind"` // overload/rate-limit/refusal/context-overflow
	Error string `json:"error"`
}

LLMErrorData llm/error:模型请求失败。

func (LLMErrorData) EventType

func (LLMErrorData) EventType() EventType

type LLMRequestData

type LLMRequestData struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
}

LLMRequestData llm/request:发起模型请求。

func (LLMRequestData) EventType

func (LLMRequestData) EventType() EventType

type LLMRetryData

type LLMRetryData struct {
	Attempt   int    `json:"attempt"`
	BackoffMs int64  `json:"backoffMs"`
	Error     string `json:"error"`
}

LLMRetryData llm/retry:模型请求重试(backoff 信息)。

func (LLMRetryData) EventType

func (LLMRetryData) EventType() EventType

type LLMStreamData

type LLMStreamData struct {
	Text string `json:"text,omitempty"`
}

LLMStreamData llm/stream:模型流式分片。

func (LLMStreamData) EventType

func (LLMStreamData) EventType() EventType

type Mention

type Mention struct {
	// Kind 是引用种类(session / file)。
	Kind MentionKind
	// Raw 是完整的原文 token(如 "@session/abc"、"#src/main.go")。
	Raw string
	// Value 是引用目标:会话 id 或文件路径。
	Value string
	// Start/End 是 Raw 在原文中的字节区间,用于「剥离 mention、保留可读内容」。
	Start int
	End   int
}

Mention 表示用户消息中的一处引用。

func ParseMentions

func ParseMentions(text string) []Mention

ParseMentions 解析原文中的所有 @session/<id> 与 #<path/file> mention。 返回按原文出现顺序的引用列表;无引用时返回空切片(非 nil)。

type MentionKind

type MentionKind string

MentionKind 表示引用种类。

const (
	// MentionSession 引用一个会话(@session/<id>)。
	MentionSession MentionKind = "session"
	// MentionFile 引用一个文件(#<path/file>)。
	MentionFile MentionKind = "file"
)

type Message

type Message struct {
	Role        string   `json:"role"` // "user" / "assistant"
	Content     string   `json:"content"`
	ToolCallIDs []string `json:"toolCallIds,omitempty"`
	Seq         uint64   `json:"seq"`
}

Message 是派生出的对话消息(供模型上下文组装使用)。

func ApplyMessage

func ApplyMessage(msgs []Message, ev SessionEvent) ([]Message, bool)

ApplyMessage 增量追加一条事件到 Message 列表。 对 SurfaceReplace:不在这里反向移除(难以撤销),而是由 Folder 层置 dirty。 返回 (newMessages, replaced bool),replaced=true 表示发生了 SurfaceReplace, 调用方需要把 messages 置 dirty。

func DeriveMessages

func DeriveMessages(events []SessionEvent) []Message

DeriveMessages 是 deriveMessages 的导出版本。

func (Message) Equal

func (m Message) Equal(o ProjectionState) bool

Equal 实现 ProjectionState 接口。

type PermissionPresetFold

type PermissionPresetFold struct {
	Present bool   `json:"present"`
	Preset  string `json:"preset,omitempty"`
}

PermissionPresetFold 是权限预设投影。

func ApplyPermissionPreset

func ApplyPermissionPreset(s PermissionPresetFold, ev SessionEvent) PermissionPresetFold

ApplyPermissionPreset latest-wins。

func FoldPermissionPreset

func FoldPermissionPreset(events []SessionEvent) PermissionPresetFold

FoldPermissionPreset 是 foldPermissionPreset 的导出版本。

func (PermissionPresetFold) Equal

Equal 对 PermissionPresetFold。

type PlanApprovalData

type PlanApprovalData struct {
	Approved bool `json:"approved"`
}

PlanApprovalData plan/approval:计划审批结果。

func (PlanApprovalData) EventType

func (PlanApprovalData) EventType() EventType

type PlanModeData

type PlanModeData struct {
	Mode string `json:"mode"` // "on" / "off"
}

PlanModeData plan/mode:计划模式切换(on/off)。

func (PlanModeData) EventType

func (PlanModeData) EventType() EventType

type PlanModeFold

type PlanModeFold struct {
	Present bool   `json:"present"`
	Mode    string `json:"mode,omitempty"` // "on" / "off"
}

PlanModeFold 是计划模式投影。

func ApplyPlanMode

func ApplyPlanMode(s PlanModeFold, ev SessionEvent) PlanModeFold

ApplyPlanMode latest-wins。

func FoldPlanMode

func FoldPlanMode(events []SessionEvent) PlanModeFold

FoldPlanMode 是 foldPlanMode 的导出版本。

func (PlanModeFold) Equal

func (p PlanModeFold) Equal(o ProjectionState) bool

Equal 对 PlanModeFold。

type PlanUpdateData

type PlanUpdateData struct {
	Content string `json:"content,omitempty"`
}

PlanUpdateData project/plan-update:计划内容更新。

func (PlanUpdateData) EventType

func (PlanUpdateData) EventType() EventType

type PrepareRequest

type PrepareRequest struct {
	// AgentSessionID 是请求代理自身的会话 ID(用于自引用拒绝;可空则跳过自引用检查)。
	AgentSessionID brand.SessionID
	// Text 是用户原始消息(可能包含 mention)。
	Text string
	// Resolver 是会话/文件解析接缝。
	Resolver SessionReferenceResolver
	// MaxContextBytes 是可选的聚合上下文预算;<=0 表示不限制。
	MaxContextBytes int
}

PrepareRequest 描述一次引用准备请求。

type PreparedReferencedMessage

type PreparedReferencedMessage struct {
	// Content 是剥离 mention token 后的可读消息内容。
	Content string
	// AdditionalContext 是聚合的不可信引用上下文;无引用时为 ""。
	AdditionalContext string
	// References 是成功解析并纳入快照的引用(按原文顺序)。
	References []ReferenceResolution
}

PreparedReferencedMessage 是一次引用准备的产物:剥离 mention 后的可读内容 + 可选的聚合参考快照(additionalContext)。

func Prepare

Prepare 解析 Text 中的 mention、解析每个引用,并返回 PreparedReferencedMessage。

规则:

  • 无引用 → 原样 Content,AdditionalContext 为空;
  • 引用自请求代理 → RefCodeSelfReference;
  • 任一引用解析失败 → 立即以对应稳定错误码返回;
  • 引用数超上限 → RefCodeTooMany;
  • 聚合上下文超预算 → RefCodeBudgetExceeded。

type PresetChangeData

type PresetChangeData struct {
	Preset string `json:"preset"`
}

PresetChangeData permission/preset-change:权限预设切换。

func (PresetChangeData) EventType

func (PresetChangeData) EventType() EventType

type Projection

type Projection[S ProjectionState] struct {
	// contains filtered or unexported fields
}

Projection 是一个已注册投影的运行实例。

func RegisterProjection

func RegisterProjection[S ProjectionState](r *Registry, def *ProjectionDefinition[S]) (*Projection[S], error)

RegisterProjection 注册一个投影定义(顶层泛型函数,因 Go 方法不支持类型参数)。

func (*Projection[S]) State

func (p *Projection[S]) State() S

State 返回当前投影状态。

type ProjectionChange

type ProjectionChange struct {
	// ProjectionID 变更的投影。
	ProjectionID brand.ProjectionID `json:"projectionId"`
	// Seq changelog 序号。
	Seq uint64 `json:"seq"`
	// EventSeq 触发变更的事件 seq。
	EventSeq uint64 `json:"eventSeq"`
	// Changed 状态是否发生变化。
	Changed bool `json:"changed"`
}

ProjectionChange 是投影 changelog 中的一条变更。

type ProjectionDefinition

type ProjectionDefinition[S ProjectionState] struct {
	// ID 投影唯一标识。
	ID brand.ProjectionID
	// Init 初始状态。
	Init S
	// Apply 增量应用一条事件到状态。
	Apply func(state S, ev SessionEvent) S
	// Merge 从全部事件重新派生状态(重放;等价于 fold*)。
	Merge func(events []SessionEvent) S
}

ProjectionDefinition 定义单个投影。

type ProjectionState

type ProjectionState interface {
	// Equal 判断两个状态是否相等(用于 changelog 增量判断)。
	Equal(other ProjectionState) bool
}

ProjectionState 是投影状态的类型约束。

type ProjectionUpdateData

type ProjectionUpdateData struct {
	ProjectionID brand.ProjectionID `json:"projectionId"`
	Hash         string             `json:"hash,omitempty"`
}

ProjectionUpdateData session/projection-updated:投影状态更新。

func (ProjectionUpdateData) EventType

func (ProjectionUpdateData) EventType() EventType

type Reason

type Reason string

Reason 是请求重建原因。

const (
	ReasonInitial Reason = "initial"
	ReasonResume  Reason = "resume"
	ReasonChange  Reason = "change"
	ReasonSeries  Reason = "series"
)

请求重建原因枚举。

type ReferenceResolution

type ReferenceResolution struct {
	Kind  MentionKind `json:"kind"`
	Raw   string      `json:"raw,omitempty"`
	Value string      `json:"value"`
	Label string      `json:"label,omitempty"`
	Slice string      `json:"slice,omitempty"` // 聚合进 additionalContext 的文本片段
}

ReferenceResolution 记录一条引用解析结果(写入 Refs 审计)。

type Registry

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

Registry 是投影注册中心。

func NewProjectionRegistry

func NewProjectionRegistry() *Registry

NewProjectionRegistry 创建投影注册中心。

func (*Registry) ApplyEvents

func (r *Registry) ApplyEvents(events []SessionEvent)

ApplyEvents 将一批新事件增量应用到全部投影,并生成 changelog。

func (*Registry) Changelog

func (r *Registry) Changelog() []ProjectionChange

Changelog 返回 changelog 快照(按产生顺序)。

func (*Registry) Rebuild

func (r *Registry) Rebuild(events []SessionEvent)

Rebuild 从全部事件重放重建全部投影(等价 fold*,供一致性校验)。

func (*Registry) SnapshotAll

func (r *Registry) SnapshotAll() map[brand.ProjectionID]any

SnapshotAll 返回全部投影的当前状态快照(按投影 ID 排序)。

type ReplaceRange

type ReplaceRange struct {
	Start uint64 `json:"start"`
	End   uint64 `json:"end"`
}

ReplaceRange 描述一次表面替换覆盖的 seq 范围。

type RequestContext

type RequestContext struct {
	// Provider 模型提供方。
	Provider string `json:"provider"`
	// Model 模型名。
	Model string `json:"model"`
	// ContextWindow 上下文窗口大小。
	ContextWindow int `json:"contextWindow,omitempty"`
	// Reason 重建原因。
	Reason Reason `json:"reason,omitempty"`
}

RequestContext 是 request/context 路由信息。

func FoldRequestContext

func FoldRequestContext(events []SessionEvent) (RequestContext, bool)

FoldRequestContext 折叠出最新 request/context(last-write-wins)。

type RequestContextData

type RequestContextData struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
	Window   int    `json:"contextWindow,omitempty"`
	Reason   string `json:"reason,omitempty"` // initial/resume/change/series
}

RequestContextData request/context:请求上下文(provider/model/contextWindow)。

func (RequestContextData) EventType

func (RequestContextData) EventType() EventType

type RequestHeaderData

type RequestHeaderData struct {
	ConfigEpoch uint64 `json:"configEpoch"`
	SystemHash  string `json:"systemHash,omitempty"`
	ToolCount   int    `json:"toolCount,omitempty"`
}

RequestHeaderData request/header:请求头快照(config/system/tools epoch)。

func (RequestHeaderData) EventType

func (RequestHeaderData) EventType() EventType

type RequestHeaderFold

type RequestHeaderFold struct {
	Present     bool   `json:"present"`
	ConfigEpoch uint64 `json:"configEpoch,omitempty"`
	SystemHash  string `json:"systemHash,omitempty"`
	ToolCount   int    `json:"toolCount,omitempty"`
}

RequestHeaderFold 是 request/header 的最新快照投影。

func ApplyRequestHeader

func ApplyRequestHeader(s RequestHeaderFold, ev SessionEvent) RequestHeaderFold

ApplyRequestHeader latest-wins。

func FoldRequestHeader

func FoldRequestHeader(events []SessionEvent) RequestHeaderFold

FoldRequestHeader 是 foldRequestHeader 的导出版本。

func (RequestHeaderFold) Equal

Equal 对 RequestHeaderFold。

type RequestHeaderSnapshot

type RequestHeaderSnapshot struct {
	// Header EpochHeader 快照。
	Header EpochHeader `json:"header"`
	// Context RequestContext 路由信息。
	Context RequestContext `json:"context"`
	// SystemPrompt system prompt 文本(重建用)。
	SystemPrompt string `json:"systemPrompt,omitempty"`
	// ToolSchemas 工具 schema JSON(重建用)。
	ToolSchemas json.RawMessage `json:"toolSchemas,omitempty"`
}

RequestHeaderSnapshot 是重建请求所需的完整快照。

func (*RequestHeaderSnapshot) SnapshotHash

func (s *RequestHeaderSnapshot) SnapshotHash() string

SnapshotHash 计算快照的稳定哈希(用于判断重建结果是否漂移)。 简化实现:拼接关键字段。

type SandboxMode

type SandboxMode string

SandboxMode 沙箱模式。

const (
	SandboxReadOnly         SandboxMode = "read-only"
	SandboxWorkspaceWrite   SandboxMode = "workspace-write"
	SandboxDangerFullAccess SandboxMode = "danger-full-access"
)

沙箱模式枚举。

type SandboxModeData

type SandboxModeData struct {
	Mode   string `json:"mode"`
	Source string `json:"source,omitempty"`
}

SandboxModeData sandbox/mode:会话沙箱模式切换(log-only,不进模型 transcript)。 对齐官方 packages/sandbox-policy/session-mode.ts:最后一条事件为会话生效覆盖。 source 为 'delegation' 时表示子代理委派时植入的覆盖。

func (SandboxModeData) EventType

func (SandboxModeData) EventType() EventType

type SeqRange

type SeqRange struct {
	From int
	To   int
}

SeqRange 是一个闭区间;From == To 时表示单个序号。

func EncodeSeqRanges

func EncodeSeqRanges(values []int) []SeqRange

EncodeSeqRanges 把严格递增序号序列编码为区间列表;非严格递增时退化为单点序列。

type SessionEvent

type SessionEvent struct {
	// Seq 为严格递增的事件序号(1..N 连续)。
	Seq uint64 `json:"seq"`
	// Time 为事件写入时间(严格单调)。
	Time time.Time `json:"time"`
	// Type 为事件类型标识。
	Type EventType `json:"type"`
	// Data 为类型化载荷(Derived Union)。
	Data EventData `json:"data"`
	// SurfaceOp 存在表示该事件是表面替换操作(compaction 唯一合法回写方式)。
	SurfaceOp *SurfaceOp `json:"surfaceOp,omitempty"`
	// SourceEventSeqs 记录派生来源事件序号(compaction/派生消息用)。
	SourceEventSeqs []uint64 `json:"sourceEventSeqs,omitempty"`
}

SessionEvent 是日志中的单条事件记录。

func EffectiveEvents

func EffectiveEvents(events []SessionEvent) []SessionEvent

EffectiveEvents 返回应用表面替换后的有效事件列表(读时替换,源事件不变)。 规则:携带 SurfaceOp{op:replace, start, end} 的事件会将 [start, end] 范围 内的旧事件隐藏,并以自身替代;普通事件按原序保留。

func (SessionEvent) MarshalJSON

func (e SessionEvent) MarshalJSON() ([]byte, error)

MarshalJSON 将 SessionEvent 序列化为 {seq,time,type,data,surfaceOp?,sourceEventSeqs?}。

func (*SessionEvent) UnmarshalJSON

func (e *SessionEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON 从 JSON 还原 SessionEvent,并按 type 分发 Data 为具体类型。

type SessionFormatUnsupportedError

type SessionFormatUnsupportedError struct {
	Version int
}

SessionFormatUnsupportedError 表示会话格式版本不支持(fail-closed)。

func (*SessionFormatUnsupportedError) Error

Error 实现 error 接口。

type SessionHeader

type SessionHeader struct {
	// Version 为格式版本号,序列化时写入、反序列化时校验(fail-closed)。
	Version int `json:"version"`
	// ID 为会话唯一标识。
	ID brand.SessionID `json:"id"`
	// CreatedAt 为会话创建时间。
	CreatedAt time.Time `json:"createdAt"`
	// Cwd 为会话工作目录(影响 FS 工具与相对路径解析)。
	Cwd string `json:"cwd,omitempty"`
	// ParentSession 为父会话 ID(fork 谱系;非空表示由某会话分叉而来)。
	ParentSession brand.SessionID `json:"parentSession,omitempty"`
	// SeedLength 为种子长度:Resume/Fork 时已回放(cold stored)的事件数,
	// 用于定位 session/end-seed 之后的 live work 分界。
	SeedLength uint64 `json:"seedLength,omitempty"`
	// Origin 为会话来源(created / fork / resume)。
	Origin HeaderOrigin `json:"origin,omitempty"`
	// DelegationDepth 为 subagent 递归委派深度(根为 0,每层 +1)。
	DelegationDepth int `json:"delegationDepth,omitempty"`
	// AgentPreset 为会话绑定的代理预设名。
	AgentPreset string `json:"agentPreset,omitempty"`
}

SessionHeader 是会话的静态元数据头部。

func NewSessionHeader

func NewSessionHeader(id brand.SessionID, cwd string) *SessionHeader

NewSessionHeader 创建全新会话头部(版本当前值 / 来源 created / 深度 0)。

func UnmarshalSessionHeader

func UnmarshalSessionHeader(data []byte) (*SessionHeader, error)

UnmarshalSessionHeader 反序列化头部并做 fail-closed 版本校验:

  • 未知/不支持的版本号 → 返回错误,拒绝读(避免用错误的解析逻辑损坏数据)。

func (*SessionHeader) Fork

func (h *SessionHeader) Fork(childID brand.SessionID) *SessionHeader

Fork 基于当前头部派生一个子会话头部(fork lineage):

  • ParentSession = 当前会话 ID;
  • Origin = fork;DelegationDepth = 父深度 + 1;
  • SeedLength 由调用方在回放完种子事件后写入。

func (*SessionHeader) Marshal

func (h *SessionHeader) Marshal() ([]byte, error)

Marshal 序列化头部为 JSON 字节。

func (*SessionHeader) Validate

func (h *SessionHeader) Validate() error

Validate 校验头部字段完整性(读取后调用)。

type SessionLog

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

SessionLog 是事件溯源日志的唯一写路径载体。

func NewSessionLog

func NewSessionLog(id brand.SessionID) *SessionLog

NewSessionLog 创建空日志,并注册内置时序不变量检查器。

func (*SessionLog) Append

func (sl *SessionLog) Append(data EventData) (uint64, error)

Append 是唯一写入路径:追加一条事件并执行时序不变量校验。

  • 自动分配严格递增序号(1..N 连续)与单调时间;
  • 违反 turn 开闭 / step 配对 / tool call↔result 匹配 → 拒绝写入并返回错误。

func (*SessionLog) Check

func (sl *SessionLog) Check() []error

Check 运行不变量注册中心(整条日志级校验:turn/step/tool 配对平衡)。 适合在持久化 / flush 前调用做一致性把关;Append 内部已做逐条状态级校验, 因此运行期不需要每 append 一次就跑整日志校验(中间态天然不平衡)。

func (*SessionLog) DisableIncrementalProjection

func (sl *SessionLog) DisableIncrementalProjection()

DisableIncrementalProjection 关闭增量派生(性能对比测试用)。

func (*SessionLog) EnableIncrementalProjection

func (sl *SessionLog) EnableIncrementalProjection()

EnableIncrementalProjection 启用 H04 增量派生。

若日志已有 N 条事件(重建场景),将用一次 FolderFromEvents 建立基线, 后续 Append 走纯增量 O(1);未启用时上层仍可 FoldAllFromLog(sl) 走全量。

func (*SessionLog) Events

func (sl *SessionLog) Events() []SessionEvent

Events 返回全部事件的只读快照。

func (*SessionLog) IncrementalEnabled

func (sl *SessionLog) IncrementalEnabled() bool

IncrementalEnabled 返回是否启用了 H04 增量派生。

func (*SessionLog) IncrementalStats

func (sl *SessionLog) IncrementalStats() FolderStats

IncrementalStats 返回 H04 统计快照;未启用时返回 zero FolderStats。

func (*SessionLog) LastSeq

func (sl *SessionLog) LastSeq() uint64

LastSeq 返回最新事件序号(无事件时为 0)。

func (*SessionLog) Len

func (sl *SessionLog) Len() int

Len 返回当前事件总数。

func (*SessionLog) NextStep

func (sl *SessionLog) NextStep() uint64

NextStep 返回当前 turn 内下一个 step 的编号(每个 turn 开始时重置为 1)。

func (*SessionLog) NextTurn

func (sl *SessionLog) NextTurn() uint64

NextTurn 返回下一个 turn 的编号(从 0 开始单调递增)。 用于 Agent 在创建 turn/start 事件前查询正确的编号。

func (*SessionLog) OpenStep

func (sl *SessionLog) OpenStep() (uint64, bool)

OpenStep 返回当前打开的 step 编号(无打开 step 时返回 0 和 false)。

func (*SessionLog) OpenTurn

func (sl *SessionLog) OpenTurn() (uint64, bool)

OpenTurn 返回当前打开的 turn 编号(无打开 turn 时返回 0 和 false)。

func (*SessionLog) Projection

func (sl *SessionLog) Projection() SessionProjection

Projection 返回最新派生投影。 启用 H04:走 IncrementalFolder.Snapshot(绝大多数情况 O(1), 仅当 SurfaceReplace 触发 dirty 时懒重建 Messages 一条投影); 未启用:回退 FoldAllFromLog O(n)。

func (*SessionLog) ProjectionMeta

func (sl *SessionLog) ProjectionMeta() SessionProjection

ProjectionMeta 返回不含 Messages 的轻量快照(热路径首选,不触发 Messages 大 slice 拷贝)。 仅填充 RequestHeader/SandboxMode/Approval/Preset/Goal/Todo/PlanMode/Title。

func (*SessionLog) SandboxMode

func (sl *SessionLog) SandboxMode() (SandboxMode, bool)

SandboxMode 从事件日志 fold 出会话级沙箱模式覆盖: 取最后一个 sandbox/mode 事件的 mode;没有则返回 ok=false。 对齐官方 packages/sandbox-policy/session-mode.ts 的 effectiveSandboxMode。

func (*SessionLog) SessionID

func (sl *SessionLog) SessionID() brand.SessionID

SessionID 返回日志所属会话 ID。

type SessionProjection

type SessionProjection struct {
	Messages      []Message               `json:"messages"`
	RequestHeader RequestHeaderFold       `json:"requestHeader"`
	SandboxMode   EffectiveSandboxMode    `json:"sandboxMode"`
	Approval      EffectiveApprovalPolicy `json:"approvalPolicy"`
	Preset        PermissionPresetFold    `json:"preset"`
	Goal          GoalFold                `json:"goal"`
	Todo          TodoFold                `json:"todo"`
	PlanMode      PlanModeFold            `json:"planMode"`
	Title         SessionTitleFold        `json:"title"`
}

SessionProjection 是全部派生投影的聚合视图。

func FoldAll

func FoldAll(events []SessionEvent) SessionProjection

FoldAll 对事件列表做一次全量折叠,返回全部派生状态。

func FoldAllFromLog

func FoldAllFromLog(sl *SessionLog) SessionProjection

FoldAllFromLog 从 SessionLog 直接折叠(便捷入口)。

type SessionReferenceError

type SessionReferenceError struct {
	Code SessionReferenceErrorCode
	Msg  string
}

SessionReferenceError 携带稳定错误码的引用失败错误。

func (*SessionReferenceError) Error

func (e *SessionReferenceError) Error() string

type SessionReferenceErrorCode

type SessionReferenceErrorCode string

SessionReferenceErrorCode 是会话引用失败的稳定分类码。

const (
	// RefCodeInvalidConfig 配置无效(如缺少 resolver / 工作区根)。
	RefCodeInvalidConfig SessionReferenceErrorCode = "SESSION_REFERENCE_INVALID_CONFIG"
	// RefCodeInvalidReference 引用语法或目标不合法。
	RefCodeInvalidReference SessionReferenceErrorCode = "SESSION_REFERENCE_INVALID_REFERENCE"
	// RefCodeSelfReference 引用了请求代理自身所在的会话。
	RefCodeSelfReference SessionReferenceErrorCode = "SESSION_REFERENCE_SELF_REFERENCE"
	// RefCodeTooMany 引用数量超过上限。
	RefCodeTooMany SessionReferenceErrorCode = "SESSION_REFERENCE_TOO_MANY"
	// RefCodeReadFailed 读取源会话失败。
	RefCodeReadFailed SessionReferenceErrorCode = "SESSION_REFERENCE_READ_FAILED"
	// RefCodeBudgetExceeded 聚合上下文超出允许预算。
	RefCodeBudgetExceeded SessionReferenceErrorCode = "SESSION_REFERENCE_BUDGET_EXCEEDED"
	// RefCodeCancelled 引用准备被取消。
	RefCodeCancelled SessionReferenceErrorCode = "SESSION_REFERENCE_CANCELLED"
	// RefCodeSessionNotFound 引用的会话不存在(M17 验收补充码)。
	RefCodeSessionNotFound SessionReferenceErrorCode = "SESSION_NOT_FOUND"
	// RefCodeFileNotFound 引用的文件不存在(M17 验收补充码)。
	RefCodeFileNotFound SessionReferenceErrorCode = "FILE_NOT_FOUND"
	// RefCodeFileOutOfWorkspace 引用文件位于工作区根之外(越界,禁止访问)。
	RefCodeFileOutOfWorkspace SessionReferenceErrorCode = "FILE_OUT_OF_WORKSPACE"
)

与上游 SessionReferenceErrorCode 对齐的错误码;另按 M17 验收补充文件/会话未找到码。

func RefCodeFrom

func RefCodeFrom(err error) SessionReferenceErrorCode

RefCodeFrom 从任意 error 提取稳定的引用错误码;非引用错误返回空串。

type SessionReferenceInput

type SessionReferenceInput struct {
	// SessionID 是源会话身份(权威标识)。
	SessionID brand.SessionID
	// Label 是可选的展示标签,进入快照。
	Label string
}

SessionReferenceInput 表示一次被选中的源会话(宿主传入的结构化引用)。

type SessionReferenceResolver

type SessionReferenceResolver interface {
	// ResolveSession 返回目标会话的可读快照片段;会话不存在返回 RefCodeSessionNotFound,
	// 读取失败返回 RefCodeReadFailed。
	ResolveSession(id brand.SessionID) (string, error)
	// ResolveFile 返回目标文件的摘要片段;不存在返回 RefCodeFileNotFound,
	// 越界(超出工作区根)返回 RefCodeFileOutOfWorkspace。
	ResolveFile(path string) (string, error)
	// WorkspaceRoot 返回当前代理绑定的工作区根(用于文件越界判定)。
	WorkspaceRoot() string
}

SessionReferenceResolver 抽象「如何把一个 mention 目标解析成上下文片段」。

设计意图:跨会话读取依赖 persistence(M43),文件解析依赖 Filesystem(M35)。 两个依赖在 M17 阶段可能尚未全部就绪,因此这里以接缝接口暴露,宿主/测试可注入真实 或桩实现;默认提供面向工作区根的文件系统桩(os.Stat 判定存在/越界)。

type SessionTitleData

type SessionTitleData struct {
	Title string `json:"title"`
}

SessionTitleData session/title:会话标题(latest-wins)。

func (SessionTitleData) EventType

func (SessionTitleData) EventType() EventType

type SessionTitleFold

type SessionTitleFold struct {
	Present bool   `json:"present"`
	Title   string `json:"title,omitempty"`
}

SessionTitleFold 是会话标题投影(latest-wins)。

func ApplySessionTitle

func ApplySessionTitle(s SessionTitleFold, ev SessionEvent) SessionTitleFold

ApplySessionTitle latest-wins。

func FoldSessionTitle

func FoldSessionTitle(events []SessionEvent) SessionTitleFold

FoldSessionTitle 是 foldSessionTitle 的导出版本。

func (SessionTitleFold) Equal

Equal 对 SessionTitleFold。

type SkillInjectData

type SkillInjectData struct {
	SkillName string `json:"skillName"`
	Content   string `json:"content,omitempty"`
}

SkillInjectData skill/inject:技能内容注入为 user message。

func (SkillInjectData) EventType

func (SkillInjectData) EventType() EventType

type SkillsCatalogData

type SkillsCatalogData struct {
	Catalog string `json:"catalog"`
	Hash    string `json:"hash"`
}

SkillsCatalogData skills/catalog:技能目录全量快照(change-only 注入用)。

func (SkillsCatalogData) EventType

func (SkillsCatalogData) EventType() EventType

type SkillsChangeData

type SkillsChangeData struct {
	Added   []string `json:"added,omitempty"`
	Removed []string `json:"removed,omitempty"`
	Changed []string `json:"changed,omitempty"`
}

SkillsChangeData skills/change:技能目录变更。

func (SkillsChangeData) EventType

func (SkillsChangeData) EventType() EventType

type StepEndData

type StepEndData struct {
	Turn    uint64 `json:"turn"`
	Step    uint64 `json:"step"`
	StepSeq uint64 `json:"stepSeq,omitempty"` // 兼容旧字段,等同于 Step
}

StepEndData step/end:单步结束。

func (StepEndData) EventType

func (StepEndData) EventType() EventType

type StepStartData

type StepStartData struct {
	Turn    uint64 `json:"turn"`
	Step    uint64 `json:"step"`
	StepSeq uint64 `json:"stepSeq,omitempty"` // 兼容旧字段,等同于 Step
}

StepStartData step/start:单步开始。 Step 是从 1 开始的单调递增整数,每个 Turn 内独立计数(新 Turn 开始时重置为 1)。

func (StepStartData) EventType

func (StepStartData) EventType() EventType

type SurfaceNode

type SurfaceNode struct {
	// Seq 事件序号。
	Seq uint64
	// Replaced 是否为替换事件(携带 surfaceOp=replace)。
	Replaced bool
	// Event 该节点的完整事件。
	Event SessionEvent
}

SurfaceNode 是表面折叠后的单个节点(源事件或替换事件)。

type SurfaceOp

type SurfaceOp struct {
	Op    SurfaceOpKind   `json:"op"`
	Start uint64          `json:"start,omitempty"`
	End   uint64          `json:"end,omitempty"`
	Data  json.RawMessage `json:"data,omitempty"`
}

SurfaceOp 描述一次表面操作(世代标记)。

  • op=replace 时,Start/End 标记被替换的旧事件 seq 范围(闭区间),Data 为替换载荷;
  • 该结构被持久化在 SessionEvent.surfaceOp 字段,读时应用,不改写源事件。

func NewAppendOp

func NewAppendOp() *SurfaceOp

NewAppendOp 构造一个追加标记(默认语义)。

func NewReplaceOp

func NewReplaceOp(start, end uint64, data json.RawMessage) *SurfaceOp

NewReplaceOp 构造一个替换标记。

type SurfaceOpKind

type SurfaceOpKind string

SurfaceOpKind 表面操作类型。

const (
	// SurfaceAppend 普通追加(默认,无需显式声明)。
	SurfaceAppend SurfaceOpKind = "append"
	// SurfaceReplace 表面替换:将 [Start, End] 范围的旧事件在"读取时"替换为 Data,
	// 源事件本身不可变(compaction 唯一合法回写历史的方式)。
	SurfaceReplace SurfaceOpKind = "replace"
)

表面操作枚举。

type SurfaceReplaceData

type SurfaceReplaceData struct {
	Start uint64          `json:"start"`
	End   uint64          `json:"end"`
	Data  json.RawMessage `json:"data,omitempty"`
}

SurfaceReplaceData surface/replace:表面替换(compaction 唯一合法回写方式)。

func (SurfaceReplaceData) EventType

func (SurfaceReplaceData) EventType() EventType

type TodoEntry

type TodoEntry struct {
	Content string `json:"content"`
	Status  string `json:"status"` // pending | in_progress | completed
}

TodoEntry 是一条带三态状态的待办(对齐官方 TodoItem)。

type TodoFold

type TodoFold struct {
	Present bool        `json:"present"`
	Items   []string    `json:"items,omitempty"`
	Entries []TodoEntry `json:"entries,omitempty"`
}

TodoFold 是待办列表投影(整体替换,last-write-wins)。

func ApplyTodoWrite

func ApplyTodoWrite(s TodoFold, ev SessionEvent) TodoFold

ApplyTodoWrite latest-wins(整体替换)。

func FoldTodoWrite

func FoldTodoWrite(events []SessionEvent) TodoFold

FoldTodoWrite 是 foldTodoWrite 的导出版本。

func (TodoFold) Equal

func (t TodoFold) Equal(o ProjectionState) bool

Equal 对 TodoFold。

type TodoWriteData

type TodoWriteData struct {
	Items   []string    `json:"items,omitempty"`
	Entries []TodoEntry `json:"entries,omitempty"`
}

TodoWriteData todo/write:整体替换待办列表。 Items 为仅内容的兼容字段,Entries 携带三态状态。

func (TodoWriteData) EventType

func (TodoWriteData) EventType() EventType

type ToolCallData

type ToolCallData struct {
	CallID brand.ToolCallID `json:"callId"`
	Tool   string           `json:"tool"`
	Input  json.RawMessage  `json:"input,omitempty"`
}

ToolCallData tool/call:一次工具调用发起。

func (ToolCallData) EventType

func (ToolCallData) EventType() EventType

type ToolErrorData

type ToolErrorData struct {
	CallID brand.ToolCallID `json:"callId"`
	Error  string           `json:"error"`
}

ToolErrorData tool/error:工具执行错误。

func (ToolErrorData) EventType

func (ToolErrorData) EventType() EventType

type ToolObservedData

type ToolObservedData struct {
	CallID brand.ToolCallID `json:"callId"`
	Kind   string           `json:"kind"`
}

ToolObservedData tool/observed:工具产生的可观察事件(fs 先读后写等)。

func (ToolObservedData) EventType

func (ToolObservedData) EventType() EventType

type ToolPresentationData

type ToolPresentationData struct {
	CallID brand.ToolCallID `json:"callId"`
	Card   string           `json:"card"`
}

ToolPresentationData tool/presentation:工具展示卡片(中立 vocabulary)。

func (ToolPresentationData) EventType

func (ToolPresentationData) EventType() EventType

type ToolResultData

type ToolResultData struct {
	CallID    brand.ToolCallID `json:"callId"`
	IsError   bool             `json:"isError,omitempty"`
	Output    string           `json:"output,omitempty"`
	Truncated bool             `json:"truncated,omitempty"`
	SpillPath string           `json:"spillPath,omitempty"`
}

ToolResultData tool/result:一次工具调用结果(与 tool/call 按 CallID 配对)。

func (ToolResultData) EventType

func (ToolResultData) EventType() EventType

type TurnEndData

type TurnEndData struct {
	Turn   uint64        `json:"turn"`
	Reason TurnEndReason `json:"reason"`
}

TurnEndData turn/end:一个 Turn 轮次结束。

func (TurnEndData) EventType

func (TurnEndData) EventType() EventType

type TurnEndReason

type TurnEndReason string

TurnEndReason 是 turn/end 的关闭原因。

const (
	ReasonCompleted   TurnEndReason = "completed"
	ReasonFinished    TurnEndReason = "finished" // 兼容旧名称,等同于 completed
	ReasonInterrupted TurnEndReason = "interrupted"
	ReasonAborted     TurnEndReason = "aborted"
	ReasonBlocked     TurnEndReason = "blocked"
	ReasonError       TurnEndReason = "error"
	ReasonMaxTokens   TurnEndReason = "max-tokens"
)

turn/end 关闭原因枚举。 对齐官方 packages/core/session/src/types.ts TurnEndReasonMap: completed / aborted / blocked / error / max-tokens / interrupted

type TurnStartData

type TurnStartData struct {
	Turn uint64 `json:"turn"`
}

TurnStartData turn/start:一个 Turn 轮次开始。 Turn 是从 0 开始的单调递增整数,每个会话独立计数。

func (TurnStartData) EventType

func (TurnStartData) EventType() EventType

type TurnStoppingData

type TurnStoppingData struct {
	Reason string `json:"reason,omitempty"`
}

TurnStoppingData turn/stopping:turn 进入停止流程(goal round driver 等监听)。

func (TurnStoppingData) EventType

func (TurnStoppingData) EventType() EventType

type UserMessageData

type UserMessageData struct {
	Content string `json:"content"`
	Source  string `json:"source,omitempty"` // e.g. "user" / "reference" / "injected"
	Refs    []any  `json:"refs,omitempty"`   // 引用的 session/文件
}

UserMessageData user/message:用户消息。

func (UserMessageData) EventType

func (UserMessageData) EventType() EventType

type UserQuestionData

type UserQuestionData struct {
	Question string `json:"question"`
	Answer   string `json:"answer,omitempty"`
}

UserQuestionData user/question:用户提问(UQ 接缝)。

func (UserQuestionData) EventType

func (UserQuestionData) EventType() EventType

type WorkspaceChangeData

type WorkspaceChangeData struct {
	WorkspaceID brand.WorkspaceID `json:"workspaceId"`
	Root        string            `json:"root,omitempty"`
}

WorkspaceChangeData workspace/change:工作区记录变更。

func (WorkspaceChangeData) EventType

func (WorkspaceChangeData) EventType() EventType

type WorkspaceFileResolver

type WorkspaceFileResolver struct {
	Root string
}

WorkspaceFileResolver 是基于工作区根的文件系统桩实现。

warning: 仅做存在性与越界判定,不读取文件内容(上游 file-reference 的发现阶段也是 「path-only」而不读内容);真正读内容交给 M35 Filesystem 接缝。

func (*WorkspaceFileResolver) ResolveFile

func (r *WorkspaceFileResolver) ResolveFile(path string) (string, error)

ResolveFile 判定文件存在性并返回摘要(此处仅返回路径摘要;读内容由 M35 承接)。

func (*WorkspaceFileResolver) ResolveSession

func (r *WorkspaceFileResolver) ResolveSession(brand.SessionID) (string, error)

ResolveSession 对文件解析器而言"无会话能力",返回 invalid hook error(以便组合)。

func (*WorkspaceFileResolver) WorkspaceRoot

func (r *WorkspaceFileResolver) WorkspaceRoot() string

WorkspaceRoot 返回工作区根。

Jump to

Keyboard shortcuts

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