Skip to content

Commit 87963fe

Browse files
author
hzq
committed
Require correlated A2A outcomes after dispatch
1 parent 56c7794 commit 87963fe

14 files changed

Lines changed: 497 additions & 213 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ English · [简体中文](CHANGELOG.zh-CN.md)
44

55
## Unreleased
66

7+
- A2A requires replies to match the current JSON-RPC request and task. An error without a confirmed outcome leaves the run interrupted, rather than assuming that the peer did not act.
78
- Owners can check an acknowledged A2A task on its original worker and peer after a gateway restart. The lookup never resends the message or changes the interrupted run.
89
- ACP cancels ambiguous permission choices instead of selecting the first option. A2A can check an acknowledged new task once after early stream completion without re-sending the message.
910

‎CHANGELOG.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
## 未发布
66

7+
- A2A 只接收与本次 JSON-RPC 请求和任务匹配的回复。发送后若只有错误、没有确认的结果,运行会保留为中断,不把错误当成对端未执行的证据。
78
- 网关重启后,owner 管理员可以通过原执行节点向原对端核对已确认接收的 A2A 任务。查询不会重发消息,也不会更改中断运行。
89
- ACP 遇到有歧义的权限选项会取消,不再默认选第一项。A2A 流提前结束时,可对已确认接收的新任务只读查询一次,不重发消息。
910

‎bench/agent-stream.ts‎

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,15 @@ import { sha } from '../src/core/util.js';
99
const out = process.argv[2];
1010
if (!out) throw new Error('Usage: node dist/bench/agent-stream.js NEW_REPORT.json');
1111
const text = 'x'.repeat(256 * 1024);
12-
const bytes = Buffer.from(
13-
[
14-
{ result: { artifactUpdate: { taskId: 't', artifact: { parts: [{ text }] } } } },
15-
{ result: { statusUpdate: { taskId: 't', status: { state: 'TASK_STATE_COMPLETED' } } } },
16-
]
17-
.map((value) => `data: ${JSON.stringify(value)}\n\n`)
18-
.join(''),
19-
);
12+
const frames = [
13+
{ task: { id: 't', contextId: 'ctx', status: { state: 'TASK_STATE_WORKING' } } },
14+
{ artifactUpdate: { taskId: 't', contextId: 'ctx', artifact: { parts: [{ text }] } } },
15+
{ statusUpdate: { taskId: 't', contextId: 'ctx', status: { state: 'TASK_STATE_COMPLETED' } } },
16+
];
17+
const wire = (id: string) =>
18+
Buffer.from(
19+
frames.map((result) => `data: ${JSON.stringify({ jsonrpc: '2.0', id, result })}\n\n`).join(''),
20+
);
2021
const config = workerSchema.parse({
2122
nodeId: 'fixture',
2223
dataDir: '/tmp/unused-oaa-stream-bench',
@@ -44,8 +45,9 @@ for (let i = 0; i < 8; i++) {
4445
events++;
4546
},
4647
undefined,
47-
(async () => {
48+
async (_url, init) => {
4849
requests++;
50+
const bytes = wire(JSON.parse(String(init?.body)).id);
4951
return new Response(
5052
new ReadableStream({
5153
pull(controller) {
@@ -59,7 +61,7 @@ for (let i = 0; i < 8; i++) {
5961
}),
6062
{ headers: { 'content-type': 'text/event-stream' } },
6163
);
62-
}) as typeof fetch,
64+
},
6365
);
6466
const ms = performance.now() - started;
6567
assert.equal(result.text, text);
@@ -74,8 +76,16 @@ const warm = samples
7476
const report = {
7577
kind: 'local-fragmented-a2a-stream',
7678
node: process.version,
77-
workloadHash: sha(bytes),
78-
sourceHash: sha(await readFile(new URL('../src/engines/a2a.js', import.meta.url))),
79+
workloadHash: sha(wire('00000000-0000-0000-0000-000000000000')),
80+
sourceHash: sha(
81+
JSON.stringify(
82+
await Promise.all(
83+
['a2a.js', 'a2a-response.js'].map((file) =>
84+
readFile(new URL(`../src/engines/${file}`, import.meta.url), 'utf8'),
85+
),
86+
),
87+
),
88+
),
7989
coldMs: samples[0]!.ms,
8090
medianWarmMs: warm[Math.floor(warm.length / 2)],
8191
samples,

‎docs/architecture.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,8 @@ Anthropic completion requires that content blocks be closed and `message_stop` b
222222

223223
A2A waits for the local event sink to finish before consuming the next event or returning success, so a persistence failure is not swallowed. Non-streaming response bodies and agent card checks are bounded during reading, not checked after unbounded buffering.
224224

225+
Each JSON-RPC envelope must match the current request before it can produce output or a terminal state. A task stream cannot switch task or context mid-request, and identifiers used for follow-up calls are validated, not truncated. After a send is attempted, an HTTP or JSON-RPC error without a confirmed task result leaves the outcome uncertain. This does not change the classification of a task that reports a matching terminal failure.
226+
225227
If a new A2A task was acknowledged by a matching JSON-RPC response and the stream ends without a final state, the same worker may make one bounded `GetTask` (A2A 1.0) or `tasks/get` (0.3) lookup on the configured peer. It does not resend the message. A matching terminal task can fill missing text only when it agrees with the text already emitted. Without confirmation, the result remains uncertain. A task ID inherited from a previous turn is not evidence that its continuation was accepted.
226228

227229
A supporting worker also records the confirmed task and context privately against the current native step before delivering its output. After a gateway restart, the [owner-admin lookup](protocol.md#checking-an-interrupted-a2a-task) uses this receipt on the original worker and peer with their original identities. It does not automatically recover or resolve the run. If the crash happened before the receipt committed, or the receipt is contradicted, there is no task to query through this endpoint.

‎docs/protocol.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,9 @@ All inspection endpoints require `read` scope and the run's agent grant, even fo
344344

345345
The call makes one bounded read (`GetTask` on 1.0, `tasks/get` on 0.3). It returns `{evidence: "a2a_task_observation", state, text?}`; bounded text may appear for a completed task. Neither the remote identifiers nor credentials are returned. An absent or contradicted receipt, lost original authorization, or changed worker or peer can prevent a query. Timeout, peer 404, or an invalid reply means the outcome is unconfirmed, not that the task did not execute. Looking up a task never sends a message, cancels the task, imports artifacts, or changes the run's state. Reconciliation remains a separate operator action.
346346

347-
The MCP bridge reuses these endpoints. A generated launcher is exercised through the official SDK's real stdio client in the no-cost test suite. `oaa_upload_text` accepts only explicitly supplied text, never a local path. `oaa_invoke` supports stable idempotency keys; accepted-task receipts retain IDs rather than embedding entire outputs. `oaa_wait_run`, `oaa_read_output` and `oaa_list_artifacts` complete the retrieval workflow. No approval-granting MCP tool is exposed.
347+
If the peer may have acted but the gateway received no matching task receipt, this endpoint returns `a2a_receipt_unavailable`. Neither that response nor a send error is evidence that the task did not execute. Keep the original OAA idempotency key to look up the same run rather than deliberately creating another run.
348+
349+
The MCP bridge uses the ordinary run endpoints, not the owner-admin A2A lookup. A generated launcher is exercised through the official SDK's real stdio client in the no-cost test suite. `oaa_upload_text` accepts only explicitly supplied text, never a local path. `oaa_invoke` supports stable idempotency keys; accepted-task receipts retain IDs rather than embedding entire outputs. `oaa_wait_run`, `oaa_read_output` and `oaa_list_artifacts` complete the retrieval workflow. No approval-granting MCP tool is exposed.
348350

349351
Artifacts are exposed using standard [MCP resource links and resource reads](https://modelcontextprotocol.io/specification/2025-11-25/server/resources). `oaa://files/{id}` returns authenticated base64 file bytes, not a public URL or local filesystem path. MCP reads are limited to 4 MiB to bound transport frames; larger files fail explicitly and use authenticated HTTP or `oaa download`. A resource's content is untrusted data. Host-specific UI and installation behavior are not implied by SDK interoperability. [MCP request cancellation](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation) is propagated to the pending HTTP wait/read, while task cancellation stays an explicit `oaa_cancel` operation.
350352

‎docs/zh-CN/architecture.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,8 @@ Anthropic 的完成要求内容块已关闭且收到 `message_stop`,而不只
222222

223223
A2A 在消费下一个事件或返回成功之前等待本地事件接收端完成,因此持久化失败不会被吞掉。非流式响应体与 agent card 检查在读取过程中就受限,而不是在无界缓冲之后再检查。
224224

225+
JSON-RPC 回包先核对本次请求 ID,再允许交付文本或接受终态;同一请求的流不能换任务或上下文,后续查询和取消使用的是校验过的原始标识,不截断标识。消息开始发送后,只有 HTTP 或 JSON-RPC 错误、没有确认的任务结果时,运行保留不确定。若匹配的任务明确报告失败终态,仍按任务失败处理。
226+
225227
新发起的 A2A 任务如果收到请求 ID 匹配的确认、但流没有交付终态,执行节点可以对同一个已配置对端做一次限时只读查询(1.0 用 `GetTask`,0.3 用 `tasks/get`),不会重发消息。只接受匹配的任务结果;已交付文本与快照不一致时不拼接、不判成功。没有确认则保留不确定状态。上一轮沿用的任务 ID 不能证明这一轮的续接已被接受。
226228

227229
支持此能力的节点还会在交付输出前,把确认过的任务 ID 与上下文 ID 私下写到当前原生步骤下。网关重启后,[owner 管理员查询](protocol.md#核对中断的-a2a-任务)用这份回执向身份未变的原执行节点和原对端核对;不会自动恢复或结算运行。在回执落盘前就崩溃,或者收到相互矛盾的任务身份时,该接口没有可查询的任务。

‎docs/zh-CN/protocol.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,9 @@ MCP 的 `oaa_list_agents` 使用有界摘要端点;`oaa_inspect_agent` 暴露
360360

361361
接口执行一次限时只读查询(1.0 的 `GetTask` 或 0.3 的 `tasks/get`),返回 `{evidence: "a2a_task_observation", state, text?}`;已完成任务可能附带有长度上限的文本。不返回远端标识或凭据。没有回执、回执矛盾、原授权失效或节点、对端身份发生变化,都可能使查询不可用。超时、对端 404 或不合法的响应只表示未能核实,不证明任务没有执行。查询不重发消息、不取消对端任务、不导入产物,也不修改运行状态;人工对账仍需单独操作。
362362

363-
MCP 桥接复用这些端点。生成的启动器在免费测试套件里经官方 SDK 真实的 stdio 客户端演练过。`oaa_upload_text` 只接受显式提供的文本,从不接受本地路径。`oaa_invoke` 支持稳定的幂等键;已接受任务的回执保留 ID,而不是嵌入完整输出。`oaa_wait_run`、`oaa_read_output` 与 `oaa_list_artifacts` 补全了取回的流程。不暴露任何授予审批的 MCP 工具。
363+
如果对端可能已经执行,但网关没有收到匹配的任务回执,此接口返回 `a2a_receipt_unavailable`。这个响应或发送错误都不证明任务没执行。应保留原 OAA 幂等键找回同一运行,不要用新键另建运行来试探。
364+
365+
MCP 桥接复用普通运行端点,不暴露 owner 管理员专用的 A2A 核对接口。生成的启动器在免费测试套件里经官方 SDK 真实的 stdio 客户端演练过。`oaa_upload_text` 只接受显式提供的文本,从不接受本地路径。`oaa_invoke` 支持稳定的幂等键;已接受任务的回执保留 ID,而不是嵌入完整输出。`oaa_wait_run`、`oaa_read_output` 与 `oaa_list_artifacts` 补全了取回的流程。不暴露任何授予审批的 MCP 工具。
364366

365367
产物按标准的 [MCP 资源链接与资源读取](https://modelcontextprotocol.io/specification/2025-11-25/server/resources)暴露。`oaa://files/{id}` 返回经鉴权的 base64 文件字节,不是公开 URL,也不是本地文件系统路径。MCP 读取限制为 4 MiB 以约束传输帧;更大的文件明确失败,请改用经鉴权的 HTTP 或 `oaa download`。资源的内容是不受信任的数据。宿主专属的界面与安装行为,并不由 SDK 的互操作性推出。[MCP 请求取消](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation)会传到待处理的 HTTP 等待/读取,而任务取消仍然是显式的 `oaa_cancel` 操作。
366368

‎src/core/a2a-receipt.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,19 @@ export const A2A_TASK_RECOVERY = 'a2a-task-recovery-v1';
55
export const A2A_LOOKUP_MS = 5_000;
66

77
// Never truncate an identifier that will be used in a subsequent request.
8-
const peerId = z
8+
export const a2aPeerId = z
99
.string()
1010
.min(1)
1111
.max(256)
12-
.regex(/^[^\x00-\x1f\x7f]+$/u);
12+
.refine((value) => !/[\x00-\x1f\x7f]/u.test(value));
1313
export const a2aTaskReceipt = z
1414
.object({
1515
adapter: z
1616
.string()
1717
.max(64)
1818
.regex(/^[a-z0-9_-]+$/),
19-
taskId: peerId,
20-
contextId: peerId,
19+
taskId: a2aPeerId,
20+
contextId: a2aPeerId,
2121
peer: z.string().regex(/^[a-f0-9]{64}$/),
2222
})
2323
.strict();

‎src/engines/a2a-response.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { a2aPeerId } from '../core/a2a-receipt.js';
2+
import { Fault } from '../core/util.js';
3+
import { bounded, record } from './shared.js';
4+
5+
type Json = Record<string, unknown>;
6+
7+
export const invalidA2AReply = (reason: string) => new Fault('invalid_protocol', reason, 502);
8+
9+
export function matchingA2AReply(raw: unknown, requestId: string): Json {
10+
const reply = record(raw);
11+
if (reply.jsonrpc !== '2.0' || reply.id !== requestId)
12+
throw invalidA2AReply('A2A reply did not match the original JSON-RPC request.');
13+
if (Object.hasOwn(reply, 'error') === Object.hasOwn(reply, 'result'))
14+
throw invalidA2AReply('A2A reply must contain either a result or an error.');
15+
return reply;
16+
}
17+
18+
export function exactA2APeerId(value: unknown): string | undefined {
19+
if (value === undefined) return undefined;
20+
const id = a2aPeerId.safeParse(value);
21+
if (!id.success) throw invalidA2AReply('A2A task or context identifier is invalid.');
22+
return id.data;
23+
}
24+
25+
/** `TASK_STATE_INPUT_REQUIRED` (1.0) and `input-required` (0.3) both become `input-required`. */
26+
export const stateName = (value: unknown): string | null => {
27+
const raw = bounded(value, 60);
28+
if (!raw) return null;
29+
return raw.startsWith('TASK_STATE_')
30+
? raw.slice('TASK_STATE_'.length).toLowerCase().replaceAll('_', '-')
31+
: raw.toLowerCase();
32+
};
33+
34+
/** 1.0 text parts have no discriminator; 0.3 parts are tagged `kind: "text"`. */
35+
export function partsText(parts: unknown): string {
36+
if (!Array.isArray(parts)) return '';
37+
return parts
38+
.map((part) => {
39+
const p = record(part);
40+
const tag = p.kind ?? p.type;
41+
return (tag === undefined || tag === 'text') && typeof p.text === 'string' ? p.text : '';
42+
})
43+
.join('');
44+
}
45+
46+
type A2AEvent =
47+
| { type: 'message'; value: Json }
48+
| { type: 'task'; value: Json }
49+
| { type: 'status'; value: Json; final: boolean }
50+
| { type: 'artifact'; value: Json };
51+
const wrappedEvents = ['statusUpdate', 'artifactUpdate', 'task', 'message'] as const;
52+
53+
/** A 1.0 result names its only payload member; a 0.3 result has a `kind` discriminator. */
54+
export function eventOf(result: Json): A2AEvent | undefined {
55+
const wrapped = wrappedEvents.filter((key) => Object.hasOwn(result, key));
56+
if (wrapped.length > 1) return undefined;
57+
const [tag] = wrapped;
58+
if (tag === 'statusUpdate') return { type: 'status', value: record(result[tag]), final: false };
59+
if (tag === 'artifactUpdate') return { type: 'artifact', value: record(result[tag]) };
60+
if (tag) return { type: tag, value: record(result[tag]) };
61+
if (result.kind === 'status-update')
62+
return { type: 'status', value: result, final: result.final === true };
63+
if (result.kind === 'artifact-update') return { type: 'artifact', value: result };
64+
if (result.kind === 'task' || result.kind === 'message')
65+
return { type: result.kind, value: result };
66+
if (typeof result.id === 'string' && result.status) return { type: 'task', value: result };
67+
return undefined;
68+
}

0 commit comments

Comments
 (0)