Documentation
¶
Overview ¶
Package agent 提供 git-ferry 的 AI 助手能力(eino 编排层)。 本包不 import hertz:SSE/HTTP 适配在 biz/handler 层,便于内网壳复用。
Package agent — AI 运行时设置文件存储(data/ai-settings.json)。 与 conf/config.yaml 的 ai 段互补:yaml 为部署默认值,设置文件为界面改写后的覆盖层; API Key 只进设置文件(与「密钥不进 yaml」约定一致)。
Index ¶
- Constants
- Variables
- func APIKeyFromEnv() string
- func BuildPrompt(extra string) string
- func DecorateTool(name string, inner tool.InvokableTool) tool.InvokableTool
- func MaskKey(key string) string
- func MemoryManifest(s *memory.Store, limit int) string
- func NewMemBridge(s *memory.Store) tools.MemStore
- func SetPersistDir(dir string)
- type Config
- type Event
- type Message
- type PendingConfirm
- type Runner
- func (r *Runner) ExecuteConfirmed(ctx context.Context, sess *Session, toolName, token string) (string, error)
- func (r *Runner) ModelName() string
- func (r *Runner) Run(ctx context.Context, sess *Session, userMsg string) (<-chan Event, context.CancelFunc, error)
- func (r *Runner) Sessions() *SessionStore
- func (r *Runner) SetMemory(mem tools.MemStore, manifest string)
- func (r *Runner) SetPolicy(p *tools.Policy)
- type Session
- func (s *Session) ConsumeConsumed(toolName, argsJSON string) bool
- func (s *Session) ConsumeConsumedPending(toolName, argsJSON string) bool
- func (s *Session) ConsumePending(toolName, token string) (string, error)
- func (s *Session) LastConfirm() (toolName, token, argsJSON string)
- func (s *Session) MarkConsumed(toolName, argsJSON string)
- func (s *Session) PendingSnapshot() *PendingConfirm
- func (s *Session) PermissionMode() string
- func (s *Session) SetLastConfirm(toolName, token, argsJSON string)
- func (s *Session) SetPending(toolName, argsJSON string) (string, error)
- func (s *Session) SetPermissionMode(mode string) bool
- type SessionStore
- func (st *SessionStore) Append(s *Session, role, content string)
- func (st *SessionStore) Compact(s *Session, max int) int
- func (st *SessionStore) Create() *Session
- func (st *SessionStore) Get(id string) (*Session, error)
- func (st *SessionStore) Snapshot(s *Session) []Message
- func (st *SessionStore) StartJanitor(ctx context.Context, interval time.Duration)
- type Settings
- type SettingsStore
- type SettingsView
- type Usage
Constants ¶
const APIKeyEnvVar = "GIT_SYNC_AI_API_KEY" //nolint:gosec // 环境变量名,非凭据字面量
APIKeyEnvVar 模型 API Key 的环境变量名。密钥不写入 config.yaml。
Variables ¶
var ( ErrNoPending = errors.New("ai_confirm_none") ErrConfirmMismatch = errors.New("ai_confirm_mismatch") ErrConfirmExpired = errors.New("ai_confirm_expired") )
var ErrBusy = errors.New("ai_busy: 当前会话数已达上限,请稍后再试")
ErrBusy 并发会话已达上限。
var ErrSessionNotFound = errors.New("ai_session_not_found")
ErrSessionNotFound 会话不存在或已过期。
var Prompt = fmt.Sprintf(promptTemplate, dangerToolNames())
Prompt 助手 system prompt(危险工具清单已由 tools.DangerToolNames() 派生填入)。
Functions ¶
func BuildPrompt ¶ added in v1.17.0
BuildPrompt 生成 system prompt,可附加记忆摘要等上下文。
记忆摘要是「用户/agent 曾经写下的内容」——属于数据不是指令。 用 oagentkit guardx/injectband 包裹:打上来源标记,并转义 body 内伪造的 <system-reminder> 标签——否则记忆正文里写一个伪造标签就能把自己抬升成 系统注入(散文规则挡不住结构化标签)。
func DecorateTool ¶
func DecorateTool(name string, inner tool.InvokableTool) tool.InvokableTool
DecorateTool 包装工具,经 ctx 中的 sink 产出 tool_start/tool_end/tool_confirm 事件。危险工具返回确认标记时升级为 tool_confirm(携带令牌),前端据此弹确认卡。
func MemoryManifest ¶ added in v1.17.0
Manifest 记忆摘要(注入 system prompt)。
func NewMemBridge ¶ added in v1.17.0
NewMemBridge 构造适配器。
Types ¶
type Config ¶
type Config struct {
Enabled bool `yaml:"enabled"`
BaseURL string `yaml:"base_url"` // OpenAI 兼容端点,内网可指向 vLLM/Ollama
Model string `yaml:"model"`
Temperature float64 `yaml:"temperature"`
MaxTokens int `yaml:"max_tokens"`
TimeoutSeconds int `yaml:"timeout_seconds"`
MaxConcurrentChats int `yaml:"max_concurrent_chats"`
// MemoryPath AI 长期记忆文件(空=data/ai-memory.json)
MemoryPath string `yaml:"memory_path"`
// HistoryMax 会话保留的最大消息轮数,超出后压缩(0=默认 40)
HistoryMax int `yaml:"history_max"`
// MemoryManifest 运行时注入的记忆摘要(不进 yaml)
MemoryManifest string `yaml:"-"`
}
Config 对应 conf/config.yaml 的 ai 段(独立于 core 配置,core 的 yaml.Unmarshal 忽略未知字段,新增段不影响引擎加载)。
func LoadConfig ¶
LoadConfig 从 yaml 文件读取 ai 段;段缺失视为未启用,不报错。
type Event ¶
type Event struct {
Type string `json:"type"` // start|delta|tool_start|tool_end|tool_confirm|done|error
Content string `json:"content,omitempty"`
Tool string `json:"tool,omitempty"`
Args string `json:"args,omitempty"`
Result string `json:"result,omitempty"`
Token string `json:"token,omitempty"`
SessionID string `json:"session_id,omitempty"`
Usage *Usage `json:"usage,omitempty"`
}
Event SSE 层与 agent 的中立事件(decorator/Runner 产出,handler 消费)。
type PendingConfirm ¶
PendingConfirm 危险工具的一次待确认调用。确认令牌 = 哈希(会话+工具+参数), 前端原样带回;后端校验工具名与令牌一致且未过期后才执行,一次性消费。
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner AI 助手编排器:eino ChatModelAgent + 工具装饰器 + 会话存储。
func NewRunnerWithModel ¶
func NewRunnerWithModel(cfg *Config, cm model.BaseModel[*schema.Message], reg *tools.Registry) (*Runner, error)
NewRunnerWithModel 以注入模型构造(测试用)。
func (*Runner) ExecuteConfirmed ¶
func (r *Runner) ExecuteConfirmed(ctx context.Context, sess *Session, toolName, token string) (string, error)
ExecuteConfirmed 确认后直达执行:校验令牌 → 标记放行 → 直调工具 → 结果写入会话(不经过模型)。返回工具输出的 JSON 文本。
func (*Runner) Run ¶
func (r *Runner) Run(ctx context.Context, sess *Session, userMsg string) (<-chan Event, context.CancelFunc, error)
Run 执行一轮对话:写入用户消息 → 跑 agent → 事件推入返回的 chan。 chan 关闭即本轮结束;error 事件后 chan 也会关闭。 返回的 cancel 供消费方提前终止(如客户端断开):取消后所有事件发送与 模型流读取立即收敛,goroutine 退出并释放并发信号量,不再产生 token 消耗。
type Session ¶
type Session struct {
ID string
Messages []Message // 已完成轮次(不含进行中输出),超过 maxRounds 淘汰最旧
CreatedAt time.Time
LastAt time.Time
// contains filtered or unexported fields
}
Session 一次对话上下文。字段由 SessionStore 管理,外部只读; 确认相关方法见 confirm.go(实现 tools.SessionScope 适配,见 runner.go)。
func (*Session) ConsumeConsumed ¶ added in v1.17.0
ConsumeConsumed 一次性取走"确认后执行"放行标记(实现 tools.SessionScope)。
func (*Session) ConsumeConsumedPending ¶ added in v1.17.0
ConsumeConsumedPending 一次性读取并清除"确认后执行"放行标记。 确认直达执行会再走一次 dangerGuard:本次放行真实执行;之后同参数再调 必须重新确认,避免会话内免确认重放。
func (*Session) ConsumePending ¶
ConsumePending 校验并消费待确认调用(handler 确认路径调用)。
func (*Session) LastConfirm ¶
LastConfirm 取走最近确认请求(取即清空),三返回值满足 tools.SessionScope。
func (*Session) MarkConsumed ¶
MarkConsumed 由 handler 在 ConsumePending 成功后调用。
func (*Session) PendingSnapshot ¶
func (s *Session) PendingSnapshot() *PendingConfirm
PendingSnapshot 只读拷贝当前待确认调用(测试用)。
func (*Session) PermissionMode ¶ added in v1.25.0
PermissionMode 取本会话显式设过的权限模式;空串表示没设过。
func (*Session) SetLastConfirm ¶
SetLastConfirm 记录最近一次确认请求(装饰器据此发 tool_confirm 事件)。
func (*Session) SetPending ¶
SetPending 在会话上登记一次待确认调用(代理给 Session 的接口适配)。
func (*Session) SetPermissionMode ¶ added in v1.25.0
SetPermissionMode 记录本会话的工具权限模式(实现 tools.SessionScope)。
**会话级**:切档只影响本会话 —— 之前档位是**进程级单例**, 一个会话切成只读,会连带把**其他所有会话**的写操作都拒掉(跨会话 DoS)。
type SessionStore ¶
type SessionStore struct {
// contains filtered or unexported fields
}
SessionStore 内存会话存储。服务重启即失效(前端收到 404 后重开会话)。
func NewSessionStore ¶
func NewSessionStore(ttl time.Duration, maxRounds int) *SessionStore
func (*SessionStore) Append ¶
func (st *SessionStore) Append(s *Session, role, content string)
Append 追加消息并把会话压入活跃态;超过 maxRounds(×2 条)淘汰最旧轮次。
func (*SessionStore) Compact ¶ added in v1.17.0
func (st *SessionStore) Compact(s *Session, max int) int
Compact 会话历史压缩:超过 max 条时保留 system+最近 N 条, 中间插入压缩摘要占位,防止上下文无限膨胀。 借鉴 zcode compact:远古细节丢弃,近期事实保留。
func (*SessionStore) Create ¶
func (st *SessionStore) Create() *Session
func (*SessionStore) Get ¶
func (st *SessionStore) Get(id string) (*Session, error)
Get 取会话;不存在或超过 TTL 返回 ErrSessionNotFound(过期即删)。
func (*SessionStore) Snapshot ¶ added in v1.14.0
func (st *SessionStore) Snapshot(s *Session) []Message
Snapshot 返回会话消息的拷贝:构建模型输入用,避免与并发 Append 竞态。
func (*SessionStore) StartJanitor ¶ added in v1.14.0
func (st *SessionStore) StartJanitor(ctx context.Context, interval time.Duration)
StartJanitor 启动周期性过期回收:Get 只做惰性清理,再无人访问的会话 (如爬虫创建后即弃)靠 janitor 兜底,防止 map 只增不减。 loop 契约:单轮 panic 收编(循环存活)、忙时丢 tick;FirstDelay=interval 保持 旧 ticker 语义(首次清扫在 interval 后)。
type Settings ¶ added in v1.17.0
type Settings struct {
Enabled bool `json:"enabled"`
BaseURL string `json:"base_url"`
Model string `json:"model"`
Temperature float64 `json:"temperature"`
MaxTokens int `json:"max_tokens"`
TimeoutSeconds int `json:"timeout_seconds"`
MaxConcurrentChats int `json:"max_concurrent_chats"`
// APIKey 明文仅存于本文件;读接口永远只回 has_api_key / masked。
//nolint:gosec // G117:字段名 APIKey 命中密钥模式,此处确为密钥存储,不回传明文
APIKey string `json:"api_key,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
Settings 前端可改的 AI 配置(持久化到 data/ai-settings.json)。
func MergeSettings ¶ added in v1.17.0
MergeSettings yaml 默认值 + 设置文件覆盖(设置文件为准,空则回退 yaml)。
type SettingsStore ¶ added in v1.17.0
type SettingsStore struct {
// contains filtered or unexported fields
}
SettingsStore 文件型设置库(并发安全)。
func OpenSettings ¶ added in v1.17.0
func OpenSettings(path string) (*SettingsStore, error)
OpenSettings 打开设置库;不存在则返回空设置。
type SettingsView ¶ added in v1.17.0
type SettingsView struct {
Enabled bool `json:"enabled"`
BaseURL string `json:"base_url"`
Model string `json:"model"`
Temperature float64 `json:"temperature"`
MaxTokens int `json:"max_tokens"`
TimeoutSeconds int `json:"timeout_seconds"`
MaxConcurrentChats int `json:"max_concurrent_chats"`
HasAPIKey bool `json:"has_api_key"`
APIKeyMasked string `json:"api_key_masked"`
UpdatedAt string `json:"updated_at,omitempty"`
}
SettingsView 读接口视图(不泄密钥)。
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package memory 提供 AI 助手的持久记忆(借鉴 zcode memory extraction/recall)。
|
Package memory 提供 AI 助手的持久记忆(借鉴 zcode memory extraction/recall)。 |
|
Package tools 把 corebridge 能力包装为 eino 工具。
|
Package tools 把 corebridge 能力包装为 eino 工具。 |
|
toolstest
Package toolstest 提供跨包共用的测试基建:SyncService mock 与脚本化假模型。
|
Package toolstest 提供跨包共用的测试基建:SyncService mock 与脚本化假模型。 |