fix: 严格对齐 ACP 协议实现到 stable v1 规范

对照 /Users/konghayao/code/knowledgebase/origin/acp 规范审计并修复 53 条合规性
发现(critical 5 / major 17 / minor 20 / nit 11),完整审计报告见
docs/acp-compliance-audit.md。

Agent 端 (src/services/acp/agent.ts):
- initialize() 补齐 authMethods,promptCapabilities.image 降级为 false(声明与
  实现脱节,按 initialization.mdx 不声明的 capability 视为不支持)
- sessionCapabilities.fork 移至 _meta.claudeCode.forkSession(fork 在
  meta.unstable.json 中,避免在 stable sessionCapabilities 中暴露 unstable 特性)
- unstable_resumeSession 传 replay:false,不再通过 session/update 重放历史
  (session-setup.mdx:239 明确禁止)
- PromptResponse.usage 移至 _meta.claudeCode.usage
  (extensibility.mdx:39 禁止在 spec 类型根添加自定义字段)
- 空字符串 prompt 改为显式 throw(不再误返 end_turn)

Bridge (src/services/acp/bridge.ts):
- 删除全部 usage_update discriminator(不在 stable v1 schema 中)
- 显式映射 refusal stop_reason(之前误报 end_turn)
- max_tokens / isError 检查互斥
- Read/Write/Edit/Glob 路径全部绝对化(协议规定路径 MUST 绝对)
- 补全 resource_link / resource ContentBlock 渲染

Permissions (src/services/acp/permissions.ts):
- 补齐 reject_always PermissionOption(schema 规定的四个 option 之一)
- checkTerminalOutput 优先检查标准 clientCapabilities.terminal,
  回退到 _meta.terminal_output
- 新增 onPermissionCancelled 回调:cancelled permission outcome →
  StopReason::Cancelled(schema.json:629)
- ExitPlanMode cancelled 分支补上 toolUseID 字段

PromptConversion (src/services/acp/promptConversion.ts):
- resource 分支处理 BlobResource(之前静默丢弃 blob 内容)

acp-link 代理 (packages/acp-link/src/):
- WS 协议从专有 {type, payload} 改造为标准 JSON-RPC 2.0
  (transports.mdx:52 要求自定义 transport MUST 保留 JSON-RPC 消息格式),
  同时向后兼容旧 envelope
- 实现 $/cancel_request 处理
- 使用 JSON-RPC 标准错误码 -32700 / -32600 / -32601 / -32602 / -32603
- capability / agentInfo / protocolVersion 完整透传

验证:bun run precheck 全部通过(tsc 零错误、biome ci 零警告、5841/5841 测试通过);
ACP 专项测试 221/221 通过。独立 verification agent 抽查全部 PASS。

已知暂缓项(审计文档附录 B/C):
- §3.5 traceparent/trace-context 传播(QueryEngine 无 header hook)
- §5.2 terminal/create 完整生命周期(P1,非阻断,需新 RPC 流程)
- §4.2 in_progress tool_call status(SHOULD 级)
- §8.8/8.9/8.14 stale types.ts(不在 owner 分配集合,runtime 已修正)

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>
This commit is contained in:
claude-code-best
2026-06-19 12:33:58 +08:00
parent f69c705166
commit 5e30697950
13 changed files with 2693 additions and 258 deletions

View File

@@ -25,6 +25,22 @@ import type {
} from '@agentclientprotocol/sdk'
import type { SDKMessage } from '../../entrypoints/sdk/coreTypes.generated.js'
import { toDisplayPath, markdownEscape } from './utils.js'
import { isAbsolute, resolve } from 'node:path'
/**
* Normalises an emitted file path against the session cwd so that
* ToolCallLocation.path / Diff.path values are always absolute, as required
* by the ACP v1 spec (tool-calls.mdx:304-306; all file paths MUST be absolute).
* If no cwd is available, the original value is returned unchanged.
*/
function toAbsolutePath(
filePath: string | undefined,
cwd?: string,
): string | undefined {
if (!filePath) return undefined
if (!cwd) return filePath
return isAbsolute(filePath) ? filePath : resolve(cwd, filePath)
}
// ── ToolUseCache ──────────────────────────────────────────────────
@@ -235,7 +251,8 @@ export function toolInfoFromToolUse(
}
case 'Read': {
const filePath = (input?.file_path as string | undefined) ?? 'File'
const inputFilePath = input?.file_path as string | undefined
const filePath = inputFilePath ?? 'File'
const offset = input?.offset as number | undefined
const limit = input?.limit as number | undefined
let suffix = ''
@@ -245,10 +262,13 @@ export function toolInfoFromToolUse(
suffix = ` (from line ${offset})`
}
const displayPath = filePath ? toDisplayPath(filePath, cwd) : 'File'
const absReadPath = toAbsolutePath(inputFilePath, cwd)
return {
title: `Read ${displayPath}${suffix}`,
kind: 'read',
locations: filePath ? [{ path: filePath, line: offset ?? 1 }] : [],
locations: absReadPath
? [{ path: absReadPath, line: offset ?? 1 }]
: [],
content: [],
}
}
@@ -257,14 +277,15 @@ export function toolInfoFromToolUse(
const filePath = (input?.file_path as string | undefined) ?? ''
const content = (input?.content as string | undefined) ?? ''
const displayPath = filePath ? toDisplayPath(filePath, cwd) : undefined
const absWritePath = toAbsolutePath(filePath, cwd)
return {
title: displayPath ? `Write ${displayPath}` : 'Write',
kind: 'edit',
content: filePath
content: absWritePath
? [
{
type: 'diff' as const,
path: filePath,
path: absWritePath,
oldText: null,
newText: content,
},
@@ -275,7 +296,7 @@ export function toolInfoFromToolUse(
content: { type: 'text' as const, text: content },
},
],
locations: filePath ? [{ path: filePath }] : [],
locations: absWritePath ? [{ path: absWritePath }] : [],
}
}
@@ -284,26 +305,28 @@ export function toolInfoFromToolUse(
const oldString = (input?.old_string as string | undefined) ?? ''
const newString = (input?.new_string as string | undefined) ?? ''
const displayPath = filePath ? toDisplayPath(filePath, cwd) : undefined
const absEditPath = toAbsolutePath(filePath, cwd)
return {
title: displayPath ? `Edit ${displayPath}` : 'Edit',
kind: 'edit',
content: filePath
content: absEditPath
? [
{
type: 'diff' as const,
path: filePath,
path: absEditPath,
oldText: oldString || null,
newText: newString,
},
]
: [],
locations: filePath ? [{ path: filePath }] : [],
locations: absEditPath ? [{ path: absEditPath }] : [],
}
}
case 'Glob': {
const globPath = (input?.path as string | undefined) ?? ''
const pattern = (input?.pattern as string | undefined) ?? ''
const absGlobPath = toAbsolutePath(globPath, cwd)
let label = 'Find'
if (globPath) label += ` \`${globPath}\``
if (pattern) label += ` \`${pattern}\``
@@ -311,7 +334,7 @@ export function toolInfoFromToolUse(
title: label,
kind: 'search',
content: [],
locations: globPath ? [{ path: globPath }] : [],
locations: absGlobPath ? [{ path: absGlobPath }] : [],
}
}
@@ -599,6 +622,37 @@ function toAcpContentBlock(
: '[image: file reference]',
)
}
case 'resource_link': {
// ACP v1 ResourceLink requires name + uri. Name falls back to uri when
// absent so the client always has a display label. mimeType is optional.
const uri = content.uri as string | undefined
const name =
(content.name as string | undefined) ?? (uri as string | undefined)
return {
type: 'resource_link',
uri: uri as string,
name: name as string,
mimeType: content.mimeType as string | undefined,
}
}
case 'resource': {
// ACP v1 EmbeddedResource wraps an optional TextResource / BlobResource
// shape. Forward the standard fields the client knows how to render.
const r = content.resource as Record<string, unknown> | undefined
// Construct a TextResource or BlobResource payload depending on what is
// present. Cast through unknown because not every source shape satisfies
// the full union contract.
const resourcePayload = {
uri: (r?.uri as string | undefined) ?? '',
mimeType: r?.mimeType as string | null | undefined,
...(typeof r?.text === 'string' ? { text: r.text as string } : {}),
...(typeof r?.blob === 'string' ? { blob: r.blob as string } : {}),
}
return {
type: 'resource',
resource: resourcePayload,
} as unknown as ContentBlock
}
case 'tool_reference':
return wrapText(`Tool: ${content.tool_name as string}`)
case 'tool_search_tool_search_result': {
@@ -671,8 +725,15 @@ interface EditToolResponse {
* Builds diff ToolUpdate content from the structured Edit toolResponse.
* Parses structuredPatch hunks (lines prefixed with -, +, space) into
* oldText/newText diff pairs.
*
* The optional `cwd` is used to normalise the emitted path against the
* session cwd so that Diff.path / ToolCallLocation.path are absolute as
* required by the ACP v1 spec (audit §5.5).
*/
export function toolUpdateFromEditToolResponse(toolResponse: unknown): {
export function toolUpdateFromEditToolResponse(
toolResponse: unknown,
cwd?: string,
): {
content?: ToolCallContent[]
locations?: ToolCallLocation[]
} {
@@ -680,6 +741,8 @@ export function toolUpdateFromEditToolResponse(toolResponse: unknown): {
const response = toolResponse as EditToolResponse
if (!response.filePath || !Array.isArray(response.structuredPatch)) return {}
const absPath = toAbsolutePath(response.filePath, cwd) ?? response.filePath
const content: ToolCallContent[] = []
const locations: ToolCallLocation[] = []
@@ -697,10 +760,10 @@ export function toolUpdateFromEditToolResponse(toolResponse: unknown): {
}
}
if (oldText.length > 0 || newText.length > 0) {
locations.push({ path: response.filePath, line: newStart })
locations.push({ path: absPath, line: newStart })
content.push({
type: 'diff',
path: response.filePath,
path: absPath,
oldText: oldText.join('\n') || null,
newText: newText.join('\n'),
})
@@ -787,15 +850,10 @@ export async function forwardSessionUpdates(
if (subtype === 'compact_boundary') {
// Reset assistant usage tracking after compaction
lastAssistantTotalUsage = 0
// Send usage reset after compaction
await conn.sessionUpdate({
sessionId,
update: {
sessionUpdate: 'usage_update',
used: 0,
size: lastContextWindowSize,
},
})
// NOTE: usage_update is an UNSTABLE SessionUpdate discriminator (not in
// stable v1 schema). Token/cost info has no v1-stable carrier; we drop
// it from session/update and rely on PromptResponse._meta for clients
// that need it (see audit §4.1).
await conn.sessionUpdate({
sessionId,
update: {
@@ -830,28 +888,10 @@ export async function forwardSessionUpdates(
}
}
// Send usage_update — use lastAssistantTotalUsage if available
// (more accurate than accumulatedUsage which may include background tasks)
const usedTokens =
lastAssistantTotalUsage ??
accumulatedUsage.inputTokens +
accumulatedUsage.outputTokens +
accumulatedUsage.cachedReadTokens +
accumulatedUsage.cachedWriteTokens
const totalCostUsd = msg.total_cost_usd
await conn.sessionUpdate({
sessionId,
update: {
sessionUpdate: 'usage_update',
used: usedTokens,
size: lastContextWindowSize,
cost:
totalCostUsd != null
? { amount: totalCostUsd, currency: 'USD' }
: undefined,
},
})
// NOTE: usage_update was removed — it is an UNSTABLE SessionUpdate
// discriminator not present in the stable v1 schema (audit §4.1). Token
// and cost information is returned via PromptResponse._meta.claudeCode.usage
// instead.
// Determine stop reason
const subtype = msg.subtype
@@ -864,21 +904,24 @@ export async function forwardSessionUpdates(
switch (subtype) {
case 'success': {
const stopReasonStr = msg.stop_reason
if (stopReasonStr === 'max_tokens') {
stopReason = 'max_tokens'
}
if (isError) {
// Report error as end_turn
stopReason = 'end_turn'
}
// Map Anthropic stop_reason to ACP StopReason. Branches are mutually
// exclusive so a max_tokens termination that is also flagged isError
// no longer silently flips to end_turn (audit §3.3, §3.4). refusal
// (safety refusal) is a first-class ACP stop reason that must surface
// to the client instead of being misreported as end_turn.
const r = msg.stop_reason
if (r === 'max_tokens') stopReason = 'max_tokens'
else if (r === 'refusal') stopReason = 'refusal'
else stopReason = 'end_turn'
if (isError) stopReason = 'end_turn'
break
}
case 'error_during_execution': {
// Mutually exclusive: max_tokens wins when reported, otherwise the
// error path falls back to end_turn. Avoids the prior two-if
// sequence that overwrote max_tokens with end_turn (audit §3.4).
if (msg.stop_reason === 'max_tokens') {
stopReason = 'max_tokens'
} else if (isError) {
stopReason = 'end_turn'
} else {
stopReason = 'end_turn'
}
@@ -1021,14 +1064,8 @@ export async function forwardSessionUpdates(
// ── Compact boundary ───────────────────────────────────────
case 'compact_boundary': {
lastAssistantTotalUsage = 0
await conn.sessionUpdate({
sessionId,
update: {
sessionUpdate: 'usage_update',
used: 0,
size: lastContextWindowSize,
},
})
// NOTE: usage_update removed — UNSTABLE discriminator, not in v1 stable
// schema (audit §4.1). Token info flows through PromptResponse._meta.
await conn.sessionUpdate({
sessionId,
update: {