agentprotocol

package
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package agentprotocol defines the versioned, provider-neutral Agent memory runtime contract: principal, scope, memory record, context request/pack, proposal, handoff, feedback and adapter descriptor.

此包只持有 DTO、校验和稳定错误码;不依赖 GORM、CLI 渲染或具体 runtime SDK。 所有 schema 使用 `yeisme.agent_*.*.v1` 版本号,unknown optional metadata 应可忽略。

Index

Constants

View Source
const (
	// ErrCodeInvalidScope — scope 缺失、格式错误或不可解析。
	ErrCodeInvalidScope = "invalid_scope"
	// ErrCodeInsufficientScope — principal 权限不足以覆盖请求 scope。
	ErrCodeInsufficientScope = "insufficient_scope"
	// ErrCodePermissionUnknown — source 可见性无法判定(private source 越权)。
	ErrCodePermissionUnknown = "permission_unknown"
	// ErrCodeValidationFailed — DTO 字段校验失败。
	ErrCodeValidationFailed = "validation_failed"
	// ErrCodeApprovalRequired — 写操作需要 owner 显式批准。
	ErrCodeApprovalRequired = "approval_required"
	// ErrCodeConflictRequired — 存在冲突 confirmed memory,需要显式解决。
	ErrCodeConflictRequired = "conflict_required"
	// ErrCodeRejected — proposal 被 review 拒绝。
	ErrCodeRejected = "rejected"
	// ErrCodeAdapterUnavailable — reference adapter 不可用或版本不支持。
	ErrCodeAdapterUnavailable = "adapter_unavailable"
	// ErrCodeBudgetExceeded — context pack 超出请求 budget(非致命,仅 truncated)。
	ErrCodeBudgetExceeded = "budget_exceeded"
)

常用稳定错误码(stable English codes)。

View Source
const AdapterSchemaVersion = "yeisme.agent_adapter.v1"

AdapterSchemaVersion 是 adapter descriptor 的 schema 版本。

View Source
const ContextSchemaVersion = "yeisme.agent_context_pack.v1"

ContextSchemaVersion 是 context request/pack 的 schema 版本。

View Source
const HandoffSchemaVersion = "yeisme.agent_handoff.v1"

HandoffSchemaVersion 是 cross-agent handoff 的 schema 版本。

View Source
const SchemaVersion = "yeisme.agent_memory.v1"

SchemaVersion 是 Agent memory runtime DTO 的 schema 版本。

Variables

This section is empty.

Functions

func ValidTransition

func ValidTransition(from, to LifecycleState) bool

ValidTransition 判断 lifecycle 转换是否合法。 非法 transition 返回 false,调用方应返回稳定 error code。

Types

type AdapterDescriptor

type AdapterDescriptor struct {
	SchemaVersion     string       `json:"schema_version"`
	AdapterID         string       `json:"adapter_id"`
	Runtime           string       `json:"runtime"`
	SupportedVersions []string     `json:"supported_versions"`
	Capabilities      []Capability `json:"capabilities"`
	MaxContextItems   int          `json:"max_context_items,omitempty"`
	MaxContextChars   int          `json:"max_context_chars,omitempty"`
	SupportsProposal  bool         `json:"supports_proposal"`
	SupportsHandoff   bool         `json:"supports_handoff"`
	SupportsFeedback  bool         `json:"supports_feedback"`
	// Metadata 携带 optional runtime-specific 信息(如 Codex hook version、Cohors team role)。
	Metadata map[string]string `json:"metadata,omitempty"`
}

AdapterDescriptor 声明一个 Agent runtime adapter 的能力。 Core field 100% 共用;runtime-specific 信息放 Metadata。

func (AdapterDescriptor) Validate

func (d AdapterDescriptor) Validate() error

Validate 检查 descriptor 必填字段。

type Capability

type Capability string

Capability 表示 principal 持有的能力。Agent 默认只能 propose; confirmed mutation 需要 owner capability 或显式 policy 授权。

const (
	CapabilityRead     Capability = "read"
	CapabilityPropose  Capability = "propose"
	CapabilityReview   Capability = "review"
	CapabilityApprove  Capability = "approve"
	CapabilityConfirm  Capability = "confirm"
	CapabilityHandoff  Capability = "handoff"
	CapabilityFeedback Capability = "feedback"
)

type Confidence

type Confidence string

Confidence 表示 memory 的置信度分级。

const (
	ConfidenceLow      Confidence = "low"
	ConfidenceMedium   Confidence = "medium"
	ConfidenceHigh     Confidence = "high"
	ConfidenceVerified Confidence = "verified"
)

type ContextBudget

type ContextBudget struct {
	MaxItems int `json:"max_items,omitempty"`
	MaxChars int `json:"max_chars,omitempty"`
}

ContextBudget 限制 context pack 的大小。 Compiler 按确定性顺序截断,超限时设 truncated=true 并提供 drill-down actions。

type ContextConflict

type ContextConflict struct {
	MemoryIDs []string `json:"memory_ids"`
	Reason    string   `json:"reason,omitempty"`
}

ContextConflict 描述一组冲突的 memory。

type ContextEntry

type ContextEntry struct {
	MemoryID    string         `json:"memory_id"`
	Kind        MemoryKind     `json:"kind"`
	Subject     string         `json:"subject,omitempty"`
	Summary     string         `json:"summary,omitempty"`
	Preview     string         `json:"preview,omitempty"`
	Confidence  Confidence     `json:"confidence,omitempty"`
	Sources     SourceRefList  `json:"sources,omitempty"`
	State       LifecycleState `json:"state"`
	ScoreReason string         `json:"score_reason,omitempty"`
}

ContextEntry 是 context pack 中的一个 bounded 条目。 不输出完整 note body;Preview 是受限摘要。

type ContextPack

type ContextPack struct {
	SchemaVersion  string            `json:"schema_version"`
	Principal      Principal         `json:"principal"`
	Scope          Scope             `json:"scope"`
	Facts          []ContextEntry    `json:"facts,omitempty"`
	Decisions      []ContextEntry    `json:"decisions,omitempty"`
	Preferences    []ContextEntry    `json:"preferences,omitempty"`
	Procedures     []ContextEntry    `json:"procedures,omitempty"`
	OpenTasks      []ContextEntry    `json:"open_tasks,omitempty"`
	FailedAttempts []ContextEntry    `json:"failed_attempts,omitempty"`
	Conflicts      []ContextConflict `json:"conflicts,omitempty"`
	Sources        SourceRefList     `json:"sources,omitempty"`
	NextActions    []NextAction      `json:"next_actions,omitempty"`
	Truncated      bool              `json:"truncated,omitempty"`
}

ContextPack 是 compiler 产出的 bounded context bundle。

func (ContextPack) AssertNoBody

func (p ContextPack) AssertNoBody(maxPreviewChars int) error

AssertNoBody 报告 pack 中是否有任何 entry 携带了看起来像完整 body 的大段文本。 这是一个防御性检查,用于 contract test。

func (ContextPack) EntryCount

func (p ContextPack) EntryCount() int

EntryCount 返回 pack 中所有 entry 的总数。

func (ContextPack) EntryPreviewChars

func (p ContextPack) EntryPreviewChars() int

EntryPreviewChars 返回所有 entry preview 的总字符数。

type ContextRequest

type ContextRequest struct {
	SchemaVersion string        `json:"schema_version"`
	Principal     Principal     `json:"principal"`
	Scope         Scope         `json:"scope"`
	Task          string        `json:"task,omitempty"`
	Intent        string        `json:"intent,omitempty"`
	Entities      []string      `json:"entities,omitempty"`
	KindFilter    []MemoryKind  `json:"kind_filter,omitempty"`
	Budget        ContextBudget `json:"budget,omitempty"`
}

ContextRequest 描述一次 context compilation 请求。 Principal 和 Scope 必须显式提供;intent/entities/filter 可选。

func (ContextRequest) Validate

func (r ContextRequest) Validate() error

Validate 检查 request 必填字段。

type Feedback

type Feedback struct {
	SchemaVersion string       `json:"schema_version"`
	FeedbackID    string       `json:"feedback_id"`
	Principal     Principal    `json:"principal"`
	Scope         Scope        `json:"scope"`
	Kind          FeedbackKind `json:"kind"`
	// MemoryID 指向被反馈的 memory(如适用)。
	MemoryID string `json:"memory_id,omitempty"`
	// ContextRequestRef 指向触发反馈的 context request(如适用)。
	ContextRequestRef string    `json:"context_request_ref,omitempty"`
	Comment           string    `json:"comment,omitempty"`
	CreatedAt         time.Time `json:"created_at"`
}

Feedback 记录一次 context/recall 的质量反馈。

func (Feedback) Validate

func (f Feedback) Validate() error

Validate 检查 feedback 必填字段。

type FeedbackKind

type FeedbackKind string

FeedbackKind 是 recall feedback 的结论类型。 Feedback 独立记录结论,不静默改写 memory content。

const (
	FeedbackUseful       FeedbackKind = "useful"
	FeedbackIrrelevant   FeedbackKind = "irrelevant"
	FeedbackStale        FeedbackKind = "stale"
	FeedbackIncorrect    FeedbackKind = "incorrect"
	FeedbackMissing      FeedbackKind = "missing"
	FeedbackCompleted    FeedbackKind = "completed"
	FeedbackScopeTooWide FeedbackKind = "scope_too_wide"
)

type Handoff

type Handoff struct {
	SchemaVersion string    `json:"schema_version"`
	HandoffID     string    `json:"handoff_id"`
	FromPrincipal Principal `json:"from_principal"`
	ToPrincipal   Principal `json:"to_principal"`
	Scope         Scope     `json:"scope"`
	Objective     string    `json:"objective"`
	CreatedAt     time.Time `json:"created_at"`
	// CurrentState 描述任务当前进度摘要。
	CurrentState string `json:"current_state,omitempty"`
	// Decisions 是已做出的关键决策列表。
	Decisions []string `json:"decisions,omitempty"`
	// CompletedWork 是已完成的工作项。
	CompletedWork []string `json:"completed_work,omitempty"`
	// Blockers 是当前阻塞项。
	Blockers []string `json:"blockers,omitempty"`
	// Verification 是验证标准或已验证结果。
	Verification []string `json:"verification,omitempty"`
	// FollowUps 是建议的后续操作。
	FollowUps []string `json:"follow_ups,omitempty"`
	// Sources 引用相关 evidence。
	Sources SourceRefList `json:"sources,omitempty"`
	// RequestedNextCapability 是接收方应具备的能力。
	RequestedNextCapability string `json:"requested_next_capability,omitempty"`
}

Handoff 携带 bounded working state,用于 cross-agent 任务交接。 不等同于 confirmed memory;不要求共享完整 transcript 或 model reasoning。

func (Handoff) Validate

func (h Handoff) Validate() error

Validate 检查 handoff 必填字段。

type LifecycleState

type LifecycleState string

LifecycleState 是 memory record 的生命周期状态。

const (
	LifecycleProposed   LifecycleState = "proposed"
	LifecycleConfirmed  LifecycleState = "confirmed"
	LifecycleRejected   LifecycleState = "rejected"
	LifecycleSuperseded LifecycleState = "superseded"
	LifecycleExpired    LifecycleState = "expired"
	LifecycleConflicted LifecycleState = "conflicted"
)

type MemoryKind

type MemoryKind string

MemoryKind 是 memory record 的语义类型。 旧消费者应把未知 kind 当通用 record 处理,而不是失败。

const (
	MemoryKindFact       MemoryKind = "fact"
	MemoryKindDecision   MemoryKind = "decision"
	MemoryKindPreference MemoryKind = "preference"
	MemoryKindProcedure  MemoryKind = "procedure"
	MemoryKindEvent      MemoryKind = "event"
	MemoryKindTask       MemoryKind = "task"
	MemoryKindFailure    MemoryKind = "failure"
)

type MemoryRecord

type MemoryRecord struct {
	SchemaVersion string         `json:"schema_version"`
	ID            string         `json:"id"`
	Kind          MemoryKind     `json:"kind"`
	Scope         Scope          `json:"scope"`
	State         LifecycleState `json:"state"`
	Subject       string         `json:"subject,omitempty"`
	Predicate     string         `json:"predicate,omitempty"`
	Object        string         `json:"object,omitempty"`
	Summary       string         `json:"summary,omitempty"`
	Confidence    Confidence     `json:"confidence,omitempty"`
	Sources       SourceRefList  `json:"sources,omitempty"`
	CreatorID     string         `json:"creator_id"`
	SupersedesID  string         `json:"supersedes_id,omitempty"`
	ConflictsWith []string       `json:"conflicts_with,omitempty"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	ExpiresAt     *time.Time     `json:"expires_at,omitempty"`
	// Metadata 携带 optional adapter-specific 信息,unknown key 应被忽略。
	Metadata map[string]string `json:"metadata,omitempty"`
}

MemoryRecord 是 Agent memory 的 canonical runtime view。 在现有 internal/memory.Record 之上增加 kind、scope、source、creator、 supersession/conflict 和 schema version。

func (MemoryRecord) IsExpired

func (m MemoryRecord) IsExpired(now time.Time) bool

IsExpired 判断 memory 是否已过期(基于 ExpiresAt)。

func (MemoryRecord) IsRecallable

func (m MemoryRecord) IsRecallable() bool

IsRecallable 判断 memory 是否应出现在默认 confirmed recall 结果中。 proposed/rejected/expired/superseded 默认不参与 recall。

func (MemoryRecord) Validate

func (m MemoryRecord) Validate() error

Validate 检查 memory record 的必填字段和枚举值。

type NegotiateResult

type NegotiateResult struct {
	Compatible         bool         `json:"compatible"`
	NegotiatedVersion  string       `json:"negotiated_version,omitempty"`
	SharedCapabilities []Capability `json:"shared_capabilities,omitempty"`
	Reason             string       `json:"reason,omitempty"`
	Degraded           bool         `json:"degraded,omitempty"`
}

NegotiateResult 是 capability negotiation 的结果。

func Negotiate

func Negotiate(d AdapterDescriptor, localVersions []string, requestedCapabilities []Capability) NegotiateResult

Negotiate 判断本地 runtime 是否与 adapter descriptor 兼容。 localVersions 是本地支持的 schema 版本列表,requestedCapabilities 是本地需要的能力。 版本交集为空或能力不满足时返回 degraded=false,compatible=false。

type NextAction

type NextAction struct {
	Name    string `json:"name"`
	Command string `json:"command,omitempty"`
	Reason  string `json:"reason,omitempty"`
}

NextAction 是 context pack 提供的安全 drill-down 操作建议。

type Principal

type Principal struct {
	SchemaVersion string       `json:"schema_version"`
	PrincipalID   string       `json:"principal_id"`
	Runtime       string       `json:"runtime,omitempty"`
	AgentID       string       `json:"agent_id,omitempty"`
	OwnerID       string       `json:"owner_id,omitempty"`
	WorkspaceID   string       `json:"workspace_id,omitempty"`
	Capabilities  []Capability `json:"capabilities"`
	Trust         TrustLevel   `json:"trust"`
	// Metadata 携带 optional adapter-specific 信息,unknown key 应被忽略。
	Metadata map[string]string `json:"metadata,omitempty"`
}

Principal 表示发起 memory 操作的 actor。 Runtime 只用于 adapter metadata,不参与 memory identity。 PrincipalID 是稳定身份标识,跨 session 保持一致。

func DefaultAdapterPrincipal

func DefaultAdapterPrincipal(principalID, runtime string) Principal

DefaultAdapterPrincipal 构造一个典型 adapter principal(只能 propose/read/feedback)。 用于 reference adapter harness 和测试。

func (Principal) CanConfirm

func (p Principal) CanConfirm() bool

CanConfirm 判断 principal 是否默认可以直接 confirm memory。 只有 owner trust 或显式 confirm capability 才允许。

func (Principal) HasCapability

func (p Principal) HasCapability(cap Capability) bool

HasCapability 判断 principal 是否持有给定能力。

func (Principal) Validate

func (p Principal) Validate() error

Validate 检查 principal 必填字段和 trust/capability 一致性。

type Proposal

type Proposal struct {
	SchemaVersion  string         `json:"schema_version"`
	ProposalID     string         `json:"proposal_id"`
	Principal      Principal      `json:"principal"`
	Scope          Scope          `json:"scope"`
	Kind           MemoryKind     `json:"kind"`
	Subject        string         `json:"subject,omitempty"`
	Summary        string         `json:"summary,omitempty"`
	Object         string         `json:"object,omitempty"`
	RequestedState LifecycleState `json:"requested_state"`
	Sources        SourceRefList  `json:"sources,omitempty"`
	Risk           RiskLevel      `json:"risk,omitempty"`
	Reason         string         `json:"reason,omitempty"`
	CreatedAt      time.Time      `json:"created_at"`
}

Proposal 是 Agent 提交的 memory 候选。 Agent 默认只能 propose;review 通过后由 owner service confirm。

func (Proposal) Validate

func (p Proposal) Validate() error

Validate 检查 proposal 必填字段。

type ProposalReview

type ProposalReview struct {
	ProposalID string               `json:"proposal_id"`
	Status     ProposalStatus       `json:"status"`
	Reason     ProposalStatusReason `json:"reason"`
	Message    string               `json:"message,omitempty"`
	// ConflictingMemoryIDs 列出与 proposal 冲突的现有 memory。
	ConflictingMemoryIDs []string `json:"conflicting_memory_ids,omitempty"`
	// DuplicateMemoryID 如果 proposal 与现有 memory 重复,指向该 memory。
	DuplicateMemoryID string `json:"duplicate_memory_id,omitempty"`
}

ProposalReview 是 review service 对 proposal 的评估结果。

type ProposalStatus

type ProposalStatus string

ProposalStatus 是 memory proposal 的 review 结果状态。

const (
	ProposalStatusDraftSaved       ProposalStatus = "draft_saved"
	ProposalStatusApprovalRequired ProposalStatus = "approval_required"
	ProposalStatusConflictRequired ProposalStatus = "conflict_required"
	ProposalStatusApproved         ProposalStatus = "approved"
	ProposalStatusRejected         ProposalStatus = "rejected"
	ProposalStatusSuperseded       ProposalStatus = "superseded"
)

type ProposalStatusReason

type ProposalStatusReason string

ProposalStatusReason 是 review service 返回的稳定原因码。

const (
	ReasonValid            ProposalStatusReason = "valid"
	ReasonDuplicate        ProposalStatusReason = "duplicate"
	ReasonConflictExisting ProposalStatusReason = "conflict_existing"
	ReasonUnsourced        ProposalStatusReason = "unsourced"
	ReasonPolicyDenied     ProposalStatusReason = "policy_denied"
	ReasonScopeMismatch    ProposalStatusReason = "scope_mismatch"
)

type Receipt

type Receipt struct {
	SchemaVersion string         `json:"schema_version"`
	ReceiptID     string         `json:"receipt_id"`
	Kind          string         `json:"kind"` // proposal_approved, handoff_created, feedback_added 等
	PrincipalID   string         `json:"principal_id"`
	Scope         Scope          `json:"scope"`
	MemoryID      string         `json:"memory_id,omitempty"`
	ProposalID    string         `json:"proposal_id,omitempty"`
	SourceRefs    SourceRefList  `json:"source_refs,omitempty"`
	LifecycleFrom LifecycleState `json:"lifecycle_from,omitempty"`
	LifecycleTo   LifecycleState `json:"lifecycle_to,omitempty"`
	CreatedAt     time.Time      `json:"created_at"`
}

Receipt 是 proposal/handoff/feedback 写操作的脱敏审计记录。 不包含完整 body 或 secret。

type RiskLevel

type RiskLevel string

RiskLevel 是 proposal 的风险分级,影响是否需要更高级别审批。

const (
	RiskLow    RiskLevel = "low"
	RiskMedium RiskLevel = "medium"
	RiskHigh   RiskLevel = "high"
)

type Scope

type Scope struct {
	Kind ScopeKind `json:"kind"`
	ID   string    `json:"id"`
}

Scope 表示一个 Agent memory 的归属范围。 Kind 是层级,ID 是该层级的稳定标识(如 owner_id、workspace_id、project_path)。 Request 必须显式 scope;缺省值只能由已注册 profile/application service 补齐。

func (Scope) Contains

func (s Scope) Contains(other Scope) bool

Contains 判断 receiver scope 是否覆盖 given scope(层级 >= given 即覆盖)。 owner 覆盖 workspace,workspace 覆盖 project,以此类推。 相同 kind + 相同 ID 视为包含。

func (Scope) Validate

func (s Scope) Validate() error

Validate 检查 scope kind 和 ID 是否合法。

type ScopeKind

type ScopeKind string

ScopeKind 枚举从宽到窄的 scope 层级。 scope 继承:owner > workspace > project > repository > session > task。 高层 scope 的 memory 对低层 scope 可见(除非被 permission 显式拒绝)。

const (
	ScopeKindOwner      ScopeKind = "owner"
	ScopeKindWorkspace  ScopeKind = "workspace"
	ScopeKindProject    ScopeKind = "project"
	ScopeKindRepository ScopeKind = "repository"
	ScopeKindSession    ScopeKind = "session"
	ScopeKindTask       ScopeKind = "task"
)

type SourceRef

type SourceRef struct {
	// Kind 是来源类型:note、receipt、task、asset、external_url 等。
	Kind string `json:"kind"`
	// Ref 是稳定标识:object_id、note_id、receipt ID 或 URL。
	Ref string `json:"ref"`
	// Label 是人类可读描述(如 note title 或 receipt summary),可选。
	Label string `json:"label,omitempty"`
	// Span 是可选的定位信息(如 heading path 或行号范围),可选。
	Span string `json:"span,omitempty"`
}

SourceRef 引用一个可验证的 evidence 来源。 不保存完整明文 body;只记录足以定位和审计的元数据。

func (SourceRef) Validate

func (s SourceRef) Validate() error

Validate 检查 source ref 最小必填字段。

type SourceRefList

type SourceRefList []SourceRef

SourceRefList 是一组 source ref,提供批量校验和去重。

func (SourceRefList) IsEmpty

func (l SourceRefList) IsEmpty() bool

IsEmpty 判断 source ref 列表是否为空。

func (SourceRefList) Validate

func (l SourceRefList) Validate() error

Validate 校验所有 ref。

type StableError

type StableError struct {
	Code    string            `json:"code"`
	Message string            `json:"message"`
	Details map[string]string `json:"details,omitempty"`
}

StableError 是 Agent memory runtime 的稳定错误信封。 Code 是稳定英文标识符(snake_case),用于跨 runtime/transport 对齐; Message 是人类可读描述;Details 携带可选 diagnostic key/value。

func NewStableError

func NewStableError(code, message string) *StableError

NewStableError 构造一个 StableError。

func (*StableError) Error

func (e *StableError) Error() string

func (*StableError) WithDetail

func (e *StableError) WithDetail(key, value string) *StableError

WithDetail 追加一个 detail key/value 并返回原 error(便于链式调用)。

type TrustLevel

type TrustLevel string

TrustLevel 表示 principal 的信任等级,决定默认可执行操作。

const (
	// TrustLevelAdapter — 外部 Agent runtime adapter,默认只能 propose。
	TrustLevelAdapter TrustLevel = "adapter"
	// TrustLevelCollaborator — 协作者,可 review 但不能直接 confirm。
	TrustLevelCollaborator TrustLevel = "collaborator"
	// TrustLevelOwner — vault owner,可直接 confirm 和 approve。
	TrustLevelOwner TrustLevel = "owner"
)

Jump to

Keyboard shortcuts

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