acp

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package acp 封装 coder/acp-go-sdk,实现桌面客户端侧的 ACP 客户端。

设计服从 AGENTS.md §1.2/§1.3:我们是 ACP client(调 NewClientSideConnection), harness(opencode acp)是 peer。Handler 实现 acp.Client 回调接口, Runner/ChatSession 管理 harness 子进程 + ACP 连接的完整生命周期。

生命周期(照搬 references/real-agent-kanban/internal/acp/runner.go):

spawn harness(独立进程组 Setpgid)→ NewClientSideConnection(handler, stdin, stdout)
→ Initialize → NewSession(cwd=项目目录) → Prompt(同步返回,期间 SessionUpdate 并发流入)
→ 判定 StopReasonEndTurn → kill 进程组 + 注销活跃 + reap 逃逸子进程

Index

Constants

View Source
const (
	// DefaultPermRetries:用户未响应时「重发提示」的默认额外次数(chat.go 装配时按设置
	// 调 SetPermissionRecovery,传入该默认值保持既有重发行为不变)。
	DefaultPermRetries = 1
)

权限回调恢复默认(§3.4 + Task #15115 + #73)。

View Source
const StopReasonEndTurn = acp.StopReasonEndTurn

StopReasonEndTurn 透传 SDK 常量:agent 自然完成一轮(internal/chat 据此判定 turn 是否正常结束)。

Variables

View Source
var ErrForkNotDeclared = errors.New("harness does not advertise sessionCapabilities.fork")

ErrForkNotDeclared:agent 未在 Initialize 响应里声明 sessionCapabilities.fork(UNSTABLE)。 #172 Phase2 铁律①:门控以声明位为准,未声明直接拒绝、不发 RPC —— 错误响应码不可假设 (探针实测:jcode 对强发 fork 曾回 -32603 而非主流的 -32601),错误响应仅作诊断。

Functions

func ActiveHarnessCount

func ActiveHarnessCount() int

ActiveHarnessCount 返回当前活跃 harness 数(供调用方判断是否安全 reap)。

func IsPeerDisconnected

func IsPeerDisconnected(err error) bool

IsPeerDisconnected 判断错误是否为 harness 进程崩溃/断开(§5.4 #2)。

Two equivalent signals, same root cause (harness process gone; must tear down connection and reconnect via Resume next time):

  • "peer disconnected":SDK 在 peer 消失时返回(§5.4 #2/#9/#11)。
  • "broken pipe":本地写已关闭的 harness stdin 管道失败的 OS 错误;SDK 经 toReqErr 包成 *RequestError{-32603,"Internal error",data:{error:"write |1: broken pipe"}} (见 acp-go-sdk errors.go),message 里只有 "Internal error",信号埋在 data, 旧实现只查 re.Message 故漏判 → 死 harness 不拆、session 卡死、裸 JSON 推前端。

err.Error() 已把 Message+Data marshal 成完整 JSON 字符串(RequestError.Error,同 SDK), 故一次大小写不敏感的子串匹配即可同时命中两类,不必拆字段。

func KillAllHarnesses

func KillAllHarnesses() int

KillAllHarnesses 杀掉「本应用上轮残留」的 harness 进程组(应用启动时调)。 与具体 harness 无关:以 pgidFile 登记的 pgid 为唯一真相(omp/opencode/... spawn 时都登记了), 对每个 tracked pgid 整组 kill -PGID 回收(§3.2)。仅当该 pgid 当前进程仍是受支持 harness 时才杀(isHarnessCmdline 安全过滤,防 pgid 被 OS 复用后误杀无关进程)。杀完清空 pgidFile(本轮重新登记)。

func ReapStrayHarnesses

func ReapStrayHarnesses() int

ReapStrayHarnesses 导出版(杀掉所有非活跃 harness)。多 session 时只能在 ActiveHarnessCount()==0 调。

func SetHarnessCommands

func SetHarnessCommands(cmds []string)

SetHarnessCommands 配置受支持 harness 的 ACP 启动命令(应用启动时调一次,传 harness.Supported 的 Command 列表)。进程回收据此识别本应用派生的 harness(omp/opencode/...),不再写死 opencode。

func SetPgidFile

func SetPgidFile(path string)

SetPgidFile 配置 pgid 持久化文件路径(应用启动时调一次,传 dataDir 下的文件)。

Types

type Attachment

type Attachment struct {
	Kind string `json:"kind,omitempty"`
	Name string `json:"name"`
	// Path:文件/目录路径(相对 session cwd 或绝对)。用于 ResourceLink 与 Resource 的 URI 兜底。
	Path string `json:"path,omitempty"`
	// Data:base64 编码的内联二进制数据。image/audio 的载体;resource 的 Blob 变体也用此字段。
	Data string `json:"data,omitempty"`
	// MimeType:Data/Text 的 MIME 类型(建议填写;image 默认 image/png,audio 默认 audio/wav)。
	MimeType string `json:"mimeType,omitempty"`
	// Text:resource 的内联文本内容(TextResourceContents 变体)。设置时优先于 Data。
	Text string `json:"text,omitempty"`
	// URI:resource 的标识 URI(可选)。空则按 Path(file:// 形式)或 Name(urn: 形式)兜底。
	URI string `json:"uri,omitempty"`
}

Attachment 是随 prompt 发给 agent 的引用(@提及 / 回形针文件 / 内联图片 / 音频 / 内联资源)。

Kind 决定发出的 ContentBlock 类型(baseline 之外的能力需 agent 声明对应 prompt 能力,§3.5):

  • "" / "file" → ContentBlock::ResourceLink(file:// URI,协议 baseline,所有 agent MUST support)
  • "image" → ContentBlock::Image(内联 base64,需 image 能力)
  • "audio" → ContentBlock::Audio(内联 base64,需 audio 能力)
  • "resource" → ContentBlock::Resource(内联文本/二进制,需 embeddedContext 能力)

兼容旧调用:Kind 空且 Data 非空时按 image 处理(buildPromptBlocks 兜底,历史粘贴图片路径)。 能力门控由前端依 SupportsImage/SupportsAudio/SupportsEmbeddedContext 决定,buildPromptBlocks 只管按 Kind 构造(与 image 既有行为一致:构造不门控,门控在调用方)。

type CapabilityMatrix

type CapabilityMatrix struct {
	HarnessID string    `json:"harnessId"`          // 关联 harness.Harness.ID(omp/opencode/...)
	ProbedAt  time.Time `json:"probedAt"`           // 探测完成时刻(缓存老化 / 「上次检测」展示用)
	ProbeErr  string    `json:"probeErr,omitempty"` // 探测失败的错误串(空 = 成功)

	// --- 协议声明位(来自 Initialize.AgentCapabilities)---
	PromptImage           bool `json:"promptImage"`           // ContentBlock::Image in prompts(promptCapabilities.image)
	PromptAudio           bool `json:"promptAudio"`           // ContentBlock::Audio in prompts(promptCapabilities.audio)
	PromptEmbeddedContext bool `json:"promptEmbeddedContext"` // ContentBlock::Resource in prompts(promptCapabilities.embeddedContext)
	LoadSession           bool `json:"loadSession"`           // session/load
	SessionList           bool `json:"sessionList"`           // session/list
	SessionClose          bool `json:"sessionClose"`          // session/close
	SessionResume         bool `json:"sessionResume"`         // session/resume
	SessionDelete         bool `json:"sessionDelete"`         // session/delete(UNSTABLE)
	SessionFork           bool `json:"sessionFork"`           // session/fork(UNSTABLE)
	AdditionalDirectories bool `json:"additionalDirectories"` // additionalDirectories(session lifecycle)
	McpAcp                bool `json:"mcpAcp"`                // McpServer::Acp(UNSTABLE)
	McpHttp               bool `json:"mcpHttp"`               // McpServer::Http
	McpSse                bool `json:"mcpSse"`                // McpServer::Sse

	// --- 模型选择位(来自 NewSession/LoadSession 响应的 ConfigOptions)---
	// 协议声明位只覆盖 Initialize;model/mode/thought_level 这三类「可下拉切换的 session config」
	// 只在 NewSession 响应里自报(SessionConfigOption,runner.go:85)。这是 issue 核心诉求:
	// 「有的 harness 没模型选择」——前端据此门控 model-select / mode / effort 入口的显隐。
	// 由 ProbeCapabilities 在 NewSession 成功后用 configBitsFromOptions 填充(零 token 成本)。
	ConfigModel  bool `json:"configModel"`  // 至少一个 category=model(或 id=model)的 Select option
	ConfigMode   bool `json:"configMode"`   // 至少一个 category=mode(或 id=mode)的 Select option
	ConfigEffort bool `json:"configEffort"` // 至少一个 category=thought_level 的 Select option(UI 称 effort)

	// --- 行为观测位(仅 withProbe=true 且 noop Prompt 成功时填)---
	EmitsUsage bool `json:"emitsUsage,omitempty"` // noop Prompt 期间至少收到一次 usage_update
	EmitsPlan  bool `json:"emitsPlan,omitempty"`  // noop Prompt 期间至少收到一次 plan / plan_update
}

CapabilityMatrix 捕获某 harness 经一次 ACP 探测得到的真实能力位。

字段分两组:

  • 协议声明位(Initialize.AgentCapabilities):prompt/session/mcp/loadSession 等硬能力, 由 matrixFromInit 从 initResp 抽取。所有位缺省 false(SDK UnmarshalJSON 已补默认)。
  • 行为观测位(可选,withProbe=true 时填):noop Prompt 期间是否真出现 usage_update / plan 事件。协议声明 ≠ 实际发送,此组字段用于「声明了但实际不发 / 没声明但实际发了」的兜底判断。

ProbeErr 非空表示探测失败(Initialize/NewSession 报错或 noop Prompt 报错);此时声明位可能 部分填充(Initialize 成功但 NewSession 失败时,声明位已有值)。前端可据此显示「上次检测失败」。

type ChatSession

type ChatSession struct {
	Runner    *Runner
	Conn      *acp.ClientSideConnection
	Handler   *Handler
	SessionID acp.SessionId
	WorkDir   string

	// CanListSessions:agent 是否声明了 session/list 能力(Initialize 响应的
	// capabilities.session.list)。协议硬约束:未声明时禁止调用 session/list
	// (session-list.mdx:Clients MUST verify this capability before calling)。
	CanListSessions bool

	// ConfigOptions:agent 在 NewSession/LoadSession 响应里自报的 session config options
	// (model/mode/effort)。set_config_option 返回时更新为最新全量。FlatConfigOptions 扁平化给前端。
	ConfigOptions []acp.SessionConfigOption
	// PromptCapabilities:agent 在 Initialize 响应里声明的 prompt 能力(image/audio/embedded)。
	// 用于能力门控:前端据此决定是否展示图片输入入口(image=false 时隐藏/禁用,§3.5)。
	PromptCapabilities acp.PromptCapabilities
	// contains filtered or unexported fields
}

ChatSession 保持 harness 进程 + ACP session 跨多轮对话。

func (*ChatSession) CanFork

func (cs *ChatSession) CanFork() bool

CanFork 报告 agent 是否声明了 sessionCapabilities.fork(铁律①门控位)。

func (*ChatSession) Close

func (cs *ChatSession) Close()

Close 销毁 session:kill 整个 harness 进程组 + 注销活跃(§3.2)。

func (*ChatSession) ElicitDeclined

func (cs *ChatSession) ElicitDeclined() bool

ElicitDeclined 报告本次 turn 期间用户是否主动 decline 过 elicitation(Skip)。 runPrompt 的 empty-turn 检测据此区分「用户主动跳过导致的空 turn」(静默)与「真异常空 turn」(提示)。

func (*ChatSession) FlatConfigOptions

func (cs *ChatSession) FlatConfigOptions() []ConfigOption

FlatConfigOptions 返回扁平化的 config options(给前端渲染下拉:model/mode/effort)。

func (*ChatSession) Fork

func (cs *ChatSession) Fork(ctx context.Context, mcps []store.McpServer) (ForkResult, error)

Fork 把当前 ACP session 复刻成一个新 session(harness 侧复制上下文,UNSTABLE 扩展)。

#172 Phase2 铁律②(同 cwd fork):cwd 恒传源 session 的 WorkDir(worktree 路径), 绝不新建 worktree / 改 baseRef —— 换 cwd fork 在 omp 是确定性错误(探针⑥),同 cwd 是 唯一普适语义。mcpServers 沿源:调用方传入源 session 落库的 MCP 选择,按 Initialize 协商的 mcp 能力过滤(与 NewChatSession/ResumeChatSession 同一转换,不受支持的传输丢弃并告警)。

fork 点恒为当前对话末尾(协议无位置参数);fork 后源与新 session 各自独立,并发使用 不在本层互斥(铁律③,omp 实测并发 prompt 有崩溃风险,由上层文档化)。

func (*ChatSession) IsAlive

func (cs *ChatSession) IsAlive() bool

IsAlive 报告 harness 进程是否仍存活(供「预热后空闲断连」检测:开 session 时 eager spawn 保持连接等首条消息,若用户迟迟不发、opencode 空闲断连 §5.4 #9,进程已退出 → 返回 false, 调用方据此拆掉死连接、下次重 spawn,避免把 broken pipe 抛给用户)。

func (*ChatSession) Prompt

func (cs *ChatSession) Prompt(ctx context.Context, message string, attachments []Attachment) (acp.StopReason, error)

Prompt 在已有 session 上发送消息并等待回复(同步返回,期间 SessionUpdate 并发流入)。 不设超时:对齐 omp TUI 的设计——turn 跑到自然结束(end_turn / error), 靠用户 Stop(走 ctx cancel)+ harness 崩溃检测(peer disconnected)兜底(§3.3)。 attachments(@提及的文件/目录)经 ACP ContentBlock::ResourceLink 发送(协议 baseline), agent 可直接按 file:// URI 访问;文本本身也照常作为 TextBlock 发出。

func (*ChatSession) RefreshConfig

func (cs *ChatSession) RefreshConfig(ctx context.Context) ([]ConfigOption, error)

RefreshConfig 重新拉取最新 configOptions + prompt capabilities(同步外部配置改动)。

用途:用户在 harness 自己的配置(如 opencode config)外部改动了 provider/model 列表 (加了新模型 / 新 provider),当前活跃 session 的 harness 进程是改动前 spawn 的,内存里 的 ConfigOptions 已过期。点「刷新」让模型下拉看到新选项。

ACP 协议没有「重新拉 configOptions」的标准方法(configOptions 只在 NewSession/LoadSession/ set_config_option 响应 + config_option_update 通知里出现)。唯一能拿到最新配置的路径是 新 spawn 一个 harness:新进程会读最新 harness 配置 → NewSession 响应带最新 configOptions。

实现为「probe harness」:用当前 session 的 cwd + 同一 harness 命令临时 spawn 一个独立 harness(独立进程组),Initialize + NewSession 拿到最新 configOptions,然后立即 CloseSession(清理 harness 持久化的 session 记录)+ kill 进程组回收。 probe 完全独立:不影响当前活跃连接、不中断进行中的对话流。

成功后覆盖 cs.ConfigOptions / cs.PromptCapabilities 为最新全量,返回扁平化结果。

func (*ChatSession) ResetElicitDeclined

func (cs *ChatSession) ResetElicitDeclined()

ResetElicitDeclined 清除 decline 标志(新 turn 开始时调,保证只反映当前 turn)。

func (*ChatSession) RespondElicitation

func (cs *ChatSession) RespondElicitation(id string, resp ElicitationResponse) bool

RespondElicitation 透传给 handler(前端用户响应 elicitation 提示,ACP v1 标准协议)。

func (*ChatSession) RespondPermission

func (cs *ChatSession) RespondPermission(id, optionID string) bool

RespondPermission 透传给 handler(前端用户裁决权限请求,§3.4)。

func (*ChatSession) SessionTitle

func (cs *ChatSession) SessionTitle(ctx context.Context) (string, error)

SessionTitle 通过 session/list 拉 harness 为本 session 生成的权威标题(§5.4 #14)。 协议硬约束:仅当 harness 在 Initialize 声明 session/list 能力时才可调用(session-list.mdx)。 与 session_info_update 推送正交:推送由 handleEvent 的 session_info 分支即时处理, 这里是主动拉取的兜底。返回空串 = harness 暂无标题或未声明该能力。

func (*ChatSession) SetConfigOption

func (cs *ChatSession) SetConfigOption(ctx context.Context, configId, value string) error

SetConfigOption 切换某个 config option(model/mode/effort),热切、同 session 即时生效。 成功后更新 cs.ConfigOptions 为 agent 返回的最新全量。configId 如 "model"/"mode"/"effort"。

func (*ChatSession) SetPermissionRules

func (cs *ChatSession) SetPermissionRules(rules []permissions.Rule)

SetPermissionRules 更新该 session 的分级权限规则快照(§3.4)。透传给 handler。

func (*ChatSession) SupportsAudio

func (cs *ChatSession) SupportsAudio() bool

SupportsAudio 报告 agent 是否声明了 audio prompt 能力(Initialize 响应的 promptCapabilities.audio)。前端据此门控音频输入入口:不支持则隐藏/禁用 + 提示。 协议:ContentBlock::Audio in prompts REQUIRES 'audio' prompt capability。

func (*ChatSession) SupportsEmbeddedContext

func (cs *ChatSession) SupportsEmbeddedContext() bool

SupportsEmbeddedContext 报告 agent 是否声明了 embeddedContext prompt 能力(Initialize 响应的 promptCapabilities.embeddedContext)。前端据此决定附件是否可内联(ContentBlock::Resource)发送 —— 内联可省去 agent 读盘往返,协议推荐优先(when available, ContentBlock::Resource is preferred)。 不支持时回退 ResourceLink(协议 baseline)。协议:ContentBlock::Resource REQUIRES 'embeddedContext'。

func (*ChatSession) SupportsImage

func (cs *ChatSession) SupportsImage() bool

SupportsImage 报告 agent 是否声明了 image prompt 能力(Initialize 响应的 promptCapabilities.image)。前端据此门控图片输入入口:不支持则隐藏/禁用 + 提示。 协议:ContentBlock::Image in prompts REQUIRES 'image' prompt capability。

type CheckResult

type CheckResult struct {
	Pass bool   `json:"pass"`
	Note string `json:"note,omitempty"` // 通过/失败的细节(失败时含简短原因)
}

CheckResult 单项检查结果。

type ConfigOption

type ConfigOption struct {
	ID           string              `json:"id"`
	Name         string              `json:"name"`
	Category     string              `json:"category"` // model | mode | thought_level
	CurrentValue string              `json:"currentValue"`
	Options      []ConfigOptionEntry `json:"options"`
}

ConfigOption 是给前端用的扁平化 session config option(从 acp.SessionConfigOption union 转换)。 agent 在 NewSession/LoadSession/set_config_option 响应、config_option_update 通知里返回 configOptions, 经 FlattenConfigOptions 拍平后推前端渲染下拉(model selector / mode / thought_level)。

func FlattenConfigOptions

func FlattenConfigOptions(opts []acp.SessionConfigOption) []ConfigOption

FlattenConfigOptions 把 SDK 的 configOption union(Select/Boolean)拍平为前端友好的 []ConfigOption。 只处理 Select(单值下拉,稳定);Boolean(unstable)暂忽略。Ungrouped/Grouped 都拍平成单层。

type ConfigOptionEntry

type ConfigOptionEntry struct {
	Value       string `json:"value"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

ConfigOptionEntry 一个可选项。model 的 value 是 "provider/model" 格式(如 "zai/glm-4.6"), 前端可按 value 的 provider 前缀分组显示。

type ConformanceReport

type ConformanceReport struct {
	Command     string `json:"command"` // 探测的启动命令(如 "junie acp")
	AgentName   string `json:"agentName"`
	ProtocolVer int    `json:"protocolVersion"`

	// Tier 1 硬门槛:任一不过 = CanAdd() 为假。
	Initialized CheckResult `json:"initialized"` // spawn + Initialize 返回合法 AgentCapabilities
	NewSession  CheckResult `json:"newSession"`  // 能在临时目录建 session
	Streamed    CheckResult `json:"streamed"`    // 至少流式吐出一条 agent_message_chunk(ACP 产出契约)

	// Tier 1 软:理想 end_turn,但流式产出即可证 ACP 健康(模型未配 key 会失败,非 conformance 问题)。
	PromptTurn CheckResult `json:"promptTurn"`

	// Tier 2 能力矩阵(Initialize 协商,永不阻断,决定可用功能)。
	LoadSession bool `json:"loadSession"` // session/load
	Resume      bool `json:"resume"`      // session/resume(无→恢复走 skip-setup)
	List        bool `json:"list"`        // session/list(无→session 标题降级)
	Close       bool `json:"close"`       // session/close
	Image       bool `json:"image"`       // promptCapabilities.image
	Audio       bool `json:"audio"`
	Providers   bool `json:"providers"` // UNSTABLE:provider 配置

	// 行为特征:哪条防御路径会生效(见 §5.4)。
	SawMessageChunk bool `json:"sawMessageChunk"`
	EmitsMessageId  bool `json:"emitsMessageId"` // 有 message/thought chunk 且携带 messageId

	// 功能覆盖(可选功能刻画;缺了只降级、不阻断,供体检单预警用户)。
	ConfigOptions    int  `json:"configOptions"`    // NewSession 返回的 configOption 数
	HasModelOption   bool `json:"hasModelOption"`   // 有 category:"model" 的 configOption(无→会话中不能切模型)
	ReportedUsage    bool `json:"reportedUsage"`    // 发 usage_update 或 Usage 非空(无→不显示 token/成本)
	StreamedThoughts bool `json:"streamedThoughts"` // 发 agent_thought_chunk(无→看不到 reasoning)
	UsedTools        bool `json:"usedTools"`        // 发 tool_call(无害 prompt 下未必触发)
	// Tier 2 behavioral probes (non-blocking; characterize client→agent RPC conformance).
	ResumeReplays  bool `json:"resumeReplays"`  // session/resume replayed history (violates session-resume.mdx MUST NOT replay)
	CancelHonored  bool `json:"cancelHonored"`  // harness replied stopReason=cancelled after session/cancel
	SetConfigWorks bool `json:"setConfigWorks"` // session/set_config_option round-trip returned full state

	// Fork UNSTABLE session/fork 探针(issue #172 Phase 1;Tier2 永不阻断 CanAdd)。
	Fork ForkReport `json:"fork"`

	// ObservedKinds 本次 Prompt 期间观察到的事件 kind 集合(诊断用)。
	ObservedKinds []string `json:"observedKinds,omitempty"`

	// Error 探针自身失败(spawn 起不来 / Initialize 崩溃等),非 conformance 判定。
	Error string `json:"error,omitempty"`
}

ConformanceReport ProbeHarness 的产出:harness 的 ACP 健康体检单。

func ProbeHarness

func ProbeHarness(ctx context.Context, command string) *ConformanceReport

ProbeHarness 对 command 指定的 ACP harness 跑一次受控 conformance 探针。

流程:临时目录隔离 → spawn+Initialize(抓能力矩阵)→ NewSession → Prompt(无害消息, 收集事件 kind 与 messageId)→ 干净 teardown(进程组回收)。

返回 *ConformanceReport(永远非 nil,哪怕探针自身出错也会回填 Error);CanAdd() 判定可否添加。

func (ConformanceReport) CanAdd

func (r ConformanceReport) CanAdd() bool

CanAdd 严格门槛:Tier1 全过(Initialized + NewSession + Streamed + PromptTurn=end_turn)。 要求完整跑完一轮(end_turn):不仅证 ACP 健康,还证该 harness 在当前环境真能干活 (模型/key/网络就绪)。能力矩阵缺失只降级、不阻断。

func (ConformanceReport) Summary

func (r ConformanceReport) Summary() string

Summary 人话体检单(供日志展示;前端按 JSON 字段自渲染)。

type ElicitationField

type ElicitationField struct {
	Name        string   `json:"name"`                  // property key(omp 固定 "value")
	Type        string   `json:"type"`                  // string | boolean(ACP schema 限定 primitive)
	Title       string   `json:"title,omitempty"`       // 字段标题(可选)
	Description string   `json:"description,omitempty"` // 字段说明(可选,omp input 用 description 当 placeholder)
	Enum        []string `json:"enum,omitempty"`        // string 的枚举(select 下拉)
	Default     string   `json:"default,omitempty"`     // 默认值(string 时)
	Required    bool     `json:"required,omitempty"`
}

ElicitationField 一个表单字段(从 JSON Schema property 扁平化)。 前端按 Type 渲染:string→input、string+Enum→select、boolean→checkbox/confirm。

type ElicitationPrompt

type ElicitationPrompt struct {
	ID        string             `json:"id"`
	SessionID string             `json:"sessionId"`
	Message   string             `json:"message"` // harness 给的人话提示(如 "Review Mode")
	Fields    []ElicitationField `json:"fields"`  // 表单字段(omp 单字段 "value")
}

ElicitationPrompt 是发给前端的 elicitation 请求(扁平化,JSON 友好)。

type ElicitationResponse

type ElicitationResponse struct {
	Action  string         `json:"action"`            // accept | decline | cancel
	Content map[string]any `json:"content,omitempty"` // accept 时:字段名 → 值(omp 约定单字段 "value")
}

ElicitationResponse 是前端对一次 elicitation 提示的响应。

type ForkReport

type ForkReport struct {
	// Declared Initialize 响应 SessionCapabilities.Fork 非 nil(P1 声明矩阵行)。
	Declared bool `json:"declared"`

	// Force undeclared 时的强 fork 取证串:"forced-fork: <code> <message>";
	// declared 或探针未跑到(NewSession 失败等)时为空。
	Force string `json:"force,omitempty"`
	// ForceClass 强 fork 结果分类:method-not-found / invalid-params / other /
	// no-answer(无 JSON-RPC 错误响应,如超时/断连)/
	// unexpected-success(未声明却 fork 成功 —— 声明与实现不一致,本身是发现)。
	ForceClass string `json:"forceClass,omitempty"`

	// P3 declared 往返逐项(六问 ①-⑥ + 扩展 ⑦⑧)。
	NewID       CheckResult `json:"newId"`       // ① 新 sessionId ≠ 源
	SourceAlive CheckResult `json:"sourceAlive"` // ② fork 后源 session 仍可 prompt(最小提示词)
	InList      CheckResult `json:"inList"`      // ③ session/list 含新 id
	Resumable   CheckResult `json:"resumable"`   // ④ 新 id 可 load/resume
	Echo        CheckResult `json:"echo"`        // ⑤ fork 响应 configOptions/modes 回显与源一致
	Cwd         CheckResult `json:"cwd"`         // ⑥ 同 cwd vs 新 cwd fork 行为差异记录
	Chain       CheckResult `json:"chain"`       // ⑦ fork 链(对 fork 结果再 fork)
	Concurrent  CheckResult `json:"concurrent"`  // ⑧ 源/fork 并发各一发 prompt 互扰观察

	// Busy-fork 四项实测(issue #191):源 turn 进行中 fork 的行为。
	// 任何一项失败都是「停在探针」的判据(实现卡 #28965 的硬前置门)。
	BusyFork    CheckResult `json:"busyFork"`    // ① 源 turn 进行中 fork RPC 成功(新 id ≠ 源)
	BusySnap    CheckResult `json:"busySnap"`    // ② fork 上下文快照点(load/resume 回放观察,如实记录)
	BusySrcOK   CheckResult `json:"busySrcOk"`   // ③ 源 turn 不受干扰(end_turn + fork 后流式延续)
	BusyForkUse CheckResult `json:"busyForkUse"` // ④ fork 后串行 prompt fork 行可用(end_turn)

	// Error fork 探针自身异常(panic 兜底等);空 = 正常收敛出报告。
	Error string `json:"error,omitempty"`
}

ForkReport UNSTABLE session/fork 探针结果(issue #172 Phase 1)。

三段产出:P1 声明位(Declared)+ P2 undeclared 强 fork 错误码锚定(Force/ForceClass) + P3 declared 最小往返取证(①-⑧:六问 + fork 链 + 并发两个扩展)。 每项独立 CheckResult;不适用/前置失败也必须落行(Note 标 "N/A: 原因"),绝不静默省略。

type ForkResult

type ForkResult struct {
	NewSessionID  string
	ConfigOptions []ConfigOption
}

ForkResult 是 session/fork 的消费面结果:新 ACP session id + fork 响应自报的 configOptions。 ConfigOptions 已按既有管线拍平(FlattenConfigOptions),业务包零 SDK 类型依赖(§2.1); 与 NewSession/LoadSession 的消费管线完全同一套表示。响应的 Modes 无既有消费者 (与 ResumeSessionResponse.Modes 同样被忽略),不透出。

type Handler

type Handler struct {
	Log     *slog.Logger
	WorkDir string
	OnEvent func(SessionEvent) // 每条 SessionUpdate 转发(→ service → Wails3 event → 前端)

	// 权限裁决(§3.4):harness 请求权限时,通过 OnPermission 通知前端弹窗,
	// 用户在前端响应 → service 调 RespondPermission → 唤醒等待的 RequestPermission。
	OnPermission func(PermissionPrompt)
	// Elicitation(ACP v1 标准协议,SDK 标 UNSTABLE):harness 请求结构化用户输入
	// (select/confirm/input/多字段 form)时,通过 OnElicitation 通知前端弹窗,用户在前端
	// 响应 → service 调 RespondElicitation → 唤醒等待的 UnstableCreateElicitation。
	// 场景:omp /review 选 review 模式、/fast on|off 确认 等(类比 §3.4 权限裁决,桌面有人在场)。
	OnElicitation func(ElicitationPrompt)
	// OnElicitationResolved:当一次 elicitation 在「无用户操作」下被终结(超时降级 decline /
	// ctx 取消 cancel)时回调 service,由 service 推 chat:elicitation-resolved 让前端清掉残留
	// 卡片(否则卡片最多残留 permTTL=5min,期间点击后端报 no pending,前端无反馈)。
	// 用户正常响应(RespondElicitation)不触发本回调 —— 前端已乐观清卡。
	OnElicitationResolved func(id string)
	// OnElicitationUnrenderable(#158):elicitation form 扁平化后无可渲染字段
	// (fields==0)时,handler 直接 Decline 给 harness;本回调让 service 向该 session
	// 前端推一条可见 notice(chat.notice.* i18n),否则用户只看到命令静默空转、
	// 不知发生了什么。nil = 不通知(handler 单测默认)。
	OnElicitationUnrenderable func()
	// OnGlobalRule:用户选「全局允许」(RespondPermission 传 "global")时回调 service,
	// 把由当前请求固化出的「准确匹配」allow 规则(permissions.ExactMatchRule)交由 service
	// 持久化进 DB + 刷新全部活跃 session 的规则快照(跨 session/project 全局生效,§3.4)。
	// nil = 不持久化(handler 单测默认 nil,只验内存记忆 + 规则形状)。
	OnGlobalRule func(permissions.Rule)
	// OnCommandsCache(#152):harness 每次上报 available_commands_update 时回调 service,
	// 把拍平的 []SlashCommand 全表持久化进 DB(sessions.commands_cache),供只读态(懒 spawn
	// 未活跃)渲染 slash 菜单。整表替换语义:空表也是合法写(harness 清空命令)。写点在 handler
	// 直落 service,不经前端回写 —— 避免「事件到前端→前端再调 binding」的双写/竞态。
	// nil = 不持久化(handler 单测默认 nil)。
	OnCommandsCache func(sessionID string, cmds []SlashCommand)
	// contains filtered or unexported fields
}

Handler 实现 acp.Client 接口。一个 Handler 对应一个 ChatSession 的一个 ACP session。

func NewHandler

func NewHandler(workDir string, onEvent func(SessionEvent), onPermission func(PermissionPrompt), onElicitation func(ElicitationPrompt), permTTL time.Duration) *Handler

NewHandler 构造一个 Handler。permTTL=0 时用默认 5 分钟。

func (*Handler) CreateTerminal

func (*Handler) EmitTurnUsage

func (h *Handler) EmitTurnUsage(sessionID string, u *acp.Usage)

EmitTurnUsage 在 Prompt 同步返回后转发 PromptResponse.Usage 的 token 明细(§1.6/Task #15138)。 streaming UsageUpdate 只含 used/size/cost,明细(CachedRead/Write/Input/Output/Thought/Total) 只能从 Prompt 响应取;此处携带最近一次 streaming 的 used/size/cost,避免前端用 0 覆盖既有占比。 调用方:ChatSession.Prompt(resp.Usage 非 nil 时)。并发安全。

func (*Handler) KillTerminal

func (*Handler) ReadTextFile

func (*Handler) ReleaseTerminal

func (*Handler) RequestPermission

func (*Handler) RespondElicitation

func (h *Handler) RespondElicitation(id string, resp ElicitationResponse) bool

RespondElicitation 由 service 调(前端用户对 elicitation 提示做了选择)。非阻塞; 返回 ok=false 表示无此待响应项(已被取消/超时/响应过)。action 见 ElicitationResponse。

func (*Handler) RespondPermission

func (h *Handler) RespondPermission(id, optionID string) bool

RespondPermission 由 service 调(前端用户点了某个选项)。非阻塞;返回 ok=false 表示无此待裁决项。

func (*Handler) SessionUpdate

func (h *Handler) SessionUpdate(ctx context.Context, n acp.SessionNotification) error

func (*Handler) SetCommandsCache

func (h *Handler) SetCommandsCache(cb func(sessionID string, cmds []SlashCommand))

SetCommandsCache sets the slash-command-table persistence callback (#152). Service assigns it during session setup; mu-guarded write stays race-free with emitCommandsCache's read-side snapshot (same rationale as SetGlobalRule).

func (*Handler) SetElicitationResolved

func (h *Handler) SetElicitationResolved(cb func(string))

SetElicitationResolved sets the elicitation-resolved notify callback. Same race rationale as SetGlobalRule: assigned after the ACP reader goroutine starts; mu synchronizes the read in notifyElicitationResolved.

func (*Handler) SetElicitationUnrenderable

func (h *Handler) SetElicitationUnrenderable(cb func())

SetElicitationUnrenderable sets the unrenderable-form notice callback (#158). Same race rationale as SetElicitationResolved: assigned after the ACP reader goroutine starts; mu synchronizes the read in notifyElicitationUnrenderable.

func (*Handler) SetGlobalRule

func (h *Handler) SetGlobalRule(cb func(permissions.Rule))

SetGlobalRule sets the "allow-global" rule-persistence callback (§3.4). Service assigns it during session setup, after the ACP reader goroutine has started; the mu-guarded write stays race-free with emitGlobalRule's read.

func (*Handler) SetPermissionRecovery

func (h *Handler) SetPermissionRecovery(retries int, timeoutPolicy string)

SetPermissionRecovery 配置权限回调失败恢复策略(Task #15115)。 retries<0 视作 0;timeoutPolicy 为 "allow"/"deny";空串/未知视作 allow(与零值语义一致), chat 装配层负责归一(normalizePermTimeoutPolicy)。 并发安全:仅在 session 启动 / 配置变更时调用,不在 RequestPermission 热路径中写。

func (*Handler) SetPermissionRules

func (h *Handler) SetPermissionRules(rules []permissions.Rule)

SetPermissionRules 更新分级权限规则引擎快照(§3.4)。service 在 session 启动 / 规则变更时调用。 传入 nil / 空切片 = 清除规则(RequestPermission 一律走弹窗)。并发安全:atomic.Pointer 替换。

func (*Handler) SetProjectAllowExternal

func (h *Handler) SetProjectAllowExternal(allow bool)

SetProjectAllowExternal 由 service 在 session 启动时调用,把项目级记忆(DB)加载进 handler, 使「本项目曾允许外部目录」的 session 命中即自动放行。

func (*Handler) TerminalOutput

func (*Handler) UnstableCreateElicitation

UnstableCreateElicitation 实现 acp.Client 回调:agent 请求结构化用户输入。 form → 扁平化推前端等响应(带超时兜底);url → 暂不支持,decline。

func (*Handler) WriteTextFile

type PermissionOption

type PermissionOption struct {
	OptionID string `json:"optionId"`
	Name     string `json:"name"`
	Kind     string `json:"kind"` // allow_once | allow_always | deny_once | deny_always
}

PermissionOption 一个可选项。

type PermissionPrompt

type PermissionPrompt struct {
	ID         string             `json:"id"`
	SessionID  string             `json:"sessionId"`
	ToolName   string             `json:"toolName"`
	Title      string             `json:"title"`
	ActionType string             `json:"actionType,omitempty"` // read/write/exec/other(由 ToolKind 派生)
	Command    string             `json:"command,omitempty"`    // 抽取的命令(exec 类,来自 RawInput)
	Locations  []string           `json:"locations,omitempty"`  // 涉及路径(ToolCall.Locations)
	Options    []PermissionOption `json:"options"`
}

PermissionPrompt 是发给前端的权限裁决请求(AGENTS.md §3.4)。 除标题/工具名外,携带决策上下文(动作分组、命令、涉及路径),让用户明确 「哪个工具/动作/目标、需决策什么、可选什么」,避免泛泛确认(§4.4)。

type PlanEntry

type PlanEntry struct {
	Content  string `json:"content"`            // 任务描述
	Priority string `json:"priority,omitempty"` // high | medium | low
	Status   string `json:"status"`             // pending | in_progress | completed
}

PlanEntry 是 agent 执行计划的一项(ACP PlanEntry 的扁平化)。 整表替换模型:harness 每次 plan_update 发全量列表,client 直接替换。

type PromptErrorClass

type PromptErrorClass string

PromptErrorClass is the classification of a Prompt failure. The class drives the handling policy in internal/chat (teardown/reconnect vs keep-alive, auto-retry vs report immediately).

const (
	// PromptErrPeerDisconnected: harness process crashed / transport broken.
	// Must tear down and reconnect (existing §3.3 semantics).
	PromptErrPeerDisconnected PromptErrorClass = "peer_disconnected"
	// PromptErrQuotaExhausted: provider usage/quota limit exhausted. The
	// connection is healthy; respawning cannot restore quota. Not retryable
	// client-side (reset is typically hours away).
	PromptErrQuotaExhausted PromptErrorClass = "quota_exhausted"
	// PromptErrTransient: transient provider/network failure (429/5xx/timeout/
	// connection blips) — a bounded client-side auto-retry is worthwhile.
	PromptErrTransient PromptErrorClass = "transient"
	// PromptErrFatal: everything else. Unknown semantics: keep the existing
	// conservative teardown+reconnect handling.
	PromptErrFatal PromptErrorClass = "fatal"
)

type PromptErrorInfo

type PromptErrorInfo struct {
	// Class is the classification result (never empty for a non-nil error).
	Class PromptErrorClass
	// RootCause is the human-readable core of the error with protocol wrapping
	// stripped (e.g. the raw provider quota message, or the embedded OS error
	// for locally-wrapped transport failures). Intended for UI display (§4.4);
	// never a raw JSON blob when a better text exists.
	RootCause string
	// ResetAt is the provider-side quota reset time as raw text (provider local
	// time, e.g. "2026-08-26 16:32:32"), extracted from the message when
	// present. Passed through verbatim to avoid timezone misinterpretation —
	// the provider text is already what the user should see. Empty when absent.
	ResetAt string
	// Retryable reports whether a bounded client-side auto-retry is worthwhile
	// (true only for PromptErrTransient).
	Retryable bool
}

PromptErrorInfo is the diagnosis of one Prompt error.

func DiagnosePromptError

func DiagnosePromptError(err error) PromptErrorInfo

DiagnosePromptError classifies a Prompt error and extracts its root cause. Pure function (no I/O) — unit-testable without a real harness (§5.1). Classification order: peer-disconnected (established transport signal) → quota (provider-limit anchors) → transient (retryable anchors) → fatal. nil maps to PromptErrFatal so callers can classify unconditionally.

type Runner

type Runner struct {
	HarnessCmd []string // 启动命令,如 ["opencode","acp"]
	Env        []string // 额外环境变量
}

Runner 驱动单个 harness(其 stdio ACP server)。model 不在 spawn 注入: 统一走 ACP session config option(category=model)+ session/set_config_option。

func NewRunner

func NewRunner(command string, env map[string]string) *Runner

NewRunner 构造 Runner。command 默认 "opencode acp"。

func (*Runner) NewChatSession

func (r *Runner) NewChatSession(ctx context.Context, workDir string, mcps []store.McpServer, onEvent func(SessionEvent), onPermission func(PermissionPrompt), onElicitation func(ElicitationPrompt)) (*ChatSession, error)

NewChatSession 创建持久对话 session:spawn harness → initialize → newSession(cwd=workDir)。 onEvent 接收每条扁平化的 SessionUpdate(→ 前端流式渲染); onPermission 接收权限裁决提示(→ 前端弹窗,§3.4); onElicitation 接收 elicitation 提示(→ 前端弹窗,ACP v1 标准协议)。调用方负责 Close()。

mcps 是该 session 选中的 MCP server(catalog 子集);按 Initialize 协商的 mcpCapability 转成 ACP 线格式注入 session/new。stdio 免协商,http/sse 不被支持则丢弃并告警。严格 harness (如 OMP)任一 server 连接失败会让 NewSession 整个失败——上层据此在 NewSessionModal 原样展示 报错,用户取消勾选可疑 server 后重试(本次不选,catalog 不动)。

func (*Runner) ProbeCapabilities

func (r *Runner) ProbeCapabilities(ctx context.Context, harnessID, workDir string, withProbe bool) (CapabilityMatrix, error)

ProbeCapabilities spawn 一个独立 harness 进程做一次能力探测(纯 ACP,§1.1)。

流程:spawn harness(独立进程组,§3.2)→ Initialize(拿 AgentCapabilities 声明的能力位) → NewSession(验证 harness 真能建 session;协议要求 cwd 存在)→ 可选地发 noop Prompt 观察实际事件流(usage_update / plan)→ CloseSession + kill 进程组回收。

完全独立:不影响任何活跃 session(独立连接、独立 handler)。失败时 proc.shutdown 幂等 回收进程组(§3.2),不残留孤儿。

withProbe=false(默认推荐):只做 Initialize + NewSession,零 token 成本,覆盖绝大多数能力位。 withProbe=true:额外发 noop Prompt("ping"),观察 SessionUpdate 流。会消耗少量 token, 且观测结果依赖 agent 当次行为(声明了未必发),默认关闭——前端如需「实际事件流」观测应 在真实对话里统计,而非 probe。

workDir 必须存在(spawnAndInit 设 cmd.Dir;NewSession 的 cwd 也填它),用 t.TempDir() 或 应用缓存目录下的稳定 probe 目录。返回 (矩阵, error):error 非 nil 时矩阵仍带已取得的声明位 + ProbeErr 串,调用方可读 ProbeErr 展示「上次检测失败」或只看 error。

func (*Runner) ResumeChatSession

func (r *Runner) ResumeChatSession(ctx context.Context, workDir, sessionID string, mcps []store.McpServer, onEvent func(SessionEvent), onPermission func(PermissionPrompt), onElicitation func(ElicitationPrompt)) (*ChatSession, error)

ResumeChatSession resumes an existing session: spawn harness → initialize → session/resume (§1.4). Used to restore conversation context after app restart (Cwd must match the original session).

type SessionEvent

type SessionEvent struct {
	SessionID string `json:"sessionId"`
	Kind      string `json:"kind"`                // agent_message_chunk | agent_thought_chunk | tool_call | tool_call_update | usage_update | plan | session_info | config_option
	Text      string `json:"text"`                // chunk 文本(message/thought);agent/thought 为累积全文
	Seq       int64  `json:"seq,omitempty"`       // 单调序号(防流式乱序,§4.3)
	MessageID string `json:"messageId,omitempty"` // ACP messageId:同一条逻辑消息的所有 chunk 共享(§5.4 #11),主键归并用
	// RotateOnce (#79): set by ResumeChatSession on the FIRST no-messageId
	// agent_message_chunk after session/resume returns. The fallback merge (backend
	// messageKey + frontend streamMerge) consumes it to force a fresh block instead of
	// appending into a pre-resume bubble (junie-style penetrating replay tail / DB tail).
	// Exactly one event per resume carries it; all other chunks are untouched.
	RotateOnce bool `json:"rotateOnce,omitempty"`
	// TurnID 标识事件所属的 turn(= 开启该 turn 的 user message ID,由 client 生成;
	// 协议无 turnId 字段,见 docs/worklog/2026-07-22-plan-history-by-turn.md)。
	// 目前仅 plan 事件携带:plan 按 turn 索引,当前 turn 实时 / 历史 turn 静态展示。
	TurnID string `json:"turnId,omitempty"`

	ToolCallID string `json:"toolCallId,omitempty"`
	ToolTitle  string `json:"toolTitle,omitempty"`
	ToolStatus string `json:"toolStatus,omitempty"`
	ToolKind   string `json:"toolKind,omitempty"`
	RawInput   any    `json:"rawInput,omitempty"`
	RawOutput  any    `json:"rawOutput,omitempty"`

	Used int64    `json:"used,omitempty"` // context tokens 已用
	Size int64    `json:"size,omitempty"` // context window 总量
	Cost *float64 `json:"cost,omitempty"` // 累积成本 USD
	// token 明细(来自 PromptResponse.Usage,UNSTABLE;§1.6/Task #15138)。
	// streaming UsageUpdate 只含 used/size/cost,明细只能从 Prompt 响应取。
	// 这些字段已是 session 级累积值(SDK:Total X tokens across all turns),直接覆盖即可。
	CachedReadTokens  int64          `json:"cachedReadTokens,omitempty"`
	CachedWriteTokens int64          `json:"cachedWriteTokens,omitempty"`
	InputTokens       int64          `json:"inputTokens,omitempty"`
	OutputTokens      int64          `json:"outputTokens,omitempty"`
	ThoughtTokens     int64          `json:"thoughtTokens,omitempty"`
	TotalTokens       int64          `json:"totalTokens,omitempty"`
	Title             string         `json:"title,omitempty"`         // session_info 标题
	ConfigOptions     []ConfigOption `json:"configOptions,omitempty"` // config_option:model/mode/effort 等(agent 自报)
	PlanEntries       []PlanEntry    `json:"planEntries,omitempty"`   // plan:agent 执行计划(整表替换,ACP protocol)
	Commands          []SlashCommand `json:"commands,omitempty"`      // available_commands:harness 自报的斜杠命令(动态,非硬编码;§1.6)
	// ImageSupported:agent 是否支持 image prompt 能力(Initialize 响应 promptCapabilities.image)。
	// 随 config_option 事件下发,前端据此门控图片输入入口(不支持则隐藏/禁用,§3.5)。
	ImageSupported bool `json:"imageSupported,omitempty"`
	// AudioSupported:agent 是否支持 audio prompt 能力。前端据此门控音频输入入口。
	AudioSupported bool `json:"audioSupported,omitempty"`
	// EmbeddedContextSupported:agent 是否支持 embeddedContext prompt 能力。
	// 前端据此决定附件是否可内联(ContentBlock::Resource)发送(省去 agent 读盘往返)。
	EmbeddedContextSupported bool `json:"embeddedContextSupported,omitempty"`
}

SessionEvent 是给前端用的「扁平化 SessionUpdate」(AGENTS.md §1.6/§4.3)。 agent 的全部产出——消息、思考、工具调用、用量——都从 SessionUpdate 回调流入, 这里转成 JSON 友好的结构,由 service 层经 Wails3 event 推前端流式渲染。

type SlashCommand

type SlashCommand struct {
	Name        string `json:"name"`                // command name WITHOUT leading "/" (e.g. "model")
	Description string `json:"description"`         // human-readable summary
	InputHint   string `json:"inputHint,omitempty"` // argument hint (ACP AvailableCommandInput.hint)
}

SlashCommand is a harness-advertised slash command (ACP available_commands_update). Per protocol: commands are invoked by sending the command text (e.g. "/model list") as a regular user message in session/prompt; the harness recognizes the "/" prefix. Name carries NO leading "/". InputHint is the argument hint (may be empty). Each harness advertises a different, dynamic list (not hardcoded); this is only the flattened wire shape forwarded to the frontend.

type StopReason

type StopReason = acp.StopReason

StopReason 透传 SDK 的 StopReason,供 internal/chat 等业务包引用 (§2.1:internal/acp 是 ACP 唯一封装层,业务包不直接 import SDK)。

Jump to

Keyboard shortcuts

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