深入解析 Macro Agent Harness 的 DiscoverAgentCapabilitiesResponse:一次请求读懂 ACP 会话配置
深入解析 Macro Agent Harness 的 DiscoverAgentCapabilitiesResponse:一次请求读懂 ACP 会话配置
在 Macro 的 Agent Harness 服务中,不同类型的 Agent 后端(内置 in-memory 引擎、用户自己的 Cursor 账号、以及本地配对的 macrod 运行时)会各自声明不同的会话配置项,例如可选模型、推理强度、速度档位。DiscoverAgentCapabilitiesResponse 就是这条"能力发现"链路的统一返回类型:它把各家 Agent 通过 ACP(Agent Client Protocol)声明的 configOptions 归一化成一份有序、稳定、可直接被前端渲染的配置清单。本文以该类型文档为骨架,结合仓库中的 Rust 服务端实现与 TypeScript SDK 产物,讲清楚这份响应的字段语义、请求约束、错误映射与实战调用方式。
类型定义速览
原文档给出的定义非常克制:
type DiscoverAgentCapabilitiesResponse = {
configOptions: AgentConfigOptionDto[];
};
语义是"Successful capability-discovery response",即一次成功的能力发现结果。它只有一个字段:
| Property | Type | Description |
|---|---|---|
configOptions |
AgentConfigOptionDto[] |
Complete ordered ACP session configuration advertised by the agent. |
关键在两点:complete(全量快照,而非增量补丁)与 ordered(顺序由 Agent 提供方决定,客户端不应重排)。Rust 侧的对应定义位于 crates/agent_harness/src/inbound/capability_discovery.rs:
/// Successful capability-discovery response.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DiscoverAgentCapabilitiesResponse {
/// Complete ordered ACP session configuration advertised by the agent.
pub config_options: Vec<AgentConfigOptionDto>,
}
impl From<AgentCapabilities> for DiscoverAgentCapabilitiesResponse { /* ... */ }
#<a href="https://link.gitcode.com/i/8a6dd179f1650b51154801c625f765e9" target="_blank">serde(rename_all = "camelCase")] 解释了为什么 JSON 里是 configOptions 而不是 config_options;TypeScript 生成物 [packages/sdk/generated/agent-harness/types.gen.ts 与该序列化结果一一对应。
为什么需要"能力发现",而不是静态能力表
不同 Agent 后端的可配置项并不一致,而且同一后端的不同模型也可能暴露不同选项。例如内置引擎在某个模型上支持推理强度、在另一个模型上不支持;Cursor 的推理参数只在特定模型变体上出现。仓库中的架构说明 docs/architecture/agent-effort.md 明确写道:UI 读取 ACP configOptions,按 thought_level 类别(历史 id 回退为 reasoning_effort)识别推理强度,并且外部 id 与取值一律视为不透明值。
因此 DiscoverAgentCapabilitiesResponse 的设计目标不是"告诉客户端有哪些开关",而是在真正创建或复用会话之前,向具体后端询问它此刻声明的完整配置,并且不持久化任何会话——这一点在路由注释里写得很直白:"Probe one provider's ACP session configuration without persisting a session."(见 crates/agent_harness/src/inbound/capability_discovery.rs)。
请求形状:configOptions 的前提条件
响应结构简单,但它依赖的请求参数决定了你能拿到什么。同一文件中的请求类型如下:
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DiscoverAgentCapabilitiesRequest {
/// Provider to probe.
pub harness: CapabilityHarnessDto,
/// Required for macrod and forbidden for other targets.
pub harness_id: Option<Uuid>,
/// Model whose session settings should be inspected.
pub model: Option<String>,
}
对应到 JSON 就是三个字段:
| 字段 | 必填性 | 取值 | 作用 |
|---|---|---|---|
harness |
必填 | in-memory | cursor | macrod |
指定要探测的后端 |
harnessId |
仅 macrod 必填,其余目标禁止传入 |
UUID 字符串 | 定位某个已配对的 macrod 运行时 |
model |
可选 | 模型 id 字符串 | 按指定模型检视会话设置(预检覆盖) |
harness 的枚举值来自 CapabilityHarnessDto,序列化策略是 kebab-case,所以字面量是 in-memory,而不是 inMemory:
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "kebab-case")]
pub enum CapabilityHarnessDto {
InMemory,
Cursor,
Macrod,
}
而 harnessId 的规则并非文档性建议,而是硬校验。领域服务 AgentCapabilitiesServiceImpl::load 用模式匹配把三种合法组合与两类非法组合分开(crates/agent_harness/src/domain/capability_discovery.rs):
match (request.harness, request.harness_id) {
(CapabilityHarness::InMemory, None) => { /* probe in_memory with caller */ }
(CapabilityHarness::Cursor, None) => { /* probe cursor with caller */ }
(CapabilityHarness::Macrod, Some(harness)) => { /* 先鉴权,再探测 */ }
(CapabilityHarness::Macrod, None) => Err(/* "harnessId is required for macrod" */),
(_, Some(_)) => Err(/* "harnessId is only valid for macrod" */),
}
非法组合返回 500 之外的业务错误:DiscoverAgentCapabilitiesError::BadRequest,HTTP 层映射为 400 Invalid target。测试 invalid_targets_are_rejected_without_probing 还额外断言了这几种非法组合不会触发任何下游探测(crates/agent_harness/src/domain/capability_discovery/test.rs)。
逐层拆解 configOptions 的元素结构
configOptions 的每一项是 AgentConfigOptionDto,它是一个"公共字段 + 类型特化字段"的扁平结构:
type AgentConfigOptionDto = AgentConfigKindDto & {
id: string;
name: string;
description?: string | null;
category?: string | null;
};
type AgentConfigKindDto =
| { type: 'select'; currentValue: string; options: AgentConfigSelectOptionDto[] }
| { type: 'boolean'; currentValue: boolean };
AgentConfigOptionDto 的四个公共字段
| 字段 | 类型 | 语义 | 使用注意 |
|---|---|---|---|
id |
string |
用于修改该设置的不透明 id | 应原样回传,不要自行拼接或解析 |
name |
string |
Agent 提供的展示标签 | 可能被本地化,不适合做逻辑分支判断 |
description |
string | null |
可选说明文案 | 可为 null,UI 需兜底 |
category |
string | null |
ACP 语义类别,如 model、thought_level |
用于逻辑分组;缺省时按普通项处理 |
id 与 category 的分工很重要:id 是"值"层面的句柄,category 是"语义"层面的标签。所以判断"这是不是模型选择器"应该看 category === 'model',而真正设置值时仍要用该选项自己的 id。
AgentConfigKindDto:以 type 为判别键的联合类型
Rust 侧用 serde 的内部标签枚举实现(crates/agent_harness/src/inbound/capability_discovery.rs):
#[serde(tag = "type", rename_all = "snake_case", rename_all_fields = "camelCase")]
pub enum AgentConfigKindDto {
Select { current_value: String, options: Vec<AgentConfigSelectOptionDto> },
Boolean { current_value: bool },
}
这带来三个可直接依赖的序列化事实:
type的取值是snake_case,即"select"与"boolean";- 变体内部的字段是
camelCase,因此是currentValue; - 该枚举在父结构中以
#[serde(flatten)]展开,所以type/currentValue/options与id/name处于同一层,不存在嵌套的kind对象。
对 select 而言,currentValue 是当前选中项的 value(不透明字符串);对 boolean 而言,currentValue 是布尔值,且没有 options 字段。客户端必须按 type 收窄类型,否则会把布尔项的 currentValue 误当字符串。
AgentConfigSelectOptionDto:选择项的可选元信息
| 字段 | 类型 | 语义 |
|---|---|---|
value |
string |
选中后回传给 Agent 的不透明值 |
name |
string |
展示标签 |
description |
string | null |
提供方给出的取值说明 |
group |
string | null |
提供方给出的分组标题 |
group 的价值在 ACP 的"分组选择"场景:当 Agent 以 SessionConfigSelectOptions::Grouped 声明选项时,投影函数会把分组名下放到每个选项上,并把层级拉平成一维数组。这一逻辑在 crates/folds/agent_fold/src/domain/session_config.rs:
SessionConfigSelectOptions::Ungrouped(options) => options
.iter()
.map(|option| project_select_option(option, None))
.collect(),
SessionConfigSelectOptions::Grouped(groups) => groups
.iter()
.flat_map(|group| {
group.options.iter()
.map(|option| project_select_option(option, Some(group.name.as_str())))
})
.collect(),
_ => return None,
也就是说:分组不会体现为嵌套结构,而是通过 group 字段保留归属;同时未识别的 ACP kind 会被 _ => return None 丢弃,session_config_options 使用 filter_map 收集,因此最终数组可能是 Agent 原生声明的一个子集。
一个完整的响应示例
下面的示例与仓库中的序列化测试 successful_response_serializes_config_options 保持同一形状(该测试断言了完整的 JSON 结构,见 crates/agent_harness/src/inbound/capability_discovery/test.rs),并额外补上一个 boolean 类型的选项以演示联合分支:
{
"configOptions": [
{
"id": "reasoning_effort",
"name": "Fast",
"description": null,
"category": "thought_level",
"type": "select",
"currentValue": "high",
"options": [
{
"value": "high",
"name": "High",
"description": null,
"group": null
}
]
},
{
"id": "auto_approve",
"name": "Auto approve tool calls",
"description": "Skip the approval prompt for safe tools",
"category": null,
"type": "boolean",
"currentValue": false
}
]
}
注意 description 与 group 在缺失时序列化为 null 而非被省略(字段类型是 Option<T> 但未加 skip_serializing_if),这一点在生成的前端类型里体现为 description?: string | null,即"可选且可为 null",客户端两种都要处理。
调用方式:HTTP、TypeScript SDK 与前端查询钩子
直接发起 HTTP 请求
接口是 POST /agent-capabilities/discover,需要 Bearer 认证(security(("bearerAuth" = []))),请求体为 JSON。一个最小的 curl 调用:
curl -X POST "$AGENT_HARNESS_HOST/agent-capabilities/discover" \
-H "Authorization: Bearer $MACRO_TOKEN" \
-H "Content-Type: application/json" \
-d '{"harness":"in-memory","model":"anthropic/claude-sonnet-5-5"}'
探测已配对的 macrod 运行时则必须带上 harnessId:
curl -X POST "$AGENT_HARNESS_HOST/agent-capabilities/discover" \
-H "Authorization: Bearer $MACRO_TOKEN" \
-H "Content-Type: application/json" \
-d '{"harness":"macrod","harnessId":"3f2b1c0e-9d4a-4b8e-8f11-2a7c9e5d6b30"}'
OpenAPI 描述见 packages/sdk/specs/agent-harness.json,其 operationId 为 discover_agent_capabilities_handler,生成的 SDK 客户端方法名正是由它派生的 discoverAgentCapabilitiesHandler。
使用生成的 TypeScript SDK
packages/sdk 由 OpenAPI 生成,方法签名非常直观(packages/sdk/generated/agent-harness/sdk.gen.ts):
const { data, error } = await sdk.discoverAgentCapabilitiesHandler({
body: { harness: 'cursor', model: 'first' },
});
if (!error && data) {
for (const option of data.configOptions) {
if (option.type === 'select') {
// option.currentValue: string, option.options: AgentConfigSelectOptionDto[]
console.log(option.id, option.currentValue, option.options.map(o => o.value));
} else {
// option.currentValue: boolean
console.log(option.id, option.currentValue);
}
}
}
前端仓库中已有一层薄封装 agentHarnessServiceClient.discoverAgentCapabilities,它以 fetchWithToken 附带鉴权头并透传 AbortSignal(apps/web/src/lib/service-clients/service-agent-harness/client.ts)。在此之上是 Solid Query 钩子 useAgentCapabilitiesQuery(apps/web/src/lib/queries/agents/capabilities.ts),它对每个选项做了一次规范化,把 undefined 的 description / group 统一改成 null,并把 select 与 boolean 两个分支显式建模:
return {
configOptions: response.configOptions.map((option) => {
const common = {
id: option.id,
name: option.name,
description: option.description ?? null,
category: option.category ?? null,
};
if (option.type === 'select')
return { ...common, type: option.type, currentValue: option.currentValue,
options: option.options.map((v) => ({
...v, description: v.description ?? null, group: v.group ?? null,
})) };
return { ...common, type: option.type, currentValue: option.currentValue };
}),
};
该钩子的查询键是 <a href="https://link.gitcode.com/i/d24532e62cdc9edcd4827b13ab1bf89b" target="_blank">'agent-capabilities', target],并且设置了 staleTime: 0、gcTime: 0、retry: false。注释点明了原因:"Capabilities belong to a harness and selected model, never a provider alone."——缓存身份必须包含 harness 与 model,否则从另一个目标带来的选项会被错误复用。对应测试 keys fresh discovery by the selected model and disables unsupported targets 验证了换模型会触发第二次请求,而 target 为 undefined 时请求根本不发出([apps/web/src/lib/queries/agents/capabilities.test.tsx)。
服务端内部链路:从路由到三个探测器
响应并非现成数据拼装,而是每次实时探测后的投影。整体链路如下:
- 路由与鉴权:
agent_capabilities_router注册POST /agent-capabilities/discover,处理器通过MacroAuthorizationExtractor<Auth, UserOnly>提取用户身份(不接受 bot 身份),随后把macro_user_id与转换后的领域请求交给服务层。 - 领域服务调度:
AgentCapabilitiesServiceImpl持有access、in_memory、cursor、macrod四个端口与一个timeout,先按 harness/harnessId 组合做合法性校验,再决定探测哪一个后端。 - macrod 先鉴权后探测:调用
HarnessCapabilityAccess::can_use(caller, harness);返回false立即得到Forbidden(403),且不会发起探测。测试invisible_macrod_is_forbidden_without_probing断言此时macrod.calls() == 0。 - 有界超时:所有探测都包在
tokio::time::timeout(self.timeout, adapter.probe(...))中,超时映射为Timeout(504)。 - 结果投影:
RawCapabilityProbe::Options(...)通过AgentCapabilities::from_options→session_config_options转成领域词表,再经From<AgentCapabilities>转为DiscoverAgentCapabilitiesResponse。
服务装配发生在 services/agent_harness_service/src/main.rs,其中超时值为 model_probe_timeout = Duration::from_secs(10)(同文件 L1296),即单次探测最长 10 秒:
let capabilities = agent_harness::inbound::capability_discovery::agent_capabilities_router(
...AgentCapabilitiesServiceImpl::new(
VisibleHarnessAccess::new(PgHarnessRepo::new(pool.clone())),
InMemoryModels::new(Some(Arc::clone(&inmem_model_engine)), config.inmem_model.clone(), Arc::clone(&inmem_model_access)),
CursorModels::new(cursor_keys.clone(), cursor_api_base_url()),
macrod_models.clone(),
model_probe_timeout,
),
...
);
错误到 HTTP 状态码的映射
capability_error_response 是一张纯粹的映射表(crates/agent_harness/src/inbound/capability_discovery.rs):
| 领域错误 | HTTP 状态 | 触发原因 |
|---|---|---|
BadRequest(_) |
400 | harnessId 与 harness 组合非法 |
Forbidden |
403 | macrod 运行时对调用者不可见 / 不可用 |
Disconnected |
409 | macrod 运行时或 Cursor 账号未连接 |
Timeout |
504 | 探测超过服务超时 |
Probe(_) |
502 | 提供方探测失败 |
其中 401 由鉴权层产生(未认证),不在这张表内。响应体在错误分支是 error.to_string() 的纯文本,而不是 JSON 结构体——所以调用方不应该对错误响应做 JSON 解析。
三种 harness 的探测语义差异
虽然响应类型统一,但三个后端"能回答什么"并不相同。从各适配器实现可以确认:
| 维度 | in-memory |
cursor |
macrod |
|---|---|---|---|
| 探测目标 | 调用者用户 id | 调用者用户 id | HarnessId |
是否需要 harnessId |
否 | 否 | 是 |
是否支持 model 参数 |
支持,且会校验模型是否在引擎支持列表中 | 支持,按模型解析默认变体 | 不支持:传 model 直接返回 Unsupported(空 configOptions) |
| 未连接时的错误 | 一般不涉及 | HarnessError::CursorNotConnected → 409 |
运行时未连接 → 409 |
| 数据来源 | 引擎 supported_models() 与用户模型访问控制 |
Cursor 账号的模型目录 | 通过运行时命令总线向 macrod 请求模型探测 |
macrod 的这条限制值得单独强调,因为它决定了一个常见误用:给 macrod 传 model 不会得到"该模型的设置",而是得到一个合法的空清单。实现位于 services/agent_harness_service/src/model_providers/macrod.rs:
// Model-specific discovery requires a live session for external ACP runtimes.
if model.is_some() {
return Ok(RawCapabilityProbe::Unsupported);
}
换言之,外部 ACP 运行时要等会话真正建立后才能暴露模型级控件,预检阶段不做猜测——这与 docs/architecture/agent-effort.md 中"External harnesses expose controls after opening a session; model-specific preflight is not guessed."一致。
in-memory 对未知模型的处理则相反,是报错而非静默降级(services/agent_harness_service/src/model_providers/in_memory.rs):
let current = access.default_model(model.unwrap_or(&self.current));
if !engine.supported_models().contains(¤t) {
return Err(CapabilityProbeError::Failed("unsupported model".to_owned()));
}
该错误经 Probe(_) 变成 502。cursor 适配器在按模型查找默认变体失败时也返回同样的 "unsupported model" 失败(services/agent_harness_service/src/model_providers/cursor.rs)。
空数组 configOptions: [] 的正确含义
AgentCapabilities::unsupported() 返回 config_options: Vec::new(),注释是"A provider with no discoverable session configuration."。这带来一个重要的语义边界:
- 空数组是成功响应,不是错误。HTTP 状态仍是 200。
- 它表示"该提供方当前无法声明会话配置",而不是"配置加载失败"。
- 客户端据此应隐藏相关控件(例如推理强度按钮),而不是弹出错误提示。测试
unsupported_provider_returns_the_supported_response_shape正是验证这一点:Unsupported会被包装成与其他成功路径相同的响应形状。
与之对应的是"配置项存在但被过滤掉"的另一情形:当 ACP 声明了当前投影不认识的 kind 时,project_option 返回 None,该项被静默跳过。因此不能把原生 ACP 的选项数量与响应中的 configOptions.length 画等号。
工程实践要点
1. 拿到的是全量快照,请整体替换
响应语义是"Complete ordered ... configuration"。新建会话、恢复会话、以及修改设置后,服务端都会返回完整配置。客户端应用新数组替换旧数组,而不是合并——这样才能正确移除已经不被支持的控件。相关约定在 docs/architecture/agent-effort.md 的会话生命周期章节中有明确说明。
2. id / value 是不透明值
文档对 id 的描述是"Opaque id used to change this setting",对 value 是"Opaque value returned to the agent when selected"。这意味着:
- 不要用
id === 'reasoning_effort'之类的判断替代category判断(reasoning_effort在仓库中确实是当前常量,但外部 harness 的 id 属于提供方契约); - 不要把值区分为"已知枚举",取值集合完全由
options决定; name只用于展示,不参与逻辑。
3. 缓存身份必须包含 harness 与 model
useAgentCapabilitiesQuery 的查询键是 ['agent-capabilities', target()],且 staleTime: 0、gcTime: 0、retry: false。这是有意为之:能力随时可能因账号、模型、运行时版本而变化,缓存跨模型复用会产生"选项与模型不匹配"的隐蔽 bug。
4. 优先做"能力驱动",而不是"预设驱动"
同一份 configOptions 可能同时包含 category: "model" 的选择器与 category: "thought_level" 的强度选择器。正确做法是遍历响应渲染控件,并按 category 排序或分组;对 type === 'boolean' 的项渲染开关。这样新增后端或后端新增配置项时,前端无需改动。
5. 错误分支要区分"可恢复"与"需引导"
409 Conflict表示连接类前置条件缺失(Cursor 未连接、macrod 未连接),应引导用户完成连接;504 Gateway Timeout表示探测超时,可提示重试;502 Bad Gateway表示提供方失败(包含不支持的模型),应展示具体原因并允许换模型;400属于调用方参数错误,通常意味着代码 bug 而非用户可修复状态。
6. 探测不会创建会话
这是该接口与"模型列表 / 会话创建"接口的关键区别:它只做一次探测,不落库、不产生会话。因此可以在 UI 打开模型子菜单、切换模型时安全地频繁调用,而不会留下副作用。
测试证据一览
仓库为该类型提供了两层测试,可作为行为契约的权威参考:
- 传输层测试 crates/agent_harness/src/inbound/capability_discovery/test.rs:覆盖三种 harness 的请求映射、五种错误到状态码的映射、以及成功响应的完整 JSON 序列化形状(含
null字段与type判别键)。 - 领域层测试 crates/agent_harness/src/domain/capability_discovery/test.rs:覆盖 macrod 先鉴权后派发、不可见 macrod 不探测、
Unsupported返回空清单、Cursor 收到的是认证调用者、非法目标组合被拒绝、以及探测超时。 - 前端测试 apps/web/src/lib/queries/agents/capabilities.test.tsx:覆盖按模型分键与目标缺省时禁用查询。
把这三层测试与本文的字段表对照阅读,基本可以无歧义地还原 DiscoverAgentCapabilitiesResponse 的全部行为边界。
延伸阅读路径
- 类型文档本体:packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DiscoverAgentCapabilitiesResponse.md
- 请求与错误类型:DiscoverAgentCapabilitiesHandlerData
- 相关类型:AgentConfigOptionDto、AgentConfigKindDto、AgentConfigSelectOptionDto、CapabilityHarnessDto
- 架构说明:docs/architecture/agent-effort.md
- 服务装配入口:services/agent_harness_service/src/main.rs